Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(store): P1.2 users table + writer/reader commands
AkitaOnRails76ecc3d77636
diff --git a/Cargo.lock b/Cargo.lockindex ff486e38..6689625d 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -199,6 +199,8 @@ version = "0.7.1"dependencies = ["ai-memory-core","anyhow",+ "base64",+ "getrandom 0.3.4","jiff","parking_lot","refinery",@@ -206,6 +208,7 @@ dependencies = ["serde","serde_json","sha2",+ "subtle","tempfile","thiserror 2.0.18","tokio",diff --git a/crates/ai-memory-core/src/error.rs b/crates/ai-memory-core/src/error.rsindex 97ebebce..732e0a50 100644--- a/crates/ai-memory-core/src/error.rs+++ b/crates/ai-memory-core/src/error.rs@@ -23,6 +23,18 @@ pub enum MemoryError {#[error("malformed record in store: {0}")]MalformedRecord(String),+ /// A username failed the validation rules in+ /// [`crate::user::validate_username`] (empty, too long, contains+ /// whitespace / control / separator characters).+ #[error("invalid username: {0}")]+ InvalidUsername(String),++ /// An email failed the basic format check in+ /// [`crate::user::validate_email`] (missing `@`, whitespace in+ /// local or domain part, empty parts, …).+ #[error("invalid email: {0}")]+ InvalidEmail(String),+/// Wraps any underlying I/O failure.#[error(transparent)]Io(#[from] std::io::Error),diff --git a/crates/ai-memory-core/src/lib.rs b/crates/ai-memory-core/src/lib.rsindex 631b5927..37ce3407 100644--- a/crates/ai-memory-core/src/lib.rs+++ b/crates/ai-memory-core/src/lib.rs@@ -14,6 +14,7 @@ pub mod observation;pub mod page;pub mod routing_snippet;pub mod sanitize;+pub mod user;/// Default workspace name used by the single-workspace v1 flow.pub const DEFAULT_WORKSPACE_NAME: &str = "default";@@ -33,3 +34,4 @@ pub use observation::{NewObservation, NewSession, Observation, ObservationKind};pub use page::{LinkTarget, NewPage, Page, Tier};pub use routing_snippet::{MARKER_END, MARKER_START, SNIPPET_BODY, full_block};pub use sanitize::{SanitizeConfig, Sanitized, Sanitizer};+pub use user::{MAX_EMAIL_LEN, MAX_USERNAME_LEN, NewUser, User, validate_email, validate_username};diff --git a/crates/ai-memory-core/src/user.rs b/crates/ai-memory-core/src/user.rsnew file mode 100644index 00000000..c8587806--- /dev/null+++ b/crates/ai-memory-core/src/user.rs@@ -0,0 +1,417 @@+//! Registered-user domain types + validation.+//!+//! The storage shape lives in `ai-memory-store`; this module owns the+//! **pure types** + **input validation** that both the writer (insert+//! path) and the CLI / admin endpoint (caller path) share. Keeping the+//! rules in core means the same `MemoryError::InvalidUsername`+//! materialises whether a username is rejected by the CLI, the HTTP+//! handler, or the writer actor — one source of truth.+//!+//! ## Attribution, not RBAC+//!+//! See [`crate::actor`] for the broader rationale: ai-memory's data is+//! single-tenant by design. A `User` row records *who* a write came+//! from; it does not gate *whether* the write was allowed.+//!+//! ## Token storage (referenced here, implemented in `ai-memory-store`)+//!+//! Tokens are 32 bytes of CSPRNG (256 bits of entropy). The store keeps+//! a single `SHA-256(token || ":" || pepper)` digest per user; the+//! per-server pepper from `[auth].token_pepper` makes a DB-only theft+//! useless to an offline attacker. SHA-256 gives an O(1) UNIQUE-index+//! lookup the per-request auth hot path needs. See+//! `ai_memory_store::users` for the actual hash + generate helpers.++use serde::{Deserialize, Serialize};++use crate::{MemoryError, UserId};++/// Maximum username length. Anything longer is a misconfiguration; the+/// engine, CLI, and web UI all assume a small username fits in a single+/// terminal column / table cell.+pub const MAX_USERNAME_LEN: usize = 64;++/// Maximum email length per RFC 5321 §4.5.3.1.3 (path length).+pub const MAX_EMAIL_LEN: usize = 254;++/// A registered user as stored. `id` is the UUIDv7 primary key; the+/// other fields mirror the `users` table.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct User {+ /// Stable identity. Used by `audit_log.author_id` and+ /// `pages.author_id` foreign keys.+ pub id: UserId,+ /// Validated username (see [`validate_username`]).+ pub username: String,+ /// Optional display name for "Last edited by Alice Smith" style UIs.+ pub name: Option<String>,+ /// Optional email; validated by [`validate_email`] before insert.+ pub email: Option<String>,+ /// Microseconds since epoch — V01 convention.+ pub created_at: i64,+ /// Microseconds since epoch; `None` until the first authenticated+ /// request from this user. Updated fire-and-forget per request.+ pub last_seen_at: Option<i64>,+ /// Microseconds since epoch; `None` means the token is active.+ /// `ai-memory user expire` stamps it, `revive` clears it,+ /// `rotate-token` issues a fresh hash AND implicitly clears this+ /// field (rotating a token only makes sense to make it usable again).+ pub token_expired_at: Option<i64>,+}++impl User {+ /// `true` if the user's current token is usable. Auth middleware+ /// uses this to short-circuit the request before hitting any+ /// further state.+ #[must_use]+ pub fn is_token_active(&self) -> bool {+ self.token_expired_at.is_none()+ }+}++/// Pre-insert shape for a new user. Carries the inputs the caller+/// (CLI / admin endpoint) collected; the actual token generation ++/// hashing lives in `ai-memory-store::users` since it owns the+/// per-server pepper.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct NewUser {+ /// Required. Will be trimmed + validated; rejected if empty after+ /// trim, longer than [`MAX_USERNAME_LEN`], or contains whitespace /+ /// control characters / common separator chars.+ pub username: String,+ /// Optional display name. Trimmed; empty string is normalised to+ /// `None` so the DB doesn't store distinct `""` and `NULL`.+ pub name: Option<String>,+ /// Optional email. Trimmed + lowercased + validated by+ /// [`validate_email`]; empty string is normalised to `None`.+ pub email: Option<String>,+}++impl NewUser {+ /// In-place validate + normalise. Returns the same error kinds the+ /// CLI and admin endpoint surface to the operator.+ ///+ /// # Errors+ /// - [`MemoryError::InvalidUsername`] when the username is empty+ /// after trim, too long, or contains forbidden characters.+ /// - [`MemoryError::InvalidEmail`] when an email is supplied but+ /// fails the basic format check.+ pub fn validate(&mut self) -> Result<(), MemoryError> {+ self.username = self.username.trim().to_string();+ validate_username(&self.username)?;++ if let Some(name) = self.name.as_mut() {+ *name = name.trim().to_string();+ }+ if self.name.as_deref() == Some("") {+ self.name = None;+ }++ if let Some(email) = self.email.as_mut() {+ *email = email.trim().to_lowercase();+ }+ match self.email.as_deref() {+ Some("") => self.email = None,+ Some(e) => validate_email(e)?,+ None => {}+ }++ Ok(())+ }+}++/// Validate a username after trim. Rules — kept minimal per the v0.8+/// design call (no complex policies, just enough to keep weird+/// characters out):+///+/// - non-empty;+/// - at most [`MAX_USERNAME_LEN`] characters (code points, not bytes);+/// - no control characters (`is_control`);+/// - no whitespace anywhere (usernames are identifiers, not free text);+/// - no common separator / quoting characters that would make CLI+/// quoting + URL embedding painful: `/ \ : ; , " ' ` `.+///+/// UTF-8 letters / digits / `.` / `-` / `_` / `@` are allowed, so+/// emails-as-usernames (`alice@home`) work for operators who want them.+///+/// # Errors+/// Returns [`MemoryError::InvalidUsername`] on any rule violation.+pub fn validate_username(s: &str) -> Result<(), MemoryError> {+ if s.is_empty() {+ return Err(MemoryError::InvalidUsername("empty after trim".into()));+ }+ let len = s.chars().count();+ if len > MAX_USERNAME_LEN {+ return Err(MemoryError::InvalidUsername(format!(+ "{len} characters, exceeds max {MAX_USERNAME_LEN}"+ )));+ }+ for ch in s.chars() {+ if ch.is_control() {+ return Err(MemoryError::InvalidUsername(format!(+ "control character U+{:04X}",+ ch as u32+ )));+ }+ if ch.is_whitespace() {+ return Err(MemoryError::InvalidUsername(format!(+ "whitespace character {ch:?}"+ )));+ }+ if matches!(ch, '/' | '\\' | ':' | ';' | ',' | '"' | '\'' | '`') {+ return Err(MemoryError::InvalidUsername(format!(+ "separator character {ch:?}"+ )));+ }+ }+ Ok(())+}++/// Basic email-format check. Intentionally permissive — operators may+/// use intranet-style addresses (`alice@home`) without a public TLD, so+/// we don't require a dot in the domain. Rules:+///+/// - at most [`MAX_EMAIL_LEN`] characters;+/// - exactly one `@`;+/// - non-empty local + non-empty domain;+/// - no whitespace anywhere;+/// - no control characters.+///+/// This is the "doesn't look obviously wrong" check, not RFC 5322+/// compliance. Quoted local parts, IP-literal domains in brackets, and+/// other rare-but-valid forms are not supported.+///+/// # Errors+/// Returns [`MemoryError::InvalidEmail`] on any rule violation.+pub fn validate_email(s: &str) -> Result<(), MemoryError> {+ let len = s.chars().count();+ if len > MAX_EMAIL_LEN {+ return Err(MemoryError::InvalidEmail(format!(+ "{len} characters, exceeds max {MAX_EMAIL_LEN}"+ )));+ }+ for ch in s.chars() {+ if ch.is_control() {+ return Err(MemoryError::InvalidEmail(format!(+ "control character U+{:04X}",+ ch as u32+ )));+ }+ if ch.is_whitespace() {+ return Err(MemoryError::InvalidEmail(format!(+ "whitespace character {ch:?}"+ )));+ }+ }+ let mut parts = s.split('@');+ let local = parts.next().unwrap_or_default();+ let domain = parts.next().unwrap_or_default();+ if parts.next().is_some() {+ return Err(MemoryError::InvalidEmail("multiple `@` characters".into()));+ }+ if local.is_empty() {+ return Err(MemoryError::InvalidEmail("empty local part".into()));+ }+ if domain.is_empty() {+ return Err(MemoryError::InvalidEmail("empty domain part".into()));+ }+ Ok(())+}++#[cfg(test)]+mod tests {+ use super::*;++ // ── username validation ───────────────────────────────────────++ #[test]+ fn username_accepts_simple() {+ assert!(validate_username("alice").is_ok());+ assert!(validate_username("boss").is_ok());+ assert!(validate_username("user_1").is_ok());+ assert!(validate_username("a.b-c").is_ok());+ }++ #[test]+ fn username_accepts_email_style() {+ // Emails-as-usernames must work for operators who want them.+ assert!(validate_username("alice@home").is_ok());+ assert!(validate_username("[email protected]").is_ok());+ }++ #[test]+ fn username_accepts_utf8_letters() {+ assert!(validate_username("bóss").is_ok());+ assert!(validate_username("ボス").is_ok());+ }++ #[test]+ fn username_rejects_empty() {+ assert!(validate_username("").is_err());+ }++ #[test]+ fn username_rejects_whitespace() {+ for s in ["boss man", "boss\tman", "boss\nman", " boss", "boss "] {+ assert!(+ validate_username(s).is_err(),+ "whitespace must be rejected: {s:?}"+ );+ }+ }++ #[test]+ fn username_rejects_control_chars() {+ assert!(validate_username("boss\x00").is_err());+ assert!(validate_username("boss\x07man").is_err());+ assert!(validate_username("boss\x7fman").is_err());+ }++ #[test]+ fn username_rejects_separator_chars() {+ for ch in ['/', '\\', ':', ';', ',', '"', '\'', '`'] {+ let s = format!("boss{ch}man");+ assert!(+ validate_username(&s).is_err(),+ "{ch:?} must be rejected: {s:?}"+ );+ }+ }++ #[test]+ fn username_rejects_over_length() {+ let too_long = "a".repeat(MAX_USERNAME_LEN + 1);+ assert!(validate_username(&too_long).is_err());+ let just_right = "a".repeat(MAX_USERNAME_LEN);+ assert!(validate_username(&just_right).is_ok());+ }++ // ── email validation ──────────────────────────────────────────++ #[test]+ fn email_accepts_typical() {+ assert!(validate_email("[email protected]").is_ok());+ assert!(validate_email("[email protected]").is_ok());+ assert!(validate_email("[email protected]").is_ok());+ }++ #[test]+ fn email_accepts_intranet_no_tld() {+ // Homelab users have `alice@home` setups; the basic check must+ // not require a dot in the domain.+ assert!(validate_email("alice@home").is_ok());+ assert!(validate_email("boss@localhost").is_ok());+ }++ #[test]+ fn email_rejects_missing_at() {+ assert!(validate_email("alice.example.com").is_err());+ }++ #[test]+ fn email_rejects_multiple_at() {+ assert!(validate_email("alice@@example.com").is_err());+ assert!(validate_email("a@b@c").is_err());+ }++ #[test]+ fn email_rejects_empty_parts() {+ assert!(validate_email("@example.com").is_err());+ assert!(validate_email("alice@").is_err());+ assert!(validate_email("@").is_err());+ }++ #[test]+ fn email_rejects_whitespace() {+ for s in ["alice @example.com", "alice@ example.com", " [email protected]"] {+ assert!(+ validate_email(s).is_err(),+ "whitespace must be rejected: {s:?}"+ );+ }+ }++ #[test]+ fn email_rejects_control_chars() {+ assert!(validate_email("alice\[email protected]").is_err());+ }++ #[test]+ fn email_rejects_over_length() {+ let local = "a".repeat(MAX_EMAIL_LEN);+ let too_long = format!("{local}@x");+ assert!(validate_email(&too_long).is_err());+ }++ // ── NewUser::validate normalisation ───────────────────────────++ #[test]+ fn new_user_trims_username() {+ let mut nu = NewUser {+ username: " alice ".into(),+ name: None,+ email: None,+ };+ nu.validate().unwrap();+ assert_eq!(nu.username, "alice");+ }++ #[test]+ fn new_user_normalises_empty_optionals_to_none() {+ let mut nu = NewUser {+ username: "alice".into(),+ name: Some(" ".into()),+ email: Some(" ".into()),+ };+ nu.validate().unwrap();+ assert_eq!(nu.name, None);+ assert_eq!(nu.email, None);+ }++ #[test]+ fn new_user_lowercases_email() {+ let mut nu = NewUser {+ username: "alice".into(),+ name: None,+ email: Some("[email protected]".into()),+ };+ nu.validate().unwrap();+ assert_eq!(nu.email.as_deref(), Some("[email protected]"));+ }++ #[test]+ fn new_user_trims_name() {+ let mut nu = NewUser {+ username: "alice".into(),+ name: Some(" Alice Smith ".into()),+ email: None,+ };+ nu.validate().unwrap();+ // Internal whitespace is fine in a display name — only the+ // edges get trimmed.+ assert_eq!(nu.name.as_deref(), Some("Alice Smith"));+ }++ #[test]+ fn new_user_rejects_invalid_username() {+ let mut nu = NewUser {+ username: "boss man".into(),+ name: None,+ email: None,+ };+ assert!(matches!(+ nu.validate(),+ Err(MemoryError::InvalidUsername(_))+ ));+ }++ #[test]+ fn new_user_rejects_invalid_email() {+ let mut nu = NewUser {+ username: "alice".into(),+ name: None,+ email: Some("not-an-email".into()),+ };+ assert!(matches!(nu.validate(), Err(MemoryError::InvalidEmail(_))));+ }+}diff --git a/crates/ai-memory-store/Cargo.toml b/crates/ai-memory-store/Cargo.tomlindex adddedd9..4121abe0 100644--- a/crates/ai-memory-store/Cargo.toml+++ b/crates/ai-memory-store/Cargo.toml@@ -19,6 +19,14 @@ tracing.workspace = truejiff.workspace = trueuuid.workspace = truesha2.workspace = true+# Token generation + comparison primitives for the users table.+# `getrandom` reads OS CSPRNG bytes; `base64` URL-encodes the+# generated token for safe transport; `subtle` provides+# constant-time slice equality for the hash compare in the+# auth hot path.+getrandom.workspace = true+base64.workspace = true+subtle.workspace = truerusqlite.workspace = truerefinery.workspace = trueparking_lot.workspace = truediff --git a/crates/ai-memory-store/migrations/V14__users.sql b/crates/ai-memory-store/migrations/V14__users.sqlnew file mode 100644index 00000000..a9f9dac9--- /dev/null+++ b/crates/ai-memory-store/migrations/V14__users.sql@@ -0,0 +1,40 @@+-- Multi-user attribution.+--+-- ai-memory's data model stays single-tenant: every authenticated user sees+-- the same wiki pages (no RBAC, no per-user data scoping). What this table+-- adds is **attribution** — every page and audit-log row can carry an+-- `author_id` so the engine, web UI, and `/api/v1` consumers can say "alice+-- wrote this page yesterday" instead of just "this page exists".+--+-- The root user lives in `config.toml` under `[auth]` (root_username,+-- root_email, root_name); it's NOT inserted here — auth middleware+-- synthesises a root ActorContext when the bearer token matches the config+-- root token, then attributes writes to that synthetic identity. Added+-- users (created via `ai-memory user add` / `POST /admin/users`) are the+-- rows in this table.+--+-- Token storage: a single SHA-256(token || ":" || pepper) digest per user.+-- Tokens are 32 bytes of CSPRNG (256 bits of entropy), so brute-force is+-- infeasible regardless of hash strength; the per-server pepper (from+-- `[auth].token_pepper`, auto-generated at `ai-memory init`) makes a+-- DB-only theft useless to an offline attacker. SHA-256 buys us a+-- deterministic 32-byte lookup key with O(1) UNIQUE-index hits, which the+-- per-request auth path needs.+--+-- token_expired_at: NULL means the token is active. `ai-memory user expire`+-- stamps it; `revive` clears it. The user row itself is never deleted —+-- historical `author_id` references keep pointing at it forever so old+-- attribution doesn't vanish when a user leaves. `rotate-token` issues a+-- new hash AND implicitly clears `token_expired_at` (rotating a token only+-- makes sense if you want it usable again).++CREATE TABLE users (+ id BLOB NOT NULL PRIMARY KEY, -- UUIDv7+ username TEXT NOT NULL UNIQUE, -- validated in core::user+ name TEXT, -- optional display name+ email TEXT UNIQUE COLLATE NOCASE, -- optional; case-insensitive unique+ token_hash BLOB NOT NULL UNIQUE, -- SHA-256(token || ":" || pepper); 32 bytes+ created_at INTEGER NOT NULL, -- microseconds since epoch (V01 convention)+ last_seen_at INTEGER, -- microseconds since epoch; NULL until first auth'd request+ token_expired_at INTEGER -- microseconds since epoch; NULL = active token+);diff --git a/crates/ai-memory-store/src/error.rs b/crates/ai-memory-store/src/error.rsindex 7862541c..a0c77011 100644--- a/crates/ai-memory-store/src/error.rs+++ b/crates/ai-memory-store/src/error.rs@@ -47,4 +47,17 @@ pub enum StoreError {/// The supplied project name failed validation (empty, slash, etc.).#[error("invalid project name: {0}")]InvalidProjectName(String),++ /// A UNIQUE constraint was violated by an insert (e.g. duplicate+ /// `users.username` / `users.email`). The string carries a+ /// human-readable explanation the CLI / admin endpoint surfaces+ /// verbatim.+ #[error("duplicate: {0}")]+ Duplicate(String),++ /// An OS primitive failed (e.g. the CSPRNG read inside+ /// [`crate::users::generate_token`]). Carries the OS error+ /// description.+ #[error("os error: {0}")]+ Os(String),}diff --git a/crates/ai-memory-store/src/lib.rs b/crates/ai-memory-store/src/lib.rsindex 92159a94..b52a0c93 100644--- a/crates/ai-memory-store/src/lib.rs+++ b/crates/ai-memory-store/src/lib.rs@@ -18,6 +18,7 @@ mod fts_query;mod migrations;mod ops;mod reader;+pub mod users;mod writer;pub use fts_query::prepare_fts5_query;@@ -31,6 +32,7 @@ pub use reader::{PageLinks, PageMeta, PageSummary, ProjectSummary, ReaderPool, RelatedPage, StatusCounts,StoredEmbedding, WorkspaceSummary, f32_vec_to_bytes,};+pub use users::{TOKEN_HASH_LEN, TOKEN_RAW_LEN, TokenPepper, generate_token, hash_token};pub use writer::WriterHandle;/// Filename used inside the data dir's `db/` subdirectory.diff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rsindex 4cd312bf..fd1b1c97 100644--- a/crates/ai-memory-store/src/reader.rs+++ b/crates/ai-memory-store/src/reader.rs@@ -12,7 +12,7 @@ use std::sync::Arc;use ai_memory_core::{AgentKind, Handoff, HandoffId, HandoffState, Observation, ObservationId, ObservationKind,- PageId, PagePath, ProjectId, SessionId, WorkspaceId,+ PageId, PagePath, ProjectId, SessionId, User, UserId, WorkspaceId,};use parking_lot::Mutex;use rusqlite::types::Value;@@ -24,6 +24,7 @@ use serde::Serialize;use crate::error::{StoreError, StoreResult};use crate::fts_query::prepare_fts5_query;+use crate::users::TOKEN_HASH_LEN;/// One hit returned by [`ReaderPool::search_pages`].#[derive(Debug, Clone, Serialize)]@@ -2748,6 +2749,55 @@ impl ReaderPool {}).await}++ // ── user lookups ────────────────────────────────────────────────++ /// Hot path for the auth middleware: hash the incoming bearer token,+ /// look up the matching row, and return the user iff their token is+ /// active (`token_expired_at IS NULL`).+ ///+ /// # Errors+ /// Propagates any SQL or pool error. Returns `Ok(None)` when no row+ /// matches the hash (either no such user, or the token was expired).+ pub async fn find_active_user_by_token_hash(+ &self,+ token_hash: [u8; TOKEN_HASH_LEN],+ ) -> StoreResult<Option<User>> {+ self.with_conn(move |conn| crate::users::find_active_user_by_token_hash(conn, &token_hash))+ .await+ }++ /// Look up a user by exact-match username. Used by admin endpoints+ /// that accept username on the wire (`expire`, `revive`,+ /// `rotate-token`).+ ///+ /// # Errors+ /// Propagates any SQL or pool error.+ pub async fn find_user_by_username(&self, username: String) -> StoreResult<Option<User>> {+ self.with_conn(move |conn| crate::users::find_user_by_username(conn, &username))+ .await+ }++ /// Look up a user by id. **Returns even users whose token is expired**+ /// — this is the attribution-display path (a page authored by alice+ /// must still render "alice" after her token has been expired).+ ///+ /// # Errors+ /// Propagates any SQL or pool error.+ pub async fn find_user_by_id(&self, id: UserId) -> StoreResult<Option<User>> {+ self.with_conn(move |conn| crate::users::find_user_by_id(conn, id))+ .await+ }++ /// All registered users, ordered by `created_at` ascending. Includes+ /// users whose token is expired (the CLI surfaces the active/expired+ /// flag from `token_expired_at`).+ ///+ /// # Errors+ /// Propagates any SQL or pool error.+ pub async fn list_users(&self) -> StoreResult<Vec<User>> {+ self.with_conn(crate::users::list_users).await+ }}/// Map a `(workspace, project, path, title, kind)` row to a [`HealthPage`].diff --git a/crates/ai-memory-store/src/users.rs b/crates/ai-memory-store/src/users.rsnew file mode 100644index 00000000..51c5c8bf--- /dev/null+++ b/crates/ai-memory-store/src/users.rs@@ -0,0 +1,640 @@+//! User management — SQL ops + token generation/hashing.+//!+//! ## Token storage rationale+//!+//! Tokens are 32 bytes of OS CSPRNG (256 bits of entropy), URL-safe+//! base64-encoded for transport. The stored digest is+//! `SHA-256(token || ":" || pepper)` where `pepper` is a per-server+//! secret kept in `[auth].token_pepper` (auto-generated by+//! `ai-memory init`).+//!+//! Why SHA-256, not argon2id:+//!+//! - **Brute force is infeasible regardless of hash strength.** 2^256+//! search space dwarfs any plausible offline campaign. Argon2id's slow+//! hashing buys nothing against tokens of this entropy.+//! - **Per-request lookup is the hot path.** SHA-256 is deterministic →+//! indexed `UNIQUE` lookup is O(1). Argon2id's per-hash salt would+//! force an O(N) scan + hash-compare per request, or a separate+//! deterministic index column that argon2id was meant to replace.+//! - **The realistic threat is DB-only theft.** An attacker without the+//! config can't reconstruct any token because the pepper isn't in the+//! stolen rows. (An attacker with both the DB *and* the config has+//! tokens directly anyway — argon2id wouldn't help.)+//!+//! Token comparison in the auth path uses [`subtle::ConstantTimeEq`]+//! to side-step timing attacks against the hash compare.+//!+//! ## Function layout+//!+//! Each function takes a `&Connection` (or `&Transaction`) and returns+//! a `StoreResult`. The writer actor owns the connection; these+//! functions don't open or close it. The lookup functions take+//! `&Connection` for read-pool use. See module-level tests for the+//! intended call shapes.++use ai_memory_core::{NewUser, User, UserId};+use base64::Engine;+use base64::engine::general_purpose::URL_SAFE_NO_PAD;+use jiff::Timestamp;+use rusqlite::{Connection, OptionalExtension, params};+use sha2::{Digest, Sha256};+use subtle::ConstantTimeEq;++use crate::error::{StoreError, StoreResult};++/// Length of a SHA-256 digest in bytes. The `users.token_hash` column+/// stores exactly this many bytes per row.+pub const TOKEN_HASH_LEN: usize = 32;++/// Length of a raw token in bytes (256 bits of entropy). The+/// URL-safe-base64-encoded form returned by [`generate_token`] is 43+/// characters (32 bytes → ⌈32*4/3⌉ = 43 unpadded chars).+pub const TOKEN_RAW_LEN: usize = 32;++/// Per-server token pepper, newtyped to keep it from being mixed up with+/// other secrets at call sites. Carries the secret read from+/// `[auth].token_pepper` in config; clone is cheap (small `String`).+#[derive(Debug, Clone)]+pub struct TokenPepper {+ inner: String,+}++impl TokenPepper {+ /// Wrap a config-loaded pepper. The caller's responsibility to+ /// ensure it carries enough entropy — `ai-memory init` generates+ /// a 32-byte CSPRNG hex-encoded pepper by default.+ #[must_use]+ pub fn new(s: impl Into<String>) -> Self {+ Self { inner: s.into() }+ }++ /// Bytes used as the second argument to the hash. The `:` separator+ /// in [`hash_token`] lives outside this method so callers can't+ /// accidentally omit it.+ fn as_bytes(&self) -> &[u8] {+ self.inner.as_bytes()+ }+}++/// Hash a plaintext token to its storage digest.+///+/// Layout: `SHA-256(token || ":" || pepper)`. The literal `:` byte+/// between the two inputs prevents the (cosmetic but real)+/// `token || pepper` ambiguity where some `(t1, p1)` and `(t2, p2)`+/// pairs would otherwise collide if `t1 || p1 == t2 || p2`.+#[must_use]+pub fn hash_token(token: &str, pepper: &TokenPepper) -> [u8; TOKEN_HASH_LEN] {+ let mut hasher = Sha256::new();+ hasher.update(token.as_bytes());+ hasher.update(b":");+ hasher.update(pepper.as_bytes());+ hasher.finalize().into()+}++/// Constant-time comparison of a fresh hash against a stored row hash.+/// Equivalent to `==` for correctness; differs in timing characteristics.+#[must_use]+pub fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {+ a.ct_eq(b).into()+}++/// Generate a fresh URL-safe-base64 token. 32 bytes of OS CSPRNG, 43+/// characters of output (unpadded). The caller is expected to display+/// this exactly once (returning it from `POST /admin/users` or+/// `POST /admin/users/:username/rotate-token`) and never store it.+///+/// # Errors+/// Returns [`StoreError::Os`] if the OS CSPRNG read fails. In practice+/// this only happens on misconfigured embedded platforms.+pub fn generate_token() -> StoreResult<String> {+ let mut bytes = [0u8; TOKEN_RAW_LEN];+ getrandom::fill(&mut bytes)+ .map_err(|e| StoreError::Os(format!("os csprng failed during token generation: {e}")))?;+ Ok(URL_SAFE_NO_PAD.encode(bytes))+}++// ── SQL ops ────────────────────────────────────────────────────────++/// Insert a fresh user row. `new_user` MUST have been validated by+/// [`NewUser::validate`](ai_memory_core::NewUser::validate) before this+/// call; the writer actor owns that pre-flight.+///+/// # Errors+/// - [`StoreError::Duplicate`] when `username` or `email` clashes with+/// an existing row (UNIQUE violation).+/// - [`StoreError::Sql`] for any other SQL failure.+pub fn insert_user(+ conn: &Connection,+ new_user: &NewUser,+ token_hash: &[u8; TOKEN_HASH_LEN],+) -> StoreResult<UserId> {+ let id = UserId::new();+ let now = Timestamp::now().as_microsecond();+ conn.execute(+ "INSERT INTO users \+ (id, username, name, email, token_hash, created_at) \+ VALUES (?1, ?2, ?3, ?4, ?5, ?6)",+ params![+ id.as_bytes(),+ &new_user.username,+ &new_user.name,+ &new_user.email,+ token_hash.as_slice(),+ now,+ ],+ )+ .map_err(map_unique_violation)?;+ Ok(id)+}++/// Replace the user's `token_hash` with a freshly-generated digest, and+/// clear `token_expired_at` (rotating a token only makes sense to make+/// it usable again). Returns whether a row was actually updated; `false`+/// means the user id didn't exist.+///+/// # Errors+/// Returns [`StoreError::Sql`] for any SQL failure other than the+/// "no row matched" case (which is reported as `Ok(false)`).+pub fn rotate_user_token(+ conn: &Connection,+ id: UserId,+ new_token_hash: &[u8; TOKEN_HASH_LEN],+) -> StoreResult<bool> {+ let rows = conn.execute(+ "UPDATE users SET token_hash = ?1, token_expired_at = NULL WHERE id = ?2",+ params![new_token_hash.as_slice(), id.as_bytes()],+ )?;+ Ok(rows > 0)+}++/// Stamp `token_expired_at = now()` — the user's current token stops+/// authenticating but the row stays put so historical attribution+/// references remain valid. Idempotent: expiring an already-expired+/// token returns `Ok(true)` and leaves `token_expired_at` unchanged.+///+/// # Errors+/// Returns [`StoreError::Sql`] for any SQL failure.+pub fn expire_user_token(conn: &Connection, id: UserId) -> StoreResult<bool> {+ let now = Timestamp::now().as_microsecond();+ let rows = conn.execute(+ "UPDATE users SET token_expired_at = COALESCE(token_expired_at, ?1) WHERE id = ?2",+ params![now, id.as_bytes()],+ )?;+ Ok(rows > 0)+}++/// Clear `token_expired_at`, re-activating the user's existing token.+/// Idempotent: reviving an already-active token is a no-op.+///+/// # Errors+/// Returns [`StoreError::Sql`] for any SQL failure.+pub fn revive_user_token(conn: &Connection, id: UserId) -> StoreResult<bool> {+ let rows = conn.execute(+ "UPDATE users SET token_expired_at = NULL WHERE id = ?1",+ params![id.as_bytes()],+ )?;+ Ok(rows > 0)+}++/// Update `last_seen_at = now()` for the user. Called fire-and-forget+/// by the auth middleware on every authenticated request; never blocks+/// the response. Returns `Ok(false)` when the row doesn't exist (the+/// caller authenticated against a token whose user was deleted+/// mid-request — already a logic error elsewhere).+///+/// # Errors+/// Returns [`StoreError::Sql`] for any SQL failure.+pub fn touch_user_last_seen(conn: &Connection, id: UserId) -> StoreResult<bool> {+ let now = Timestamp::now().as_microsecond();+ let rows = conn.execute(+ "UPDATE users SET last_seen_at = ?1 WHERE id = ?2",+ params![now, id.as_bytes()],+ )?;+ Ok(rows > 0)+}++/// Look up the user that owns `token_hash` IF the token is currently+/// active (`token_expired_at IS NULL`). Hot path for the auth+/// middleware.+///+/// # Errors+/// Returns [`StoreError::Sql`] for any SQL failure other than "no row+/// matched" (which is reported as `Ok(None)`).+pub fn find_active_user_by_token_hash(+ conn: &Connection,+ token_hash: &[u8; TOKEN_HASH_LEN],+) -> StoreResult<Option<User>> {+ conn.query_row(+ "SELECT id, username, name, email, created_at, last_seen_at, token_expired_at \+ FROM users WHERE token_hash = ?1 AND token_expired_at IS NULL",+ params![token_hash.as_slice()],+ row_to_user,+ )+ .optional()+ .map_err(StoreError::from)+}++/// Look up a user by exact-match username. Used by the admin endpoints+/// (`expire`, `revive`, `rotate-token` all accept username on the wire).+///+/// # Errors+/// Returns [`StoreError::Sql`] for any SQL failure other than "no row+/// matched" (`Ok(None)`).+pub fn find_user_by_username(conn: &Connection, username: &str) -> StoreResult<Option<User>> {+ conn.query_row(+ "SELECT id, username, name, email, created_at, last_seen_at, token_expired_at \+ FROM users WHERE username = ?1",+ params![username],+ row_to_user,+ )+ .optional()+ .map_err(StoreError::from)+}++/// Look up a user by id. **Returns even users whose token is expired**+/// — needed by the attribution display path (we still want to render+/// "alice wrote this last month" after alice's token has been expired).+///+/// # Errors+/// Returns [`StoreError::Sql`] for any SQL failure other than "no row+/// matched" (`Ok(None)`).+pub fn find_user_by_id(conn: &Connection, id: UserId) -> StoreResult<Option<User>> {+ conn.query_row(+ "SELECT id, username, name, email, created_at, last_seen_at, token_expired_at \+ FROM users WHERE id = ?1",+ params![id.as_bytes()],+ row_to_user,+ )+ .optional()+ .map_err(StoreError::from)+}++/// All users, ordered by `created_at` ascending. Used by+/// `GET /admin/users` / `ai-memory user list`. Includes users whose+/// token is expired (the CLI surfaces the active/expired flag from+/// `token_expired_at`).+///+/// # Errors+/// Returns [`StoreError::Sql`] for any SQL failure.+pub fn list_users(conn: &Connection) -> StoreResult<Vec<User>> {+ let mut stmt = conn.prepare(+ "SELECT id, username, name, email, created_at, last_seen_at, token_expired_at \+ FROM users ORDER BY created_at ASC",+ )?;+ let rows = stmt+ .query_map([], row_to_user)?+ .collect::<Result<Vec<_>, _>>()?;+ Ok(rows)+}++// ── helpers ────────────────────────────────────────────────────────++fn row_to_user(row: &rusqlite::Row<'_>) -> rusqlite::Result<User> {+ let id_bytes: Vec<u8> = row.get(0)?;+ let id = UserId::from_slice(&id_bytes).map_err(|e| {+ rusqlite::Error::FromSqlConversionFailure(+ 0,+ rusqlite::types::Type::Blob,+ Box::new(std::io::Error::other(e.to_string())),+ )+ })?;+ Ok(User {+ id,+ username: row.get(1)?,+ name: row.get(2)?,+ email: row.get(3)?,+ created_at: row.get(4)?,+ last_seen_at: row.get(5)?,+ token_expired_at: row.get(6)?,+ })+}++/// Map SQLite UNIQUE-violation errors to a typed `Duplicate`. Anything+/// else passes through verbatim. The CLI / admin endpoint relies on+/// this to render a readable "username already taken" message.+fn map_unique_violation(e: rusqlite::Error) -> StoreError {+ if let rusqlite::Error::SqliteFailure(sqlite_err, msg) = &e+ && sqlite_err.code == rusqlite::ErrorCode::ConstraintViolation+ {+ let text = msg.clone().unwrap_or_else(|| sqlite_err.to_string());+ // SQLite reports `UNIQUE constraint failed: users.username`+ // (or `users.email`); the substring is stable across versions.+ if text.contains("users.username") {+ return StoreError::Duplicate("username already taken".into());+ }+ if text.contains("users.email") {+ return StoreError::Duplicate("email already in use".into());+ }+ if text.contains("users.token_hash") {+ return StoreError::Duplicate("token hash collision".into());+ }+ return StoreError::Duplicate(text);+ }+ StoreError::from(e)+}++#[cfg(test)]+mod tests {+ use super::*;+ use ai_memory_core::NewUser;+ use rusqlite::Connection;++ fn fresh_conn() -> Connection {+ let mut conn = Connection::open_in_memory().unwrap();+ conn.pragma_update(None, "foreign_keys", "ON").unwrap();+ crate::migrations::run(&mut conn).expect("migrations::run");+ conn+ }++ fn pepper() -> TokenPepper {+ TokenPepper::new("test-pepper-1234567890abcdef")+ }++ fn sample_new_user(name: &str) -> NewUser {+ NewUser {+ username: name.to_string(),+ name: None,+ email: None,+ }+ }++ #[test]+ fn hash_token_is_deterministic_and_isolates_pepper() {+ let p = pepper();+ let h1 = hash_token("hunter2", &p);+ let h2 = hash_token("hunter2", &p);+ assert_eq!(h1, h2, "same input → same hash");++ let p2 = TokenPepper::new("different-pepper");+ let h3 = hash_token("hunter2", &p2);+ assert_ne!(h1, h3, "different pepper → different hash");++ let h4 = hash_token("hunter3", &p);+ assert_ne!(h1, h4, "different token → different hash");+ }++ #[test]+ fn hash_token_separator_blocks_ambiguous_concatenation() {+ // Without the `:` separator, ("ab", "cd") and ("abc", "d") would+ // hash the same input. The separator prevents that.+ let p1 = TokenPepper::new("cd");+ let p2 = TokenPepper::new("d");+ let h1 = hash_token("ab", &p1);+ let h2 = hash_token("abc", &p2);+ assert_ne!(h1, h2);+ }++ #[test]+ fn generate_token_emits_url_safe_base64_of_expected_length() {+ let tok = generate_token().unwrap();+ // URL-safe-no-pad of 32 bytes is 43 chars (`(32*8+5)/6 = 43`).+ assert_eq!(tok.len(), 43);+ assert!(+ tok.chars()+ .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')+ );+ }++ #[test]+ fn generate_token_is_unique_per_call() {+ let a = generate_token().unwrap();+ let b = generate_token().unwrap();+ assert_ne!(a, b);+ }++ #[test]+ fn insert_then_find_by_username_round_trip() {+ let conn = fresh_conn();+ let p = pepper();+ let hash = hash_token("the-token", &p);++ let mut nu = sample_new_user("alice");+ nu.validate().unwrap();+ let id = insert_user(&conn, &nu, &hash).unwrap();++ let found = find_user_by_username(&conn, "alice").unwrap().unwrap();+ assert_eq!(found.id, id);+ assert_eq!(found.username, "alice");+ assert!(found.is_token_active());+ }++ #[test]+ fn insert_rejects_duplicate_username() {+ let conn = fresh_conn();+ let p = pepper();+ let mut nu = sample_new_user("alice");+ nu.validate().unwrap();++ let h1 = hash_token("token-a", &p);+ let h2 = hash_token("token-b", &p);+ insert_user(&conn, &nu, &h1).unwrap();+ let err = insert_user(&conn, &nu, &h2).unwrap_err();+ assert!(+ matches!(&err, StoreError::Duplicate(m) if m.contains("username")),+ "expected Duplicate(username), got {err:?}"+ );+ }++ #[test]+ fn insert_rejects_duplicate_email_case_insensitive() {+ let conn = fresh_conn();+ let p = pepper();+ let mut a = NewUser {+ username: "alice".into(),+ name: None,+ email: Some("[email protected]".into()),+ };+ a.validate().unwrap();+ insert_user(&conn, &a, &hash_token("ta", &p)).unwrap();++ let mut b = NewUser {+ username: "bob".into(),+ name: None,+ email: Some("[email protected]".into()),+ };+ b.validate().unwrap();+ // Both lowercased to `[email protected]` — UNIQUE COLLATE NOCASE+ // catches it even without the validation lowercase.+ let err = insert_user(&conn, &b, &hash_token("tb", &p)).unwrap_err();+ assert!(matches!(&err, StoreError::Duplicate(m) if m.contains("email")));+ }++ #[test]+ fn find_active_user_by_token_hash_returns_only_active() {+ let conn = fresh_conn();+ let p = pepper();+ let token = "live-token";+ let hash = hash_token(token, &p);+ let mut nu = sample_new_user("alice");+ nu.validate().unwrap();+ let id = insert_user(&conn, &nu, &hash).unwrap();++ // Active → returns Some.+ let found = find_active_user_by_token_hash(&conn, &hash).unwrap();+ assert_eq!(found.unwrap().id, id);++ // After expire → returns None.+ let updated = expire_user_token(&conn, id).unwrap();+ assert!(updated);+ let found = find_active_user_by_token_hash(&conn, &hash).unwrap();+ assert!(+ found.is_none(),+ "expired user must NOT come back from active-token lookup"+ );+ }++ #[test]+ fn find_user_by_id_returns_even_expired_users() {+ // Critical for attribution: a page authored by alice last+ // month must still display "alice" today even after alice's+ // token has been expired.+ let conn = fresh_conn();+ let p = pepper();+ let mut nu = sample_new_user("alice");+ nu.validate().unwrap();+ let id = insert_user(&conn, &nu, &hash_token("t", &p)).unwrap();+ expire_user_token(&conn, id).unwrap();++ let found = find_user_by_id(&conn, id).unwrap().unwrap();+ assert_eq!(found.id, id);+ assert!(found.token_expired_at.is_some());+ assert!(!found.is_token_active());+ }++ #[test]+ fn expire_is_idempotent_preserving_original_timestamp() {+ let conn = fresh_conn();+ let p = pepper();+ let mut nu = sample_new_user("alice");+ nu.validate().unwrap();+ let id = insert_user(&conn, &nu, &hash_token("t", &p)).unwrap();++ expire_user_token(&conn, id).unwrap();+ let first = find_user_by_id(&conn, id)+ .unwrap()+ .unwrap()+ .token_expired_at;+ assert!(first.is_some());++ // Second expire call must not move the timestamp forward —+ // COALESCE in the UPDATE keeps the original.+ expire_user_token(&conn, id).unwrap();+ let second = find_user_by_id(&conn, id)+ .unwrap()+ .unwrap()+ .token_expired_at;+ assert_eq!(first, second, "expire must be idempotent");+ }++ #[test]+ fn revive_clears_expiration() {+ let conn = fresh_conn();+ let p = pepper();+ let mut nu = sample_new_user("alice");+ nu.validate().unwrap();+ let id = insert_user(&conn, &nu, &hash_token("t", &p)).unwrap();++ expire_user_token(&conn, id).unwrap();+ assert!(+ !find_user_by_id(&conn, id)+ .unwrap()+ .unwrap()+ .is_token_active()+ );++ revive_user_token(&conn, id).unwrap();+ assert!(+ find_user_by_id(&conn, id)+ .unwrap()+ .unwrap()+ .is_token_active()+ );+ }++ #[test]+ fn rotate_token_issues_new_hash_and_revives() {+ let conn = fresh_conn();+ let p = pepper();+ let mut nu = sample_new_user("alice");+ nu.validate().unwrap();+ let h_old = hash_token("old-token", &p);+ let id = insert_user(&conn, &nu, &h_old).unwrap();+ expire_user_token(&conn, id).unwrap();++ let h_new = hash_token("new-token", &p);+ let updated = rotate_user_token(&conn, id, &h_new).unwrap();+ assert!(updated);++ // Old hash no longer authenticates.+ assert!(+ find_active_user_by_token_hash(&conn, &h_old)+ .unwrap()+ .is_none()+ );+ // New hash does — and the user is implicitly revived.+ let found = find_active_user_by_token_hash(&conn, &h_new).unwrap();+ assert_eq!(found.unwrap().id, id);+ }++ #[test]+ fn touch_last_seen_records_timestamp() {+ let conn = fresh_conn();+ let p = pepper();+ let mut nu = sample_new_user("alice");+ nu.validate().unwrap();+ let id = insert_user(&conn, &nu, &hash_token("t", &p)).unwrap();+ assert!(+ find_user_by_id(&conn, id)+ .unwrap()+ .unwrap()+ .last_seen_at+ .is_none(),+ "fresh users have no last_seen_at"+ );++ touch_user_last_seen(&conn, id).unwrap();+ assert!(+ find_user_by_id(&conn, id)+ .unwrap()+ .unwrap()+ .last_seen_at+ .is_some(),+ "touch must populate last_seen_at"+ );+ }++ #[test]+ fn list_users_orders_by_created_at_ascending() {+ let conn = fresh_conn();+ let p = pepper();+ for name in ["alice", "bob", "carol"] {+ let mut nu = sample_new_user(name);+ nu.validate().unwrap();+ insert_user(&conn, &nu, &hash_token(name, &p)).unwrap();+ }+ let users = list_users(&conn).unwrap();+ assert_eq!(users.len(), 3);+ let usernames: Vec<_> = users.iter().map(|u| u.username.as_str()).collect();+ assert_eq!(usernames, vec!["alice", "bob", "carol"]);+ }++ #[test]+ fn rotate_returns_false_for_unknown_user() {+ let conn = fresh_conn();+ let p = pepper();+ let ghost = UserId::new();+ let updated = rotate_user_token(&conn, ghost, &hash_token("x", &p)).unwrap();+ assert!(!updated);+ }++ #[test]+ fn constant_time_eq_matches_plain_eq() {+ let a = [1u8, 2, 3, 4];+ let b = [1u8, 2, 3, 4];+ let c = [1u8, 2, 3, 5];+ assert!(constant_time_eq(&a, &b));+ assert!(!constant_time_eq(&a, &c));+ assert!(!constant_time_eq(&a, &[1u8, 2, 3]));+ }+}diff --git a/crates/ai-memory-store/src/writer.rs b/crates/ai-memory-store/src/writer.rsindex 127badae..1c61e73d 100644--- a/crates/ai-memory-store/src/writer.rs+++ b/crates/ai-memory-store/src/writer.rs@@ -11,14 +11,15 @@ use std::sync::{Arc, Mutex};use std::thread::{self, JoinHandle};use ai_memory_core::{- AgentKind, HandoffId, NewHandoff, NewObservation, NewPage, NewSession, ObservationId, PageId,- ProjectId, SessionId, WorkspaceId,+ AgentKind, HandoffId, NewHandoff, NewObservation, NewPage, NewSession, NewUser, ObservationId,+ PageId, ProjectId, SessionId, UserId, WorkspaceId,};use rusqlite::Connection;use tokio::sync::{mpsc, oneshot};use crate::error::{StoreError, StoreResult};use crate::ops::{self, EmbeddingWrite, PurgeSummary, ReorgSummary};+use crate::users::{self, TOKEN_HASH_LEN};/// Commands accepted by the writer thread.pub(crate) enum WriteCmd {@@ -128,6 +129,28 @@ pub(crate) enum WriteCmd {applied_at: i64,reply: oneshot::Sender<StoreResult<()>>,},+ CreateUser {+ new_user: NewUser,+ token_hash: [u8; TOKEN_HASH_LEN],+ reply: oneshot::Sender<StoreResult<UserId>>,+ },+ RotateUserToken {+ user_id: UserId,+ new_token_hash: [u8; TOKEN_HASH_LEN],+ reply: oneshot::Sender<StoreResult<bool>>,+ },+ ExpireUserToken {+ user_id: UserId,+ reply: oneshot::Sender<StoreResult<bool>>,+ },+ ReviveUserToken {+ user_id: UserId,+ reply: oneshot::Sender<StoreResult<bool>>,+ },+ TouchUserLastSeen {+ user_id: UserId,+ reply: oneshot::Sender<StoreResult<bool>>,+ },Shutdown,}@@ -494,6 +517,94 @@ impl WriterHandle {rx.await.map_err(|_| StoreError::WriterClosed)?}+ /// Insert a new user. `new_user` MUST already have been validated by+ /// [`NewUser::validate`](ai_memory_core::NewUser::validate); the+ /// caller (CLI or admin handler) generates the plaintext token,+ /// hashes it with the per-server pepper via+ /// [`crate::users::hash_token`], and passes only the digest in.+ ///+ /// # Errors+ /// - [`StoreError::WriterClosed`] if the writer has shut down.+ /// - [`StoreError::Duplicate`] when the username or email collides.+ /// - [`StoreError::Sqlite`] for any other SQL failure.+ pub async fn create_user(+ &self,+ new_user: NewUser,+ token_hash: [u8; TOKEN_HASH_LEN],+ ) -> StoreResult<UserId> {+ let (tx, rx) = oneshot::channel();+ self.send(WriteCmd::CreateUser {+ new_user,+ token_hash,+ reply: tx,+ })+ .await?;+ rx.await.map_err(|_| StoreError::WriterClosed)?+ }++ /// Replace a user's token hash with a freshly-generated digest.+ /// Implicitly clears `token_expired_at` — rotating an expired+ /// token only makes sense to make it usable again. Returns `false`+ /// when the user id doesn't exist; `true` on successful update.+ ///+ /// # Errors+ /// Returns [`StoreError::WriterClosed`] / [`StoreError::Sqlite`]+ /// per the usual writer-actor flow.+ pub async fn rotate_user_token(+ &self,+ user_id: UserId,+ new_token_hash: [u8; TOKEN_HASH_LEN],+ ) -> StoreResult<bool> {+ let (tx, rx) = oneshot::channel();+ self.send(WriteCmd::RotateUserToken {+ user_id,+ new_token_hash,+ reply: tx,+ })+ .await?;+ rx.await.map_err(|_| StoreError::WriterClosed)?+ }++ /// Stamp `token_expired_at = now()` so the user's current token stops+ /// authenticating. Idempotent — repeating the call leaves the original+ /// expiry timestamp untouched. Returns `false` when the user doesn't exist.+ ///+ /// # Errors+ /// Returns [`StoreError::WriterClosed`] / [`StoreError::Sqlite`].+ pub async fn expire_user_token(&self, user_id: UserId) -> StoreResult<bool> {+ let (tx, rx) = oneshot::channel();+ self.send(WriteCmd::ExpireUserToken { user_id, reply: tx })+ .await?;+ rx.await.map_err(|_| StoreError::WriterClosed)?+ }++ /// Clear `token_expired_at`, re-activating the user's existing token.+ /// Idempotent. Returns `false` when the user doesn't exist.+ ///+ /// # Errors+ /// Returns [`StoreError::WriterClosed`] / [`StoreError::Sqlite`].+ pub async fn revive_user_token(&self, user_id: UserId) -> StoreResult<bool> {+ let (tx, rx) = oneshot::channel();+ self.send(WriteCmd::ReviveUserToken { user_id, reply: tx })+ .await?;+ rx.await.map_err(|_| StoreError::WriterClosed)?+ }++ /// Update `last_seen_at = now()` for the user. Called fire-and-forget+ /// by the auth middleware on every authenticated request. Returns+ /// `false` when the user doesn't exist (caller authenticated against+ /// a token whose user vanished mid-request — already a logic error+ /// elsewhere).+ ///+ /// # Errors+ /// Returns [`StoreError::WriterClosed`] / [`StoreError::Sqlite`].+ pub async fn touch_user_last_seen(&self, user_id: UserId) -> StoreResult<bool> {+ let (tx, rx) = oneshot::channel();+ self.send(WriteCmd::TouchUserLastSeen { user_id, reply: tx })+ .await?;+ rx.await.map_err(|_| StoreError::WriterClosed)?+ }+async fn send(&self, cmd: WriteCmd) -> StoreResult<()> {self.inner.tx@@ -676,6 +787,34 @@ fn worker_loop(mut conn: Connection, mut rx: mpsc::Receiver<WriteCmd>) {let result = ops::insert_wiki_migration(&mut conn, &name, applied_at);send_or_warn(reply, result, "insert_wiki_migration");}+ WriteCmd::CreateUser {+ new_user,+ token_hash,+ reply,+ } => {+ let result = users::insert_user(&conn, &new_user, &token_hash);+ send_or_warn(reply, result, "create_user");+ }+ WriteCmd::RotateUserToken {+ user_id,+ new_token_hash,+ reply,+ } => {+ let result = users::rotate_user_token(&conn, user_id, &new_token_hash);+ send_or_warn(reply, result, "rotate_user_token");+ }+ WriteCmd::ExpireUserToken { user_id, reply } => {+ let result = users::expire_user_token(&conn, user_id);+ send_or_warn(reply, result, "expire_user_token");+ }+ WriteCmd::ReviveUserToken { user_id, reply } => {+ let result = users::revive_user_token(&conn, user_id);+ send_or_warn(reply, result, "revive_user_token");+ }+ WriteCmd::TouchUserLastSeen { user_id, reply } => {+ let result = users::touch_user_last_seen(&conn, user_id);+ send_or_warn(reply, result, "touch_user_last_seen");+ }}}tracing::debug!("writer thread exiting cleanly");