1pub mod broker;
17pub mod channel;
18pub mod chat_key;
19#[cfg(unix)]
20pub mod helper_mac;
21pub mod optin_key;
22pub mod person_sign;
23pub mod task_key;
24pub mod web;
25
26use std::sync::OnceLock;
27
28use serde::{Deserialize, Serialize};
29use serde_json::{Map, Value, json};
30
31pub use broker::{Broker, Trust};
32
33pub(crate) const KINDS_JSON: &str = include_str!("consent-kinds.json");
36
37pub const PROOF_DOMAIN: &str = "leanctx.cloud.consent_proof.v1\n";
39pub const STATEMENT_DOMAIN: &str = "leanctx.cloud.consent.v1\n";
41pub const STATEMENT_SCHEMA: &str = "leanctx.cloud.consent.v1";
42
43pub const REQUEST_TTL_MS: u64 = 24 * 60 * 60 * 1000;
45
46#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
49#[serde(rename_all = "snake_case")]
50pub enum Kind {
51 LinkVault,
52 ApiKeySet,
53}
54
55impl Kind {
56 pub const ALL: [Kind; 2] = [Kind::LinkVault, Kind::ApiKeySet];
57
58 pub fn as_str(self) -> &'static str {
59 match self {
60 Kind::LinkVault => "link_vault",
61 Kind::ApiKeySet => "api_key_set",
62 }
63 }
64
65 pub fn parse(value: &str) -> Option<Kind> {
66 Kind::ALL.into_iter().find(|k| k.as_str() == value)
67 }
68
69 fn spec(self) -> &'static KindSpec {
70 kind_specs()
71 .iter()
72 .find(|s| s.value == self.as_str())
73 .expect("every kind is in the embedded fixture (tested)")
74 }
75
76 pub fn subject_fields(self) -> &'static [String] {
78 &self.spec().subject
79 }
80
81 pub fn answerable_on(self, channel: &str) -> bool {
83 self.spec().channels.iter().any(|c| c == channel)
84 }
85
86 pub fn typed_field(self) -> &'static str {
89 match self {
90 Kind::LinkVault => "vault",
91 Kind::ApiKeySet => "vendor",
92 }
93 }
94}
95
96impl std::fmt::Display for Kind {
97 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
98 f.write_str(self.as_str())
99 }
100}
101
102#[derive(Debug, Deserialize)]
103struct KindSpec {
104 value: String,
105 channels: Vec<String>,
106 subject: Vec<String>,
107}
108
109#[derive(Debug, Deserialize)]
110struct KindList {
111 values: Vec<KindSpec>,
112}
113
114fn kind_specs() -> &'static [KindSpec] {
115 static SPECS: OnceLock<Vec<KindSpec>> = OnceLock::new();
116 SPECS.get_or_init(|| {
117 serde_json::from_str::<KindList>(KINDS_JSON)
118 .expect("embedded consent-kinds.json parses (tested)")
119 .values
120 })
121}
122
123#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
125#[serde(rename_all = "snake_case")]
126pub enum Channel {
127 OsPresence,
128 TtyOnly,
129 Cockpit,
130 Web,
131}
132
133impl Channel {
134 pub fn as_str(self) -> &'static str {
135 match self {
136 Channel::OsPresence => "os_presence",
137 Channel::TtyOnly => "tty_only",
138 Channel::Cockpit => "cockpit",
139 Channel::Web => "web",
140 }
141 }
142
143 fn surface(self) -> &'static str {
145 match self {
146 Channel::OsPresence | Channel::TtyOnly => "cli",
147 Channel::Cockpit => "cockpit",
148 Channel::Web => "web",
149 }
150 }
151}
152
153#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
154#[serde(rename_all = "snake_case")]
155pub enum State {
156 Pending,
157 Approved,
158 Denied,
159 Expired,
160}
161
162#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
164#[serde(deny_unknown_fields)]
165pub struct PresenceSignature {
166 pub key_id: String,
167 pub alg: String,
168 pub signature: String,
170}
171
172#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
174#[serde(rename_all = "snake_case")]
175pub enum Proof {
176 Presence(PresenceSignature),
177 Statement(Value),
178 Mac(String),
180}
181
182#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
184#[serde(deny_unknown_fields)]
185pub struct Record {
186 pub consent_id: String,
187 pub kind: Kind,
188 pub subject: Value,
189 pub subject_digest: String,
190 pub created_at: u64,
191 pub expires_at: u64,
192 pub state: State,
193 #[serde(default, skip_serializing_if = "Option::is_none")]
194 pub channel: Option<Channel>,
195 #[serde(default, skip_serializing_if = "Option::is_none")]
196 pub approved_at: Option<u64>,
197 #[serde(default, skip_serializing_if = "Option::is_none")]
198 pub proof: Option<Proof>,
199}
200
201impl Record {
202 pub fn proof_input(&self, approved_at: u64) -> Result<Vec<u8>, ConsentError> {
204 lean_ctx_protocol::cloud::signing_input(
205 PROOF_DOMAIN,
206 &json!({
207 "consent_id": self.consent_id,
208 "kind": self.kind,
209 "subject_digest": self.subject_digest,
210 "approved_at": approved_at,
211 }),
212 )
213 .map_err(|e| ConsentError::Local(e.to_string()))
214 }
215
216 pub fn fingerprint(&self) -> &str {
218 &self.subject_digest[..16]
219 }
220
221 pub fn typed_value(&self) -> String {
223 let value = self.subject[self.kind.typed_field()]
224 .as_str()
225 .unwrap_or_default();
226 if is_uuid(value) {
228 value[..8].to_string()
229 } else {
230 value.to_string()
231 }
232 }
233}
234
235#[derive(Debug, Clone, PartialEq, Eq)]
238pub enum ConsentError {
239 Required {
241 consent_id: String,
242 kind: Kind,
243 },
244 Denied,
246 Expired,
248 RecordInvalid,
250 WebOnly {
252 consent_id: String,
253 },
254 TerminalOnly,
256 PresenceRequiredByPolicy {
258 consent_id: String,
259 },
260 ChannelRefused(String),
263 NotFound,
265 InvalidSubject(String),
267 InvalidState,
269 WebTimeout,
271 PresenceCancelled,
273 HelperMissing,
275 HelperSignature,
277 PolicyExpired(String),
280 BrowserUnsupported,
283 Local(String),
284}
285
286impl ConsentError {
287 pub fn code(&self) -> &'static str {
288 match self {
289 ConsentError::Required { .. } => "consent_required",
290 ConsentError::Denied => "consent_denied",
291 ConsentError::Expired => "consent_expired",
292 ConsentError::RecordInvalid => "consent_record_invalid",
293 ConsentError::WebOnly { .. } => "consent_web_only",
294 ConsentError::TerminalOnly => "consent_terminal_only",
295 ConsentError::PresenceRequiredByPolicy { .. } => "consent_presence_required_by_policy",
296 ConsentError::ChannelRefused(_) => "consent_channel_refused",
297 ConsentError::NotFound => "not_found",
298 ConsentError::InvalidSubject(_) => "invalid_subject",
299 ConsentError::InvalidState => "invalid_state",
300 ConsentError::WebTimeout => "consent_web_timeout",
301 ConsentError::PresenceCancelled => "presence_cancelled",
302 ConsentError::HelperMissing => "helper_missing",
303 ConsentError::HelperSignature => "helper_signature",
304 ConsentError::PolicyExpired(_) => "policy_authorisation_expired",
305 ConsentError::BrowserUnsupported => "consent_browser_unsupported",
306 ConsentError::Local(_) => "local",
307 }
308 }
309}
310
311impl std::fmt::Display for ConsentError {
312 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
313 match self {
314 ConsentError::Required { .. } => {
316 f.write_str("Approve in a terminal: lean-ctx cloud consent")
317 }
318 ConsentError::Denied => f.write_str("The person declined this."),
319 ConsentError::Expired => f.write_str("This request expired; run the command again."),
320 ConsentError::RecordInvalid => {
321 f.write_str("A consent record was altered; approve again.")
322 }
323 ConsentError::WebOnly { consent_id } => write!(
324 f,
325 "Answer this one in the browser: lean-ctx cloud consent --web {consent_id}"
326 ),
327 ConsentError::TerminalOnly => {
328 f.write_str("This one is answered in the terminal only: lean-ctx cloud consent")
329 }
330 ConsentError::PresenceRequiredByPolicy { consent_id } => write!(
331 f,
332 "Your workspace requires system confirmation or the browser. Run: lean-ctx cloud consent --web {consent_id}"
333 ),
334 ConsentError::ChannelRefused(why) => write!(f, "Not approved: {why}"),
335 ConsentError::NotFound => f.write_str("No such consent request on this computer."),
336 ConsentError::InvalidSubject(why) => write!(f, "invalid consent subject: {why}"),
337 ConsentError::InvalidState => f.write_str("This request was already answered."),
338 ConsentError::WebTimeout => {
339 f.write_str("No answer in the browser within 10 minutes; run the command again.")
340 }
341 ConsentError::PresenceCancelled => {
342 f.write_str("System confirmation was cancelled. Nothing was approved.")
343 }
344 ConsentError::HelperMissing => f.write_str(
345 "LeanCTX Consent.app is not installed; run lean-ctx cloud consent-helper install.",
346 ),
347 ConsentError::HelperSignature => f.write_str(
348 "LeanCTX Consent.app signature invalid; run lean-ctx cloud consent-helper install.",
349 ),
350 ConsentError::PolicyExpired(why) => write!(f, "Refused: {why}"),
351 ConsentError::BrowserUnsupported => f.write_str(
352 "This Cloud does not offer the confirmation in the browser yet. Try again after its next update.",
353 ),
354 ConsentError::Local(why) => write!(f, "consent store: {why}"),
355 }
356 }
357}
358
359impl std::error::Error for ConsentError {}
360
361impl From<ConsentError> for crate::CloudError {
362 fn from(error: ConsentError) -> Self {
363 crate::CloudError::Refused(format!("{}: {error}", error.code()))
364 }
365}
366
367pub fn new_consent_id() -> Result<String, ConsentError> {
369 let mut bytes = [0u8; 10];
370 getrandom::fill(&mut bytes).map_err(|e| ConsentError::Local(e.to_string()))?;
371 Ok(format!("cns_{}", base32_lower(&bytes)))
372}
373
374pub fn is_consent_id(value: &str) -> bool {
375 value.strip_prefix("cns_").is_some_and(|rest| {
376 rest.len() == 16
377 && rest
378 .bytes()
379 .all(|b| b.is_ascii_lowercase() || (b'2'..=b'7').contains(&b))
380 })
381}
382
383fn base32_lower(bytes: &[u8]) -> String {
384 const ALPHABET: &[u8; 32] = b"abcdefghijklmnopqrstuvwxyz234567";
385 let mut out = String::with_capacity(bytes.len().div_ceil(5) * 8);
386 let (mut buffer, mut bits) = (0u32, 0u32);
387 for &byte in bytes {
388 buffer = (buffer << 8) | u32::from(byte);
389 bits += 8;
390 while bits >= 5 {
391 bits -= 5;
392 out.push(ALPHABET[((buffer >> bits) & 31) as usize] as char);
393 }
394 }
395 out
396}
397
398pub fn subject_digest(subject: &Value) -> Result<String, ConsentError> {
400 let bytes = lean_ctx_protocol::cloud::canonical_json(subject)
401 .map_err(|e| ConsentError::InvalidSubject(e.to_string()))?;
402 Ok(blake3::hash(&bytes).to_hex().to_string())
403}
404
405pub fn check_subject(kind: Kind, subject: &Value) -> Result<(), ConsentError> {
408 let bad = |why: String| Err(ConsentError::InvalidSubject(format!("{kind}: {why}")));
409 let Some(fields) = subject.as_object() else {
410 return bad("not an object".into());
411 };
412 let expected = kind.subject_fields();
413 if fields.len() != expected.len() || !expected.iter().all(|f| fields.contains_key(f)) {
414 let got: Vec<&String> = fields.keys().collect();
415 return bad(format!("fields {got:?}, expected {expected:?}"));
416 }
417 for (name, value) in fields {
418 if !field_ok(kind, name, value) {
419 return bad(format!("field {name}"));
420 }
421 }
422 Ok(())
423}
424
425fn field_ok(kind: Kind, name: &str, value: &Value) -> bool {
426 let text = value.as_str();
427 match name {
428 "link_digest" => text.is_some_and(is_hex64),
429 "vault" if kind == Kind::LinkVault => {
430 text.is_some_and(|v| crate::vault_address::VaultAddress::parse(v).is_ok())
431 }
432 "vault" => text.is_some_and(is_uuid),
433 "remote_seen" | "bound_repo" => {
434 value.is_null() || text.is_some_and(|t| (1..=500).contains(&t.chars().count()))
435 }
436 "target_vault" => value.is_null(),
437 "worker_id" => text.is_some_and(crate::bus::address::is_worker_id),
438 "cli" => text.is_some_and(|t| !t.is_empty() && t.len() <= 64),
439 "vendor" => text.is_some_and(|t| handle_like(t, 32)),
440 "requester" => text.is_some_and(|t| handle_like(t, 39)),
441 "instance_fingerprint" => text.is_some_and(|t| t.len() == 16 && is_lower_hex(t)),
442 _ => false,
443 }
444}
445
446fn handle_like(value: &str, max: usize) -> bool {
448 let bytes = value.as_bytes();
449 !bytes.is_empty()
450 && bytes.len() <= max
451 && bytes[0] != b'-'
452 && bytes
453 .iter()
454 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || *b == b'-')
455}
456
457fn is_lower_hex(value: &str) -> bool {
458 value
459 .bytes()
460 .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
461}
462
463fn is_hex64(value: &str) -> bool {
464 value.len() == 64 && is_lower_hex(value)
465}
466
467fn is_uuid(value: &str) -> bool {
468 let parts: Vec<&str> = value.split('-').collect();
469 parts.len() == 5
470 && parts.iter().map(|p| p.len()).eq([8, 4, 4, 4, 12])
471 && parts.iter().all(|p| is_lower_hex(p))
472}
473
474pub fn subject(fields: &[(&str, Value)]) -> Value {
476 Value::Object(
477 fields
478 .iter()
479 .map(|(k, v)| ((*k).to_string(), v.clone()))
480 .collect::<Map<_, _>>(),
481 )
482}
483
484#[cfg(test)]
485mod tests;