1use base64::Engine as _;
8use base64::engine::general_purpose::URL_SAFE_NO_PAD as B64URL;
9use ed25519_dalek::Signer as _;
10use serde::{Deserialize, Serialize};
11use serde_json::{Value, json};
12
13use super::super::CloudError;
14use super::super::instance_key::InstanceKeys;
15use super::super::transport::CloudClient;
16use super::card::WorkerCard;
17use super::{WorkerAliasKey, alias_signing_key, check_name, key_id};
18
19pub const WORKER_DOMAIN: &str = "leanctx.cloud.worker.v1\n";
20pub const INSTANCE_CARD_DOMAIN: &str = "leanctx.cloud.instance_card.v1\n";
21
22pub struct Registration<'a> {
25 pub instance_id: &'a str,
26 pub host_app: &'a str,
27 pub role: &'a str,
28 pub name: &'a str,
29 pub card: &'a WorkerCard,
30 pub alias_place: Option<&'a str>,
31}
32
33fn sign(keys: &InstanceKeys, domain: &str, mut body: Value) -> Result<Value, CloudError> {
35 let signer = keys.signing_key();
36 body["key_id"] = key_id(signer).into();
37 let input = lean_ctx_protocol::cloud::signing_input(domain, &body)
38 .map_err(|e| CloudError::Local(e.to_string()))?;
39 body["signature"] = hex::encode(signer.sign(&input).to_bytes()).into();
40 Ok(body)
41}
42
43pub fn register_body(keys: &InstanceKeys, reg: &Registration<'_>) -> Result<Value, CloudError> {
46 let name = check_name(reg.name)
47 .map_err(|refusal| CloudError::Config(format!("invalid_name: {}", refusal.message())))?;
48 let card = serde_json::to_value(reg.card).map_err(|e| CloudError::Local(e.to_string()))?;
49 let mut body = json!({
50 "host_app": reg.host_app,
51 "role": reg.role,
52 "name": name,
53 "card": card,
54 });
55 match reg.alias_place {
56 None => {
57 body["worker_id"] =
58 super::workspace_worker_id(reg.instance_id, reg.host_app, reg.role).into();
59 }
60 Some(place) => {
61 let alias = WorkerAliasKey::of(keys);
62 body["worker_id"] = alias.worker_id(reg.host_app, reg.role, place).into();
63 body["place"] = place.into();
64 body["alias_pubkey"] = B64URL
65 .encode(alias_signing_key(keys, place).verifying_key().as_bytes())
66 .into();
67 body["hlc_node"] = alias.hlc_node(place).into();
68 }
69 }
70 sign(keys, WORKER_DOMAIN, body)
71}
72
73#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
76#[serde(rename_all = "snake_case")]
77pub enum ConsentChannel {
78 OsPresence,
79 TtyOnly,
80}
81
82pub fn instance_card_body(
86 keys: &InstanceKeys,
87 instance_version: &str,
88 consent_channel: ConsentChannel,
89 clear_presence_key: bool,
90) -> Result<Value, CloudError> {
91 let mut body = json!({
92 "instance_version": instance_version,
93 "consent_channel": consent_channel,
94 });
95 if clear_presence_key {
96 body["presence_key"] = Value::Null;
97 }
98 sign(keys, INSTANCE_CARD_DOMAIN, body)
99}
100
101#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
103pub struct RegisteredWorker {
104 pub id: String,
105 pub name: String,
106 pub place: Option<String>,
107 pub status: String,
108 pub registered_at: u64,
109}
110
111#[derive(Deserialize)]
112struct WorkerEnvelope {
113 worker: RegisteredWorker,
114}
115
116#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
118pub struct PresenceKey {
119 pub alg: String,
120 pub key_id: String,
121 pub hardware: bool,
122 pub bound_at: u64,
123}
124
125#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
126pub struct Account {
127 pub user_id: String,
128 #[serde(default)]
131 pub handle: Option<String>,
132 #[serde(default, skip_serializing_if = "Option::is_none")]
134 pub email: Option<String>,
135}
136
137#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
138pub struct CardState {
139 pub instance_version: String,
140 pub consent_channel: ConsentChannel,
141 pub updated_at: u64,
142}
143
144#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
146pub struct InstanceCard {
147 pub card: CardState,
148 pub account: Account,
149 pub presence_key: Option<PresenceKey>,
150}
151
152const MAX_ANSWER: usize = 64 * 1024;
154
155fn worded(code: &str, reason: &str) -> Option<String> {
158 Some(match (code, reason) {
159 (_, "confusable") => "This name mixes alphabets. Use one alphabet.".into(),
160 (_, "reserved") => {
161 "Names may not contain cloud, thinkery, leanctx or moderator. Pick another name.".into()
162 }
163 ("worker_not_owned", _) => {
164 "worker_not_owned: LeanCTX Cloud has bound this worker id to another instance.".into()
165 }
166 (_, "worker_cap_reached") => {
167 "worker_cap_reached: this instance already has 32 workers on LeanCTX Cloud.".into()
168 }
169 (_, "presence_key_locked") => "The presence key can only be cleared here; bind a new one with `lean-ctx cloud connect --bind-presence-key`.".into(),
170 _ => return None,
171 })
172}
173
174fn call<T: for<'de> Deserialize<'de>>(
176 client: &CloudClient,
177 method: &str,
178 path: &str,
179 body: &Value,
180 what: &str,
181) -> Result<T, CloudError> {
182 let (status, answer) = client.send_answer(method, path, Some(body), MAX_ANSWER)?;
183 if !(200..300).contains(&status) {
184 let code = answer["error"]["code"].as_str().unwrap_or_default();
185 let reason = answer["error"]["reason"].as_str().unwrap_or_default();
186 return Err(worded(code, reason).map_or_else(
187 || CloudError::from_response(status, &answer),
188 CloudError::Config,
189 ));
190 }
191 parse(answer, what)
192}
193
194fn parse<T: for<'de> Deserialize<'de>>(value: Value, what: &str) -> Result<T, CloudError> {
195 serde_json::from_value(value).map_err(|e| CloudError::Protocol(format!("{what}: {e}")))
196}
197
198pub fn register(
200 client: &CloudClient,
201 keys: &InstanceKeys,
202 reg: &Registration<'_>,
203) -> Result<RegisteredWorker, CloudError> {
204 let body = register_body(keys, reg)?;
205 Ok(call::<WorkerEnvelope>(client, "POST", "/workers", &body, "worker registration")?.worker)
206}
207
208pub fn announce_instance(session: &crate::auth::Session) -> Result<InstanceCard, CloudError> {
212 let keys = InstanceKeys::load(&session.store)?;
213 let channel = if crate::consent::broker::bound_presence_key(&session.store).is_some() {
214 ConsentChannel::OsPresence
215 } else {
216 ConsentChannel::TtyOnly
217 };
218 let minor = std::cell::Cell::new(None);
219 let exchanged = session.with_client(|client| {
220 let (status, answer) =
221 card_exchange(client, &keys, &session.instance.instance_id, channel, false)?;
222 minor.set(client.answered_minor());
223 if status == 401 {
224 return Err(CloudError::from_response(status, &answer));
226 }
227 Ok((status, answer))
228 });
229 let speaks = match &exchanged {
233 Ok((status, _)) if (200..300).contains(status) => Some(true),
234 Ok((404, _)) | Err(CloudError::NotFound) => Some(false),
235 _ => None,
236 };
237 if let Some(v2) = speaks {
238 crate::bus::relay_v2::record_protocol_minor(&session.store, v2, minor.get())?;
239 }
240 let _ = session.with_client(|client| {
243 crate::session_ref::refresh(&session.store, &session.instance.url, client)
244 });
245 let result = exchanged.and_then(|(status, answer)| card_from(status, answer));
246 if let Ok(card) = &result {
248 session
249 .store
250 .write_config(crate::consent::broker::ACCOUNT_FILE, &card.account)?;
251 }
252 result
253}
254
255pub fn retire(client: &CloudClient, worker_id: &str) -> Result<(), CloudError> {
263 if !crate::bus::address::is_worker_id(worker_id) {
264 return Err(CloudError::Config(format!(
265 "{worker_id} is not a worker id"
266 )));
267 }
268 let (status, answer) =
269 client.send_answer("DELETE", &format!("/workers/{worker_id}"), None, MAX_ANSWER)?;
270 let code = answer["error"]["code"].as_str().unwrap_or_default();
271 if (200..300).contains(&status)
272 || (status == 404 && code == "not_found")
273 || code == "worker_not_owned"
274 {
275 return Ok(());
276 }
277 Err(CloudError::from_response(status, &answer))
278}
279
280pub fn retire_evicted(session: &crate::auth::Session) -> Result<(), CloudError> {
285 let instance_id = &session.instance.instance_id;
286 let mut first_error = None;
287 for worker_id in super::attach::retired(&session.store, instance_id)? {
288 match session.with_client(|client| retire(client, &worker_id)) {
289 Ok(()) => super::attach::retirement_done(&session.store, instance_id, &worker_id)?,
290 Err(error) => {
291 first_error.get_or_insert(error);
292 }
293 }
294 }
295 first_error.map_or(Ok(()), Err)
296}
297
298pub const IDLE_RETIRE: std::time::Duration = std::time::Duration::from_hours(24);
301pub const SESSION_IDLE_RETIRE: std::time::Duration = std::time::Duration::from_secs(3600);
304const SESSION_END_GRACE: std::time::Duration = std::time::Duration::from_secs(600);
306
307pub fn sweep(session: &crate::auth::Session) -> Result<Vec<String>, CloudError> {
312 let instance_id = &session.instance.instance_id;
313 let mut gone = super::attach::give_up_idle(&session.store, instance_id, IDLE_RETIRE, false)?;
314 gone.extend(super::attach::give_up_idle(
315 &session.store,
316 instance_id,
317 SESSION_IDLE_RETIRE,
318 true,
319 )?);
320 retire_evicted(session)?;
321 Ok(gone)
322}
323
324pub fn on_session_end(store: &crate::state::CloudStore) {
330 let Ok(Some(instance)) = store.instance() else {
331 return;
332 };
333 match super::attach::give_up_idle(store, &instance.instance_id, SESSION_END_GRACE, true) {
334 Ok(gone) if !gone.is_empty() => {
335 tracing::debug!("cloud: workers of ended sessions given up: {gone:?}");
336 }
337 Ok(_) => {}
338 Err(error) => tracing::debug!("cloud: workers of ended sessions not given up: {error}"),
339 }
340}
341
342pub fn ensure_registered(
349 session: &crate::auth::Session,
350 attached: &super::attach::LocalWorker,
351 card: &WorkerCard,
352) -> Result<super::attach::LocalWorker, CloudError> {
353 if attached.registered_at.is_some() {
354 return Ok(attached.clone());
355 }
356 if let Err(error) = retire_evicted(session) {
357 session
358 .store
359 .record_error(&format!("worker retirement: {error}"));
360 }
361 let keys = InstanceKeys::load(&session.store)?;
362 let instance = &session.instance;
363 let name = attached.name.clone().unwrap_or_else(|| {
364 super::default_name(
365 &instance.label,
366 &super::attach::host_display(&attached.host_app),
367 &attached.role,
368 )
369 });
370 let reg = Registration {
371 instance_id: &instance.instance_id,
372 host_app: &attached.host_app,
373 role: &attached.role,
374 name: &name,
375 card,
376 alias_place: None,
377 };
378 let worker = session.with_client(|client| register(client, &keys, ®))?;
379 if worker.id != attached.worker_id {
380 return Err(CloudError::Protocol(format!(
381 "LeanCTX Cloud registered {} for {}",
382 worker.id, attached.worker_id
383 )));
384 }
385 super::attach::update_book(&session.store, &instance.instance_id, |workers| {
386 let entry = workers.iter_mut().find(|w| w.worker_id == worker.id)?;
387 entry.registered_at = Some(worker.registered_at);
388 entry.name = Some(worker.name.clone());
389 Some(entry.clone())
390 })?
391 .ok_or_else(|| CloudError::Local(format!("{} left the worker book", worker.id)))
392}
393
394pub fn patch(
396 client: &CloudClient,
397 worker_id: &str,
398 name: Option<&str>,
399 card: Option<&WorkerCard>,
400) -> Result<RegisteredWorker, CloudError> {
401 if !crate::bus::address::is_worker_id(worker_id) {
402 return Err(CloudError::Config(format!(
403 "{worker_id} is not a worker id"
404 )));
405 }
406 let mut body = json!({});
407 if let Some(name) = name {
408 body["name"] = check_name(name)
409 .map_err(|r| CloudError::Config(format!("invalid_name: {}", r.message())))?
410 .into();
411 }
412 if let Some(card) = card {
413 body["card"] = serde_json::to_value(card).map_err(|e| CloudError::Local(e.to_string()))?;
414 }
415 if body.as_object().is_none_or(serde_json::Map::is_empty) {
416 return Err(CloudError::Config("nothing to change".into()));
417 }
418 let path = format!("/workers/{worker_id}");
419 Ok(call::<WorkerEnvelope>(client, "PATCH", &path, &body, "worker update")?.worker)
420}
421
422pub fn send_instance_card(
424 client: &CloudClient,
425 keys: &InstanceKeys,
426 instance_id: &str,
427 consent_channel: ConsentChannel,
428 clear_presence_key: bool,
429) -> Result<InstanceCard, CloudError> {
430 let (status, answer) = card_exchange(
431 client,
432 keys,
433 instance_id,
434 consent_channel,
435 clear_presence_key,
436 )?;
437 card_from(status, answer)
438}
439
440fn card_exchange(
441 client: &CloudClient,
442 keys: &InstanceKeys,
443 instance_id: &str,
444 consent_channel: ConsentChannel,
445 clear_presence_key: bool,
446) -> Result<(u16, Value), CloudError> {
447 let body = instance_card_body(
448 keys,
449 env!("CARGO_PKG_VERSION"),
450 consent_channel,
451 clear_presence_key,
452 )?;
453 let path = format!("/instances/{instance_id}/card");
454 client.send_answer("PATCH", &path, Some(&body), MAX_ANSWER)
455}
456
457fn card_from(status: u16, answer: Value) -> Result<InstanceCard, CloudError> {
458 if !(200..300).contains(&status) {
459 let code = answer["error"]["code"].as_str().unwrap_or_default();
460 let reason = answer["error"]["reason"].as_str().unwrap_or_default();
461 return Err(worded(code, reason).map_or_else(
462 || CloudError::from_response(status, &answer),
463 CloudError::Config,
464 ));
465 }
466 parse(answer, "instance card")
467}
468
469#[cfg(test)]
470mod tests {
471 use super::super::card::{Availability, Budget};
472 use super::*;
473
474 const FIXTURES: &str = concat!(
475 concat!(env!("CARGO_MANIFEST_DIR"), "/../.."),
476 "/crates/lean-ctx-protocol/tests/fixtures/cloud-v2/"
477 );
478
479 fn fixture(name: &str) -> Value {
480 let text = std::fs::read_to_string(format!("{FIXTURES}{name}")).unwrap();
481 serde_json::from_str(&text).unwrap()
482 }
483
484 fn instance_a() -> InstanceKeys {
485 InstanceKeys::from_seeds([0x49; 32], [0x01; 32])
486 }
487
488 #[test]
489 fn workspace_registration_matches_the_fixture_byte_for_byte() {
490 let card = WorkerCard::new(
491 "claude-code",
492 Some("claude-opus-5-5"),
493 ["ctx_read", "ctx_search", "ctx_shell"].map(String::from),
494 Budget {
495 tasks_per_day: Some(20),
496 usd_cents_per_day: None,
497 },
498 Availability::Online,
499 );
500 let body = register_body(
501 &instance_a(),
502 &Registration {
503 instance_id: "6f2b9c4e-1a3d-4e5f-8a7b-0c1d2e3f4a5b",
504 host_app: "claude-code",
505 role: "backend",
506 name: "yves-mac · Claude Code · backend",
507 card: &card,
508 alias_place: None,
509 },
510 )
511 .unwrap();
512 assert_eq!(body, fixture("routes/worker_register.request.json"));
513 }
514
515 #[test]
516 fn alias_registration_matches_the_fixture_byte_for_byte() {
517 let card = WorkerCard::new(
518 "codex",
519 None,
520 Vec::new(),
521 Budget::default(),
522 Availability::Idle,
523 );
524 let body = register_body(
525 &instance_a(),
526 &Registration {
527 instance_id: "6f2b9c4e-1a3d-4e5f-8a7b-0c1d2e3f4a5b",
528 host_app: "codex",
529 role: "general",
530 name: "Codex · general",
531 card: &card,
532 alias_place: Some("vault:3f1c2b6a-8d4e-4a7b-9c10-5e2f6a7b8c01"),
533 },
534 )
535 .unwrap();
536 let want = fixture("routes/worker_register.alias.request.json");
537 assert_eq!(body, want);
538 assert!(!body.to_string().contains("6f2b9c4e"));
540 }
541
542 #[test]
543 fn instance_cards_match_the_fixtures_and_can_only_clear() {
544 let keys = instance_a();
545 assert_eq!(
546 instance_card_body(&keys, "3.12.0", ConsentChannel::OsPresence, false).unwrap(),
547 fixture("routes/instance_card.request.json")
548 );
549 assert_eq!(
550 instance_card_body(&keys, "3.12.0", ConsentChannel::TtyOnly, true).unwrap(),
551 fixture("routes/instance_card.clear.request.json")
552 );
553 let card: InstanceCard =
554 parse(fixture("routes/instance_card.response.json"), "card").unwrap();
555 assert_eq!(card.presence_key.unwrap().key_id, "ef1bd9c792ccc768");
556 assert_eq!(card.account.handle.as_deref(), Some("yves"));
557 let mut nameless = fixture("routes/instance_card.response.json");
560 nameless["account"]["handle"] = Value::Null;
561 let card = card_from(200, nameless).unwrap();
562 assert_eq!(card.account.handle, None);
563 assert_eq!(card.account.email, None);
564 let mut named = fixture("routes/instance_card.response.json");
566 named["account"]["email"] = json!("dana@example.test");
567 let card = card_from(200, named).unwrap();
568 assert_eq!(card.account.email.as_deref(), Some("dana@example.test"));
569 assert!(card_from(404, json!({"error": {"code": "not_found"}})).is_err());
570 }
571
572 #[test]
573 fn a_mixed_alphabet_name_is_refused_before_it_leaves() {
574 let card = WorkerCard::new(
575 "codex",
576 None,
577 Vec::new(),
578 Budget::default(),
579 Availability::Idle,
580 );
581 let err = register_body(
582 &instance_a(),
583 &Registration {
584 instance_id: "6f2b9c4e-1a3d-4e5f-8a7b-0c1d2e3f4a5b",
585 host_app: "codex",
586 role: "general",
587 name: "аdmin",
588 card: &card,
589 alias_place: None,
590 },
591 )
592 .unwrap_err();
593 assert!(err.to_string().contains("invalid_name"), "{err}");
594 }
595
596 #[test]
597 fn refusals_reach_the_person_in_their_words() {
598 let locked = fixture("routes/instance_card.error.presence_key_locked.json");
599 let text = worded(
600 locked["error"]["code"].as_str().unwrap(),
601 locked["error"]["reason"].as_str().unwrap(),
602 )
603 .unwrap();
604 assert!(text.contains("--bind-presence-key"), "{text}");
605 assert_eq!(
606 worded("invalid_request", "confusable").unwrap(),
607 "This name mixes alphabets. Use one alphabet."
608 );
609 assert!(
610 worded("worker_not_owned", "")
611 .unwrap()
612 .starts_with("worker_not_owned")
613 );
614 assert_eq!(worded("invalid_request", "other"), None);
615 }
616
617 #[test]
618 fn responses_parse() {
619 let w: WorkerEnvelope =
620 parse(fixture("routes/worker_register.response.json"), "w").unwrap();
621 assert_eq!(w.worker.id, "wkr_vk4oelpv5lzjmev44hun");
622 let p: WorkerEnvelope = parse(fixture("routes/worker_patch.response.json"), "p").unwrap();
623 assert!(p.worker.name.contains("payments"));
624 let r: WorkerEnvelope = parse(
626 fixture("routes/worker_register.reactivated.response.json"),
627 "r",
628 )
629 .unwrap();
630 assert!(r.worker.id.starts_with("wkr_"));
631 }
632
633 fn retiring_cloud(
636 status: u16,
637 body: String,
638 ) -> (String, std::sync::Arc<std::sync::Mutex<Vec<String>>>) {
639 use std::io::{BufRead as _, BufReader, Write as _};
640 let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
641 let origin = format!("http://127.0.0.1:{}", listener.local_addr().unwrap().port());
642 let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
643 let recorded = std::sync::Arc::clone(&seen);
644 std::thread::spawn(move || {
645 for stream in listener.incoming().flatten() {
646 let mut writer = stream.try_clone().unwrap();
647 let mut reader = BufReader::new(stream);
648 let mut line = String::new();
649 if reader.read_line(&mut line).unwrap_or(0) == 0 {
650 continue;
651 }
652 loop {
653 let mut header = String::new();
654 reader.read_line(&mut header).unwrap();
655 if header.trim_end().is_empty() {
656 break;
657 }
658 }
659 recorded.lock().unwrap().push(line.trim_end().to_string());
660 let _ = write!(
661 writer,
662 "HTTP/1.1 {status} X\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
663 body.len()
664 );
665 }
666 });
667 (origin, seen)
668 }
669
670 #[test]
675 fn retiring_a_worker_is_done_unless_cloud_could_not_answer() {
676 let route = fixture("routes/worker_retire.request.json");
677 let id = route["path"]
678 .as_str()
679 .unwrap()
680 .strip_prefix("/v1/workers/")
681 .unwrap()
682 .to_string();
683 assert_eq!(route["method"], "DELETE");
684 assert_eq!(route["response"]["status"], 204);
685 for (status, body) in [
686 (204, String::new()),
687 (
688 404,
689 fixture("routes/worker_retire.error.not_found.json").to_string(),
690 ),
691 (
692 409,
693 fixture("routes/worker_retire.error.not_owned.json").to_string(),
694 ),
695 ] {
696 let (origin, seen) = retiring_cloud(status, body);
697 let client = CloudClient::new(&origin).unwrap();
698 retire(&client, &id).unwrap_or_else(|e| panic!("{status}: {e}"));
699 assert_eq!(
700 seen.lock().unwrap().as_slice(),
701 [format!("DELETE /v1/workers/{id} HTTP/1.1")]
702 );
703 }
704 let (origin, _) = retiring_cloud(503, r#"{"error":{"code":"unavailable"}}"#.into());
705 assert!(retire(&CloudClient::new(&origin).unwrap(), &id).is_err());
706 let (origin, _) = retiring_cloud(404, String::new());
708 assert!(retire(&CloudClient::new(&origin).unwrap(), &id).is_err());
709 assert!(retire(&CloudClient::new(&origin).unwrap(), "../admin").is_err());
710 }
711}