feat(cli): implement device add with signing + deploy key

- Create crates/relicario-cli/src/device.rs: local key storage under
  ~/.config/relicario/devices/<name>/, current-device tracking, and
  git signing config (gpg.format=ssh, user.signingkey, core.sshCommand)
- Add Device command to CLI with add/revoke/list subcommands
- cmd_device add: generates two ed25519 keypairs (signing + deploy),
  registers deploy key via Gitea API, stores keys at 0600, configures
  git SSH signing, updates .relicario/devices.json and commits
- Gitea config read from flags or RELICARIO_GITEA_{URL,TOKEN,OWNER,REPO}
- --no-gitea flag skips API registration for non-Gitea remotes

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
adlee-was-taken
2026-05-02 12:19:55 -04:00
parent 61f2f9c18f
commit b1f9f2fbfc
2 changed files with 473 additions and 1 deletions

View File

@@ -2,9 +2,10 @@
//!
//! See module docs for the unlock flow and vault layout.
mod device;
mod gitea;
mod helpers;
mod session;
mod gitea;
use std::path::PathBuf;
@@ -189,6 +190,12 @@ enum Commands {
/// Passphrase to score, or `-` to read from stdin.
passphrase: String,
},
/// Manage registered devices (signing keys + deploy keys).
Device {
#[command(subcommand)]
action: DeviceAction,
},
}
#[derive(Subcommand)]
@@ -348,6 +355,54 @@ enum ImportAction {
},
}
#[derive(Subcommand)]
enum DeviceAction {
/// Register this machine as a new device.
///
/// Generates two ed25519 keypairs: one for signing commits, one for push
/// access (deploy key). The deploy public key is registered via the Gitea
/// API. Both private keys are stored locally in
/// `~/.config/relicario/devices/<name>/`. The vault's `.relicario/devices.json`
/// is updated and committed.
///
/// Required environment variables (or flags):
/// RELICARIO_GITEA_URL — e.g. https://git.example.com
/// RELICARIO_GITEA_TOKEN — personal access token with repo write access
/// RELICARIO_GITEA_OWNER — repository owner
/// RELICARIO_GITEA_REPO — repository name
Add {
/// Human-readable name for this device (e.g. "laptop-2026").
#[arg(long)]
name: String,
/// Gitea API base URL (overrides RELICARIO_GITEA_URL).
#[arg(long)]
gitea_url: Option<String>,
/// Gitea personal access token (overrides RELICARIO_GITEA_TOKEN).
#[arg(long)]
gitea_token: Option<String>,
/// Gitea repository owner (overrides RELICARIO_GITEA_OWNER).
#[arg(long)]
owner: Option<String>,
/// Gitea repository name (overrides RELICARIO_GITEA_REPO).
#[arg(long)]
repo: Option<String>,
/// Skip Gitea API registration (useful when the remote is not Gitea).
#[arg(long)]
no_gitea: bool,
},
/// Revoke a registered device.
///
/// Removes the device from `devices.json`, adds it to `revoked.json`,
/// deletes the deploy key from Gitea, and commits the change.
Revoke {
/// Name of the device to revoke.
#[arg(long)]
name: String,
},
/// List registered devices.
List,
}
fn main() -> Result<()> {
let cli = Cli::parse();
match cli.command {
@@ -380,6 +435,7 @@ fn main() -> Result<()> {
Ok(())
}
Commands::Rate { passphrase } => cmd_rate(passphrase),
Commands::Device { action } => cmd_device(action),
}
}
@@ -2228,3 +2284,253 @@ fn cmd_rate(passphrase: String) -> Result<()> {
println!("note: init requires score ≥ 3 (see `relicario init`)");
Ok(())
}
// ── Device management ─────────────────────────────────────────────────────────
/// Build a `GiteaClient` from flags or environment variables.
fn load_gitea_client(
gitea_url: Option<String>,
gitea_token: Option<String>,
owner: Option<String>,
repo: Option<String>,
) -> Result<crate::gitea::GiteaClient> {
let url = gitea_url
.or_else(|| std::env::var("RELICARIO_GITEA_URL").ok())
.ok_or_else(|| anyhow::anyhow!(
"Gitea URL required — pass --gitea-url or set RELICARIO_GITEA_URL"
))?;
let token = gitea_token
.or_else(|| std::env::var("RELICARIO_GITEA_TOKEN").ok())
.ok_or_else(|| anyhow::anyhow!(
"Gitea token required — pass --gitea-token or set RELICARIO_GITEA_TOKEN"
))?;
let owner = owner
.or_else(|| std::env::var("RELICARIO_GITEA_OWNER").ok())
.ok_or_else(|| anyhow::anyhow!(
"Gitea owner required — pass --owner or set RELICARIO_GITEA_OWNER"
))?;
let repo = repo
.or_else(|| std::env::var("RELICARIO_GITEA_REPO").ok())
.ok_or_else(|| anyhow::anyhow!(
"Gitea repo required — pass --repo or set RELICARIO_GITEA_REPO"
))?;
Ok(crate::gitea::GiteaClient::new(&url, &token, &owner, &repo))
}
fn cmd_device(action: DeviceAction) -> Result<()> {
use std::fs;
use relicario_core::device::{DeviceEntry, RevokedEntry, generate_keypair};
let root = crate::helpers::vault_dir()?;
let relicario_dir = root.join(".relicario");
let devices_path = relicario_dir.join("devices.json");
match action {
DeviceAction::Add { name, gitea_url, gitea_token, owner, repo, no_gitea } => {
// Guard: don't overwrite an already-registered device name.
let existing: Vec<DeviceEntry> = fs::read(&devices_path)
.ok()
.and_then(|b| serde_json::from_slice(&b).ok())
.unwrap_or_default();
if existing.iter().any(|d| d.name == name) {
anyhow::bail!("a device named '{}' is already registered", name);
}
eprintln!("Generating signing keypair...");
let (signing_priv, signing_pub) = generate_keypair()
.map_err(|e| anyhow::anyhow!("generate signing keypair: {e}"))?;
eprintln!("Generating deploy keypair...");
let (deploy_priv, deploy_pub) = generate_keypair()
.map_err(|e| anyhow::anyhow!("generate deploy keypair: {e}"))?;
// Optionally register deploy key with Gitea.
let gitea_key_id: u64 = if no_gitea {
eprintln!("Skipping Gitea deploy key registration (--no-gitea).");
0
} else {
let client = load_gitea_client(gitea_url, gitea_token, owner, repo)?;
let key_title = format!("relicario-{}", name);
eprintln!("Registering deploy key '{}' with Gitea...", key_title);
client.create_deploy_key(&key_title, &deploy_pub)?
};
// Store keys locally with proper permissions.
crate::device::store_device_keys(
&name,
&signing_priv,
&signing_pub,
&deploy_priv,
&deploy_pub,
gitea_key_id,
)?;
// Mark as current device.
crate::device::set_current_device(&name)?;
// Configure git signing + SSH deploy key in the vault repo.
crate::device::configure_git_signing(&root, &name)?;
// Update devices.json.
let current_name = name.clone();
let mut devices = existing;
devices.push(DeviceEntry {
name: name.clone(),
public_key: signing_pub.clone(),
added_at: relicario_core::now_unix(),
added_by: current_name,
});
fs::create_dir_all(&relicario_dir)?;
fs::write(&devices_path, serde_json::to_string_pretty(&devices)?)?;
// Commit the update.
let status = crate::helpers::git_command(
&root,
&["add", ".relicario/devices.json"],
)
.status()?;
if !status.success() {
anyhow::bail!("git add .relicario/devices.json failed");
}
let msg = format!("device: register {}", name);
let status = crate::helpers::git_command(&root, &["commit", "-m", &msg])
.status()?;
if !status.success() {
anyhow::bail!("git commit failed");
}
eprintln!("Device '{}' registered.", name);
eprintln!("Signing public key:");
eprintln!(" {}", signing_pub);
if gitea_key_id != 0 {
eprintln!("Gitea deploy key ID: {}", gitea_key_id);
}
Ok(())
}
DeviceAction::Revoke { name } => {
// Guard: refuse to revoke the currently active device (would lock
// the user out). They must add another device first.
if let Some(current) = crate::device::current_device()? {
if current == name {
anyhow::bail!(
"cannot revoke the current device '{}' — you would lose \
push access. Register another device first.",
name
);
}
}
// Load devices.json.
let mut devices: Vec<DeviceEntry> = fs::read(&devices_path)
.ok()
.and_then(|b| serde_json::from_slice(&b).ok())
.unwrap_or_default();
let device = devices
.iter()
.find(|d| d.name == name)
.ok_or_else(|| anyhow::anyhow!("device '{}' not found", name))?
.clone();
// Remove from devices.json.
devices.retain(|d| d.name != name);
fs::write(&devices_path, serde_json::to_string_pretty(&devices)?)?;
// Append to revoked.json.
let revoked_path = relicario_dir.join("revoked.json");
let mut revoked: Vec<RevokedEntry> = fs::read(&revoked_path)
.ok()
.and_then(|b| serde_json::from_slice(&b).ok())
.unwrap_or_default();
let revoked_by = crate::device::current_device()?
.unwrap_or_else(|| "unknown".to_string());
revoked.push(RevokedEntry {
name: name.clone(),
public_key: device.public_key.clone(),
revoked_at: relicario_core::now_unix(),
revoked_by,
});
fs::write(&revoked_path, serde_json::to_string_pretty(&revoked)?)?;
// Delete deploy key from Gitea (best-effort — don't fail if it
// was already deleted or the config is missing).
if let Ok(key_id) = crate::device::load_gitea_key_id(&name) {
if key_id != 0 {
// Build client from env vars only (no flags in revoke).
match load_gitea_client(None, None, None, None) {
Ok(client) => {
if let Err(e) = client.delete_deploy_key(key_id) {
eprintln!(
"warning: failed to delete Gitea deploy key {}: {}",
key_id, e
);
} else {
eprintln!("Deleted Gitea deploy key {}.", key_id);
}
}
Err(_) => {
eprintln!(
"warning: Gitea env vars not set — deploy key {} \
not deleted from Gitea.",
key_id
);
}
}
}
}
// Commit devices.json + revoked.json.
let mut paths = vec![".relicario/devices.json"];
if revoked_path.exists() {
paths.push(".relicario/revoked.json");
}
let mut add_args = vec!["add"];
add_args.extend_from_slice(&paths);
let status = crate::helpers::git_command(&root, &add_args).status()?;
if !status.success() {
anyhow::bail!("git add failed");
}
let msg = format!("device: revoke {}", name);
let status = crate::helpers::git_command(&root, &["commit", "-m", &msg])
.status()?;
if !status.success() {
anyhow::bail!("git commit failed");
}
eprintln!("Device '{}' revoked.", name);
Ok(())
}
DeviceAction::List => {
let devices: Vec<DeviceEntry> = fs::read(&devices_path)
.ok()
.and_then(|b| serde_json::from_slice(&b).ok())
.unwrap_or_default();
let current = crate::device::current_device()?.unwrap_or_default();
if devices.is_empty() {
println!("No registered devices.");
return Ok(());
}
println!("{:<20} {:<20} {}", "NAME", "ADDED", "SIGNING KEY (prefix)");
println!("{}", "-".repeat(72));
for d in &devices {
let marker = if d.name == current { " *" } else { "" };
let added = crate::helpers::iso8601(d.added_at);
// Show only the first 40 chars of the public key line for readability.
let key_prefix: String = d.public_key.chars().take(40).collect();
println!("{:<20} {:<20} {}{}",
d.name, added, key_prefix, marker);
}
if !current.is_empty() {
println!("\n* = current device");
}
Ok(())
}
}
}