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): persist device documents in storage
Steven Enamakel033b493f7e65
diff --git a/crates/openhuman-core/src/security/devices/store_documents.rs b/crates/openhuman-core/src/security/devices/store_documents.rsindex c8e1e697b6..60ba2092bd 100644--- a/crates/openhuman-core/src/security/devices/store_documents.rs+++ b/crates/openhuman-core/src/security/devices/store_documents.rs@@ -14,14 +14,16 @@use anyhow::Result;use chrono::Utc;use serde_json::{json, Value};-use tinystoragedrivers::{CollectionSpec, Filter, IndexSpec, Precondition, Query, Sort, Versioned};+use tinystoragedrivers::{CollectionSpec, Filter, Precondition, Query, Sort, Versioned};use crate::config::Config;use crate::security::devices::types::PairedDevice;use crate::storage::documents::{compare_and_swap, text, Repo};use crate::storage::DocumentStoreExt;-pub(super) const DEVICES: &str = "paired_devices";+use super::storage_schema::{legacy_collections, spec, DEVICES};+use crate::storage::schema_support::{key_of, ms_rfc3339};+const DOMAIN: &str = "devices::store";/// The legacy `devices.db`, as the storage importer reads it.@@ -29,14 +31,14 @@ pub(crate) fn import_source() -> crate::storage::import::Source {crate::storage::import::Source {domain: "devices",db: "devices/devices.db",- collections,+ collections: legacy_collections,read_legacy: |scratch, _real| super::store_import::read(scratch),rekey: |record, _config| record,}}fn collections() -> Vec<CollectionSpec> {- vec![CollectionSpec::new(DEVICES).index(IndexSpec::new("by_active", ["revoked", "created_at"]))]+ vec![spec()]}/// The document store for this call: the storage backend, in the acting scope.@@ -48,14 +50,25 @@ pub(super) fn current(config: &Config) -> Result<Docs> {)?))}+/// The channel id a document id was built from (ids are `Key::of` of it).+fn channel_id_of(id: &str) -> String {+ tinystoragedrivers::Key::from_stored(id)+ .split()+ .and_then(|mut parts| (parts.len() == 1).then(|| parts.remove(0)))+ .unwrap_or_else(|| id.to_string())+}+fn to_device(stored: &Versioned<Value>) -> PairedDevice {let doc = &stored.doc;PairedDevice {- channel_id: stored.id.clone(),+ channel_id: channel_id_of(&stored.id),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),+ created_at: ms_rfc3339(doc.get("created_ms").and_then(Value::as_i64).unwrap_or(0)),+ last_seen_at: doc+ .get("last_seen_ms")+ .and_then(Value::as_i64)+ .map(ms_rfc3339),peer_online: None,revoked: doc.get("revoked").and_then(Value::as_bool).unwrap_or(false),}@@ -78,13 +91,12 @@ impl Docs {device_pubkey: &str,core_session_token_hash: &str,) -> Result<PairedDevice> {- let id = channel_id.to_string();+ let id = key_of(channel_id)?;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,+ "created_ms": Utc::now().timestamp_millis(),"revoked": false,});self.0.run(|docs| async move {@@ -101,15 +113,15 @@ impl Docs {}pub(super) fn touch_device(&self, channel_id: &str) -> Result<()> {- let id = channel_id.to_string();- let now = Utc::now().to_rfc3339();+ let id = key_of(channel_id)?;+ let now = Utc::now().timestamp_millis();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);+ next["last_seen_ms"] = json!(now);Some(next)}).await@@ -118,7 +130,7 @@ impl Docs {}pub(super) fn revoke_device(&self, channel_id: &str) -> Result<bool> {- let id = channel_id.to_string();+ let id = key_of(channel_id)?;self.0.run(|docs| async move {// Like the SQL `UPDATE`, revoking an already revoked device still// reports that the device exists.@@ -133,14 +145,14 @@ impl Docs {}pub(super) fn get_device(&self, channel_id: &str) -> Result<Option<PairedDevice>> {- let id = channel_id.to_string();+ let id = key_of(channel_id)?;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"));+ let query = Query::filter(Filter::eq("revoked", false)).sort(Sort::asc("created_ms"));Ok(docs.query_all(DEVICES, &query).await?diff --git a/crates/openhuman-core/src/storage/schema_support.rs b/crates/openhuman-core/src/storage/schema_support.rsindex 1cb6a288b4..a5caf2dfba 100644--- a/crates/openhuman-core/src/storage/schema_support.rs+++ b/crates/openhuman-core/src/storage/schema_support.rs@@ -29,6 +29,15 @@ pub fn rfc3339_ms(text: &str) -> Option<i64> {.map(|at| at.timestamp_millis())}+/// The RFC 3339 form of `ms` epoch milliseconds, for an RPC type that still+/// presents a formatted time. An out-of-range value reads as the epoch.+#[must_use]+pub fn ms_rfc3339(ms: i64) -> String {+ chrono::DateTime::from_timestamp_millis(ms)+ .unwrap_or_default()+ .to_rfc3339_opts(chrono::SecondsFormat::Millis, true)+}+/// The time held by `body[field]`, as epoch milliseconds: an RFC 3339 string.#[must_use]pub fn time_ms(body: &Value, field: &str) -> Option<i64> {