use crate::layer0::vocabulary::{HANDLE_MCARD_AUTH_TOKEN};
use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey};
use rand::RngCore;
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChallengeRecord {
pub did: String,
pub nonce: String,
pub challenge: String,
pub timestamp: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuthTokenRecord {
pub session_id: String,
pub handle: String,
pub bound_did: String,
pub expiry: String,
pub content_hash: String,
}
pub fn generate_auth_challenge(did: &str) -> ChallengeRecord {
let mut nonce_bytes = [0u8; 32];
rand::thread_rng().fill_bytes(&mut nonce_bytes);
let nonce = hex::encode(nonce_bytes);
let now = chrono::Utc::now().to_rfc3339();
let challenge = format!("clm_challenge:{}:{}", did, nonce);
ChallengeRecord {
did: did.to_string(),
nonce,
challenge,
timestamp: now,
}
}
pub fn sign_auth_challenge(challenge_text: &str, private_key_hex: &str) -> Result<String, String> {
let priv_bytes = hex::decode(private_key_hex).map_err(|e| format!("Invalid hex private key: {}", e))?;
let key_arr: [u8; 32] = priv_bytes.try_into().map_err(|_| "Private key must be exactly 32 bytes".to_string())?;
let signing_key = SigningKey::from_bytes(&key_arr);
let sig = signing_key.sign(challenge_text.as_bytes());
Ok(hex::encode(sig.to_bytes()))
}
pub fn verify_auth_challenge(
_did: &str,
public_key_bs58: &str,
challenge_text: &str,
signature_hex: &str,
) -> Result<bool, String> {
let pub_bytes = bs58::decode(public_key_bs58).into_vec().map_err(|e| format!("Invalid base58 public key: {}", e))?;
let pub_arr: [u8; 32] = pub_bytes.try_into().map_err(|_| "Public key must be exactly 32 bytes".to_string())?;
let verifying_key = VerifyingKey::from_bytes(&pub_arr).map_err(|e| format!("Invalid Ed25519 public key bytes: {}", e))?;
let sig_bytes = hex::decode(signature_hex).map_err(|e| format!("Invalid hex signature: {}", e))?;
let sig_arr: [u8; 64] = sig_bytes.try_into().map_err(|_| "Signature must be exactly 64 bytes".to_string())?;
let signature = Signature::from_bytes(&sig_arr);
match verifying_key.verify(challenge_text.as_bytes(), &signature) {
Ok(_) => Ok(true),
Err(_) => Ok(false),
}
}
pub fn mint_vcard_auth_token(
db_name_or_path: &str,
clm_root: Option<&str>,
did: &str,
expiry_secs: u64,
) -> Result<AuthTokenRecord, String> {
let mut sess_bytes = [0u8; 16];
rand::thread_rng().fill_bytes(&mut sess_bytes);
let session_id = format!("sess_{}", hex::encode(sess_bytes));
let expiry_dt = chrono::Utc::now() + chrono::Duration::seconds(expiry_secs as i64);
let expiry_iso = expiry_dt.to_rfc3339();
let handle = format!("{HANDLE_MCARD_AUTH_TOKEN}{}", session_id);
let content_json = serde_json::json!({
"bound_did": did,
"expiry": expiry_iso,
"session_id": session_id,
}).to_string();
let content_hash = crate::auth_namespace::mint_auth_mcard(db_name_or_path, clm_root, &handle, &content_json)?;
Ok(AuthTokenRecord {
session_id,
handle,
bound_did: did.to_string(),
expiry: expiry_iso,
content_hash,
})
}
pub fn verify_vcard_auth_token(
db_name_or_path: &str,
clm_root: Option<&str>,
session_id: &str,
) -> Result<bool, String> {
let handle = format!("{HANDLE_MCARD_AUTH_TOKEN}{}", session_id);
let db_path = if Path::new(db_name_or_path).is_absolute() || db_name_or_path.contains('/') || db_name_or_path.ends_with(".db") {
PathBuf::from(db_name_or_path)
} else {
let root = clm_root.map(PathBuf::from).unwrap_or_else(|| {
crate::layer0::environment::var(crate::layer0::vocabulary_env::ENV_CLM_ROOT).map(PathBuf::from).unwrap_or_else(|_| PathBuf::from("."))
});
root.join("db").join(db_name_or_path)
};
if !db_path.exists() {
return Ok(false);
}
let conn = rusqlite::Connection::open(&db_path).map_err(|e| e.to_string())?;
let _ = conn.busy_timeout(std::time::Duration::from_millis(u64::from(crate::layer0::runtime_contract::SQLITE_BUSY_TIMEOUT_MS)));
let Some(content) = crate::layer2::record_store::read_handle_text(&conn, handle.as_ref())
.map_err(|error| error.to_string())? else { return Ok(false); };
let v: serde_json::Value = serde_json::from_str(&content).map_err(|e| e.to_string())?;
let expiry_str = v.get("expiry").and_then(|x| x.as_str()).ok_or("Missing expiry in token")?;
let expiry_dt = chrono::DateTime::parse_from_rfc3339(expiry_str).map_err(|e| e.to_string())?;
let now = chrono::Utc::now();
Ok(expiry_dt > now)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_challenge_sign_verify_roundtrip() {
let identity = crate::identity::generate_ed25519_keypair().unwrap();
let challenge = generate_auth_challenge(&identity.did);
let signature = sign_auth_challenge(&challenge.challenge, &identity.private_key_hex).unwrap();
assert!(!signature.is_empty());
let is_valid = verify_auth_challenge(&identity.did, &identity.public_key_bs58, &challenge.challenge, &signature).unwrap();
assert!(is_valid);
let is_invalid = verify_auth_challenge(&identity.did, &identity.public_key_bs58, "corrupted_challenge", &signature).unwrap();
assert!(!is_invalid);
}
#[test]
fn test_vcard_token_mint_and_verify() {
let tmp_db = std::env::temp_dir().join("clm_test_vcard_token.db");
let _ = std::fs::remove_file(&tmp_db);
let db_str = tmp_db.to_str().unwrap();
let identity = crate::identity::generate_ed25519_keypair().unwrap();
let token = mint_vcard_auth_token(db_str, None, &identity.did, 3600).unwrap();
assert!(token.handle.starts_with("mcard:auth/token/sess_"));
let is_valid = verify_vcard_auth_token(db_str, None, &token.session_id).unwrap();
assert!(is_valid);
let _ = std::fs::remove_file(&tmp_db);
}
}