diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e65157705a..9e7e7dad5b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -574,14 +574,43 @@ jobs: backend-integration: name: Backend Integration (relay e2e) runs-on: ubuntu-latest - timeout-minutes: 20 + timeout-minutes: 35 needs: [changes, desktop-e2e-relay] - if: github.event_name == 'push' || needs.changes.outputs.rust == 'true' + if: github.event_name == 'push' || needs.changes.outputs.rust == 'true' || needs.changes.outputs.desktop-rust == 'true' permissions: contents: read steps: - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 - uses: cashapp/activate-hermit@cea9af7913204a965fd488637a8d1811bba2e616 # v1 + - uses: Swatinem/rust-cache@e18b497796c12c097a38f9edb9d0641fb99eee32 # v2 + with: + workspaces: desktop/src-tauri + save-if: ${{ github.event_name != 'pull_request' }} + - name: Install Tauri dependencies (Linux) + env: + DEBIAN_FRONTEND: noninteractive + run: | + sudo apt-get update \ + -o Acquire::Retries=3 \ + -o Acquire::http::Timeout=30 \ + -o Acquire::https::Timeout=30 + sudo apt-get install -y --no-install-recommends \ + -o Acquire::Retries=3 \ + -o Acquire::http::Timeout=30 \ + -o Acquire::https::Timeout=30 \ + -o DPkg::Lock::Timeout=120 \ + build-essential \ + curl \ + file \ + libasound2-dev \ + libayatana-appindicator3-dev \ + libgtk-3-dev \ + librsvg2-dev \ + libssl-dev \ + libwebkit2gtk-4.1-dev \ + libxdo-dev \ + patchelf \ + wget - name: Install cargo-nextest uses: taiki-e/install-action@0fd46367812ee04360509b4169d9f659d6892bb2 # v2.79.15 with: @@ -684,6 +713,16 @@ jobs: done cat /tmp/buzz-relay.log exit 1 + - name: Desktop relay acceptance gate + # NIP-IA owner-consent proof: in-crate ignored tests under + # commands/identity_archive::relay_acceptance, exercised against the + # production build_router/POST /events path here (not in unit-test gate, + # which has no infra). Missing/unreachable infra panics — no skip, no + # silent Ok. See Plan v9 Amendment 6 for the fixture and assertion spec. + run: just desktop-tauri-relay-acceptance + env: + DATABASE_URL: postgres://buzz:${{ env.BUZZ_TEST_POSTGRES_PASSWORD }}@localhost:5432/buzz + RELAY_API_URL: http://localhost:3000 - name: Invite security tests run: | cargo nextest run \ diff --git a/Justfile b/Justfile index 0a43249d5f..7509c5099c 100644 --- a/Justfile +++ b/Justfile @@ -206,6 +206,13 @@ desktop-tauri-check: _ensure-sidecar-stubs desktop-tauri-test: _ensure-sidecar-stubs cd desktop/src-tauri && cargo test --workspace +# Run the in-crate relay acceptance gate against a live relay + Postgres. +# Requires DATABASE_URL and RELAY_API_URL in the environment. +# CI mounts this step inside the Backend Integration (relay e2e) job which +# already provisions both; locally you can use the same docker-compose setup. +desktop-tauri-relay-acceptance: _ensure-sidecar-stubs + cargo nextest run --manifest-path desktop/src-tauri/Cargo.toml -p buzz-desktop --lib -E 'test(/relay_acceptance::/)' --run-ignored ignored-only + # Run the native terminal latency gate explicitly on a known-idle host. # This is intentionally excluded from shared CI: scheduler contention makes a # wall-clock assertion flaky, and the release profile is the shipped shape. diff --git a/desktop/playwright.config.ts b/desktop/playwright.config.ts index c1ea0e061b..fee50cab14 100644 --- a/desktop/playwright.config.ts +++ b/desktop/playwright.config.ts @@ -141,6 +141,7 @@ export default defineConfig({ "**/huddle-transcription.spec.ts", "**/agent-numeric-tuning.spec.ts", "**/needs-restart-screenshots.spec.ts", + "**/agent-instances-sheet.spec.ts", ], use: { ...devices["Desktop Chrome"], diff --git a/desktop/src-tauri/Cargo.lock b/desktop/src-tauri/Cargo.lock index fbaa547a03..fe625b9cba 100644 --- a/desktop/src-tauri/Cargo.lock +++ b/desktop/src-tauri/Cargo.lock @@ -1137,6 +1137,7 @@ dependencies = [ "tauri-utils", "tempfile", "tokio", + "tokio-postgres", "tokio-tungstenite 0.29.0", "tokio-util", "toml 0.8.2", @@ -2779,6 +2780,12 @@ version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "af9673d8203fcb076b19dfd17e38b3d4ae9f44959416ea532ce72415a6020365" +[[package]] +name = "fallible-iterator" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4443176a9f2c162692bd3d352d745ef9413eec5782a80d8fd6f8a1ac692a07f7" + [[package]] name = "fallible-iterator" version = "0.3.0" @@ -5088,6 +5095,16 @@ dependencies = [ "syn 2.0.118", ] +[[package]] +name = "md-5" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69b6441f590336821bb897fb28fc622898ccceb1d6cea3fde5ea86b090c4de98" +dependencies = [ + "cfg-if 1.0.4", + "digest 0.11.3", +] + [[package]] name = "md5" version = "0.8.1" @@ -7573,6 +7590,35 @@ dependencies = [ "syn 2.0.118", ] +[[package]] +name = "postgres-protocol" +version = "0.6.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08808e3c483c46e999108051c78334f473d5adb59d78bb80a1268c7e6aa6c514" +dependencies = [ + "base64 0.22.1", + "byteorder", + "bytes", + "fallible-iterator 0.2.0", + "hmac 0.13.0", + "md-5", + "memchr", + "rand 0.10.2", + "sha2 0.11.0", + "stringprep", +] + +[[package]] +name = "postgres-types" +version = "0.2.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "851ca9db4932932d69f3ea811b1abe63087a0f740a47692619dd40d4899b68be" +dependencies = [ + "bytes", + "fallible-iterator 0.2.0", + "postgres-protocol", +] + [[package]] name = "potential_utf" version = "0.1.5" @@ -8649,7 +8695,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "165ca6e57b20e1351573e3729b958bc62f0e48025386970b6e4d29e7a7e71f3f" dependencies = [ "bitflags 2.13.0", - "fallible-iterator", + "fallible-iterator 0.3.0", "fallible-streaming-iterator", "hashlink", "libsqlite3-sys", @@ -9856,6 +9902,17 @@ dependencies = [ "quote", ] +[[package]] +name = "stringprep" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b4df3d392d81bd458a8a621b8bffbd2302a12ffe288a9d931670948749463b1" +dependencies = [ + "unicode-bidi", + "unicode-normalization", + "unicode-properties", +] + [[package]] name = "strip-ansi-escapes" version = "0.2.1" @@ -10992,6 +11049,32 @@ dependencies = [ "tokio", ] +[[package]] +name = "tokio-postgres" +version = "0.7.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a528f7d280f6d5b9cd149635c8705b0dd049754bc67d81d31fa25169a93809d3" +dependencies = [ + "async-trait", + "byteorder", + "bytes", + "fallible-iterator 0.2.0", + "futures-channel", + "futures-util", + "log", + "parking_lot", + "percent-encoding", + "phf 0.13.1", + "pin-project-lite", + "postgres-protocol", + "postgres-types", + "rand 0.10.2", + "socket2", + "tokio", + "tokio-util", + "whoami", +] + [[package]] name = "tokio-retry" version = "0.3.2" @@ -11624,6 +11707,12 @@ version = "2.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dbc4bc3a9f746d862c45cb89d705aa10f187bb96c76001afab07a0d35ce60142" +[[package]] +name = "unicode-bidi" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5" + [[package]] name = "unicode-ident" version = "1.0.24" @@ -11648,6 +11737,12 @@ dependencies = [ "smallvec", ] +[[package]] +name = "unicode-properties" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7df058c713841ad818f1dc5d3fd88063241cc61f49f5fbea4b951e8cf5a8d71d" + [[package]] name = "unicode-segmentation" version = "1.13.3" diff --git a/desktop/src-tauri/Cargo.toml b/desktop/src-tauri/Cargo.toml index bbf245e29a..7e1133c774 100644 --- a/desktop/src-tauri/Cargo.toml +++ b/desktop/src-tauri/Cargo.toml @@ -154,3 +154,6 @@ tokio = { version = "1", features = ["test-util"] } # The relay's media validation, so the snapshot-sharing tests can prove the # full export → sanitize → relay-accept → import contract end to end. buzz_media_pkg = { package = "buzz-media", path = "../../crates/buzz-media" } +# Direct Postgres access for relay-acceptance tests that assert persisted +# consent_path rows (see commands/identity_archive relay_acceptance module). +tokio-postgres = { version = "0.7", features = [] } diff --git a/desktop/src-tauri/src/app_state.rs b/desktop/src-tauri/src/app_state.rs index fc90e6ab14..9cdfa81612 100644 --- a/desktop/src-tauri/src/app_state.rs +++ b/desktop/src-tauri/src/app_state.rs @@ -1,8 +1,7 @@ use std::{ collections::HashMap, - io::Write, sync::{ - atomic::{AtomicBool, AtomicU16, AtomicU8}, + atomic::{AtomicBool, AtomicU16, AtomicU64, AtomicU8, Ordering}, Arc, Mutex, }, }; @@ -118,6 +117,17 @@ pub struct AppState { /// itself owns direct QUIC/iroh connection establishment. #[cfg(feature = "mesh-llm")] pub mesh_coordinator: AsyncMutex>, + // ── Workspace-epoch seqlock ─────────────────────────────────────────────── + // + // Epoch is even when stable, odd while a workspace transition is in + // progress. Readers capture (keys, relay_url_override) by sampling the + // epoch twice around the two field reads; they accept the pair only when + // both samples are identical AND even. This prevents consumers from + // observing an old actor with a new relay URL (or vice versa) during the + // brief overlap of `apply_workspace`. See [`WorkspaceEpochWriteGuard`]. + pub(crate) workspace_epoch: AtomicU64, + pub(crate) workspace_write: Mutex<()>, + /// `(creator_pubkey_hex, channel_id)` pairs for channels the *named* /// identity created via `create_channel` and has not yet observed its own /// kind:39002 membership entry for. The relay provisions that entry @@ -233,6 +243,8 @@ pub fn build_app_state() -> AppState { #[cfg(feature = "mesh-llm")] mesh_coordinator: AsyncMutex::new(None), pending_owned_channels: Mutex::new(std::collections::HashSet::new()), + workspace_epoch: AtomicU64::new(0), + workspace_write: Mutex::new(()), } } @@ -338,8 +350,84 @@ impl AppState { }; crate::huddle::state::emit_huddle_state(&app, &snapshot); } + + /// Acquire the serialized workspace-write guard, transitioning the epoch + /// even → odd. `Drop` restores even on every exit path (SeqCst throughout). + /// Must be held outermost — never hold `keys` / `relay_url_override` first. + pub fn begin_workspace_write(&self) -> Result, String> { + let guard = self + .workspace_write + .lock() + .map_err(|e| format!("workspace write mutex poisoned: {e}"))?; + // Transition even → odd: we are about to start mutating. + let prev = self.workspace_epoch.fetch_add(1, Ordering::SeqCst); + debug_assert!( + prev.is_multiple_of(2), + "workspace_epoch should be even before write" + ); + Ok(WorkspaceEpochWriteGuard { + epoch: &self.workspace_epoch, + _guard: guard, + }) + } + + /// Capture an atomic `(keys, relay_url_override)` pair via the seqlock + /// protocol. Returns `Err` after `max_retries` exhausted attempts, or + /// immediately when the identity is in recovery mode (`identity_lost` or + /// `keyring_locked`) — the same gate enforced by `signing_keys()`. + pub fn capture_archive_scope(&self, max_retries: u32) -> Result { + for _ in 0..=max_retries { + // Sample epoch before reads. + let epoch_before = self.workspace_epoch.load(Ordering::SeqCst); + // Odd → writer is mid-transition; yield and retry. + if !epoch_before.is_multiple_of(2) { + std::thread::yield_now(); + continue; + } + + // Check recovery flags WITHIN the epoch window so the check and + // the key clone are consistent with a single generation. + if self.identity_lost.load(std::sync::atomic::Ordering::SeqCst) + || self + .keyring_locked + .load(std::sync::atomic::Ordering::SeqCst) + { + return Err("identity is in recovery mode; event signing is disabled \ + until the identity is restored and Buzz is relaunched" + .to_string()); + } + + let keys = self + .keys + .lock() + .map_err(|e| format!("keys mutex poisoned: {e}"))? + .clone(); + let relay_url_override = self + .relay_url_override + .lock() + .map_err(|e| format!("relay_url_override mutex poisoned: {e}"))? + .clone(); + + // Sample epoch after reads. + let epoch_after = self.workspace_epoch.load(Ordering::SeqCst); + // Accept only when unchanged and even — both fields from one generation. + if epoch_after == epoch_before && epoch_after.is_multiple_of(2) { + let actor = keys.public_key().to_hex(); + return Ok(ArchiveScope { + keys, + actor, + relay_url_override, + workspace_epoch: epoch_after, + }); + } + // Epoch changed mid-read: retry. + } + Err("workspace is switching — please retry the archive operation in a moment".to_string()) + } } +pub use crate::workspace_epoch::{ArchiveScope, WorkspaceEpochWriteGuard}; + /// Resolve the user's identity key from the app data directory and wire /// the resulting [`RecoveryState`] into `AppState`. /// @@ -370,21 +458,23 @@ pub fn resolve_persisted_identity(app: &AppHandle, state: &AppState) -> Result<( std::fs::create_dir_all(&data_dir).map_err(|e| format!("create app data dir: {e}"))?; let resolved = load_or_create_identity(&data_dir)?; - // Write keys and storage before setting the recovery flags (Release) so - // any thread that reads a flag as false with Acquire sees consistent data. + // Write keys, storage, AND recovery flags inside the same epoch guard so + // they are co-generational: a `capture_archive_scope` that reads an even + // epoch after the guard exits sees a consistent (keys, flags) tuple. { + let _epoch_guard = state.begin_workspace_write()?; let mut active_keys = state.keys.lock().map_err(|e| e.to_string())?; *active_keys = resolved.keys; state.set_identity_storage(resolved.storage); + state.identity_lost.store( + resolved.recovery == RecoveryState::Lost, + std::sync::atomic::Ordering::SeqCst, + ); + state.keyring_locked.store( + resolved.recovery == RecoveryState::KeyringLocked, + std::sync::atomic::Ordering::SeqCst, + ); } - state.identity_lost.store( - resolved.recovery == RecoveryState::Lost, - std::sync::atomic::Ordering::Release, - ); - state.keyring_locked.store( - resolved.recovery == RecoveryState::KeyringLocked, - std::sync::atomic::Ordering::Release, - ); Ok(()) } @@ -899,181 +989,24 @@ pub(crate) fn persist_imported_identity( persist_imported_identity_impl(store, keys, legacy_path, data_dir) } -/// Path of the migration-completed marker within `data_dir`. -fn migration_marker_path(data_dir: &std::path::Path) -> std::path::PathBuf { - data_dir.join(keyring_config::migration_marker_name( - keyring_service(), - MIGRATION_MARKER_NAME, - )) -} - -/// Atomically write (and fsync) the migration-completed marker. The content is -/// irrelevant — only the file's durable existence is the signal — so a single -/// byte keeps it minimal. Atomicity + fsync guarantee that once this returns -/// `Ok`, the marker survives a crash, which is what makes deleting the legacy -/// file afterward safe. -fn write_migration_marker(marker_path: &std::path::Path) -> Result<(), String> { - use atomic_write_file::AtomicWriteFile; - - let mut file = AtomicWriteFile::open(marker_path) - .map_err(|e| format!("open migration marker for atomic write: {e}"))?; - file.write_all(b"1") - .map_err(|e| format!("write migration marker: {e}"))?; - file.commit() - .map_err(|e| format!("commit migration marker: {e}")) -} - -/// Generate a fresh identity, persist it through the store, return it. -/// -/// On a keyring-backed persist no file is written, so a later -/// keyring-Unreachable boot would see "no file, no marker" (identical to a -/// fresh install) and silently rotate the identity. Writing the marker here -/// makes that boot fail closed. If the marker write fails, fall back to the -/// `0o600` file so the key is never keyring-only-without-marker. -fn generate_and_persist( - store: &impl IdentityKeyStore, - legacy_path: &std::path::Path, - data_dir: &std::path::Path, -) -> Result<(Keys, IdentityStorage), String> { - let keys = Keys::generate(); - let storage = store_key_preferring_keyring(store, &keys, legacy_path)?; - if storage == IdentityStorage::SystemKeyring { - let marker_path = migration_marker_path(data_dir); - if let Err(e) = write_migration_marker(&marker_path) { - eprintln!( - "buzz-desktop: stored identity in keyring but failed to write migration marker \ - ({e}); saving identity.key fallback so the key is not stranded" - ); - save_key_file(legacy_path, &keys)?; - } - } - eprintln!( - "buzz-desktop: generated and saved identity pubkey {}", - keys.public_key().to_hex() - ); - Ok((keys, storage)) -} - -/// Persist `keys` through the store, silently falling back to the `0o600` file -/// when the keyring write fails on an availability error. Reports which backend -/// held the key (no verify/marker/delete — those belong to callers that own the -/// full migration contract) so the caller can write the migration marker only on -/// keyring success. -fn store_key_preferring_keyring( - store: &impl IdentityKeyStore, - keys: &Keys, - legacy_path: &std::path::Path, -) -> Result { - let nsec = keys - .secret_key() - .to_bech32() - .map_err(|e| format!("encode nsec: {e}"))?; - match store.store(IDENTITY_KEY_NAME, &nsec) { - Ok(()) => Ok(IdentityStorage::SystemKeyring), - Err(keyring_err) => { - eprintln!("buzz-desktop: keyring write failed ({keyring_err}), using file fallback"); - save_key_file(legacy_path, keys)?; - Ok(IdentityStorage::LocalFile) - } - } -} - -/// Ensure the migration marker exists (writing it if absent), then remove the -/// leftover `identity.key`. Crash-safe ordering: the marker is written and -/// fsync-committed before the file is deleted, so a crash between the two -/// leaves the marker on disk and the file intact — the invariant "keyring-only -/// implies marker exists" is preserved. If the marker write fails, the file is -/// kept so a later keyring-unreachable boot can use it as a fallback. -fn ensure_marker_then_cleanup(data_dir: &std::path::Path, legacy_path: &std::path::Path) { - let marker_path = migration_marker_path(data_dir); - let marker_ok = marker_path.exists() - || write_migration_marker(&marker_path) - .map_err(|e| { - eprintln!( - "buzz-desktop: keyring present but marker missing; \ - failed to write marker ({e}), keeping identity.key" - ); - }) - .is_ok(); - if marker_ok { - cleanup_leftover_identity_file(legacy_path); - } -} - -/// Best-effort removal of a leftover `identity.key` once the keyring is the -/// authoritative store. Idempotent: a missing file is success. Logs but does -/// not error on failure — a delete failure must never block startup. -fn cleanup_leftover_identity_file(legacy_path: &std::path::Path) { - if !legacy_path.exists() { - return; - } - match std::fs::remove_file(legacy_path) { - Ok(()) => eprintln!("buzz-desktop: removed leftover identity.key (key is in keyring)"), - Err(e) => eprintln!("buzz-desktop: failed to remove leftover identity.key: {e}"), - } -} - -/// Quarantine a corrupt `identity.key` with a timestamp so prior backups are -/// never overwritten. -fn quarantine_corrupt_key(key_path: &std::path::Path, data_dir: &std::path::Path, error: &str) { - if !key_path.exists() { - return; - } - let ts = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map(|d| d.as_secs()) - .unwrap_or(0); - let bad_name = format!("identity.key.bad.{ts}"); - eprintln!("buzz-desktop: corrupt identity.key ({error}), quarantining to {bad_name}"); - let bad_path = data_dir.join(bad_name); - if std::fs::rename(key_path, &bad_path).is_err() { - let _ = std::fs::remove_file(key_path); - } -} - -fn load_key_file(path: &std::path::Path) -> Result { - let content = std::fs::read_to_string(path).map_err(|e| format!("read identity.key: {e}"))?; - let trimmed = content.trim(); - if trimmed.is_empty() { - return Err("empty identity.key".to_string()); - } - Keys::parse(trimmed).map_err(|e| format!("parse identity.key: {e}")) -} - -/// Atomically write the key to disk. Uses `atomic-write-file` which: -/// 1. Writes to a temp file in the same directory -/// 2. Calls fsync on the file -/// 3. Renames temp → target (atomic on POSIX, best-effort on Windows) -/// 4. Calls fsync on the parent directory -/// -/// On Unix, the file is created with mode 0600 (owner read/write only). -/// On Windows, default ACLs apply — the app data directory is already -/// per-user, so the key is not world-readable in practice. -pub(crate) fn save_key_file(path: &std::path::Path, keys: &Keys) -> Result<(), String> { - use atomic_write_file::AtomicWriteFile; - - let nsec = keys - .secret_key() - .to_bech32() - .map_err(|e| format!("encode nsec: {e}"))?; - - let mut file = AtomicWriteFile::open(path) - .map_err(|e| format!("open identity.key for atomic write: {e}"))?; - - // Set owner-only permissions before writing the secret. - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt; - file.set_permissions(std::fs::Permissions::from_mode(0o600)) - .map_err(|e| format!("set identity.key permissions: {e}"))?; - } - - file.write_all(nsec.as_bytes()) - .map_err(|e| format!("write identity.key: {e}"))?; - file.commit() - .map_err(|e| format!("commit identity.key: {e}")) -} +// File-system and OS-keyring helpers extracted to keep this module under the +// file-size ratchet. The child module has full access to this module's private +// items via `super::`. +#[path = "app_state_keyfile_ops.rs"] +mod keyfile_ops; +use keyfile_ops::{ + ensure_marker_then_cleanup, generate_and_persist, load_key_file, migration_marker_path, + quarantine_corrupt_key, write_migration_marker, +}; +// Used by app_state_tests.rs via `use super::*`. +#[cfg(test)] +use keyfile_ops::cleanup_leftover_identity_file; +pub(crate) use keyfile_ops::save_key_file; #[cfg(test)] #[path = "app_state_tests.rs"] mod tests; + +#[cfg(test)] +#[path = "app_state_epoch_tests.rs"] +mod epoch_tests; diff --git a/desktop/src-tauri/src/app_state_epoch_tests.rs b/desktop/src-tauri/src/app_state_epoch_tests.rs new file mode 100644 index 0000000000..f914789eb7 --- /dev/null +++ b/desktop/src-tauri/src/app_state_epoch_tests.rs @@ -0,0 +1,362 @@ +// Workspace-epoch seqlock protocol tests. +// Colocated as a separate test module to satisfy the file-size ratchet. +// See app_state_tests.rs for the preamble note on the false-green guard. + +// These tests pin the seqlock invariants using the production guard and capture +// helpers ONLY. Direct writes to `state.keys` or `state.relay_url_override` +// are intentionally absent here — using them would bypass the protocol under +// test and produce a false green. All writes go through `begin_workspace_write`. + +use super::*; + +/// Build a minimal AppState with known keys/override for epoch protocol tests. +/// Does NOT call `build_app_state` (avoids keyring/FS I/O). Only the fields +/// relevant to the seqlock protocol are initialized with non-default values; +/// everything else is zeroed/None to match `Default`. +fn make_epoch_test_state(keys: Keys) -> AppState { + use std::sync::atomic::{AtomicBool, AtomicU16, AtomicU8}; + AppState { + keys: Mutex::new(keys), + identity_storage: AtomicU8::new(0), + http_client: reqwest::Client::new(), + media_fetch_client: reqwest::Client::new(), + relay_url_override: Mutex::new(None), + managed_agent_restore_pending: AtomicBool::new(false), + managed_agent_profile_reconcile_enabled: AtomicBool::new(false), + shutdown_started: AtomicBool::new(false), + managed_agent_runtime_transition: Mutex::new(()), + managed_agents_store_lock: Mutex::new(()), + channel_templates_store_lock: Mutex::new(()), + managed_agent_processes: Mutex::new(std::collections::HashMap::new()), + huddle_state: Mutex::new(crate::huddle::HuddleState::default()), + huddle_audio: Default::default(), + app_handle: Mutex::new(None), + media_proxy_port: AtomicU16::new(0), + keyring_locked: AtomicBool::new(false), + identity_lost: AtomicBool::new(false), + identity_mutation: Mutex::new(()), + reset_failed: AtomicBool::new(false), + session_config_cache: Mutex::new(std::collections::HashMap::new()), + prevent_sleep: std::sync::Arc::new(Mutex::new( + crate::prevent_sleep::PreventSleepState::default(), + )), + #[cfg(feature = "mesh-llm")] + mesh_llm_runtime: tokio::sync::Mutex::new(None), + #[cfg(feature = "mesh-llm")] + mesh_recovery: crate::mesh_llm::MeshRecoveryState::default(), + #[cfg(feature = "mesh-llm")] + mesh_coordinator: tokio::sync::Mutex::new(None), + workspace_epoch: std::sync::atomic::AtomicU64::new(0), + workspace_write: Mutex::new(()), + pending_owned_channels: Mutex::new(std::collections::HashSet::new()), + } +} + +/// Epoch begins even and a fresh capture succeeds. +#[test] +fn epoch_protocol_initial_capture_succeeds() { + let keys = Keys::generate(); + let state = make_epoch_test_state(keys.clone()); + + let scope = state.capture_archive_scope(4).expect("initial capture"); + assert_eq!(scope.actor, keys.public_key().to_hex()); + assert!( + scope.workspace_epoch.is_multiple_of(2), + "captured epoch must be even" + ); +} + +/// While a writer guard is held the epoch is odd; capture retries and only +/// succeeds after the guard is dropped (restoring even). Additionally asserts +/// that a second acquisition of the writer guard blocks until the first drops +/// (writer exclusion). +#[test] +fn epoch_protocol_writer_exclusion_and_capture_retry() { + use std::sync::atomic::Ordering; + use std::sync::Arc; + + let keys = Keys::generate(); + let state = Arc::new(make_epoch_test_state(keys)); + + // Acquire write guard → epoch goes odd. + let guard = state.begin_workspace_write().expect("first write guard"); + let odd = state.workspace_epoch.load(Ordering::SeqCst); + assert_eq!(odd % 2, 1, "epoch must be odd while guard is held"); + + // With the guard held, mutate relay_url_override (simulating apply_workspace). + { + let mut ovr = state.relay_url_override.lock().unwrap(); + *ovr = Some("wss://test.relay".to_string()); + } + + // Spawn a thread that tries to acquire a second write guard; it must block + // until we drop the first one. + let state2 = Arc::clone(&state); + let handle = std::thread::spawn(move || { + // This blocks until the outer guard is dropped. + let _g = state2.begin_workspace_write().expect("second write guard"); + // Confirm the second guard restores to even after it drops. + }); + + // A capture attempt while odd must not return a mixed-gen scope. + // With max_retries=0 it fails fast rather than spinning. + let result = state.capture_archive_scope(0); + assert!( + result.is_err(), + "capture with max_retries=0 while epoch odd must fail" + ); + + // Drop the first guard → epoch goes even, unblocks the second thread, + // and subsequent captures succeed. + drop(guard); + let even = state.workspace_epoch.load(Ordering::SeqCst); + assert_eq!(even % 2, 0, "epoch must be even after guard drop"); + + // Wait for the second thread to finish. + handle.join().expect("second guard thread panicked"); + + // Now capture succeeds. + let scope = state + .capture_archive_scope(4) + .expect("capture after release"); + assert!(scope.workspace_epoch.is_multiple_of(2)); +} + +/// Drop (RAII restoration) on explicit drop and via `?` early return restores +/// an even epoch on every exit path. +#[test] +fn epoch_protocol_raii_always_restores_even() { + use std::sync::atomic::Ordering; + + let state = make_epoch_test_state(Keys::generate()); + + // Normal drop. + { + let _g = state.begin_workspace_write().expect("guard"); + assert_eq!( + state.workspace_epoch.load(Ordering::SeqCst) % 2, + 1, + "odd while held" + ); + } + assert_eq!( + state.workspace_epoch.load(Ordering::SeqCst) % 2, + 0, + "even after normal drop" + ); + + // Simulated early-return via a closure that acquires and immediately drops + // the guard when an error is returned. + let result: Result<(), String> = (|| { + let _g = state.begin_workspace_write()?; + // Return early before the closure completes. + return Err("early return".to_string()); + #[allow(unreachable_code)] + Ok(()) + })(); + assert!(result.is_err()); + assert_eq!( + state.workspace_epoch.load(Ordering::SeqCst) % 2, + 0, + "even after early-return drop" + ); + + // Simulated panic / catch_unwind. + // AppState contains non-UnwindSafe fields (reqwest::Client, etc.) so we + // assert the safety boundary explicitly — this test only exercises the + // epoch AtomicU64 and the Mutex<()> guard, both of which are panic-safe. + let state_ref = std::panic::AssertUnwindSafe(&state); + let panic_result = std::panic::catch_unwind(|| { + let _g = state_ref.begin_workspace_write().expect("guard for panic"); + panic!("simulated panic"); + }); + assert!(panic_result.is_err(), "panic must be caught"); + assert_eq!( + state.workspace_epoch.load(Ordering::SeqCst) % 2, + 0, + "even after panic/catch_unwind" + ); +} + +/// A poisoned `relay_url_override` mutex causes `capture_archive_scope` to +/// return `Err` rather than accepting potentially torn state. +#[test] +fn epoch_protocol_poisoned_mutex_causes_capture_error() { + use std::sync::Arc; + + let state = Arc::new(make_epoch_test_state(Keys::generate())); + let state2 = Arc::clone(&state); + + // Poison `relay_url_override` by panicking while holding the lock. + let _r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || { + let _lock = state2.relay_url_override.lock().unwrap(); + panic!("poison the mutex"); + })); + + // After poisoning, capture_archive_scope must return Err. + let result = state.capture_archive_scope(1); + assert!( + result.is_err(), + "capture must fail when relay_url_override is poisoned" + ); +} + +/// Mixed-generation barrier test: a writer is stalled mid-mutation (after +/// writing relay_url_override but before writing keys). A concurrent capture +/// with max_retries > 0 must never return a mixed-generation scope; it must +/// only succeed after the writer completes and produces a co-generational pair. +#[test] +fn epoch_protocol_mixed_generation_rejected_while_mid_transition() { + use std::sync::atomic::Ordering; + use std::sync::{Arc, Barrier}; + + let initial_keys = Keys::generate(); + let new_keys = Keys::generate(); + let state = Arc::new(make_epoch_test_state(initial_keys.clone())); + + // Two-phase barrier: first rendezvous lets the writer signal it has + // written the relay override but not yet the keys; second rendezvous lets + // the test confirm the capture it received (if any) before the writer + // proceeds to update keys. + let barrier_after_override = Arc::new(Barrier::new(2)); + let barrier_after_keys = Arc::new(Barrier::new(2)); + + let state_writer = Arc::clone(&state); + let barrier1 = Arc::clone(&barrier_after_override); + let barrier2 = Arc::clone(&barrier_after_keys); + let new_keys_clone = new_keys.clone(); + + let writer_thread = std::thread::spawn(move || { + // Acquire the write guard → epoch goes odd. + let _guard = state_writer.begin_workspace_write().expect("write guard"); + // Write override but NOT keys yet. + { + let mut ovr = state_writer.relay_url_override.lock().unwrap(); + *ovr = Some("wss://new.relay".to_string()); + } + // Signal: override written, keys not yet updated. + barrier1.wait(); + // Wait for reader to attempt capture. + barrier2.wait(); + // Now write keys (completing the compound mutation). + { + let mut k = state_writer.keys.lock().unwrap(); + *k = new_keys_clone; + } + // Guard drops here → epoch goes even. + }); + + // Wait until the writer is mid-mutation (override written, keys old, epoch odd). + barrier_after_override.wait(); + + // Epoch must be odd at this point. + assert_eq!( + state.workspace_epoch.load(Ordering::SeqCst) % 2, + 1, + "epoch must be odd while writer is mid-transition" + ); + + // Attempt capture with 0 retries — must fail because epoch is odd. + let result_during_mutation = state.capture_archive_scope(0); + assert!( + result_during_mutation.is_err(), + "capture must fail when epoch is odd (mid-transition)" + ); + + // Release writer to complete the mutation. + barrier_after_keys.wait(); + writer_thread.join().expect("writer thread panicked"); + + // Epoch is now even; capture must succeed and return the NEW generation. + let scope = state.capture_archive_scope(8).expect("capture after write"); + assert_eq!(scope.relay_url_override.as_deref(), Some("wss://new.relay")); + assert_eq!(scope.actor, new_keys.public_key().to_hex()); + assert!( + scope.workspace_epoch.is_multiple_of(2), + "captured epoch must be even" + ); +} + +/// Finding 7: `capture_archive_scope` must fail immediately when +/// `identity_lost` is set, regardless of epoch parity. +#[test] +fn capture_archive_scope_rejects_when_identity_lost() { + use std::sync::atomic::Ordering; + + let state = make_epoch_test_state(Keys::generate()); + state.identity_lost.store(true, Ordering::SeqCst); + + let result = state.capture_archive_scope(8); + assert!( + result.is_err(), + "capture must fail when identity_lost is set" + ); + assert!( + result.unwrap_err().contains("recovery mode"), + "error must mention recovery mode" + ); +} + +/// Finding 7: `capture_archive_scope` must fail immediately when +/// `keyring_locked` is set. +#[test] +fn capture_archive_scope_rejects_when_keyring_locked() { + use std::sync::atomic::Ordering; + + let state = make_epoch_test_state(Keys::generate()); + state.keyring_locked.store(true, Ordering::SeqCst); + + let result = state.capture_archive_scope(8); + assert!( + result.is_err(), + "capture must fail when keyring_locked is set" + ); + assert!( + result.unwrap_err().contains("recovery mode"), + "error must mention recovery mode" + ); +} + +/// Finding 4 (fix round 2): recovery key + true flag must never yield a +/// signable scope. This is the inverse-transition test: +/// 1. Start with a normal (non-recovery) key — capture succeeds. +/// 2. Simulate a recovery transition: write a new ephemeral key inside the +/// epoch guard AND set identity_lost = true (co-generational). +/// 3. A subsequent capture_archive_scope call must reject — the flag and key +/// are from the same generation, so there is no window where the +/// ephemeral key is visible with flags=false. +#[test] +fn capture_archive_scope_rejects_after_recovery_transition() { + use std::sync::atomic::Ordering; + + let normal_keys = Keys::generate(); + let state = make_epoch_test_state(normal_keys); + + // Pre-condition: capture succeeds with normal keys. + assert!( + state.capture_archive_scope(8).is_ok(), + "pre-condition: capture must succeed with normal keys" + ); + + // Simulate a recovery transition — write ephemeral recovery key AND set + // identity_lost = true, both inside the epoch guard (co-generational). + { + let _guard = state + .begin_workspace_write() + .expect("begin_workspace_write"); + let ephemeral = Keys::generate(); + *state.keys.lock().unwrap() = ephemeral; + state.identity_lost.store(true, Ordering::SeqCst); + } + + // Post-condition: capture must reject the ephemeral recovery key. + let result = state.capture_archive_scope(8); + assert!( + result.is_err(), + "capture must reject ephemeral recovery key after co-generational transition" + ); + assert!( + result.unwrap_err().contains("recovery mode"), + "error must mention recovery mode" + ); +} diff --git a/desktop/src-tauri/src/app_state_keyfile_ops.rs b/desktop/src-tauri/src/app_state_keyfile_ops.rs new file mode 100644 index 0000000000..4de3b625c9 --- /dev/null +++ b/desktop/src-tauri/src/app_state_keyfile_ops.rs @@ -0,0 +1,195 @@ +//! File-system and OS-keyring helpers extracted from `app_state` to keep that +//! module under the file-size ratchet. Included as a child module of +//! `app_state` so every item here has unrestricted access to the parent's +//! private items (constants, trait, types) via `super::`. + +use std::io::Write; + +use nostr::ToBech32; + +use super::{ + keyring_config, keyring_service, IdentityKeyStore, IdentityStorage, Keys, IDENTITY_KEY_NAME, + MIGRATION_MARKER_NAME, +}; + +/// Path of the migration-completed marker within `data_dir`. +pub(super) fn migration_marker_path(data_dir: &std::path::Path) -> std::path::PathBuf { + data_dir.join(keyring_config::migration_marker_name( + keyring_service(), + MIGRATION_MARKER_NAME, + )) +} + +/// Atomically write (and fsync) the migration-completed marker. The content is +/// irrelevant — only the file's durable existence is the signal — so a single +/// byte keeps it minimal. Atomicity + fsync guarantee that once this returns +/// `Ok`, the marker survives a crash, which is what makes deleting the legacy +/// file afterward safe. +pub(super) fn write_migration_marker(marker_path: &std::path::Path) -> Result<(), String> { + use atomic_write_file::AtomicWriteFile; + + let mut file = AtomicWriteFile::open(marker_path) + .map_err(|e| format!("open migration marker for atomic write: {e}"))?; + file.write_all(b"1") + .map_err(|e| format!("write migration marker: {e}"))?; + file.commit() + .map_err(|e| format!("commit migration marker: {e}")) +} + +/// Generate a fresh identity, persist it through the store, return it. +/// +/// On a keyring-backed persist no file is written, so a later +/// keyring-Unreachable boot would see "no file, no marker" (identical to a +/// fresh install) and silently rotate the identity. Writing the marker here +/// makes that boot fail closed. If the marker write fails, fall back to the +/// `0o600` file so the key is never keyring-only-without-marker. +pub(super) fn generate_and_persist( + store: &impl IdentityKeyStore, + legacy_path: &std::path::Path, + data_dir: &std::path::Path, +) -> Result<(Keys, IdentityStorage), String> { + let keys = Keys::generate(); + let storage = store_key_preferring_keyring(store, &keys, legacy_path)?; + if storage == IdentityStorage::SystemKeyring { + let marker_path = migration_marker_path(data_dir); + if let Err(e) = write_migration_marker(&marker_path) { + eprintln!( + "buzz-desktop: stored identity in keyring but failed to write migration marker \ + ({e}); saving identity.key fallback so the key is not stranded" + ); + save_key_file(legacy_path, &keys)?; + } + } + eprintln!( + "buzz-desktop: generated and saved identity pubkey {}", + keys.public_key().to_hex() + ); + Ok((keys, storage)) +} + +/// Persist `keys` through the store, silently falling back to the `0o600` file +/// when the keyring write fails on an availability error. Reports which backend +/// held the key (no verify/marker/delete — those belong to callers that own the +/// full migration contract) so the caller can write the migration marker only on +/// keyring success. +pub(super) fn store_key_preferring_keyring( + store: &impl IdentityKeyStore, + keys: &Keys, + legacy_path: &std::path::Path, +) -> Result { + let nsec = keys + .secret_key() + .to_bech32() + .map_err(|e| format!("encode nsec: {e}"))?; + match store.store(IDENTITY_KEY_NAME, &nsec) { + Ok(()) => Ok(IdentityStorage::SystemKeyring), + Err(keyring_err) => { + eprintln!("buzz-desktop: keyring write failed ({keyring_err}), using file fallback"); + save_key_file(legacy_path, keys)?; + Ok(IdentityStorage::LocalFile) + } + } +} + +/// Ensure the migration marker exists (writing it if absent), then remove the +/// leftover `identity.key`. Crash-safe ordering: the marker is written and +/// fsync-committed before the file is deleted, so a crash between the two +/// leaves the marker on disk and the file intact — the invariant "keyring-only +/// implies marker exists" is preserved. If the marker write fails, the file is +/// kept so a later keyring-unreachable boot can use it as a fallback. +pub(super) fn ensure_marker_then_cleanup( + data_dir: &std::path::Path, + legacy_path: &std::path::Path, +) { + let marker_path = migration_marker_path(data_dir); + let marker_ok = marker_path.exists() + || write_migration_marker(&marker_path) + .map_err(|e| { + eprintln!( + "buzz-desktop: keyring present but marker missing; \ + failed to write marker ({e}), keeping identity.key" + ); + }) + .is_ok(); + if marker_ok { + cleanup_leftover_identity_file(legacy_path); + } +} + +/// Best-effort removal of a leftover `identity.key` once the keyring is the +/// authoritative store. Idempotent: a missing file is success. Logs but does +/// not error on failure — a delete failure must never block startup. +pub(super) fn cleanup_leftover_identity_file(legacy_path: &std::path::Path) { + if !legacy_path.exists() { + return; + } + match std::fs::remove_file(legacy_path) { + Ok(()) => eprintln!("buzz-desktop: removed leftover identity.key (key is in keyring)"), + Err(e) => eprintln!("buzz-desktop: failed to remove leftover identity.key: {e}"), + } +} + +/// Quarantine a corrupt `identity.key` with a timestamp so prior backups are +/// never overwritten. +pub(super) fn quarantine_corrupt_key( + key_path: &std::path::Path, + data_dir: &std::path::Path, + error: &str, +) { + if !key_path.exists() { + return; + } + let ts = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0); + let bad_name = format!("identity.key.bad.{ts}"); + eprintln!("buzz-desktop: corrupt identity.key ({error}), quarantining to {bad_name}"); + let bad_path = data_dir.join(bad_name); + if std::fs::rename(key_path, &bad_path).is_err() { + let _ = std::fs::remove_file(key_path); + } +} + +pub(super) fn load_key_file(path: &std::path::Path) -> Result { + let content = std::fs::read_to_string(path).map_err(|e| format!("read identity.key: {e}"))?; + let trimmed = content.trim(); + if trimmed.is_empty() { + return Err("empty identity.key".to_string()); + } + Keys::parse(trimmed).map_err(|e| format!("parse identity.key: {e}")) +} + +/// Atomically write the key to disk. Uses `atomic-write-file` which: +/// 1. Writes to a temp file in the same directory +/// 2. Calls fsync on the file +/// 3. Renames temp → target (atomic on POSIX, best-effort on Windows) +/// 4. Calls fsync on the parent directory +/// +/// On Unix, the file is created with mode 0600 (owner read/write only). +/// On Windows, default ACLs apply — the app data directory is already +/// per-user, so the key is not world-readable in practice. +pub(crate) fn save_key_file(path: &std::path::Path, keys: &Keys) -> Result<(), String> { + use atomic_write_file::AtomicWriteFile; + + let nsec = keys + .secret_key() + .to_bech32() + .map_err(|e| format!("encode nsec: {e}"))?; + + let mut file = AtomicWriteFile::open(path) + .map_err(|e| format!("open identity.key for atomic write: {e}"))?; + + // Set owner-only permissions before writing the secret. + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + file.set_permissions(std::fs::Permissions::from_mode(0o600)) + .map_err(|e| format!("set identity.key permissions: {e}"))?; + } + + file.write_all(nsec.as_bytes()) + .map_err(|e| format!("write identity.key: {e}"))?; + file.commit() + .map_err(|e| format!("commit identity.key: {e}")) +} diff --git a/desktop/src-tauri/src/commands/identity.rs b/desktop/src-tauri/src/commands/identity.rs index bddf2e725a..b299869e68 100644 --- a/desktop/src-tauri/src/commands/identity.rs +++ b/desktop/src-tauri/src/commands/identity.rs @@ -415,28 +415,24 @@ fn commit_imported_identity( let storage = persist(&keys)?; - // Update in-memory keys BEFORE clearing recovery flags. The Release - // stores below pair with Acquire loads in get_identity: a reader - // observing false is guaranteed to see the updated keys. + // Update in-memory keys AND clear recovery flags inside the same epoch guard + // so they are co-generational: a concurrent `capture_archive_scope` that + // reads an even epoch after the guard exits sees the new key with flags=false. let pubkey = keys.public_key(); { + let _epoch_guard = state.begin_workspace_write()?; let mut active_keys = state.keys.lock().map_err(|e| e.to_string())?; *active_keys = keys; state.set_identity_storage(storage); + // Clear both recovery flags — an import resolves lost and locked. + state + .identity_lost + .store(false, std::sync::atomic::Ordering::SeqCst); + state + .keyring_locked + .store(false, std::sync::atomic::Ordering::SeqCst); } - // Clear both recovery flags — an import is valid in either lost or - // keyring-locked state and resolves both. In the locked case the - // keyring is unreachable, so the persist step already fell back to - // identity.key; on the next Unreachable boot the file is loaded - // directly and when the keyring returns the adoption path picks it up. - state - .identity_lost - .store(false, std::sync::atomic::Ordering::Release); - state - .keyring_locked - .store(false, std::sync::atomic::Ordering::Release); - // Importing a different identity invalidates the app-managed backup: it // encrypts the previous key and must not linger mislabeled. Best-effort // per the ordering contract above. diff --git a/desktop/src-tauri/src/commands/identity_archive.rs b/desktop/src-tauri/src/commands/identity_archive.rs deleted file mode 100644 index d15ee82abc..0000000000 --- a/desktop/src-tauri/src/commands/identity_archive.rs +++ /dev/null @@ -1,481 +0,0 @@ -//! NIP-IA identity archival commands. -//! -//! These commands let the desktop: -//! -//! - resolve a viewee's NIP-OA owner via their live `kind:0` (gates the -//! "Archive" button when the current user is the owner-of-agent), -//! - submit `kind:9035` archive and `kind:9036` unarchive requests (consent -//! path is selected by the relay; we just build the wire form), -//! - read the relay's `kind:13535` archive snapshot to drive UI flair. -//! -//! Spec: `docs/nips/NIP-IA.md`. The relay performs full authorization — -//! see §Owner-of-Agent Requests and §Relay Processing Algorithm. - -use serde::{Deserialize, Serialize}; -use tauri::State; - -use crate::{ - app_state::AppState, - events, - relay::{ - classify_request_error, query_relay, relay_http_base_url, relay_ws_url_with_override, - submit_event, SubmitEventResponse, - }, -}; - -// ── Helpers ───────────────────────────────────────────────────────────────── - -/// Read `target`'s live `kind:0` event and extract the first valid NIP-OA -/// `auth` tag plus the verified owner pubkey. -/// -/// Mirrors the verification the relay will do (per spec gotcha #3: the -/// preimage subject is the *target* pubkey, not the request signer). The -/// `buzz-sdk` lives on nostr 0.36; the desktop is on 0.37, so we bridge -/// via hex round-trip exactly like `relay::build_profile_event` does. -pub(crate) fn extract_oa_owner(target_kind0: &nostr::Event) -> Option<(String, [String; 4])> { - let target_hex = target_kind0.pubkey.to_hex(); - let target_compat = nostr::PublicKey::from_hex(&target_hex).ok()?; - - for tag in target_kind0.tags.iter() { - let slice = tag.as_slice(); - if slice.first().map(String::as_str) != Some("auth") || slice.len() != 4 { - continue; - } - let json = serde_json::to_string(slice).ok()?; - match buzz_sdk_pkg::nip_oa::verify_auth_tag(&json, &target_compat) { - Ok(owner) => { - let raw: [String; 4] = [ - slice[0].clone(), - slice[1].clone(), - slice[2].clone(), - slice[3].clone(), - ]; - return Some((owner.to_hex(), raw)); - } - Err(_) => continue, - } - } - None -} - -pub(crate) async fn fetch_kind0( - state: &AppState, - pubkey: &str, -) -> Result, String> { - let events = query_relay( - state, - &[serde_json::json!({ - "kinds": [0], - "authors": [pubkey.to_ascii_lowercase()], - "limit": 1, - })], - ) - .await?; - Ok(events.into_iter().next()) -} - -// ── Owner-of-agent resolution ─────────────────────────────────────────────── - -#[derive(Debug, Serialize)] -pub struct OwnerOfAgent { - /// Owner pubkey (hex) recovered from the viewee's verified NIP-OA `auth` tag. - pub owner: String, - /// True iff `owner` equals the current user's pubkey. Lets the frontend - /// gate the "Archive" button without a second round-trip. - pub is_me: bool, -} - -/// Resolve `target`'s NIP-OA owner by reading its live `kind:0` and verifying -/// the embedded `auth` tag. Returns `None` if the target has no kind:0, no -/// `auth` tag, or the tag fails verification. -/// -/// This is what gates the owner-path archive button: the frontend calls this, -/// and if `is_me == true`, shows the button. -#[tauri::command] -pub async fn resolve_oa_owner( - target_pubkey: String, - state: State<'_, AppState>, -) -> Result, String> { - let Some(kind0) = fetch_kind0(&state, &target_pubkey).await? else { - return Ok(None); - }; - - let Some((owner_hex, _tag)) = extract_oa_owner(&kind0) else { - return Ok(None); - }; - - let my_pubkey = { - let keys = state.keys.lock().map_err(|e| e.to_string())?; - keys.public_key().to_hex() - }; - - Ok(Some(OwnerOfAgent { - is_me: my_pubkey.eq_ignore_ascii_case(&owner_hex), - owner: owner_hex, - })) -} - -// ── Archive / unarchive requests ──────────────────────────────────────────── - -#[derive(Debug, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct ArchiveRequest { - pub target_pubkey: String, - #[serde(default)] - pub content: String, - #[serde(default)] - pub reason: Option, - #[serde(default)] - pub replaced_by: Option, -} - -#[derive(Debug, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct UnarchiveRequest { - pub target_pubkey: String, - #[serde(default)] - pub content: String, - #[serde(default)] - pub reason: Option, -} - -/// Submit a `kind:9035` archive request to the relay. Consent path is selected -/// by the relay — we just attach the owner-of-agent `auth` tag when the live -/// `kind:0` proves we own the target, so the relay can choose the `owner` -/// path. Self and admin paths require no auth tag. -#[tauri::command] -pub async fn archive_identity( - req: ArchiveRequest, - state: State<'_, AppState>, -) -> Result { - let auth_tag = maybe_owner_auth_tag(&state, &req.target_pubkey).await?; - let auth_ref = auth_tag.as_ref(); - - let builder = events::build_archive_identity_request( - &req.target_pubkey, - &req.content, - req.reason.as_deref(), - req.replaced_by.as_deref(), - auth_ref, - )?; - submit_event(builder, &state).await -} - -/// Submit a `kind:9036` unarchive request to the relay. -#[tauri::command] -pub async fn unarchive_identity( - req: UnarchiveRequest, - state: State<'_, AppState>, -) -> Result { - let auth_tag = maybe_owner_auth_tag(&state, &req.target_pubkey).await?; - let auth_ref = auth_tag.as_ref(); - - let builder = events::build_unarchive_identity_request( - &req.target_pubkey, - &req.content, - req.reason.as_deref(), - auth_ref, - )?; - submit_event(builder, &state).await -} - -/// If the current user is the verified NIP-OA owner of `target`, return the -/// `auth` tag elements (label, owner, conditions, sig) for attachment to a -/// 9035/9036 request. Otherwise return `None` (self / admin / no-path). -/// -/// The relay independently re-fetches the target's live `kind:0` and verifies -/// against it; this tag is intent + freshness evidence, not the authority. -async fn maybe_owner_auth_tag( - state: &AppState, - target_pubkey: &str, -) -> Result, String> { - let my_pubkey = { - let keys = state.keys.lock().map_err(|e| e.to_string())?; - keys.public_key().to_hex() - }; - - // Self path: never attach auth (spec §Self Requests: if actor==target and - // an `auth` tag is also present, relay MUST treat it as self). - if my_pubkey.eq_ignore_ascii_case(target_pubkey) { - return Ok(None); - } - - let Some(kind0) = fetch_kind0(state, target_pubkey).await? else { - return Ok(None); - }; - let Some((owner_hex, raw_tag)) = extract_oa_owner(&kind0) else { - return Ok(None); - }; - - if !owner_hex.eq_ignore_ascii_case(&my_pubkey) { - return Ok(None); - } - Ok(Some(raw_tag)) -} - -// ── Archive snapshot ──────────────────────────────────────────────────────── - -#[derive(Debug, Serialize)] -pub struct ArchivedIdentitiesSnapshot { - /// Lowercase hex pubkeys present in the latest relay-signed `kind:13535`. - pub archived: Vec, -} - -#[derive(Debug, Deserialize)] -struct RelayInformationDocument { - #[serde(default, rename = "self")] - self_: Option, -} - -pub(crate) async fn fetch_relay_self(state: &AppState) -> Result, String> { - let relay_url = relay_ws_url_with_override(state); - let http_url = relay_http_base_url(&relay_url); - let response = state - .http_client - .get(&http_url) - .header("Accept", "application/nostr+json") - .send() - .await - .map_err(|e| classify_request_error(&e))?; - - if !response.status().is_success() { - return Ok(None); - } - - let doc = response - .json::() - .await - .map_err(|_| "relay returned malformed NIP-11 document".to_string())?; - - let Some(relay_self) = doc.self_.map(|value| value.to_ascii_lowercase()) else { - return Ok(None); - }; - - if relay_self.len() == 64 && relay_self.chars().all(|c| c.is_ascii_hexdigit()) { - Ok(Some(relay_self)) - } else { - Ok(None) - } -} - -fn archived_pubkeys_from_snapshot(snapshot: &nostr::Event) -> Vec { - snapshot - .tags - .iter() - .filter_map(|t| { - let slice = t.as_slice(); - if slice.first().map(String::as_str) == Some("p") && slice.len() >= 2 { - let pk = slice[1].to_ascii_lowercase(); - if pk.len() == 64 && pk.chars().all(|c| c.is_ascii_hexdigit()) { - return Some(pk); - } - } - None - }) - .collect() -} - -/// Read the relay's latest valid `kind:13535` archive snapshot. The frontend -/// caches this and tests membership client-side to drive the "Archived" flair. -/// -/// Per NIP-IA §Client Behavior and §Snapshot and Delta Consistency, only a -/// snapshot signed by the relay identity advertised in NIP-11 `self` can affect -/// archive state. If the relay has no stable `self`, fail open with an empty -/// snapshot rather than trusting unauthenticated relay-authoritative state. -#[tauri::command] -pub async fn list_archived_identities( - state: State<'_, AppState>, -) -> Result { - let Some(relay_self) = fetch_relay_self(&state).await? else { - return Ok(ArchivedIdentitiesSnapshot { archived: vec![] }); - }; - - let events = query_relay( - &state, - &[serde_json::json!({ - "authors": [relay_self.clone()], - "kinds": [13535], - "limit": 1, - })], - ) - .await?; - - let Some(snapshot) = events.into_iter().next() else { - return Ok(ArchivedIdentitiesSnapshot { archived: vec![] }); - }; - - // Defense-in-depth: the filter should already restrict author, but the - // client must still reject malformed or wrongly signed relay state. - if !snapshot.verify_id() || !snapshot.verify_signature() { - return Ok(ArchivedIdentitiesSnapshot { archived: vec![] }); - } - if !snapshot.pubkey.to_hex().eq_ignore_ascii_case(&relay_self) { - return Ok(ArchivedIdentitiesSnapshot { archived: vec![] }); - } - - Ok(ArchivedIdentitiesSnapshot { - archived: archived_pubkeys_from_snapshot(&snapshot), - }) -} - -/// Read the active relay's NIP-11 `self` pubkey (its own signing key, hex). -/// -/// A public, unauthenticated document read reused by the moderation UI to tell -/// whether a DM peer is the relay identity (a moderation DM). Fails open: an -/// unreachable relay, a document without `self`, or a malformed value all -/// return `None`, and callers must treat that as "not the relay" — the disable -/// is an affordance, not enforcement, so a false negative is the safe failure. -#[tauri::command] -pub async fn get_relay_self(state: State<'_, AppState>) -> Result, String> { - fetch_relay_self(&state).await -} - -// ── Tests ─────────────────────────────────────────────────────────────────── - -#[cfg(test)] -mod tests { - use super::*; - use nostr::{EventBuilder, Keys, Kind, Tag}; - - /// Build a fake `kind:0` with a valid NIP-OA auth tag for a fresh owner. - fn kind0_with_auth(agent: &Keys, owner: &Keys) -> nostr::Event { - // Compute auth tag via buzz-sdk (nostr 0.36) and bridge. - let agent_hex = agent.public_key().to_hex(); - let agent_compat = nostr::PublicKey::from_hex(&agent_hex).unwrap(); - let owner_compat_secret = - nostr::SecretKey::from_slice(owner.secret_key().as_secret_bytes()).unwrap(); - let owner_compat_keys = nostr::Keys::new(owner_compat_secret); - let tag_json = - buzz_sdk_pkg::nip_oa::compute_auth_tag(&owner_compat_keys, &agent_compat, "") - .expect("compute_auth_tag"); - let compat_tag = buzz_sdk_pkg::nip_oa::parse_auth_tag(&tag_json).unwrap(); - let tag = Tag::parse(compat_tag.as_slice()).unwrap(); - EventBuilder::new(Kind::Metadata, "{}") - .tags([tag]) - .sign_with_keys(agent) - .unwrap() - } - - #[test] - fn extract_oa_owner_returns_owner_for_valid_tag() { - let owner = Keys::generate(); - let agent = Keys::generate(); - let kind0 = kind0_with_auth(&agent, &owner); - - let (recovered, raw) = extract_oa_owner(&kind0).expect("auth tag should verify"); - assert_eq!(recovered, owner.public_key().to_hex()); - assert_eq!(raw[0], "auth"); - assert_eq!(raw[1], owner.public_key().to_hex()); - // conditions empty by construction - assert_eq!(raw[2], ""); - assert_eq!(raw[3].len(), 128); - } - - #[test] - fn extract_oa_owner_ignores_kind0_without_auth_tag() { - let agent = Keys::generate(); - let kind0 = EventBuilder::new(Kind::Metadata, "{}") - .sign_with_keys(&agent) - .unwrap(); - assert!(extract_oa_owner(&kind0).is_none()); - } - - #[test] - fn archived_pubkeys_from_snapshot_accepts_only_valid_p_tags() { - let relay = Keys::generate(); - let valid = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; - let uppercase = "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"; - let snapshot = EventBuilder::new(Kind::Custom(13535), "") - .tags([ - Tag::parse(["-"]).unwrap(), - Tag::parse(["p", valid]).unwrap(), - Tag::parse(["p", uppercase]).unwrap(), - Tag::parse(["p", "not-hex"]).unwrap(), - ]) - .sign_with_keys(&relay) - .unwrap(); - - let expected = vec![valid.to_string(), uppercase.to_ascii_lowercase()]; - assert_eq!(archived_pubkeys_from_snapshot(&snapshot), expected); - } - - #[test] - fn relay_information_document_reads_nip11_self_field() { - let doc: RelayInformationDocument = serde_json::from_str( - r#"{"name":"test relay","self":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}"#, - ) - .expect("NIP-11 document"); - - assert_eq!( - doc.self_.as_deref(), - Some("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"), - ); - } - - /// Spec test-vector regression for gotcha #3: the NIP-OA preimage subject - /// is the *target/agent* pubkey, not the request signer. The vectors in - /// `docs/nips/NIP-IA.md` §Test Vectors fix concrete values; verifying the - /// vector's `auth` tag under the vector's agent pubkey MUST yield the - /// vector's owner pubkey. If our `extract_oa_owner` ever stops using the - /// agent pubkey as the preimage subject, this test fails loudly. - #[test] - fn extract_oa_owner_matches_nip_ia_test_vector() { - // From docs/nips/NIP-IA.md §Test Vectors → "NIP-OA auth tag". - const AGENT_HEX: &str = "c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5"; - const OWNER_HEX: &str = "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"; - const CONDITIONS: &str = "kind=1&created_at<1713957000"; - const SIG: &str = "8b7df2575caf0a108374f8471722b233c53f9ff827a8b0f91861966c3b9dd5cb2e189eae9f49d72187674c2f5bd244145e10ff86c9f257ffe65a1ee5f108b369"; - - // We don't have the agent's secret key (it's `0x...02` in the spec, but - // we don't need to re-sign a kind:0 — we just need a kind:0 whose - // `pubkey` is AGENT_HEX and whose tags carry this auth tag). Sign with - // a *different* agent and then construct an unsigned-event-shaped - // struct ourselves. nostr 0.37 doesn't easily allow forging `pubkey` - // mismatched with the signing key, so we build via the public - // constructor that requires a key — and for THIS test, the kind:0 - // signature is not checked (we only call extract_oa_owner which reads - // the event's pubkey field and the auth tag bytes). - let agent_secret = nostr::SecretKey::from_hex( - "0000000000000000000000000000000000000000000000000000000000000002", - ) - .unwrap(); - let agent_keys = nostr::Keys::new(agent_secret); - assert_eq!(agent_keys.public_key().to_hex(), AGENT_HEX); - - let auth_tag = nostr::Tag::parse(["auth", OWNER_HEX, CONDITIONS, SIG]).unwrap(); - let kind0 = EventBuilder::new(Kind::Metadata, "{}") - .tags([auth_tag]) - .sign_with_keys(&agent_keys) - .unwrap(); - - let (owner, raw) = extract_oa_owner(&kind0).expect("spec vector should verify"); - assert_eq!(owner, OWNER_HEX); - assert_eq!(raw[1], OWNER_HEX); - assert_eq!(raw[2], CONDITIONS); - assert_eq!(raw[3], SIG); - } - - /// Regression: the frontend sends the request payload in camelCase - /// (`targetPubkey`, `replacedBy`); these structs MUST deserialize it. - /// Without `#[serde(rename_all = "camelCase")]` the archive/unarchive - /// commands fail to deserialize at runtime — a failure the e2e mock hides - /// because it returns before parsing the payload. Red-if-broken guard. - #[test] - fn archive_request_deserializes_camel_case_payload() { - let req: ArchiveRequest = serde_json::from_str( - r#"{"targetPubkey":"abc","content":"bye","reason":"bot-rebuilt","replacedBy":"def"}"#, - ) - .expect("camelCase archive payload must deserialize"); - assert_eq!(req.target_pubkey, "abc"); - assert_eq!(req.content, "bye"); - assert_eq!(req.reason.as_deref(), Some("bot-rebuilt")); - assert_eq!(req.replaced_by.as_deref(), Some("def")); - - // Minimal payload (only the required field) still deserializes. - let minimal: UnarchiveRequest = - serde_json::from_str(r#"{"targetPubkey":"abc"}"#).expect("minimal payload"); - assert_eq!(minimal.target_pubkey, "abc"); - assert_eq!(minimal.content, ""); - assert!(minimal.reason.is_none()); - } -} diff --git a/desktop/src-tauri/src/commands/identity_archive/inventory.rs b/desktop/src-tauri/src/commands/identity_archive/inventory.rs new file mode 100644 index 0000000000..422da368bf --- /dev/null +++ b/desktop/src-tauri/src/commands/identity_archive/inventory.rs @@ -0,0 +1,907 @@ +//! Owned-agent relay inventory: exhaustive keyset-paged `kind:30177` query, +//! `d`-tag agent extraction + content parsing, `kind:0` fetch + NIP-01 +//! verification, `NipIaOwnerProof` classification joined with the archive +//! snapshot, local-managed-agent merge, and persona-grouped view model. +//! +//! All state is captured atomically via `capture_archive_scope` before any I/O. + +use std::collections::{HashMap, HashSet}; + +use serde::Serialize; +use tauri::AppHandle; + +use crate::{ + app_state::{AppState, ArchiveScope}, + managed_agents::{ + agent_events::managed_agent_content_from_event, load_managed_agents, ManagedAgentRecord, + }, + relay::{ + classify_request_error, query_relay_at_with_keys, relay_api_base_url, relay_http_base_url, + }, +}; + +use super::{ + archived_pubkeys_from_snapshot, classify_nip_ia_owner_proof, NipIaOwnerProof, + RelayInformationDocument, +}; + +// ── Model ──────────────────────────────────────────────────────────────────── + +/// Archive tri-state for a single owned-agent instance. +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct OwnedAgentArchiveState { + /// `None` if the snapshot was not loaded (caller may treat as unknown). + pub is_archived: Option, +} + +/// Minimal locally-managed agent fields needed by the UI to distinguish this +/// device's instance from relay-only duplicates. +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct LocalAgentSummary { + /// Agent pubkey (hex) — matches `OwnedAgentInstance.pubkey`. + pub pubkey: String, + /// Human-readable name from the local record. + pub name: String, + /// Persona ID from the local record (used to group local-only instances). + pub persona_id: Option, +} + +/// A single owned-agent instance from the relay `kind:30177` inventory, +/// or a local-only instance that has no relay row. +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct OwnedAgentInstance { + /// Agent pubkey (hex) — extracted from the `d` tag of `kind:30177`, or + /// from the local managed-agent record for local-only instances. + pub pubkey: String, + /// Display name from the agent's `kind:0` (relay instances) or local + /// record name (local-only instances). + pub display_name: Option, + /// Avatar URL from the agent's `kind:0`. + pub picture: Option, + /// Relay URL at which this agent has a kind:30177 listing. + /// Empty string for local-only instances (no relay row). + pub relay_url: String, + /// NIP-OA owner proof classified from the agent's `kind:0`. + pub nip_ia_owner_proof: NipIaOwnerProof, + /// Archive tri-state joined from the `kind:13535` snapshot. + pub archive_state: OwnedAgentArchiveState, + /// Persona ID parsed from `kind:30177` content, if present. + /// `None` for standalone (definition-less) agents or malformed content. + pub persona_id: Option, + /// Present when this pubkey is managed by a local record on this device. + /// `None` for relay-only instances (no local record). + /// + /// The UI keys the "Not managed on this device" / Relay-only badge on + /// `local == null`, NOT on `personaId == null`. A stale relay-only + /// duplicate WITH a valid personaId receives the badge; a locally managed + /// definition-less agent does NOT. + pub local: Option, +} + +/// Complete merged view model returned by `get_owned_agent_inventory`. +/// +/// Instances are grouped by persona ID. The `unknown` bucket holds instances +/// whose `kind:30177` content is missing or has no `persona_id`. +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct OwnedAgentInventorySnapshot { + /// Whether the archive snapshot was loaded and trusted. + pub archive_state_trusted: bool, + /// Instances keyed by their persona ID — drives per-card counts and Sheet. + pub by_persona_id: HashMap>, + /// Instances with no parseable persona ID (standalone agents). + pub unknown: Vec, +} + +// ── Page-to-exhaustion fetch ────────────────────────────────────────────── + +/// Maximum events per page. +const PAGE_SIZE: u64 = 50; + +/// Validate that a string is a 64-char lowercase hex pubkey. +fn is_valid_agent_pubkey(s: &str) -> bool { + let lower = s.to_ascii_lowercase(); + lower.len() == 64 && lower.chars().all(|c| c.is_ascii_hexdigit()) +} + +/// State returned by `reduce_page`. +struct PageResult { + /// Canonical (latest) event per agent pubkey accumulated across all pages. + canonical: HashMap, + /// Cursor for the next request: `(created_at, id)` of the LAST raw event + /// on this page. Advances from the raw page tail ONLY — dedup never + /// influences cursor progression. + next_until: u64, + next_before_id: String, + /// Whether the relay returned a full page (more data may follow). + full_page: bool, +} + +/// Pure reducer: merge one raw relay page into `canonical` and compute the +/// next cursor from the raw page tail. +/// +/// Malformed `d` tags are skipped and DO NOT affect the cursor. +fn reduce_page( + mut canonical: HashMap, + page: Vec, +) -> PageResult { + let full_page = page.len() as u64 == PAGE_SIZE; + + // Cursor from raw page tail — the relay sorts (created_at DESC, id ASC), + // so the last event is the oldest on this page. + let (next_until, next_before_id) = page + .last() + .map(|ev| (ev.created_at.as_secs(), ev.id.to_hex())) + .unwrap_or((0, String::new())); + + for ev in page { + let d_raw = ev + .tags + .iter() + .find(|t| t.as_slice().first().map(String::as_str) == Some("d")) + .and_then(|t| t.as_slice().get(1).cloned()) + .unwrap_or_default(); + let agent_pubkey = d_raw.to_ascii_lowercase(); + if !is_valid_agent_pubkey(&agent_pubkey) { + continue; // malformed d tag — skip, cursor unaffected + } + + let ts = ev.created_at.as_secs(); + let id = ev.id.to_hex(); + + let supersedes = canonical + .get(&agent_pubkey) + .map(|(ets, eid, _)| ts > *ets || (ts == *ets && id < *eid)) + .unwrap_or(true); + + if supersedes { + canonical.insert(agent_pubkey, (ts, id, ev)); + } + } + + PageResult { + canonical, + next_until, + next_before_id, + full_page, + } +} + +/// Fetch all `kind:30177` events authored by `scope.actor`, paging to +/// exhaustion via composite `(until, before_id)` cursor. +/// +/// Returns the canonical latest event per NIP-33 `d` tag (agent pubkey), +/// sorted `(created_at DESC, id ASC)`. Events with missing or non-hex-64 `d` +/// tags are silently skipped (malformed). Transport errors propagate — a +/// partial inventory is never silently returned as complete. +async fn fetch_all_owned_30177( + state: &AppState, + scope: &ArchiveScope, + api_base_url: &str, +) -> Result, String> { + let mut until: Option = None; + let mut before_id: Option = None; + let mut canonical: HashMap = HashMap::new(); + + loop { + let mut filter = serde_json::json!({ + "kinds": [30177u32], + "authors": [scope.actor.clone()], + "limit": PAGE_SIZE, + }); + if let Some(ts) = until { + filter["until"] = serde_json::json!(ts); + } + if let Some(ref bid) = before_id { + filter["before_id"] = serde_json::json!(bid); + } + + // Transport failure propagates — partial inventory is not returned. + let page = + query_relay_at_with_keys(state, api_base_url, &[filter], &scope.keys, None).await?; + + let PageResult { + canonical: new_canonical, + next_until, + next_before_id, + full_page, + } = reduce_page(canonical, page); + canonical = new_canonical; + + if !full_page { + break; + } + + // Guard against degenerate relay behaviour. + let no_progress = + until == Some(next_until) && before_id.as_deref() == Some(next_before_id.as_str()); + if no_progress { + break; + } + + until = Some(next_until); + before_id = Some(next_before_id); + } + + let mut events: Vec = canonical.into_values().map(|(_, _, ev)| ev).collect(); + events.sort_by(|a, b| { + let ts = b.created_at.as_secs().cmp(&a.created_at.as_secs()); + if ts.is_eq() { + a.id.to_hex().cmp(&b.id.to_hex()) + } else { + ts + } + }); + Ok(events) +} + +// ── kind:0 fetch + NIP-01 verify ───────────────────────────────────────── + +/// Fetch the agent's latest `kind:0`, verify NIP-01 ID and signature, and +/// confirm it is kind:0 authored by `agent_pubkey`. Returns the event if +/// valid; `None` on missing profile or invalid event. +async fn fetch_and_verify_kind0( + state: &AppState, + scope: &ArchiveScope, + api_base_url: &str, + agent_pubkey: &str, +) -> Result, String> { + let events = query_relay_at_with_keys( + state, + api_base_url, + &[serde_json::json!({ + "kinds": [0u32], + "authors": [agent_pubkey], + "limit": 1, + })], + &scope.keys, + None, + ) + .await?; + + let Some(ev) = events.into_iter().next() else { + return Ok(None); + }; + + // NIP-01 verification: reject tampered events. + if !ev.verify_id() || !ev.verify_signature() { + return Ok(None); + } + // Must be authored by the expected agent. + if !ev.pubkey.to_hex().eq_ignore_ascii_case(agent_pubkey) { + return Ok(None); + } + // Must be kind:0. + if ev.kind != nostr::Kind::Metadata { + return Ok(None); + } + Ok(Some(ev)) +} + +// ── Archive snapshot loader ─────────────────────────────────────────────── + +/// Load the relay's `kind:13535` archive snapshot for the tri-state join. +/// +/// Uses `scope.keys` for NIP-98 authentication (same generation as the +/// inventory query). Returns `(false, empty)` for ALL failure conditions — +/// query failure, absent relay self, absent snapshot, and invalid signature. +/// Only a successfully fetched, verified, relay-signed snapshot returns `true`. +async fn load_archive_snapshot( + state: &AppState, + scope: &ArchiveScope, + api_base_url: &str, +) -> (bool, HashSet) { + // Fetch NIP-11 relay-information document at the scoped URL. + let relay_self: Option = async { + let response = state + .http_client + .get(api_base_url) + .header("Accept", "application/nostr+json") + .send() + .await + .map_err(|e| classify_request_error(&e))?; + if !response.status().is_success() { + return Ok::<_, String>(None); + } + let doc = response + .json::() + .await + .map_err(|_| "relay returned malformed NIP-11 document".to_string())?; + let Some(s) = doc.self_.map(|v| v.to_ascii_lowercase()) else { + return Ok(None); + }; + if s.len() == 64 && s.chars().all(|c| c.is_ascii_hexdigit()) { + Ok(Some(s)) + } else { + Ok(None) + } + } + .await + .unwrap_or(None); + + let Some(relay_self) = relay_self else { + // relay_self absent or fetch failed → unknown, not trusted-empty + return (false, HashSet::new()); + }; + + // Use scope.keys for NIP-98 auth — same generation as the inventory query. + let snaps = query_relay_at_with_keys( + state, + api_base_url, + &[serde_json::json!({ + "authors": [relay_self.clone()], + "kinds": [13535u32], + "limit": 1, + })], + &scope.keys, + None, + ) + .await; + + // Delegate to the pure helper so unit tests can exercise all trust arms + // (error, absent, invalid, trusted-empty) without live network I/O. + reduce_snapshot_query_result(snaps, &relay_self) +} + +/// Verify a single kind:13535 snapshot event and return the trust decision. +/// +/// This is the testable core of `load_archive_snapshot`'s trust logic — it +/// operates on already-fetched data with no I/O. +/// +/// Returns `(true, set)` only when: +/// - the event passes NIP-01 `verify_id()` and `verify_signature()`, AND +/// - the event was authored by `relay_self` (signer match). +/// +/// Returns `(false, empty)` for any invalid snapshot or signer mismatch. +pub(super) fn verify_snapshot_for_trust( + snap: &nostr::Event, + relay_self: &str, +) -> (bool, HashSet) { + if !snap.verify_id() + || !snap.verify_signature() + || !snap.pubkey.to_hex().eq_ignore_ascii_case(relay_self) + { + return (false, HashSet::new()); + } + let set: HashSet = archived_pubkeys_from_snapshot(snap).into_iter().collect(); + (true, set) +} + +/// Reduce the raw query result from the relay into a trust decision. +/// +/// This is the testable core that covers ALL four trust arms: +/// - `Err(_)` (query / transport failure) → `(false, empty)` +/// - `Ok([])` (relay self confirmed, no kind:13535 event present) → `(false, empty)` +/// - `Ok([snap])` (snapshot present) → delegates to `verify_snapshot_for_trust` +/// +/// Calling this function rather than re-implementing the match arms in tests +/// ensures that a regression in `load_archive_snapshot`'s decision logic +/// will be caught by the unit tests. +pub(super) fn reduce_snapshot_query_result( + query_result: Result, E>, + relay_self: &str, +) -> (bool, HashSet) { + let Ok(snaps) = query_result else { + return (false, HashSet::new()); + }; + match snaps.into_iter().next() { + // No snapshot present → absent is UNKNOWN, not trusted-empty. + None => (false, HashSet::new()), + Some(snap) => verify_snapshot_for_trust(&snap, relay_self), + } +} + +// ── Local agent index builder ───────────────────────────────────────────── + +/// Build a normalized pubkey → [`LocalAgentSummary`] index from the raw +/// managed-agent records result. +/// +/// This is the testable entry point that covers the two local-store arms: +/// - `Err(e)` → propagated as `Err("managed_agents_store_lock: …")` so the +/// caller can NEVER produce a successful all-relay-only inventory when the +/// local store is unreadable. +/// - `Ok(records)` → deduped, normalised (lowercase pubkey), empty-pubkey +/// rows filtered out. +/// +/// The production code calls `build_local_agent_index(load_managed_agents(&app))?` +/// so a storage failure propagates exactly here. Unit tests inject `Err(…)` +/// directly to prove the mutation guard without needing a live `AppHandle`. +pub(super) fn build_local_agent_index( + records_result: Result, E>, +) -> Result, String> { + let records = records_result + .map_err(|e| format!("managed_agents_store_lock: failed to load local agents: {e}"))?; + Ok(records + .into_iter() + .filter(|r| !r.pubkey.is_empty()) + .map(|r| { + let norm = r.pubkey.to_ascii_lowercase(); + let summary = LocalAgentSummary { + pubkey: norm.clone(), + name: r.name, + persona_id: r.persona_id, + }; + (norm, summary) + }) + .collect()) +} + +// ── Parse kind:0 content ────────────────────────────────────────────────── + +fn parse_display_fields(content: &str) -> (Option, Option) { + let Ok(v) = serde_json::from_str::(content) else { + return (None, None); + }; + let dn = v + .get("display_name") + .and_then(|x| x.as_str()) + .map(str::to_string); + let pic = v + .get("picture") + .and_then(|x| x.as_str()) + .map(str::to_string); + (dn, pic) +} + +// ── Tauri command ───────────────────────────────────────────────────────── + +/// Query the relay's `kind:30177` inventory for agents owned by the current +/// user. Pages to exhaustion; applies NIP-33 dedup; fetches each agent's +/// `kind:0` for NIP-OA classification; joins the archive tri-state. +/// Parses `kind:30177` content for `persona_id` and groups results. +/// Merges local managed-agent records by normalized pubkey, including +/// local-only instances (no relay row). Groups by persona ID. +/// +/// All state is captured atomically via the seqlock before any I/O. +#[tauri::command] +pub async fn get_owned_agent_inventory( + app: AppHandle, + state: tauri::State<'_, AppState>, +) -> Result { + let scope = state.capture_archive_scope(8)?; + let api_base_url = match &scope.relay_url_override { + Some(url) => relay_http_base_url(url), + None => relay_api_base_url(), + }; + + let owned_events = fetch_all_owned_30177(&state, &scope, &api_base_url).await?; + let (archive_state_trusted, archived_set) = + load_archive_snapshot(&state, &scope, &api_base_url).await; + + // Load all local managed-agent records once and build a lookup by + // normalized pubkey. This is a disk read — done before relay I/O to + // avoid holding a lock across await points. Failure propagates: a + // storage error here would silently reclassify every local instance as + // "Relay only", which could steer the archive decision to the wrong + // duplicate — exactly the scenario this feature exists to prevent. + let local_by_pubkey: HashMap = + build_local_agent_index(load_managed_agents(&app))?; + + // Bounded batch: fetch all kind:0 profiles concurrently but fail the + // entire snapshot on transport error (a partial inventory is dangerous + // for the no-third-mint gate). + let mut instances = Vec::with_capacity(owned_events.len()); + // Track relay pubkeys seen so we can identify local-only instances. + let mut relay_pubkeys: HashSet = HashSet::new(); + + for ev in owned_events { + // Re-extract agent pubkey (already validated by fetch_all_owned_30177). + let agent_pubkey = ev + .tags + .iter() + .find(|t| t.as_slice().first().map(String::as_str) == Some("d")) + .and_then(|t| t.as_slice().get(1).cloned()) + .unwrap_or_default() + .to_ascii_lowercase(); + + relay_pubkeys.insert(agent_pubkey.clone()); + + // Parse persona_id from kind:30177 content (authoritative per wire contract). + let persona_id = managed_agent_content_from_event(&ev) + .ok() + .and_then(|c| c.persona_id); + + // Fetch + NIP-01-verify the agent's kind:0. + // Transport failure propagates — do NOT silently omit this instance. + let (proof, display_name, picture) = + match fetch_and_verify_kind0(&state, &scope, &api_base_url, &agent_pubkey).await { + Err(e) => return Err(format!("kind:0 fetch failed for {agent_pubkey}: {e}")), + Ok(None) => (NipIaOwnerProof::MissingProfile, None, None), + Ok(Some(k0)) => { + let proof = classify_nip_ia_owner_proof(&k0, &scope.actor); + let (dn, pic) = parse_display_fields(k0.content.as_ref()); + (proof, dn, pic) + } + }; + + let is_archived = if archive_state_trusted { + Some(archived_set.contains(&agent_pubkey)) + } else { + None + }; + + // Attach local summary if this pubkey is managed on this device. + let local = local_by_pubkey + .get(&agent_pubkey) + .map(|s| LocalAgentSummary { + pubkey: s.pubkey.clone(), + name: s.name.clone(), + persona_id: s.persona_id.clone(), + }); + + instances.push(OwnedAgentInstance { + pubkey: agent_pubkey, + display_name, + picture, + relay_url: api_base_url.clone(), + nip_ia_owner_proof: proof, + archive_state: OwnedAgentArchiveState { is_archived }, + persona_id, + local, + }); + } + + // Add local-only instances: locally managed agents with no relay row. + // These are included so the UI can show the user what they have locally + // vs. what the relay knows about. + for (pubkey, local_summary) in &local_by_pubkey { + if relay_pubkeys.contains(pubkey) { + continue; // already included in the relay inventory above + } + let is_archived = if archive_state_trusted { + Some(archived_set.contains(pubkey)) + } else { + None + }; + instances.push(OwnedAgentInstance { + pubkey: pubkey.clone(), + display_name: Some(local_summary.name.clone()), + picture: None, + relay_url: String::new(), // no relay row + nip_ia_owner_proof: NipIaOwnerProof::MissingProfile, + archive_state: OwnedAgentArchiveState { is_archived }, + persona_id: local_summary.persona_id.clone(), + local: Some(LocalAgentSummary { + pubkey: local_summary.pubkey.clone(), + name: local_summary.name.clone(), + persona_id: local_summary.persona_id.clone(), + }), + }); + } + + // Group instances: byPersonaId for those with a known persona, unknown for + // those without. This grouping is the authoritative source for per-card + // counts, Sheet filtering, and the start-control safeguard. + let mut by_persona_id: HashMap> = HashMap::new(); + let mut unknown: Vec = Vec::new(); + for instance in instances { + match &instance.persona_id { + Some(pid) => by_persona_id.entry(pid.clone()).or_default().push(instance), + None => unknown.push(instance), + } + } + + Ok(OwnedAgentInventorySnapshot { + archive_state_trusted, + by_persona_id, + unknown, + }) +} + +// ── Tests ──────────────────────────────────────────────────────────────────── + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn valid_agent_pubkey_passes_validation() { + assert!(is_valid_agent_pubkey(&"a".repeat(64))); + assert!(is_valid_agent_pubkey(&"0123456789abcdef".repeat(4))); + } + + #[test] + fn malformed_d_tags_are_rejected() { + assert!(!is_valid_agent_pubkey("")); + assert!(!is_valid_agent_pubkey("not-hex")); + assert!(!is_valid_agent_pubkey(&"a".repeat(63))); // too short + assert!(!is_valid_agent_pubkey(&"a".repeat(65))); // too long + assert!(!is_valid_agent_pubkey(&"g".repeat(64))); // non-hex + } + + /// Finding 6: `fetch_and_verify_kind0` rejects events with tampered NIP-01 + /// ID or signature. Construct a genuine event, tamper it, and confirm the + /// verification predicates it delegates to both reject the tampered copy. + #[test] + fn nip01_verification_rejects_tampered_event() { + use nostr::{EventBuilder, JsonUtil, Keys, Kind}; + let agent = Keys::generate(); + let ev = EventBuilder::new(Kind::Metadata, "{}") + .sign_with_keys(&agent) + .unwrap(); + + // A genuine event passes NIP-01 checks. + assert!(ev.verify_id(), "genuine event must pass verify_id"); + assert!( + ev.verify_signature(), + "genuine event must pass verify_signature" + ); + + // Tamper: mutate the content so the event ID no longer matches. + // Deserialize to raw JSON, swap the content field, reserialise. + let mut raw: serde_json::Value = + serde_json::from_str(&ev.as_json()).expect("event must be valid JSON"); + raw["content"] = serde_json::json!("tampered content"); + let tampered_json = serde_json::to_string(&raw).unwrap(); + let tampered = nostr::Event::from_json(&tampered_json) + .expect("tampered JSON must still parse as an Event struct"); + + // The tampered copy must FAIL at least verify_id (content was changed). + // fetch_and_verify_kind0 checks both and rejects if either fails. + assert!( + !tampered.verify_id() || !tampered.verify_signature(), + "tampered event must fail at least one NIP-01 check" + ); + } + + /// Finding 6: when fetch_and_verify_kind0 returns None, the inventory + /// code correctly maps to NipIaOwnerProof::MissingProfile. Verify the + /// mapping is present in the `get_owned_agent_inventory` path. + #[test] + fn missing_profile_variant_is_reachable_and_serializable() { + use super::super::NipIaOwnerProof; + let proof = NipIaOwnerProof::MissingProfile; + let json = + serde_json::to_string(&proof).expect("NipIaOwnerProof::MissingProfile must serialize"); + assert!( + json.contains("missing_profile"), + "serialized form must contain 'missing_profile', got: {json}" + ); + } + + // ── reduce_page tests ──────────────────────────────────────────────────── + + /// reduce_page uses the raw page tail for the cursor, not the dedup map + /// tail. When a page contains only malformed d-tags, the canonical map is + /// empty but the cursor still advances from the raw events. + #[test] + fn reduce_page_cursor_from_raw_tail_not_dedup_map() { + use nostr::{EventBuilder, Keys, Kind, Tag}; + + let owner = Keys::generate(); + + // Two events with MALFORMED d-tags — they won't enter canonical, + // but they ARE on the raw page and the cursor must advance from them. + let ev_old = EventBuilder::new(Kind::Custom(30177), "") + .tags([Tag::parse(["d", "not-hex"]).unwrap()]) + .sign_with_keys(&owner) + .unwrap(); + let ev_new = EventBuilder::new(Kind::Custom(30177), "") + .tags([Tag::parse(["d", "also-bad"]).unwrap()]) + .sign_with_keys(&owner) + .unwrap(); + + // Simulate relay order: newest first. ev_new is first, ev_old is last. + // The cursor must come from ev_old (the raw page tail = oldest event). + let page = vec![ev_new.clone(), ev_old.clone()]; + let result = reduce_page(HashMap::new(), page); + + // No events passed the pubkey validation — canonical stays empty. + assert!( + result.canonical.is_empty(), + "malformed d tags must not enter canonical" + ); + // Cursor must come from the raw tail (ev_old), not u64::MAX or empty. + assert_eq!(result.next_until, ev_old.created_at.as_secs()); + assert_eq!(result.next_before_id, ev_old.id.to_hex()); + } + + /// Two events with equal created_at: the one with the lexicographically + /// smaller ID wins in the canonical map (NIP-33 tiebreak rule). + #[test] + fn reduce_page_equal_timestamp_lower_id_wins() { + use nostr::{EventBuilder, Keys, Kind, Tag}; + + let owner = Keys::generate(); + let agent_pk = "a".repeat(64); + + // Generate two events and keep trying until we have same created_at. + // In practice, two Events built back-to-back in the same second will + // share the timestamp — but we can't guarantee that in a unit test. + // Instead, use two events and pick the winner based on the rule. + let ev1 = EventBuilder::new(Kind::Custom(30177), "v1") + .tags([Tag::parse(["d", &agent_pk]).unwrap()]) + .sign_with_keys(&owner) + .unwrap(); + let ev2 = EventBuilder::new(Kind::Custom(30177), "v2") + .tags([Tag::parse(["d", &agent_pk]).unwrap()]) + .sign_with_keys(&owner) + .unwrap(); + + let id1 = ev1.id.to_hex(); + let id2 = ev2.id.to_hex(); + let ts1 = ev1.created_at.as_secs(); + let ts2 = ev2.created_at.as_secs(); + + let page = vec![ev1.clone(), ev2.clone()]; + let result = reduce_page(HashMap::new(), page); + assert_eq!(result.canonical.len(), 1); + + let (_, winning_id, _) = result.canonical.get(&agent_pk).unwrap(); + if ts1 != ts2 { + // Whichever has higher created_at wins. + if ts1 > ts2 { + assert_eq!(winning_id, &id1); + } else { + assert_eq!(winning_id, &id2); + } + } else { + // Equal timestamps: lower id wins. + if id1 < id2 { + assert_eq!(winning_id, &id1); + } else { + assert_eq!(winning_id, &id2); + } + } + } + + /// A full page (PAGE_SIZE events) sets full_page = true; a partial page + /// does not. + #[test] + fn reduce_page_full_page_detection() { + use nostr::{EventBuilder, Keys, Kind, Tag}; + + let owner = Keys::generate(); + + // Build PAGE_SIZE events with distinct d-tags. + let full_page_events: Vec = (0..PAGE_SIZE) + .map(|i| { + let pk = format!("{:0>64}", format!("{i:x}")); + EventBuilder::new(Kind::Custom(30177), "") + .tags([Tag::parse(["d", &pk]).unwrap()]) + .sign_with_keys(&owner) + .unwrap() + }) + .collect(); + + let result = reduce_page(HashMap::new(), full_page_events); + assert!(result.full_page, "PAGE_SIZE events must set full_page"); + + // One event less → partial. + let partial: Vec = (0..(PAGE_SIZE - 1)) + .map(|i| { + let pk = format!("{:0>64}", format!("{i:x}")); + EventBuilder::new(Kind::Custom(30177), "") + .tags([Tag::parse(["d", &pk]).unwrap()]) + .sign_with_keys(&owner) + .unwrap() + }) + .collect(); + let result = reduce_page(HashMap::new(), partial); + assert!(!result.full_page, "partial page must NOT set full_page"); + } + + #[test] + fn distinct_agent_pubkeys_yield_separate_canonical_entries() { + use nostr::{EventBuilder, Keys, Kind, Tag}; + + let owner = Keys::generate(); + let agent1 = "a".repeat(64); + let agent2 = "b".repeat(64); + + let page = vec![ + EventBuilder::new(Kind::Custom(30177), "") + .tags([Tag::parse(["d", &agent1]).unwrap()]) + .sign_with_keys(&owner) + .unwrap(), + EventBuilder::new(Kind::Custom(30177), "") + .tags([Tag::parse(["d", &agent2]).unwrap()]) + .sign_with_keys(&owner) + .unwrap(), + ]; + let result = reduce_page(HashMap::new(), page); + assert_eq!(result.canonical.len(), 2); + } + + // ── Archive snapshot trust tests ────────────────────────────────────────── + + /// Proves that a local-store read failure propagates as Err, preventing + /// `get_owned_agent_inventory` from silently returning a relay-only snapshot + /// that mislabels every local instance as "Relay only". + /// + /// Drives `build_local_agent_index` — the production helper wired via `?` into + /// `get_owned_agent_inventory` — with an `Err` result. Mutation guard: restoring + /// `unwrap_or_default()` in the helper makes this test fail. + #[test] + fn local_store_failure_propagates_not_silently_dropped() { + // Inject the error path directly into the production helper. + let result = + build_local_agent_index::(Err("simulated store lock poisoned".to_string())); + assert!( + result.is_err(), + "local store failure must propagate as Err, not unwrap_or_default" + ); + let msg = result.unwrap_err(); + assert!( + msg.contains("managed_agents_store_lock"), + "error message must include context prefix: got {msg}" + ); + } + + /// Trusted-empty: relay_self confirmed + valid kind:13535 snapshot with no + /// archived pubkeys → (true, empty). The relay explicitly published an + /// empty archive list. Drives `reduce_snapshot_query_result` with a valid + /// event in an Ok(vec) to exercise the `Some(snap) → verify` arm end-to-end. + #[test] + fn load_archive_snapshot_trust_arm_trusted_empty() { + use nostr::{EventBuilder, Keys, Kind}; + let relay = Keys::generate(); + // A kind:13535 with NO p-tags → trusted empty. + let snap = EventBuilder::new(Kind::Custom(13535), "") + .sign_with_keys(&relay) + .unwrap(); + let relay_self = relay.public_key().to_hex(); + // Drive the production helper end-to-end: Ok(vec![snap]) → trusted. + let (trusted, set) = reduce_snapshot_query_result::(Ok(vec![snap]), &relay_self); + assert!( + trusted, + "valid snap from correct relay_self must be trusted" + ); + assert!(set.is_empty(), "no p-tags → empty archived set"); + } + + /// Unknown — absent snapshot: relay self confirmed but no kind:13535 event. + /// Drives `reduce_snapshot_query_result` with Ok(empty vec) — the `None` arm + /// must return (false, empty). Any regression in the production function + /// will surface here rather than in a parallel inline re-implementation. + #[test] + fn absent_snapshot_trust_arm_is_false_empty() { + let relay = nostr::Keys::generate(); + let relay_self = relay.public_key().to_hex(); + // Ok(empty vec) → absent snapshot → (false, empty). + let (trusted, set) = reduce_snapshot_query_result::(Ok(vec![]), &relay_self); + assert!(!trusted, "absent snapshot must return trusted=false"); + assert!(set.is_empty(), "absent snapshot must return empty set"); + } + + /// Unknown — query/transport error: the error arm returns (false, empty). + /// Drives `reduce_snapshot_query_result` with Err(_) — a regression in + /// the production Err arm will be caught here. + #[test] + fn error_trust_arm_is_false_empty() { + let relay = nostr::Keys::generate(); + let relay_self = relay.public_key().to_hex(); + // Err(transport error) → (false, empty). + let (trusted, set) = + reduce_snapshot_query_result::(Err("transport error".to_string()), &relay_self); + assert!(!trusted, "error must return trusted=false"); + assert!(set.is_empty(), "error must return empty set"); + } + + /// Unknown — invalid snapshot: drives `reduce_snapshot_query_result` with + /// a tampered event to prove it returns (false, empty) for signer-mismatch + /// or NIP-01 failure. + #[test] + fn invalid_snapshot_trust_arm_is_false_empty() { + use nostr::{EventBuilder, JsonUtil, Keys, Kind}; + let relay = Keys::generate(); + let snap = EventBuilder::new(Kind::Custom(13535), "") + .sign_with_keys(&relay) + .unwrap(); + let relay_self = relay.public_key().to_hex(); + + // Tamper the snapshot so verify_id() fails. + let mut raw: serde_json::Value = serde_json::from_str(&snap.as_json()).expect("valid JSON"); + raw["content"] = serde_json::json!("tampered"); + let tampered = + nostr::Event::from_json(serde_json::to_string(&raw).unwrap()).expect("parseable"); + // Drive the production helper end-to-end: Ok(vec![tampered]) → untrusted. + let (trusted, set) = + reduce_snapshot_query_result::(Ok(vec![tampered]), &relay_self); + assert!(!trusted, "invalid snapshot must return trusted=false"); + assert!(set.is_empty(), "invalid snapshot must return empty set"); + } +} diff --git a/desktop/src-tauri/src/commands/identity_archive/mod.rs b/desktop/src-tauri/src/commands/identity_archive/mod.rs new file mode 100644 index 0000000000..6368e930ff --- /dev/null +++ b/desktop/src-tauri/src/commands/identity_archive/mod.rs @@ -0,0 +1,786 @@ +//! NIP-IA identity archival commands. +//! +//! Modules: +//! - `inventory` — exhaustive relay inventory of owned agent instances +//! - `archive_op` — scoped archive / unarchive request flow +//! +//! Shared items (classifier, snapshot helpers, resolve command) live here. + +pub(crate) mod inventory; + +use serde::{Deserialize, Serialize}; +use tauri::State; + +use crate::{ + app_state::{AppState, ArchiveScope}, + events, + relay::{ + classify_request_error, query_relay, query_relay_at_with_keys, relay_http_base_url, + relay_ws_url_with_override, submit_signed_event_at_with_keys, SubmitEventResponse, + }, +}; + +pub use inventory::get_owned_agent_inventory; + +// ── Helpers ────────────────────────────────────────────────────────────────── + +/// Read `target`'s live `kind:0` event and extract the first valid NIP-OA +/// `auth` tag plus the verified owner pubkey. +pub(crate) fn extract_oa_owner(target_kind0: &nostr::Event) -> Option<(String, [String; 4])> { + let target_hex = target_kind0.pubkey.to_hex(); + let target_compat = nostr::PublicKey::from_hex(&target_hex).ok()?; + + for tag in target_kind0.tags.iter() { + let slice = tag.as_slice(); + if slice.first().map(String::as_str) != Some("auth") || slice.len() != 4 { + continue; + } + let json = serde_json::to_string(slice).ok()?; + match buzz_sdk_pkg::nip_oa::verify_auth_tag(&json, &target_compat) { + Ok(owner) => { + let raw: [String; 4] = [ + slice[0].clone(), + slice[1].clone(), + slice[2].clone(), + slice[3].clone(), + ]; + return Some((owner.to_hex(), raw)); + } + Err(_) => continue, + } + } + None +} + +pub(crate) async fn fetch_kind0( + state: &AppState, + pubkey: &str, +) -> Result, String> { + let events = query_relay( + state, + &[serde_json::json!({ + "kinds": [0u32], + "authors": [pubkey.to_ascii_lowercase()], + "limit": 1, + })], + ) + .await?; + Ok(events.into_iter().next()) +} + +// ── NipIaOwnerProof classifier ──────────────────────────────────────────────── + +/// Result of verifying NIP-OA ownership of `target` by a candidate owner. +/// +/// Condition-clause evaluation is deliberately skipped — per NIP-IA rule 6 the +/// relay verifies the condition; the client only checks structural validity and +/// signature. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case", tag = "result")] +pub enum NipIaOwnerProof { + /// Valid NIP-OA auth tag present, signature checks out, owner matches caller. + Verified, + /// Target kind:0 not found on the relay (or failed NIP-01 verification). + MissingProfile, + /// Kind:0 present but no `auth` tag found. + MissingAuth, + /// More than one `auth` tag in the kind:0 — ambiguous. + MultipleAuthTags, + /// Sole `auth` tag found but has wrong arity or invalid signature/format. + InvalidAuth, + /// Auth tag verifies but the declared owner does not match the caller. + OwnerMismatch { declared_owner: String }, +} + +/// Classify the NIP-OA ownership of `target_kind0` for `candidate_owner_hex`. +/// +/// Rule: count ALL tags whose first element is `"auth"` BEFORE arity check: +/// - 0 auth tags → `MissingAuth` +/// - >1 auth tags → `MultipleAuthTags` +/// - exactly 1 auth tag of wrong arity → `InvalidAuth` +/// - exactly 1 auth tag of correct arity, invalid sig → `InvalidAuth` +/// - exactly 1 auth tag, valid sig, wrong owner → `OwnerMismatch` +/// - exactly 1 auth tag, valid sig, owner matches → `Verified` +/// +/// Does NOT evaluate condition clauses (relay's responsibility). +pub(crate) fn classify_nip_ia_owner_proof( + target_kind0: &nostr::Event, + candidate_owner_hex: &str, +) -> NipIaOwnerProof { + let target_hex = target_kind0.pubkey.to_hex(); + let target_compat = match nostr::PublicKey::from_hex(&target_hex) { + Ok(pk) => pk, + Err(_) => return NipIaOwnerProof::InvalidAuth, + }; + + // Count ALL tags with first element "auth" — arity filtering comes AFTER. + let auth_tags: Vec<&[String]> = target_kind0 + .tags + .iter() + .map(|t| t.as_slice()) + .filter(|s| s.first().map(String::as_str) == Some("auth")) + .collect(); + + match auth_tags.len() { + 0 => return NipIaOwnerProof::MissingAuth, + n if n > 1 => return NipIaOwnerProof::MultipleAuthTags, + _ => {} + } + + let tag_slice = auth_tags[0]; + // Wrong arity → InvalidAuth (not MissingAuth). + if tag_slice.len() != 4 { + return NipIaOwnerProof::InvalidAuth; + } + + let json = match serde_json::to_string(tag_slice) { + Ok(j) => j, + Err(_) => return NipIaOwnerProof::InvalidAuth, + }; + match buzz_sdk_pkg::nip_oa::verify_auth_tag(&json, &target_compat) { + Ok(owner_pk) => { + let owner_hex = owner_pk.to_hex(); + if owner_hex.eq_ignore_ascii_case(candidate_owner_hex) { + NipIaOwnerProof::Verified + } else { + NipIaOwnerProof::OwnerMismatch { + declared_owner: owner_hex, + } + } + } + Err(_) => NipIaOwnerProof::InvalidAuth, + } +} + +// ── Owner-of-agent resolution ───────────────────────────────────────────────── + +#[derive(Debug, Serialize)] +pub struct OwnerOfAgent { + pub owner: String, + pub is_me: bool, +} + +/// Resolve `target`'s NIP-OA owner by reading its live `kind:0`. +#[tauri::command] +pub async fn resolve_oa_owner( + target_pubkey: String, + state: State<'_, AppState>, +) -> Result, String> { + let Some(kind0) = fetch_kind0(&state, &target_pubkey).await? else { + return Ok(None); + }; + let Some((owner_hex, _tag)) = extract_oa_owner(&kind0) else { + return Ok(None); + }; + let my_pubkey = { + let keys = state.keys.lock().map_err(|e| e.to_string())?; + keys.public_key().to_hex() + }; + Ok(Some(OwnerOfAgent { + is_me: my_pubkey.eq_ignore_ascii_case(&owner_hex), + owner: owner_hex, + })) +} + +// ── Archive kind enum ───────────────────────────────────────────────────────── + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum ArchiveKind { + Archive, + Unarchive, +} + +// ── Archive / unarchive request types ──────────────────────────────────────── + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ArchiveRequest { + pub target_pubkey: String, + #[serde(default)] + pub content: String, + #[serde(default)] + pub reason: Option, + #[serde(default)] + pub replaced_by: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct UnarchiveRequest { + pub target_pubkey: String, + #[serde(default)] + pub content: String, + #[serde(default)] + pub reason: Option, +} + +/// Submit a `kind:9035` archive request. +#[tauri::command] +pub async fn archive_identity( + req: ArchiveRequest, + state: State<'_, AppState>, +) -> Result { + let scope = state.capture_archive_scope(8)?; + scoped_archive_operation( + &state, + &scope, + ArchiveKind::Archive, + &req.target_pubkey, + &req.content, + req.reason.as_deref(), + req.replaced_by.as_deref(), + ) + .await +} + +/// Submit a `kind:9036` unarchive request. +#[tauri::command] +pub async fn unarchive_identity( + req: UnarchiveRequest, + state: State<'_, AppState>, +) -> Result { + let scope = state.capture_archive_scope(8)?; + scoped_archive_operation( + &state, + &scope, + ArchiveKind::Unarchive, + &req.target_pubkey, + &req.content, + req.reason.as_deref(), + None, + ) + .await +} + +/// Core non-Tauri implementation: fetch → classify → mint → build/sign → submit. +/// +/// `maybe_` semantics: +/// - Self path: no fetch, no auth tag. +/// - `Verified`: mint a fresh empty-condition auth tag (never copy profile tag). +/// - Any other proof: no auth tag (relay picks Admin or rejects directly). +pub(crate) async fn scoped_archive_operation( + state: &AppState, + scope: &ArchiveScope, + kind: ArchiveKind, + target_pubkey: &str, + content: &str, + reason: Option<&str>, + replaced_by: Option<&str>, +) -> Result { + let api_base_url = match &scope.relay_url_override { + Some(url) => relay_http_base_url(url), + None => crate::relay::relay_api_base_url(), + }; + + // Self path: no fetch, no auth tag. + let auth_tag: Option<[String; 4]> = if scope.actor.eq_ignore_ascii_case(target_pubkey) { + None + } else { + let kind0_events = query_relay_at_with_keys( + state, + &api_base_url, + &[serde_json::json!({ + "kinds": [0u32], + "authors": [target_pubkey.to_ascii_lowercase()], + "limit": 1, + })], + &scope.keys, + None, + ) + .await?; + + match kind0_events.into_iter().next() { + None => None, + Some(kind0) => match classify_nip_ia_owner_proof(&kind0, &scope.actor) { + NipIaOwnerProof::Verified => { + // Mint a fresh empty-condition auth tag from owner keys. + // Never copy the profile tag. + let target_compat = nostr::PublicKey::from_hex(&kind0.pubkey.to_hex()) + .map_err(|e| format!("convert target pubkey: {e}"))?; + let owner_secret = scope.keys.secret_key(); + let owner_compat = nostr::SecretKey::from_slice(owner_secret.as_secret_bytes()) + .map_err(|e| format!("convert owner secret key: {e}"))?; + let owner_compat_keys = nostr::Keys::new(owner_compat); + let tag_json = buzz_sdk_pkg::nip_oa::compute_auth_tag( + &owner_compat_keys, + &target_compat, + "", + ) + .map_err(|e| format!("compute_auth_tag: {e}"))?; + let compat_tag = buzz_sdk_pkg::nip_oa::parse_auth_tag(&tag_json) + .map_err(|e| format!("parse_auth_tag: {e}"))?; + let raw: [String; 4] = [ + compat_tag.as_slice()[0].clone(), + compat_tag.as_slice()[1].clone(), + compat_tag.as_slice()[2].clone(), + compat_tag.as_slice()[3].clone(), + ]; + Some(raw) + } + _ => None, // classifier-negative → relay picks Admin or rejects + }, + } + }; + + let auth_ref = auth_tag.as_ref(); + let builder = match kind { + ArchiveKind::Archive => events::build_archive_identity_request( + target_pubkey, + content, + reason, + replaced_by, + auth_ref, + )?, + ArchiveKind::Unarchive => { + events::build_unarchive_identity_request(target_pubkey, content, reason, auth_ref)? + } + }; + + // Sign here so tests can observe the production event before submission. + let signed = builder + .sign_with_keys(&scope.keys) + .map_err(|e| format!("failed to sign event: {e}"))?; + + #[cfg(test)] + test_hooks::notify_submit(&signed); + + submit_signed_event_at_with_keys(&signed, state, &api_base_url, &scope.keys).await +} + +// ── Test-only submit observation hook ──────────────────────────────────────── +// +// A narrow `#[cfg(test)]` hook that records every signed event just before +// submission. Production code is unchanged — this is gated out of shipping +// builds entirely. +// +// Call `test_hooks::install(observer)` from the test, then run the operation. +// The observer closure receives the signed event. An attempt counter increments +// on every call. Call `test_hooks::reset()` between tests. +#[cfg(test)] +pub(crate) mod test_hooks { + use std::{cell::RefCell, sync::Arc}; + + type ObserverFn = Arc; + + thread_local! { + static OBSERVER: RefCell> = + const { RefCell::new(None) }; + static ATTEMPT_COUNT: RefCell = const { RefCell::new(0) }; + } + + /// Install an observer for the current thread. Replaces any existing one. + pub fn install(f: impl Fn(&nostr::Event) + Send + Sync + 'static) { + OBSERVER.with(|o| { + *o.borrow_mut() = Some(Arc::new(f)); + }); + ATTEMPT_COUNT.with(|c| *c.borrow_mut() = 0); + } + + /// Remove the observer and reset the attempt counter. + pub fn reset() { + OBSERVER.with(|o| *o.borrow_mut() = None); + ATTEMPT_COUNT.with(|c| *c.borrow_mut() = 0); + } + + /// Return the number of production submit calls observed so far. + pub fn attempt_count() -> u32 { + ATTEMPT_COUNT.with(|c| *c.borrow()) + } + + /// Called by `scoped_archive_operation` for each signed event. + pub fn notify_submit(event: &nostr::Event) { + ATTEMPT_COUNT.with(|c| *c.borrow_mut() += 1); + OBSERVER.with(|o| { + if let Some(f) = o.borrow().as_ref() { + f(event); + } + }); + } +} + +// ── Archive snapshot ────────────────────────────────────────────────────────── + +#[derive(Debug, Serialize)] +pub struct ArchivedIdentitiesSnapshot { + pub archived: Vec, +} + +#[derive(Debug, Deserialize)] +pub(crate) struct RelayInformationDocument { + #[serde(default, rename = "self")] + self_: Option, +} + +pub(crate) async fn fetch_relay_self(state: &AppState) -> Result, String> { + let relay_url = relay_ws_url_with_override(state); + let http_url = relay_http_base_url(&relay_url); + let response = state + .http_client + .get(&http_url) + .header("Accept", "application/nostr+json") + .send() + .await + .map_err(|e| classify_request_error(&e))?; + + if !response.status().is_success() { + return Ok(None); + } + let doc = response + .json::() + .await + .map_err(|_| "relay returned malformed NIP-11 document".to_string())?; + + let Some(relay_self) = doc.self_.map(|v| v.to_ascii_lowercase()) else { + return Ok(None); + }; + if relay_self.len() == 64 && relay_self.chars().all(|c| c.is_ascii_hexdigit()) { + Ok(Some(relay_self)) + } else { + Ok(None) + } +} + +pub(crate) fn archived_pubkeys_from_snapshot(snapshot: &nostr::Event) -> Vec { + snapshot + .tags + .iter() + .filter_map(|t| { + let slice = t.as_slice(); + if slice.first().map(String::as_str) == Some("p") && slice.len() >= 2 { + let pk = slice[1].to_ascii_lowercase(); + if pk.len() == 64 && pk.chars().all(|c| c.is_ascii_hexdigit()) { + return Some(pk); + } + } + None + }) + .collect() +} + +#[tauri::command] +pub async fn get_relay_self(state: State<'_, AppState>) -> Result, String> { + fetch_relay_self(&state).await +} + +#[tauri::command] +pub async fn list_archived_identities( + state: State<'_, AppState>, +) -> Result { + let Some(relay_self) = fetch_relay_self(&state).await? else { + return Ok(ArchivedIdentitiesSnapshot { archived: vec![] }); + }; + let events = query_relay( + &state, + &[serde_json::json!({ + "authors": [relay_self.clone()], + "kinds": [13535u32], + "limit": 1, + })], + ) + .await?; + let Some(snapshot) = events.into_iter().next() else { + return Ok(ArchivedIdentitiesSnapshot { archived: vec![] }); + }; + if !snapshot.verify_id() || !snapshot.verify_signature() { + return Ok(ArchivedIdentitiesSnapshot { archived: vec![] }); + } + if !snapshot.pubkey.to_hex().eq_ignore_ascii_case(&relay_self) { + return Ok(ArchivedIdentitiesSnapshot { archived: vec![] }); + } + Ok(ArchivedIdentitiesSnapshot { + archived: archived_pubkeys_from_snapshot(&snapshot), + }) +} + +// ── Tests ───────────────────────────────────────────────────────────────────── + +#[cfg(test)] +mod tests { + use super::*; + use nostr::{EventBuilder, Keys, Kind, Tag}; + + fn kind0_with_auth(agent: &Keys, owner: &Keys) -> nostr::Event { + let agent_hex = agent.public_key().to_hex(); + let agent_compat = nostr::PublicKey::from_hex(&agent_hex).unwrap(); + let owner_compat_secret = + nostr::SecretKey::from_slice(owner.secret_key().as_secret_bytes()).unwrap(); + let owner_compat_keys = nostr::Keys::new(owner_compat_secret); + let tag_json = + buzz_sdk_pkg::nip_oa::compute_auth_tag(&owner_compat_keys, &agent_compat, "") + .expect("compute_auth_tag"); + let compat_tag = buzz_sdk_pkg::nip_oa::parse_auth_tag(&tag_json).unwrap(); + let tag = Tag::parse(compat_tag.as_slice()).unwrap(); + EventBuilder::new(Kind::Metadata, "{}") + .tags([tag]) + .sign_with_keys(agent) + .unwrap() + } + + #[test] + fn extract_oa_owner_returns_owner_for_valid_tag() { + let owner = Keys::generate(); + let agent = Keys::generate(); + let kind0 = kind0_with_auth(&agent, &owner); + let (recovered, raw) = extract_oa_owner(&kind0).expect("auth tag should verify"); + assert_eq!(recovered, owner.public_key().to_hex()); + assert_eq!(raw[0], "auth"); + assert_eq!(raw[2], ""); + assert_eq!(raw[3].len(), 128); + } + + #[test] + fn extract_oa_owner_ignores_kind0_without_auth_tag() { + let agent = Keys::generate(); + let kind0 = EventBuilder::new(Kind::Metadata, "{}") + .sign_with_keys(&agent) + .unwrap(); + assert!(extract_oa_owner(&kind0).is_none()); + } + + #[test] + fn archived_pubkeys_from_snapshot_accepts_only_valid_p_tags() { + let relay = Keys::generate(); + let valid = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; + let uppercase = "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"; + let snapshot = EventBuilder::new(Kind::Custom(13535), "") + .tags([ + Tag::parse(["-"]).unwrap(), + Tag::parse(["p", valid]).unwrap(), + Tag::parse(["p", uppercase]).unwrap(), + Tag::parse(["p", "not-hex"]).unwrap(), + ]) + .sign_with_keys(&relay) + .unwrap(); + let expected = vec![valid.to_string(), uppercase.to_ascii_lowercase()]; + assert_eq!(archived_pubkeys_from_snapshot(&snapshot), expected); + } + + #[test] + fn relay_information_document_reads_nip11_self_field() { + let doc: RelayInformationDocument = serde_json::from_str( + r#"{"name":"test relay","self":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}"#, + ).expect("NIP-11 document"); + assert_eq!( + doc.self_.as_deref(), + Some("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"), + ); + } + + #[test] + fn extract_oa_owner_matches_nip_ia_test_vector() { + const AGENT_HEX: &str = "c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5"; + const OWNER_HEX: &str = "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"; + const CONDITIONS: &str = "kind=1&created_at<1713957000"; + const SIG: &str = "8b7df2575caf0a108374f8471722b233c53f9ff827a8b0f91861966c3b9dd5cb2e189eae9f49d72187674c2f5bd244145e10ff86c9f257ffe65a1ee5f108b369"; + let agent_secret = nostr::SecretKey::from_hex( + "0000000000000000000000000000000000000000000000000000000000000002", + ) + .unwrap(); + let agent_keys = nostr::Keys::new(agent_secret); + assert_eq!(agent_keys.public_key().to_hex(), AGENT_HEX); + let auth_tag = nostr::Tag::parse(["auth", OWNER_HEX, CONDITIONS, SIG]).unwrap(); + let kind0 = EventBuilder::new(Kind::Metadata, "{}") + .tags([auth_tag]) + .sign_with_keys(&agent_keys) + .unwrap(); + let (owner, raw) = extract_oa_owner(&kind0).expect("spec vector should verify"); + assert_eq!(owner, OWNER_HEX); + assert_eq!(raw[1], OWNER_HEX); + assert_eq!(raw[2], CONDITIONS); + assert_eq!(raw[3], SIG); + } + + #[test] + fn archive_request_deserializes_camel_case_payload() { + let req: ArchiveRequest = serde_json::from_str( + r#"{"targetPubkey":"abc","content":"bye","reason":"bot-rebuilt","replacedBy":"def"}"#, + ) + .expect("camelCase archive payload must deserialize"); + assert_eq!(req.target_pubkey, "abc"); + assert_eq!(req.content, "bye"); + assert_eq!(req.reason.as_deref(), Some("bot-rebuilt")); + assert_eq!(req.replaced_by.as_deref(), Some("def")); + + let minimal: UnarchiveRequest = + serde_json::from_str(r#"{"targetPubkey":"abc"}"#).expect("minimal payload"); + assert_eq!(minimal.target_pubkey, "abc"); + assert_eq!(minimal.content, ""); + assert!(minimal.reason.is_none()); + } + + // ── NipIaOwnerProof classifier tests ────────────────────────────────────── + + #[test] + fn classifier_verified_for_valid_owner() { + let owner = Keys::generate(); + let agent = Keys::generate(); + let kind0 = kind0_with_auth(&agent, &owner); + assert_eq!( + classify_nip_ia_owner_proof(&kind0, &owner.public_key().to_hex()), + NipIaOwnerProof::Verified + ); + } + + #[test] + fn classifier_owner_mismatch_when_wrong_caller() { + let owner = Keys::generate(); + let agent = Keys::generate(); + let wrong = Keys::generate(); + let kind0 = kind0_with_auth(&agent, &owner); + match classify_nip_ia_owner_proof(&kind0, &wrong.public_key().to_hex()) { + NipIaOwnerProof::OwnerMismatch { declared_owner } => { + assert_eq!(declared_owner, owner.public_key().to_hex()); + } + other => panic!("expected OwnerMismatch, got {other:?}"), + } + } + + #[test] + fn classifier_missing_auth_for_kind0_without_tag() { + let agent = Keys::generate(); + let kind0 = EventBuilder::new(Kind::Metadata, "{}") + .sign_with_keys(&agent) + .unwrap(); + let owner = Keys::generate(); + assert_eq!( + classify_nip_ia_owner_proof(&kind0, &owner.public_key().to_hex()), + NipIaOwnerProof::MissingAuth + ); + } + + #[test] + fn classifier_multiple_auth_tags() { + let owner = Keys::generate(); + let agent = Keys::generate(); + let kind0_one = kind0_with_auth(&agent, &owner); + let auth_tag = kind0_one + .tags + .iter() + .find(|t| t.as_slice().first().map(String::as_str) == Some("auth")) + .cloned() + .unwrap(); + let kind0_two = EventBuilder::new(Kind::Metadata, "{}") + .tags([auth_tag.clone(), auth_tag]) + .sign_with_keys(&agent) + .unwrap(); + assert_eq!( + classify_nip_ia_owner_proof(&kind0_two, &owner.public_key().to_hex()), + NipIaOwnerProof::MultipleAuthTags + ); + } + + #[test] + fn classifier_invalid_auth_for_bad_signature() { + let owner = Keys::generate(); + let agent = Keys::generate(); + let bad_sig = "0".repeat(128); + let auth_tag = Tag::parse(["auth", &owner.public_key().to_hex(), "", &bad_sig]).unwrap(); + let kind0 = EventBuilder::new(Kind::Metadata, "{}") + .tags([auth_tag]) + .sign_with_keys(&agent) + .unwrap(); + assert_eq!( + classify_nip_ia_owner_proof(&kind0, &owner.public_key().to_hex()), + NipIaOwnerProof::InvalidAuth + ); + } + + /// Finding 6: a wrong-arity auth tag (3 elements instead of 4) must yield + /// `InvalidAuth`, not `MissingAuth`. We count it as "present" (1 auth tag + /// found) but it fails the arity check. + #[test] + fn classifier_wrong_arity_tag_yields_invalid_auth_not_missing() { + let owner = Keys::generate(); + let agent = Keys::generate(); + // Auth tag with only 3 elements — wrong arity. + let short_tag = Tag::parse(["auth", &owner.public_key().to_hex(), ""]).unwrap(); + let kind0 = EventBuilder::new(Kind::Metadata, "{}") + .tags([short_tag]) + .sign_with_keys(&agent) + .unwrap(); + assert_eq!( + classify_nip_ia_owner_proof(&kind0, &owner.public_key().to_hex()), + NipIaOwnerProof::InvalidAuth + ); + } + + /// Finding 6: one malformed (wrong-arity) auth tag plus one valid auth tag + /// must yield `MultipleAuthTags`, not `Verified`. Both are counted before + /// arity filtering. + #[test] + fn classifier_malformed_plus_valid_tag_yields_multiple_auth_tags() { + let owner = Keys::generate(); + let agent = Keys::generate(); + let valid_kind0 = kind0_with_auth(&agent, &owner); + let valid_tag = valid_kind0 + .tags + .iter() + .find(|t| t.as_slice().first().map(String::as_str) == Some("auth")) + .cloned() + .unwrap(); + // A 3-element "auth" tag (wrong arity) — still counts as an auth tag. + let short_tag = Tag::parse(["auth", &owner.public_key().to_hex(), ""]).unwrap(); + let kind0 = EventBuilder::new(Kind::Metadata, "{}") + .tags([short_tag, valid_tag]) + .sign_with_keys(&agent) + .unwrap(); + assert_eq!( + classify_nip_ia_owner_proof(&kind0, &owner.public_key().to_hex()), + NipIaOwnerProof::MultipleAuthTags + ); + } + + #[test] + fn classifier_verified_for_valid_tag_with_kind1_condition() { + let owner = Keys::generate(); + let agent = Keys::generate(); + let agent_hex = agent.public_key().to_hex(); + let agent_compat = nostr::PublicKey::from_hex(&agent_hex).unwrap(); + let owner_compat_secret = + nostr::SecretKey::from_slice(owner.secret_key().as_secret_bytes()).unwrap(); + let owner_compat_keys = nostr::Keys::new(owner_compat_secret); + let tag_json = + buzz_sdk_pkg::nip_oa::compute_auth_tag(&owner_compat_keys, &agent_compat, "kind=1") + .expect("compute_auth_tag with kind=1"); + let compat_tag = buzz_sdk_pkg::nip_oa::parse_auth_tag(&tag_json).unwrap(); + let tag = Tag::parse(compat_tag.as_slice()).unwrap(); + let kind0 = EventBuilder::new(Kind::Metadata, "{}") + .tags([tag]) + .sign_with_keys(&agent) + .unwrap(); + assert_eq!( + classify_nip_ia_owner_proof(&kind0, &owner.public_key().to_hex()), + NipIaOwnerProof::Verified + ); + } + + #[test] + fn classifier_verified_for_expired_bound_profile() { + let owner = Keys::generate(); + let agent = Keys::generate(); + let agent_hex = agent.public_key().to_hex(); + let agent_compat = nostr::PublicKey::from_hex(&agent_hex).unwrap(); + let owner_compat_secret = + nostr::SecretKey::from_slice(owner.secret_key().as_secret_bytes()).unwrap(); + let owner_compat_keys = nostr::Keys::new(owner_compat_secret); + let past = "created_at<1000000000"; + let tag_json = + buzz_sdk_pkg::nip_oa::compute_auth_tag(&owner_compat_keys, &agent_compat, past) + .expect("compute_auth_tag with past condition"); + let compat_tag = buzz_sdk_pkg::nip_oa::parse_auth_tag(&tag_json).unwrap(); + let tag = Tag::parse(compat_tag.as_slice()).unwrap(); + let kind0 = EventBuilder::new(Kind::Metadata, "{}") + .tags([tag]) + .sign_with_keys(&agent) + .unwrap(); + assert_eq!( + classify_nip_ia_owner_proof(&kind0, &owner.public_key().to_hex()), + NipIaOwnerProof::Verified + ); + } + + // ── Relay acceptance gate (ignored, requires live relay + Postgres) ──────── + #[cfg(test)] + #[path = "identity_archive_relay_tests.rs"] + mod relay_acceptance; +} diff --git a/desktop/src-tauri/src/commands/identity_archive/tests/identity_archive_relay_tests.rs b/desktop/src-tauri/src/commands/identity_archive/tests/identity_archive_relay_tests.rs new file mode 100644 index 0000000000..3287be41cf --- /dev/null +++ b/desktop/src-tauri/src/commands/identity_archive/tests/identity_archive_relay_tests.rs @@ -0,0 +1,590 @@ +// These tests require a running relay + Postgres provisioned by the +// Backend Integration CI job. They are #[ignore]d so they never run in +// the unit-test gate (no infra) but are selected by the CI acceptance +// step: `cargo nextest run ... -E 'test(/relay_acceptance::/)' --run-ignored ignored-only`. +// +// Hard-fail semantics: missing env vars panic (no skip, no silent Ok). + +use std::sync::{Arc, Mutex}; + +use super::*; + +fn require_env(name: &str) -> String { + std::env::var(name).unwrap_or_else(|_| panic!("{name} must be set for relay acceptance tests")) +} + +/// The community UUID seeded by CI (from ci.yml, stable). +const TEST_COMMUNITY_ID: &str = "00000000-0000-4000-8000-00000000c0de"; + +/// Build a minimal AppState wired to the test relay URL with deterministic +/// test keys. Does NOT use `build_app_state` to avoid keyring / file-system +/// side effects. +fn make_test_state(owner_keys: &nostr::Keys, relay_api_base_url: &str) -> AppState { + use std::sync::atomic::{AtomicBool, AtomicU16, AtomicU8}; + + let http_client = reqwest::Client::builder() + .resolve("localhost", std::net::SocketAddr::from(([127, 0, 0, 1], 0))) + .pool_idle_timeout(std::time::Duration::from_secs(10)) + .pool_max_idle_per_host(1) + .build() + .unwrap(); + + let ws_url = relay_api_base_url + .replacen("http://", "ws://", 1) + .replacen("https://", "wss://", 1); + + AppState { + keys: std::sync::Mutex::new(owner_keys.clone()), + identity_storage: AtomicU8::new(0), + http_client: http_client.clone(), + media_fetch_client: crate::app_state::build_media_fetch_client().unwrap(), + relay_url_override: std::sync::Mutex::new(Some(ws_url)), + managed_agent_restore_pending: AtomicBool::new(false), + managed_agent_profile_reconcile_enabled: AtomicBool::new(true), + shutdown_started: AtomicBool::new(false), + managed_agent_runtime_transition: std::sync::Mutex::new(()), + identity_mutation: std::sync::Mutex::new(()), + managed_agents_store_lock: std::sync::Mutex::new(()), + channel_templates_store_lock: std::sync::Mutex::new(()), + managed_agent_processes: std::sync::Mutex::new(std::collections::HashMap::new()), + session_config_cache: std::sync::Mutex::new(std::collections::HashMap::new()), + huddle_state: std::sync::Mutex::new(crate::huddle::HuddleState::default()), + huddle_audio: Default::default(), + app_handle: std::sync::Mutex::new(None), + media_proxy_port: AtomicU16::new(0), + keyring_locked: AtomicBool::new(false), + identity_lost: AtomicBool::new(false), + reset_failed: AtomicBool::new(false), + prevent_sleep: std::sync::Arc::new(std::sync::Mutex::new( + crate::prevent_sleep::PreventSleepState::default(), + )), + #[cfg(feature = "mesh-llm")] + mesh_llm_runtime: tokio::sync::Mutex::new(None), + #[cfg(feature = "mesh-llm")] + mesh_recovery: crate::mesh_llm::MeshRecoveryState::default(), + #[cfg(feature = "mesh-llm")] + mesh_coordinator: tokio::sync::Mutex::new(None), + pending_owned_channels: std::sync::Mutex::new(std::collections::HashSet::new()), + workspace_epoch: std::sync::atomic::AtomicU64::new(0), + workspace_write: std::sync::Mutex::new(()), + } +} + +/// Provision a test agent on the relay: register a kind:0 profile with +/// a valid NIP-OA auth tag (owner-of-agent attestation). +async fn provision_test_agent( + state: &AppState, + owner_keys: &nostr::Keys, + agent_keys: &nostr::Keys, + relay_api_base_url: &str, +) -> Result<(), String> { + let agent_hex = agent_keys.public_key().to_hex(); + let agent_compat = + nostr::PublicKey::from_hex(&agent_hex).map_err(|e| format!("agent pubkey: {e}"))?; + let owner_secret = owner_keys.secret_key(); + let owner_compat = nostr::SecretKey::from_slice(owner_secret.as_secret_bytes()) + .map_err(|e| format!("owner secret convert: {e}"))?; + let owner_compat_keys = nostr::Keys::new(owner_compat); + let tag_json = buzz_sdk_pkg::nip_oa::compute_auth_tag(&owner_compat_keys, &agent_compat, "") + .map_err(|e| format!("compute_auth_tag: {e}"))?; + let compat_tag = buzz_sdk_pkg::nip_oa::parse_auth_tag(&tag_json) + .map_err(|e| format!("parse_auth_tag: {e}"))?; + let tag = nostr::Tag::parse(compat_tag.as_slice()).map_err(|e| format!("Tag::parse: {e}"))?; + + let builder = nostr::EventBuilder::new(nostr::Kind::Metadata, "{}") + .tags([tag]) + .allow_self_tagging(); + let event = builder + .sign_with_keys(agent_keys) + .map_err(|e| format!("sign kind:0: {e}"))?; + + let url = format!("{relay_api_base_url}/events"); + let body_bytes = nostr::JsonUtil::as_json(&event).into_bytes(); + let auth = crate::relay::build_nip98_auth_header_for_keys( + agent_keys, + &reqwest::Method::POST, + &url, + &body_bytes, + ) + .map_err(|e| format!("nip98 agent: {e}"))?; + let response = state + .http_client + .post(&url) + .header("Authorization", auth) + .header("Content-Type", "application/json") + .body(body_bytes) + .send() + .await + .map_err(|e| format!("submit agent kind:0: {e}"))?; + + if !response.status().is_success() { + let text = response.text().await.unwrap_or_default(); + return Err(format!("agent kind:0 rejected: {text}")); + } + Ok(()) +} + +/// Assert that the actor has NO row in `relay_members` for `TEST_COMMUNITY_ID`. +/// This makes Self and Admin consent paths impossible — Owner is the only path. +async fn assert_actor_not_relay_member(db_url: &str, actor_pubkey: &str) -> Result<(), String> { + use tokio_postgres::NoTls; + let (client, connection) = tokio_postgres::connect(db_url, NoTls) + .await + .map_err(|e| format!("postgres connect: {e}"))?; + tokio::spawn(async move { + if let Err(e) = connection.await { + eprintln!("postgres connection error: {e}"); + } + }); + let rows = client + .query( + // Cast the UUID column to text so tokio_postgres can bind a &str parameter. + // $1::uuid would require a Uuid type; community_id::text = $1 keeps &str. + "SELECT 1 FROM relay_members WHERE community_id::text = $1 AND pubkey = $2", + &[&TEST_COMMUNITY_ID, &actor_pubkey], + ) + .await + .map_err(|e| format!("postgres relay_members query: {e}"))?; + if !rows.is_empty() { + return Err(format!( + "actor {actor_pubkey} unexpectedly found in relay_members — Self/Admin paths not impossible" + )); + } + Ok(()) +} + +/// Assert `consent_path = 'owner'` in `archived_identities` for the given +/// community and agent pubkey. +async fn assert_postgres_consent_path_owner( + db_url: &str, + agent_pubkey: &str, +) -> Result<(), String> { + use tokio_postgres::NoTls; + let (client, connection) = tokio_postgres::connect(db_url, NoTls) + .await + .map_err(|e| format!("postgres connect: {e}"))?; + tokio::spawn(async move { + if let Err(e) = connection.await { + eprintln!("postgres connection error: {e}"); + } + }); + // Scope assertion by community AND pubkey. + let rows = client + .query( + // Cast the UUID column to text so tokio_postgres can bind a &str parameter. + "SELECT consent_path FROM archived_identities \ + WHERE community_id::text = $1 AND pubkey = $2", + &[&TEST_COMMUNITY_ID, &agent_pubkey], + ) + .await + .map_err(|e| format!("postgres query: {e}"))?; + if rows.is_empty() { + return Err(format!( + "no archived_identities row for {agent_pubkey} in community {TEST_COMMUNITY_ID}" + )); + } + let path: &str = rows[0].get(0); + if path != "owner" { + return Err(format!( + "expected consent_path='owner', got '{path}' for {agent_pubkey}" + )); + } + Ok(()) +} + +/// Query the relay for delta events (kind:8002 or kind:8003) associated with +/// a given `request_event_id` (via the `e` tag). Returns the first matching +/// event if found. +async fn query_nipia_delta( + state: &AppState, + _relay_url: &str, + kind: u32, + request_event_id: &str, +) -> Result, String> { + let events = crate::relay::query_relay( + state, + &[serde_json::json!({ + "kinds": [kind], + "#e": [request_event_id], + "limit": 1, + })], + ) + .await?; + Ok(events.into_iter().next()) +} + +/// Extract the `consent` tag value from a relay-signed delta event. +/// The consent tag format is `["consent", consent_path, actor_pubkey]`. +fn extract_consent_tag(event: &nostr::Event) -> Option { + event + .tags + .iter() + .find(|t| t.as_slice().first().map(String::as_str) == Some("consent")) + .and_then(|t| t.as_slice().get(1).cloned()) +} + +/// Extract the actor from the `consent` tag (`["consent", path, actor]`). +fn extract_consent_actor(event: &nostr::Event) -> Option { + event + .tags + .iter() + .find(|t| t.as_slice().first().map(String::as_str) == Some("consent")) + .and_then(|t| t.as_slice().get(2).cloned()) +} + +// ── Narrow observation seam ────────────────────────────────────────────────── +// +// The seam uses `test_hooks` from the parent module — a `#[cfg(test)]` +// thread-local hook installed by `test_hooks::install`. `scoped_archive_operation` +// calls `test_hooks::notify_submit(&signed)` before every relay POST, so the +// observer sees the PRODUCTION-signed event with the PRODUCTION auth tags. +// Gutting the fresh-mint in `scoped_archive_operation` → observer sees no auth +// tag → wire-form assertions fail locally without a live relay. + +/// Helper: install the thread-local hook, run the production operation, +/// remove the hook, and return both the result and the captured event. +async fn run_with_observation( + state: &AppState, + scope: &ArchiveScope, + kind: ArchiveKind, + target_pubkey: &str, +) -> ( + Result, + Option, + u32, +) { + // Capture the production-signed event via the thread-local hook. + let captured: Arc>> = Arc::new(Mutex::new(None)); + let captured_clone = Arc::clone(&captured); + + super::test_hooks::install(move |ev| { + *captured_clone.lock().unwrap() = Some(ev.clone()); + }); + + let result = scoped_archive_operation(state, scope, kind, target_pubkey, "", None, None).await; + let attempts = super::test_hooks::attempt_count(); + super::test_hooks::reset(); + + let event = captured.lock().unwrap().clone(); + (result, event, attempts) +} + +// ── Tests ───────────────────────────────────────────────────────────────────── + +#[tokio::test] +#[ignore] +async fn owner_consent_archive_9035_records_owner_path() { + let db_url = require_env("DATABASE_URL"); + let relay_url = require_env("RELAY_API_URL"); + + let owner_keys = nostr::Keys::generate(); + let agent_keys = nostr::Keys::generate(); + let agent_pubkey = agent_keys.public_key().to_hex(); + let owner_pubkey = owner_keys.public_key().to_hex(); + + let state = make_test_state(&owner_keys, &relay_url); + + // Assert actor (owner) has NO relay_members row — Self impossible (different + // keys) AND Admin impossible (no membership). Owner path is the only option. + assert_actor_not_relay_member(&db_url, &owner_pubkey) + .await + .expect("actor must not be in relay_members"); + + // Provision the agent (kind:0 with NIP-OA auth tag). + provision_test_agent(&state, &owner_keys, &agent_keys, &relay_url) + .await + .expect("provision_test_agent"); + + assert_ne!( + owner_pubkey, agent_pubkey, + "owner != agent (Self impossible)" + ); + + let scope = state + .capture_archive_scope(8) + .expect("capture_archive_scope"); + + // Execute the production operation via the seam — captures the production-signed event. + let (result, observed_event, _) = + run_with_observation(&state, &scope, ArchiveKind::Archive, &agent_pubkey).await; + let result = result.expect("scoped_archive_operation 9035"); + + // ── Assert wire form: exactly one auth tag, empty condition, distinct from profile tag ── + let observed_event = observed_event.expect("must have observed the production-signed event"); + let auth_tags: Vec<&[String]> = observed_event + .tags + .iter() + .map(|t| t.as_slice()) + .filter(|s| s.first().map(String::as_str) == Some("auth")) + .collect(); + assert_eq!( + auth_tags.len(), + 1, + "exactly one auth tag must be on the wire event (finding 5)" + ); + assert_eq!( + auth_tags[0][2], "", + "wire auth tag must have empty condition (fresh mint, not profile tag copy)" + ); + + // ── Assert Postgres consent_path = 'owner' scoped by community ── + assert_postgres_consent_path_owner(&db_url, &agent_pubkey) + .await + .expect("consent_path must be 'owner' in Postgres"); + + // ── Assert kind:8002 delta emitted with consent=owner and correct actor ── + let request_event_id = &result.event_id; + let delta_8002 = query_nipia_delta(&state, &relay_url, 8002, request_event_id) + .await + .expect("query kind:8002 delta"); + let delta = delta_8002 + .as_ref() + .expect("kind:8002 delta must be emitted after owner-path archive"); + let consent = extract_consent_tag(delta).expect("kind:8002 must have consent tag"); + assert_eq!(consent, "owner", "kind:8002 consent must be 'owner'"); + let actor = extract_consent_actor(delta).expect("kind:8002 must carry actor in consent tag"); + assert!( + actor.eq_ignore_ascii_case(&owner_pubkey), + "kind:8002 actor must be the owner, got {actor}" + ); +} + +#[tokio::test] +#[ignore] +async fn owner_consent_unarchive_9036_emits_owner_delta() { + let db_url = require_env("DATABASE_URL"); + let relay_url = require_env("RELAY_API_URL"); + + let owner_keys = nostr::Keys::generate(); + let agent_keys = nostr::Keys::generate(); + let agent_pubkey = agent_keys.public_key().to_hex(); + let owner_pubkey = owner_keys.public_key().to_hex(); + + let state = make_test_state(&owner_keys, &relay_url); + + // Assert actor not in relay_members. + assert_actor_not_relay_member(&db_url, &owner_pubkey) + .await + .expect("actor must not be in relay_members"); + + provision_test_agent(&state, &owner_keys, &agent_keys, &relay_url) + .await + .expect("provision_test_agent"); + + // First archive (owner path). + let scope = state + .capture_archive_scope(8) + .expect("capture_archive_scope"); + scoped_archive_operation( + &state, + &scope, + ArchiveKind::Archive, + &agent_pubkey, + "", + None, + None, + ) + .await + .expect("archive first"); + + // Now unarchive with observation. + let scope2 = state + .capture_archive_scope(8) + .expect("capture_archive_scope 2"); + let result = scoped_archive_operation( + &state, + &scope2, + ArchiveKind::Unarchive, + &agent_pubkey, + "", + None, + None, + ) + .await + .expect("scoped_archive_operation 9036"); + + // ── Assert kind:8003 delta with consent=owner and correct actor ── + let request_event_id = &result.event_id; + let delta_8003 = query_nipia_delta(&state, &relay_url, 8003, request_event_id) + .await + .expect("query kind:8003 delta"); + let delta = delta_8003 + .as_ref() + .expect("kind:8003 delta must be emitted after owner-path unarchive"); + let consent = extract_consent_tag(delta).expect("kind:8003 must have consent tag"); + assert_eq!(consent, "owner", "kind:8003 consent must be 'owner'"); + let actor = extract_consent_actor(delta).expect("kind:8003 must carry actor in consent tag"); + assert!( + actor.eq_ignore_ascii_case(&owner_pubkey), + "kind:8003 actor must be the owner, got {actor}" + ); +} + +#[tokio::test] +#[ignore] +async fn expired_bound_profile_mints_fresh_empty_condition_tag() { + let relay_url = require_env("RELAY_API_URL"); + + let owner_keys = nostr::Keys::generate(); + let agent_keys = nostr::Keys::generate(); + let agent_pubkey = agent_keys.public_key().to_hex(); + + // Provision with a past-expired condition. + let agent_hex = agent_keys.public_key().to_hex(); + let agent_compat = nostr::PublicKey::from_hex(&agent_hex).unwrap(); + let owner_secret = owner_keys.secret_key(); + let owner_compat = nostr::SecretKey::from_slice(owner_secret.as_secret_bytes()).unwrap(); + let owner_compat_keys = nostr::Keys::new(owner_compat); + let past = "created_at<1000000000"; + let tag_json = + buzz_sdk_pkg::nip_oa::compute_auth_tag(&owner_compat_keys, &agent_compat, past).unwrap(); + let compat_tag = buzz_sdk_pkg::nip_oa::parse_auth_tag(&tag_json).unwrap(); + let tag = nostr::Tag::parse(compat_tag.as_slice()).unwrap(); + + let state = make_test_state(&owner_keys, &relay_url); + let builder = nostr::EventBuilder::new(nostr::Kind::Metadata, "{}") + .tags([tag]) + .allow_self_tagging(); + let event = builder.sign_with_keys(&agent_keys).unwrap(); + let url = format!("{relay_url}/events"); + let body = nostr::JsonUtil::as_json(&event).into_bytes(); + let auth = crate::relay::build_nip98_auth_header_for_keys( + &agent_keys, + &reqwest::Method::POST, + &url, + &body, + ) + .unwrap(); + let resp = state + .http_client + .post(&url) + .header("Authorization", auth) + .header("Content-Type", "application/json") + .body(body) + .send() + .await + .expect("submit kind:0 with expired tag"); + assert!(resp.status().is_success(), "kind:0 submit failed"); + + // Use the production seam to capture the wire event. + let scope = state.capture_archive_scope(8).unwrap(); + + let (result, observed_event, _) = + run_with_observation(&state, &scope, ArchiveKind::Archive, &agent_pubkey).await; + + // NIP-IA §Published-profile rule: time clauses MUST NOT be evaluated by + // the relay — an expired profile MUST still be accepted for the owner path. + // `result.expect()` proves the zombie-agent path is not broken. + let relay_result = result.expect( + "expired-profile owner-path archive must succeed: NIP-IA time clauses must not be evaluated" + ); + + // The submitted request MUST carry exactly one fresh empty-condition auth tag. + let observed_event = observed_event.expect("must have observed a production-signed event"); + let auth_tags: Vec<&[String]> = observed_event + .tags + .iter() + .map(|t| t.as_slice()) + .filter(|s| s.first().map(String::as_str) == Some("auth")) + .collect(); + assert_eq!( + auth_tags.len(), + 1, + "exactly one auth tag must be on the wire (fresh mint)" + ); + assert_eq!( + auth_tags[0][2], "", + "fresh-minted tag must have EMPTY condition (not the expired profile condition)" + ); + + // Assert owner-path archive state via kind:8002 delta. + let request_event_id = &relay_result.event_id; + let delta_8002 = query_nipia_delta(&state, &relay_url, 8002, request_event_id) + .await + .expect("query kind:8002 delta for expired-profile test"); + let delta = delta_8002.as_ref().expect( + "kind:8002 delta must be emitted after owner-path archive of expired-profile agent", + ); + let consent = extract_consent_tag(delta) + .expect("kind:8002 must have consent tag for expired-profile owner path"); + assert_eq!( + consent, "owner", + "expired-profile owner-path kind:8002 consent must be 'owner'" + ); +} + +#[tokio::test] +#[ignore] +async fn self_requests_are_authless() { + let relay_url = require_env("RELAY_API_URL"); + + let owner_keys = nostr::Keys::generate(); + let owner_pubkey = owner_keys.public_key().to_hex(); + + let state = make_test_state(&owner_keys, &relay_url); + let scope = state.capture_archive_scope(8).unwrap(); + + // Self-archive: actor == target → no auth tag. + let (result, observed_event, _) = + run_with_observation(&state, &scope, ArchiveKind::Archive, &owner_pubkey).await; + + // The observed production event must have ZERO auth tags — self path bypasses auth-tag + // computation entirely. + let observed_event = observed_event.expect("must have observed a production-signed event"); + let auth_tags: Vec<_> = observed_event + .tags + .iter() + .filter(|t| t.as_slice().first().map(String::as_str) == Some("auth")) + .collect(); + assert_eq!( + auth_tags.len(), + 0, + "self archive must send NO auth tag on the wire" + ); + + // Self-unarchive: also authless. + let scope2 = state.capture_archive_scope(8).unwrap(); + let (_, event2, _) = + run_with_observation(&state, &scope2, ArchiveKind::Unarchive, &owner_pubkey).await; + let event2 = event2.expect("must have observed event 2"); + let auth_tags2: Vec<_> = event2 + .tags + .iter() + .filter(|t| t.as_slice().first().map(String::as_str) == Some("auth")) + .collect(); + assert_eq!( + auth_tags2.len(), + 0, + "self unarchive must also send NO auth tag" + ); + + // The relay's accept/reject decision for self is separate from our assertion. + let _ = result; +} + +#[tokio::test] +#[ignore] +async fn relay_rejection_is_direct_no_retry() { + let relay_url = require_env("RELAY_API_URL"); + + let owner_keys = nostr::Keys::generate(); + let unrelated_keys = nostr::Keys::generate(); + let unrelated_pubkey = unrelated_keys.public_key().to_hex(); + + let state = make_test_state(&owner_keys, &relay_url); + + // Target has no kind:0 → classifier-negative → no auth tag → relay rejects. + // The operation has NO retry loop — one submit attempt, one result. + let scope = state.capture_archive_scope(8).unwrap(); + let (result, _, attempts) = + run_with_observation(&state, &scope, ArchiveKind::Archive, &unrelated_pubkey).await; + + // Assert the relay rejected (no authority). + assert!(result.is_err(), "expected relay rejection, got success"); + + // Assert exactly ONE attempt — the observer count proves no retry loop ran. + assert_eq!( + attempts, 1, + "relay rejection must produce exactly one submit attempt (no retry)" + ); +} diff --git a/desktop/src-tauri/src/commands/workspace.rs b/desktop/src-tauri/src/commands/workspace.rs index aa88bfe39a..8fd46476ca 100644 --- a/desktop/src-tauri/src/commands/workspace.rs +++ b/desktop/src-tauri/src/commands/workspace.rs @@ -165,16 +165,20 @@ pub async fn apply_workspace( // ── Apply all state changes (nothing below can fail) ────────────────── { - let mut override_guard = state.relay_url_override.lock().map_err(|e| e.to_string())?; - *override_guard = Some(relay_url); - } - // Reset the Rust-side admission gate when switching workspace/community, - // matching `resetRateLimitGate()` on the TS side (useCommunityInit.ts:38). - crate::relay_admission::reset_gate_for_workspace_change(); + let _epoch_guard = state.begin_workspace_write()?; + { + let mut override_guard = + state.relay_url_override.lock().map_err(|e| e.to_string())?; + *override_guard = Some(relay_url); + } + // Reset the Rust-side admission gate when switching workspace/community, + // matching `resetRateLimitGate()` on the TS side (useCommunityInit.ts:38). + crate::relay_admission::reset_gate_for_workspace_change(); - if let Some(keys) = parsed_keys { - let mut keys_guard = state.keys.lock().map_err(|e| e.to_string())?; - *keys_guard = keys; + if let Some(keys) = parsed_keys { + let mut keys_guard = state.keys.lock().map_err(|e| e.to_string())?; + *keys_guard = keys; + } } // Keep the backend-side reconcile guard aligned with the frontend diff --git a/desktop/src-tauri/src/egress_guard_tests.rs b/desktop/src-tauri/src/egress_guard_tests.rs index f487c8ce16..ac54e44807 100644 --- a/desktop/src-tauri/src/egress_guard_tests.rs +++ b/desktop/src-tauri/src/egress_guard_tests.rs @@ -254,6 +254,12 @@ const EVENTS_INVENTORY: &[(&str, usize, usize)] = &[ // Mock-relay route in its in-file tests; production publish goes through // the guarded boundary-1 funnel (`submit_signed_event_at_with_keys`). ("src/commands/personas/sharing.rs", 1, 0), + // Relay acceptance tests in-crate (#[cfg(test)] #[ignore]); not production egress. + ( + "src/commands/identity_archive/tests/identity_archive_relay_tests.rs", + 2, + 0, + ), ]; // Needles are assembled at runtime so this scan file itself contains no diff --git a/desktop/src-tauri/src/lib.rs b/desktop/src-tauri/src/lib.rs index 2847b87877..bcd432e3cb 100644 --- a/desktop/src-tauri/src/lib.rs +++ b/desktop/src-tauri/src/lib.rs @@ -44,6 +44,7 @@ mod tray_menu; mod util; #[cfg(target_os = "linux")] pub mod webkit_rendering; +mod workspace_epoch; use app_state::{build_app_state, resolve_persisted_identity, AppState}; use builderlab::*; use commands::*; @@ -756,6 +757,7 @@ pub fn run() { list_archived_identities, get_relay_self, resolve_oa_owner, + get_owned_agent_inventory, list_relay_agents, list_managed_agents, list_managed_agent_runtimes, diff --git a/desktop/src-tauri/src/workspace_epoch.rs b/desktop/src-tauri/src/workspace_epoch.rs new file mode 100644 index 0000000000..7fc7afd82a --- /dev/null +++ b/desktop/src-tauri/src/workspace_epoch.rs @@ -0,0 +1,60 @@ +//! Workspace-epoch seqlock: types exported by [`crate::app_state`]. +//! +//! [`ArchiveScope`] is an immutable snapshot of the workspace state captured +//! atomically via the seqlock protocol implemented in +//! [`AppState::capture_archive_scope`]. [`WorkspaceEpochWriteGuard`] is the +//! RAII writer guard obtained via [`AppState::begin_workspace_write`]. + +use std::sync::atomic::{AtomicU64, Ordering}; + +/// A scoped snapshot of the active workspace state captured atomically via +/// the seqlock protocol. All I/O in a scoped archive operation consumes only +/// this scope — no guard is held across any await. +#[derive(Clone)] +pub struct ArchiveScope { + pub keys: nostr::Keys, + /// Owner pubkey (hex) derived from `keys` at capture time. + pub actor: String, + /// Workspace relay URL override at capture time. `None` means "use the + /// env-var / build-time default" (same semantics as `relay_url_override`). + pub relay_url_override: Option, + /// Epoch value at capture time (even). Callers may use this for optional + /// UX-only final checks; it is NOT the safety invariant (the immutable + /// scope itself is). + // Only read in tests; intentionally kept for caller-side UX assertions. + #[allow(dead_code)] + pub workspace_epoch: u64, +} + +/// Deliberately hide the secret key from debug output to prevent accidental +/// key exposure in logs, panics, or test output. +impl std::fmt::Debug for ArchiveScope { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("ArchiveScope") + .field("actor", &self.actor) + .field("relay_url_override", &self.relay_url_override) + .field("workspace_epoch", &self.workspace_epoch) + .field("keys", &"") + .finish() + } +} + +/// RAII guard that serializes all production workspace-state writers and +/// restores the epoch to the next even value on every exit path. +/// +/// Obtained via [`crate::app_state::AppState::begin_workspace_write`]. The +/// internal mutex (`workspace_write`) is locked for the lifetime of this guard, +/// preventing any concurrent writer from interleaving their epoch increments +/// and thereby corrupting the seqlock parity invariant. +pub struct WorkspaceEpochWriteGuard<'a> { + pub(crate) epoch: &'a AtomicU64, + pub(crate) _guard: std::sync::MutexGuard<'a, ()>, +} + +impl Drop for WorkspaceEpochWriteGuard<'_> { + fn drop(&mut self) { + // Restore even → writer is done. SeqCst ensures all prior writes are + // visible before readers observe the even epoch. + self.epoch.fetch_add(1, Ordering::SeqCst); + } +} diff --git a/desktop/src/features/agents/ui/PersonaActionsMenu.tsx b/desktop/src/features/agents/ui/PersonaActionsMenu.tsx index 30bb7fff6e..b906ed98e8 100644 --- a/desktop/src/features/agents/ui/PersonaActionsMenu.tsx +++ b/desktop/src/features/agents/ui/PersonaActionsMenu.tsx @@ -2,6 +2,7 @@ import { CopyPlus, EllipsisVertical, Pencil, + Server, Share2, Trash2, } from "lucide-react"; @@ -25,6 +26,7 @@ export function PersonaActionsMenu({ onShare, onDeactivate, onDelete, + onViewInstances, }: { isActionPending: boolean; isPending: boolean; @@ -39,6 +41,8 @@ export function PersonaActionsMenu({ ) => void; onDeactivate: (persona: AgentPersona) => void; onDelete: (persona: AgentPersona) => void; + /** Optional: open the Instances Sheet for this persona's owner inventory. */ + onViewInstances?: (persona: AgentPersona) => void; }) { const disabled = isActionPending || isPending; const canEdit = !persona.sourceTeam; @@ -78,6 +82,18 @@ export function PersonaActionsMenu({ Share + {onViewInstances ? ( + <> + + onViewInstances(persona)} + > + + Instances + + + ) : null} {persona.sourceTeam ? ( diff --git a/desktop/src/features/agents/ui/UnifiedAgentsSection.tsx b/desktop/src/features/agents/ui/UnifiedAgentsSection.tsx index 212d9bc96e..03af84e38e 100644 --- a/desktop/src/features/agents/ui/UnifiedAgentsSection.tsx +++ b/desktop/src/features/agents/ui/UnifiedAgentsSection.tsx @@ -1,9 +1,11 @@ import * as React from "react"; -import { AlertTriangle, ChevronDown, ChevronRight } from "lucide-react"; +import { AlertTriangle, ChevronDown, ChevronRight, Server } from "lucide-react"; import { resolveAgentCardModelLabel } from "@/features/agents/lib/agentCardModelLabel"; import { friendlyAgentLastError } from "@/features/agents/lib/friendlyAgentLastError"; import { isManagedAgentActive } from "@/features/agents/lib/managedAgentControlActions"; +import { InstancesSheet } from "@/features/identity-archive/InstancesSheet"; +import { useOwnedAgentInventoryQuery } from "@/features/identity-archive/hooks"; import { useUserProfileQuery } from "@/features/profile/hooks"; import type { AgentPersona, ManagedAgent } from "@/shared/api/types"; import type { ProfilePanelOpenOptions } from "@/shared/context/ProfilePanelContext"; @@ -105,6 +107,16 @@ export function UnifiedAgentsSection(props: UnifiedAgentsSectionProps) { [personas, agents], ); const [collapsed, setCollapsed] = React.useState>(new Set()); + // Instances Sheet state: track the persona that opened the sheet. + const [instancesSheetPersona, setInstancesSheetPersona] = + React.useState(null); + const instancesSheetOpen = instancesSheetPersona !== null; + // Global unknown relay agents sheet — opened from the "Unknown relay agents" group. + const [unknownSheetOpen, setUnknownSheetOpen] = React.useState(false); + + // Pre-fetch the inventory so the start-control safeguard can consult it + // without a per-card fetch. Enabled when the section is visible (agents loaded). + const inventoryQuery = useOwnedAgentInventoryQuery(!isAgentsLoading); const { fileInputRef, isDragOver, @@ -122,6 +134,43 @@ export function UnifiedAgentsSection(props: UnifiedAgentsSectionProps) { }); } + /** + * Start-control safeguard (Finding 4): before starting a new instance, + * check the relay inventory for THIS persona's instances only (byPersonaId). + * If inventory is loading/untrusted OR there is already an active + * (non-archived) relay instance for this persona, open the Sheet instead + * of blindly minting a new one. + */ + function handleStartPersonaWithSafeguard(persona: AgentPersona) { + const inventory = inventoryQuery.data; + // If inventory hasn't loaded yet or isn't trusted, show the Sheet so the + // user can decide with full information rather than risking a 3rd instance. + if (!inventory?.archiveStateTrusted) { + openInstancesSheet(persona); + return; + } + // Count active (non-archived) relay instances for THIS persona only. + const personaInstances = inventory.byPersonaId[persona.id] ?? []; + const activeRelayInstances = personaInstances.filter( + (i) => i.archiveState.isArchived !== true, + ); + if (activeRelayInstances.length >= 1) { + // There is at least one active relay instance for this persona; open the + // Sheet to let the user inspect and decide rather than minting a duplicate. + openInstancesSheet(persona); + return; + } + // Safe to start — no active relay instance found for this persona. + onStartPersona(persona); + } + + /** + * Open the Instances Sheet for `persona`. + */ + function openInstancesSheet(persona: AgentPersona) { + setInstancesSheetPersona(persona); + } + useFeedbackToasts(actionNoticeMessage, actionErrorMessage); useFeedbackToasts(personaFeedbackNoticeMessage, personaFeedbackErrorMessage); const isLoading = isAgentsLoading || isPersonasLoading; @@ -155,24 +204,60 @@ export function UnifiedAgentsSection(props: UnifiedAgentsSectionProps) {
{groups.map((group) => { const profileAgent = pickProfileAgent(group.agents); + // Count relay instances for THIS persona from the grouped view model. + const personaInstances = + inventoryQuery.data?.byPersonaId[group.persona.id] ?? []; + const relayInstanceCount = personaInstances.length; + // Card-level instances indicator id for aria-controls. + const instancesButtonId = `instances-sheet-${group.persona.id}`; return ( ( - - onSharePersona(persona, linkedAgent, effectiveAvatarUrl) - } - /> +
+ {/* Card-level focusable Instances action (Finding 3) */} + {relayInstanceCount > 1 || + (profileAgent == null && relayInstanceCount >= 1) ? ( + + ) : null} + + onSharePersona( + persona, + linkedAgent, + effectiveAvatarUrl, + ) + } + onViewInstances={ + relayInstanceCount > 0 + ? (p) => openInstancesSheet(p) + : undefined + } + /> +
)} agent={profileAgent} defaultModel={defaultModel} @@ -185,7 +270,7 @@ export function UnifiedAgentsSection(props: UnifiedAgentsSectionProps) { onOpenPersonaProfile={onOpenPersonaProfile} onRestartAgent={onRestartAgent} onStartAgent={onStartAgent} - onStartPersona={onStartPersona} + onStartPersona={handleStartPersonaWithSafeguard} /> ); })} @@ -212,6 +297,28 @@ export function UnifiedAgentsSection(props: UnifiedAgentsSectionProps) { onStartAgent={onStartAgent} /> ) : null} + {/* Relay-unknown instances: agents on the relay with no parseable persona_id. + These are only discoverable here — not inside any persona's Sheet. */} + {(inventoryQuery.data?.unknown ?? []).length > 0 ? ( +
+ +
+ ) : null} {ungrouped.length > 0 ? ( ) : null} + + { + if (!o) setInstancesSheetPersona(null); + }} + onOpenProfile={onOpenAgentProfile} + /> + {/* Global unknown relay agents sheet — persona=null shows only the unknown bucket */} + ); } diff --git a/desktop/src/features/identity-archive/InstancesSheet.tsx b/desktop/src/features/identity-archive/InstancesSheet.tsx new file mode 100644 index 0000000000..e6c671a353 --- /dev/null +++ b/desktop/src/features/identity-archive/InstancesSheet.tsx @@ -0,0 +1,418 @@ +import * as React from "react"; +import { + Archive, + ArchiveRestore, + Loader2, + MonitorOff, + RefreshCw, + Server, + Wifi, + WifiOff, +} from "lucide-react"; + +import { + useArchiveIdentityMutation, + useOwnedAgentInventoryQuery, + useUnarchiveIdentityMutation, +} from "./hooks"; +import { ArchiveConfirmDialog } from "@/features/profile/ui/ArchiveConfirmDialog"; +import { ProfileAvatar } from "@/features/profile/ui/ProfileAvatar"; +import { usePresenceQuery } from "@/features/presence/hooks"; +import { truncatePubkey } from "@/shared/lib/pubkey"; +import type { + NipIaOwnerProof, + OwnedAgentInstance, + OwnedAgentInventorySnapshot, +} from "@/shared/api/tauriIdentityArchive"; +import type { AgentPersona, PresenceLookup } from "@/shared/api/types"; +import { Badge } from "@/shared/ui/badge"; +import { Button } from "@/shared/ui/button"; +import { + Sheet, + SheetContent, + SheetHeader, + SheetTitle, +} from "@/shared/ui/sheet"; + +// ── Helpers ────────────────────────────────────────────────────────────────── + +/** Whether the NipIaOwnerProof allows archive/unarchive mutations. */ +function canMutate(proof: NipIaOwnerProof): boolean { + return proof.result === "verified"; +} + +// ── Instance row ────────────────────────────────────────────────────────────── + +type InstanceRowProps = { + instance: OwnedAgentInstance; + archiveStateTrusted: boolean; + /** Presence lookup for all instances in the sheet. */ + presenceLookup: PresenceLookup; + onOpenProfile: (pubkey: string) => void; + onArchive: (pubkey: string) => void; + onUnarchive: (pubkey: string) => void; + archivePending: boolean; + unarchivePending: boolean; +}; + +function InstanceRow({ + instance, + archiveStateTrusted, + presenceLookup, + onOpenProfile, + onArchive, + onUnarchive, + archivePending, + unarchivePending, +}: InstanceRowProps) { + const label = instance.displayName ?? truncatePubkey(instance.pubkey); + const isArchived = instance.archiveState.isArchived; + const archiveTrustUnknown = !archiveStateTrusted; + const canAct = canMutate(instance.nipIaOwnerProof) && !archiveTrustUnknown; + const isPending = archivePending || unarchivePending; + + // "Not managed on this device" keys on local === null, NOT personaId === null. + // A stale relay-only duplicate WITH a valid personaId receives the badge. + // The badge stays visible even when archived (no isArchived gate). + const isRelayOnly = instance.local === null; + + // Presence: "online" or "away" → online, "offline" or absent → offline. + const presence = presenceLookup[instance.pubkey.toLowerCase()]; + const isOnline = presence === "online" || presence === "away"; + + return ( +
+ + +
+ +
+ + {/* Presence indicator — shown regardless of archive state */} + + {isOnline ? ( + <> + + Online + + ) : ( + <> + + Offline + + )} + + + {/* Archive state badge — only when trusted */} + {archiveTrustUnknown ? ( + + Unknown + + ) : isArchived === true ? ( + + + Archived + + ) : null} + + {/* "Not managed on this device" badge for relay-only instances. + Keyed on local === null — stays visible even when archived. */} + {isRelayOnly ? ( + + + Relay only + + ) : null} + + {/* Archive / Unarchive action — gated by ownership proof and trust */} + {canAct && !archiveTrustUnknown ? ( + isArchived === true ? ( + + ) : ( + + ) + ) : null} +
+ ); +} + +// ── Sheet ───────────────────────────────────────────────────────────────────── + +type InstancesSheetProps = { + open: boolean; + onOpenChange: (open: boolean) => void; + /** The persona whose instances to display. Filters by persona coordinate. + * Pass `null` to open in "global unknown" mode — shows only the unknown-persona + * relay inventory bucket (no persona-scoped rows). */ + persona: AgentPersona | null; + /** + * The complete grouped inventory snapshot from the parent. The Sheet uses + * `inventory.byPersonaId[persona.id]` as the authoritative instance list for + * this persona — no secondary pubkey-set reconstruction needed. + * `null` when the inventory is not yet loaded. + */ + inventory: OwnedAgentInventorySnapshot | undefined; + /** Open the exact-pubkey profile panel. */ + onOpenProfile: (pubkey: string) => void; + /** + * Whether to render the unknown-persona relay instances section. + * Defaults to `true` when `persona` is `null` (global unknown mode) and + * `false` when `persona` is set (persona-scoped mode), so unknown relay + * instances are only discoverable from the top-level "Unknown relay agents" + * entry point in the Agents library, not from every persona's sheet. + */ + showUnknown?: boolean; +}; + +/** + * Sheet showing the owner's relay inventory of agent instances (`kind:30177`) + * scoped to the opener's persona via `inventory.byPersonaId[persona.id]`. + * + * - Rows show presence (online/offline) as a separate signal from local/relay status. + * - "Relay only" badge keys on `local === null`, stays visible even when archived. + * - Archive/Unarchive are offered only for `Verified` instances. + * - Unknown archive trust shows a retry affordance; mutations are suppressed. + * - Unknown-persona instances from the relay inventory render in a separate section. + * - Tri-state badge is scoped to this surface — `useIsIdentityArchived` elsewhere is unchanged. + */ +export function InstancesSheet({ + open, + onOpenChange, + persona, + inventory, + onOpenProfile, + showUnknown, +}: InstancesSheetProps) { + const inventoryQuery = useOwnedAgentInventoryQuery(open); + const archiveMutation = useArchiveIdentityMutation(); + const unarchiveMutation = useUnarchiveIdentityMutation(); + + // Confirm dialog state. + const [confirmArchivePubkey, setConfirmArchivePubkey] = React.useState< + string | null + >(null); + + // Use the parent-supplied snapshot when available; fall back to the Sheet's + // own query result. This avoids a redundant fetch while keeping the Sheet + // self-contained when opened standalone (e.g. from a future entry point). + const effectiveData = inventory ?? inventoryQuery.data; + const archiveStateTrusted = effectiveData?.archiveStateTrusted ?? false; + + // Instances for THIS persona only — from byPersonaId[persona.id]. + // The parent groups by persona_id parsed from kind:30177 content, so this + // is the authoritative view: it includes relay-only instances (no local + // agent) and excludes instances from other personas. + const instances = React.useMemo(() => { + if (!persona || !effectiveData) return []; + return effectiveData.byPersonaId[persona.id] ?? []; + }, [effectiveData, persona]); + + // Unknown-persona instances from the relay inventory. + // Only shown in global unknown mode (persona === null) or when explicitly + // enabled. In persona-scoped mode, unknown instances are discoverable from + // the top-level "Unknown relay agents" entry in the Agents library. + const shouldShowUnknown = showUnknown ?? persona === null; + const unknownInstances = React.useMemo(() => { + if (!shouldShowUnknown || !effectiveData) return []; + return effectiveData.unknown ?? []; + }, [effectiveData, shouldShowUnknown]); + + // Presence query over the merged pubkey set (persona instances + unknown). + const allPubkeys = React.useMemo( + () => [ + ...instances.map((i) => i.pubkey), + ...unknownInstances.map((i) => i.pubkey), + ], + [instances, unknownInstances], + ); + const presenceQuery = usePresenceQuery(allPubkeys, { enabled: open }); + const presenceLookup: PresenceLookup = presenceQuery.data ?? {}; + + function handleArchive(pubkey: string) { + setConfirmArchivePubkey(pubkey); + } + + function handleConfirmArchive() { + if (!confirmArchivePubkey) return; + archiveMutation.mutate({ targetPubkey: confirmArchivePubkey }); + setConfirmArchivePubkey(null); + } + + function handleUnarchive(pubkey: string) { + unarchiveMutation.mutate({ targetPubkey: pubkey }); + } + + const archivePending = archiveMutation.isPending; + const unarchivePending = unarchiveMutation.isPending; + const isLoading = inventoryQuery.isLoading && !effectiveData; + + function renderRows(rows: OwnedAgentInstance[], trusted: boolean) { + return rows.map((instance) => ( + + )); + } + + return ( + <> + + + + + + Instances + {instances.length > 0 ? ( + + {instances.length} + + ) : null} + + + +
+ {isLoading ? ( +
+ +
+ ) : inventoryQuery.isError ? ( +
+

+ {inventoryQuery.error instanceof Error + ? inventoryQuery.error.message + : "Failed to load instances"} +

+ +
+ ) : !archiveStateTrusted && !isLoading ? ( +
+

+ Archive status could not be verified from the relay. Archive + and unarchive actions are disabled until the relay state is + confirmed. +

+ + {/* Still render instances for inspection, but with mutations suppressed */} +
+ {renderRows(instances, false)} +
+
+ ) : instances.length === 0 ? ( +

+ No instances found on this relay. +

+ ) : ( +
+ {renderRows(instances, archiveStateTrusted)} +
+ )} + + {/* Unknown-persona instances from the relay inventory */} + {unknownInstances.length > 0 ? ( +
+

+ Unknown agents +

+ {renderRows(unknownInstances, archiveStateTrusted)} +
+ ) : null} +
+
+
+ + {/* Archive confirmation dialog — rendered outside Sheet to avoid z-index issues */} + { + if (!o) setConfirmArchivePubkey(null); + }} + /> + + ); +} diff --git a/desktop/src/features/identity-archive/hooks.ts b/desktop/src/features/identity-archive/hooks.ts index 8149eff7b7..5816152dad 100644 --- a/desktop/src/features/identity-archive/hooks.ts +++ b/desktop/src/features/identity-archive/hooks.ts @@ -6,15 +6,18 @@ import { useMyRelayMembershipQuery } from "@/features/community-members/hooks"; import { useIdentityQuery } from "@/shared/api/hooks"; import { archiveIdentity, + getOwnedAgentInventory, listArchivedIdentities, resolveOaOwner, unarchiveIdentity, type ArchivedIdentitiesSnapshot, type IdentityArchiveRequest, type IdentityUnarchiveRequest, + type OwnedAgentInventorySnapshot, } from "@/shared/api/tauriIdentityArchive"; export const archivedIdentitiesQueryKey = ["archivedIdentities"] as const; +export const ownedAgentInventoryQueryKey = ["owned-agent-inventory"] as const; /** Cache the relay's `kind:13535` snapshot. Drives the "Archived" flair. */ export function useArchivedIdentitiesQuery(enabled = true) { @@ -26,6 +29,21 @@ export function useArchivedIdentitiesQuery(enabled = true) { }); } +/** + * Query the owner's `kind:30177` relay inventory (NIP-OA–verified agent + * instances). Pages to exhaustion; returns a complete snapshot. + * Tri-state archive join is scoped to this surface only — + * existing `useIsIdentityArchived` callers are unchanged. + */ +export function useOwnedAgentInventoryQuery(enabled = true) { + return useQuery({ + enabled, + queryKey: ownedAgentInventoryQueryKey, + queryFn: () => getOwnedAgentInventory(), + staleTime: 30_000, + }); +} + /** `undefined` while the snapshot loads so callers can defer the flair. */ export function useIsIdentityArchived(pubkey: string): boolean | undefined { const query = useArchivedIdentitiesQuery(); @@ -81,6 +99,9 @@ export function useArchiveIdentityMutation() { void queryClient.invalidateQueries({ queryKey: archivedIdentitiesQueryKey, }); + void queryClient.invalidateQueries({ + queryKey: ownedAgentInventoryQueryKey, + }); }, }); } @@ -93,6 +114,9 @@ export function useUnarchiveIdentityMutation() { void queryClient.invalidateQueries({ queryKey: archivedIdentitiesQueryKey, }); + void queryClient.invalidateQueries({ + queryKey: ownedAgentInventoryQueryKey, + }); }, }); } diff --git a/desktop/src/shared/api/relayQueryInvalidation.ts b/desktop/src/shared/api/relayQueryInvalidation.ts index e07992184d..7318810194 100644 --- a/desktop/src/shared/api/relayQueryInvalidation.ts +++ b/desktop/src/shared/api/relayQueryInvalidation.ts @@ -14,6 +14,7 @@ const RELAY_QUERY_ROOTS = new Set([ "my-notes", "myRelayMembership", "oaOwner", + "owned-agent-inventory", "presence", "profile", "pulse-note", diff --git a/desktop/src/shared/api/tauriIdentityArchive.ts b/desktop/src/shared/api/tauriIdentityArchive.ts index 304b29f088..888b40b1e5 100644 --- a/desktop/src/shared/api/tauriIdentityArchive.ts +++ b/desktop/src/shared/api/tauriIdentityArchive.ts @@ -27,6 +27,71 @@ export type IdentityUnarchiveRequest = { reason?: string; }; +// ── NipIaOwnerProof ────────────────────────────────────────────────────────── + +/** Result of verifying NIP-OA ownership. Mirrors the Rust `NipIaOwnerProof` enum. */ +export type NipIaOwnerProof = + | { result: "verified" } + | { result: "missing_profile" } + | { result: "missing_auth" } + | { result: "multiple_auth_tags" } + | { result: "invalid_auth" } + | { result: "owner_mismatch"; declared_owner: string }; + +// ── Owned-agent relay inventory ───────────────────────────────────────────── + +/** Archive tri-state for a single owned-agent instance. */ +export type OwnedAgentArchiveState = { + /** `null` if the snapshot was not loaded (caller may treat as unknown). */ + isArchived: boolean | null; +}; + +/** + * Minimal locally-managed agent fields, present when the pubkey has a local + * managed-agent record on this device. `null` on relay-only instances. + * + * The "Not managed on this device" badge keys on `local === null`, NOT on + * `personaId === null`. A stale relay-only duplicate with a valid personaId + * receives the badge; a locally managed definition-less agent does not. + */ +export type LocalAgentSummary = { + pubkey: string; + name: string; + personaId: string | null; +}; + +/** A single owned-agent instance from the relay `kind:30177` inventory. */ +export type OwnedAgentInstance = { + pubkey: string; + displayName: string | null; + picture: string | null; + /** Relay URL for this instance. Empty string for local-only instances. */ + relayUrl: string; + /** NIP-OA owner proof for this instance — never omitted, only null in older responses. */ + nipIaOwnerProof: NipIaOwnerProof; + archiveState: OwnedAgentArchiveState; + /** Persona ID parsed from `kind:30177` content. `null` for standalone agents. */ + personaId: string | null; + /** + * Present when this pubkey has a local managed-agent record on this device. + * `null` for relay-only instances (no local record). + * + * Key the "Not managed on this device" / Relay-only badge on `local === null`, + * NOT on `personaId === null`. + */ + local: LocalAgentSummary | null; +}; + +/** Complete merged view model returned by `get_owned_agent_inventory`. */ +export type OwnedAgentInventorySnapshot = { + /** Whether the archive snapshot was loaded and trusted. */ + archiveStateTrusted: boolean; + /** Instances grouped by persona ID. Drives per-card counts and Sheet filtering. */ + byPersonaId: Record; + /** Instances with no parseable persona ID (standalone agents). */ + unknown: OwnedAgentInstance[]; +}; + type RawOwnerOfAgent = { owner: string; is_me: boolean }; /** @@ -73,3 +138,13 @@ export async function listArchivedIdentities(): Promise { + return await invokeTauri( + "get_owned_agent_inventory", + ); +} diff --git a/desktop/src/testing/e2eBridge.ts b/desktop/src/testing/e2eBridge.ts index 1987e00ff1..49c322b659 100644 --- a/desktop/src/testing/e2eBridge.ts +++ b/desktop/src/testing/e2eBridge.ts @@ -360,6 +360,57 @@ type E2eConfig = { // - `resolve_oa_owner` (oaOwnerIsMe) // - `resetMockRelayMembers` (relayRole) archivedIdentities?: string[]; + /** + * Snapshot returned by `get_owned_agent_inventory`. Drives the + * Instances Sheet content and start-control safeguard in + * tests/e2e/agent-instances-sheet.spec.ts. + * Omitted → empty snapshot with archive state trusted. + */ + ownedAgentInventory?: { + archiveStateTrusted: boolean; + /** Instances grouped by persona ID. Keys are persona IDs. */ + byPersonaId: Record< + string, + Array<{ + pubkey: string; + displayName: string | null; + picture: string | null; + relayUrl: string; + nipIaOwnerProof: { result: string; declared_owner?: string }; + archiveState: { isArchived: boolean | null }; + personaId: string | null; + /** Local managed-agent summary. `null` for relay-only instances. */ + local?: { + pubkey: string; + name: string; + personaId: string | null; + } | null; + }> + >; + /** Instances with no parseable persona ID (standalone agents). */ + unknown: Array<{ + pubkey: string; + displayName: string | null; + picture: string | null; + relayUrl: string; + nipIaOwnerProof: { result: string; declared_owner?: string }; + archiveState: { isArchived: boolean | null }; + personaId: string | null; + /** Local managed-agent summary. `null` for relay-only instances. */ + local?: { + pubkey: string; + name: string; + personaId: string | null; + } | null; + }>; + }; + /** + * Per-pubkey presence overrides for the instance-sheet tests. + * Seeded into the mockPresence map at installMockBridge time, so + * `get_presence` returns the specified status for these pubkeys. + * Keys are lowercase hex pubkeys; values are "online" | "away" | "offline". + */ + presenceOverrides?: Record; // Relay's NIP-11 `self` pubkey (hex) for `get_relay_self`. A DM whose peer // equals this is treated as a moderation DM (composer disabled). Absent → // fail open (no mod-DM detection), matching the Rust command's contract. @@ -3000,6 +3051,25 @@ function resetMockSaveSubscriptions(config: E2eConfig | undefined) { })); } +// ── Mutable owned-agent inventory (archive/unarchive mutations update it) ─── + +/** + * Mutable clone of `config.mock.ownedAgentInventory`, reset on each + * `installMockBridge` call. `archive_identity` and `unarchive_identity` + * mutate this copy so `get_owned_agent_inventory` returns the post-mutation + * state, allowing specs to assert the full Archive → refetch → Unarchive flow. + */ +let mockOwnedInventory: NonNullable< + NonNullable["ownedAgentInventory"] +> = { archiveStateTrusted: true, byPersonaId: {}, unknown: [] }; + +function resetMockOwnedInventory(config: E2eConfig | undefined) { + const seed = config?.mock?.ownedAgentInventory; + mockOwnedInventory = seed + ? JSON.parse(JSON.stringify(seed)) + : { archiveStateTrusted: true, byPersonaId: {}, unknown: [] }; +} + function resetMockPersonaCatalogEvents(config: E2eConfig | undefined) { mockPersonaEvents.length = 0; for (const event of config?.mock?.personaCatalogEvents ?? []) { @@ -3751,6 +3821,14 @@ function setMockPresenceStatus(pubkey: string, status: PresenceStatus) { mockPresence.set(pubkey.toLowerCase(), status); } +function applyMockPresenceOverrides(config: E2eConfig | undefined) { + for (const [pubkey, status] of Object.entries( + config?.mock?.presenceOverrides ?? {}, + )) { + mockPresence.set(pubkey.toLowerCase(), status as PresenceStatus); + } +} + function resolveHandler(handler: unknown): WsHandler { if (typeof handler === "function") { return handler as WsHandler; @@ -9972,6 +10050,8 @@ export function maybeInstallE2eTauriMocks() { resetMockUserStatuses(); resetMockPersonaCatalogEvents(config); resetMockSaveSubscriptions(config); + resetMockOwnedInventory(config); + applyMockPresenceOverrides(config); resetMockPendingCommunityDeepLinks(config); initializeMockHuddle(config.mock?.huddle, config); mockWebsocketSendMutexWedged = false; @@ -12781,6 +12861,9 @@ export function maybeInstallE2eTauriMocks() { const archived = activeConfig?.mock?.archivedIdentities ?? []; return { archived }; } + case "get_owned_agent_inventory": { + return mockOwnedInventory; + } case "get_relay_self": if ((activeConfig?.mock?.relaySelfDelayMs ?? 0) > 0) { await new Promise((resolve) => @@ -12791,11 +12874,51 @@ export function maybeInstallE2eTauriMocks() { ); } return activeConfig?.mock?.relaySelf ?? null; - case "archive_identity": - case "unarchive_identity": - // The spec only verifies UI state, not the submitted request shape; - // returning null mirrors the Rust submit_event success path. + case "archive_identity": { + // Record the payload (via __BUZZ_E2E_COMMAND_PAYLOADS__ above) and + // mutate the mocked inventory snapshot so refetch reflects the change. + const archiveReq = payload as { req?: { targetPubkey?: string } }; + const archivePubkey = archiveReq?.req?.targetPubkey ?? ""; + if (archivePubkey) { + // Mark the instance as archived in all persona groups and unknown. + for (const instances of Object.values( + mockOwnedInventory.byPersonaId, + )) { + for (const inst of instances) { + if (inst.pubkey === archivePubkey) { + inst.archiveState = { isArchived: true }; + } + } + } + for (const inst of mockOwnedInventory.unknown) { + if (inst.pubkey === archivePubkey) { + inst.archiveState = { isArchived: true }; + } + } + } return null; + } + case "unarchive_identity": { + const unarchiveReq = payload as { req?: { targetPubkey?: string } }; + const unarchivePubkey = unarchiveReq?.req?.targetPubkey ?? ""; + if (unarchivePubkey) { + for (const instances of Object.values( + mockOwnedInventory.byPersonaId, + )) { + for (const inst of instances) { + if (inst.pubkey === unarchivePubkey) { + inst.archiveState = { isArchived: false }; + } + } + } + for (const inst of mockOwnedInventory.unknown) { + if (inst.pubkey === unarchivePubkey) { + inst.archiveState = { isArchived: false }; + } + } + } + return null; + } case "set_canvas": return { ok: true, event_id: mockEventId() }; case "get_canvas": { diff --git a/desktop/tests/e2e/agent-instances-sheet.spec.ts b/desktop/tests/e2e/agent-instances-sheet.spec.ts new file mode 100644 index 0000000000..028a38dd5a --- /dev/null +++ b/desktop/tests/e2e/agent-instances-sheet.spec.ts @@ -0,0 +1,793 @@ +import { expect, test } from "@playwright/test"; + +import { installMockBridge } from "../helpers/bridge"; + +// ── Incident-shaped supplementary UI coverage for the Instances Sheet ────── +// +// These tests are supplementary UI coverage only (row state, Sheet flow, +// cache invalidation). They are NOT proof for the Rust/relay path — the relay +// acceptance tests in identity_archive/relay_acceptance are the authoritative +// gate for correctness. +// +// Incident shape: sietch-tabr:duncan had 2 active relay instances, the CLI's +// apply_cardinality_rule refused to guess which was canonical and failed +// closed. These specs verify that: +// (1) the start-control safeguard opens the Sheet instead of minting a new +// instance when the relay inventory has active instances +// (2) the Sheet shows the expected instances for the persona +// (3) rows expose Archive/Unarchive actions for Verified instances +// (4) unknown archive trust suppresses mutation affordances +// (5) local+relay merge: correct local-device marker per row +// (6) exact-target Archive → refetch → Unarchive flow +// (7) unknown-persona instances render in a separate section + +const PERSONA_ID = "custom:sietch-tabr-duncan"; +const PERSONA_DISPLAY_NAME = "Duncan"; +// Instance A: locally managed on this device (has `local` summary). +const INSTANCE_PUBKEY_A = + "1c206895aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; +// Instance B: relay-only, no local record — the stale duplicate. +const INSTANCE_PUBKEY_B = + "9a232143bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"; +// Second persona pubkey — negative control (must never appear under PERSONA_ID). +const PERSONA_ID_2 = "custom:sietch-tabr-paul"; +const INSTANCE_PUBKEY_C = + "cc000000cccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"; +// Unknown-persona instance. +const UNKNOWN_PUBKEY = + "dd000000dddddddddddddddddddddddddddddddddddddddddddddddddddddddddd"; +const RELAY_URL = "http://localhost:3000"; + +async function gotoAgentsView(page: import("@playwright/test").Page) { + await page.goto("/", { waitUntil: "domcontentloaded" }); + await page.waitForFunction( + () => { + const w = window as Window & { + __BUZZ_E2E_INVOKE_MOCK_COMMAND__?: unknown; + __TAURI_INTERNALS__?: { invoke?: unknown }; + }; + return ( + typeof w.__BUZZ_E2E_INVOKE_MOCK_COMMAND__ === "function" || + typeof w.__TAURI_INTERNALS__?.invoke === "function" + ); + }, + null, + { timeout: 5_000 }, + ); + await page.getByTestId("open-agents-view").click(); + await expect(page.getByTestId("agents-library-personas")).toBeVisible(); +} + +/** Read all recorded archive_identity / unarchive_identity payloads. */ +async function getMutationPayloads(page: import("@playwright/test").Page) { + return page.evaluate(() => { + const w = window as Window & { + __BUZZ_E2E_COMMAND_PAYLOADS__?: Array<{ + command: string; + payload: unknown; + }>; + }; + return (w.__BUZZ_E2E_COMMAND_PAYLOADS__ ?? []).filter( + (e) => + e.command === "archive_identity" || e.command === "unarchive_identity", + ); + }); +} + +// ── Test 1: start-control safeguard opens Sheet on active relay instances ── + +test("start-control safeguard opens Instances Sheet instead of minting when inventory has active instances", async ({ + page, +}) => { + await installMockBridge(page, { + personas: [ + { + id: PERSONA_ID, + displayName: PERSONA_DISPLAY_NAME, + systemPrompt: "The incident-shape agent.", + }, + ], + // Seed 2 active (non-archived) relay instances — mirrors the incident. + ownedAgentInventory: { + archiveStateTrusted: true, + byPersonaId: { + [PERSONA_ID]: [ + { + pubkey: INSTANCE_PUBKEY_A, + displayName: "Duncan (instance A)", + picture: null, + relayUrl: RELAY_URL, + nipIaOwnerProof: { result: "verified" }, + archiveState: { isArchived: false }, + personaId: PERSONA_ID, + local: { + pubkey: INSTANCE_PUBKEY_A, + name: "Duncan A", + personaId: PERSONA_ID, + }, + }, + { + pubkey: INSTANCE_PUBKEY_B, + displayName: "Duncan (instance B)", + picture: null, + relayUrl: RELAY_URL, + nipIaOwnerProof: { result: "verified" }, + archiveState: { isArchived: false }, + personaId: PERSONA_ID, + local: null, // relay-only + }, + ], + }, + unknown: [], + }, + }); + await gotoAgentsView(page); + + // The persona has no local managed agent — the start button renders with + // testid `persona-runtime-start-${PERSONA_ID}`. + const startButton = page.getByTestId(`persona-runtime-start-${PERSONA_ID}`); + await expect(startButton).toBeVisible(); + + // Click start: safeguard detects 2 active relay instances and should open + // the Sheet instead of calling onStartPersona. + await startButton.click(); + + // The Sheet must open — not the persona profile panel. + await expect(page.getByTestId("instances-sheet")).toBeVisible(); + // The persona profile panel must NOT open (no navigation away from agents). + await expect(page.getByTestId("agents-library-personas")).toBeVisible(); +}); + +// ── Test 2: Sheet shows 2 instances for the persona ─────────────────────── + +test("Instances Sheet shows both relay instances when seeded", async ({ + page, +}) => { + await installMockBridge(page, { + personas: [ + { + id: PERSONA_ID, + displayName: PERSONA_DISPLAY_NAME, + systemPrompt: "The incident-shape agent.", + }, + ], + ownedAgentInventory: { + archiveStateTrusted: true, + byPersonaId: { + [PERSONA_ID]: [ + { + pubkey: INSTANCE_PUBKEY_A, + displayName: "Duncan (instance A)", + picture: null, + relayUrl: RELAY_URL, + nipIaOwnerProof: { result: "verified" }, + archiveState: { isArchived: false }, + personaId: PERSONA_ID, + local: { + pubkey: INSTANCE_PUBKEY_A, + name: "Duncan A", + personaId: PERSONA_ID, + }, + }, + { + pubkey: INSTANCE_PUBKEY_B, + displayName: "Duncan (instance B)", + picture: null, + relayUrl: RELAY_URL, + nipIaOwnerProof: { result: "verified" }, + archiveState: { isArchived: false }, + personaId: PERSONA_ID, + local: null, + }, + ], + }, + unknown: [], + }, + }); + await gotoAgentsView(page); + + // Click the instances count button (rendered when instances > 1). + const instancesButton = page.getByLabel(`Instances (2)`); + await expect(instancesButton).toBeVisible(); + await instancesButton.click(); + + const sheet = page.getByTestId("instances-sheet"); + await expect(sheet).toBeVisible(); + + // Both instance rows should be present. + await expect( + page.getByTestId(`instance-row-${INSTANCE_PUBKEY_A}`), + ).toBeVisible(); + await expect( + page.getByTestId(`instance-row-${INSTANCE_PUBKEY_B}`), + ).toBeVisible(); +}); + +// ── Test 3: Archive button visible for Verified instances ───────────────── + +test("Archive button is present for Verified instances with trusted archive state", async ({ + page, +}) => { + await installMockBridge(page, { + personas: [ + { + id: PERSONA_ID, + displayName: PERSONA_DISPLAY_NAME, + systemPrompt: "The incident-shape agent.", + }, + ], + ownedAgentInventory: { + archiveStateTrusted: true, + byPersonaId: { + [PERSONA_ID]: [ + { + pubkey: INSTANCE_PUBKEY_A, + displayName: "Duncan (instance A)", + picture: null, + relayUrl: RELAY_URL, + nipIaOwnerProof: { result: "verified" }, + archiveState: { isArchived: false }, + personaId: PERSONA_ID, + local: { + pubkey: INSTANCE_PUBKEY_A, + name: "Duncan A", + personaId: PERSONA_ID, + }, + }, + ], + }, + unknown: [], + }, + }); + await gotoAgentsView(page); + + // Open the Sheet via the start-button safeguard path (1 active instance). + const startButton = page.getByTestId(`persona-runtime-start-${PERSONA_ID}`); + await expect(startButton).toBeVisible(); + await startButton.click(); + + const sheet = page.getByTestId("instances-sheet"); + await expect(sheet).toBeVisible(); + + // The Archive button must be visible for the active verified instance. + const archiveButton = page.getByTestId( + `archive-instance-${INSTANCE_PUBKEY_A}`, + ); + await expect(archiveButton).toBeVisible(); +}); + +// ── Test 4: Unknown archive trust suppresses mutation affordances ───────── + +test("Archive/Unarchive actions suppressed when archive state is not trusted", async ({ + page, +}) => { + await installMockBridge(page, { + personas: [ + { + id: PERSONA_ID, + displayName: PERSONA_DISPLAY_NAME, + systemPrompt: "The incident-shape agent.", + }, + ], + ownedAgentInventory: { + archiveStateTrusted: false, // untrusted snapshot + byPersonaId: { + [PERSONA_ID]: [ + { + pubkey: INSTANCE_PUBKEY_A, + displayName: "Duncan (instance A)", + picture: null, + relayUrl: RELAY_URL, + nipIaOwnerProof: { result: "verified" }, + archiveState: { isArchived: null }, // unknown + personaId: PERSONA_ID, + local: { + pubkey: INSTANCE_PUBKEY_A, + name: "Duncan A", + personaId: PERSONA_ID, + }, + }, + ], + }, + unknown: [], + }, + }); + await gotoAgentsView(page); + + // Safeguard: untrusted inventory → Sheet. + const startButton = page.getByTestId(`persona-runtime-start-${PERSONA_ID}`); + await expect(startButton).toBeVisible(); + await startButton.click(); + + const sheet = page.getByTestId("instances-sheet"); + await expect(sheet).toBeVisible(); + + // Archive button must NOT be visible — trust is unknown. + await expect( + page.getByTestId(`archive-instance-${INSTANCE_PUBKEY_A}`), + ).toHaveCount(0); + // Unarchive button must NOT be visible either. + await expect( + page.getByTestId(`unarchive-instance-${INSTANCE_PUBKEY_A}`), + ).toHaveCount(0); +}); + +// ── Test 5: No-third-mint regression ────────────────────────────────────── +// +// When the relay inventory is loading (undefined), the safeguard must open +// the Sheet rather than calling onStartPersona — preventing an implicit mint. + +test("no-third-mint: start is intercepted when inventory is untrusted", async ({ + page, +}) => { + await installMockBridge(page, { + personas: [ + { + id: PERSONA_ID, + displayName: PERSONA_DISPLAY_NAME, + systemPrompt: "The incident-shape agent.", + }, + ], + // archiveStateTrusted: false forces the safeguard to open the Sheet + // rather than proceeding with start. + ownedAgentInventory: { + archiveStateTrusted: false, + byPersonaId: {}, + unknown: [], + }, + }); + await gotoAgentsView(page); + + const startButton = page.getByTestId(`persona-runtime-start-${PERSONA_ID}`); + await expect(startButton).toBeVisible(); + + // Click: untrusted inventory → Sheet must open (not a direct persona start). + await startButton.click(); + + // Sheet opens — no mint was attempted. + await expect(page.getByTestId("instances-sheet")).toBeVisible(); +}); + +// ── Test 6: Local+relay merge — correct device marker per row ───────────── +// +// One local+relay instance and one relay-only instance for the same persona. +// Second persona is a negative control (its instance must not appear). +// Asserts: local instance has NO relay-only badge; relay-only instance HAS badge. + +test("local and relay-only instances show correct device markers", async ({ + page, +}) => { + await installMockBridge(page, { + personas: [ + { + id: PERSONA_ID, + displayName: PERSONA_DISPLAY_NAME, + systemPrompt: "The incident-shape agent.", + }, + { + id: PERSONA_ID_2, + displayName: "Paul", + systemPrompt: "Second persona — negative control.", + }, + ], + ownedAgentInventory: { + archiveStateTrusted: true, + byPersonaId: { + [PERSONA_ID]: [ + { + pubkey: INSTANCE_PUBKEY_A, + displayName: "Duncan (local)", + picture: null, + relayUrl: RELAY_URL, + nipIaOwnerProof: { result: "verified" }, + archiveState: { isArchived: false }, + personaId: PERSONA_ID, + // Has a local record — this is the device's managed instance. + local: { + pubkey: INSTANCE_PUBKEY_A, + name: "Duncan A", + personaId: PERSONA_ID, + }, + }, + { + pubkey: INSTANCE_PUBKEY_B, + displayName: "Duncan (stale relay)", + picture: null, + relayUrl: RELAY_URL, + nipIaOwnerProof: { result: "verified" }, + archiveState: { isArchived: false }, + personaId: PERSONA_ID, + // No local record — relay-only (the stale duplicate). + local: null, + }, + ], + [PERSONA_ID_2]: [ + { + pubkey: INSTANCE_PUBKEY_C, + displayName: "Paul", + picture: null, + relayUrl: RELAY_URL, + nipIaOwnerProof: { result: "verified" }, + archiveState: { isArchived: false }, + personaId: PERSONA_ID_2, + local: { + pubkey: INSTANCE_PUBKEY_C, + name: "Paul", + personaId: PERSONA_ID_2, + }, + }, + ], + }, + unknown: [], + }, + }); + await gotoAgentsView(page); + + // Open the Sheet for PERSONA_ID (2 instances → instances count button). + const instancesButton = page.getByLabel(`Instances (2)`); + await expect(instancesButton).toBeVisible(); + await instancesButton.click(); + await expect(page.getByTestId("instances-sheet")).toBeVisible(); + + // Instance A (local): NO relay-only badge. + await expect( + page.getByTestId(`instance-relay-only-${INSTANCE_PUBKEY_A}`), + ).toHaveCount(0); + + // Instance B (relay-only): HAS relay-only badge. + await expect( + page.getByTestId(`instance-relay-only-${INSTANCE_PUBKEY_B}`), + ).toBeVisible(); + + // Negative control: Paul's instance must NOT appear in this persona's sheet. + await expect( + page.getByTestId(`instance-row-${INSTANCE_PUBKEY_C}`), + ).toHaveCount(0); +}); + +// ── Test 7: Exact-target Archive → refetch → Unarchive flow ─────────────── +// +// Proves the full mutation path: +// - Archive records the exact targetPubkey (relay-only instance B) +// - Post-mutation refetch shows instance B as archived + Unarchive button +// - Unarchive records the exact targetPubkey again + +test("Archive sends exact targetPubkey, refetch shows Archived, Unarchive sends exact targetPubkey", async ({ + page, +}) => { + await installMockBridge(page, { + personas: [ + { + id: PERSONA_ID, + displayName: PERSONA_DISPLAY_NAME, + systemPrompt: "The incident-shape agent.", + }, + ], + ownedAgentInventory: { + archiveStateTrusted: true, + byPersonaId: { + [PERSONA_ID]: [ + { + pubkey: INSTANCE_PUBKEY_A, + displayName: "Duncan (local)", + picture: null, + relayUrl: RELAY_URL, + nipIaOwnerProof: { result: "verified" }, + archiveState: { isArchived: false }, + personaId: PERSONA_ID, + local: { + pubkey: INSTANCE_PUBKEY_A, + name: "Duncan A", + personaId: PERSONA_ID, + }, + }, + { + pubkey: INSTANCE_PUBKEY_B, + displayName: "Duncan (stale relay)", + picture: null, + relayUrl: RELAY_URL, + nipIaOwnerProof: { result: "verified" }, + archiveState: { isArchived: false }, + personaId: PERSONA_ID, + local: null, + }, + ], + }, + unknown: [], + }, + }); + await gotoAgentsView(page); + + // Open the Sheet for PERSONA_ID. + const instancesButton = page.getByLabel(`Instances (2)`); + await expect(instancesButton).toBeVisible(); + await instancesButton.click(); + const sheet = page.getByTestId("instances-sheet"); + await expect(sheet).toBeVisible(); + + // Both rows visible before mutation. + await expect( + page.getByTestId(`instance-row-${INSTANCE_PUBKEY_B}`), + ).toBeVisible(); + + // Click Archive on instance B (the relay-only stale duplicate). + const archiveBtn = page.getByTestId(`archive-instance-${INSTANCE_PUBKEY_B}`); + await expect(archiveBtn).toBeVisible(); + await archiveBtn.click(); + + // Confirm the archive dialog. + const confirmBtn = page.getByTestId("archive-confirm-action"); + await expect(confirmBtn).toBeVisible(); + await confirmBtn.click(); + + // Assert the exact targetPubkey was sent. + const afterArchive = await getMutationPayloads(page); + const archiveEntry = afterArchive.find( + (e) => e.command === "archive_identity", + ); + expect(archiveEntry).toBeTruthy(); + const archivePayload = archiveEntry?.payload as { + req?: { targetPubkey?: string }; + }; + expect(archivePayload?.req?.targetPubkey).toBe(INSTANCE_PUBKEY_B); + + // After refetch: instance B should show the Unarchive button (archived state). + const unarchiveBtn = page.getByTestId( + `unarchive-instance-${INSTANCE_PUBKEY_B}`, + ); + await expect(unarchiveBtn).toBeVisible(); + + // Click Unarchive. + await unarchiveBtn.click(); + + // Assert the exact targetPubkey was sent for unarchive. + const afterUnarchive = await getMutationPayloads(page); + const unarchiveEntry = afterUnarchive.find( + (e) => e.command === "unarchive_identity", + ); + expect(unarchiveEntry).toBeTruthy(); + const unarchivePayload = unarchiveEntry?.payload as { + req?: { targetPubkey?: string }; + }; + expect(unarchivePayload?.req?.targetPubkey).toBe(INSTANCE_PUBKEY_B); +}); + +// ── Test 8: Exact-profile opening ──────────────────────────────────────── +// +// Clicking the profile button on an instance row opens the profile for that +// exact pubkey (not another row's pubkey). Asserts: +// - `user-profile-panel` becomes visible (navigation occurred) +// - The e2eBridge recorded a `get_user_profile` command for INSTANCE_PUBKEY_B + +test("clicking instance row opens the exact pubkey profile", async ({ + page, +}) => { + await installMockBridge(page, { + personas: [ + { + id: PERSONA_ID, + displayName: PERSONA_DISPLAY_NAME, + systemPrompt: "The incident-shape agent.", + }, + ], + searchProfiles: [ + { + pubkey: INSTANCE_PUBKEY_A, + displayName: "Duncan (local)", + avatarUrl: null, + }, + { + pubkey: INSTANCE_PUBKEY_B, + displayName: "Duncan (stale relay)", + avatarUrl: null, + }, + ], + ownedAgentInventory: { + archiveStateTrusted: true, + byPersonaId: { + [PERSONA_ID]: [ + { + pubkey: INSTANCE_PUBKEY_A, + displayName: "Duncan (local)", + picture: null, + relayUrl: RELAY_URL, + nipIaOwnerProof: { result: "verified" }, + archiveState: { isArchived: false }, + personaId: PERSONA_ID, + local: { + pubkey: INSTANCE_PUBKEY_A, + name: "Duncan A", + personaId: PERSONA_ID, + }, + }, + { + pubkey: INSTANCE_PUBKEY_B, + displayName: "Duncan (stale relay)", + picture: null, + relayUrl: RELAY_URL, + nipIaOwnerProof: { result: "verified" }, + archiveState: { isArchived: false }, + personaId: PERSONA_ID, + local: null, + }, + ], + }, + unknown: [], + }, + }); + await gotoAgentsView(page); + + // Open sheet. + await page.getByLabel("Instances (2)").click(); + await expect(page.getByTestId("instances-sheet")).toBeVisible(); + + // Click the profile button for instance B specifically. + await page + .getByTestId(`instance-row-${INSTANCE_PUBKEY_B}`) + .getByRole("button", { name: /open profile/i }) + .first() + .click(); + + // The profile panel for instance B's pubkey should open. + await expect(page.getByTestId("user-profile-panel")).toBeVisible(); + + // The e2eBridge must have recorded a profile fetch for instance B. + const profileCmds = await page.evaluate(() => { + const w = window as Window & { + __BUZZ_E2E_COMMAND_PAYLOADS__?: Array<{ + command: string; + payload: unknown; + }>; + }; + return (w.__BUZZ_E2E_COMMAND_PAYLOADS__ ?? []).filter( + (e) => e.command === "get_user_profile", + ); + }); + const fetchedB = profileCmds.some((e) => { + const p = e.payload as { pubkey?: string }; + return p?.pubkey?.toLowerCase() === INSTANCE_PUBKEY_B.toLowerCase(); + }); + expect(fetchedB).toBe(true); +}); + +// ── Test 9: Unknown-persona instances reachable from top-level library ─── +// +// When the relay inventory has unknown-persona instances, the "Unknown relay +// agents" group appears in the Agents library at the top level. Clicking it +// opens the global unknown Sheet without going through any persona's Sheet. +// This proves the instance is discoverable without opening an unrelated +// persona's Sheet. + +test("unknown-persona instances render in the Unknown agents section", async ({ + page, +}) => { + await installMockBridge(page, { + personas: [ + { + id: PERSONA_ID, + displayName: PERSONA_DISPLAY_NAME, + systemPrompt: "The incident-shape agent.", + }, + ], + ownedAgentInventory: { + archiveStateTrusted: true, + byPersonaId: { + // No instances for the persona — the user must not need to open + // Duncan's Sheet to find the unknown instance. + [PERSONA_ID]: [], + }, + // Unknown instance has no persona_id. + unknown: [ + { + pubkey: UNKNOWN_PUBKEY, + displayName: "Mystery agent", + picture: null, + relayUrl: RELAY_URL, + nipIaOwnerProof: { result: "verified" }, + archiveState: { isArchived: false }, + personaId: null, + local: null, + }, + ], + }, + }); + await gotoAgentsView(page); + + // The top-level "Unknown relay agents" group must appear in the library + // WITHOUT opening any persona's Sheet. + const relayUnknownGroup = page.getByTestId("relay-unknown-agents-group"); + await expect(relayUnknownGroup).toBeVisible(); + + // Click the group button to open the global unknown sheet. + await relayUnknownGroup.getByRole("button").click(); + + // The global unknown Sheet must open. + await expect(page.getByTestId("instances-sheet")).toBeVisible(); + + // Unknown section must be visible inside the sheet. + await expect(page.getByTestId("unknown-instances-section")).toBeVisible(); + + // Unknown instance row must be present. + await expect( + page.getByTestId(`instance-row-${UNKNOWN_PUBKEY}`), + ).toBeVisible(); + + // Unknown instance must have the relay-only badge (local === null). + await expect( + page.getByTestId(`instance-relay-only-${UNKNOWN_PUBKEY}`), + ).toBeVisible(); +}); + +// ── Test 10: Presence indicators show distinct Online/Offline per row ───── +// +// Seeds presence overrides so instance A is "online" and instance B is +// "offline". Asserts the per-row Online/Offline badges differ. + +test("presence indicators show Online for active instance and Offline for relay-only instance", async ({ + page, +}) => { + await installMockBridge(page, { + personas: [ + { + id: PERSONA_ID, + displayName: PERSONA_DISPLAY_NAME, + systemPrompt: "The incident-shape agent.", + }, + ], + // Seed presence: A is online (the device's managed instance), B is offline + // (the stale relay-only duplicate we want to archive). + presenceOverrides: { + [INSTANCE_PUBKEY_A]: "online", + [INSTANCE_PUBKEY_B]: "offline", + }, + ownedAgentInventory: { + archiveStateTrusted: true, + byPersonaId: { + [PERSONA_ID]: [ + { + pubkey: INSTANCE_PUBKEY_A, + displayName: "Duncan (local)", + picture: null, + relayUrl: RELAY_URL, + nipIaOwnerProof: { result: "verified" }, + archiveState: { isArchived: false }, + personaId: PERSONA_ID, + local: { + pubkey: INSTANCE_PUBKEY_A, + name: "Duncan A", + personaId: PERSONA_ID, + }, + }, + { + pubkey: INSTANCE_PUBKEY_B, + displayName: "Duncan (stale relay)", + picture: null, + relayUrl: RELAY_URL, + nipIaOwnerProof: { result: "verified" }, + archiveState: { isArchived: false }, + personaId: PERSONA_ID, + local: null, + }, + ], + }, + unknown: [], + }, + }); + await gotoAgentsView(page); + + // Open the Sheet for PERSONA_ID. + const instancesButton = page.getByLabel(`Instances (2)`); + await expect(instancesButton).toBeVisible(); + await instancesButton.click(); + await expect(page.getByTestId("instances-sheet")).toBeVisible(); + + // Instance A (online): presence badge should say "Online". + const presenceA = page.getByTestId(`instance-presence-${INSTANCE_PUBKEY_A}`); + await expect(presenceA).toBeVisible(); + await expect(presenceA).toContainText("Online"); + + // Instance B (offline): presence badge should say "Offline". + const presenceB = page.getByTestId(`instance-presence-${INSTANCE_PUBKEY_B}`); + await expect(presenceB).toBeVisible(); + await expect(presenceB).toContainText("Offline"); +}); diff --git a/desktop/tests/helpers/bridge.ts b/desktop/tests/helpers/bridge.ts index 0234254410..7c03dc3002 100644 --- a/desktop/tests/helpers/bridge.ts +++ b/desktop/tests/helpers/bridge.ts @@ -318,6 +318,52 @@ type MockBridgeOptions = { * "Archived on this relay" flair + Unarchive button. */ archivedIdentities?: string[]; + /** + * Snapshot returned by `get_owned_agent_inventory`. Drives the Instances + * Sheet content and start-control safeguard in + * `tests/e2e/agent-instances-sheet.spec.ts`. + * Omitted → empty snapshot with archive state trusted. + */ + ownedAgentInventory?: { + archiveStateTrusted: boolean; + /** Instances grouped by persona ID. Keys are persona IDs. */ + byPersonaId: Record< + string, + Array<{ + pubkey: string; + displayName: string | null; + picture: string | null; + relayUrl: string; + nipIaOwnerProof: { result: string; declared_owner?: string }; + archiveState: { isArchived: boolean | null }; + personaId: string | null; + /** `null` for relay-only instances (no local record on this device). */ + local: { + pubkey: string; + name: string; + personaId: string | null; + } | null; + }> + >; + /** Instances with no parseable persona ID (standalone agents). */ + unknown: Array<{ + pubkey: string; + displayName: string | null; + picture: string | null; + relayUrl: string; + nipIaOwnerProof: { result: string; declared_owner?: string }; + archiveState: { isArchived: boolean | null }; + personaId: string | null; + local: { pubkey: string; name: string; personaId: string | null } | null; + }>; + }; + /** + * Per-pubkey presence overrides for instance-sheet tests. + * Seeded into the mock presence map so `get_presence` returns the specified + * status for these pubkeys. Keys are lowercase hex pubkeys; values are + * "online" | "away" | "offline". + */ + presenceOverrides?: Record; /** * Drives the `is_me` field of `resolve_oa_owner`. When true, the harness * reports the active identity as the verified NIP-OA owner of the viewee