Skip to main content

lean_ctx/core/hive/workers/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Durable workers (SPEC-ENGINE §3.6, C0 2.0 section 2): the identity an
3//! agent has on Hive instead of its process id.
4//!
5//! - Workspace places see `wkr_` ids derived from the instance UUID, host
6//!   app and role, which the server recomputes.
7//! - Public vaults and swarms see place-scoped aliases keyed by the
8//!   `worker_alias_key`, derived in memory from the instance signing seed
9//!   and never written or sent, so co-members who know the instance UUID
10//!   can neither reproduce an alias nor link two places.
11
12pub 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
24/// HKDF salt of the `worker_alias_key` (info empty).
25const WORKER_ALIAS_SALT: &str = "leanctx.hive.worker-alias.v1";
26/// HKDF salt of a per-place alias signing seed (info = place ref).
27const ALIAS_SIGNING_SALT: &str = "leanctx.hive.alias.v1";
28
29/// Role used when none is given or nothing survives normalisation.
30pub const GENERAL_ROLE: &str = "general";
31/// Longest normalised role.
32const ROLE_MAX: usize = 32;
33/// Longest worker name, in Unicode scalar values after NFKC.
34const NAME_MAX: usize = 64;
35/// Case-insensitive substrings no worker name may carry.
36const RESERVED: [&str; 4] = ["hive", "thinkery", "leanctx", "moderator"];
37
38/// Lowercase; every character outside `[a-z0-9-]` becomes `-`; runs
39/// collapsed and trimmed; at most 32 characters; empty → `general`.
40pub 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
59/// The instance id as the server hashes it: the dashed lowercase UUID. A
60/// 1.x enrolment stores `inst_<32 hex>`; the same id in another spelling
61/// would give another worker id (E10 `worker_not_owned`, dogfood 25.10.).
62pub 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
82/// Workspace worker id: `wkr_` + base32(blake3(instance ‖ "|" ‖ host ‖ "|" ‖ role))[..20],
83/// over the canonical instance id.
84pub 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
95/// RFC 4648 base32, lowercase, without padding.
96fn 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
114/// The secret that keys place-scoped worker aliases and `hlc.node`.
115pub 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    /// `wkr_` + base32(blake3_keyed(key, host ‖ "|" ‖ role ‖ "|" ‖ place_ref))[..20].
132    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    /// `hex(blake3_keyed(key, place_ref))[..16]`.
138    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
143/// Ed25519 key that signs this instance's events in a public vault or swarm
144/// (RESOLUTIONS R38). `place_ref` is `"{kind}:{id}"`.
145pub 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
150/// `hlc.node` of this instance's events in a public vault or swarm.
151pub fn alias_hlc_node(keys: &InstanceKeys, place_ref: &str) -> String {
152    WorkerAliasKey::of(keys).hlc_node(place_ref)
153}
154
155/// C0 `key_id`: `hex(blake3(public key))[..16]`.
156pub fn key_id(key: &SigningKey) -> String {
157    blake3::hash(key.verifying_key().as_bytes()).to_hex()[..16].to_string()
158}
159
160/// Why a worker name is refused (C0 2.0 `name` vectors), checked in this order.
161#[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    /// The text the person sees (SPEC-ENGINE §3.6, WEB §4.4).
180    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
193/// Scripts told apart by the single-script rule; any other script counts
194/// as one more (C0 2.0 server rule).
195const 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
230/// The C0 2.0 worker-name rule, applied before a name leaves the engine.
231/// Returns the NFKC form that is sent.
232pub 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
263/// Default name `<instance label> · <Host app> · <role>`, built to pass
264/// [`check_name`]: label characters outside the rule are dropped, and a
265/// label that still fails is left out.
266pub 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;