The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
//! On-disk (and OS-keychain-backed) persistence for wallet setup state.
use std::fs;
#[cfg(unix)]
use std::fs::File;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};
use log::{debug, warn};
use once_cell::sync::Lazy;
use parking_lot::Mutex;
use tempfile::NamedTempFile;
use crate::config::Config;
use super::types::StoredWalletState;
use super::validate_setup;
use super::WalletSetupParams;
pub(super) const LOG_PREFIX: &str = "[wallet]";
const WALLET_STATE_FILENAME: &str = "wallet-state.json";
/// Keychain key for the encrypted mnemonic blob (user_id is added by the keyring module).
const KEYCHAIN_MNEMONIC_KEY: &str = "wallet.mnemonic";
pub(super) static WALLET_STATE_FILE_LOCK: Lazy<Mutex<()>> = Lazy::new(|| Mutex::new(()));
/// Derive a stable keychain user-id from the workspace directory path.
///
/// Uses the same strategy as credentials/profiles.rs: take the last meaningful
/// path component of the workspace directory.
fn wallet_user_id(config: &Config) -> String {
// workspace_dir is typically `{openhuman_dir}/workspace` — take the parent
// (the user's openhuman dir) and then the last component.
let candidate = config
.workspace_dir
.parent()
.and_then(|p| p.file_name())
.and_then(|s| s.to_str())
.filter(|s| !s.is_empty());
if let Some(id) = candidate {
return id.to_string();
}
// Fallback: FNV-1a hash of the workspace path.
let path_str = config.workspace_dir.to_string_lossy();
let mut hash: u64 = 14695981039346656037u64;
for b in path_str.as_bytes() {
hash ^= u64::from(*b);
hash = hash.wrapping_mul(1099511628211u64);
}
format!("wallet-path-{hash:016x}")
}
/// Load the encrypted mnemonic from the OS keychain if available.
///
/// Returns `None` if the keychain is unavailable or the entry does not exist.
pub(super) fn keychain_load_mnemonic(config: &Config) -> Option<String> {
let policy = crate::security::keyring_consent::policy::check_secret_access();
if policy != crate::security::keyring_consent::PolicyDecision::Proceed
|| !crate::security::secret_storage::is_available()
{
log::debug!("{LOG_PREFIX} keychain unavailable or consent pending, skipping mnemonic load policy={policy:?}");
return None;
}
let user_id = wallet_user_id(config);
match crate::security::secret_storage::get(&user_id, KEYCHAIN_MNEMONIC_KEY) {
Ok(Some(val)) => {
log::debug!("{LOG_PREFIX} keychain mnemonic loaded user_id={user_id}");
Some(val)
}
Ok(None) => {
log::debug!("{LOG_PREFIX} keychain mnemonic not found user_id={user_id}");
None
}
Err(e) => {
log::warn!("{LOG_PREFIX} keychain mnemonic load error user_id={user_id}: {e}");
None
}
}
}
/// Store the encrypted mnemonic in the OS keychain.
///
/// Returns `true` if the write succeeded.
fn keychain_save_mnemonic(config: &Config, encrypted_mnemonic: &str) -> bool {
let policy = crate::security::keyring_consent::policy::check_secret_access();
if policy != crate::security::keyring_consent::PolicyDecision::Proceed
|| !crate::security::secret_storage::is_available()
{
log::debug!("{LOG_PREFIX} keychain unavailable or consent pending, skipping mnemonic save policy={policy:?}");
return false;
}
let user_id = wallet_user_id(config);
match crate::security::secret_storage::set(&user_id, KEYCHAIN_MNEMONIC_KEY, encrypted_mnemonic)
{
Ok(()) => {
log::debug!("{LOG_PREFIX} keychain mnemonic saved user_id={user_id}");
true
}
Err(e) => {
log::warn!("{LOG_PREFIX} keychain mnemonic save error user_id={user_id}: {e}");
false
}
}
}
/// Whether a keychain entry exists for the encrypted mnemonic.
pub(super) fn keychain_has_mnemonic(config: &Config) -> bool {
let policy = crate::security::keyring_consent::policy::check_secret_access();
if policy != crate::security::keyring_consent::PolicyDecision::Proceed
|| !crate::security::secret_storage::is_available()
{
return false;
}
let user_id = wallet_user_id(config);
matches!(
crate::security::secret_storage::get(&user_id, KEYCHAIN_MNEMONIC_KEY),
Ok(Some(_))
)
}
pub(super) fn wallet_state_path(config: &Config) -> PathBuf {
config
.workspace_dir
.join("state")
.join(WALLET_STATE_FILENAME)
}
fn ensure_wallet_state_dir(path: &Path) -> Result<(), String> {
if let Some(parent) = path.parent() {
fs::create_dir_all(parent).map_err(|e| {
format!(
"failed to create workspace state dir {}: {e}",
parent.display()
)
})?;
}
Ok(())
}
fn corrupted_wallet_state_path(path: &Path) -> PathBuf {
let timestamp = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|value| value.as_millis())
.unwrap_or(0);
path.with_extension(format!("json.corrupted.{timestamp}"))
}
fn quarantine_corrupted_wallet_state(path: &Path, reason: &str) {
let quarantine_path = corrupted_wallet_state_path(path);
warn!(
"{LOG_PREFIX} quarantining corrupted wallet state {} -> {} ({reason})",
path.display(),
quarantine_path.display()
);
if let Err(rename_error) = fs::rename(path, &quarantine_path) {
warn!(
"{LOG_PREFIX} failed to quarantine {} via rename: {}",
path.display(),
rename_error
);
if let Err(remove_error) = fs::remove_file(path) {
warn!(
"{LOG_PREFIX} failed to remove unreadable wallet state {}: {}",
path.display(),
remove_error
);
}
}
}
// Deliberately local, not on the storage port (for now): this file is paired
// with the OS keychain entry for the encrypted mnemonic and falls back to
// holding that secret itself when no keychain exists. Splitting the metadata
// onto a shared backend while the key material stays on one machine would
// leave a wallet that exists in one place and not the other. It moves with
// the secrets work (`SecretStore`), not as a plain document. Allowlisted in
// `scripts/ci/check-storage-bypass.mjs`.
pub(super) fn load_stored_wallet_state_unlocked(
config: &Config,
) -> Result<Option<StoredWalletState>, String> {
let path = wallet_state_path(config);
// ── Step 1: Try to resolve the encrypted mnemonic from the OS keychain ──
// If the keychain has the entry, we don't need the JSON field at all.
// The JSON file may or may not exist (it still holds non-secret metadata).
let keychain_mnemonic = keychain_load_mnemonic(config);
// ── Step 2: Load state from JSON (metadata, accounts, flags) ─────────────
if !path.exists() {
if keychain_mnemonic.is_some() {
// Keychain has the mnemonic but there is no wallet-state.json.
// This shouldn't happen in practice (both are written together),
// but we log it and return None so the user re-setups the wallet.
warn!(
"{LOG_PREFIX} keychain has mnemonic but no wallet-state.json at {}; \
treating as not configured",
path.display()
);
}
return Ok(None);
}
let raw = match fs::read_to_string(&path) {
Ok(raw) => raw,
Err(error) => {
warn!(
"{LOG_PREFIX} failed to read {}; falling back to defaults: {}",
path.display(),
error
);
quarantine_corrupted_wallet_state(&path, &error.to_string());
return Ok(None);
}
};
let mut state = match serde_json::from_str::<StoredWalletState>(&raw) {
Ok(state) => state,
Err(error) => {
warn!(
"{LOG_PREFIX} failed to parse {}; falling back to defaults: {}",
path.display(),
error
);
quarantine_corrupted_wallet_state(&path, &error.to_string());
return Ok(None);
}
};
// ── Step 3: Merge keychain mnemonic with JSON state ───────────────────────
// Priority: keychain > JSON field.
let needs_keychain_migration =
keychain_mnemonic.is_none() && state.encrypted_mnemonic.is_some();
if let Some(mnemonic) = keychain_mnemonic {
// Keychain is authoritative. If the JSON still has the field, clear it.
if state.encrypted_mnemonic.is_some() {
debug!(
"{LOG_PREFIX} load: clearing encrypted_mnemonic from JSON (already in keychain)"
);
state.encrypted_mnemonic = None;
// Rewrite the JSON without the secret field.
if let Err(e) = save_stored_wallet_state_unlocked(config, &state) {
warn!(
"{LOG_PREFIX} load: failed to rewrite wallet-state.json after keychain migration: {e}"
);
}
}
state.encrypted_mnemonic = Some(mnemonic);
} else if needs_keychain_migration {
// The encrypted mnemonic is in the JSON. Promote it to keychain if available.
if let Some(ref enc_mnemonic) = state.encrypted_mnemonic.clone() {
debug!("{LOG_PREFIX} load: promoting encrypted_mnemonic from JSON to keychain");
if keychain_save_mnemonic(config, enc_mnemonic) {
// Successfully saved to keychain — clear from JSON.
state.encrypted_mnemonic = None;
if let Err(e) = save_stored_wallet_state_unlocked(config, &state) {
warn!(
"{LOG_PREFIX} load: failed to rewrite wallet-state.json after mnemonic promotion: {e}"
);
}
// Restore the value in-memory so validation passes.
state.encrypted_mnemonic = Some(enc_mnemonic.clone());
}
}
}
// ── Step 4: Validate (allows encrypted_mnemonic to be None when in keychain) ──
// Build validation params treating keychain-held mnemonic as present.
// Re-probe the keychain here so that headless / CI environments where
// keychain_load_mnemonic returned None at the top of this function (e.g.
// because the keychain entry was written by a concurrent task and was not
// yet visible to the earlier read) get one more chance to find the secret.
let effective_mnemonic = state.encrypted_mnemonic.clone().or_else(|| {
let reprobe = keychain_load_mnemonic(config);
if reprobe.is_some() {
debug!(
"{LOG_PREFIX} load: re-probe found mnemonic in keychain \
that was absent on initial probe; merging into state"
);
}
reprobe
});
// Propagate whatever was found (initial probe, migration, or re-probe) back
// into `state` so that callers (reveal_recovery_phrase, secret_material)
// always receive a complete state when the mnemonic is accessible.
if state.encrypted_mnemonic.is_none() {
if let Some(ref m) = effective_mnemonic {
debug!("{LOG_PREFIX} load: setting encrypted_mnemonic from effective_mnemonic");
state.encrypted_mnemonic = Some(m.clone());
}
}
let validation_params = WalletSetupParams {
consent_granted: state.consent_granted,
source: state.source,
mnemonic_word_count: state.mnemonic_word_count,
encrypted_mnemonic: effective_mnemonic,
accounts: state.accounts.clone(),
// force is irrelevant for validation; always false here.
force: false,
};
if let Err(validation_error) = validate_setup(&validation_params) {
warn!(
"{LOG_PREFIX} stored wallet state at {} failed validation: {validation_error}",
path.display()
);
quarantine_corrupted_wallet_state(&path, &validation_error);
return Ok(None);
}
Ok(Some(state))
}
fn sync_parent_dir(path: &Path) -> Result<(), String> {
#[cfg(unix)]
if let Some(parent) = path.parent() {
File::open(parent)
.and_then(|dir| dir.sync_all())
.map_err(|e| format!("failed to sync directory {}: {e}", parent.display()))?;
}
#[cfg(not(unix))]
{
let _ = path;
}
Ok(())
}
pub(super) fn save_stored_wallet_state_unlocked(
config: &Config,
state: &StoredWalletState,
) -> Result<(), String> {
let path = wallet_state_path(config);
ensure_wallet_state_dir(&path)?;
// When the OS keychain is available, store the encrypted mnemonic there and
// write the JSON without the secret field. This is the preferred path on
// macOS / Windows / Linux-with-Secret-Service.
let mut state_for_json = state.clone();
if let Some(ref enc_mnemonic) = state.encrypted_mnemonic {
if keychain_save_mnemonic(config, enc_mnemonic) {
debug!("{LOG_PREFIX} save: encrypted_mnemonic saved to keychain; stripping from JSON");
state_for_json.encrypted_mnemonic = None;
} else {
debug!("{LOG_PREFIX} save: keychain unavailable; keeping encrypted_mnemonic in JSON");
}
}
let payload = serde_json::to_string_pretty(&state_for_json)
.map_err(|e| format!("failed to serialize wallet state: {e}"))?;
let parent = path
.parent()
.ok_or_else(|| format!("failed to resolve parent dir for {}", path.display()))?;
let mut temp_file = NamedTempFile::new_in(parent)
.map_err(|e| format!("failed to create temp file in {}: {e}", parent.display()))?;
temp_file.write_all(payload.as_bytes()).map_err(|e| {
format!(
"failed to write temp wallet state for {}: {e}",
path.display()
)
})?;
temp_file.as_file_mut().sync_all().map_err(|e| {
format!(
"failed to sync temp wallet state for {}: {e}",
path.display()
)
})?;
sync_parent_dir(&path)?;
temp_file.persist(&path).map_err(|e| {
format!(
"failed to persist wallet state {}: {}",
path.display(),
e.error
)
})?;
sync_parent_dir(&path)?;
Ok(())
}
pub(super) fn current_time_ms() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|value| value.as_millis() as u64)
.unwrap_or(0)
}
pub(super) fn to_status(config: &Config, state: Option<StoredWalletState>) -> super::WalletStatus {
match state {
Some(state) => {
// A mnemonic is "stored" if it's either in the JSON field (headless path)
// or has been moved to the OS keychain (preferred path).
let secret_in_json = state
.encrypted_mnemonic
.as_ref()
.map(|v| !v.trim().is_empty())
.unwrap_or(false);
let secret_stored = secret_in_json || keychain_has_mnemonic(config);
super::WalletStatus {
configured: true,
onboarding_completed: state.consent_granted && !state.accounts.is_empty(),
consent_granted: state.consent_granted,
secret_stored,
source: Some(state.source),
mnemonic_word_count: Some(state.mnemonic_word_count),
accounts: state.accounts,
updated_at_ms: Some(state.updated_at_ms),
}
}
None => super::WalletStatus {
configured: false,
onboarding_completed: false,
consent_granted: false,
secret_stored: false,
source: None,
mnemonic_word_count: None,
accounts: Vec::new(),
updated_at_ms: None,
},
}
}