docs/generated/contracts.mdgenerated from code
Reference · 12 min read
caps
Contracts: caps.
Read as
Source: crates/lvcs-doc/src/kinds/caps/mod.rs.
1/// The root of every grant chain (discussion:owner/107): the owner's key and the2/// project name, whose [`ProjectRoot::project_id`] is the project id,3/// `HASH` of the canonical CBOR array (owner key bytes, name text), so4/// `lvcs://<project-id>` names a project without a registry. A daemon5/// accepts a `.lvcs/caps` owner only when its root's project id equals the6/// project id the daemon runs (the one `lvcs init` made, or the one7/// `lvcs join` was given): `lvcs join` learns the root from the caps8/// document's seed and checks it before it verifies any other change, so9/// the first node it syncs from can't substitute an owner of its own.10#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]11pub struct ProjectRoot {12 pub owner: PeerKey,13 pub name: String,14}1516/// A grant's id: the `HASH` of its [`Grant`]'s canonical CBOR encoding17/// ([`Grant::id`]), so a renewal (a new window) is a new grant with a new18/// id and a fresh quota (discussion:owner/148). A change's `Record::grant` names it. Written19/// in `ID_ENCODING`. The all-zero id ([`GrantId::OWNER`]) names no grant:20/// the owner's own changes, which need none (chosen at the M3 freeze).21#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]22pub struct GrantId(#[serde(with = "crate::cbor::fixed")] pub [u8; 32]);2324/// One thing a grant lets its grantee do (discussion:owner/146). Chosen at the25/// M3 freeze: changes and gossip are separate capabilities, so a grant can26/// let a peer talk without writing. A plugin's own capabilities are27/// [`Capability::Verb`]s its manifest declares (discussion:owner/514).28#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]29pub enum Capability {30 /// Sign changes to documents under the grant's `paths`: edits, tree31 /// saves, and control-document writes.32 Write,33 /// Approve protected-path changes (discussion:owner/518).34 Approve,35 /// Issue grants no wider than this one (discussion:owner/146).36 Delegate,37 /// Read documents under the grant's `paths` over the daemon's API38 /// (discussion:owner/300). It authorizes no change; a peer holding no39 /// live `Read` grant reads everything, as before, and one holding any40 /// reads only what they cover. A `Read` grant to [`ANYONE`] lets an41 /// unauthenticated client read those paths.42 Read,43 /// A verb a plugin's manifest declares (discussion:owner/514), on the grant's44 /// `paths`: [`MESSAGE_VERB`] (messaging's: publish gossip about, and45 /// post in threads on, documents under them), [`CHANNEL_MOVE_VERB`]46 /// (the actions plugin's: move the channels whose names they cover),47 /// or any other plugin's. Its name is at most `GRANT_TERM_MAX_BYTES`48 /// ([`verb_valid`]).49 Verb(String),50}5152/// Messaging's verb (discussion:owner/514): publish gossip (notifications,53/// responses, thread messages, presence) about documents under a grant's54/// paths, and post in a thread anchored there.55pub const MESSAGE_VERB: &str = "message";5657/// The actions plugin's channel-moving verb (discussion:owner/514, its name still58/// open: renamed here alone): attest a channel, on the channel's ledger59/// path ([`channel_ledger`]), which a grant's paths cover like any path60/// (`.lvcs/x/actions/channels/**` for every channel).61pub const CHANNEL_MOVE_VERB: &str = "channel.move";6263/// Where the actions plugin keeps each channel's ledger (discussion:owner/514).64pub const CHANNEL_LEDGER_PREFIX: &str = ".lvcs/x/actions/channels/";6566/// The ledger path of channel `name`, which the channel move verb is67/// checked on. Until the actions plugin owns its channels, today's channel68/// document and log document of `name` are checked here: this is the one69/// place they map onto it.70#[must_use]71pub fn channel_ledger(name: &str) -> String {72 format!("{CHANNEL_LEDGER_PREFIX}{name}")73}7475impl Capability {76 /// Its name: `write`, `approve`, `delegate`, `read`, or the verb.77 #[must_use]78 pub fn name(&self) -> &str {79 match self {80 Self::Write => "write",81 Self::Approve => "approve",82 Self::Delegate => "delegate",83 Self::Read => "read",84 Self::Verb(verb) => verb,85 }86 }8788 /// Messaging's [`MESSAGE_VERB`].89 #[must_use]90 pub fn message() -> Self {91 Self::Verb(MESSAGE_VERB.to_owned())92 }9394 /// The actions plugin's [`CHANNEL_MOVE_VERB`].95 #[must_use]96 pub fn channel_move() -> Self {97 Self::Verb(CHANNEL_MOVE_VERB.to_owned())98 }99100 /// Whether it is the verb named `name`.101 #[must_use]102 pub fn is_verb(&self, name: &str) -> bool {103 matches!(self, Self::Verb(verb) if verb == name)104 }105}106107/// Whether `verb` is a verb's name as a manifest may declare it: 1 to108/// `GRANT_TERM_MAX_BYTES` bytes of lowercase ASCII letters, digits, `-`,109/// and `.`, starting with a letter.110#[must_use]111pub fn verb_valid(verb: &str) -> bool {112 verb.len() <= GRANT_TERM_MAX_BYTES113 && verb.bytes().next().is_some_and(|b| b.is_ascii_lowercase())114 && verb115 .bytes()116 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || matches!(b, b'-' | b'.'))117}118119/// The channels `grant` names to move one by one (discussion:owner/514): when it120/// names [`CHANNEL_MOVE_VERB`], each of its paths that is one channel's121/// ledger path, not a pattern. A pattern (`.lvcs/x/actions/channels/**`)122/// moves every channel it covers ([`moves_channel`]), which a reader that123/// knows the channels (a runner, from its actions) checks one by one.124pub fn moved_channels(grant: &Grant) -> impl Iterator<Item = crate::kinds::channel::ChannelName> {125 let moves = grant126 .capabilities127 .iter()128 .any(|need| need.is_verb(CHANNEL_MOVE_VERB));129 grant130 .paths131 .iter()132 .filter(move |_| moves)133 .filter(|path| !path.contains(['*', '?', '[', '!', '\\']))134 .filter_map(|path| path.strip_prefix(CHANNEL_LEDGER_PREFIX))135 .filter_map(|name| crate::kinds::channel::ChannelName::parse(name).ok())136}137138/// Whether `grant` lets its grantee move the channel `name` (139/// discussion:owner/514): it names [`CHANNEL_MOVE_VERB`] and its paths cover the channel's140/// ledger path.141#[must_use]142pub fn moves_channel(grant: &Grant, name: &str) -> bool {143 grant144 .capabilities145 .iter()146 .any(|need| need.is_verb(CHANNEL_MOVE_VERB))147 && covers(&grant.paths, &channel_ledger(name))148}149150/// The grantee key of a grant to anyone (discussion:owner/300): the all-zero key,151/// which is no Ed25519 public key, so nothing ever signs as it. Only a152/// `Read` grant means anything for it.153pub const ANYONE: PeerKey = PeerKey([0; 32]);154155/// A grant's terms (discussion:owner/146), every one optional and156/// left out of the grant's encoding when absent. `harness` and `model`157/// name what the grantee runs, for attribution only: a receiving daemon158/// shows them beside the sender's `peer` tier, computed from the159/// grant `authorize` found, never from a message (discussion:owner/147), and no160/// check reads them but their length: each is at most161/// `GRANT_TERM_MAX_BYTES` (discussion:owner/178), and a caps change putting a162/// grant with a longer one is `out_of_scope`. `quota` is discussion:owner/70's change quota, enforced only163/// when set: in each document, a change signed under the grant is invalid164/// on every node when it comes after `quota` among its actor's changes165/// under the grant, counted in its peer's signed spans (history row 459);166/// the daemon signs167/// under a grant without a quota before a quota'd one, and under the168/// largest quota first (discussion:owner/178). `sign_per_sec`, `sign_burst`, and169/// `gossip_per_sec` are this grant's values for the grantee's signing and170/// gossip buckets, an absent one giving the `[limits]` default in force;171/// the grantee is metered at the largest over its live grants (172/// discussion:owner/178), so no grant lowers the rate another gives. An issuer may set any173/// value, since limits bound load, not authority. A renewal copies the174/// terms. `alias` is the name the project owner gives the grantee175/// (discussion:owner/243 and discussion:owner/247), for display and addressing only, no176/// authority: at most `ALIAS_MAX_BYTES` of lowercase ASCII letters,177/// digits, and `-`, starting with a letter ([`alias_valid`]), on a grant178/// the owner issued, else the grant is `out_of_scope` on every node. An179/// alias is bound for the life of the project to the grantee of the first180/// grant naming it, ordered by `not_before_s` then grant id, whether that181/// grant is live, expired, or revoked; a later grant naming it for another182/// grantee gives that grantee no alias.183#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]184pub struct GrantTerms {185 #[serde(default, skip_serializing_if = "Option::is_none")]186 pub harness: Option<String>,187 #[serde(default, skip_serializing_if = "Option::is_none")]188 pub model: Option<String>,189 #[serde(default, skip_serializing_if = "Option::is_none")]190 pub quota: Option<u64>,191 #[serde(default, skip_serializing_if = "Option::is_none")]192 pub sign_per_sec: Option<u32>,193 #[serde(default, skip_serializing_if = "Option::is_none")]194 pub sign_burst: Option<u32>,195 #[serde(default, skip_serializing_if = "Option::is_none")]196 pub gossip_per_sec: Option<u32>,197 #[serde(default, skip_serializing_if = "Option::is_none")]198 pub alias: Option<String>,199 /// The grant is a device certificate (discussion:owner/300): its issuer200 /// delegates to the grantee, a device key paired with `lvcs auth201 /// login`, which `lvcs auth status` lists and `lvcs auth logout`202 /// revokes. No rule reads it.203 #[serde(default, skip_serializing_if = "core::ops::Not::not")]204 pub device: bool,205 /// A device grant's name (discussion:owner/526): its person names their own206 /// devices, each name unique among that person's devices, never a207 /// project alias. Only a device grant names one; no rule reads it.208 #[serde(default, skip_serializing_if = "Option::is_none")]209 pub name: Option<String>,210 /// The grantee is an instance of the plugin this names (211 /// discussion:owner/553): a node's own key for a `local` plugin installed there, which212 /// the verifier treats as the plugin's key while the grant holds213 /// ([`instance_of`]). No rule reads it otherwise.214 #[serde(default, skip_serializing_if = "Option::is_none")]215 pub plugin: Option<String>,216}217218/// A capability grant (discussion:owner/58): `issuer` (the owner,219/// or a holder of [`Capability::Delegate`]) lets `grantee`, on the220/// [`GrantTerms`] `terms`, do `capabilities` on `paths` (gitignore-syntax221/// patterns relative to the project root, like every LVCS path pattern,222/// matched with the `ignore` crate's gitignore matcher, which `lvcs-doc`223/// links from the M3 freeze; sorted; `**` for everything)224/// within the window `not_before_s..not_after_s` in Unix seconds. A change225/// is within the window when the window contains the change's own commit226/// time (discussion:owner/58), which its signature covers, so every node decides alike227/// whatever its clock says; `not_after_s` is exclusive and absent only for228/// a grant with no expiry. `capabilities` is sorted.229///230/// `via` makes it a delegated grant (discussion:owner/514): `issuer`, a user,231/// lets `grantee`, the key of the installed plugin `via` names, act for232/// it. It needs no `Delegate`: any grant of its issuer's lets the issuer233/// add or revoke it, and it is never a chain link. An attempt under it is234/// authorized only when this grant covers it (the plugin's manifest, as235/// install granted it) and so does a grant of its issuer's own that is236/// not delegated (the user's): the intersection, decided at each check.237/// A change signed under it is attributed `<issuer> via <plugin>`.238#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]239pub struct Grant {240 pub issuer: PeerKey,241 pub grantee: PeerKey,242 #[serde(default, skip_serializing_if = "Option::is_none")]243 pub via: Option<String>,244 pub terms: GrantTerms,245 pub paths: Vec<String>,246 pub capabilities: Vec<Capability>,247 pub not_before_s: i64,248 pub not_after_s: Option<i64>,249}250251/// An installed plugin as the `.lvcs/caps` document holds it (252/// discussion:owner/514), at `/plugins/<name>`, written by `lvcs plugin install` (and253/// `upgrade`, which replaces it, and `remove`, which deletes it) under a254/// grant that names `Delegate`, as every caps write: `key` is the plugin's255/// own key (the grantee of its grants and of users' delegated grants that256/// name it in `via`), `command` the one top-level command it adds or257/// `parent` the plugin whose command it adds subcommands under (exactly258/// one of them), `verbs` the verbs its manifest declares (each259/// [`verb_valid`]), `rules` the checks every node's verifier makes of an260/// entry its ledgers under `.lvcs/x/<name>/` admit, `private` whether261/// that prefix is private: no `Read` grant whose patterns reach beyond it262/// covers it, and `remote` the remote roles its installer allowed (empty263/// for a `local` plugin, whose key every daemon refuses on `/lvcs/rpc/1`264/// and any connection but its per-user socket). Every node reads the265/// plugins it knows from here, so the rules a verifier applies are the266/// ones the change's deps hold.267#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]268pub struct PluginRecord {269 pub key: PeerKey,270 #[serde(default, skip_serializing_if = "Option::is_none")]271 pub command: Option<String>,272 #[serde(default, skip_serializing_if = "Option::is_none")]273 pub parent: Option<String>,274 pub verbs: Vec<String>,275 pub rules: Vec<EntryRule>,276 #[serde(default, skip_serializing_if = "core::ops::Not::not")]277 pub private: bool,278 #[serde(default, skip_serializing_if = "Vec::is_empty")]279 pub remote: Vec<String>,280 #[serde(default, skip_serializing_if = "Vec::is_empty")]281 pub surfaces: Vec<PluginSurface>,282 #[serde(default, skip_serializing_if = "Vec::is_empty")]283 pub owners: Vec<OwnerRule>,284 /// The ledgers an anonymous reader of a public project may read285 /// (discussion:owner/566): its manifest's `public_ledgers`, path patterns under286 /// its own prefix; none for a private plugin. Read where the anyone287 /// grant's paths also cover the ledger.288 #[serde(default, skip_serializing_if = "Vec::is_empty")]289 pub public: Vec<String>,290 /// The ledgers that roll to segments past `LEDGER_SEGMENT_MAX_BYTES`291 /// (discussion:owner/638): its manifest's `segmented`, path patterns under292 /// its own prefix. A segment `B~n` of a base `B` they match is judged293 /// as `B`.294 #[serde(default, skip_serializing_if = "Vec::is_empty")]295 pub segmented: Vec<String>,296}297298/// An owner rule of a plugin's manifest: a ledger at `owner`, a path299/// under the plugin's prefix one of whose segments is `{peer}`, takes an300/// event only from the peer that segment names (`ID_ENCODING`), its301/// author or the user a delegated grant acts for; and, with `or_plugin`,302/// from the plugin's own key too. Every other segment is literal.303#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]304pub struct OwnerRule {305 pub owner: String,306 #[serde(default, skip_serializing_if = "core::ops::Not::not")]307 pub or_plugin: bool,308}309310/// The placeholder segment an [`OwnerRule`]'s template names its owner by.311pub const OWNER_PEER: &str = "{peer}";312313impl OwnerRule {314 /// Whether its template is plain: names (not empty, `.`, or `..`, no315 /// `{` or `}` but the one `{peer}` segment) of at most316 /// `SURFACE_PATH_MAX_BYTES` in all.317 #[must_use]318 pub fn valid(&self) -> bool {319 let segments: Vec<&str> = self.owner.split('/').collect();320 self.owner.len() <= SURFACE_PATH_MAX_BYTES321 && segments322 .iter()323 .filter(|segment| **segment == OWNER_PEER)324 .count()325 == 1326 && segments.iter().all(|segment| {327 *segment == OWNER_PEER328 || !(matches!(*segment, "" | "." | "..")329 || segment.contains('{')330 || segment.contains('}'))331 })332 }333334 /// The owner segment of `path` (a ledger's path under its plugin's335 /// prefix) when the template matches it, segment by segment.336 #[must_use]337 pub fn owner_of<'a>(&self, path: &'a str) -> Option<&'a str> {338 let template: Vec<&str> = self.owner.split('/').collect();339 let path: Vec<&'a str> = path.split('/').collect();340 if template.len() != path.len() {341 return None;342 }343 let mut owner = None;344 for (want, have) in template.iter().zip(&path) {345 if *want == OWNER_PEER {346 owner = Some(*have);347 } else if want != have {348 return None;349 }350 }351 owner352 }353}354355/// The most surfaces one plugin declares (discussion:owner/520).356pub const SURFACES_MAX: usize = 16;357358/// The longest path a surface's entry or asset names, in bytes.359pub const SURFACE_PATH_MAX_BYTES: usize = 256;360361/// One UI surface a plugin ships (discussion:owner/520): a sandboxed web362/// component of `kind` (a name [`verb_valid`] takes, which the app363/// knows), at the surface API `version`, whose module is `entry`, a path364/// under the plugin's `ui/` ([`surface_path_valid`]).365#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]366pub struct PluginSurface {367 pub kind: String,368 pub version: String,369 pub entry: String,370}371372/// Whether `path` names a file under a plugin's `ui/`: `ui/` then one or373/// more `/`-separated names (not empty, `.`, or `..`, no `\`), at most374/// `SURFACE_PATH_MAX_BYTES`.375#[must_use]376pub fn surface_path_valid(path: &str) -> bool {377 let Some(rest) = path.strip_prefix("ui/") else {378 return false;379 };380 path.len() <= SURFACE_PATH_MAX_BYTES381 && !path.contains('\\')382 && rest383 .split('/')384 .all(|segment| !matches!(segment, "" | "." | ".."))385}386387/// One rule of a plugin's manifest (discussion:owner/514): an entry appended to388/// one of the plugin's ledgers needs `Verb(verb)` (or `Write`, `Approve`,389/// `Delegate`, `Read` when `verb` names one) on the address its field390/// `field` holds, a JSON string; except when `except` names a field391/// holding a JSON array of peer keys (`ID_ENCODING`) that lists the392/// appending author, who then needs nothing more. An entry with no string393/// at `field` is refused. Core reads only the fields rules name.394#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]395pub struct EntryRule {396 pub verb: String,397 pub field: String,398 #[serde(default, skip_serializing_if = "Option::is_none")]399 pub except: Option<String>,400}401402/// A grant with its issuer's `SIGNATURE` over [`Grant::signing_input`].403/// The `.lvcs/caps` document holds every signed grant; a grant whose404/// signature or chain fails is ignored by every node.405#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]406pub struct SignedGrant {407 pub grant: Grant,408 #[serde(with = "crate::cbor::fixed")]409 pub sig: [u8; 64],410}411412/// The static signed capability file `lvcs init` writes and that seeds the413/// `.lvcs/caps` document (discussion:owner/60), at `.lvcs/capabilities.cbor`: its414/// format version `v` (1), the project id's bytes, the project name and415/// the owner's key (the [`ProjectRoot`], whose project id must equal416/// `project`, so a node that knows only the id can check the owner), the417/// seed grants (`lvcs init` writes none), and the owner's `SIGNATURE` over418/// [`CapsFile::signing_input`]. Encoded as canonical CBOR. The caps419/// document's seed change carries `name`, `owner`, and the grants, so a420/// node that syncs `.lvcs/caps` learns the root.421#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]422pub struct CapsFile {423 pub v: u64,424 #[serde(with = "crate::cbor::fixed")]425 pub project: [u8; 32],426 pub name: String,427 pub owner: PeerKey,428 pub grants: Vec<SignedGrant>,429 #[serde(with = "crate::cbor::fixed")]430 pub sig: [u8; 64],431}