| 1 | |
|
| 2 | |
|
| 3 | |
|
| 4 | |
|
| 5 | | use super::{ui, Ctx}; |
| 6 | | use anyhow::{bail, Context, Result}; |
| 7 | | use spectra_core::identity::Identity; |
| 8 | | use spectra_core::keys::KeyPair; |
| 9 | | use spectra_core::ledger::Ledger; |
| 10 | | use spectra_core::principals::{identity_payload, signed_event, Principals}; |
| 11 | | use std::path::{Path, PathBuf}; |
| 12 | |
|
| 13 | |
|
| 14 | |
|
| 15 | 94× | pub fn owner_home(ctx: &Ctx, flag: Option<PathBuf>) -> PathBuf { |
| 16 | 94× | flag.or_else(|| ctx.config_owner_home()).unwrap_or_else(spectra_core::keys::default_home) |
| 17 | 94× | } |
| 18 | |
|
| 19 | 21× | pub async fn init(ctx: &Ctx, owner_home_flag: Option<PathBuf>, name: Option<String>) -> Result<i32> { |
| 20 | 21× | let data = &ctx.data; |
| 21 | 21× | let db = data.join("spectra.db"); |
| 22 | 21× | if db.exists() { |
| 23 | 1× | bail!("{} already holds a Spectra (spectra identity show)", data.display()); |
| 24 | 20× | } |
| 25 | 20× | let home = owner_home(ctx, owner_home_flag); |
| 26 | 20× | KeyPair::load_home(&home).with_context(|| { |
| 27 | 1× | format!("the owner signs with their own identity: none usable in {} (spectra identity create, or --owner-home)", home.display()) |
| 28 | 1× | })?; |
| 29 | 19× | std::fs::create_dir_all(data)?; |
| 30 | | #[cfg(unix)] |
| 31 | | { |
| 32 | | use std::os::unix::fs::PermissionsExt; |
| 33 | 19× | std::fs::set_permissions(data, std::fs::Permissions::from_mode(0o700))?; |
| 34 | | } |
| 35 | 19× | let name = name.unwrap_or_else(hostname); |
| 36 | 19× | let instance = KeyPair::instance(data, &name)?; |
| 37 | | |
| 38 | | |
| 39 | 19× | let owner = spectra_core::keys::delegate(&home, instance.key, None)?; |
| 40 | 19× | let ledger = Ledger::open(&db, Some(instance.clone())).await?; |
| 41 | 19× | let mut first = vec![ |
| 42 | 19× | signed_event(&owner, "human", "identity.owner", identity_payload(&owner.identity)), |
| 43 | 19× | signed_event(&instance, "system", "identity.instance", identity_payload(&instance.identity)), |
| 44 | | ]; |
| 45 | 19× | first.extend(spectra_core::conversation::default_channel_events()); |
| 46 | 19× | ledger.append(first).await?; |
| 47 | 19× | ledger.checkpoint().await?; |
| 48 | 19× | let home_s = home.display().to_string(); |
| 49 | 19× | std::fs::write( |
| 50 | 19× | data.join("spectra.toml"), |
| 51 | 19× | format!("# Spectra's configuration (spec §22.1).\n\n[owner]\nkey = \"{}\"\nhome = {}\n", owner.key.to_hex(), toml_str(&home_s)), |
| 52 | 0× | )?; |
| 53 | 19× | println!("{} {} {}", ui::done("Initialised"), ui::subject("Spectra"), ui::path(data.display())); |
| 54 | 19× | println!("{}", ui::kv("owner", format!("{}{}{}", ui::author(&owner.identity.name), ui::sep(), ui::hash(owner.key.short(12))))); |
| 55 | 19× | println!("{}", ui::kv("instance", format!("{}{}{}", name, ui::sep(), ui::hash(instance.key.short(12))))); |
| 56 | 19× | println!("{}", ui::kv("ledger", format!("{}{}", ui::path(db.display()), ui::dim(" (verified with spectra admin verify)")))); |
| 57 | 19× | println!(); |
| 58 | 19× | println!( |
| 59 | | " {} {} {}", |
| 60 | 19× | ui::note(), |
| 61 | 19× | ui::dim("then add agents with"), |
| 62 | 19× | ui::id("spectra agent add NAME --kind KIND --project PROJECT --home DIR") |
| 63 | | ); |
| 64 | 19× | Ok(0) |
| 65 | 21× | } |
| 66 | |
|
| 67 | 2× | pub async fn show(ctx: &Ctx, json: bool) -> Result<i32> { |
| 68 | 2× | if let Some(cfg) = ctx.remote()? { |
| 69 | 1× | return show_remote(&cfg, json).await; |
| 70 | 1× | } |
| 71 | 1× | let ledger = Ledger::open_read_only(&ctx.db()?).await?; |
| 72 | 1× | let p = Principals::load(&ledger).await?; |
| 73 | 1× | let owner = p.owner().context("no owner is recorded")?; |
| 74 | 1× | let instance = p.instance(); |
| 75 | 1× | let delegated = instance.is_some_and(|i| owner.delegates_to(&i.hash(), spectra_core::ids::now_ms())); |
| 76 | 1× | if json { |
| 77 | 1× | println!( |
| 78 | | "{}", |
| 79 | 1× | serde_json::json!({ |
| 80 | 1× | "owner": { "name": owner.name, "key": owner.hash().to_hex() }, |
| 81 | 1× | "instance": instance.map(|i| serde_json::json!({ "name": i.name, "key": i.hash().to_hex(), "delegated": delegated })), |
| 82 | | }) |
| 83 | | ); |
| 84 | 1× | return Ok(0); |
| 85 | 0× | } |
| 86 | 0× | println!("{}", ui::section("Owner")); |
| 87 | 0× | println!("{}", ui::kv("name", ui::author(format!("{} <{}>", owner.name, owner.contact)))); |
| 88 | 0× | println!("{}", ui::kv("key", ui::hash(owner.hash().to_hex()))); |
| 89 | 0× | println!("{}", ui::kv("delegates", owner.delegates.len())); |
| 90 | 0× | if let Some(i) = instance { |
| 91 | 0× | println!("{}", ui::section("Instance")); |
| 92 | 0× | println!("{}", ui::kv("name", &i.name)); |
| 93 | 0× | println!("{}", ui::kv("key", ui::hash(i.hash().to_hex()))); |
| 94 | 0× | if delegated { |
| 95 | 0× | println!("{}", ui::kv("status", ui::ok("delegated by the owner: checkpoints are verifiably yours"))); |
| 96 | 0× | } else { |
| 97 | 0× | println!("{}", ui::kv("status", ui::warn("not delegated by the owner's current identity"))); |
| 98 | 0× | } |
| 99 | 0× | } |
| 100 | 0× | Ok(0) |
| 101 | 2× | } |
| 102 | |
|
| 103 | |
|
| 104 | |
|
| 105 | 0× | pub async fn refresh(ctx: &Ctx, owner_home_flag: Option<PathBuf>) -> Result<i32> { |
| 106 | 0× | let home = owner_home(ctx, owner_home_flag); |
| 107 | 0× | let w = ctx.owner_writer(&home).await?; |
| 108 | 0× | let rotated = w.refresh_event(&home).await?; |
| 109 | 0× | let outcome = rotated.as_ref().map(|_| KeyPair::load_home(&home).map(|p| p.identity)).transpose()?; |
| 110 | 0× | if let Some(e) = rotated { |
| 111 | 0× | w.append(vec![e]).await?; |
| 112 | 0× | } |
| 113 | 0× | match outcome { |
| 114 | 0× | Some(id) => println!( |
| 115 | | "{} {}{}{}", |
| 116 | 0× | ui::done("Recorded"), |
| 117 | 0× | ui::subject("the owner's current identity"), |
| 118 | 0× | ui::sep(), |
| 119 | 0× | ui::hash(id.hash().short(12)) |
| 120 | | ), |
| 121 | 0× | None => println!("{} {}", ui::done("Current"), ui::subject("the owner's identity has not moved")), |
| 122 | | } |
| 123 | 0× | Ok(0) |
| 124 | 0× | } |
| 125 | |
|
| 126 | |
|
| 127 | |
|
| 128 | |
|
| 129 | 43× | pub async fn refresh_event(ledger: &Ledger, home: &Path) -> Result<Option<spectra_core::event::NewEvent>> { |
| 130 | 43× | let p = Principals::load(ledger).await?; |
| 131 | 43× | let recorded = p.owner().context("no owner is recorded (spectra init)")?.clone(); |
| 132 | 43× | rotation(&recorded, home) |
| 133 | 43× | } |
| 134 | |
|
| 135 | |
|
| 136 | |
|
| 137 | |
|
| 138 | 50× | pub fn rotation(recorded: &Identity, home: &Path) -> Result<Option<spectra_core::event::NewEvent>> { |
| 139 | 50× | let pair = KeyPair::load_home(home)?; |
| 140 | 50× | if pair.key == recorded.hash() { |
| 141 | 23× | return Ok(None); |
| 142 | 27× | } |
| 143 | 27× | let mut chain = Vec::new(); |
| 144 | 27× | let mut at = pair.identity.clone(); |
| 145 | 27× | while let Some(prev) = at.previous { |
| 146 | 27× | if prev == recorded.hash() { |
| 147 | 27× | break; |
| 148 | 0× | } |
| 149 | 0× | let file = home.join("keys").join(format!("{}.identity", prev.to_hex())); |
| 150 | 0× | at = Identity::decode( |
| 151 | 0× | &std::fs::read(&file).with_context(|| format!("{} is not a successor of the recorded owner", pair.identity.name))?, |
| 152 | | ) |
| 153 | 0× | .map_err(|e| anyhow::anyhow!("{}: {e}", file.display()))?; |
| 154 | 0× | chain.push(hex::encode(at.encode())); |
| 155 | 0× | if chain.len() > 1000 { |
| 156 | 0× | bail!("the owner's identity chain is too long to follow"); |
| 157 | 0× | } |
| 158 | | } |
| 159 | 27× | if at.previous != Some(recorded.hash()) && pair.identity.previous != Some(recorded.hash()) { |
| 160 | 0× | bail!("{} in {} is not a successor of the recorded owner {}", pair.identity.name, home.display(), recorded.hash().short(12)); |
| 161 | 27× | } |
| 162 | 27× | let mut payload = identity_payload(&pair.identity); |
| 163 | 27× | payload["chain"] = chain.into(); |
| 164 | 27× | Ok(Some(signed_event(&pair, "human", "identity.rotated", payload))) |
| 165 | 50× | } |
| 166 | |
|
| 167 | |
|
| 168 | |
|
| 169 | |
|
| 170 | 7× | pub async fn recorded_owner(ledger: &Ledger, home: &Path) -> Result<KeyPair> { |
| 171 | 7× | let p = Principals::load(ledger).await?; |
| 172 | 7× | let recorded = p.owner().context("no owner is recorded (spectra init)")?.hash(); |
| 173 | 7× | let keys = home.join("keys"); |
| 174 | 7× | KeyPair::load(&keys.join(format!("{}.secret", recorded.to_hex())), &keys.join(format!("{}.identity", recorded.to_hex()))) |
| 175 | 7× | .with_context(|| format!("the recorded owner's key is not in {}", home.display())) |
| 176 | 7× | } |
| 177 | |
|
| 178 | |
|
| 179 | 1× | async fn show_remote(cfg: &super::connect::ClientCfg, json: bool) -> Result<i32> { |
| 180 | 1× | let info = super::call(&spectra_mcp::client::Client::at(cfg.endpoint()?, None), "GET", "/api/v1/instance", None).await?; |
| 181 | 1× | let owner_key = info["owner"].as_str().unwrap_or("").to_string(); |
| 182 | 1× | let instance_key = info["instance"]["key"].as_str().unwrap_or("").to_string(); |
| 183 | 1× | let home = spectra_core::keys::default_home(); |
| 184 | 1× | let me = KeyPair::load_home(&home).ok(); |
| 185 | 1× | let delegated = me.as_ref().is_some_and(|m| { |
| 186 | 1× | spectra_core::identity::KeyId::from_hex(&instance_key).is_some_and(|k| m.identity.delegates_to(&k, spectra_core::ids::now_ms())) |
| 187 | 1× | }); |
| 188 | 1× | if json { |
| 189 | 1× | println!( |
| 190 | | "{}", |
| 191 | 1× | serde_json::json!({ |
| 192 | 1× | "server": cfg.server, |
| 193 | 1× | "owner": { "name": me.as_ref().map(|m| m.identity.name.clone()), "key": owner_key }, |
| 194 | 1× | "instance": { "name": info["name"], "key": instance_key, "delegated": delegated }, |
| 195 | | }) |
| 196 | | ); |
| 197 | 1× | return Ok(0); |
| 198 | 0× | } |
| 199 | 0× | println!("{}", ui::section("Server")); |
| 200 | 0× | println!("{}", ui::kv("url", ui::path(&cfg.server))); |
| 201 | 0× | println!("{}", ui::section("Owner")); |
| 202 | 0× | if let Some(m) = &me { |
| 203 | 0× | println!("{}", ui::kv("name", ui::author(format!("{} <{}>", m.identity.name, m.identity.contact)))); |
| 204 | 0× | } |
| 205 | 0× | println!("{}", ui::kv("key", ui::hash(&owner_key))); |
| 206 | 0× | println!("{}", ui::section("Instance")); |
| 207 | 0× | println!("{}", ui::kv("name", info["name"].as_str().unwrap_or(""))); |
| 208 | 0× | println!("{}", ui::kv("key", ui::hash(&instance_key))); |
| 209 | 0× | if delegated { |
| 210 | 0× | println!("{}", ui::kv("status", ui::ok("delegated by you: its checkpoints and certificate are verifiably yours"))); |
| 211 | 0× | } else { |
| 212 | 0× | println!("{}", ui::kv("status", ui::warn("not delegated by your current identity"))); |
| 213 | 0× | } |
| 214 | 0× | Ok(0) |
| 215 | 1× | } |
| 216 | |
|
| 217 | |
|
| 218 | 2× | pub fn create(name: &str, contact: &str, home: Option<PathBuf>) -> Result<i32> { |
| 219 | 2× | let home = home.unwrap_or_else(spectra_core::keys::default_home); |
| 220 | 2× | let pair = KeyPair::create_home(&home, name.trim(), contact.trim())?; |
| 221 | 1× | println!("{} {} {}", ui::done("Created"), ui::subject("your identity"), ui::path(home.display())); |
| 222 | 1× | println!("{}", ui::kv("name", ui::author(&pair.identity.name))); |
| 223 | 1× | println!("{}", ui::kv("key", ui::hash(pair.key.to_hex()))); |
| 224 | 1× | println!(" {} {}", ui::note(), ui::dim("keep keys/ private: anyone with it can act as you")); |
| 225 | 1× | println!( |
| 226 | | " {} {} {}", |
| 227 | 1× | ui::note(), |
| 228 | 1× | ui::dim("next: spectra init here, or on a server"), |
| 229 | 1× | ui::id(format!("spectra init --owner {}", pair.key.to_hex())) |
| 230 | | ); |
| 231 | 1× | Ok(0) |
| 232 | 2× | } |
| 233 | |
|
| 234 | |
|
| 235 | |
|
| 236 | |
|
| 237 | 6× | pub async fn init_for(ctx: &Ctx, owner_key: &str, name: Option<String>) -> Result<i32> { |
| 238 | 6× | let key = owner_key.trim().to_ascii_lowercase(); |
| 239 | 6× | if key.len() != 64 || hex::decode(&key).is_err() { |
| 240 | 1× | bail!("{owner_key} is not a KeyId (64 hex digits; the owner's `spectra identity show` prints it)"); |
| 241 | 5× | } |
| 242 | 5× | let data = &ctx.data; |
| 243 | 5× | let db = data.join("spectra.db"); |
| 244 | 5× | if db.exists() { |
| 245 | 0× | bail!("{} already holds a Spectra (spectra identity show)", data.display()); |
| 246 | 5× | } |
| 247 | 5× | std::fs::create_dir_all(data)?; |
| 248 | | #[cfg(unix)] |
| 249 | | { |
| 250 | | use std::os::unix::fs::PermissionsExt; |
| 251 | 5× | std::fs::set_permissions(data, std::fs::Permissions::from_mode(0o700))?; |
| 252 | | } |
| 253 | 5× | let name = name.unwrap_or_else(hostname); |
| 254 | 5× | let instance = KeyPair::instance(data, &name)?; |
| 255 | 5× | let ledger = Ledger::open(&db, Some(instance.clone())).await?; |
| 256 | 5× | let mut first = vec![signed_event(&instance, "system", "identity.instance", identity_payload(&instance.identity))]; |
| 257 | 5× | first.extend(spectra_core::conversation::default_channel_events()); |
| 258 | 5× | ledger.append(first).await?; |
| 259 | 5× | ledger.checkpoint().await?; |
| 260 | 5× | std::fs::write( |
| 261 | 5× | data.join("spectra.toml"), |
| 262 | 5× | format!( |
| 263 | | "# Spectra's configuration (spec §22.1).\n\n[owner]\nkey = \"{key}\" # claimed from the owner's machine with `spectra connect`\n\n[server]\n# bind = \"[::]:7350\" # serve other machines over TLS (spec §8.6)\n" |
| 264 | | ), |
| 265 | 0× | )?; |
| 266 | 5× | println!("{} {} {}", ui::done("Initialised"), ui::subject("Spectra"), ui::path(data.display())); |
| 267 | 5× | println!("{}", ui::kv("owner", format!("{}{}", ui::hash(&key[..12]), ui::dim(" (named; not yet claimed)")))); |
| 268 | 5× | println!("{}", ui::kv("instance", format!("{}{}{}", name, ui::sep(), ui::hash(instance.key.short(12))))); |
| 269 | 5× | println!(); |
| 270 | 5× | println!(" {} {}", ui::note(), ui::dim("serve it to other machines: set [server] bind in spectra.toml, then spectra serve")); |
| 271 | 5× | println!(" {} {}", ui::note(), ui::dim("then, on the owner's machine:")); |
| 272 | 5× | println!(" {}", ui::id("spectra connect https://HOST:7350")); |
| 273 | 5× | Ok(0) |
| 274 | 6× | } |
| 275 | |
|
| 276 | 18× | fn hostname() -> String { |
| 277 | 18× | std::fs::read_to_string("/etc/hostname") |
| 278 | 18× | .ok() |
| 279 | 18× | .map(|h| h.trim().to_string()) |
| 280 | 18× | .filter(|h| !h.is_empty()) |
| 281 | 18× | .unwrap_or_else(|| "spectra".into()) |
| 282 | 18× | } |
| 283 | |
|
| 284 | 19× | fn toml_str(s: &str) -> String { |
| 285 | 19× | serde_json::to_string(s).unwrap_or_default() |
| 286 | 19× | } |