The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
feat(security): route device store through document backend
Steven Enamakelc2916d16b325
diff --git a/crates/openhuman-core/src/security/devices/store.rs b/crates/openhuman-core/src/security/devices/store.rsindex 40eb0f3745..e5bba9dbd1 100644--- a/crates/openhuman-core/src/security/devices/store.rs+++ b/crates/openhuman-core/src/security/devices/store.rs@@ -1,5 +1,8 @@//! SQLite persistence for paired devices.//!+//! With a storage backend configured ([`crate::storage`]) every function+//! here is served from the document port instead (`store_documents.rs`).+//!//! Follows the same `with_connection` pattern as `cron/store.rs`://! open a per-call connection to a domain-scoped `.db` file inside the//! workspace directory, execute DDL on each open (idempotent), then run@@ -24,6 +27,9 @@ pub fn insert_device(device_pubkey: &str,core_session_token_hash: &str,) -> Result<PairedDevice> {+ if let Some(docs) = super::store_documents::current()? {+ return docs.insert_device(channel_id, label, device_pubkey, core_session_token_hash);+ }let now = Utc::now().to_rfc3339();with_connection(config, |conn| {conn.execute(@@ -47,6 +53,9 @@ pub fn insert_device(/// Update `last_seen_at` for a device (called on `tunnel:peer-status` online events).pub fn touch_device(config: &Config, channel_id: &str) -> Result<()> {+ if let Some(docs) = super::store_documents::current()? {+ return docs.touch_device(channel_id);+ }let now = Utc::now().to_rfc3339();with_connection(config, |conn| {conn.execute(@@ -60,6 +69,9 @@ pub fn touch_device(config: &Config, channel_id: &str) -> Result<()> {/// Mark a device as revoked (soft delete).pub fn revoke_device(config: &Config, channel_id: &str) -> Result<bool> {+ if let Some(docs) = super::store_documents::current()? {+ return docs.revoke_device(channel_id);+ }let rows = with_connection(config, |conn| {conn.execute("UPDATE paired_devices SET revoked = 1 WHERE channel_id = ?1",@@ -72,6 +84,9 @@ pub fn revoke_device(config: &Config, channel_id: &str) -> Result<bool> {/// Load a single paired device by channel_id (returns None if not found).pub fn get_device(config: &Config, channel_id: &str) -> Result<Option<PairedDevice>> {+ if let Some(docs) = super::store_documents::current()? {+ return docs.get_device(channel_id);+ }with_connection(config, |conn| {let mut stmt = conn.prepare("SELECT channel_id, label, device_pubkey, created_at, last_seen_at, revoked \@@ -84,6 +99,9 @@ pub fn get_device(config: &Config, channel_id: &str) -> Result<Option<PairedDevi/// List all non-revoked paired devices ordered by creation time.pub fn list_devices(config: &Config) -> Result<Vec<PairedDevice>> {+ if let Some(docs) = super::store_documents::current()? {+ return docs.list_devices();+ }with_connection(config, |conn| {let mut stmt = conn.prepare("SELECT channel_id, label, device_pubkey, created_at, last_seen_at, revoked \diff --git a/crates/openhuman-core/src/security/devices/store_documents.rs b/crates/openhuman-core/src/security/devices/store_documents.rsnew file mode 100644index 0000000000..05cee945b0--- /dev/null+++ b/crates/openhuman-core/src/security/devices/store_documents.rs@@ -0,0 +1,133 @@+//! Paired devices on the `tinystoragedrivers` document port.+//!+//! Used instead of `devices/devices.db` when the host configured a storage+//! backend ([`crate::storage`]); the functions in `store.rs` pick it per call.+//! Devices live under the current call's storage scope (the acting agent,+//! `local` on a single-user host).+//!+//! One `paired_devices` document per `channel_id`, with the SQLite columns as+//! fields. Pairing replaces a document outright (`INSERT OR REPLACE`);+//! touching and revoking are compare-and-swap, so a touch never revives a+//! device another process revoked in between.++use anyhow::Result;+use chrono::Utc;+use serde_json::{json, Value};+use tinystoragedrivers::{CollectionSpec, Filter, IndexSpec, Precondition, Query, Sort, Versioned};++use crate::security::devices::types::PairedDevice;+use crate::storage::documents::{compare_and_swap, text, Repo};+use crate::storage::{DocumentStoreExt, ScopedStorage};++const DEVICES: &str = "paired_devices";+const DOMAIN: &str = "devices::store";++fn collections() -> Vec<CollectionSpec> {+ vec![CollectionSpec::new(DEVICES).index(IndexSpec::new("by_active", ["revoked", "created_at"]))]+}++/// The document store for this call, when the host configured one.+pub(super) fn current() -> Result<Option<Docs>> {+ Ok(Repo::current(DOMAIN, collections)?.map(Docs))+}++fn to_device(stored: &Versioned<Value>) -> PairedDevice {+ let doc = &stored.doc;+ PairedDevice {+ channel_id: stored.id.clone(),+ label: text(doc, "label").unwrap_or_default().to_string(),+ device_pubkey: text(doc, "device_pubkey").unwrap_or_default().to_string(),+ created_at: text(doc, "created_at").unwrap_or_default().to_string(),+ last_seen_at: text(doc, "last_seen_at").map(str::to_string),+ peer_online: None,+ revoked: doc.get("revoked").and_then(Value::as_bool).unwrap_or(false),+ }+}++/// The paired-device store over one scoped document handle.+#[derive(Clone)]+pub(super) struct Docs(Repo);++impl Docs {+ #[cfg(test)]+ pub(super) fn over(scoped: &ScopedStorage) -> Self {+ Self(Repo::over(scoped, DOMAIN, collections))+ }++ pub(super) fn insert_device(+ &self,+ channel_id: &str,+ label: &str,+ device_pubkey: &str,+ core_session_token_hash: &str,+ ) -> Result<PairedDevice> {+ let id = channel_id.to_string();+ let doc = json!({+ "label": label,+ "device_pubkey": device_pubkey,+ "core_session_token_hash": core_session_token_hash,+ "created_at": Utc::now().to_rfc3339(),+ "last_seen_at": Value::Null,+ "revoked": false,+ });+ self.0.run(|docs| async move {+ let version = docs.put(DEVICES, &id, doc.clone(), Precondition::None).await?;+ Ok(to_device(&Versioned { id, version, doc }))+ })+ }++ pub(super) fn touch_device(&self, channel_id: &str) -> Result<()> {+ let id = channel_id.to_string();+ let now = Utc::now().to_rfc3339();+ self.0.run(|docs| async move {+ compare_and_swap(&docs, DEVICES, &id, |doc| {+ if doc.get("revoked") == Some(&json!(true)) {+ return None;+ }+ let mut next = doc.clone();+ next["last_seen_at"] = json!(now);+ Some(next)+ })+ .await+ .map(|_| ())+ })+ }++ pub(super) fn revoke_device(&self, channel_id: &str) -> Result<bool> {+ let id = channel_id.to_string();+ self.0.run(|docs| async move {+ // Like the SQL `UPDATE`, revoking an already revoked device still+ // reports that the device exists.+ let revoked = compare_and_swap(&docs, DEVICES, &id, |doc| {+ let mut next = doc.clone();+ next["revoked"] = json!(true);+ Some(next)+ })+ .await?;+ Ok(revoked.is_some())+ })+ }++ pub(super) fn get_device(&self, channel_id: &str) -> Result<Option<PairedDevice>> {+ let id = channel_id.to_string();+ self.0.run(|docs| async move {+ Ok(docs.get(DEVICES, &id).await?.as_ref().map(to_device))+ })+ }++ pub(super) fn list_devices(&self) -> Result<Vec<PairedDevice>> {+ self.0.run(|docs| async move {+ let query = Query::filter(Filter::eq("revoked", false)).sort(Sort::asc("created_at"));+ Ok(docs+ .query_all(DEVICES, &query)+ .await?+ .iter()+ .map(to_device)+ .collect())+ })+ }+}++#[cfg(test)]+#[path = "store_documents_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/security/devices/store_documents_tests.rs b/crates/openhuman-core/src/security/devices/store_documents_tests.rsnew file mode 100644index 0000000000..33843f4603--- /dev/null+++ b/crates/openhuman-core/src/security/devices/store_documents_tests.rs@@ -0,0 +1,84 @@+use super::*;+use crate::storage::{MemoryStorage, Scope, StorageBackend};++fn docs_in(storage: &MemoryStorage, scope: &str) -> Docs {+ Docs::over(&storage.for_scope(&Scope::new(scope).unwrap()).unwrap())+}++fn docs() -> Docs {+ docs_in(&MemoryStorage::new(), "local")+}++#[test]+fn a_paired_device_round_trips() {+ let store = docs();+ let device = store.insert_device("ch-1", "iPhone", "pk", "hash").unwrap();+ assert_eq!(device.channel_id, "ch-1");+ assert_eq!(device.label, "iPhone");+ assert!(!device.revoked);+ assert!(device.last_seen_at.is_none());+ let read = store.get_device("ch-1").unwrap().expect("stored");+ assert_eq!(read.device_pubkey, "pk");+ assert_eq!(read.created_at, device.created_at);+ assert!(store.get_device("missing").unwrap().is_none());+}++#[test]+fn pairing_again_replaces_the_device() {+ let store = docs();+ store.insert_device("ch-1", "old", "pk1", "h").unwrap();+ store.revoke_device("ch-1").unwrap();+ let again = store.insert_device("ch-1", "new", "pk2", "h").unwrap();+ assert!(!again.revoked, "a re-pair clears the revocation");+ assert_eq!(store.list_devices().unwrap()[0].label, "new");+}++#[test]+fn touch_marks_live_devices_only() {+ let store = docs();+ store.insert_device("live", "a", "pk", "h").unwrap();+ store.insert_device("gone", "b", "pk", "h").unwrap();+ store.revoke_device("gone").unwrap();+ store.touch_device("live").unwrap();+ store.touch_device("gone").unwrap();+ store.touch_device("missing").unwrap();+ assert!(store.get_device("live").unwrap().unwrap().last_seen_at.is_some());+ assert!(store.get_device("gone").unwrap().unwrap().last_seen_at.is_none());+}++#[test]+fn revoke_hides_the_device_and_reports_existence() {+ let store = docs();+ store.insert_device("ch-1", "a", "pk", "h").unwrap();+ assert!(store.revoke_device("ch-1").unwrap());+ assert!(store.revoke_device("ch-1").unwrap(), "still exists");+ assert!(!store.revoke_device("missing").unwrap());+ assert!(store.list_devices().unwrap().is_empty());+ assert!(store.get_device("ch-1").unwrap().unwrap().revoked);+}++#[test]+fn devices_list_oldest_first() {+ let store = docs();+ store.insert_device("first", "a", "pk", "h").unwrap();+ std::thread::sleep(std::time::Duration::from_millis(5));+ store.insert_device("second", "b", "pk", "h").unwrap();+ let ids: Vec<String> = store+ .list_devices()+ .unwrap()+ .into_iter()+ .map(|device| device.channel_id)+ .collect();+ assert_eq!(ids, ["first", "second"]);+}++#[test]+fn scopes_keep_devices_apart() {+ let storage = MemoryStorage::new();+ docs_in(&storage, "alice")+ .insert_device("ch-1", "a", "pk", "h")+ .unwrap();+ let bob = docs_in(&storage, "bob");+ assert!(bob.list_devices().unwrap().is_empty());+ assert!(!bob.revoke_device("ch-1").unwrap());+}