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