1use serde::{Deserialize, Serialize};
23use serde_json::Value;
24
25use crate::CloudError;
26use crate::config::CloudConfig;
27use crate::state::{CloudStore, write_private};
28use crate::transport::CloudClient;
29
30pub const PATH: &str = "/stop";
33pub const FEATURE: &str = "team_stop";
35pub const MAX_ANSWER_BYTES: usize = 64 * 1024;
37pub const MAX_REASON_CHARS: usize = 500;
39const FILE: &str = "team-stop.json";
41
42#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
44pub struct TeamStop {
45 pub team: String,
47 pub stopped: bool,
48 pub since: Option<String>,
50 pub by: Option<String>,
52 pub reason: Option<String>,
53 pub generation: u64,
55 pub role: Option<String>,
57 pub may_stop: bool,
58 pub may_release: bool,
59 pub company_admin: Option<bool>,
62 pub step_up_url: Option<String>,
65}
66
67impl TeamStop {
68 #[must_use]
72 pub fn release_link(&self, web_origin: &str) -> Option<String> {
73 if let Some(url) = self
74 .step_up_url
75 .as_ref()
76 .filter(|u| below_origin(u, web_origin))
77 {
78 return Some(url.clone());
79 }
80 (self.stopped && self.may_release)
81 .then(|| format!("{}/o/{}/stop/", web_origin.trim_end_matches('/'), self.team))
82 }
83}
84
85#[must_use]
87pub fn is_slug(slug: &str) -> bool {
88 !slug.is_empty()
89 && slug.len() <= 64
90 && slug
91 .bytes()
92 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
93}
94
95#[must_use]
98pub fn safe_text(text: &str, max: usize) -> Option<String> {
99 let text: String = text
100 .chars()
101 .map(|c| if c.is_control() { ' ' } else { c })
102 .take(max)
103 .collect();
104 let text = text.trim();
105 (!text.is_empty()).then(|| text.to_owned())
106}
107
108#[must_use]
111pub fn below_origin(url: &str, origin: &str) -> bool {
112 let origin = origin.trim_end_matches('/');
113 url.len() <= 2048
114 && !origin.is_empty()
115 && !url.chars().any(|c| c.is_control() || c.is_whitespace())
116 && url
117 .strip_prefix(origin)
118 .is_some_and(|rest| rest.starts_with('/'))
119}
120
121pub fn decode(body: &Value) -> Result<TeamStop, CloudError> {
124 let bad = |why: &str| CloudError::Protocol(format!("team stop: {why}"));
125 let team = body["team"]
126 .as_str()
127 .filter(|t| is_slug(t))
128 .ok_or_else(|| bad("team is not a slug"))?;
129 let stopped = body["stopped"]
130 .as_bool()
131 .ok_or_else(|| bad("stopped is not a boolean"))?;
132 let since = body["since"]
133 .as_str()
134 .filter(|t| t.len() <= 64 && t.chars().all(|c| c.is_ascii_graphic()))
135 .map(str::to_owned);
136 let role = body["role"]
137 .as_str()
138 .filter(|r| {
139 !r.is_empty() && r.len() <= 32 && r.bytes().all(|b| b.is_ascii_lowercase() || b == b'_')
140 })
141 .map(str::to_owned);
142 Ok(TeamStop {
143 team: team.to_owned(),
144 stopped,
145 since: since.filter(|_| stopped),
146 by: ["name", "email"]
148 .iter()
149 .find_map(|key| body["by"][*key].as_str().and_then(|n| safe_text(n, 200)))
150 .filter(|_| stopped),
151 reason: body["reason"]
152 .as_str()
153 .and_then(|r| safe_text(r, MAX_REASON_CHARS))
154 .filter(|_| stopped),
155 generation: body["generation"].as_u64().unwrap_or(0),
156 role,
157 may_stop: body["may_stop"].as_bool() == Some(true),
158 may_release: body["may_release"].as_bool() == Some(true),
159 company_admin: body["company"]["admin"].as_bool(),
160 step_up_url: body["step_up_url"]
161 .as_str()
162 .filter(|u| {
163 let host = u
164 .strip_prefix("https://")
165 .or_else(|| u.strip_prefix("http://"));
166 host.is_some_and(|rest| !rest.starts_with('/'))
167 && u.len() <= 2048
168 && !u.chars().any(|c| c.is_control() || c.is_whitespace())
169 })
170 .map(str::to_owned),
171 })
172}
173
174pub fn fetch(client: &CloudClient) -> Result<(u16, Value), CloudError> {
177 let (status, body) = client.send_answer("GET", PATH, None, MAX_ANSWER_BYTES)?;
178 if status == 401 {
179 return Err(CloudError::Unauthorized);
180 }
181 Ok((status, body))
182}
183
184pub fn offered(store: &CloudStore, server: &str, client: &CloudClient) -> Result<bool, CloudError> {
188 crate::session_ref::refresh(store, server, client)?;
189 Ok(crate::session_ref::announced(store, FEATURE))
190}
191
192#[must_use]
195pub fn refused(status: u16, body: &Value) -> CloudError {
196 CloudError::from_response(status, body)
197}
198
199pub fn classify(status: u16, body: &Value) -> Result<Option<TeamStop>, CloudError> {
202 let code = body["error"]["code"].as_str().unwrap_or_default();
203 match status {
204 200 => decode(body).map(Some),
205 404 if code.is_empty() || code == "not_found" => Ok(None),
206 403 => Err(CloudError::Forbidden),
207 _ => Err(CloudError::from_response(status, body)),
208 }
209}
210
211#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
212#[serde(default)]
213struct Cache {
214 server: String,
216 org_id: String,
220 instance_id: String,
221 stop: Option<TeamStop>,
223 read_at: Option<u64>,
225}
226
227#[derive(Debug, Clone, PartialEq, Eq)]
229pub struct TeamStopRead {
230 pub stop: TeamStop,
231 pub age_s: Option<u64>,
234 pub stale: bool,
237}
238
239#[derive(Debug, Clone, PartialEq, Eq)]
241pub enum Cached {
242 Missing,
244 NotOffered,
246 Kept(TeamStopRead),
247}
248
249fn now_unix() -> u64 {
250 std::time::SystemTime::now()
251 .duration_since(std::time::UNIX_EPOCH)
252 .map_or(0, |d| d.as_secs())
253}
254
255pub fn read(store: &CloudStore, config: &CloudConfig) -> Option<Cached> {
258 let instance = store.instance().ok()??;
259 let Some(cache) = load(store).filter(|c| c.is_for(&instance)) else {
260 return Some(Cached::Missing);
261 };
262 let Some(stop) = cache.stop else {
263 return Some(Cached::NotOffered);
264 };
265 let age_s = cache.read_at.and_then(|at| now_unix().checked_sub(at));
266 let fresh_for = u64::from(config.pull_interval()) * 60 * 2;
267 Some(Cached::Kept(TeamStopRead {
268 stop,
269 age_s,
270 stale: age_s.is_none_or(|age| age > fresh_for),
271 }))
272}
273
274pub fn refresh_with(
278 store: &CloudStore,
279 session: &crate::auth::Session,
280) -> Result<Option<TeamStop>, CloudError> {
281 let server = session.instance.url.clone();
282 if !session.with_client(|client| offered(store, &server, client))? {
283 keep(store, None);
284 return Ok(None);
285 }
286 let (status, body) = session.with_client(fetch)?;
287 let stop = classify(status, &body)?;
288 keep(store, stop.as_ref());
289 Ok(stop)
290}
291
292pub fn session(
296 store: &CloudStore,
297 config: &CloudConfig,
298) -> Result<crate::auth::Session, CloudError> {
299 crate::scheduler::connected_session(store, config)
300}
301
302pub fn apply(
306 status: &mut lean_ctx_protocol::cloud::status::CloudCliStatusV1,
307 cached: &Cached,
308 web_origin: &str,
309) {
310 use lean_ctx_protocol::cloud::status::{CloudStatusCompanyV1, CloudStatusTeamStopV1};
311 let read = match cached {
312 Cached::NotOffered => return,
313 Cached::Missing => {
316 status.team_stop = Some(None);
317 return;
318 }
319 Cached::Kept(read) => read,
320 };
321 let stop = &read.stop;
322 status.team_stop = Some(Some(CloudStatusTeamStopV1 {
323 active: stop.stopped,
324 reason: stop.reason.clone(),
325 since: stop.since.clone(),
326 by: stop.by.clone(),
327 generation: stop.generation,
328 may_stop: stop.may_stop,
329 may_release: stop.may_release,
330 cache: if read.stale { "stale" } else { "fresh" }.into(),
331 age_s: read.age_s,
332 }));
333 status.role.clone_from(&stop.role);
334 status.org_slug = Some(stop.team.clone());
335 status.company = stop
336 .company_admin
337 .map(|admin| CloudStatusCompanyV1 { admin });
338 status.step_up_url = stop.release_link(web_origin).filter(|_| stop.stopped);
339}
340
341pub fn keep(store: &CloudStore, stop: Option<&TeamStop>) {
346 let Ok(Some(instance)) = store.instance() else {
347 return;
348 };
349 let (stop, read_at) = match stop {
350 Some(stop) => (Some(stop.clone()), Some(now_unix())),
351 None => match load(store).filter(|c| c.is_for(&instance)) {
352 Some(Cache {
353 stop: Some(kept), ..
354 }) if kept.stopped => (Some(kept), None),
355 _ => (None, Some(now_unix())),
356 },
357 };
358 let cache = Cache {
359 server: instance.url,
360 org_id: instance.org_id,
361 instance_id: instance.instance_id,
362 stop,
363 read_at,
364 };
365 if let Ok(bytes) = serde_json::to_vec_pretty(&cache) {
366 let _ = write_private(store.data_dir(), FILE, &bytes);
367 }
368}
369
370impl Cache {
371 fn is_for(&self, instance: &crate::state::InstanceRecord) -> bool {
373 self.server == instance.url
374 && self.org_id == instance.org_id
375 && self.instance_id == instance.instance_id
376 }
377}
378
379fn load(store: &CloudStore) -> Option<Cache> {
380 std::fs::read(store.data_dir().join(FILE))
381 .ok()
382 .and_then(|b| serde_json::from_slice(&b).ok())
383}
384
385#[cfg(test)]
386mod tests {
387 use super::*;
388 use serde_json::json;
389
390 fn stopped() -> Value {
391 json!({
392 "team": "acme-platform",
393 "stopped": true,
394 "since": "2026-11-19T10:00:00Z",
395 "by": {"id": "8d0c", "name": "Ada\u{1b}[2J Lovelace"},
396 "reason": "runaway agent\nspending",
397 "generation": 3,
398 "team_stop": {"since": "2026-11-19T10:00:00Z", "generation": 3},
399 "role": "admin",
400 "may_stop": true,
401 "may_release": true,
402 "signed": {"v": 1, "signature": "sig"}
403 })
404 }
405
406 #[test]
407 fn a_stop_is_checked_and_its_words_made_safe() {
408 let stop = decode(&stopped()).unwrap();
409 assert_eq!(
410 stop,
411 TeamStop {
412 team: "acme-platform".into(),
413 stopped: true,
414 since: Some("2026-11-19T10:00:00Z".into()),
415 by: Some("Ada [2J Lovelace".into()),
416 reason: Some("runaway agent spending".into()),
417 generation: 3,
418 role: Some("admin".into()),
419 may_stop: true,
420 may_release: true,
421 company_admin: None,
422 step_up_url: None,
423 }
424 );
425 assert_eq!(
426 stop.release_link("https://cloud.leanctx.com/").as_deref(),
427 Some("https://cloud.leanctx.com/o/acme-platform/stop/")
428 );
429 }
430
431 #[test]
432 fn a_running_team_names_no_stopper_and_no_release_link() {
433 let body = json!({"team": "acme", "stopped": false, "since": null, "by": null,
434 "reason": null, "generation": 4, "role": "contributor", "may_stop": true,
435 "may_release": false, "company": {"admin": true}});
436 let stop = decode(&body).unwrap();
437 assert!(!stop.stopped && stop.by.is_none() && stop.reason.is_none());
438 assert_eq!(stop.company_admin, Some(true));
439 assert_eq!(stop.release_link("https://cloud.leanctx.com"), None);
440 }
441
442 #[test]
443 fn a_stopper_without_a_name_is_named_by_email() {
444 let mut body = stopped();
445 body["by"] = json!({"id": "8d0c", "name": null, "email": "ada@acme.test"});
446 assert_eq!(decode(&body).unwrap().by.as_deref(), Some("ada@acme.test"));
447 body["by"] = json!({"id": "8d0c", "name": " ", "email": "ada@acme.test"});
448 assert_eq!(decode(&body).unwrap().by.as_deref(), Some("ada@acme.test"));
449 }
450
451 #[test]
452 fn a_broken_answer_is_refused_and_odd_members_left_out() {
453 for bad in [
454 json!({"stopped": true}),
455 json!({"team": "Acme Co", "stopped": true}),
456 json!({"team": "acme", "stopped": "yes"}),
457 ] {
458 assert!(
459 matches!(decode(&bad), Err(CloudError::Protocol(_))),
460 "{bad}"
461 );
462 }
463 let mut body = stopped();
464 body["role"] = json!("Admin<b>");
465 body["since"] = json!("2026-11-19 10:00");
466 body["may_release"] = json!("true");
467 body["step_up_url"] = json!("javascript:alert(1)");
468 let stop = decode(&body).unwrap();
469 assert_eq!(
470 (stop.role, stop.since, stop.may_release, stop.step_up_url),
471 (None, None, false, None)
472 );
473 body["step_up_url"] = json!("https://cloud.leanctx.com/o/acme-platform/stop/");
474 assert!(decode(&body).unwrap().step_up_url.is_some());
475 }
476
477 #[test]
478 fn links_stay_below_their_origin() {
479 let origin = "https://cloud.leanctx.com";
480 assert!(below_origin("https://cloud.leanctx.com/o/a/stop/", origin));
481 for bad in [
482 "https://cloud.leanctx.com.evil.example/o/a/stop/",
483 "https://evil.example/o/a/stop/",
484 "https://cloud.leanctx.com/o/a b/",
485 "https://cloud.leanctx.com",
486 ] {
487 assert!(!below_origin(bad, origin), "{bad}");
488 }
489 }
490
491 #[test]
492 fn an_older_cloud_offers_no_stop_and_a_refusal_is_an_error() {
493 assert_eq!(classify(404, &json!({})).unwrap(), None);
494 assert_eq!(
495 classify(403, &json!({"error": {"code": "forbidden"}})).unwrap_err(),
496 CloudError::Forbidden
497 );
498 assert!(classify(200, &stopped()).unwrap().unwrap().stopped);
499 }
500}