| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
use anyhow::{bail, Context, Result}; |
| 11 |
use oxy_core::durable::{write_atomic, write_atomic_private}; |
| 12 |
use oxy_core::hash::KeyId; |
| 13 |
use oxy_core::identity::{Identity, SecretKey, Signature}; |
| 14 |
use std::fs; |
| 15 |
use std::path::{Path, PathBuf}; |
| 16 |
|
| 17 |
|
| 18 |
#[derive(Clone, Debug)] |
| 19 |
pub struct KeyPair { |
| 20 |
pub key: KeyId, |
| 21 |
pub identity: Identity, |
| 22 |
secret: SecretKey, |
| 23 |
} |
| 24 |
|
| 25 |
impl KeyPair { |
| 26 |
|
| 27 |
pub fn generate(name: &str, email: &str) -> KeyPair { |
| 28 |
let secret = SecretKey::generate(); |
| 29 |
let identity = secret.identity(name, email, crate::ids::now_ms()); |
| 30 |
KeyPair { key: identity.hash(), identity, secret } |
| 31 |
} |
| 32 |
|
| 33 |
|
| 34 |
|
| 35 |
|
| 36 |
|
| 37 |
pub fn sign(&self, message: &[u8]) -> Signature { |
| 38 |
self.secret.sign_challenge(&self.key, message).expect("Spectra messages are longer than 16 bytes") |
| 39 |
} |
| 40 |
|
| 41 |
|
| 42 |
|
| 43 |
pub fn create_home(home: &Path, name: &str, email: &str) -> Result<KeyPair> { |
| 44 |
let pair = KeyPair::generate(name, email); |
| 45 |
let keys = home.join("keys"); |
| 46 |
fs::create_dir_all(&keys).with_context(|| format!("creating {}", keys.display()))?; |
| 47 |
#[cfg(unix)] |
| 48 |
{ |
| 49 |
use std::os::unix::fs::PermissionsExt; |
| 50 |
fs::set_permissions(home, fs::Permissions::from_mode(0o700))?; |
| 51 |
} |
| 52 |
write_atomic_private(&keys.join(format!("{}.secret", pair.key.to_hex())), &pair.secret.encode(&pair.key))?; |
| 53 |
write_atomic(&keys.join(format!("{}.identity", pair.key.to_hex())), &pair.identity.encode())?; |
| 54 |
let config = home.join("config.toml"); |
| 55 |
oxy_core::repo::Config::set_user(&config, "author.name", name)?; |
| 56 |
oxy_core::repo::Config::set_user(&config, "author.email", email)?; |
| 57 |
oxy_core::repo::Config::set_user(&config, "author.key", &pair.key.to_hex())?; |
| 58 |
Ok(pair) |
| 59 |
} |
| 60 |
|
| 61 |
|
| 62 |
|
| 63 |
pub fn load_home(home: &Path) -> Result<KeyPair> { |
| 64 |
let keys = home.join("keys"); |
| 65 |
let key = match author_key(home)? { |
| 66 |
Some(k) => k, |
| 67 |
None => { |
| 68 |
let secrets: Vec<PathBuf> = fs::read_dir(&keys) |
| 69 |
.with_context(|| format!("reading {}", keys.display()))? |
| 70 |
.filter_map(|e| e.ok().map(|e| e.path())) |
| 71 |
.filter(|p| p.extension().is_some_and(|x| x == "secret")) |
| 72 |
.collect(); |
| 73 |
match secrets.as_slice() { |
| 74 |
[one] => KeyId::from_hex(one.file_stem().and_then(|s| s.to_str()).unwrap_or("")) |
| 75 |
.context("a secret key file is not named by its key")?, |
| 76 |
[] => bail!("{} holds no secret key: an agent home is made by `spectra agent add`", home.display()), |
| 77 |
_ => bail!("{} holds several keys and its config.toml names none (author.key)", home.display()), |
| 78 |
} |
| 79 |
} |
| 80 |
}; |
| 81 |
KeyPair::load(&keys.join(format!("{}.secret", key.to_hex())), &keys.join(format!("{}.identity", key.to_hex()))) |
| 82 |
} |
| 83 |
|
| 84 |
|
| 85 |
pub fn load(secret: &Path, identity: &Path) -> Result<KeyPair> { |
| 86 |
let (key, secret_key) = SecretKey::decode(&fs::read(secret).with_context(|| format!("reading {}", secret.display()))?) |
| 87 |
.map_err(|e| anyhow::anyhow!("{}: {e}", secret.display()))?; |
| 88 |
let identity = Identity::decode(&fs::read(identity).with_context(|| format!("reading {}", identity.display()))?) |
| 89 |
.map_err(|e| anyhow::anyhow!("{}: {e}", identity.display()))?; |
| 90 |
if identity.hash() != key { |
| 91 |
bail!("{} is not the identity of {}", identity.name, secret.display()); |
| 92 |
} |
| 93 |
if secret_key.identity(&identity.name, &identity.email, identity.created).ed25519_pk != identity.ed25519_pk { |
| 94 |
bail!("the secret key in {} does not match its identity", secret.display()); |
| 95 |
} |
| 96 |
Ok(KeyPair { key, identity, secret: secret_key }) |
| 97 |
} |
| 98 |
|
| 99 |
|
| 100 |
pub fn instance(data: &Path, name: &str) -> Result<KeyPair> { |
| 101 |
let keys = data.join("keys"); |
| 102 |
let (secret, identity) = (keys.join("instance.secret"), keys.join("instance.identity")); |
| 103 |
if secret.exists() { |
| 104 |
return KeyPair::load(&secret, &identity); |
| 105 |
} |
| 106 |
fs::create_dir_all(&keys)?; |
| 107 |
let pair = KeyPair::generate(name, ""); |
| 108 |
write_atomic_private(&secret, &pair.secret.encode(&pair.key))?; |
| 109 |
write_atomic(&identity, &pair.identity.encode())?; |
| 110 |
Ok(pair) |
| 111 |
} |
| 112 |
} |
| 113 |
|
| 114 |
|
| 115 |
|
| 116 |
pub fn home_identity(home: &Path) -> Result<Identity> { |
| 117 |
let key = author_key(home)?.with_context(|| format!("{} names no identity (author.key in config.toml)", home.display()))?; |
| 118 |
let path = home.join("keys").join(format!("{}.identity", key.to_hex())); |
| 119 |
Identity::decode(&fs::read(&path).with_context(|| format!("reading {}", path.display()))?) |
| 120 |
.map_err(|e| anyhow::anyhow!("{}: {e}", path.display())) |
| 121 |
} |
| 122 |
|
| 123 |
fn author_key(home: &Path) -> Result<Option<KeyId>> { |
| 124 |
let config = home.join("config.toml"); |
| 125 |
let Ok(text) = fs::read_to_string(&config) else { return Ok(None) }; |
| 126 |
let table: toml::Table = text.parse().with_context(|| format!("reading {}", config.display()))?; |
| 127 |
let found = table.get("author").and_then(|a| a.get("key")).or_else(|| table.get("author.key")).and_then(|v| v.as_str()); |
| 128 |
Ok(match found { |
| 129 |
Some(hex) => Some(KeyId::from_hex(hex).with_context(|| format!("{}: author.key is not a key", config.display()))?), |
| 130 |
None => None, |
| 131 |
}) |
| 132 |
} |
| 133 |
|
| 134 |
#[cfg(test)] |
| 135 |
mod tests { |
| 136 |
use super::*; |
| 137 |
|
| 138 |
#[test] |
| 139 |
fn a_home_made_here_reads_back_and_signs_verifiably() { |
| 140 |
let dir = tempfile::tempdir().unwrap(); |
| 141 |
let made = KeyPair::create_home(dir.path(), "claude-oxygen", "").unwrap(); |
| 142 |
let read = KeyPair::load_home(dir.path()).unwrap(); |
| 143 |
assert_eq!(made.key, read.key); |
| 144 |
assert_eq!(home_identity(dir.path()).unwrap().hash(), made.key); |
| 145 |
let msg = b"spectra1 test message of some length"; |
| 146 |
let sig = read.sign(msg); |
| 147 |
oxy_core::identity::verify_challenge(&made.identity, &sig, msg).unwrap(); |
| 148 |
assert!(oxy_core::identity::verify_challenge(&made.identity, &sig, b"spectra1 another message entirely").is_err()); |
| 149 |
} |
| 150 |
|
| 151 |
#[test] |
| 152 |
fn the_instance_key_is_made_once() { |
| 153 |
let dir = tempfile::tempdir().unwrap(); |
| 154 |
let a = KeyPair::instance(dir.path(), "laptop").unwrap(); |
| 155 |
let b = KeyPair::instance(dir.path(), "laptop").unwrap(); |
| 156 |
assert_eq!(a.key, b.key); |
| 157 |
} |
| 158 |
} |