pub mod broker;
pub mod channel;
#[cfg(unix)]
pub mod helper_mac;
pub mod proof;
pub mod web;
use std::sync::OnceLock;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value, json};
pub use broker::{Broker, Restart, Trust};
pub(crate) const KINDS_JSON: &str = include_str!("consent-kinds.json");
pub const PROOF_DOMAIN: &str = "leanctx.hive.consent_proof.v1\n";
pub const STATEMENT_DOMAIN: &str = "leanctx.hive.consent.v1\n";
pub const STATEMENT_SCHEMA: &str = "leanctx.hive.consent.v1";
pub const REQUEST_TTL_MS: u64 = 24 * 60 * 60 * 1000;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Kind {
LinkVault,
PublicPresence,
SwarmJoin,
PledgeChange,
UnattendedStart,
ProcedureConfirm,
ReviewerEnable,
ApiKeySet,
SealedGrant,
}
impl Kind {
pub const ALL: [Kind; 9] = [
Kind::LinkVault,
Kind::PublicPresence,
Kind::SwarmJoin,
Kind::PledgeChange,
Kind::UnattendedStart,
Kind::ProcedureConfirm,
Kind::ReviewerEnable,
Kind::ApiKeySet,
Kind::SealedGrant,
];
pub fn as_str(self) -> &'static str {
match self {
Kind::LinkVault => "link_vault",
Kind::PublicPresence => "public_presence",
Kind::SwarmJoin => "swarm_join",
Kind::PledgeChange => "pledge_change",
Kind::UnattendedStart => "unattended_start",
Kind::ProcedureConfirm => "procedure_confirm",
Kind::ReviewerEnable => "reviewer_enable",
Kind::ApiKeySet => "api_key_set",
Kind::SealedGrant => "sealed_grant",
}
}
pub fn parse(value: &str) -> Option<Kind> {
Kind::ALL.into_iter().find(|k| k.as_str() == value)
}
fn spec(self) -> &'static KindSpec {
kind_specs()
.iter()
.find(|s| s.value == self.as_str())
.expect("every kind is in the embedded fixture (tested)")
}
pub fn subject_fields(self) -> &'static [String] {
&self.spec().subject
}
pub fn answerable_on(self, channel: &str) -> bool {
self.spec().channels.iter().any(|c| c == channel)
}
pub fn server_gated(self) -> bool {
self.spec().server_route.is_some()
}
pub fn typed_field(self) -> &'static str {
match self {
Kind::LinkVault | Kind::PublicPresence | Kind::SealedGrant => "vault",
Kind::SwarmJoin | Kind::PledgeChange | Kind::UnattendedStart => "swarm",
Kind::ProcedureConfirm => "item_id",
Kind::ReviewerEnable => "place",
Kind::ApiKeySet => "vendor",
}
}
}
impl std::fmt::Display for Kind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Deserialize)]
struct KindSpec {
value: String,
channels: Vec<String>,
subject: Vec<String>,
server_route: Option<String>,
}
#[derive(Debug, Deserialize)]
struct KindList {
values: Vec<KindSpec>,
}
fn kind_specs() -> &'static [KindSpec] {
static SPECS: OnceLock<Vec<KindSpec>> = OnceLock::new();
SPECS.get_or_init(|| {
serde_json::from_str::<KindList>(KINDS_JSON)
.expect("embedded consent-kinds.json parses (tested)")
.values
})
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Channel {
OsPresence,
TtyOnly,
Cockpit,
Web,
}
impl Channel {
pub fn as_str(self) -> &'static str {
match self {
Channel::OsPresence => "os_presence",
Channel::TtyOnly => "tty_only",
Channel::Cockpit => "cockpit",
Channel::Web => "web",
}
}
fn surface(self) -> &'static str {
match self {
Channel::OsPresence | Channel::TtyOnly => "cli",
Channel::Cockpit => "cockpit",
Channel::Web => "web",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum State {
Pending,
Approved,
Denied,
Expired,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PresenceSignature {
pub key_id: String,
pub alg: String,
pub signature: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Proof {
Presence(PresenceSignature),
Statement(Value),
Mac(String),
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Record {
pub consent_id: String,
pub kind: Kind,
pub subject: Value,
pub subject_digest: String,
pub created_at: u64,
pub expires_at: u64,
pub state: State,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub channel: Option<Channel>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub approved_at: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub proof: Option<Proof>,
}
impl Record {
pub fn proof_input(&self, approved_at: u64) -> Result<Vec<u8>, ConsentError> {
lean_ctx_protocol::hive::signing_input(
PROOF_DOMAIN,
&json!({
"consent_id": self.consent_id,
"kind": self.kind,
"subject_digest": self.subject_digest,
"approved_at": approved_at,
}),
)
.map_err(|e| ConsentError::Local(e.to_string()))
}
pub fn fingerprint(&self) -> &str {
&self.subject_digest[..16]
}
pub fn typed_value(&self) -> String {
let value = self.subject[self.kind.typed_field()]
.as_str()
.unwrap_or_default();
if is_uuid(value) {
value[..8].to_string()
} else {
value.to_string()
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ConsentError {
Required {
consent_id: String,
kind: Kind,
},
Denied,
Expired,
RecordInvalid,
WebOnly {
consent_id: String,
},
TerminalOnly,
PresenceRequiredByPolicy {
consent_id: String,
},
ChannelRefused(String),
NotFound,
InvalidSubject(String),
InvalidState,
WebTimeout,
PresenceCancelled,
HelperMissing,
HelperSignature,
PolicyExpired(String),
Local(String),
}
impl ConsentError {
pub fn code(&self) -> &'static str {
match self {
ConsentError::Required { .. } => "consent_required",
ConsentError::Denied => "consent_denied",
ConsentError::Expired => "consent_expired",
ConsentError::RecordInvalid => "consent_record_invalid",
ConsentError::WebOnly { .. } => "consent_web_only",
ConsentError::TerminalOnly => "consent_terminal_only",
ConsentError::PresenceRequiredByPolicy { .. } => "consent_presence_required_by_policy",
ConsentError::ChannelRefused(_) => "consent_channel_refused",
ConsentError::NotFound => "not_found",
ConsentError::InvalidSubject(_) => "invalid_subject",
ConsentError::InvalidState => "invalid_state",
ConsentError::WebTimeout => "consent_web_timeout",
ConsentError::PresenceCancelled => "presence_cancelled",
ConsentError::HelperMissing => "helper_missing",
ConsentError::HelperSignature => "helper_signature",
ConsentError::PolicyExpired(_) => "policy_authorisation_expired",
ConsentError::Local(_) => "local",
}
}
}
impl std::fmt::Display for ConsentError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ConsentError::Required { .. } => {
f.write_str("Approve in a terminal: lean-ctx hive consent")
}
ConsentError::Denied => f.write_str("The person declined this."),
ConsentError::Expired => f.write_str("This request expired; run the command again."),
ConsentError::RecordInvalid => {
f.write_str("A consent record was altered; approve again.")
}
ConsentError::WebOnly { consent_id } => write!(
f,
"Answer this one in the browser: lean-ctx hive consent --web {consent_id}"
),
ConsentError::TerminalOnly => {
f.write_str("This one is answered in the terminal only: lean-ctx hive consent")
}
ConsentError::PresenceRequiredByPolicy { consent_id } => write!(
f,
"Your workspace requires system confirmation or the browser. Run: lean-ctx hive consent --web {consent_id}"
),
ConsentError::ChannelRefused(why) => write!(f, "Not approved: {why}"),
ConsentError::NotFound => f.write_str("No such consent request on this computer."),
ConsentError::InvalidSubject(why) => write!(f, "invalid consent subject: {why}"),
ConsentError::InvalidState => f.write_str("This request was already answered."),
ConsentError::WebTimeout => {
f.write_str("No answer in the browser within 10 minutes; run the command again.")
}
ConsentError::PresenceCancelled => {
f.write_str("System confirmation was cancelled. Nothing was approved.")
}
ConsentError::HelperMissing => f.write_str(
"LeanCTX Consent.app is not installed; run lean-ctx hive consent-helper install.",
),
ConsentError::HelperSignature => f.write_str(
"LeanCTX Consent.app signature invalid; run lean-ctx hive consent-helper install.",
),
ConsentError::PolicyExpired(why) => write!(f, "Refused: {why}"),
ConsentError::Local(why) => write!(f, "consent store: {why}"),
}
}
}
impl std::error::Error for ConsentError {}
impl From<ConsentError> for crate::core::hive::HiveError {
fn from(error: ConsentError) -> Self {
crate::core::hive::HiveError::Refused(format!("{}: {error}", error.code()))
}
}
pub fn new_consent_id() -> Result<String, ConsentError> {
let mut bytes = [0u8; 10];
getrandom::fill(&mut bytes).map_err(|e| ConsentError::Local(e.to_string()))?;
Ok(format!("cns_{}", base32_lower(&bytes)))
}
pub fn is_consent_id(value: &str) -> bool {
value.strip_prefix("cns_").is_some_and(|rest| {
rest.len() == 16
&& rest
.bytes()
.all(|b| b.is_ascii_lowercase() || (b'2'..=b'7').contains(&b))
})
}
fn base32_lower(bytes: &[u8]) -> String {
const ALPHABET: &[u8; 32] = b"abcdefghijklmnopqrstuvwxyz234567";
let mut out = String::with_capacity(bytes.len().div_ceil(5) * 8);
let (mut buffer, mut bits) = (0u32, 0u32);
for &byte in bytes {
buffer = (buffer << 8) | u32::from(byte);
bits += 8;
while bits >= 5 {
bits -= 5;
out.push(ALPHABET[((buffer >> bits) & 31) as usize] as char);
}
}
out
}
pub fn subject_digest(subject: &Value) -> Result<String, ConsentError> {
let bytes = lean_ctx_protocol::hive::canonical_json(subject)
.map_err(|e| ConsentError::InvalidSubject(e.to_string()))?;
Ok(blake3::hash(&bytes).to_hex().to_string())
}
pub fn check_subject(kind: Kind, subject: &Value) -> Result<(), ConsentError> {
let bad = |why: String| Err(ConsentError::InvalidSubject(format!("{kind}: {why}")));
let Some(fields) = subject.as_object() else {
return bad("not an object".into());
};
let expected = kind.subject_fields();
if fields.len() != expected.len() || !expected.iter().all(|f| fields.contains_key(f)) {
let got: Vec<&String> = fields.keys().collect();
return bad(format!("fields {got:?}, expected {expected:?}"));
}
for (name, value) in fields {
if !field_ok(kind, name, value) {
return bad(format!("field {name}"));
}
}
Ok(())
}
fn field_ok(kind: Kind, name: &str, value: &Value) -> bool {
let text = value.as_str();
match name {
"link_digest" | "pledge_digest" | "before_digest" | "after_digest" | "item_digest" => {
text.is_some_and(is_hex64)
}
"command_digests" => value.as_array().is_some_and(|items| {
(1..=10).contains(&items.len())
&& items.iter().all(|d| d.as_str().is_some_and(is_hex64))
}),
"vault" if kind == Kind::LinkVault => {
text.is_some_and(|v| crate::core::hive::vault_address::VaultAddress::parse(v).is_ok())
}
"swarm" | "vault" => text.is_some_and(is_uuid),
"remote_seen" | "bound_repo" => {
value.is_null() || text.is_some_and(|t| (1..=500).contains(&t.chars().count()))
}
"target_vault" => value.is_null(),
"worker_id" => text.is_some_and(crate::core::hive::bus::address::is_worker_id),
"cli" => text.is_some_and(|t| !t.is_empty() && t.len() <= 64),
"usd_cents_per_day" => value.as_u64().is_some(),
"reviewer_usd_cents_per_day" => value.as_u64().is_some_and(|c| (100..=50_000).contains(&c)),
"source" => matches!(text, Some("owner" | "own")),
"place" => text.is_some_and(|t| {
t.split_once(':')
.is_some_and(|(k, id)| !k.is_empty() && !id.is_empty())
}),
"item_id" => text.is_some_and(|t| t.starts_with("rv_")),
"vendor" => text.is_some_and(|t| handle_like(t, 32)),
"requester" => text.is_some_and(|t| handle_like(t, 39)),
"engine_fingerprint" => text.is_some_and(|t| t.len() == 16 && is_lower_hex(t)),
_ => false,
}
}
fn handle_like(value: &str, max: usize) -> bool {
let bytes = value.as_bytes();
!bytes.is_empty()
&& bytes.len() <= max
&& bytes[0] != b'-'
&& bytes
.iter()
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || *b == b'-')
}
fn is_lower_hex(value: &str) -> bool {
value
.bytes()
.all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
}
fn is_hex64(value: &str) -> bool {
value.len() == 64 && is_lower_hex(value)
}
fn is_uuid(value: &str) -> bool {
let parts: Vec<&str> = value.split('-').collect();
parts.len() == 5
&& parts.iter().map(|p| p.len()).eq([8, 4, 4, 4, 12])
&& parts.iter().all(|p| is_lower_hex(p))
}
pub fn subject(fields: &[(&str, Value)]) -> Value {
Value::Object(
fields
.iter()
.map(|(k, v)| ((*k).to_string(), v.clone()))
.collect::<Map<_, _>>(),
)
}
#[cfg(test)]
mod tests;