Skip to main content

lean_ctx_cloud/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 Cloud 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.cloud.worker-alias.v1";
26/// HKDF salt of a per-place alias signing seed (info = place ref).
27const ALIAS_SIGNING_SALT: &str = "leanctx.cloud.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] = ["cloud", "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/// Length of the session tag in a per-session role.
60const SESSION_TAG_LEN: usize = 8;
61/// Domain of the session tag hash.
62const SESSION_TAG_DOMAIN: &str = "leanctx.cloud.session-agent.v1|";
63
64/// The role a session's worker is registered under. Without an app session
65/// it is the normalised role, so every session of that role on this
66/// instance shares one worker. With an app session (`LEAN_CTX_SESSION_ID`,
67/// recorded as the presence's `app_session_id`) it is
68/// `<role>-s<tag>`, where `tag` is base32(blake3(domain ‖ session))[..8] and
69/// the role is cut so the whole fits the 32-character role limit. Each
70/// session then gets its own durable worker (`wkr_` id), stable for the
71/// life of that app session. Cloud recomputes the id from the role as sent,
72/// so this needs nothing new on Cloud, and Cloud's `self_verify` check
73/// (worker id of the verdict == worker id of the result) then tells a
74/// worker session apart from a separate reviewer session on the same host.
75pub 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
86/// The instance id as the server hashes it: the dashed lowercase UUID. A
87/// 1.x enrolment stores `inst_<32 hex>`; the same id in another spelling
88/// would give another worker id (E10 `worker_not_owned`, dogfood 25.10.).
89pub 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
109/// Workspace worker id: `wkr_` + base32(blake3(instance ‖ "|" ‖ host ‖ "|" ‖ role))[..20],
110/// over the canonical instance id.
111pub 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
122/// RFC 4648 base32, lowercase, without padding.
123fn 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
141/// The secret that keys place-scoped worker aliases and `hlc.node`.
142pub 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    /// `wkr_` + base32(blake3_keyed(key, host ‖ "|" ‖ role ‖ "|" ‖ place_ref))[..20].
159    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    /// `hex(blake3_keyed(key, place_ref))[..16]`.
165    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
170/// Ed25519 key that signs this instance's events in a public vault or swarm
171/// (RESOLUTIONS R38). `place_ref` is `"{kind}:{id}"`.
172pub 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
177/// `hlc.node` of this instance's events in a public vault or swarm.
178pub fn alias_hlc_node(keys: &InstanceKeys, place_ref: &str) -> String {
179    WorkerAliasKey::of(keys).hlc_node(place_ref)
180}
181
182/// C0 `key_id`: `hex(blake3(public key))[..16]`.
183pub fn key_id(key: &SigningKey) -> String {
184    blake3::hash(key.verifying_key().as_bytes()).to_hex()[..16].to_string()
185}
186
187/// Why a worker name is refused (C0 2.0 `name` vectors), checked in this order.
188#[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    /// The text the person sees (SPEC-ENGINE §3.6, WEB §4.4).
207    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
220/// Scripts told apart by the single-script rule; any other script counts
221/// as one more (C0 2.0 server rule).
222const 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
257/// The C0 2.0 worker-name rule, applied before a name leaves the engine.
258/// Returns the NFKC form that is sent.
259pub 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
290/// Default name `<instance label> · <Host app> · <role>`, built to pass
291/// [`check_name`]: label characters outside the rule are dropped, and a
292/// label that still fails is left out.
293pub 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;