From d63b1c7d3bfa2fa73132de1f905796014af9cd86 Mon Sep 17 00:00:00 2001 From: DarkSky Date: Wed, 25 Nov 2026 18:25:32 +0900 Subject: [PATCH] feat(frontend): add IDB v3/V1 store, legacy import, and L3 client core Add the Wasm IndexedDB v3/V1 storage model, cross-tab BroadcastChannel codec, frozen v0.27.5 REST and GraphQL request/response codecs, and SQLite inbound sync batch persistence in affine-store. Add the pure-Rust affine-legacy-import crate for allowlisted Capacitor WebView localStorage parsing, positive sentinel validation, and rollback-window writeback serialization. Add the device-neutral affine-client L3 domain crate with HostBridge, ServerRegistry (enforcing F3 on Web hosts), AuthController, StoreBackedDocDirectory (closing root registration, anti-resurrection, and restart recovery invariants), workspace domain services, exact substring weighted search, 25-language i18n catalog, and production PlatformAccessibility first-frame semantic root entry. --- packages/common/store/src/api_client.rs | 541 +++++++++++ packages/common/store/src/id_converter.rs | 10 + packages/common/store/src/idb/mod.rs | 862 ++++++++++++++++++ packages/common/store/src/idb/origin.rs | 136 +++ packages/common/store/src/idb/v1.rs | 406 +++++++++ packages/common/store/src/lib.rs | 2 + packages/common/store/src/sqlite/storage.rs | 13 +- packages/common/store/src/sqlite/sync.rs | 93 ++ packages/common/store/src/sync/engine/mod.rs | 4 +- packages/frontend/AGENTS.md | 2 +- packages/frontend/Cargo.lock | 23 + packages/frontend/Cargo.toml | 4 + packages/frontend/client/AGENTS.md | 13 + packages/frontend/client/CLAUDE.md | 1 + packages/frontend/client/Cargo.toml | 22 + packages/frontend/client/src/accessibility.rs | 226 +++++ packages/frontend/client/src/auth.rs | 541 +++++++++++ packages/frontend/client/src/bootstrap.rs | 116 +++ packages/frontend/client/src/doc_directory.rs | 585 ++++++++++++ packages/frontend/client/src/domain.rs | 546 +++++++++++ packages/frontend/client/src/host.rs | 145 +++ packages/frontend/client/src/i18n.rs | 313 +++++++ packages/frontend/client/src/lib.rs | 95 ++ packages/frontend/client/src/search.rs | 178 ++++ packages/frontend/client/src/server.rs | 198 ++++ packages/frontend/legacy-import/AGENTS.md | 14 + packages/frontend/legacy-import/CLAUDE.md | 1 + packages/frontend/legacy-import/Cargo.toml | 15 + packages/frontend/legacy-import/src/lib.rs | 521 +++++++++++ .../frontend/legacy-import/src/sentinel.rs | 216 +++++ .../frontend/legacy-import/src/writeback.rs | 245 +++++ 31 files changed, 6083 insertions(+), 4 deletions(-) create mode 100644 packages/common/store/src/api_client.rs create mode 100644 packages/common/store/src/idb/mod.rs create mode 100644 packages/common/store/src/idb/origin.rs create mode 100644 packages/common/store/src/idb/v1.rs create mode 100644 packages/frontend/client/AGENTS.md create mode 100644 packages/frontend/client/CLAUDE.md create mode 100644 packages/frontend/client/Cargo.toml create mode 100644 packages/frontend/client/src/accessibility.rs create mode 100644 packages/frontend/client/src/auth.rs create mode 100644 packages/frontend/client/src/bootstrap.rs create mode 100644 packages/frontend/client/src/doc_directory.rs create mode 100644 packages/frontend/client/src/domain.rs create mode 100644 packages/frontend/client/src/host.rs create mode 100644 packages/frontend/client/src/i18n.rs create mode 100644 packages/frontend/client/src/lib.rs create mode 100644 packages/frontend/client/src/search.rs create mode 100644 packages/frontend/client/src/server.rs create mode 100644 packages/frontend/legacy-import/AGENTS.md create mode 100644 packages/frontend/legacy-import/CLAUDE.md create mode 100644 packages/frontend/legacy-import/Cargo.toml create mode 100644 packages/frontend/legacy-import/src/lib.rs create mode 100644 packages/frontend/legacy-import/src/sentinel.rs create mode 100644 packages/frontend/legacy-import/src/writeback.rs diff --git a/packages/common/store/src/api_client.rs b/packages/common/store/src/api_client.rs new file mode 100644 index 0000000000..d25c85f068 --- /dev/null +++ b/packages/common/store/src/api_client.rs @@ -0,0 +1,541 @@ +//! Frozen `v0.27.5` REST (`/api/auth/session*`) and GraphQL (`/graphql`) request/response codecs. + +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; + +use crate::{ + error::{StoreError, StoreResult}, + sync::DEFAULT_CLIENT_VERSION, +}; + +/// Header carrying the client protocol version (`x-affine-version`). +pub const HEADER_AFFINE_VERSION: &str = "x-affine-version"; + +/// Header distinguishing `web` (same-origin cookie/CSRF) vs `native` (Bearer token) clients. +pub const HEADER_CLIENT_KIND: &str = "x-affine-client-kind"; + +/// Header carrying the refresh retry counter on `POST /api/auth/session/refresh`. +pub const HEADER_REFRESH_ATTEMPT: &str = "x-affine-refresh-attempt"; + +/// Client kind wire value for `x-affine-client-kind`. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum ApiClientKind { + Web, + Native, +} + +impl ApiClientKind { + pub const fn as_str(self) -> &'static str { + match self { + Self::Web => "web", + Self::Native => "native", + } + } +} + +/// HTTP method for transport-agnostic API requests. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum ApiHttpMethod { + Get, + Post, + Delete, +} + +/// Transport-agnostic HTTP request emitted by frozen REST and GraphQL codecs. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct ApiHttpRequest { + pub method: ApiHttpMethod, + pub path: String, + pub headers: Vec<(String, String)>, + pub body: Option>, +} + +/// Common request context for building frozen AFFiNE server API calls. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct ApiRequestContext { + pub client_kind: ApiClientKind, + pub client_version: String, + pub bearer_token: Option, +} + +impl ApiRequestContext { + pub fn web() -> Self { + Self { + client_kind: ApiClientKind::Web, + client_version: DEFAULT_CLIENT_VERSION.to_string(), + bearer_token: None, + } + } + + pub fn native(bearer_token: Option) -> Self { + Self { + client_kind: ApiClientKind::Native, + client_version: DEFAULT_CLIENT_VERSION.to_string(), + bearer_token, + } + } + + fn base_headers(&self, json_body: bool) -> Vec<(String, String)> { + let mut headers = vec![ + ( + HEADER_AFFINE_VERSION.to_string(), + self.client_version.clone(), + ), + ( + HEADER_CLIENT_KIND.to_string(), + self.client_kind.as_str().to_string(), + ), + ("cache-control".to_string(), "no-store".to_string()), + ]; + if json_body { + headers.push(("content-type".to_string(), "application/json".to_string())); + } + if self.client_kind == ApiClientKind::Native + && let Some(ref token) = self.bearer_token + { + headers.push(("authorization".to_string(), format!("Bearer {token}"))); + } + headers + } +} + +/// User summary returned by `GET /api/auth/session`. +#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AuthSessionUser { + pub id: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub email: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub name: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub avatar_url: Option, +} + +/// Response body of `GET /api/auth/session`. +#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AuthSessionResponse { + pub user: Option, +} + +/// Request body of `POST /api/auth/session/exchange`. +#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AuthSessionExchangeRequest { + pub code: String, + pub installation_id: String, + pub platform: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub device_name: Option, +} + +/// Request body of `POST /api/auth/session/refresh` and `POST /api/auth/session/revoke`. +#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AuthRefreshTokenRequest { + pub refresh_token: String, +} + +/// Nested session metadata returned by `/api/auth/session/{exchange,refresh}` (`AuthPlugin.swift`). +#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AuthSessionMeta { + pub id: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub absolute_expires_at: Option, +} + +/// Token pair response returned by `/api/auth/session/exchange` and `/api/auth/session/refresh`. +#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AuthTokenPairResponse { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub token_type: Option, + pub access_token: String, + pub refresh_token: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub expires_in: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub refresh_expires_at: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub session: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub session_id: Option, +} + +impl AuthTokenPairResponse { + /// Extract session ID preferring frozen nested `session.id`, falling back to legacy `sessionId`. + pub fn resolved_session_id(&self) -> Option<&str> { + self.session + .as_ref() + .map(|s| s.id.as_str()) + .or(self.session_id.as_deref()) + } + + /// Extract `session.absoluteExpiresAt` if present. + pub fn absolute_expires_at(&self) -> Option<&str> { + self.session + .as_ref() + .and_then(|s| s.absolute_expires_at.as_deref()) + } +} + +/// Build `GET /api/auth/session`. +pub fn build_get_auth_session_request(ctx: &ApiRequestContext) -> ApiHttpRequest { + ApiHttpRequest { + method: ApiHttpMethod::Get, + path: "/api/auth/session".to_string(), + headers: ctx.base_headers(false), + body: None, + } +} + +/// Decode `GET /api/auth/session` response JSON. +pub fn decode_auth_session_response(body: &[u8]) -> StoreResult { + Ok(serde_json::from_slice(body)?) +} + +/// Build `POST /api/auth/session/exchange` (native clients only). +pub fn build_auth_session_exchange_request( + ctx: &ApiRequestContext, + payload: &AuthSessionExchangeRequest, +) -> StoreResult { + if ctx.client_kind != ApiClientKind::Native { + return Err(StoreError::InvalidProtocol( + "POST /api/auth/session/exchange is restricted to native clients".into(), + )); + } + Ok(ApiHttpRequest { + method: ApiHttpMethod::Post, + path: "/api/auth/session/exchange".to_string(), + headers: ctx.base_headers(true), + body: Some(serde_json::to_vec(payload)?), + }) +} + +/// Validate a lowercase canonical UUID string (`xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx`). +pub fn is_valid_lowercase_uuid(value: &str) -> bool { + let bytes = value.as_bytes(); + if bytes.len() != 36 { + return false; + } + for (idx, &b) in bytes.iter().enumerate() { + if matches!(idx, 8 | 13 | 18 | 23) { + if b != b'-' { + return false; + } + } else if !matches!(b, b'0'..=b'9' | b'a'..=b'f') { + return false; + } + } + true +} + +/// Build `POST /api/auth/session/refresh` (native clients only). +/// +/// `attempt_id`, when provided, is sent as `x-affine-refresh-attempt` and MUST be a valid +/// lowercase UUID idempotency key (matching `AuthPlugin.swift` and `rest-routes.json`). +pub fn build_auth_session_refresh_request( + ctx: &ApiRequestContext, + refresh_token: &str, + attempt_id: Option<&str>, +) -> StoreResult { + if ctx.client_kind != ApiClientKind::Native { + return Err(StoreError::InvalidProtocol( + "POST /api/auth/session/refresh is restricted to native clients".into(), + )); + } + let mut headers = ctx.base_headers(true); + if let Some(id) = attempt_id { + if !is_valid_lowercase_uuid(id) { + return Err(StoreError::InvalidProtocol(format!( + "x-affine-refresh-attempt must be a lowercase UUID, got `{id}`" + ))); + } + headers.push((HEADER_REFRESH_ATTEMPT.to_string(), id.to_string())); + } + let payload = AuthRefreshTokenRequest { + refresh_token: refresh_token.to_string(), + }; + Ok(ApiHttpRequest { + method: ApiHttpMethod::Post, + path: "/api/auth/session/refresh".to_string(), + headers, + body: Some(serde_json::to_vec(&payload)?), + }) +} + +/// Build `POST /api/auth/session/revoke` (native clients only). +pub fn build_auth_session_revoke_request( + ctx: &ApiRequestContext, + refresh_token: &str, +) -> StoreResult { + if ctx.client_kind != ApiClientKind::Native { + return Err(StoreError::InvalidProtocol( + "POST /api/auth/session/revoke is restricted to native clients".into(), + )); + } + let payload = AuthRefreshTokenRequest { + refresh_token: refresh_token.to_string(), + }; + Ok(ApiHttpRequest { + method: ApiHttpMethod::Post, + path: "/api/auth/session/revoke".to_string(), + headers: ctx.base_headers(true), + body: Some(serde_json::to_vec(&payload)?), + }) +} + +/// Decode token pair JSON from `/api/auth/session/exchange` or `/api/auth/session/refresh`. +pub fn decode_auth_token_pair_response(body: &[u8]) -> StoreResult { + Ok(serde_json::from_slice(body)?) +} + +/// GraphQL request envelope (`POST /graphql`). +#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct GraphqlRequest { + pub operation_name: String, + pub query: String, + pub variables: Value, +} + +/// GraphQL error entry inside a `POST /graphql` response. +#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] +pub struct GraphqlError { + pub message: String, + #[serde(default)] + pub extensions: Option, +} + +fn none_default() -> Option { + None +} + +/// Generic GraphQL response envelope. +#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] +pub struct GraphqlResponse { + #[serde(default = "none_default")] + pub data: Option, + #[serde(default)] + pub errors: Vec, +} + +/// Build a `POST /graphql` HTTP request. +pub fn build_graphql_request( + ctx: &ApiRequestContext, + operation_name: impl Into, + query: impl Into, + variables: Value, +) -> StoreResult { + let envelope = GraphqlRequest { + operation_name: operation_name.into(), + query: query.into(), + variables, + }; + Ok(ApiHttpRequest { + method: ApiHttpMethod::Post, + path: "/graphql".to_string(), + headers: ctx.base_headers(true), + body: Some(serde_json::to_vec(&envelope)?), + }) +} + +/// Decode a `POST /graphql` response, surfacing GraphQL-level errors as `StoreError::InvalidProtocol`. +pub fn decode_graphql_response Deserialize<'de>>(body: &[u8]) -> StoreResult { + let parsed: GraphqlResponse = serde_json::from_slice(body)?; + if let Some(first_err) = parsed.errors.first() { + return Err(StoreError::InvalidProtocol(first_err.message.clone())); + } + parsed + .data + .ok_or_else(|| StoreError::InvalidProtocol("GraphQL response missing `data`".into())) +} + +/// Build the frozen `createBlobUpload` GraphQL mutation request (`blob-upload-create.gql`). +pub fn build_create_blob_upload_request( + ctx: &ApiRequestContext, + workspace_id: &str, + key: &str, + size: u64, + mime: &str, +) -> StoreResult { + const QUERY: &str = "mutation createBlobUpload($workspaceId: String!, $key: String!, $size: Int!, $mime: String!) { createBlobUpload(workspaceId: $workspaceId, key: $key, size: $size, mime: $mime) { method blobKey alreadyUploaded uploadUrl headers expiresAt uploadId partSize uploadedParts { partNumber etag } } }"; + build_graphql_request( + ctx, + "createBlobUpload", + QUERY, + json!({ + "workspaceId": workspace_id, + "key": key, + "size": size, + "mime": mime, + }), + ) +} + +/// Build the frozen `completeBlobUpload` GraphQL mutation request. +pub fn build_complete_blob_upload_request( + ctx: &ApiRequestContext, + workspace_id: &str, + key: &str, + upload_id: Option<&str>, + parts: Option<&[(u32, String)]>, +) -> StoreResult { + const QUERY: &str = "mutation completeBlobUpload($workspaceId: String!, $key: String!, $uploadId: String, $parts: [BlobUploadPartInput!]) { completeBlobUpload(workspaceId: $workspaceId, key: $key, uploadId: $uploadId, parts: $parts) }"; + let parts_val = parts.map(|items| { + items + .iter() + .map(|(part_number, etag)| json!({ "partNumber": part_number, "etag": etag })) + .collect::>() + }); + build_graphql_request( + ctx, + "completeBlobUpload", + QUERY, + json!({ + "workspaceId": workspace_id, + "key": key, + "uploadId": upload_id, + "parts": parts_val, + }), + ) +} + +/// Build the frozen `deleteBlob` GraphQL mutation request. +pub fn build_delete_blob_request( + ctx: &ApiRequestContext, + workspace_id: &str, + key: &str, + permanently: bool, +) -> StoreResult { + const QUERY: &str = "mutation deleteBlob($workspaceId: String!, $key: String!, $permanently: Boolean) { deleteBlob(workspaceId: $workspaceId, key: $key, permanently: $permanently) }"; + build_graphql_request( + ctx, + "deleteBlob", + QUERY, + json!({ + "workspaceId": workspace_id, + "key": key, + "permanently": permanently, + }), + ) +} + +/// Build the frozen `listBlobs` GraphQL query request (`blob-list.gql`). +pub fn build_list_blobs_request( + ctx: &ApiRequestContext, + workspace_id: &str, + first: u32, + after: Option<&str>, +) -> StoreResult { + const QUERY: &str = "query listBlobs($workspaceId: String!, $first: Int!, $after: String) { workspace(id: $workspaceId) { blobs(first: $first, after: $after) { key size mime createdAt } } }"; + build_graphql_request( + ctx, + "listBlobs", + QUERY, + json!({ + "workspaceId": workspace_id, + "first": first, + "after": after, + }), + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn auth_session_and_blob_graphql_codecs_enforce_client_kind_and_roundtrip() { + let web = ApiRequestContext::web(); + let get_session = build_get_auth_session_request(&web); + assert_eq!(get_session.method, ApiHttpMethod::Get); + assert_eq!(get_session.path, "/api/auth/session"); + assert!( + get_session + .headers + .contains(&(HEADER_CLIENT_KIND.into(), "web".into())) + ); + assert!(build_auth_session_revoke_request(&web, "rt-1").is_err()); + + let native = ApiRequestContext::native(Some("jwt-abc".into())); + let exchange = build_auth_session_exchange_request( + &native, + &AuthSessionExchangeRequest { + code: "code-1".into(), + installation_id: "inst-1".into(), + platform: "ios".into(), + device_name: Some("iPhone".into()), + }, + ) + .unwrap(); + assert_eq!(exchange.path, "/api/auth/session/exchange"); + assert!( + exchange + .headers + .contains(&("authorization".into(), "Bearer jwt-abc".into())) + ); + + let attempt_uuid = "550e8400-e29b-41d4-a716-446655440000"; + let refresh = + build_auth_session_refresh_request(&native, "rt-1", Some(attempt_uuid)).unwrap(); + assert!( + refresh + .headers + .contains(&(HEADER_REFRESH_ATTEMPT.into(), attempt_uuid.into())) + ); + // Non-UUID attempt IDs (such as numeric counters or uppercase UUIDs) MUST be rejected. + assert!(build_auth_session_refresh_request(&native, "rt-1", Some("1")).is_err()); + assert!(build_auth_session_refresh_request(&native, "rt-1", Some("2")).is_err()); + assert!( + build_auth_session_refresh_request( + &native, + "rt-1", + Some("550E8400-E29B-41D4-A716-446655440000") + ) + .is_err() + ); + + let list_req = build_list_blobs_request(&native, "ws-1", 50, Some("cursor-1")).unwrap(); + let list_body: GraphqlRequest = + serde_json::from_slice(list_req.body.as_ref().unwrap()).unwrap(); + assert_eq!(list_body.operation_name, "listBlobs"); + assert_eq!(list_body.variables["first"], 50); + assert_eq!(list_body.variables["after"], "cursor-1"); + + let session = decode_auth_session_response( + br#"{"user":{"id":"u-1","email":"a@b.com","name":"Alice"}}"#, + ) + .unwrap(); + assert_eq!(session.user.unwrap().id, "u-1"); + + let tokens = decode_auth_token_pair_response( + br#"{"tokenType":"Bearer","accessToken":"at-1","refreshToken":"rt-2","expiresIn":3600,"refreshExpiresAt":"2026-12-01T00:00:00Z","session":{"id":"sess-9","absoluteExpiresAt":"2027-01-01T00:00:00Z"}}"#, + ) + .unwrap(); + assert_eq!(tokens.token_type.as_deref(), Some("Bearer")); + assert_eq!(tokens.access_token, "at-1"); + assert_eq!(tokens.refresh_token, "rt-2"); + assert_eq!(tokens.expires_in, Some(3600)); + assert_eq!( + tokens.refresh_expires_at.as_deref(), + Some("2026-12-01T00:00:00Z") + ); + assert_eq!(tokens.resolved_session_id(), Some("sess-9")); + assert_eq!(tokens.absolute_expires_at(), Some("2027-01-01T00:00:00Z")); + + let gql_req = + build_create_blob_upload_request(&native, "ws-1", "blob-1", 42, "image/png").unwrap(); + assert_eq!(gql_req.path, "/graphql"); + let parsed_body: GraphqlRequest = + serde_json::from_slice(gql_req.body.as_ref().unwrap()).unwrap(); + assert_eq!(parsed_body.operation_name, "createBlobUpload"); + assert_eq!(parsed_body.variables["workspaceId"], "ws-1"); + + let ok_data: Value = decode_graphql_response(br#"{"data":{"deleteBlob":true}}"#).unwrap(); + assert_eq!(ok_data["deleteBlob"], true); + assert!(decode_graphql_response::(br#"{"errors":[{"message":"boom"}]}"#).is_err()); + } +} diff --git a/packages/common/store/src/id_converter.rs b/packages/common/store/src/id_converter.rs index 514cca9ba6..faf896b697 100644 --- a/packages/common/store/src/id_converter.rs +++ b/packages/common/store/src/id_converter.rs @@ -130,6 +130,16 @@ impl IdConverter { &self.space_id } + /// Return all registered `(page_id, subdoc_guid)` mappings (excluding the root workspace ID), + /// including modern pages where `page_id == subdoc_guid`. + pub fn page_mappings(&self) -> Vec<(&str, &str)> { + self.new_to_old + .iter() + .filter(|(page_id, _)| page_id.as_str() != self.space_id) + .map(|(page_id, subdoc_guid)| (page_id.as_str(), subdoc_guid.as_str())) + .collect() + } + /// Convert a local normalized document ID to the legacy/wire document ID. pub fn new_id_to_old_id(&self, new_id: &str) -> String { if let Some(rest) = new_id.strip_prefix("db$") { diff --git a/packages/common/store/src/idb/mod.rs b/packages/common/store/src/idb/mod.rs new file mode 100644 index 0000000000..6bdf5eb4b2 --- /dev/null +++ b/packages/common/store/src/idb/mod.rs @@ -0,0 +1,862 @@ +//! Cross-platform IndexedDB v3 storage model, V1 read-only fallback, and `BroadcastChannel` DTOs. +//! +//! Mirrors `packages/common/nbstore/src/impls/idb/` (`schema.ts`, `db.ts`, `doc.ts`, `v1/`). +//! In browser runtimes, real 12-store IndexedDB persistence and structured-clone `BroadcastChannel` +//! delivery are hosted by `packages/frontend/hosts/web/src/idb-storage.js`. + +pub mod origin; +pub mod v1; + +use std::{ + collections::{BTreeMap, BTreeSet}, + sync::{Arc, Mutex}, +}; + +use y_octo::{merge_updates_v1, validate_update_v1}; + +use crate::{ + error::{StoreError, StoreResult}, + sync::SpaceType, + workspace_db::PendingDocUpdate, +}; + +pub use origin::{ + IdbBlobSyncRecord, IdbChannelDocUpdate, IdbChannelMessage, IdbIndexerSyncRecord, + IdbSharedOrigin, +}; +pub use v1::{ + IDB_V1_BLOB_STORE_NAME, IDB_V1_CONST_TIMESTAMP_MS, IDB_V1_DOC_DB_NAME, IDB_V1_DOC_STORE_NAME, + IdbHostPlatform, IdbV1BlobRecord, IdbV1BlobStorage, IdbV1DocRecord, IdbV1DocStorage, + IdbV1ListedBlob, IdbV1RawUpdate, idb_v1_blob_db_name, is_idb_v1_fallback_enabled, +}; + +/// Frozen IndexedDB schema version (`migrations.length === 3` in `schema.ts`). +pub const IDB_SCHEMA_VERSION: u32 = 3; + +/// Exact key path specification for an IndexedDB object store or index. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum IdbKeyPath { + None, + Single(&'static str), + Compound(&'static [&'static str]), +} + +/// Exact index definition on an IndexedDB object store. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct IdbIndexSpec { + pub name: &'static str, + pub key_path: IdbKeyPath, + pub unique: bool, +} + +/// Exact object store definition matching `packages/common/nbstore/src/impls/idb/schema.ts`. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct IdbStoreSpec { + pub name: &'static str, + pub key_path: IdbKeyPath, + pub auto_increment: bool, + pub indexes: &'static [IdbIndexSpec], + pub added_in_version: u32, +} + +/// Ordered migration steps for IndexedDB schema upgrades (`0 -> 1 -> 2 -> 3`). +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum IdbMigrationStep { + Init = 1, + InitBlobSync = 2, + InitIndexer = 3, +} + +const SNAPSHOTS_INDEXES: &[IdbIndexSpec] = &[IdbIndexSpec { + name: "updatedAt", + key_path: IdbKeyPath::Single("updatedAt"), + unique: false, +}]; + +const UPDATES_INDEXES: &[IdbIndexSpec] = &[IdbIndexSpec { + name: "docId", + key_path: IdbKeyPath::Single("docId"), + unique: false, +}]; + +const CLOCKS_INDEXES: &[IdbIndexSpec] = &[IdbIndexSpec { + name: "timestamp", + key_path: IdbKeyPath::Single("timestamp"), + unique: false, +}]; + +const PEER_CLOCKS_INDEXES: &[IdbIndexSpec] = &[IdbIndexSpec { + name: "peer", + key_path: IdbKeyPath::Single("peer"), + unique: false, +}]; + +const BLOB_SYNC_INDEXES: &[IdbIndexSpec] = &[IdbIndexSpec { + name: "peer", + key_path: IdbKeyPath::Single("peer"), + unique: false, +}]; + +const INDEXER_RECORDS_INDEXES: &[IdbIndexSpec] = &[ + IdbIndexSpec { + name: "table", + key_path: IdbKeyPath::Single("table"), + unique: false, + }, + IdbIndexSpec { + name: "id", + key_path: IdbKeyPath::Compound(&["table", "id"]), + unique: true, + }, +]; + +const INVERTED_INDEX_INDEXES: &[IdbIndexSpec] = &[ + IdbIndexSpec { + name: "key", + key_path: IdbKeyPath::Compound(&["table", "key"]), + unique: false, + }, + IdbIndexSpec { + name: "nid", + key_path: IdbKeyPath::Single("nid"), + unique: false, + }, +]; + +/// All 12 IndexedDB v3 object stores in migration order. +pub const IDB_OBJECT_STORES: &[IdbStoreSpec] = &[ + IdbStoreSpec { + name: "snapshots", + key_path: IdbKeyPath::Single("docId"), + auto_increment: false, + indexes: SNAPSHOTS_INDEXES, + added_in_version: 1, + }, + IdbStoreSpec { + name: "updates", + key_path: IdbKeyPath::Compound(&["docId", "createdAt"]), + auto_increment: false, + indexes: UPDATES_INDEXES, + added_in_version: 1, + }, + IdbStoreSpec { + name: "clocks", + key_path: IdbKeyPath::Single("docId"), + auto_increment: false, + indexes: CLOCKS_INDEXES, + added_in_version: 1, + }, + IdbStoreSpec { + name: "peerClocks", + key_path: IdbKeyPath::Compound(&["peer", "docId"]), + auto_increment: false, + indexes: PEER_CLOCKS_INDEXES, + added_in_version: 1, + }, + IdbStoreSpec { + name: "blobs", + key_path: IdbKeyPath::Single("key"), + auto_increment: false, + indexes: &[], + added_in_version: 1, + }, + IdbStoreSpec { + name: "blobData", + key_path: IdbKeyPath::Single("key"), + auto_increment: false, + indexes: &[], + added_in_version: 1, + }, + IdbStoreSpec { + name: "locks", + key_path: IdbKeyPath::Single("key"), + auto_increment: false, + indexes: &[], + added_in_version: 1, + }, + IdbStoreSpec { + name: "blobSync", + key_path: IdbKeyPath::Compound(&["peer", "key"]), + auto_increment: false, + indexes: BLOB_SYNC_INDEXES, + added_in_version: 2, + }, + IdbStoreSpec { + name: "indexerMetadata", + key_path: IdbKeyPath::Single("key"), + auto_increment: false, + indexes: &[], + added_in_version: 3, + }, + IdbStoreSpec { + name: "indexerRecords", + key_path: IdbKeyPath::None, + auto_increment: true, + indexes: INDEXER_RECORDS_INDEXES, + added_in_version: 3, + }, + IdbStoreSpec { + name: "invertedIndex", + key_path: IdbKeyPath::None, + auto_increment: true, + indexes: INVERTED_INDEX_INDEXES, + added_in_version: 3, + }, + IdbStoreSpec { + name: "indexerSync", + key_path: IdbKeyPath::Single("docId"), + auto_increment: false, + indexes: &[], + added_in_version: 3, + }, +]; + +/// Return the migration steps required to upgrade an IndexedDB database from `old_version` to v3. +pub fn migration_steps_for_upgrade(old_version: u32) -> &'static [IdbMigrationStep] { + const ALL: &[IdbMigrationStep] = &[ + IdbMigrationStep::Init, + IdbMigrationStep::InitBlobSync, + IdbMigrationStep::InitIndexer, + ]; + let start = (old_version as usize).min(ALL.len()); + &ALL[start..] +} + +/// Format the IndexedDB database name matching `IDBConnection.dbName` (`${flavour}:${type}:${id}`). +pub fn idb_db_name(flavour: &str, space_type: SpaceType, id: &str) -> String { + format!("{flavour}:{}:{id}", space_type.as_str()) +} + +/// Format the shared connection identifier (`idb(3):${dbName}`). +pub fn idb_share_id(db_name: &str) -> String { + format!("idb({IDB_SCHEMA_VERSION}):{db_name}") +} + +/// Format the cross-tab `BroadcastChannel` name (`idb:${dbName}`). +pub fn idb_broadcast_channel_name(db_name: &str) -> String { + format!("idb:{db_name}") +} + +/// Snapshot row in the `snapshots` object store. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct IdbSnapshotRecord { + pub doc_id: String, + pub bin: Vec, + pub created_at_ms: i64, + pub updated_at_ms: i64, +} + +/// Peer clock row in the `peerClocks` object store. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct IdbPeerClockRecord { + pub peer: String, + pub doc_id: String, + pub clock_ms: i64, + pub pulled_clock_ms: i64, + pub pushed_clock_ms: i64, + pub pending_create: bool, + pub cache_token: u64, +} + +impl IdbPeerClockRecord { + pub fn new(peer: impl Into, doc_id: impl Into) -> Self { + Self { + peer: peer.into(), + doc_id: doc_id.into(), + clock_ms: 0, + pulled_clock_ms: 0, + pushed_clock_ms: 0, + pending_create: false, + cache_token: 0, + } + } +} + +/// Blob metadata row in the `blobs` object store. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct IdbBlobMeta { + pub key: String, + pub mime: String, + pub size: usize, + pub created_at_ms: i64, + pub deleted_at_ms: Option, +} + +/// Merged document record returned by [`IdbWorkspaceStore::get_doc`]. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct IdbDocRecord { + pub doc_id: String, + pub bin: Vec, + pub timestamp_ms: i64, +} + +/// Pure-Rust IndexedDB v3 workspace store backed by an [`IdbSharedOrigin`]. +#[derive(Debug)] +pub struct IdbWorkspaceStore { + flavour: String, + space_type: SpaceType, + space_id: String, + db: Arc>, + subscriber_id: u64, + outbound_channel: Vec, +} + +impl Drop for IdbWorkspaceStore { + fn drop(&mut self) { + let mut guard = self.db.lock().unwrap_or_else(|err| err.into_inner()); + guard.unregister_subscriber(self.subscriber_id); + } +} + +impl IdbWorkspaceStore { + /// Open an isolated store backed by a fresh single-database origin. + pub fn new( + flavour: impl Into, + space_type: SpaceType, + space_id: impl Into, + ) -> Self { + Self::open_in_origin(&IdbSharedOrigin::new(), flavour, space_type, space_id) + } + + /// Open (or reopen) a named database in `origin`, sharing persistence and cross-tab + /// `BroadcastChannel` events with any other handle opened against the same `origin`. + pub fn open_in_origin( + origin: &IdbSharedOrigin, + flavour: impl Into, + space_type: SpaceType, + space_id: impl Into, + ) -> Self { + let flavour = flavour.into(); + let space_id = space_id.into(); + let db_name = idb_db_name(&flavour, space_type, &space_id); + let db = origin.open_db(&db_name); + let subscriber_id = db + .lock() + .unwrap_or_else(|err| err.into_inner()) + .register_subscriber(); + Self { + flavour, + space_type, + space_id, + db, + subscriber_id, + outbound_channel: Vec::new(), + } + } + + pub fn db_name(&self) -> String { + idb_db_name(&self.flavour, self.space_type, &self.space_id) + } + + pub fn channel_name(&self) -> String { + idb_broadcast_channel_name(&self.db_name()) + } + + /// Drain messages published by this handle since the last drain. + pub fn drain_channel_messages(&mut self) -> Vec { + std::mem::take(&mut self.outbound_channel) + } + + /// Poll cross-tab `BroadcastChannel` messages received from sibling handles on the same origin. + pub fn poll_channel_messages(&mut self) -> Vec { + self.db + .lock() + .unwrap_or_else(|err| err.into_inner()) + .drain_inbox(self.subscriber_id) + } + + fn apply_doc_update_locked( + db: &mut origin::IdbDatabaseState, + space_id: &str, + doc_id: &str, + bin: Vec, + create_for_peer: Option<&str>, + origin_tag: Option<&str>, + now_ms: i64, + ) -> (i64, IdbChannelMessage) { + let prev = db.clocks.get(doc_id).copied().unwrap_or(0); + let timestamp_ms = now_ms.max(prev.saturating_add(1)); + db.updates + .insert((doc_id.to_string(), timestamp_ms), bin.clone()); + db.clocks.insert(doc_id.to_string(), timestamp_ms); + + if let Some(peer) = create_for_peer { + let entry = db + .peer_clocks + .entry((peer.to_string(), doc_id.to_string())) + .or_insert_with(|| IdbPeerClockRecord::new(peer, doc_id)); + entry.pending_create = true; + let root = db + .peer_clocks + .entry((peer.to_string(), space_id.to_string())) + .or_insert_with(|| IdbPeerClockRecord::new(peer, space_id)); + root.cache_token = root.cache_token.saturating_add(1); + } + + let msg = IdbChannelMessage::Update { + update: IdbChannelDocUpdate { + doc_id: doc_id.to_string(), + bin, + timestamp: timestamp_ms, + editor: None, + create_for_peer: create_for_peer.map(str::to_string), + }, + origin: origin_tag.map(str::to_string), + }; + (timestamp_ms, msg) + } + + /// Push a single document update with monotonic per-doc timestamps and optional `create_for_peer`. + pub fn push_doc_update( + &mut self, + doc_id: &str, + bin: Vec, + create_for_peer: Option<&str>, + origin_tag: Option<&str>, + now_ms: i64, + ) -> StoreResult { + if !bin.is_empty() && bin != [0, 0] { + validate_update_v1(&bin).map_err(|err| StoreError::InvalidBinary(err.to_string()))?; + } + let mut db = self.db.lock().unwrap_or_else(|err| err.into_inner()); + let (timestamp_ms, msg) = Self::apply_doc_update_locked( + &mut db, + &self.space_id, + doc_id, + bin, + create_for_peer, + origin_tag, + now_ms, + ); + db.broadcast(self.subscriber_id, msg.clone()); + self.outbound_channel.push(msg); + Ok(timestamp_ms) + } + + /// Atomically apply a batch of [`PendingDocUpdate`] entries inside a single lock critical + /// section, committing all updates before broadcasting any cross-tab notifications. + pub fn push_updates_batch( + &mut self, + updates: &[PendingDocUpdate], + create_for_peer: Option<&str>, + now_ms: i64, + ) -> StoreResult> { + for item in updates { + if !item.update.is_empty() && item.update != [0, 0] { + validate_update_v1(&item.update) + .map_err(|err| StoreError::InvalidBinary(err.to_string()))?; + } + } + let mut db = self.db.lock().unwrap_or_else(|err| err.into_inner()); + let mut results = Vec::with_capacity(updates.len()); + let mut messages = Vec::with_capacity(updates.len()); + for item in updates { + if item.update.is_empty() || item.update == [0, 0] { + continue; + } + let (ts, msg) = Self::apply_doc_update_locked( + &mut db, + &self.space_id, + &item.doc_id, + item.update.clone(), + create_for_peer, + None, + now_ms, + ); + results.push((item.doc_id.clone(), ts)); + messages.push(msg); + } + for msg in messages { + db.broadcast(self.subscriber_id, msg.clone()); + self.outbound_channel.push(msg); + } + Ok(results) + } + + /// Read and merge the snapshot + incremental updates for `doc_id`. + pub fn get_doc(&self, doc_id: &str) -> StoreResult> { + let db = self.db.lock().unwrap_or_else(|err| err.into_inner()); + let snapshot = db.snapshots.get(doc_id); + let doc_updates: Vec<(i64, Vec)> = db + .updates + .range((doc_id.to_string(), i64::MIN)..=(doc_id.to_string(), i64::MAX)) + .map(|((_, ts), bin)| (*ts, bin.clone())) + .collect(); + + if doc_updates.is_empty() { + return Ok(snapshot.map(|s| IdbDocRecord { + doc_id: doc_id.to_string(), + bin: s.bin.clone(), + timestamp_ms: s.updated_at_ms, + })); + } + + let mut sources: Vec<&[u8]> = Vec::with_capacity(doc_updates.len() + 1); + let mut max_ts = i64::MIN; + if let Some(snap) = snapshot { + if !snap.bin.is_empty() && snap.bin != [0, 0] { + sources.push(&snap.bin); + } + max_ts = max_ts.max(snap.updated_at_ms); + } + for (ts, bin) in &doc_updates { + if !bin.is_empty() && bin.as_slice() != [0, 0] { + sources.push(bin.as_slice()); + } + max_ts = max_ts.max(*ts); + } + + let merged = match sources.as_slice() { + [] => vec![0, 0], + [single] => (*single).to_vec(), + many => merge_updates_v1(many.iter().copied()) + .and_then(|u| u.encode_v1()) + .map_err(|err| StoreError::InvalidBinary(err.to_string()))?, + }; + Ok(Some(IdbDocRecord { + doc_id: doc_id.to_string(), + bin: merged, + timestamp_ms: max_ts, + })) + } + + /// Delete a document from `snapshots`, `updates`, and `clocks`, clear matching `pending_create` + /// flags in `peerClocks` (incrementing the peer root `cache_token`), and broadcast deletion. + pub fn delete_doc(&mut self, doc_id: &str) { + let mut db = self.db.lock().unwrap_or_else(|err| err.into_inner()); + db.snapshots.remove(doc_id); + db.clocks.remove(doc_id); + let keys: Vec<(String, i64)> = db + .updates + .range((doc_id.to_string(), i64::MIN)..=(doc_id.to_string(), i64::MAX)) + .map(|(k, _)| k.clone()) + .collect(); + for key in keys { + db.updates.remove(&key); + } + + let affected_peers: Vec = db + .peer_clocks + .iter_mut() + .filter_map(|((peer, rec_doc_id), record)| { + if rec_doc_id == doc_id && record.pending_create { + record.pending_create = false; + Some(peer.clone()) + } else { + None + } + }) + .collect(); + for peer in affected_peers { + let root = db + .peer_clocks + .entry((peer.clone(), self.space_id.clone())) + .or_insert_with(|| IdbPeerClockRecord::new(peer, &self.space_id)); + root.cache_token = root.cache_token.saturating_add(1); + } + + let msg = IdbChannelMessage::Delete { + doc_id: doc_id.to_string(), + }; + db.broadcast(self.subscriber_id, msg.clone()); + self.outbound_channel.push(msg); + } + + pub fn get_doc_timestamps(&self, after_ms: Option) -> BTreeMap { + let db = self.db.lock().unwrap_or_else(|err| err.into_inner()); + db.clocks + .iter() + .filter(|(_, ts)| after_ms.is_none_or(|cutoff| **ts > cutoff)) + .map(|(id, ts)| (id.clone(), *ts)) + .collect() + } + + pub fn peer_clock(&self, peer: &str, doc_id: &str) -> Option { + let db = self.db.lock().unwrap_or_else(|err| err.into_inner()); + db.peer_clocks + .get(&(peer.to_string(), doc_id.to_string())) + .cloned() + } + + pub fn put_blob(&mut self, key: &str, mime: &str, data: Vec, now_ms: i64) { + let mut db = self.db.lock().unwrap_or_else(|err| err.into_inner()); + let size = data.len(); + db.blobs.insert( + key.to_string(), + IdbBlobMeta { + key: key.to_string(), + mime: mime.to_string(), + size, + created_at_ms: now_ms, + deleted_at_ms: None, + }, + ); + db.blob_data.insert(key.to_string(), data); + } + + pub fn get_blob(&self, key: &str) -> Option<(IdbBlobMeta, Vec)> { + let db = self.db.lock().unwrap_or_else(|err| err.into_inner()); + let meta = db.blobs.get(key)?; + if meta.deleted_at_ms.is_some() { + return None; + } + let data = db.blob_data.get(key)?; + Some((meta.clone(), data.clone())) + } + + pub fn set_blob_sync(&mut self, peer: &str, key: &str, uploaded_at_ms: Option) { + let mut db = self.db.lock().unwrap_or_else(|err| err.into_inner()); + db.blob_sync.insert( + (peer.to_string(), key.to_string()), + IdbBlobSyncRecord { + peer: peer.to_string(), + key: key.to_string(), + uploaded_at_ms, + }, + ); + } + + pub fn get_blob_sync(&self, peer: &str, key: &str) -> Option { + let db = self.db.lock().unwrap_or_else(|err| err.into_inner()); + db.blob_sync + .get(&(peer.to_string(), key.to_string())) + .cloned() + } + + pub fn set_indexer_sync(&mut self, doc_id: &str, indexed_clock_ms: i64, version: Option) { + let mut db = self.db.lock().unwrap_or_else(|err| err.into_inner()); + db.indexer_sync.insert( + doc_id.to_string(), + IdbIndexerSyncRecord { + doc_id: doc_id.to_string(), + indexed_clock_ms, + indexer_version: version, + }, + ); + } + + pub fn get_indexer_sync(&self, doc_id: &str) -> Option { + let db = self.db.lock().unwrap_or_else(|err| err.into_inner()); + db.indexer_sync.get(doc_id).cloned() + } + + pub fn all_store_names(&self) -> BTreeSet<&'static str> { + IDB_OBJECT_STORES.iter().map(|s| s.name).collect() + } +} + +/// Userspace-scoped IndexedDB v3 store (`${flavour}:userspace:${userId}`). +#[derive(Debug)] +pub struct IdbUserspaceStore { + inner: IdbWorkspaceStore, +} + +impl IdbUserspaceStore { + pub fn open_in_origin( + origin: &IdbSharedOrigin, + flavour: impl Into, + user_id: impl Into, + ) -> Self { + Self { + inner: IdbWorkspaceStore::open_in_origin( + origin, + flavour, + SpaceType::Userspace, + user_id, + ), + } + } + + pub fn db_name(&self) -> String { + self.inner.db_name() + } + + pub fn channel_name(&self) -> String { + self.inner.channel_name() + } + + pub fn push_doc_update( + &mut self, + doc_id: &str, + bin: Vec, + origin_tag: Option<&str>, + now_ms: i64, + ) -> StoreResult { + self.inner + .push_doc_update(doc_id, bin, None, origin_tag, now_ms) + } + + pub fn get_doc(&self, doc_id: &str) -> StoreResult> { + self.inner.get_doc(doc_id) + } + + pub fn delete_doc(&mut self, doc_id: &str) { + self.inner.delete_doc(doc_id); + } + + pub fn poll_channel_messages(&mut self) -> Vec { + self.inner.poll_channel_messages() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::workspace_db::WorkspaceDb; + + #[test] + fn idb_v3_schema_matches_all_12_object_stores_and_naming_contract() { + assert_eq!(IDB_SCHEMA_VERSION, 3); + assert_eq!(IDB_OBJECT_STORES.len(), 12); + + let names: Vec<&str> = IDB_OBJECT_STORES.iter().map(|s| s.name).collect(); + assert_eq!( + names, + vec![ + "snapshots", + "updates", + "clocks", + "peerClocks", + "blobs", + "blobData", + "locks", + "blobSync", + "indexerMetadata", + "indexerRecords", + "invertedIndex", + "indexerSync", + ] + ); + + assert_eq!(migration_steps_for_upgrade(0).len(), 3); + assert_eq!(migration_steps_for_upgrade(1).len(), 2); + assert_eq!(migration_steps_for_upgrade(2).len(), 1); + assert_eq!(migration_steps_for_upgrade(3).len(), 0); + + let db_name = idb_db_name("local", SpaceType::Workspace, "ws-42"); + assert_eq!(db_name, "local:workspace:ws-42"); + assert_eq!(idb_share_id(&db_name), "idb(3):local:workspace:ws-42"); + assert_eq!( + idb_broadcast_channel_name(&db_name), + "idb:local:workspace:ws-42" + ); + } + + #[test] + fn idb_shared_origin_persists_across_reopen_broadcasts_between_tabs_and_supports_userspace() { + let origin = IdbSharedOrigin::new(); + let mut ws = WorkspaceDb::new("ws-1", "u1", 1); + let init_update = ws.initialize_meta().unwrap().unwrap(); + + let mut tab_a = + IdbWorkspaceStore::open_in_origin(&origin, "local", SpaceType::Workspace, "ws-1"); + let mut tab_b = + IdbWorkspaceStore::open_in_origin(&origin, "local", SpaceType::Workspace, "ws-1"); + + let ts = tab_a + .push_doc_update( + "ws-1", + init_update.clone(), + Some("cloud"), + Some("local"), + 1_000, + ) + .unwrap(); + assert_eq!(ts, 1_000); + tab_a.put_blob("b1", "image/png", vec![1, 2, 3], 1_001); + tab_a.set_blob_sync("cloud", "b1", Some(1_002)); + tab_a.set_indexer_sync("ws-1", 1_000, Some(2)); + + // Tab B immediately receives the 0.27.5 BroadcastChannel update message. + let b_inbox = tab_b.poll_channel_messages(); + assert_eq!(b_inbox.len(), 1); + assert_eq!( + b_inbox[0], + IdbChannelMessage::Update { + update: IdbChannelDocUpdate { + doc_id: "ws-1".into(), + bin: init_update.clone(), + timestamp: 1_000, + editor: None, + create_for_peer: Some("cloud".into()), + }, + origin: Some("local".into()), + } + ); + + // Close Tab A and reopen on the same origin: all stores survive intact. + drop(tab_a); + let mut reopened = + IdbWorkspaceStore::open_in_origin(&origin, "local", SpaceType::Workspace, "ws-1"); + assert_eq!(reopened.get_doc("ws-1").unwrap().unwrap().bin, init_update); + assert!(reopened.peer_clock("cloud", "ws-1").unwrap().pending_create); + assert_eq!(reopened.peer_clock("cloud", "ws-1").unwrap().cache_token, 1); + assert_eq!(reopened.get_blob("b1").unwrap().1, vec![1, 2, 3]); + assert_eq!( + reopened + .get_blob_sync("cloud", "b1") + .unwrap() + .uploaded_at_ms, + Some(1_002) + ); + assert_eq!( + reopened.get_indexer_sync("ws-1").unwrap().indexer_version, + Some(2) + ); + + // Delete clears pending_create, increments cache_token, and broadcasts delete to Tab B. + reopened.delete_doc("ws-1"); + assert!(reopened.get_doc("ws-1").unwrap().is_none()); + assert!(!reopened.peer_clock("cloud", "ws-1").unwrap().pending_create); + assert_eq!(reopened.peer_clock("cloud", "ws-1").unwrap().cache_token, 2); + assert_eq!( + tab_b.poll_channel_messages(), + vec![IdbChannelMessage::Delete { + doc_id: "ws-1".into() + }] + ); + + // Userspace store uses `${flavour}:userspace:${userId}` and persists across reopen. + let mut user_a = IdbUserspaceStore::open_in_origin(&origin, "cloud", "user-7"); + assert_eq!(user_a.db_name(), "cloud:userspace:user-7"); + user_a + .push_doc_update("settings", vec![0, 0], Some("local"), 2_000) + .unwrap(); + drop(user_a); + let user_b = IdbUserspaceStore::open_in_origin(&origin, "cloud", "user-7"); + assert_eq!( + user_b.get_doc("settings").unwrap().unwrap().timestamp_ms, + 2_000 + ); + + // Atomic batch commit: Handle B sees BOTH root and child docs upon receiving the first message. + let batch_origin = IdbSharedOrigin::new(); + let mut handle_a = + IdbWorkspaceStore::open_in_origin(&batch_origin, "local", SpaceType::Workspace, "ws-b"); + let mut handle_b = + IdbWorkspaceStore::open_in_origin(&batch_origin, "local", SpaceType::Workspace, "ws-b"); + let mut ws_b = WorkspaceDb::new("ws-b", "u1", 1); + let root_bin = ws_b.initialize_meta().unwrap().unwrap(); + let child_bin = root_bin.clone(); + handle_a + .push_updates_batch( + &[ + PendingDocUpdate { + doc_id: "ws-b".into(), + update: root_bin, + }, + PendingDocUpdate { + doc_id: "child-1".into(), + update: child_bin, + }, + ], + None, + 3_000, + ) + .unwrap(); + let first_msgs = handle_b.poll_channel_messages(); + assert_eq!(first_msgs.len(), 2); + assert!(handle_b.get_doc("ws-b").unwrap().is_some()); + assert!(handle_b.get_doc("child-1").unwrap().is_some()); + } +} diff --git a/packages/common/store/src/idb/origin.rs b/packages/common/store/src/idb/origin.rs new file mode 100644 index 0000000000..9deb388d47 --- /dev/null +++ b/packages/common/store/src/idb/origin.rs @@ -0,0 +1,136 @@ +//! Shared in-memory origin backend and `0.27.5` `BroadcastChannel` DTOs for IndexedDB v3 stores. +//! +//! In browser runtimes, real 12-store IndexedDB persistence and structured-clone `BroadcastChannel` +//! delivery are hosted by `packages/frontend/hosts/web/src/idb-storage.js`. This module provides a +//! deterministic, zero-`web-sys` shared origin (`IdbSharedOrigin`) so closing and reopening a named +//! database preserves all stores and concurrent tabs on the same origin receive `update`/`delete` +//! broadcasts. + +use std::{ + collections::{BTreeMap, VecDeque}, + sync::{Arc, Mutex}, +}; + +use serde::{Deserialize, Serialize}; + +use super::{IdbBlobMeta, IdbPeerClockRecord, IdbSnapshotRecord}; + +/// `0.27.5` `DocRecord` payload carried by `BroadcastChannel("idb:")` update messages. +/// +/// Mirrors `packages/common/nbstore/src/impls/idb/doc.ts:14-20, 84-94` (`docId`, `bin`, +/// `timestamp`, `editor`, `createForPeer`). +#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct IdbChannelDocUpdate { + pub doc_id: String, + pub bin: Vec, + /// Epoch milliseconds corresponding to the JS `Date` `timestamp` field. + pub timestamp: i64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub editor: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub create_for_peer: Option, +} + +/// Cross-tab `BroadcastChannel("idb:")` message matching `IndexedDBDocStorage` `ChannelMessage`. +#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] +#[serde(tag = "type", rename_all = "lowercase")] +pub enum IdbChannelMessage { + Delete { + #[serde(rename = "docId")] + doc_id: String, + }, + Update { + update: IdbChannelDocUpdate, + #[serde(default, skip_serializing_if = "Option::is_none")] + origin: Option, + }, +} + +/// Blob sync record in the `blobSync` object store. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct IdbBlobSyncRecord { + pub peer: String, + pub key: String, + pub uploaded_at_ms: Option, +} + +/// Indexer sync record in the `indexerSync` object store. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct IdbIndexerSyncRecord { + pub doc_id: String, + pub indexed_clock_ms: i64, + pub indexer_version: Option, +} + +#[derive(Default, Debug)] +pub(super) struct IdbDatabaseState { + pub snapshots: BTreeMap, + pub updates: BTreeMap<(String, i64), Vec>, + pub clocks: BTreeMap, + pub peer_clocks: BTreeMap<(String, String), IdbPeerClockRecord>, + pub blobs: BTreeMap, + pub blob_data: BTreeMap>, + pub blob_sync: BTreeMap<(String, String), IdbBlobSyncRecord>, + pub indexer_sync: BTreeMap, + pub next_subscriber_id: u64, + pub subscribers: BTreeMap>, +} + +impl IdbDatabaseState { + pub fn register_subscriber(&mut self) -> u64 { + self.next_subscriber_id = self.next_subscriber_id.saturating_add(1); + let id = self.next_subscriber_id; + self.subscribers.insert(id, VecDeque::new()); + id + } + + pub fn unregister_subscriber(&mut self, id: u64) { + self.subscribers.remove(&id); + } + + pub fn broadcast(&mut self, sender_id: u64, message: IdbChannelMessage) { + for (&sub_id, queue) in &mut self.subscribers { + if sub_id != sender_id { + queue.push_back(message.clone()); + } + } + } + + pub fn drain_inbox(&mut self, subscriber_id: u64) -> Vec { + self.subscribers + .get_mut(&subscriber_id) + .map(|q| q.drain(..).collect()) + .unwrap_or_default() + } +} + +/// Shared same-origin persistence and `BroadcastChannel` hub for IndexedDB v3 databases. +#[derive(Clone, Debug, Default)] +pub struct IdbSharedOrigin { + databases: Arc>>>>, +} + +impl IdbSharedOrigin { + pub fn new() -> Self { + Self::default() + } + + pub(super) fn open_db(&self, db_name: &str) -> Arc> { + let mut guard = self.databases.lock().unwrap_or_else(|err| err.into_inner()); + guard + .entry(db_name.to_string()) + .or_insert_with(|| Arc::new(Mutex::new(IdbDatabaseState::default()))) + .clone() + } + + /// List all database names currently persisted in this origin. + pub fn database_names(&self) -> Vec { + self.databases + .lock() + .unwrap_or_else(|err| err.into_inner()) + .keys() + .cloned() + .collect() + } +} diff --git a/packages/common/store/src/idb/v1.rs b/packages/common/store/src/idb/v1.rs new file mode 100644 index 0000000000..498160930a --- /dev/null +++ b/packages/common/store/src/idb/v1.rs @@ -0,0 +1,406 @@ +//! Web-exclusive IndexedDB V1 read-only fallback storage model. +//! +//! Mirrors `packages/common/nbstore/src/impls/idb/v1/{db,doc,blob}.ts` and +//! `packages/frontend/core/src/modules/workspace-engine/impls/local.ts:197-210`. + +use std::collections::BTreeMap; + +use y_octo::merge_updates_v1; + +use crate::{ + error::{StoreError, StoreResult}, + id_converter::IdConverter, +}; + +/// Legacy V1 IndexedDB database name for documents (`affine-local`). +pub const IDB_V1_DOC_DB_NAME: &str = "affine-local"; + +/// Legacy V1 IndexedDB object store name for documents (`workspace`, `keyPath: "id"`). +pub const IDB_V1_DOC_STORE_NAME: &str = "workspace"; + +/// Legacy V1 IndexedDB object store name for blobs (`blob`). +pub const IDB_V1_BLOB_STORE_NAME: &str = "blob"; + +/// Fixed timestamp used by `IndexedDBV1DocStorage` (`new Date(1893456000000)`). +pub const IDB_V1_CONST_TIMESTAMP_MS: i64 = 1_893_456_000_000; + +/// Host platform kind determining whether IndexedDB V1 fallback is enabled. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum IdbHostPlatform { + Web, + MobileWeb, + Ios, + Android, + Electron, +} + +/// Web-exclusive V1 fallback gate matching `local.ts:197-210`. +/// +/// Only Web and MobileWeb enable `IndexedDBV1DocStorage` / `IndexedDBV1BlobStorage`. +pub const fn is_idb_v1_fallback_enabled(platform: IdbHostPlatform) -> bool { + matches!(platform, IdbHostPlatform::Web | IdbHostPlatform::MobileWeb) +} + +/// Format the legacy V1 IndexedDB blob database name (`${spaceId}_blob`). +pub fn idb_v1_blob_db_name(space_id: &str) -> String { + format!("{space_id}_blob") +} + +/// Single raw update entry inside a V1 `workspace` object store record. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct IdbV1RawUpdate { + pub timestamp_ms: i64, + pub update: Vec, +} + +/// Read-only merged document record returned by [`IdbV1DocStorage`]. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct IdbV1DocRecord { + pub doc_id: String, + pub bin: Vec, + pub timestamp_ms: i64, +} + +/// Read-only IndexedDB V1 document storage model (`affine-local` / `workspace`). +#[derive(Clone, Debug)] +pub struct IdbV1DocStorage { + space_id: String, + workspace_rows: BTreeMap>, +} + +impl IdbV1DocStorage { + pub fn new( + space_id: impl Into, + workspace_rows: BTreeMap>, + ) -> Self { + Self { + space_id: space_id.into(), + workspace_rows, + } + } + + pub fn is_readonly(&self) -> bool { + true + } + + pub fn id_converter(&self) -> StoreResult { + let root_buf = self.raw_get_doc(&self.space_id)?; + IdConverter::from_root_doc_bytes(&self.space_id, None, root_buf.as_deref()) + } + + /// Read a document by normalized local `doc_id`, resolving legacy GUIDs via [`IdConverter`]. + pub fn get_doc(&self, doc_id: &str) -> StoreResult> { + let converter = self.id_converter()?; + let old_id = converter.new_id_to_old_id(doc_id); + let Some(bin) = self.raw_get_doc(&old_id)? else { + return Ok(None); + }; + Ok(Some(IdbV1DocRecord { + doc_id: old_id, + bin, + timestamp_ms: IDB_V1_CONST_TIMESTAMP_MS, + })) + } + + /// V1 storage is read-only; writes are ignored and return `IDB_V1_CONST_TIMESTAMP_MS`. + pub fn push_doc_update(&mut self, _doc_id: &str, _bin: &[u8]) -> i64 { + IDB_V1_CONST_TIMESTAMP_MS + } + + /// Enumerate all normalized document IDs belonging to this workspace in V1 storage. + pub fn get_doc_timestamps(&self) -> StoreResult> { + let converter = self.id_converter()?; + let mut old_ids = vec![self.space_id.clone()]; + + if let Some(root_bin) = self.raw_get_doc(&self.space_id)? { + let root_converter = + IdConverter::from_root_doc_bytes(&self.space_id, None, Some(&root_bin))?; + for (_, subdoc_guid) in root_converter.page_mappings() { + if self.workspace_rows.contains_key(subdoc_guid) { + old_ids.push(subdoc_guid.to_string()); + } + } + } + + let db_prefix = format!("db${}$", self.space_id); + for key in self.workspace_rows.keys() { + if key.starts_with(&db_prefix) || is_userdata_key_for_space(key, &self.space_id) { + old_ids.push(key.clone()); + } + } + + let mut out = BTreeMap::new(); + for old_id in old_ids { + if self.workspace_rows.contains_key(&old_id) || old_id == self.space_id { + out.insert( + converter.old_id_to_new_id(&old_id), + IDB_V1_CONST_TIMESTAMP_MS, + ); + } + } + Ok(out) + } + + fn raw_get_doc(&self, old_id: &str) -> StoreResult>> { + let Some(updates) = self.workspace_rows.get(old_id) else { + return Ok(None); + }; + if updates.is_empty() { + return Ok(None); + } + if updates.len() == 1 { + return Ok(Some(updates[0].update.clone())); + } + let merged = merge_updates_v1(updates.iter().map(|u| u.update.as_slice())) + .and_then(|u| u.encode_v1()) + .map_err(|err| StoreError::InvalidBinary(err.to_string()))?; + Ok(Some(merged)) + } +} + +/// Exact `$`-segmented match for 3-segment (`userdata$$`) and 4-segment +/// (`userdata$$$`) keys, preventing prefix collisions like `ws-1` vs `ws-10`. +fn is_userdata_key_for_space(key: &str, space_id: &str) -> bool { + let mut parts = key.split('$'); + let Some(prefix) = parts.next() else { + return false; + }; + let Some(uid) = parts.next() else { + return false; + }; + let Some(key_space_id) = parts.next() else { + return false; + }; + if prefix != "userdata" || uid.is_empty() || key_space_id != space_id { + return false; + } + match (parts.next(), parts.next()) { + (None, None) => true, + (Some(doc_id), None) => !doc_id.is_empty(), + _ => false, + } +} + +/// Blob record returned by [`IdbV1BlobStorage::get`]. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct IdbV1BlobRecord { + pub key: String, + pub mime: String, + pub data: Vec, +} + +/// Listed blob metadata returned by [`IdbV1BlobStorage::list`]. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct IdbV1ListedBlob { + pub key: String, + pub mime: String, + pub size: usize, +} + +/// Read-only IndexedDB V1 blob storage model (`${spaceId}_blob` / `blob`). +#[derive(Clone, Debug)] +pub struct IdbV1BlobStorage { + space_id: String, + blobs: BTreeMap>, +} + +impl IdbV1BlobStorage { + pub fn new(space_id: impl Into, blobs: BTreeMap>) -> Self { + Self { + space_id: space_id.into(), + blobs, + } + } + + pub fn db_name(&self) -> String { + idb_v1_blob_db_name(&self.space_id) + } + + pub fn is_readonly(&self) -> bool { + true + } + + pub fn get(&self, key: &str) -> Option { + self.blobs.get(key).map(|data| IdbV1BlobRecord { + key: key.to_string(), + mime: String::new(), + data: data.clone(), + }) + } + + pub fn list(&self) -> Vec { + self.blobs + .iter() + .map(|(key, data)| IdbV1ListedBlob { + key: key.clone(), + mime: String::new(), + size: data.len(), + }) + .collect() + } + + /// V1 blob storage is read-only; `set` is a no-op. + pub fn set(&mut self, _key: &str, _data: Vec) {} +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn v1_fallback_is_web_only_and_readonly() { + assert!(is_idb_v1_fallback_enabled(IdbHostPlatform::Web)); + assert!(is_idb_v1_fallback_enabled(IdbHostPlatform::MobileWeb)); + assert!(!is_idb_v1_fallback_enabled(IdbHostPlatform::Ios)); + assert!(!is_idb_v1_fallback_enabled(IdbHostPlatform::Android)); + assert!(!is_idb_v1_fallback_enabled(IdbHostPlatform::Electron)); + + let mut rows = BTreeMap::new(); + rows.insert( + "db$ws-1$folders".to_string(), + vec![IdbV1RawUpdate { + timestamp_ms: 100, + update: vec![0, 0], + }], + ); + rows.insert( + "userdata$u1$ws-1".to_string(), + vec![IdbV1RawUpdate { + timestamp_ms: 100, + update: vec![0, 0], + }], + ); + rows.insert( + "userdata$u1$ws-1$favorite".to_string(), + vec![IdbV1RawUpdate { + timestamp_ms: 100, + update: vec![0, 0], + }], + ); + rows.insert( + "userdata$u1$ws-10$favorite".to_string(), + vec![IdbV1RawUpdate { + timestamp_ms: 100, + update: vec![0, 0], + }], + ); + let mut docs = IdbV1DocStorage::new("ws-1", rows); + assert!(docs.is_readonly()); + assert_eq!( + docs.push_doc_update("ws-1", &[0, 0]), + IDB_V1_CONST_TIMESTAMP_MS + ); + let ts = docs.get_doc_timestamps().unwrap(); + assert_eq!(ts.get("db$folders"), Some(&IDB_V1_CONST_TIMESTAMP_MS)); + assert_eq!(ts.get("userdata$u1$ws-1"), Some(&IDB_V1_CONST_TIMESTAMP_MS)); + assert_eq!( + ts.get("userdata$u1$favorite"), + Some(&IDB_V1_CONST_TIMESTAMP_MS) + ); + assert!(!ts.contains_key("userdata$u1$ws-10$favorite")); + assert!(!ts.contains_key("userdata$u1$0$favorite")); + let doc = docs.get_doc("db$folders").unwrap().unwrap(); + assert_eq!(doc.timestamp_ms, IDB_V1_CONST_TIMESTAMP_MS); + + // Verify modern pages (subdoc.guid == page_id) AND legacy pages (subdoc.guid != page_id) + // are both discovered by `get_doc_timestamps()` and readable via `get_doc()`. + let mut root_session = y_octo::DocSession::<()>::with_config( + y_octo::DocOptions::from_identity(1, "ws-v1".to_string()), + y_octo::SessionConfig { + undo: y_octo::SessionUndoConfig::Disabled, + }, + ); + let meta = y_octo::TypeTarget::from( + root_session + .ensure_root("meta", y_octo::YTypeKind::Map) + .unwrap(), + ); + let spaces = y_octo::TypeTarget::from( + root_session + .ensure_root("spaces", y_octo::YTypeKind::Map) + .unwrap(), + ); + root_session + .begin_tx(y_octo::SessionTxOrigin::Untracked) + .unwrap(); + root_session + .map_set( + &meta, + "pages".to_string(), + y_octo::SessionValue::Array(Vec::new()), + ) + .unwrap(); + let pages_target = y_octo::TypeTarget::Path(y_octo::TypePath::root("meta").key("pages")); + root_session + .array_push( + &pages_target, + vec![ + y_octo::SessionValue::Map(vec![( + "id".to_string(), + y_octo::SessionValue::Any(y_octo::Any::String("page-1".into())), + )]), + y_octo::SessionValue::Map(vec![( + "id".to_string(), + y_octo::SessionValue::Any(y_octo::Any::String("page-2".into())), + )]), + ], + ) + .unwrap(); + root_session + .map_set( + &spaces, + "page-1".to_string(), + y_octo::SessionValue::Doc { + guid: "legacy-guid-1".into(), + gc: true, + }, + ) + .unwrap(); + root_session + .map_set( + &spaces, + "page-2".to_string(), + y_octo::SessionValue::Doc { + guid: "page-2".into(), + gc: true, + }, + ) + .unwrap(); + let root_bin = root_session.commit_tx().unwrap().unwrap().update; + + let mut page_rows = BTreeMap::new(); + page_rows.insert( + "ws-v1".into(), + vec![IdbV1RawUpdate { + timestamp_ms: 10, + update: root_bin, + }], + ); + page_rows.insert( + "legacy-guid-1".into(), + vec![IdbV1RawUpdate { + timestamp_ms: 11, + update: vec![0, 0], + }], + ); + page_rows.insert( + "page-2".into(), + vec![IdbV1RawUpdate { + timestamp_ms: 12, + update: vec![0, 0], + }], + ); + let v1_pages = IdbV1DocStorage::new("ws-v1", page_rows); + let page_ts = v1_pages.get_doc_timestamps().unwrap(); + assert_eq!(page_ts.get("page-1"), Some(&IDB_V1_CONST_TIMESTAMP_MS)); + assert_eq!(page_ts.get("page-2"), Some(&IDB_V1_CONST_TIMESTAMP_MS)); + assert!(v1_pages.get_doc("page-1").unwrap().is_some()); + assert!(v1_pages.get_doc("page-2").unwrap().is_some()); + + let mut blobs = IdbV1BlobStorage::new("ws-1", BTreeMap::from([("k1".into(), vec![1, 2])])); + assert_eq!(blobs.db_name(), "ws-1_blob"); + blobs.set("k2", vec![3]); + assert!(blobs.get("k2").is_none()); + assert_eq!(blobs.list().len(), 1); + } +} diff --git a/packages/common/store/src/lib.rs b/packages/common/store/src/lib.rs index 5e7f36be93..c628487bfb 100644 --- a/packages/common/store/src/lib.rs +++ b/packages/common/store/src/lib.rs @@ -1,10 +1,12 @@ #![forbid(unsafe_code)] +pub mod api_client; pub mod blob_api; pub mod clock; pub mod directory; pub mod error; pub mod id_converter; +pub mod idb; #[cfg(not(target_family = "wasm"))] pub mod sqlite; pub mod sync; diff --git a/packages/common/store/src/sqlite/storage.rs b/packages/common/store/src/sqlite/storage.rs index ad1b15c253..74619886e1 100644 --- a/packages/common/store/src/sqlite/storage.rs +++ b/packages/common/store/src/sqlite/storage.rs @@ -25,7 +25,8 @@ impl SqliteDocStorage { let base_options = SqliteConnectOptions::new() .filename(&path) .foreign_keys(true) - .synchronous(SqliteSynchronous::Full); + .synchronous(SqliteSynchronous::Full) + .busy_timeout(std::time::Duration::from_millis(5_000)); if path == ":memory:" { let pool = SqlitePoolOptions::new() @@ -82,7 +83,7 @@ impl SqliteDocStorage { self.pool.is_closed() } - /// Flush the WAL journal into the main database file. + /// Flush the WAL journal into the main database file (`FULL` mode). pub async fn checkpoint(&self) -> StoreResult<()> { sqlx::query("PRAGMA wal_checkpoint(FULL);") .execute(&self.pool) @@ -90,6 +91,14 @@ impl SqliteDocStorage { Ok(()) } + /// Perform a non-blocking `PASSIVE` WAL checkpoint. + pub async fn checkpoint_passive(&self) -> StoreResult<()> { + sqlx::query("PRAGMA wal_checkpoint(PASSIVE);") + .execute(&self.pool) + .await?; + Ok(()) + } + /// Export a compacted copy of the database to `target_path`. pub async fn vacuum_into(&self, target_path: &str) -> StoreResult<()> { sqlx::query("VACUUM INTO ?;") diff --git a/packages/common/store/src/sqlite/sync.rs b/packages/common/store/src/sqlite/sync.rs index 25a5f6d5bc..5dc633fa36 100644 --- a/packages/common/store/src/sqlite/sync.rs +++ b/packages/common/store/src/sqlite/sync.rs @@ -334,6 +334,68 @@ impl SqliteDocStorage { tx.commit().await?; Ok(()) } + /// Persist inbound `SpaceSyncEvent` document updates atomically inside a single + /// `BEGIN IMMEDIATE` transaction via [`Self::push_updates_batch`], then advance both + /// `remote_clock` and `pulled_remote_clock` in `peer_clocks` using each event's server + /// `timestamp` (distinct from `local_now_ms`). + pub async fn persist_inbound_sync_events( + &self, + peer: &str, + events: &[crate::sync::SpaceSyncEvent], + local_now_ms: i64, + ) -> StoreResult> { + let mut batch = Vec::new(); + let mut remote_clocks: HashMap = HashMap::new(); + for event in events { + match event { + crate::sync::SpaceSyncEvent::DocLoaded { + doc_id, + missing, + timestamp, + .. + } => { + remote_clocks + .entry(doc_id.clone()) + .and_modify(|ts| *ts = (*ts).max(*timestamp)) + .or_insert(*timestamp); + if !missing.is_empty() && missing.as_slice() != [0, 0] { + batch.push(crate::workspace_db::PendingDocUpdate { + doc_id: doc_id.clone(), + update: missing.clone(), + }); + } + } + crate::sync::SpaceSyncEvent::RemoteDocUpdates { + doc_id, + updates, + timestamp, + .. + } => { + remote_clocks + .entry(doc_id.clone()) + .and_modify(|ts| *ts = (*ts).max(*timestamp)) + .or_insert(*timestamp); + for update in updates { + if !update.is_empty() && update.as_slice() != [0, 0] { + batch.push(crate::workspace_db::PendingDocUpdate { + doc_id: doc_id.clone(), + update: update.clone(), + }); + } + } + } + _ => {} + } + } + let persisted = self.push_updates_batch(&batch, None, local_now_ms).await?; + for (doc_id, remote_ms) in remote_clocks { + let remote_dt = millis_to_naive_utc(remote_ms); + self.set_peer_remote_clock(peer, &doc_id, remote_dt).await?; + self.set_peer_pulled_remote_clock(peer, &doc_id, remote_dt) + .await?; + } + Ok(persisted) + } } #[cfg(test)] @@ -403,4 +465,35 @@ mod tests { .unwrap(); assert_eq!(cleared.docs.len(), 1); } + + #[tokio::test] + async fn persist_inbound_sync_events_updates_doc_and_peer_remote_clocks() { + let storage = SqliteDocStorage::new(":memory:"); + storage.connect().await.unwrap(); + let mut ws = crate::workspace_db::WorkspaceDb::new("ws-sync", "u1", 1); + let init = ws.initialize_meta().unwrap().unwrap(); + let events = vec![crate::sync::SpaceSyncEvent::DocLoaded { + doc_id: "ws-sync".into(), + missing: init.clone(), + state: vec![], + timestamp: 42_000, + }]; + let persisted = storage + .persist_inbound_sync_events("cloud", &events, 50_000) + .await + .unwrap(); + assert_eq!(persisted.len(), 1); + let remote = storage + .get_peer_remote_clock("cloud", "ws-sync") + .await + .unwrap() + .unwrap(); + let pulled = storage + .get_peer_pulled_remote_clock("cloud", "ws-sync") + .await + .unwrap() + .unwrap(); + assert_eq!(naive_utc_to_millis(remote.timestamp), 42_000); + assert_eq!(naive_utc_to_millis(pulled.timestamp), 42_000); + } } diff --git a/packages/common/store/src/sync/engine/mod.rs b/packages/common/store/src/sync/engine/mod.rs index f00ae76f34..36792c453b 100644 --- a/packages/common/store/src/sync/engine/mod.rs +++ b/packages/common/store/src/sync/engine/mod.rs @@ -31,12 +31,14 @@ pub enum SocketAuthMode { WebCookie, /// Native iOS / Android: send `{"token": ..., "tokenType": "jwt"}` in Socket.IO `40` CONNECT. NativeJwt { token: String }, + /// Native host with no stored session credentials (never falls back to Web cookies). + Unauthenticated, } impl SocketAuthMode { pub(super) fn to_connect_payload(&self) -> Value { match self { - Self::WebCookie => json!({}), + Self::WebCookie | Self::Unauthenticated => json!({}), Self::NativeJwt { token } => json!({ "token": token, "tokenType": "jwt", diff --git a/packages/frontend/AGENTS.md b/packages/frontend/AGENTS.md index 371cc184c9..632120a495 100644 --- a/packages/frontend/AGENTS.md +++ b/packages/frontend/AGENTS.md @@ -5,7 +5,7 @@ It uses `resolver = "3"`, edition 2024, and its own `rust-toolchain.toml` (`1.98 ## Workspace boundaries and four-domain guards -- `packages/frontend/Cargo.toml` lists every client member crate explicitly (`../ui/tokens`, `../ui/ui`, `../ui/kit`, `../common/store`, `../../blocksuite/crates/doc`, `../../blocksuite/crates/editor`, `../../blocksuite/crates/playground`, `../../blocksuite/crates/preview`, `hosts/android`, and `hosts/ios`). +- `packages/frontend/Cargo.toml` lists every client member crate explicitly (`../ui/tokens`, `../ui/ui`, `../ui/kit`, `../common/store`, `legacy-import`, `client`, `../../blocksuite/crates/doc`, `../../blocksuite/crates/editor`, `../../blocksuite/crates/playground`, `../../blocksuite/crates/preview`, `hosts/android`, and `hosts/ios`). Never use directory wildcards that can scan asset directories. - `packages/frontend/Cargo.toml` excludes `native` and `mobile-native`. Those legacy crates remain members of the root `Cargo.toml` workspace. diff --git a/packages/frontend/Cargo.lock b/packages/frontend/Cargo.lock index 0fc704d1af..ee32ad878e 100644 --- a/packages/frontend/Cargo.lock +++ b/packages/frontend/Cargo.lock @@ -31,10 +31,33 @@ dependencies = [ "serde_json", ] +[[package]] +name = "affine-client" +version = "0.1.0" +dependencies = [ + "affine-legacy-import", + "affine-store", + "blocksuite-editor", + "getrandom 0.3.4", + "serde", + "serde_json", + "thiserror 2.0.21", + "y-octo", +] + [[package]] name = "affine-ios-host" version = "0.1.0" +[[package]] +name = "affine-legacy-import" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", + "thiserror 2.0.21", +] + [[package]] name = "affine-store" version = "0.1.0" diff --git a/packages/frontend/Cargo.toml b/packages/frontend/Cargo.toml index 13eb06de9c..c6d1620de1 100644 --- a/packages/frontend/Cargo.toml +++ b/packages/frontend/Cargo.toml @@ -5,6 +5,8 @@ members = [ "../ui/ui", "../ui/kit", "../common/store", + "legacy-import", + "client", "../../blocksuite/crates/doc", "../../blocksuite/crates/editor", "../../blocksuite/crates/playground", @@ -17,6 +19,8 @@ default-members = [ "../ui/ui", "../ui/kit", "../common/store", + "legacy-import", + "client", "../../blocksuite/crates/doc", "../../blocksuite/crates/editor", "../../blocksuite/crates/playground", diff --git a/packages/frontend/client/AGENTS.md b/packages/frontend/client/AGENTS.md new file mode 100644 index 0000000000..543ccefa78 --- /dev/null +++ b/packages/frontend/client/AGENTS.md @@ -0,0 +1,13 @@ +# Working in `packages/frontend/client/` (for agents) + +`packages/frontend/client/` (`affine-client`) is the L3 device-neutral client domain crate shared by Mobile, Desktop, and Web hosts. +This crate belongs to the client Cargo workspace rooted at `packages/frontend/Cargo.toml`. + +## Domain boundaries and invariants + +- Keep `#![forbid(unsafe_code)]` at the crate root. +- Remain strictly device-neutral: never import `ui::Window`, view elements, or mobile-only shell concepts. +- Enforce `F3`: only `HostKind::Native` allows adding cross-origin self-hosted servers; `HostKind::Web` rejects self-hosted server addition. +- Keep `StoreBackedDocDirectory` (`WorkspaceDocDirectory` implementation) aligned with the root-registration and anti-resurrection invariants (`F1`): persist `root_registered` immediately upon root write success, return `Err(DirectoryError::NotFound)` on replaying deleted intents, and preserve unfinished create intents across restarts. +- Keep `PlatformAccessibility` active in production (non-`harness`) builds so Web, iOS, and Android hosts can consume a stable first-frame semantic root. +- Keep every `.rs` file at or below 800 non-test lines, zero `super::super::`, and zero system wall-clock calls. diff --git a/packages/frontend/client/CLAUDE.md b/packages/frontend/client/CLAUDE.md new file mode 100644 index 0000000000..43c994c2d3 --- /dev/null +++ b/packages/frontend/client/CLAUDE.md @@ -0,0 +1 @@ +@AGENTS.md diff --git a/packages/frontend/client/Cargo.toml b/packages/frontend/client/Cargo.toml new file mode 100644 index 0000000000..e4f81f2941 --- /dev/null +++ b/packages/frontend/client/Cargo.toml @@ -0,0 +1,22 @@ +[package] +name = "affine-client" +workspace = ".." +version.workspace = true +edition.workspace = true +publish.workspace = true +license.workspace = true + +[lints] +workspace = true + +[dependencies] +affine-legacy-import = { path = "../legacy-import" } +affine-store = { path = "../../common/store" } +blocksuite-editor = { path = "../../../blocksuite/crates/editor" } +getrandom.workspace = true +serde.workspace = true +serde_json.workspace = true +thiserror.workspace = true + +[dev-dependencies] +y-octo.workspace = true diff --git a/packages/frontend/client/src/accessibility.rs b/packages/frontend/client/src/accessibility.rs new file mode 100644 index 0000000000..db324e6ceb --- /dev/null +++ b/packages/frontend/client/src/accessibility.rs @@ -0,0 +1,226 @@ +//! First-frame production accessibility semantic entry (`PlatformAccessibility`). +//! +//! Always compiled and active in shipping (non-`harness`) builds so Web (ARIA), iOS +//! (`UIAccessibility`), and Android (`AccessibilityNodeInfo`) hosts can discover the root +//! semantic tree on frame 1. + +use std::collections::BTreeMap; + +use serde::{Deserialize, Serialize}; + +/// Semantic role exported to platform accessibility trees. +#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum AccessibilityRole { + Application, + Main, + Navigation, + Region, + Heading, + Button, + TextField, + Document, + List, + ListItem, + Tab, + TabList, + Dialog, + Alert, + Status, +} + +/// Logical screen-space bounding rectangle in logical pixels. +#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct AccessibilityBounds { + pub x: f32, + pub y: f32, + pub width: f32, + pub height: f32, +} + +/// Semantic state flags exposed on an [`AccessibilityNode`]. +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AccessibilityState { + pub disabled: bool, + pub selected: bool, + pub checked: Option, + pub expanded: Option, + pub hidden: bool, + pub busy: bool, +} + +/// Stable production semantic node consumed by Web, iOS, and Android hosts. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AccessibilityNode { + pub id: String, + pub role: AccessibilityRole, + pub name: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub value: Option, + pub state: AccessibilityState, + pub focused: bool, + pub bounds: AccessibilityBounds, + pub children: Vec, +} + +/// Complete semantic tree snapshot exported on first frame and subsequent updates. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AccessibilityTree { + pub root_id: String, + pub nodes: BTreeMap, +} + +impl AccessibilityTree { + pub fn root(&self) -> Option<&AccessibilityNode> { + self.nodes.get(&self.root_id) + } + + pub fn node(&self, id: &str) -> Option<&AccessibilityNode> { + self.nodes.get(id) + } + + pub fn focused_node(&self) -> Option<&AccessibilityNode> { + self.nodes.values().find(|n| n.focused) + } +} + +/// Production accessibility sink implemented by Web, iOS, and Android platform hosts. +pub trait PlatformAccessibility { + /// Publish the latest semantic tree snapshot to the native accessibility bridge. + fn publish_tree(&mut self, tree: &AccessibilityTree); + + /// Announce a live status update (e.g. "Document created", "Offline mode"). + fn announce(&mut self, message: &str, polite: bool); +} + +/// Builder producing a discoverable first-frame production semantic root entry. +#[derive(Clone, Debug)] +pub struct FirstFrameAccessibilityRoot { + app_name: String, + workspace_name: String, + active_doc_title: Option, + viewport_bounds: AccessibilityBounds, +} + +impl FirstFrameAccessibilityRoot { + pub fn new( + app_name: impl Into, + workspace_name: impl Into, + active_doc_title: Option, + viewport_bounds: AccessibilityBounds, + ) -> Self { + Self { + app_name: app_name.into(), + workspace_name: workspace_name.into(), + active_doc_title, + viewport_bounds, + } + } + + /// Build the frame-1 semantic tree with stable root, navigation, and main document landmarks. + pub fn build_tree(&self) -> AccessibilityTree { + let root_id = "app.root".to_string(); + let nav_id = "app.navigation".to_string(); + let main_id = "app.main".to_string(); + + let mut nodes = BTreeMap::new(); + nodes.insert( + root_id.clone(), + AccessibilityNode { + id: root_id.clone(), + role: AccessibilityRole::Application, + name: self.app_name.clone(), + value: Some(self.workspace_name.clone()), + state: AccessibilityState::default(), + focused: false, + bounds: self.viewport_bounds, + children: vec![nav_id.clone(), main_id.clone()], + }, + ); + nodes.insert( + nav_id.clone(), + AccessibilityNode { + id: nav_id, + role: AccessibilityRole::Navigation, + name: self.workspace_name.clone(), + value: None, + state: AccessibilityState::default(), + focused: false, + bounds: self.viewport_bounds, + children: Vec::new(), + }, + ); + nodes.insert( + main_id.clone(), + AccessibilityNode { + id: main_id, + role: AccessibilityRole::Main, + name: self + .active_doc_title + .clone() + .unwrap_or_else(|| self.workspace_name.clone()), + value: self.active_doc_title.clone(), + state: AccessibilityState::default(), + focused: true, + bounds: self.viewport_bounds, + children: Vec::new(), + }, + ); + + AccessibilityTree { root_id, nodes } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + struct RecordingAccessibility { + trees: Vec, + announcements: Vec<(String, bool)>, + } + + impl PlatformAccessibility for RecordingAccessibility { + fn publish_tree(&mut self, tree: &AccessibilityTree) { + self.trees.push(tree.clone()); + } + + fn announce(&mut self, message: &str, polite: bool) { + self.announcements.push((message.to_string(), polite)); + } + } + + #[test] + fn first_frame_accessibility_root_exports_stable_semantic_landmarks() { + let builder = FirstFrameAccessibilityRoot::new( + "AFFiNE", + "Personal Workspace", + Some("Welcome".into()), + AccessibilityBounds { + x: 0.0, + y: 0.0, + width: 390.0, + height: 844.0, + }, + ); + let tree = builder.build_tree(); + let mut sink = RecordingAccessibility { + trees: Vec::new(), + announcements: Vec::new(), + }; + sink.publish_tree(&tree); + sink.announce("Workspace ready", true); + + assert_eq!(sink.trees.len(), 1); + let root = sink.trees[0].root().expect("root node"); + assert_eq!(root.role, AccessibilityRole::Application); + assert_eq!(root.children, vec!["app.navigation", "app.main"]); + let focused = sink.trees[0].focused_node().expect("focused main node"); + assert_eq!(focused.id, "app.main"); + assert_eq!(focused.name, "Welcome"); + assert_eq!(sink.announcements, vec![("Workspace ready".into(), true)]); + } +} diff --git a/packages/frontend/client/src/auth.rs b/packages/frontend/client/src/auth.rs new file mode 100644 index 0000000000..66c34b27fc --- /dev/null +++ b/packages/frontend/client/src/auth.rs @@ -0,0 +1,541 @@ +//! Pure sans-I/O authentication state machine and `0.27.5` `StoredAuthTokenPair` codec. +//! +//! ## Single Refresh Owner Architecture +//! Native platform hosts (`hosts/ios` `LegacyAuthBridge` and `hosts/android` `AuthSessionStore`) +//! are the sole I/O owners for Keychain/Keystore persistence and single-flight network +//! `/api/auth/session/{exchange,refresh,revoke}` execution. [`AuthController`] performs zero +//! network I/O and zero credential writes; host coordinators feed outcomes into +//! [`AuthController::apply_native_tokens`], [`AuthController::clear_native_session`], and +//! [`AuthController::apply_session_response`]. + +use affine_store::{ + api_client::{ + ApiHttpRequest, ApiRequestContext, AuthSessionMeta, AuthSessionUser, AuthTokenPairResponse, + build_get_auth_session_request, decode_auth_session_response, + }, + sync::SocketAuthMode, +}; +use serde::{Deserialize, Serialize}; + +use crate::{ + ClientError, ClientResult, + host::{HostBridge, HostKind}, +}; + +/// Seconds between Unix epoch (`1970-01-01T00:00:00Z`) and Apple CoreFoundation / `Date` +/// reference epoch (`2001-01-01T00:00:00Z`). +pub const APPLE_CF_EPOCH_OFFSET_SECS: f64 = 978_307_200.0; + +/// Native host storage format selector preventing iOS CF-epoch integer-second ambiguity. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum NativeAuthPlatform { + /// iOS Keychain JSON (`accessExpiresAt` encoded as 2001 CoreFoundation epoch seconds). + Ios, + /// Android DataStore JSON (`accessExpiresAt` encoded as 1970 Unix milliseconds). + Android, +} + +/// Canonical `0.27.5` persisted native token pair (`StoredAuthTokenPair`). +/// +/// Stores `version = 1`, absolute `accessExpiresAt` (Unix ms in memory / Android DataStore, +/// convertible losslessly to/from iOS 2001 CF epoch seconds), and nested `session: { id, absoluteExpiresAt }`. +#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct StoredAuthTokenPair { + pub version: u32, + pub token_type: String, + pub access_token: String, + pub access_expires_at: i64, + pub refresh_token: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub refresh_expires_at: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub session: Option, +} + +/// Alias preserving compatibility for callers referring to `NativeTokenPair`. +pub type NativeTokenPair = StoredAuthTokenPair; + +#[derive(Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +struct IosKeychainTokenPairWire { + version: u32, + token_type: String, + access_token: String, + access_expires_at: f64, + refresh_token: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + refresh_expires_at: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + session: Option, +} + +impl StoredAuthTokenPair { + /// Validate and convert a server [`AuthTokenPairResponse`] into a [`StoredAuthTokenPair`] + /// using an explicit deterministic `now_ms`. + /// + /// Rejects non-`Bearer` `token_type`, missing or zero `expires_in`, and malformed RFC 3339 + /// `refresh_expires_at` / `session.absolute_expires_at` timestamps. + pub fn from_wire(parsed: AuthTokenPairResponse, now_ms: i64) -> ClientResult { + let token_type = parsed + .token_type + .as_deref() + .filter(|t| t.eq_ignore_ascii_case("Bearer")) + .ok_or_else(|| { + ClientError::InvalidAuthPayload(format!( + "expected Bearer tokenType, got {:?}", + parsed.token_type + )) + })?; + let expires_in = parsed.expires_in.filter(|&secs| secs > 0).ok_or_else(|| { + ClientError::InvalidAuthPayload("expiresIn must be a positive integer".into()) + })?; + if let Some(ref ts) = parsed.refresh_expires_at + && !is_valid_rfc3339(ts) + { + return Err(ClientError::InvalidAuthPayload(format!( + "invalid RFC3339 refreshExpiresAt: `{ts}`" + ))); + } + let session = parsed.session.or_else(|| { + parsed.session_id.map(|id| AuthSessionMeta { + id, + absolute_expires_at: None, + }) + }); + if let Some(ref meta) = session + && let Some(ref abs_ts) = meta.absolute_expires_at + && !is_valid_rfc3339(abs_ts) + { + return Err(ClientError::InvalidAuthPayload(format!( + "invalid RFC3339 session.absoluteExpiresAt: `{abs_ts}`" + ))); + } + + let expires_ms = expires_in + .checked_mul(1_000) + .and_then(|ms| i64::try_from(ms).ok()) + .ok_or_else(|| ClientError::InvalidAuthPayload("expiresIn overflow".into()))?; + + Ok(Self { + version: 1, + token_type: token_type.to_string(), + access_token: parsed.access_token, + access_expires_at: now_ms.saturating_add(expires_ms), + refresh_token: parsed.refresh_token, + refresh_expires_at: parsed.refresh_expires_at, + session, + }) + } + + pub fn session_id(&self) -> Option<&str> { + self.session.as_ref().map(|s| s.id.as_str()) + } + + pub fn access_expires_at_unix_ms(&self) -> i64 { + self.access_expires_at + } + + /// Convert `access_expires_at` (Unix ms) to iOS `Date` / CF 2001 epoch seconds. + pub fn access_expires_at_ios_cf_secs(&self) -> f64 { + (self.access_expires_at as f64 / 1_000.0) - APPLE_CF_EPOCH_OFFSET_SECS + } + + /// Convert iOS `Date` / CF 2001 epoch seconds back to Unix milliseconds. + pub fn unix_ms_from_ios_cf_secs(cf_secs: f64) -> i64 { + ((cf_secs + APPLE_CF_EPOCH_OFFSET_SECS) * 1_000.0).round() as i64 + } + + /// Serialize to the exact `0.27.5` Android DataStore JSON format (Unix ms `accessExpiresAt`). + pub fn to_android_datastore_json(&self) -> ClientResult { + Ok(serde_json::to_string(self)?) + } + + /// Deserialize from the exact `0.27.5` Android DataStore JSON format. + pub fn from_android_datastore_json(raw: &str) -> ClientResult { + Ok(serde_json::from_str(raw)?) + } + + /// Serialize to the exact `0.27.5` iOS Keychain JSON format (2001 CF epoch seconds `accessExpiresAt`). + pub fn to_ios_keychain_json(&self) -> ClientResult { + let wire = IosKeychainTokenPairWire { + version: self.version, + token_type: self.token_type.clone(), + access_token: self.access_token.clone(), + access_expires_at: self.access_expires_at_ios_cf_secs(), + refresh_token: self.refresh_token.clone(), + refresh_expires_at: self.refresh_expires_at.clone(), + session: self.session.clone(), + }; + Ok(serde_json::to_string(&wire)?) + } + + /// Deserialize from the exact `0.27.5` iOS Keychain JSON format. + pub fn from_ios_keychain_json(raw: &str) -> ClientResult { + let wire: IosKeychainTokenPairWire = serde_json::from_str(raw)?; + Ok(Self { + version: wire.version, + token_type: wire.token_type, + access_token: wire.access_token, + access_expires_at: Self::unix_ms_from_ios_cf_secs(wire.access_expires_at), + refresh_token: wire.refresh_token, + refresh_expires_at: wire.refresh_expires_at, + session: wire.session, + }) + } +} + +/// Active session state for a single server. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum AuthSessionState { + SignedOut, + Authenticated { user: AuthSessionUser }, +} + +/// Pure sans-I/O per-server authentication state machine. +#[derive(Clone, Debug)] +pub struct AuthController { + server_id: String, + base_url: String, + host_kind: HostKind, + state: AuthSessionState, + native_tokens: Option, + mutation_epoch: u64, +} + +impl AuthController { + pub fn new( + server_id: impl Into, + base_url: impl Into, + host_kind: HostKind, + ) -> Self { + Self { + server_id: server_id.into(), + base_url: base_url.into().trim().trim_end_matches('/').to_string(), + host_kind, + state: AuthSessionState::SignedOut, + native_tokens: None, + mutation_epoch: 0, + } + } + + pub fn server_id(&self) -> &str { + &self.server_id + } + + pub fn base_url(&self) -> &str { + &self.base_url + } + + /// Endpoint-scoped credential key (`auth:`) isolating credentials by URL. + pub fn credential_key(&self) -> String { + format!("auth:{}", self.base_url) + } + + pub fn mutation_epoch(&self) -> u64 { + self.mutation_epoch + } + + pub fn state(&self) -> &AuthSessionState { + &self.state + } + + pub fn native_tokens(&self) -> Option<&StoredAuthTokenPair> { + self.native_tokens.as_ref() + } + + /// Hydrate offline cached user profile (for example from `global-state:-auth`) + /// so transient `5xx`/`429`/network failures preserve the cached signed-in UI state. + pub fn set_cached_user(&mut self, user: AuthSessionUser) { + self.state = AuthSessionState::Authenticated { user }; + } + + /// Sync newly exchanged or refreshed tokens produced by the native host coordinator. + pub fn apply_native_tokens(&mut self, pair: StoredAuthTokenPair) { + self.mutation_epoch = self.mutation_epoch.saturating_add(1); + self.native_tokens = Some(pair); + } + + /// Clear in-memory tokens and transition to `SignedOut` after host-owned revoke/sign-out. + pub fn clear_native_session(&mut self) { + self.mutation_epoch = self.mutation_epoch.saturating_add(1); + self.native_tokens = None; + self.state = AuthSessionState::SignedOut; + } + + /// Build the frozen [`ApiRequestContext`] for this host kind and current credential state. + pub fn api_context(&self) -> ApiRequestContext { + match self.host_kind { + HostKind::Web => ApiRequestContext::web(), + HostKind::Native => ApiRequestContext::native( + self.native_tokens.as_ref().map(|t| t.access_token.clone()), + ), + } + } + + /// Build the Socket.IO `40` CONNECT [`SocketAuthMode`] for `SpaceSyncEngine`. + /// + /// Native hosts without stored tokens return [`SocketAuthMode::Unauthenticated`] and never + /// fall back to [`SocketAuthMode::WebCookie`]. + pub fn socket_auth_mode(&self) -> SocketAuthMode { + match self.host_kind { + HostKind::Web => SocketAuthMode::WebCookie, + HostKind::Native => match &self.native_tokens { + Some(tokens) => SocketAuthMode::NativeJwt { + token: tokens.access_token.clone(), + }, + None => SocketAuthMode::Unauthenticated, + }, + } + } + + /// Build a transport-agnostic `GET /api/auth/session` request for the host to execute. + pub fn build_session_request(&self) -> ApiHttpRequest { + build_get_auth_session_request(&self.api_context()) + } + + /// Apply a `GET /api/auth/session` HTTP response to [`AuthSessionState`]. + /// + /// Transitions to `SignedOut` ONLY on `401`/`403` or `200 { user: null }`. Any other error + /// status (`>= 400`, including `429` and `5xx`) returns `Err` and preserves `self.state`. + pub fn apply_session_response( + &mut self, + status: u16, + body: &[u8], + ) -> ClientResult { + if status == 401 || status == 403 { + self.state = AuthSessionState::SignedOut; + return Ok(self.state.clone()); + } + if status >= 400 { + return Err(ClientError::Host(format!( + "fetch session failed with transient HTTP {status}" + ))); + } + let decoded = decode_auth_session_response(body)?; + self.state = match decoded.user { + Some(user) => AuthSessionState::Authenticated { user }, + None => AuthSessionState::SignedOut, + }; + Ok(self.state.clone()) + } + + /// Load stored native credentials from [`HostBridge`] using the explicit [`NativeAuthPlatform`] + /// codec. + /// + /// - When the host vault returns `None` (credential deleted by the host coordinator), clears + /// in-memory `native_tokens` and transitions to `SignedOut` so no stale JWT remains. + /// - When the stored JSON is corrupted, deletes it via `host.delete_credential`, clears + /// in-memory state, and returns `Ok(false)`. + pub fn load_stored_credentials( + &mut self, + host: &mut dyn HostBridge, + platform: NativeAuthPlatform, + ) -> ClientResult { + if self.host_kind != HostKind::Native { + return Ok(false); + } + let key = self.credential_key(); + let Some(raw) = host.read_credential(&key)? else { + self.clear_native_session(); + return Ok(false); + }; + let parsed = match platform { + NativeAuthPlatform::Ios => StoredAuthTokenPair::from_ios_keychain_json(&raw), + NativeAuthPlatform::Android => StoredAuthTokenPair::from_android_datastore_json(&raw), + }; + match parsed { + Ok(pair) => { + self.apply_native_tokens(pair); + Ok(true) + } + Err(_) => { + let _ = host.delete_credential(&key); + self.clear_native_session(); + Ok(false) + } + } + } +} + +/// Pure-Rust RFC 3339 timestamp syntax and range validator (`YYYY-MM-DDTHH:MM:SS(.frac)?(Z|[+-]HH:MM)`). +fn is_valid_rfc3339(s: &str) -> bool { + let bytes = s.as_bytes(); + if bytes.len() < 20 { + return false; + } + let date_ok = bytes[4] == b'-' + && bytes[7] == b'-' + && matches!(bytes[10], b'T' | b't' | b' ') + && bytes[13] == b':' + && bytes[16] == b':'; + if !date_ok { + return false; + } + let (Some(_year), Some(month), Some(day), Some(hour), Some(min), Some(sec)) = ( + parse_digits(&s[0..4]), + parse_digits(&s[5..7]), + parse_digits(&s[8..10]), + parse_digits(&s[11..13]), + parse_digits(&s[14..16]), + parse_digits(&s[17..19]), + ) else { + return false; + }; + if !(1..=12).contains(&month) || !(1..=31).contains(&day) || hour > 23 || min > 59 || sec > 60 { + return false; + } + let mut idx = 19; + if idx < bytes.len() && bytes[idx] == b'.' { + idx += 1; + let frac_start = idx; + while idx < bytes.len() && bytes[idx].is_ascii_digit() { + idx += 1; + } + if idx == frac_start { + return false; + } + } + let tz = &s[idx..]; + if tz == "Z" || tz == "z" { + return true; + } + let tz_bytes = tz.as_bytes(); + if tz_bytes.len() == 6 + && matches!(tz_bytes[0], b'+' | b'-') + && tz_bytes[3] == b':' + && let (Some(tz_h), Some(tz_m)) = (parse_digits(&tz[1..3]), parse_digits(&tz[4..6])) + { + return tz_h <= 23 && tz_m <= 59; + } + false +} + +fn parse_digits(s: &str) -> Option { + if s.is_empty() || !s.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + s.parse::().ok() +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::host::MemoryHostBridge; + + #[test] + fn ios_integer_and_fractional_cf_epoch_seconds_decode_explicitly_without_android_ambiguity() { + let mut host = MemoryHostBridge::new(HostKind::Native, "inst-ios"); + let mut auth = + AuthController::new("affine-cloud", "https://app.affine.pro", HostKind::Native); + + // Integer CF epoch seconds (Swift JSONEncoder emits `800000000` without `.0`). + let ios_int = r#"{"version":1,"tokenType":"Bearer","accessToken":"at-int","accessExpiresAt":800000000,"refreshToken":"rt-int","refreshExpiresAt":"2026-12-01T00:00:00Z","session":{"id":"s-int","absoluteExpiresAt":"2027-01-01T00:00:00Z"}}"#; + host.seed_credential(auth.credential_key(), ios_int); + assert!( + auth.load_stored_credentials(&mut host, NativeAuthPlatform::Ios) + .unwrap() + ); + assert_eq!( + auth.native_tokens().unwrap().access_expires_at_unix_ms(), + 1_778_307_200_000 + ); + + // Fractional CF epoch seconds `800000000.5` -> `1778307200500` ms. + let ios_frac = r#"{"version":1,"tokenType":"Bearer","accessToken":"at-frac","accessExpiresAt":800000000.5,"refreshToken":"rt-frac","refreshExpiresAt":"2026-12-01T00:00:00Z","session":{"id":"s-frac","absoluteExpiresAt":"2027-01-01T00:00:00Z"}}"#; + host.seed_credential(auth.credential_key(), ios_frac); + assert!( + auth.load_stored_credentials(&mut host, NativeAuthPlatform::Ios) + .unwrap() + ); + assert_eq!( + auth.native_tokens().unwrap().access_expires_at_unix_ms(), + 1_778_307_200_500 + ); + + // Android DataStore fixture (`1970` Unix ms) roundtrips cleanly with Android selector. + let android_json = r#"{"version":1,"tokenType":"Bearer","accessToken":"at-and","accessExpiresAt":1795622400000,"refreshToken":"rt-and","refreshExpiresAt":"2026-12-01T00:00:00Z","session":{"id":"s-and","absoluteExpiresAt":"2027-01-01T00:00:00Z"}}"#; + host.seed_credential(auth.credential_key(), android_json); + assert!( + auth.load_stored_credentials(&mut host, NativeAuthPlatform::Android) + .unwrap() + ); + assert_eq!( + auth.native_tokens().unwrap().access_expires_at_unix_ms(), + 1_795_622_400_000 + ); + } + + #[test] + fn deleted_host_credential_clears_stale_jwt_and_from_wire_validates_fields() { + let mut host = MemoryHostBridge::new(HostKind::Native, "inst-1"); + let mut auth = + AuthController::new("affine-cloud", "https://app.affine.pro", HostKind::Native); + + let valid_wire = AuthTokenPairResponse { + token_type: Some("Bearer".into()), + access_token: "at-1".into(), + refresh_token: "rt-1".into(), + expires_in: Some(3600), + refresh_expires_at: Some("2026-12-01T00:00:00Z".into()), + session: Some(AuthSessionMeta { + id: "sess-1".into(), + absolute_expires_at: Some("2027-01-01T00:00:00Z".into()), + }), + session_id: None, + }; + let pair = StoredAuthTokenPair::from_wire(valid_wire.clone(), 1_700_000_000_000).unwrap(); + auth.apply_native_tokens(pair); + assert_eq!( + auth.socket_auth_mode(), + SocketAuthMode::NativeJwt { + token: "at-1".into() + } + ); + + // Host vault has no credential (deleted by host coordinator) -> clears in-memory JWT. + assert!( + !auth + .load_stored_credentials(&mut host, NativeAuthPlatform::Android) + .unwrap() + ); + assert_eq!(auth.socket_auth_mode(), SocketAuthMode::Unauthenticated); + assert_eq!(auth.state(), &AuthSessionState::SignedOut); + + // `from_wire` rejects non-Bearer, zero expiresIn, and malformed RFC3339 timestamps. + let mut bad_type = valid_wire.clone(); + bad_type.token_type = Some("Basic".into()); + assert!(StoredAuthTokenPair::from_wire(bad_type, 1_000).is_err()); + + let mut zero_exp = valid_wire.clone(); + zero_exp.expires_in = Some(0); + assert!(StoredAuthTokenPair::from_wire(zero_exp, 1_000).is_err()); + + let mut bad_refresh_ts = valid_wire.clone(); + bad_refresh_ts.refresh_expires_at = Some("not-a-date".into()); + assert!(StoredAuthTokenPair::from_wire(bad_refresh_ts, 1_000).is_err()); + + let mut bad_abs_ts = valid_wire; + bad_abs_ts.session.as_mut().unwrap().absolute_expires_at = Some("2027-99-99".into()); + assert!(StoredAuthTokenPair::from_wire(bad_abs_ts, 1_000).is_err()); + + // Sans-I/O session response: 503/429 preserves cached user; 401/403 signs out. + auth.set_cached_user(AuthSessionUser { + id: "u1".into(), + email: None, + name: Some("Alice".into()), + avatar_url: None, + }); + let req = auth.build_session_request(); + assert_eq!(req.path, "/api/auth/session"); + assert!(auth.apply_session_response(503, b"unavailable").is_err()); + assert!(matches!( + auth.state(), + AuthSessionState::Authenticated { .. } + )); + assert_eq!( + auth.apply_session_response(401, b"{}").unwrap(), + AuthSessionState::SignedOut + ); + } +} diff --git a/packages/frontend/client/src/bootstrap.rs b/packages/frontend/client/src/bootstrap.rs new file mode 100644 index 0000000000..c3b6470ff0 --- /dev/null +++ b/packages/frontend/client/src/bootstrap.rs @@ -0,0 +1,116 @@ +//! Startup bootstrap gate consuming `affine_legacy_import::import_from_sentinel`. +//! +//! Ensures fresh-workspace initialization runs ONLY when the legacy WebView sentinel is verified +//! healthy with zero allowlisted AFFiNE keys, and blocks initialization when the WebView is +//! unready or reports an unexpected origin. + +use affine_legacy_import::{ + LegacyImportError, LegacyLocalStorageSnapshot, SentinelEvaluation, SentinelFailureReason, + WebViewStorageSentinel, import_from_sentinel, +}; + +/// Outcome of evaluating the legacy WebView sentinel at app startup. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum BootstrapDecision { + /// Verified fresh install (zero allowlisted AFFiNE keys): safe to initialize default workspace. + InitializeFreshWorkspace, + /// Verified existing user state imported from allowlisted keys (even if workspace list is `"[]"`). + RestoreExisting(LegacyLocalStorageSnapshot), + /// WebView was unready, origin mismatched, or critical workspace list was corrupt: + /// MUST NOT initialize a default workspace or scan `*.db` files. + BlockOnUnreadyWebView(String), +} + +/// Startup bootstrap gate enforcing legacy upgrade safety invariants (`F1`). +#[derive(Clone, Debug)] +pub struct WorkspaceBootstrapGate { + allowed_origins: Vec, +} + +impl WorkspaceBootstrapGate { + pub fn new(allowed_origins: impl IntoIterator>) -> Self { + Self { + allowed_origins: allowed_origins.into_iter().map(Into::into).collect(), + } + } + + /// Evaluate a captured [`WebViewStorageSentinel`] and decide whether to initialize a fresh + /// workspace, restore imported legacy state, or block startup recovery. + pub fn evaluate(&self, sentinel: &WebViewStorageSentinel) -> BootstrapDecision { + let refs: Vec<&str> = self.allowed_origins.iter().map(String::as_str).collect(); + match import_from_sentinel(sentinel, &refs) { + Ok((eval, snapshot)) => { + if eval.should_initialize_fresh_workspace() { + BootstrapDecision::InitializeFreshWorkspace + } else { + debug_assert!(matches!( + eval, + SentinelEvaluation::ValidPopulated { + has_allowlisted_keys: true + } + )); + BootstrapDecision::RestoreExisting(snapshot) + } + } + Err(LegacyImportError::SentinelFailed(reason)) => { + BootstrapDecision::BlockOnUnreadyWebView(format_reason(&reason)) + } + Err(other) => BootstrapDecision::BlockOnUnreadyWebView(other.to_string()), + } + } +} + +fn format_reason(reason: &SentinelFailureReason) -> String { + format!("{reason:?}") +} + +#[cfg(test)] +mod tests { + use std::collections::BTreeMap; + + use super::*; + + #[test] + fn bootstrap_gate_routes_fresh_existing_empty_and_unready_sentinels() { + let gate = WorkspaceBootstrapGate::new(["capacitor://localhost", "https://localhost"]); + + // 1. Fresh install -> InitializeFreshWorkspace. + let fresh = WebViewStorageSentinel { + origin: "capacitor://localhost".into(), + length: 0, + keys: vec![], + entries: BTreeMap::new(), + }; + assert_eq!( + gate.evaluate(&fresh), + BootstrapDecision::InitializeFreshWorkspace + ); + + // 2. Existing user with empty workspace list -> RestoreExisting (never re-init default). + let deleted_all = WebViewStorageSentinel { + origin: "capacitor://localhost".into(), + length: 1, + keys: vec!["affine-local-workspace".into()], + entries: BTreeMap::from([("affine-local-workspace".into(), "[]".into())]), + }; + match gate.evaluate(&deleted_all) { + BootstrapDecision::RestoreExisting(snap) => { + assert!(snap.has_local_workspace_key); + assert!(snap.local_workspace_ids.is_empty()); + } + other => panic!("expected RestoreExisting, got {other:?}"), + } + + // 3. Unready WebView / wrong origin -> BlockOnUnreadyWebView. + let unready = WebViewStorageSentinel { + origin: "about:blank".into(), + length: 0, + keys: vec![], + entries: BTreeMap::new(), + }; + assert!(matches!( + gate.evaluate(&unready), + BootstrapDecision::BlockOnUnreadyWebView(_) + )); + } +} diff --git a/packages/frontend/client/src/doc_directory.rs b/packages/frontend/client/src/doc_directory.rs new file mode 100644 index 0000000000..40bbb0953c --- /dev/null +++ b/packages/frontend/client/src/doc_directory.rs @@ -0,0 +1,585 @@ +//! Production [`blocksuite_editor::WorkspaceDocDirectory`] backed by a shared +//! `Arc>` (Single Root Writer). +//! +//! Enforces all four-reviewer locked invariants: +//! 1. Persists `root_registered = true` immediately upon root doc write success (decoupled from +//! child page skeleton initialization). +//! 2. Replaying an `intent_id` whose root-registered document was deleted from `meta.pages` +//! always returns `Err(DirectoryError::NotFound)` and never revives the deleted document (`F1`). +//! 3. Persists unfinished create intents across session restarts (`export_recovery_state` / +//! `import_recovery_state`) and retires them idempotently once confirmed. +//! 4. Ephemeral (`intent_id: None`) creations use a 128-bit CSPRNG replica seed (`getrandom`) +//! + existence guard so offline replicas across processes never collide on `"ephemeral-1"`. + +use std::{ + collections::BTreeMap, + sync::{Arc, Mutex, MutexGuard}, +}; + +use affine_store::{ + directory::{CreateDocId, CreateDocRequest, DocId, DocMode, DocQuery, WorkspaceDirectory}, + workspace_db::{PendingDocUpdate, derive_page_id_for_op}, +}; +use blocksuite_editor::{ + DirectoryError, DocQueryPage, DocQueryRequest, EditorDocId, EditorDocMode, EditorDocSummary, + MatchedDocSummary, WorkspaceDocDirectory, match_exact_substring_utf16, +}; +use serde::{Deserialize, Serialize}; + +fn generate_replica_seed_hex() -> Result { + let mut bytes = [0u8; 16]; + getrandom::fill(&mut bytes) + .map_err(|err| DirectoryError::Other(format!("CSPRNG failure: {err}")))?; + let mut out = String::with_capacity(32); + for b in bytes { + use std::fmt::Write as _; + let _ = write!(&mut out, "{b:02x}"); + } + Ok(out) +} + +/// Persisted state for a single linked-document creation intent. +#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CreateIntentEntry { + pub doc_id: String, + pub mode: String, + /// `true` immediately after `WorkspaceDb` writes `meta.pages` + `spaces[pageId]`. + pub root_registered: bool, + /// `true` once the caller inserted the source reference chip for this intent. + pub source_linked: bool, + /// `true` once the child page skeleton initialization has been confirmed. + pub skeleton_initialized: bool, +} + +/// Workspace-bound serializable create-intent ledger surviving restarts. +#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CreateIntentLedger { + pub space_id: String, + pub intents: BTreeMap, +} + +/// Production [`WorkspaceDocDirectory`] backed by a shared [`WorkspaceDirectory`] and [`CreateIntentLedger`]. +pub struct StoreBackedDocDirectory { + directory: Arc>, + ledger: CreateIntentLedger, + now_ms: i64, + replica_seed: Option, + next_ephemeral_op: u64, +} + +impl StoreBackedDocDirectory { + /// Wrap a newly owned [`WorkspaceDirectory`] in a shared single-root-writer handle. + pub fn new(directory: WorkspaceDirectory, initial_now_ms: i64) -> Self { + Self::from_shared(Arc::new(Mutex::new(directory)), initial_now_ms) + } + + /// Attach to an existing shared [`WorkspaceDirectory`] (e.g. shared with [`crate::WorkspaceDomainService`]). + pub fn from_shared(directory: Arc>, initial_now_ms: i64) -> Self { + let space_id = directory + .lock() + .unwrap_or_else(|e| e.into_inner()) + .db() + .space_id() + .to_string(); + let replica_seed = generate_replica_seed_hex().ok(); + Self { + directory, + ledger: CreateIntentLedger { + space_id, + intents: BTreeMap::new(), + }, + now_ms: initial_now_ms, + replica_seed, + next_ephemeral_op: 0, + } + } + + pub fn shared_directory(&self) -> Arc> { + Arc::clone(&self.directory) + } + + pub fn lock_directory(&self) -> MutexGuard<'_, WorkspaceDirectory> { + self.directory.lock().unwrap_or_else(|e| e.into_inner()) + } + + pub fn set_now_ms(&mut self, now_ms: i64) { + self.now_ms = now_ms; + } + + pub fn ledger(&self) -> &CreateIntentLedger { + &self.ledger + } + + pub fn drain_pending_updates(&mut self) -> Vec { + self.lock_directory().drain_pending_updates() + } + + /// Export both the create-intent ledger and `WorkspaceDirectory`'s `ExplicitCreateJournal`. + pub fn export_recovery_state(&self) -> Result<(Vec, Vec), DirectoryError> { + let ledger_bytes = + serde_json::to_vec(&self.ledger).map_err(|e| DirectoryError::Other(e.to_string()))?; + let journal_bytes = self + .lock_directory() + .export_explicit_create_journal() + .map_err(|e| DirectoryError::Other(e.to_string()))?; + Ok((ledger_bytes, journal_bytes)) + } + + /// Restore persisted create-intent ledger and `ExplicitCreateJournal` after a restart. + pub fn import_recovery_state( + &mut self, + ledger_bytes: &[u8], + journal_bytes: &[u8], + ) -> Result<(), DirectoryError> { + let restored: CreateIntentLedger = serde_json::from_slice(ledger_bytes) + .map_err(|e| DirectoryError::Other(e.to_string()))?; + let mut dir = self.lock_directory(); + if restored.space_id != dir.db().space_id() { + return Err(DirectoryError::Other(format!( + "intent ledger space_id {:?} does not match workspace {:?}", + restored.space_id, + dir.db().space_id() + ))); + } + dir.import_explicit_create_journal(journal_bytes) + .map_err(|e| DirectoryError::Other(e.to_string()))?; + drop(dir); + self.ledger.intents.extend(restored.intents); + Ok(()) + } + + /// Record that the child page skeleton has finished initializing, and idempotently retire + /// the intent from the unfinished-create journal once confirmed. + pub fn confirm_child_skeleton_and_retire(&mut self, intent_id: &str) -> bool { + let Some(entry) = self.ledger.intents.get_mut(intent_id) else { + return false; + }; + entry.skeleton_initialized = true; + if let Ok(doc_id) = DocId::new(entry.doc_id.clone()) { + self.lock_directory().acknowledge_explicit_create(&doc_id); + } + true + } + + /// Return all intents whose child page skeleton has not yet been confirmed (for crash replay). + pub fn unfinished_intents(&self) -> Vec<(&str, &CreateIntentEntry)> { + self.ledger + .intents + .iter() + .filter(|(_, entry)| !entry.skeleton_initialized) + .map(|(k, v)| (k.as_str(), v)) + .collect() + } + + fn next_unique_ephemeral_create_id( + &mut self, + dir: &WorkspaceDirectory, + ) -> Result { + let space_id = dir.db().space_id(); + let seed = match &self.replica_seed { + Some(s) => s.clone(), + None => { + let fresh = generate_replica_seed_hex()?; + self.replica_seed = Some(fresh.clone()); + fresh + } + }; + + loop { + self.next_ephemeral_op = self.next_ephemeral_op.saturating_add(1); + let op_key = format!("ephemeral-{seed}-{}", self.next_ephemeral_op); + let candidate_id = derive_page_id_for_op(space_id, &op_key); + let doc_id = + DocId::new(&candidate_id).map_err(|e| DirectoryError::Other(e.to_string()))?; + let exists = dir + .get_doc(&doc_id) + .map_err(|e| DirectoryError::Other(e.to_string()))? + .is_some(); + if !exists { + return CreateDocId::from_op(op_key) + .map_err(|e| DirectoryError::Other(e.to_string())); + } + } + } +} + +fn to_store_mode(mode: EditorDocMode) -> DocMode { + match mode { + EditorDocMode::Page => DocMode::Page, + EditorDocMode::Edgeless => DocMode::Edgeless, + } +} + +fn to_editor_mode(mode: DocMode) -> EditorDocMode { + match mode { + DocMode::Page => EditorDocMode::Page, + DocMode::Edgeless => EditorDocMode::Edgeless, + } +} + +impl WorkspaceDocDirectory for StoreBackedDocDirectory { + fn query_linked_docs(&self, req: &DocQueryRequest) -> Result { + if req.cancel.is_cancelled() { + return Ok(DocQueryPage { + items: Vec::new(), + next_cursor: None, + cancelled: true, + }); + } + let offset: usize = match &req.cursor { + None => 0, + Some(raw) => raw + .parse::() + .map_err(|_| DirectoryError::InvalidCursor(raw.clone()))?, + }; + + let store_page = self + .lock_directory() + .query_docs( + &DocQuery { + include_trashed: false, + ..DocQuery::default() + }, + None, + ) + .map_err(|e| DirectoryError::Other(e.to_string()))?; + + let mut matches = Vec::new(); + for entry in store_page.entries { + if req.cancel.is_cancelled() { + return Ok(DocQueryPage { + items: Vec::new(), + next_cursor: None, + cancelled: true, + }); + } + if let Some((score, title_highlights)) = + match_exact_substring_utf16(&entry.title, &req.query) + { + matches.push(MatchedDocSummary { + doc: EditorDocSummary { + id: EditorDocId::new(entry.id.as_str()), + title: entry.title, + mode: to_editor_mode(entry.mode), + updated_at_ms: entry.updated_date_ms.unwrap_or(entry.create_date_ms), + }, + score, + title_highlights, + }); + } + } + + matches.sort_by(|a, b| { + a.score + .total_cmp(&b.score) + .then_with(|| b.doc.updated_at_ms.cmp(&a.doc.updated_at_ms)) + .then_with(|| a.doc.id.cmp(&b.doc.id)) + }); + + let limit = req.limit.max(1); + let start = offset.min(matches.len()); + let end = (start + limit).min(matches.len()); + let next_cursor = (end < matches.len()).then(|| end.to_string()); + + Ok(DocQueryPage { + items: matches[start..end].to_vec(), + next_cursor, + cancelled: false, + }) + } + + fn rename_doc_title( + &mut self, + id: &EditorDocId, + title: &str, + ) -> Result { + let doc_id = DocId::new(id.as_str()).map_err(|e| DirectoryError::Other(e.to_string()))?; + let mut dir = self.lock_directory(); + let existing = dir + .get_doc(&doc_id) + .map_err(|e| DirectoryError::Other(e.to_string()))? + .ok_or_else(|| DirectoryError::NotFound(id.clone()))?; + dir.rename_doc(&doc_id, title) + .map_err(|e| DirectoryError::Other(e.to_string()))?; + Ok(EditorDocSummary { + id: id.clone(), + title: title.to_string(), + mode: to_editor_mode(existing.mode), + updated_at_ms: existing.updated_date_ms.unwrap_or(existing.create_date_ms), + }) + } + + fn create_linked_doc( + &mut self, + title: &str, + mode: EditorDocMode, + intent_id: Option<&str>, + ) -> Result { + let store_mode = to_store_mode(mode); + + // Invariant 2 (F1): if this intent was already root-registered and is now absent from + // `meta.pages`, it was deleted — return `Err(NotFound)` and NEVER revive it. + if let Some(intent) = intent_id + && let Some(rec) = self.ledger.intents.get(intent).cloned() + { + let dir = self.lock_directory(); + let doc_id = + DocId::new(&rec.doc_id).map_err(|e| DirectoryError::Other(e.to_string()))?; + if let Some(existing) = dir + .get_doc(&doc_id) + .map_err(|e| DirectoryError::Other(e.to_string()))? + { + return Ok(EditorDocSummary { + id: EditorDocId::new(existing.id.as_str()), + title: existing.title, + mode: to_editor_mode(existing.mode), + updated_at_ms: existing.updated_date_ms.unwrap_or(existing.create_date_ms), + }); + } + if rec.root_registered { + return Err(DirectoryError::NotFound(EditorDocId::new(rec.doc_id))); + } + } + + let created = { + let create_id = match intent_id { + Some(intent) => CreateDocId::from_op(intent) + .map_err(|e| DirectoryError::Other(e.to_string()))?, + None => { + let shared = Arc::clone(&self.directory); + let guard = shared.lock().unwrap_or_else(|e| e.into_inner()); + self.next_unique_ephemeral_create_id(&guard)? + } + }; + let mut dir = self.lock_directory(); + let outcome = dir + .create_doc(CreateDocRequest { + id: create_id, + title: title.to_string(), + mode: store_mode, + now_ms: self.now_ms, + }) + .map_err(|e| DirectoryError::Other(e.to_string()))?; + let summary = dir + .get_doc(&outcome.doc_id) + .map_err(|e| DirectoryError::Other(e.to_string()))? + .ok_or_else(|| { + DirectoryError::NotFound(EditorDocId::new(outcome.doc_id.as_str())) + })?; + (outcome, summary) + }; + + // Invariant 1: root write succeeded -> immediately persist `root_registered = true`. + if let Some(intent) = intent_id { + self.ledger + .intents + .entry(intent.to_string()) + .and_modify(|entry| { + entry.doc_id = created.0.doc_id.as_str().to_string(); + entry.root_registered = true; + }) + .or_insert_with(|| CreateIntentEntry { + doc_id: created.0.doc_id.as_str().to_string(), + mode: store_mode.as_str().to_string(), + root_registered: true, + source_linked: false, + skeleton_initialized: false, + }); + } + + Ok(EditorDocSummary { + id: EditorDocId::new(created.1.id.as_str()), + title: created.1.title, + mode: to_editor_mode(created.1.mode), + updated_at_ms: created + .1 + .updated_date_ms + .unwrap_or(created.1.create_date_ms), + }) + } + + fn has_create_intent(&self, intent_id: &str) -> bool { + self.ledger.intents.contains_key(intent_id) + } + + fn is_create_intent_linked(&self, intent_id: &str) -> bool { + self.ledger + .intents + .get(intent_id) + .is_some_and(|rec| rec.source_linked) + } + + fn mark_create_intent_linked(&mut self, intent_id: &str) { + if let Some(rec) = self.ledger.intents.get_mut(intent_id) { + rec.source_linked = true; + } + } + + fn mark_doc_root_registered(&mut self, id: &EditorDocId) { + for rec in self.ledger.intents.values_mut() { + if rec.doc_id == id.as_str() { + rec.root_registered = true; + } + } + } +} + +#[cfg(test)] +mod tests { + use affine_store::workspace_db::WorkspaceDb; + + use super::*; + + fn new_store_backed_directory() -> StoreBackedDocDirectory { + let mut db = WorkspaceDb::new("ws-s2", "u1", 1); + db.initialize_meta().unwrap(); + let _ = db.drain_pending_updates(); + StoreBackedDocDirectory::new(WorkspaceDirectory::new(db), 1_000) + } + + #[test] + fn closes_all_four_reviewer_directory_invariants_across_restart_and_delete() { + let mut dir = new_store_backed_directory(); + + let created = dir + .create_linked_doc("Architecture", EditorDocMode::Edgeless, Some("intent-1")) + .unwrap(); + assert_eq!(created.mode, EditorDocMode::Edgeless); + assert!(dir.ledger().intents["intent-1"].root_registered); + assert!(!dir.ledger().intents["intent-1"].skeleton_initialized); + assert_eq!(dir.unfinished_intents().len(), 1); + + let (root_snap, props_snap) = { + let guard = dir.lock_directory(); + ( + guard.db().root().encode_update_v1().unwrap(), + guard + .db() + .db_table(affine_store::workspace_db::WorkspaceDbTableName::DocProperties) + .unwrap() + .encode_update_v1() + .unwrap(), + ) + }; + let (ledger_bytes, journal_bytes) = dir.export_recovery_state().unwrap(); + + let mut recovered_db = + WorkspaceDb::from_root_update_v1("ws-s2", "u1", 2, &root_snap).unwrap(); + recovered_db + .load_db_table( + affine_store::workspace_db::WorkspaceDbTableName::DocProperties, + &props_snap, + ) + .unwrap(); + let mut recovered = + StoreBackedDocDirectory::new(WorkspaceDirectory::new(recovered_db), 2_000); + recovered + .import_recovery_state(&ledger_bytes, &journal_bytes) + .unwrap(); + assert_eq!(recovered.unfinished_intents().len(), 1); + let replayed = recovered + .create_linked_doc("Architecture", EditorDocMode::Edgeless, Some("intent-1")) + .unwrap(); + assert_eq!(replayed.id, created.id); + assert!(recovered.confirm_child_skeleton_and_retire("intent-1")); + assert!(recovered.unfinished_intents().is_empty()); + + let full = recovered + .lock_directory() + .db() + .root() + .encode_update_v1() + .unwrap(); + let mut peer = y_octo::DocOptions::from_identity(9, "ws-s2".to_string()).build(); + peer.apply_update_from_binary_v1(&full).unwrap(); + let sv = peer.get_state_vector(); + let meta = peer.get_or_create_map("meta").unwrap(); + let Some(y_octo::Value::Array(mut pages)) = meta.get("pages") else { + panic!("meta.pages missing"); + }; + pages.remove(0, 1).unwrap(); + let diff = peer.encode_state_as_update_v1(&sv).unwrap(); + recovered + .lock_directory() + .db_mut() + .apply_remote_root_update(&diff) + .unwrap(); + + let err = recovered + .create_linked_doc("Architecture", EditorDocMode::Edgeless, Some("intent-1")) + .expect_err("deleted doc must not revive on intent replay"); + assert_eq!(err, DirectoryError::NotFound(created.id)); + } + + #[test] + fn ephemeral_none_intents_across_independent_instances_produce_distinct_ids() { + let mut db = WorkspaceDb::new("ws-eph", "u1", 1); + db.initialize_meta().unwrap(); + let shared = Arc::new(Mutex::new(WorkspaceDirectory::new(db))); + + let mut inst_a = StoreBackedDocDirectory::from_shared(Arc::clone(&shared), 100); + let mut inst_b = StoreBackedDocDirectory::from_shared(Arc::clone(&shared), 200); + + let a = inst_a + .create_linked_doc("First", EditorDocMode::Page, None) + .unwrap(); + let b = inst_b + .create_linked_doc("Second", EditorDocMode::Page, None) + .unwrap(); + assert_ne!(a.id, b.id); + + // Explicit intent stays idempotent on the same instance. + let exp1 = inst_a + .create_linked_doc("Explicit", EditorDocMode::Page, Some("intent-x")) + .unwrap(); + let exp2 = inst_a + .create_linked_doc("Explicit", EditorDocMode::Page, Some("intent-x")) + .unwrap(); + assert_eq!(exp1.id, exp2.id); + } + + #[test] + fn offline_replicas_from_same_snapshot_generate_distinct_ids_and_merge_cleanly() { + let mut base = WorkspaceDb::new("ws-offline", "u1", 1); + base.initialize_meta().unwrap(); + let root_snap = base.root().encode_update_v1().unwrap(); + + let db_a = WorkspaceDb::from_root_update_v1("ws-offline", "u1", 10, &root_snap).unwrap(); + let db_b = WorkspaceDb::from_root_update_v1("ws-offline", "u2", 20, &root_snap).unwrap(); + let mut replica_a = StoreBackedDocDirectory::new(WorkspaceDirectory::new(db_a), 100); + let mut replica_b = StoreBackedDocDirectory::new(WorkspaceDirectory::new(db_b), 100); + + let page_a = replica_a + .create_linked_doc("Offline A", EditorDocMode::Page, None) + .unwrap(); + let page_b = replica_b + .create_linked_doc("Offline B", EditorDocMode::Page, None) + .unwrap(); + assert_ne!(page_a.id, page_b.id); + + for upd in replica_a + .drain_pending_updates() + .into_iter() + .chain(replica_b.drain_pending_updates()) + { + if upd.doc_id == "ws-offline" { + base.apply_remote_root_update(&upd.update).unwrap(); + } + } + let merged = WorkspaceDirectory::new(base); + assert!( + merged + .get_doc(&DocId::new(page_a.id.as_str()).unwrap()) + .unwrap() + .is_some() + ); + assert!( + merged + .get_doc(&DocId::new(page_b.id.as_str()).unwrap()) + .unwrap() + .is_some() + ); + } +} diff --git a/packages/frontend/client/src/domain.rs b/packages/frontend/client/src/domain.rs new file mode 100644 index 0000000000..a6004db931 --- /dev/null +++ b/packages/frontend/client/src/domain.rs @@ -0,0 +1,546 @@ +//! Core L3 workspace domain models and services (`Workspace`, `Doc`, `Folder`, `Collection`, +//! `Tag`, `Favorite`, `Journal`, `Trash`) backed by a shared `Arc>`. + +use std::{ + collections::BTreeMap, + sync::{Arc, Mutex, MutexGuard}, +}; + +use affine_store::{ + directory::{DocId, WorkspaceDirectory}, + workspace_db::{ + DocPropertiesRow, FavoriteRow, FolderRow, UserdataTableName, WorkspaceDbTableName, + }, +}; +use serde::{Deserialize, Serialize}; + +use crate::{ClientError, ClientResult}; + +/// High-level workspace identity and sync flavour. +#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct WorkspaceModel { + pub id: String, + pub name: String, + pub flavour: String, + pub is_cloud: bool, +} + +/// Projected document summary in the L3 client domain. +#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct DocModel { + pub id: String, + pub title: String, + pub mode: String, + pub create_date_ms: i64, + pub updated_date_ms: Option, + pub trashed: bool, + pub tags: Vec, + pub journal_date: Option, + pub is_favorite: bool, +} + +/// Tree node in the workspace folder hierarchy (`db$folders`). +#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct FolderNode { + pub id: String, + pub parent_id: Option, + pub node_type: String, + pub data: String, + pub index: String, +} + +/// Smart collection filter rule. +#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum CollectionRule { + HasTag(String), + ModeIs(String), + TitleContains(String), + IncludeDocIds(Vec), +} + +/// User-defined collection grouping documents by explicit IDs and filter rules. +#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CollectionModel { + pub id: String, + pub name: String, + pub rules: Vec, +} + +/// Tag descriptor with document count. +#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct TagModel { + pub id: String, + pub name: String, + pub color: String, + pub doc_count: usize, +} + +/// Pinned favorite entry (`userdata$$favorite`). +#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct FavoriteItem { + pub key: String, + pub index: String, +} + +/// Daily journal entry keyed by `YYYY-MM-DD`. +#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct JournalEntry { + pub date: String, + pub doc_id: String, + pub title: String, +} + +/// Soft-deleted document in workspace Trash. +#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct TrashItem { + pub doc_id: String, + pub title: String, + pub trashed_at_ms: Option, +} + +/// L3 domain service projecting and mutating workspace entities over a shared [`WorkspaceDirectory`]. +pub struct WorkspaceDomainService { + directory: Arc>, + collections: BTreeMap, + tag_palette: BTreeMap, +} + +impl WorkspaceDomainService { + /// Wrap a newly owned [`WorkspaceDirectory`] in a shared single-root-writer handle. + pub fn new(directory: WorkspaceDirectory) -> Self { + Self::from_shared(Arc::new(Mutex::new(directory))) + } + + /// Attach to an existing shared [`WorkspaceDirectory`] (shared with [`crate::StoreBackedDocDirectory`]). + pub fn from_shared(directory: Arc>) -> Self { + Self { + directory, + collections: BTreeMap::new(), + tag_palette: BTreeMap::new(), + } + } + + pub fn shared_directory(&self) -> Arc> { + Arc::clone(&self.directory) + } + + pub fn lock_directory(&self) -> MutexGuard<'_, WorkspaceDirectory> { + self.directory.lock().unwrap_or_else(|e| e.into_inner()) + } + + pub fn register_tag_meta( + &mut self, + id: impl Into, + name: impl Into, + color: impl Into, + ) { + self.tag_palette + .insert(id.into(), (name.into(), color.into())); + } + + pub fn upsert_collection(&mut self, collection: CollectionModel) { + self.collections.insert(collection.id.clone(), collection); + } + + /// List all non-trashed documents enriched with `journal` and `favorite` metadata. + pub fn list_docs(&self) -> ClientResult> { + let fav_keys = self.favorite_keys()?; + let dir = self.lock_directory(); + let props_table = dir.db().db_table(WorkspaceDbTableName::DocProperties); + let page = dir.query_docs( + &affine_store::directory::DocQuery { + include_trashed: false, + ..Default::default() + }, + None, + )?; + + let mut docs = Vec::with_capacity(page.entries.len()); + for entry in page.entries { + let journal_date = props_table + .and_then(|t| t.get_row::(entry.id.as_str()).ok()) + .flatten() + .and_then(|r| r.journal); + let fav_key = format!("doc:{}", entry.id.as_str()); + docs.push(DocModel { + id: entry.id.as_str().to_string(), + title: entry.title, + mode: entry.mode.as_str().to_string(), + create_date_ms: entry.create_date_ms, + updated_date_ms: entry.updated_date_ms, + trashed: entry.trashed, + tags: entry.tags, + journal_date, + is_favorite: fav_keys.contains(&fav_key), + }); + } + Ok(docs) + } + + /// List soft-deleted documents in Trash. + pub fn list_trash(&self) -> ClientResult> { + let page = self.lock_directory().query_docs( + &affine_store::directory::DocQuery { + include_trashed: true, + ..Default::default() + }, + None, + )?; + Ok(page + .entries + .into_iter() + .filter(|e| e.trashed) + .map(|e| TrashItem { + doc_id: e.id.as_str().to_string(), + title: e.title, + trashed_at_ms: e.updated_date_ms, + }) + .collect()) + } + + /// List daily journal entries ordered by date (`YYYY-MM-DD`). + pub fn list_journals(&self) -> ClientResult> { + let mut journals: Vec = self + .list_docs()? + .into_iter() + .filter_map(|doc| { + doc.journal_date.map(|date| JournalEntry { + date, + doc_id: doc.id, + title: doc.title, + }) + }) + .collect(); + journals.sort_by(|a, b| a.date.cmp(&b.date).then_with(|| a.doc_id.cmp(&b.doc_id))); + Ok(journals) + } + + /// Aggregate tags across active documents. + pub fn list_tags(&self) -> ClientResult> { + let mut counts: BTreeMap = BTreeMap::new(); + for doc in self.list_docs()? { + for tag in doc.tags { + *counts.entry(tag).or_insert(0) += 1; + } + } + for id in self.tag_palette.keys() { + counts.entry(id.clone()).or_insert(0); + } + Ok(counts + .into_iter() + .map(|(id, doc_count)| { + let (name, color) = self + .tag_palette + .get(&id) + .cloned() + .unwrap_or_else(|| (id.clone(), "default".to_string())); + TagModel { + id, + name, + color, + doc_count, + } + }) + .collect()) + } + + /// Evaluate a collection's rules against active documents. + pub fn evaluate_collection(&self, collection_id: &str) -> ClientResult> { + let Some(col) = self.collections.get(collection_id) else { + return Ok(Vec::new()); + }; + let docs = self.list_docs()?; + Ok(docs + .into_iter() + .filter(|doc| matches_collection(doc, &col.rules)) + .collect()) + } + + /// Upsert a folder node in `db$folders`. + pub fn upsert_folder(&mut self, node: FolderNode) -> ClientResult<()> { + self.lock_directory().db_mut().upsert_db_row( + WorkspaceDbTableName::Folders, + &FolderRow { + id: node.id, + parent_id: node.parent_id, + data: node.data, + folder_type: node.node_type, + index: node.index, + }, + )?; + Ok(()) + } + + /// List all folder nodes from `db$folders` sorted by `(parent_id, index, id)`. + pub fn list_folders(&self) -> ClientResult> { + let dir = self.lock_directory(); + let Some(table) = dir.db().db_table(WorkspaceDbTableName::Folders) else { + return Ok(Vec::new()); + }; + let mut rows: Vec = table + .list_rows::()? + .into_iter() + .map(|r| FolderNode { + id: r.id, + parent_id: r.parent_id, + node_type: r.folder_type, + data: r.data, + index: r.index, + }) + .collect(); + rows.sort_by(|a, b| { + a.parent_id + .cmp(&b.parent_id) + .then_with(|| a.index.cmp(&b.index)) + .then_with(|| a.id.cmp(&b.id)) + }); + Ok(rows) + } + + /// Pin a favorite item in `userdata$$favorite`. + pub fn add_favorite( + &mut self, + key: impl Into, + index: impl Into, + ) -> ClientResult<()> { + self.lock_directory().db_mut().upsert_userdata_row( + UserdataTableName::Favorite, + &FavoriteRow { + key: key.into(), + index: index.into(), + }, + )?; + Ok(()) + } + + /// List favorites from `userdata$$favorite` ordered by fractional index. + pub fn list_favorites(&self) -> ClientResult> { + let dir = self.lock_directory(); + let Some(table) = dir.db().userdata_table(UserdataTableName::Favorite) else { + return Ok(Vec::new()); + }; + let mut items: Vec = table + .list_rows::()? + .into_iter() + .map(|r| FavoriteItem { + key: r.key, + index: r.index, + }) + .collect(); + items.sort_by(|a, b| a.index.cmp(&b.index).then_with(|| a.key.cmp(&b.key))); + Ok(items) + } + + /// Mark an existing non-trashed document as a daily journal entry for `date` (`YYYY-MM-DD`). + /// + /// Rejects missing/trashed documents, unresolved `db$docProperties`, and tombstoned rows, and + /// preserves all existing `DocPropertiesRow` fields (including `primaryMode = edgeless` and + /// custom fields). + pub fn set_journal_date(&mut self, doc_id: &DocId, date: &str) -> ClientResult<()> { + let mut dir = self.lock_directory(); + let entry = dir + .get_doc(doc_id)? + .filter(|e| !e.trashed) + .ok_or_else(|| ClientError::DocNotFound(doc_id.as_str().to_string()))?; + + if !dir + .db() + .is_db_table_resolved(WorkspaceDbTableName::DocProperties) + { + return Err(ClientError::TableNotLoaded( + WorkspaceDbTableName::DocProperties.local_doc_id(), + )); + } + + let existing_row = + if let Some(table) = dir.db().db_table(WorkspaceDbTableName::DocProperties) { + if table.is_soft_deleted(doc_id.as_str())? { + return Err(ClientError::RowTombstoned(doc_id.as_str().to_string())); + } + table.get_row::(doc_id.as_str())? + } else { + None + }; + + let mut row = existing_row.unwrap_or_else(|| DocPropertiesRow { + id: doc_id.as_str().to_string(), + primary_mode: Some(entry.mode.as_str().to_string()), + edgeless_color_theme: None, + journal: None, + page_width: None, + is_template: None, + integration_type: None, + created_by: None, + updated_by: None, + custom_fields: BTreeMap::new(), + }); + row.journal = Some(date.to_string()); + dir.db_mut() + .upsert_db_row(WorkspaceDbTableName::DocProperties, &row)?; + Ok(()) + } + + fn favorite_keys(&self) -> ClientResult> { + Ok(self.list_favorites()?.into_iter().map(|f| f.key).collect()) + } +} + +fn matches_collection(doc: &DocModel, rules: &[CollectionRule]) -> bool { + if rules.is_empty() { + return true; + } + rules.iter().all(|rule| match rule { + CollectionRule::HasTag(tag) => doc.tags.iter().any(|t| t == tag), + CollectionRule::ModeIs(mode) => doc.mode == *mode, + CollectionRule::TitleContains(needle) => { + doc.title.to_lowercase().contains(&needle.to_lowercase()) + } + CollectionRule::IncludeDocIds(ids) => ids.iter().any(|id| id == &doc.id), + }) +} + +#[cfg(test)] +mod tests { + use affine_store::{ + directory::{CreateDocId, CreateDocRequest, DocMode}, + workspace_db::WorkspaceDb, + }; + use blocksuite_editor::{EditorDocMode, WorkspaceDocDirectory}; + + use super::*; + use crate::doc_directory::StoreBackedDocDirectory; + + #[test] + fn domain_service_projects_docs_folders_collections_favorites_journals_and_trash() { + let mut db = WorkspaceDb::new("ws-dom", "u1", 1); + db.initialize_meta().unwrap(); + let mut svc = WorkspaceDomainService::new(WorkspaceDirectory::new(db)); + + let d1 = svc + .lock_directory() + .create_doc(CreateDocRequest { + id: CreateDocId::from_op("op-1").unwrap(), + title: "Daily Standup".into(), + mode: DocMode::Edgeless, + now_ms: 100, + }) + .unwrap() + .doc_id; + let d2 = svc + .lock_directory() + .create_doc(CreateDocRequest { + id: CreateDocId::from_op("op-2").unwrap(), + title: "Trash Candidate".into(), + mode: DocMode::Page, + now_ms: 200, + }) + .unwrap() + .doc_id; + + // Seed existing Edgeless DocProperties fields before calling set_journal_date. + svc.lock_directory() + .db_mut() + .upsert_db_row( + WorkspaceDbTableName::DocProperties, + &DocPropertiesRow { + id: d1.as_str().to_string(), + primary_mode: Some("edgeless".into()), + edgeless_color_theme: Some("dark".into()), + journal: None, + page_width: Some("fullWidth".into()), + is_template: Some(true), + integration_type: None, + created_by: Some("u1".into()), + updated_by: Some("u1".into()), + custom_fields: BTreeMap::from([( + "custom:priority".into(), + serde_json::json!("high"), + )]), + }, + ) + .unwrap(); + svc.set_journal_date(&d1, "2026-11-25").unwrap(); + let preserved = svc + .lock_directory() + .db() + .db_table(WorkspaceDbTableName::DocProperties) + .unwrap() + .get_row::(d1.as_str()) + .unwrap() + .unwrap(); + assert_eq!(preserved.primary_mode.as_deref(), Some("edgeless")); + assert_eq!(preserved.journal.as_deref(), Some("2026-11-25")); + assert_eq!(preserved.page_width.as_deref(), Some("fullWidth")); + assert_eq!( + preserved.custom_fields.get("custom:priority"), + Some(&serde_json::json!("high")) + ); + + // Tombstoned DocProperties row MUST NOT be revived by set_journal_date. + svc.lock_directory() + .db_mut() + .soft_delete_db_row(WorkspaceDbTableName::DocProperties, d1.as_str()) + .unwrap(); + assert_eq!( + svc.set_journal_date(&d1, "2026-11-26"), + Err(ClientError::RowTombstoned(d1.as_str().to_string())) + ); + + // Unloaded DocProperties table MUST return TableNotLoaded instead of writing default Page. + let root_snap = svc.lock_directory().db().root().encode_update_v1().unwrap(); + let unloaded_db = WorkspaceDb::from_root_update_v1("ws-dom", "u1", 2, &root_snap).unwrap(); + let mut unloaded_svc = WorkspaceDomainService::new(WorkspaceDirectory::new(unloaded_db)); + assert_eq!( + unloaded_svc.set_journal_date(&d1, "2026-11-25"), + Err(ClientError::TableNotLoaded("db$docProperties".into())) + ); + + svc.add_favorite(format!("doc:{}", d1.as_str()), "a0") + .unwrap(); + svc.upsert_folder(FolderNode { + id: "f-1".into(), + parent_id: None, + node_type: "folder".into(), + data: "Projects".into(), + index: "a0".into(), + }) + .unwrap(); + svc.upsert_collection(CollectionModel { + id: "col-1".into(), + name: "Standups".into(), + rules: vec![CollectionRule::TitleContains("standup".into())], + }); + svc.lock_directory().trash_doc(&d2, 300).unwrap(); + + assert_eq!(svc.list_trash().unwrap().len(), 1); + assert_eq!(svc.list_folders().unwrap().len(), 1); + assert_eq!(svc.evaluate_collection("col-1").unwrap().len(), 1); + } + + #[test] + fn shared_single_root_writer_exposes_linked_doc_immediately_in_domain_service() { + let mut db = WorkspaceDb::new("ws-shared", "u1", 1); + db.initialize_meta().unwrap(); + let shared = Arc::new(Mutex::new(WorkspaceDirectory::new(db))); + + let mut editor_dir = StoreBackedDocDirectory::from_shared(Arc::clone(&shared), 500); + let domain_svc = WorkspaceDomainService::from_shared(Arc::clone(&shared)); + + let created = editor_dir + .create_linked_doc("Shared Note", EditorDocMode::Page, Some("intent-shared")) + .unwrap(); + let docs = domain_svc.list_docs().unwrap(); + assert_eq!(docs.len(), 1); + assert_eq!(docs[0].id, created.id.as_str()); + assert_eq!(docs[0].title, "Shared Note"); + } +} diff --git a/packages/frontend/client/src/host.rs b/packages/frontend/client/src/host.rs new file mode 100644 index 0000000000..8594069659 --- /dev/null +++ b/packages/frontend/client/src/host.rs @@ -0,0 +1,145 @@ +//! Host boundary port (`HostBridge`) decoupling L3 domain logic from platform shells. +//! +//! Native auth I/O (`exchange`/`refresh`/`revoke` and Keychain/Keystore writes) is owned +//! exclusively by the platform host (`hosts/ios` `LegacyAuthBridge` / `hosts/android` +//! `AuthSessionStore`). `HostBridge` therefore exposes only read/delete credential access, +//! WebSocket handles, installation ID, local KV, and accessibility announcements. + +use std::collections::BTreeMap; + +use serde::{Deserialize, Serialize}; + +use crate::ClientResult; + +/// Host runtime class governing security and transport policies (such as `F3` and auth mode). +#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum HostKind { + /// Browser / Web Mobile host (same-origin cookies/CSRF, no cross-origin self-hosted add). + Web, + /// Native iOS / Android / Desktop host (Bearer JWT, self-hosted server registry allowed). + Native, +} + +/// Opaque handle to a host-managed WebSocket connection. +#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)] +pub struct WsHandle(pub u64); + +/// Device-neutral host port implemented by Web, iOS, Android, and Desktop shells. +pub trait HostBridge { + fn host_kind(&self) -> HostKind; + + fn ws_connect(&mut self, url: &str, headers: &[(String, String)]) -> ClientResult; + + fn ws_send(&mut self, handle: WsHandle, text: &str) -> ClientResult<()>; + + fn ws_close(&mut self, handle: WsHandle) -> ClientResult<()>; + + fn read_credential(&self, key: &str) -> ClientResult>; + + fn delete_credential(&mut self, key: &str) -> ClientResult<()>; + + fn installation_id(&self) -> String; + + fn kv_get(&self, key: &str) -> Option; + + fn kv_set(&mut self, key: &str, value: &str); + + fn kv_remove(&mut self, key: &str); + + fn announce_accessibility(&mut self, message: &str); +} + +/// Deterministic in-memory [`HostBridge`] for unit tests and headless simulations. +#[derive(Clone, Debug)] +pub struct MemoryHostBridge { + host_kind: HostKind, + installation_id: String, + credentials: BTreeMap, + kv: BTreeMap, + announcements: Vec, + next_ws: u64, + ws_messages: BTreeMap>, +} + +impl MemoryHostBridge { + pub fn new(host_kind: HostKind, installation_id: impl Into) -> Self { + Self { + host_kind, + installation_id: installation_id.into(), + credentials: BTreeMap::new(), + kv: BTreeMap::new(), + announcements: Vec::new(), + next_ws: 1, + ws_messages: BTreeMap::new(), + } + } + + /// Seed a credential entry in the simulated host vault (simulating host-owned persistence). + pub fn seed_credential(&mut self, key: impl Into, secret: impl Into) { + self.credentials.insert(key.into(), secret.into()); + } + + pub fn announcements(&self) -> &[String] { + &self.announcements + } + + pub fn ws_sent(&self, handle: WsHandle) -> Option<&[String]> { + self.ws_messages.get(&handle).map(Vec::as_slice) + } +} + +impl HostBridge for MemoryHostBridge { + fn host_kind(&self) -> HostKind { + self.host_kind + } + + fn ws_connect(&mut self, _url: &str, _headers: &[(String, String)]) -> ClientResult { + let handle = WsHandle(self.next_ws); + self.next_ws = self.next_ws.saturating_add(1); + self.ws_messages.insert(handle, Vec::new()); + Ok(handle) + } + + fn ws_send(&mut self, handle: WsHandle, text: &str) -> ClientResult<()> { + self.ws_messages + .entry(handle) + .or_default() + .push(text.to_string()); + Ok(()) + } + + fn ws_close(&mut self, handle: WsHandle) -> ClientResult<()> { + self.ws_messages.remove(&handle); + Ok(()) + } + + fn read_credential(&self, key: &str) -> ClientResult> { + Ok(self.credentials.get(key).cloned()) + } + + fn delete_credential(&mut self, key: &str) -> ClientResult<()> { + self.credentials.remove(key); + Ok(()) + } + + fn installation_id(&self) -> String { + self.installation_id.clone() + } + + fn kv_get(&self, key: &str) -> Option { + self.kv.get(key).cloned() + } + + fn kv_set(&mut self, key: &str, value: &str) { + self.kv.insert(key.to_string(), value.to_string()); + } + + fn kv_remove(&mut self, key: &str) { + self.kv.remove(key); + } + + fn announce_accessibility(&mut self, message: &str) { + self.announcements.push(message.to_string()); + } +} diff --git a/packages/frontend/client/src/i18n.rs b/packages/frontend/client/src/i18n.rs new file mode 100644 index 0000000000..1f0dbe0795 --- /dev/null +++ b/packages/frontend/client/src/i18n.rs @@ -0,0 +1,313 @@ +//! 25-language i18n catalog and deterministic fallback chain matching +//! `packages/frontend/i18n/src/resources/index.ts`. + +use std::collections::BTreeMap; + +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +use crate::ClientResult; + +/// Metadata for one of the 25 supported AFFiNE locales. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct LanguageMeta { + pub code: &'static str, + pub name: &'static str, + pub original_name: &'static str, + pub rtl: bool, +} + +/// Exact 25 supported locales matching `packages/frontend/i18n/src/resources/index.ts`. +pub const SUPPORTED_LANGUAGES: &[LanguageMeta] = &[ + LanguageMeta { + code: "en", + name: "English", + original_name: "English", + rtl: false, + }, + LanguageMeta { + code: "ko", + name: "Korean (South Korea)", + original_name: "한국어(대한민국)", + rtl: false, + }, + LanguageMeta { + code: "pt-BR", + name: "Portuguese (Brazil)", + original_name: "português (Brasil)", + rtl: false, + }, + LanguageMeta { + code: "zh-Hans", + name: "Simplified Chinese", + original_name: "简体中文", + rtl: false, + }, + LanguageMeta { + code: "zh-Hant", + name: "Traditional Chinese", + original_name: "繁體中文", + rtl: false, + }, + LanguageMeta { + code: "fr", + name: "French", + original_name: "français", + rtl: false, + }, + LanguageMeta { + code: "es", + name: "Spanish", + original_name: "español", + rtl: false, + }, + LanguageMeta { + code: "es-AR", + name: "Spanish (Argentina)", + original_name: "español (Argentina)", + rtl: false, + }, + LanguageMeta { + code: "es-CL", + name: "Spanish (Chile)", + original_name: "español (Chile)", + rtl: false, + }, + LanguageMeta { + code: "pl", + name: "Polish", + original_name: "Polski", + rtl: false, + }, + LanguageMeta { + code: "de", + name: "German", + original_name: "Deutsch", + rtl: false, + }, + LanguageMeta { + code: "ru", + name: "Russian", + original_name: "русский", + rtl: false, + }, + LanguageMeta { + code: "ja", + name: "Japanese", + original_name: "日本語", + rtl: false, + }, + LanguageMeta { + code: "it", + name: "Italian", + original_name: "italiano", + rtl: false, + }, + LanguageMeta { + code: "ca", + name: "Catalan", + original_name: "català", + rtl: false, + }, + LanguageMeta { + code: "da", + name: "Danish", + original_name: "dansk", + rtl: false, + }, + LanguageMeta { + code: "hi", + name: "Hindi", + original_name: "हिन्दी", + rtl: false, + }, + LanguageMeta { + code: "sv-SE", + name: "Swedish (Sweden)", + original_name: "svenska (Sverige)", + rtl: false, + }, + LanguageMeta { + code: "ur", + name: "Urdu", + original_name: "اردو", + rtl: true, + }, + LanguageMeta { + code: "ar", + name: "Arabic", + original_name: "العربية", + rtl: true, + }, + LanguageMeta { + code: "fa", + name: "Persian", + original_name: "فارسی", + rtl: true, + }, + LanguageMeta { + code: "uk", + name: "Ukrainian", + original_name: "українська", + rtl: false, + }, + LanguageMeta { + code: "nb-NO", + name: "Norwegian", + original_name: "Norsk (Bokmål)", + rtl: false, + }, + LanguageMeta { + code: "kk", + name: "Kazakh", + original_name: "Қазақша", + rtl: false, + }, + LanguageMeta { + code: "tr", + name: "Turkish", + original_name: "Türkçe", + rtl: false, + }, +]; + +/// Look up metadata for a canonical supported locale code. +pub fn find_language(code: &str) -> Option { + SUPPORTED_LANGUAGES + .iter() + .copied() + .find(|meta| meta.code.eq_ignore_ascii_case(code)) +} + +/// Resolve an ordered fallback chain of supported locale codes terminating in `"en"`. +pub fn resolve_fallback_chain(requested: &str) -> Vec<&'static str> { + let normalized = requested.trim().replace('_', "-"); + let mut chain = Vec::new(); + + if let Some(exact) = find_language(&normalized) { + chain.push(exact.code); + } else { + let lower = normalized.to_ascii_lowercase(); + if lower.starts_with("zh-tw") + || lower.starts_with("zh-hk") + || lower.starts_with("zh-mo") + || lower.starts_with("zh-hant") + { + chain.push("zh-Hant"); + } else if lower.starts_with("zh") { + chain.push("zh-Hans"); + } else if lower.starts_with("pt") { + chain.push("pt-BR"); + } else if lower.starts_with("sv") { + chain.push("sv-SE"); + } else if lower.starts_with("nb") || lower.starts_with("no") { + chain.push("nb-NO"); + } + } + + if let Some((base, _)) = normalized.split_once('-') + && let Some(base_meta) = find_language(base) + && !chain.contains(&base_meta.code) + { + chain.push(base_meta.code); + } + + if !chain.contains(&"en") { + chain.push("en"); + } + chain +} + +/// Runtime i18n dictionary store supporting dynamic locale loading and fallback lookup. +#[derive(Clone, Debug, Default, Serialize, Deserialize)] +pub struct I18nCatalog { + active_locale: String, + bundles: BTreeMap>, +} + +impl I18nCatalog { + pub fn new(active_locale: impl Into) -> Self { + let req = active_locale.into(); + let resolved = resolve_fallback_chain(&req)[0].to_string(); + Self { + active_locale: resolved, + bundles: BTreeMap::new(), + } + } + + pub fn active_locale(&self) -> &str { + &self.active_locale + } + + pub fn is_rtl(&self) -> bool { + find_language(&self.active_locale).is_some_and(|m| m.rtl) + } + + pub fn set_locale(&mut self, locale: &str) { + self.active_locale = resolve_fallback_chain(locale)[0].to_string(); + } + + /// Load a flat JSON resource bundle (`{ "key": "value" }`) for `locale`. + pub fn load_json_bundle(&mut self, locale: &str, json_bytes: &[u8]) -> ClientResult { + let parsed: Value = serde_json::from_slice(json_bytes)?; + let Some(obj) = parsed.as_object() else { + return Ok(0); + }; + let canonical = find_language(locale) + .map(|m| m.code.to_string()) + .unwrap_or_else(|| locale.to_string()); + let entry = self.bundles.entry(canonical).or_default(); + let mut count = 0usize; + for (k, v) in obj { + if let Some(s) = v.as_str() { + entry.insert(k.clone(), s.to_string()); + count += 1; + } + } + Ok(count) + } + + /// Translate `key` walking [`resolve_fallback_chain`] for the active locale, falling back to `key`. + pub fn t<'a>(&'a self, key: &'a str) -> &'a str { + for locale in resolve_fallback_chain(&self.active_locale) { + if let Some(bundle) = self.bundles.get(locale) + && let Some(val) = bundle.get(key) + { + return val.as_str(); + } + } + key + } +} + +#[cfg(test)] +mod tests { + use std::path::PathBuf; + + use super::*; + + #[test] + fn supports_all_25_languages_and_parses_all_repo_resource_files() { + assert_eq!(SUPPORTED_LANGUAGES.len(), 25); + assert_eq!(resolve_fallback_chain("es-AR"), vec!["es-AR", "es", "en"]); + assert_eq!(resolve_fallback_chain("zh-TW"), vec!["zh-Hant", "en"]); + assert_eq!(resolve_fallback_chain("zh-CN"), vec!["zh-Hans", "en"]); + assert_eq!(resolve_fallback_chain("unknown-XX"), vec!["en"]); + + let resources_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../i18n/src/resources"); + let mut catalog = I18nCatalog::new("es-AR"); + for lang in SUPPORTED_LANGUAGES { + let file_path = resources_dir.join(format!("{}.json", lang.code)); + let raw = std::fs::read(&file_path) + .unwrap_or_else(|e| panic!("failed to read {}: {e}", file_path.display())); + let loaded = catalog.load_json_bundle(lang.code, &raw).unwrap(); + assert!(loaded > 0, "locale {} had zero string entries", lang.code); + } + + // Arabic/Persian/Urdu are RTL; English is LTR. + catalog.set_locale("ar"); + assert!(catalog.is_rtl()); + catalog.set_locale("en"); + assert!(!catalog.is_rtl()); + } +} diff --git a/packages/frontend/client/src/lib.rs b/packages/frontend/client/src/lib.rs new file mode 100644 index 0000000000..234192b8ac --- /dev/null +++ b/packages/frontend/client/src/lib.rs @@ -0,0 +1,95 @@ +//! L3 device-neutral AFFiNE client domain core. +//! +//! Shared across Mobile, Desktop, and Web hosts with zero `ui::Window` or view dependencies. + +#![forbid(unsafe_code)] + +pub mod accessibility; +pub mod auth; +pub mod bootstrap; +pub mod doc_directory; +pub mod domain; +pub mod host; +pub mod i18n; +pub mod search; +pub mod server; + +use thiserror::Error; + +pub use accessibility::{ + AccessibilityBounds, AccessibilityNode, AccessibilityRole, AccessibilityState, + AccessibilityTree, FirstFrameAccessibilityRoot, PlatformAccessibility, +}; +pub use auth::{ + AuthController, AuthSessionState, NativeAuthPlatform, NativeTokenPair, StoredAuthTokenPair, +}; +pub use bootstrap::{BootstrapDecision, WorkspaceBootstrapGate}; +pub use doc_directory::{CreateIntentEntry, CreateIntentLedger, StoreBackedDocDirectory}; +pub use domain::{ + CollectionModel, DocModel, FavoriteItem, FolderNode, JournalEntry, TagModel, TrashItem, + WorkspaceDomainService, WorkspaceModel, +}; +pub use host::{HostBridge, HostKind, MemoryHostBridge, WsHandle}; +pub use i18n::{I18nCatalog, LanguageMeta, SUPPORTED_LANGUAGES, resolve_fallback_chain}; +pub use search::{SearchDocument, SearchHit, SearchWeights, WeightedSearchEngine}; +pub use server::{DEFAULT_CLOUD_SERVER_ID, ServerEntry, ServerRegistry}; + +/// Unified error type for the L3 client domain crate. +#[derive(Debug, Error, Eq, PartialEq)] +pub enum ClientError { + #[error("adding cross-origin self-hosted servers is forbidden on Web hosts")] + SelfHostedForbiddenOnWeb, + + #[error("built-in official cloud server cannot be removed")] + CannotRemoveBuiltInServer, + + #[error("server with ID `{0}` already exists")] + DuplicateServerId(String), + + #[error("server with base URL `{0}` already exists")] + DuplicateServerUrl(String), + + #[error("server `{0}` not found")] + ServerNotFound(String), + + #[error("invalid server URL `{0}`")] + InvalidServerUrl(String), + + #[error("document `{0}` not found")] + DocNotFound(String), + + #[error("workspace metadata table `{0}` is not loaded")] + TableNotLoaded(String), + + #[error("row `{0}` is tombstoned and cannot be revived")] + RowTombstoned(String), + + #[error("operation requires a native host")] + NativeHostRequired, + + #[error("invalid auth payload: {0}")] + InvalidAuthPayload(String), + + #[error("host bridge error: {0}")] + Host(String), + + #[error("store error: {0}")] + Store(String), + + #[error("serialization error: {0}")] + Serialization(String), +} + +impl From for ClientError { + fn from(value: affine_store::StoreError) -> Self { + Self::Store(value.to_string()) + } +} + +impl From for ClientError { + fn from(value: serde_json::Error) -> Self { + Self::Serialization(value.to_string()) + } +} + +pub type ClientResult = Result; diff --git a/packages/frontend/client/src/search.rs b/packages/frontend/client/src/search.rs new file mode 100644 index 0000000000..e5af2b1ae3 --- /dev/null +++ b/packages/frontend/client/src/search.rs @@ -0,0 +1,178 @@ +//! `threshold: 0` exact substring weighted search engine with UTF-16 highlight spans. + +use blocksuite_editor::{Utf16HighlightSpan, match_exact_substring_utf16}; +use serde::{Deserialize, Serialize}; + +/// Field weights applied when combining exact substring match scores. +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct SearchWeights { + pub title: f64, + pub tags: f64, + pub body: f64, +} + +impl Default for SearchWeights { + fn default() -> Self { + Self { + title: 3.0, + tags: 2.0, + body: 1.0, + } + } +} + +/// Indexable document input for [`WeightedSearchEngine`]. +#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] +pub struct SearchDocument { + pub id: String, + pub title: String, + pub tags: Vec, + pub body_preview: String, + pub updated_at_ms: i64, +} + +/// Ranked search result from [`WeightedSearchEngine::search`]. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct SearchHit { + pub doc_id: String, + pub title: String, + /// Higher score ranks first (`title` > `tags` > `body` exact substring matches). + pub score: f64, + pub title_highlights: Vec, + pub matched_tags: Vec, + pub body_highlights: Vec, + pub updated_at_ms: i64, +} + +/// Exact substring (`threshold: 0`, zero fuzzy typos) weighted document search engine. +#[derive(Clone, Debug)] +pub struct WeightedSearchEngine { + weights: SearchWeights, +} + +impl Default for WeightedSearchEngine { + fn default() -> Self { + Self::new(SearchWeights::default()) + } +} + +impl WeightedSearchEngine { + pub fn new(weights: SearchWeights) -> Self { + Self { weights } + } + + pub fn search(&self, docs: &[SearchDocument], query: &str, limit: usize) -> Vec { + let mut hits = Vec::new(); + + for doc in docs { + if query.is_empty() { + hits.push(SearchHit { + doc_id: doc.id.clone(), + title: doc.title.clone(), + score: 0.0, + title_highlights: Vec::new(), + matched_tags: Vec::new(), + body_highlights: Vec::new(), + updated_at_ms: doc.updated_at_ms, + }); + continue; + } + + let mut total_score = 0.0; + let mut matched = false; + + let title_highlights = + if let Some((dist, spans)) = match_exact_substring_utf16(&doc.title, query) { + matched = true; + total_score += self.weights.title * (1.0 - dist); + spans + } else { + Vec::new() + }; + + let mut matched_tags = Vec::new(); + for tag in &doc.tags { + if let Some((dist, _)) = match_exact_substring_utf16(tag, query) { + matched = true; + total_score += self.weights.tags * (1.0 - dist); + matched_tags.push(tag.clone()); + } + } + + let body_highlights = if let Some((dist, spans)) = + match_exact_substring_utf16(&doc.body_preview, query) + { + matched = true; + total_score += self.weights.body * (1.0 - dist); + spans + } else { + Vec::new() + }; + + if matched { + hits.push(SearchHit { + doc_id: doc.id.clone(), + title: doc.title.clone(), + score: total_score, + title_highlights, + matched_tags, + body_highlights, + updated_at_ms: doc.updated_at_ms, + }); + } + } + + hits.sort_by(|a, b| { + b.score + .total_cmp(&a.score) + .then_with(|| b.updated_at_ms.cmp(&a.updated_at_ms)) + .then_with(|| a.doc_id.cmp(&b.doc_id)) + }); + + if limit > 0 && hits.len() > limit { + hits.truncate(limit); + } + hits + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn exact_substring_weighted_search_rejects_typos_and_ranks_title_above_body() { + let engine = WeightedSearchEngine::default(); + let docs = vec![ + SearchDocument { + id: "d-body".into(), + title: "Notes".into(), + tags: vec![], + body_preview: "Contains sync protocol spec".into(), + updated_at_ms: 200, + }, + SearchDocument { + id: "d-tag".into(), + title: "Misc".into(), + tags: vec!["sync".into()], + body_preview: "Unrelated".into(), + updated_at_ms: 150, + }, + SearchDocument { + id: "d-title".into(), + title: "Sync".into(), + tags: vec![], + body_preview: "".into(), + updated_at_ms: 100, + }, + ]; + + // threshold: 0 -> fuzzy typo "snyc" matches zero documents. + assert!(engine.search(&docs, "snyc", 10).is_empty()); + + let hits = engine.search(&docs, "sync", 10); + let ids: Vec<&str> = hits.iter().map(|h| h.doc_id.as_str()).collect(); + assert_eq!(ids, vec!["d-title", "d-tag", "d-body"]); + assert_eq!(hits[0].title_highlights.len(), 1); + } +} diff --git a/packages/frontend/client/src/server.rs b/packages/frontend/client/src/server.rs new file mode 100644 index 0000000000..0cfa9edb85 --- /dev/null +++ b/packages/frontend/client/src/server.rs @@ -0,0 +1,198 @@ +//! Multi-server registry (official cloud + self-hosted) enforcing iron rule `F3`. + +use std::collections::BTreeMap; + +use affine_legacy_import::{LegacyLocalStorageSnapshot, LegacyServerMetadata}; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +use crate::{ClientError, ClientResult, host::HostKind}; + +/// Built-in official AFFiNE Cloud server identifier matching `BUILD_IN_SERVERS`. +pub const DEFAULT_CLOUD_SERVER_ID: &str = "affine-cloud"; + +/// Registered server entry managed by [`ServerRegistry`]. +#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ServerEntry { + pub id: String, + pub base_url: String, + pub is_self_hosted: bool, + pub built_in: bool, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub config: Option, +} + +/// Device-neutral server registry enforcing `F3` (no cross-origin self-hosted server addition on Web). +#[derive(Clone, Debug)] +pub struct ServerRegistry { + host_kind: HostKind, + servers: Vec, +} + +impl ServerRegistry { + /// Create a registry seeded with the built-in official server. + pub fn new(host_kind: HostKind, official_base_url: impl Into) -> Self { + let base_url = normalize_base_url(&official_base_url.into()); + Self { + host_kind, + servers: vec![ServerEntry { + id: DEFAULT_CLOUD_SERVER_ID.to_string(), + base_url, + is_self_hosted: false, + built_in: true, + config: None, + }], + } + } + + /// Hydrate self-hosted servers from an imported legacy `localStorage` snapshot. + /// + /// On `HostKind::Web`, cross-origin self-hosted entries are ignored in compliance with `F3`. + pub fn hydrate_from_legacy(&mut self, snapshot: &LegacyLocalStorageSnapshot) { + if let Some(cloud_cfg) = snapshot.server_configs.get(DEFAULT_CLOUD_SERVER_ID) + && let Some(cloud) = self + .servers + .iter_mut() + .find(|s| s.id == DEFAULT_CLOUD_SERVER_ID) + { + cloud.config = Some(cloud_cfg.clone()); + } + if !self.can_add_self_hosted() { + return; + } + for meta in &snapshot.server_list { + let cfg = snapshot.server_configs.get(&meta.id).cloned(); + let _ = self.add_self_hosted_server(&meta.id, &meta.base_url, cfg); + } + } + + /// Return `true` only on `HostKind::Native` (`F3`: Web hosts never expose cross-origin server add). + pub const fn can_add_self_hosted(&self) -> bool { + matches!(self.host_kind, HostKind::Native) + } + + pub fn list(&self) -> &[ServerEntry] { + &self.servers + } + + pub fn get(&self, server_id: &str) -> Option<&ServerEntry> { + self.servers.iter().find(|s| s.id == server_id) + } + + /// Add a self-hosted server on native hosts; returns [`ClientError::SelfHostedForbiddenOnWeb`] on Web. + pub fn add_self_hosted_server( + &mut self, + id: impl Into, + base_url: &str, + config: Option, + ) -> ClientResult<&ServerEntry> { + if !self.can_add_self_hosted() { + return Err(ClientError::SelfHostedForbiddenOnWeb); + } + let id = id.into(); + if self.servers.iter().any(|s| s.id == id) { + return Err(ClientError::DuplicateServerId(id)); + } + let normalized = normalize_base_url(base_url); + if !normalized.starts_with("http://") && !normalized.starts_with("https://") { + return Err(ClientError::InvalidServerUrl(base_url.to_string())); + } + if self + .servers + .iter() + .any(|s| s.base_url.eq_ignore_ascii_case(&normalized)) + { + return Err(ClientError::DuplicateServerUrl(normalized)); + } + self.servers.push(ServerEntry { + id, + base_url: normalized, + is_self_hosted: true, + built_in: false, + config, + }); + Ok(self.servers.last().expect("pushed entry")) + } + + /// Remove a user-added self-hosted server; built-in official cloud cannot be removed. + pub fn remove_server(&mut self, server_id: &str) -> ClientResult<()> { + let Some(pos) = self.servers.iter().position(|s| s.id == server_id) else { + return Err(ClientError::ServerNotFound(server_id.to_string())); + }; + if self.servers[pos].built_in { + return Err(ClientError::CannotRemoveBuiltInServer); + } + self.servers.remove(pos); + Ok(()) + } + + pub fn update_server_config(&mut self, server_id: &str, config: Value) -> ClientResult<()> { + let Some(entry) = self.servers.iter_mut().find(|s| s.id == server_id) else { + return Err(ClientError::ServerNotFound(server_id.to_string())); + }; + entry.config = Some(config); + Ok(()) + } + + /// Export non-built-in self-hosted servers and configs for rollback writeback. + pub fn export_legacy_servers(&self) -> (Vec, BTreeMap) { + let mut list = Vec::new(); + let mut configs = BTreeMap::new(); + for server in &self.servers { + if !server.built_in { + list.push(LegacyServerMetadata { + id: server.id.clone(), + base_url: server.base_url.clone(), + }); + } + if let Some(ref cfg) = server.config { + configs.insert(server.id.clone(), cfg.clone()); + } + } + (list, configs) + } +} + +fn normalize_base_url(raw: &str) -> String { + raw.trim().trim_end_matches('/').to_string() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn f3_web_host_forbids_adding_cross_origin_self_hosted_servers() { + let mut web = ServerRegistry::new(HostKind::Web, "https://app.affine.pro"); + assert!(!web.can_add_self_hosted()); + assert_eq!( + web.add_self_hosted_server("self-1", "https://notes.example.com", None), + Err(ClientError::SelfHostedForbiddenOnWeb) + ); + assert_eq!(web.list().len(), 1); + + let mut native = ServerRegistry::new(HostKind::Native, "https://app.affine.pro/"); + assert!(native.can_add_self_hosted()); + let added = native + .add_self_hosted_server("self-1", "https://notes.example.com/", None) + .unwrap(); + assert_eq!(added.base_url, "https://notes.example.com"); + assert_eq!( + native.add_self_hosted_server("self-1", "https://other.example.com", None), + Err(ClientError::DuplicateServerId("self-1".into())) + ); + assert_eq!( + native.add_self_hosted_server("self-2", "https://notes.example.com", None), + Err(ClientError::DuplicateServerUrl( + "https://notes.example.com".into() + )) + ); + assert_eq!( + native.remove_server(DEFAULT_CLOUD_SERVER_ID), + Err(ClientError::CannotRemoveBuiltInServer) + ); + native.remove_server("self-1").unwrap(); + assert_eq!(native.list().len(), 1); + } +} diff --git a/packages/frontend/legacy-import/AGENTS.md b/packages/frontend/legacy-import/AGENTS.md new file mode 100644 index 0000000000..1153a3ea21 --- /dev/null +++ b/packages/frontend/legacy-import/AGENTS.md @@ -0,0 +1,14 @@ +# Working in `packages/frontend/legacy-import/` (for agents) + +`packages/frontend/legacy-import/` (`affine-legacy-import`) is the pure-Rust upgrade compatibility layer between legacy `0.27.5` Capacitor WebView `localStorage` state and the native client core. +This crate belongs to the client Cargo workspace rooted at `packages/frontend/Cargo.toml`. + +## Domain boundaries and invariants + +- Keep `#![forbid(unsafe_code)]` at the crate root. +- Depend only on pure utility crates (`serde`, `serde_json`, `thiserror`) so this crate never pulls in `sqlx`, UI crates, host crates, or legacy WebView IndexedDB. +- Parse and write back only the explicit `localStorage` allowlist (`affine-local-workspace`, `global-state:serverList`, `global-state:serverConfig:`, `global-state:-auth`, `global-state:cloud-workspace:`, `global-state:selfhosted-workspace-:`, `affine-flag:*`, `global-state:affine-flag:*`, `global-cache:i18n_lng`, `last_workspace_id`, `last_workspace_flavour`, `affine-settings`, `theme`). +- Validate the positive sentinel `{ origin, length, keys, entries }` including reverse completeness for core allowlisted keys before importing. + Never clear state, initialize a default workspace, or scan `*.db` files when the sentinel reports an origin mismatch or unready WebView. +- Preserve malformed auxiliary JSON entries verbatim in `preserved_raw_entries` so a single corrupt optional key never aborts importing valid local workspace IDs. +- Keep every `.rs` file at or below 800 non-test lines, zero `super::super::`, and zero system wall-clock calls. diff --git a/packages/frontend/legacy-import/CLAUDE.md b/packages/frontend/legacy-import/CLAUDE.md new file mode 100644 index 0000000000..43c994c2d3 --- /dev/null +++ b/packages/frontend/legacy-import/CLAUDE.md @@ -0,0 +1 @@ +@AGENTS.md diff --git a/packages/frontend/legacy-import/Cargo.toml b/packages/frontend/legacy-import/Cargo.toml new file mode 100644 index 0000000000..61f1d564bd --- /dev/null +++ b/packages/frontend/legacy-import/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "affine-legacy-import" +workspace = ".." +version.workspace = true +edition.workspace = true +publish.workspace = true +license.workspace = true + +[lints] +workspace = true + +[dependencies] +serde.workspace = true +serde_json.workspace = true +thiserror.workspace = true diff --git a/packages/frontend/legacy-import/src/lib.rs b/packages/frontend/legacy-import/src/lib.rs new file mode 100644 index 0000000000..9092046daf --- /dev/null +++ b/packages/frontend/legacy-import/src/lib.rs @@ -0,0 +1,521 @@ +//! Pure-Rust Capacitor WebView `localStorage` import, positive sentinel validation, +//! and rollback-window writeback serializer. +//! +//! Zero legacy WebView IndexedDB dependencies and zero `*.db` directory scanning. + +#![forbid(unsafe_code)] + +pub mod sentinel; +pub mod writeback; + +use std::collections::{BTreeMap, BTreeSet}; + +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use thiserror::Error; + +pub use sentinel::{ + SentinelEvaluation, SentinelFailureReason, WebViewStorageSentinel, evaluate_sentinel, +}; +pub use writeback::{ + LocalStorageMutation, WritebackReadbackReport, build_writeback_changeset, + verify_writeback_readback, +}; + +/// Exact `localStorage` key for the ordered local workspace allowlist. +pub const KEY_LOCAL_WORKSPACE_LIST: &str = "affine-local-workspace"; +/// Prefix used by `LocalStorageGlobalState` in `0.27.5` (`packages/frontend/core/src/modules/storage/impls/storage.ts`). +pub const PREFIX_GLOBAL_STATE: &str = "global-state:"; +/// Exact `localStorage` key for the self-hosted server list (`global-state:serverList`). +pub const KEY_SERVER_LIST: &str = "global-state:serverList"; +/// Prefix for per-server cached configuration (`global-state:serverConfig:`). +pub const PREFIX_SERVER_CONFIG: &str = "global-state:serverConfig:"; +/// Suffix for per-server cached auth session (`global-state:-auth`). +pub const SUFFIX_SERVER_AUTH: &str = "-auth"; +/// Prefix for bare feature flags (`affine-flag:*`). +pub const PREFIX_FEATURE_FLAG: &str = "affine-flag:"; +/// Prefix for `LocalStorageGlobalState`-prefixed feature flags (`global-state:affine-flag:*`). +pub const PREFIX_GLOBAL_STATE_FEATURE_FLAG: &str = "global-state:affine-flag:"; +/// Prefix for official cloud workspace list cache (`global-state:cloud-workspace:`). +pub const PREFIX_CLOUD_WORKSPACE_CACHE: &str = "global-state:cloud-workspace:"; +/// Prefix for self-hosted workspace list cache (`global-state:selfhosted-workspace-:`). +pub const PREFIX_SELFHOSTED_WORKSPACE_CACHE: &str = "global-state:selfhosted-workspace-"; +/// Exact `localStorage` key for persisted i18n language (`global-cache:i18n_lng`). +pub const KEY_I18N_LNG: &str = "global-cache:i18n_lng"; +/// Exact `localStorage` key for last opened workspace ID. +pub const KEY_LAST_WORKSPACE_ID: &str = "last_workspace_id"; +/// Exact `localStorage` key for last opened workspace flavour. +pub const KEY_LAST_WORKSPACE_FLAVOUR: &str = "last_workspace_flavour"; +/// Exact `localStorage` key for serialized user settings. +pub const KEY_AFFINE_SETTINGS: &str = "affine-settings"; +/// Exact `localStorage` key for active theme mode (`light` / `dark` / `system`). +pub const KEY_THEME: &str = "theme"; + +/// Error returned while parsing or verifying legacy WebView `localStorage` state. +#[derive(Debug, Error, Eq, PartialEq)] +pub enum LegacyImportError { + #[error("sentinel validation failed: {0:?}")] + SentinelFailed(SentinelFailureReason), + + #[error("malformed JSON for key `{key}`: {message}")] + MalformedJson { key: String, message: String }, + + #[error("key `{0}` is outside the legacy localStorage allowlist")] + DisallowedKey(String), +} + +/// Server metadata entry stored in `global-state:serverList`. +#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct LegacyServerMetadata { + pub id: String, + pub base_url: String, +} + +/// Parsed snapshot of all allowlisted Capacitor WebView `localStorage` keys. +#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)] +pub struct LegacyLocalStorageSnapshot { + /// Ordered, deduplicated local workspace IDs from `affine-local-workspace` (verbatim, never trimmed). + pub local_workspace_ids: Vec, + /// `true` when `affine-local-workspace` existed in `localStorage` (including `"[]"`). + #[serde(default)] + pub has_local_workspace_key: bool, + /// Self-hosted server entries from `global-state:serverList`. + pub server_list: Vec, + /// `true` when `global-state:serverList` existed in `localStorage` (including `"[]"`). + #[serde(default)] + pub has_server_list_key: bool, + /// Per-server config blobs from `global-state:serverConfig:`. + pub server_configs: BTreeMap, + /// Per-server cached auth session JSON from canonical `global-state:-auth`. + pub server_auth_sessions: BTreeMap, + /// Cloud and self-hosted workspace offline list caches (`global-state:cloud-workspace:*` + /// and `global-state:selfhosted-workspace-*`) preserved verbatim for offline cold start. + #[serde(default)] + pub cloud_workspace_caches: BTreeMap, + /// Feature flags from `affine-flag:` or `global-state:affine-flag:`. + pub feature_flags: BTreeMap, + /// Flag names originally stored under `global-state:affine-flag:` for 1:1 writeback. + #[serde(default)] + pub global_state_flag_names: BTreeSet, + /// Active locale code from `global-cache:i18n_lng`. + pub i18n_lng: Option, + /// Last opened workspace ID from `last_workspace_id`. + pub last_workspace_id: Option, + /// Last opened workspace flavour from `last_workspace_flavour`. + pub last_workspace_flavour: Option, + /// Raw settings JSON object from `affine-settings`. + pub affine_settings: Option, + /// Theme preference from `theme`. + pub theme: Option, + /// Auxiliary keys whose JSON failed to parse (or legacy bare `-auth` keys collected by + /// mobile probes), preserved verbatim on writeback so no data is silently deleted. + #[serde(default)] + pub preserved_raw_entries: BTreeMap, +} + +impl LegacyLocalStorageSnapshot { + /// Explicitly replace `local_workspace_ids` and retire any raw preserved entry for + /// `affine-local-workspace`, marking the key present so empty lists serialize as `"[]"`. + pub fn set_local_workspace_ids(&mut self, ids: Vec) { + self.preserved_raw_entries.remove(KEY_LOCAL_WORKSPACE_LIST); + self.local_workspace_ids = dedupe_preserve_order(ids); + self.has_local_workspace_key = true; + } + + /// Explicitly replace `server_list` and retire any corrupt raw preserved entry for + /// `global-state:serverList`, marking the key present so empty lists serialize as `"[]"`. + pub fn set_server_list(&mut self, servers: Vec) { + self.preserved_raw_entries.remove(KEY_SERVER_LIST); + self.server_list = servers; + self.has_server_list_key = true; + } +} + +/// Parse a canonical `global-state:-auth` key, returning ``. +pub(crate) fn parse_canonical_server_auth_key(key: &str) -> Option<&str> { + let rest = key.strip_prefix(PREFIX_GLOBAL_STATE)?; + let server_id = rest.strip_suffix(SUFFIX_SERVER_AUTH)?; + if !server_id.is_empty() && !server_id.contains(':') { + Some(server_id) + } else { + None + } +} + +/// Return `true` for a bare `-auth` key (without `:` or `global-state:` prefix) that mobile +/// probes may collect; accepted in `entries` as `preserved_raw_entries` without blocking fresh install. +pub(crate) fn is_legacy_bare_auth_key(key: &str) -> bool { + key.strip_suffix(SUFFIX_SERVER_AUTH) + .is_some_and(|id| !id.is_empty() && !id.contains(':')) +} + +/// Parse a feature flag key, returning `(flag_name, is_global_state_prefixed)`. +pub(crate) fn parse_feature_flag_key(key: &str) -> Option<(&str, bool)> { + if let Some(flag_name) = key.strip_prefix(PREFIX_GLOBAL_STATE_FEATURE_FLAG) + && !flag_name.is_empty() + { + return Some((flag_name, true)); + } + if let Some(flag_name) = key.strip_prefix(PREFIX_FEATURE_FLAG) + && !flag_name.is_empty() + { + return Some((flag_name, false)); + } + None +} + +/// Return `true` for optional offline cloud/self-hosted workspace list cache keys. +pub fn is_cloud_workspace_cache_key(key: &str) -> bool { + if let Some(account_id) = key.strip_prefix(PREFIX_CLOUD_WORKSPACE_CACHE) { + return !account_id.is_empty(); + } + if let Some(rest) = key.strip_prefix(PREFIX_SELFHOSTED_WORKSPACE_CACHE) + && let Some((server_id, account_id)) = rest.split_once(':') + { + return !server_id.is_empty() && !account_id.is_empty(); + } + false +} + +/// Return `true` for the core allowlisted keys enforced by cross-slice sentinel reverse completeness. +pub fn is_core_sentinel_required_key(key: &str) -> bool { + if matches!( + key, + KEY_LOCAL_WORKSPACE_LIST + | KEY_SERVER_LIST + | KEY_I18N_LNG + | KEY_LAST_WORKSPACE_ID + | KEY_LAST_WORKSPACE_FLAVOUR + | KEY_AFFINE_SETTINGS + | KEY_THEME + ) { + return true; + } + if let Some(rest) = key.strip_prefix(PREFIX_SERVER_CONFIG) { + return !rest.is_empty(); + } + parse_feature_flag_key(key).is_some() || parse_canonical_server_auth_key(key).is_some() +} + +/// Return `true` if `key` belongs to the official AFFiNE `localStorage` allowlist +/// (core required keys + optional cloud/self-hosted workspace list cache keys). +pub fn is_allowlisted_key(key: &str) -> bool { + is_core_sentinel_required_key(key) || is_cloud_workspace_cache_key(key) +} + +/// Return `true` if `key` is permitted inside `WebViewStorageSentinel::entries` (official allowlist +/// plus bare `-auth` keys that mobile probes may forward). +pub(crate) fn is_permitted_sentinel_entry_key(key: &str) -> bool { + is_allowlisted_key(key) || is_legacy_bare_auth_key(key) +} + +/// Parse allowlisted entries from a validated positive sentinel. +/// +/// Refuses to import and returns `Err(LegacyImportError::SentinelFailed(_))` if the sentinel +/// indicates an origin mismatch, missing required allowlisted entry, or unready WebView, +/// preventing accidental workspace reset or deleted-workspace resurrection (`F1`). +pub fn import_from_sentinel( + sentinel: &WebViewStorageSentinel, + allowed_origins: &[&str], +) -> Result<(SentinelEvaluation, LegacyLocalStorageSnapshot), LegacyImportError> { + let evaluation = evaluate_sentinel(sentinel, allowed_origins); + match &evaluation { + SentinelEvaluation::UnreadyOrMismatch(reason) => { + Err(LegacyImportError::SentinelFailed(reason.clone())) + } + SentinelEvaluation::ValidEmpty => Ok((evaluation, LegacyLocalStorageSnapshot::default())), + SentinelEvaluation::ValidPopulated { .. } => { + let snapshot = parse_allowlisted_entries(&sentinel.entries)?; + Ok((evaluation, snapshot)) + } + } +} + +/// Parse allowlisted keys from a raw `localStorage` map with per-key fault tolerance. +/// +/// `affine-local-workspace` MUST be a valid JSON array (non-string and empty elements are filtered +/// out without trimming original IDs, matching `workspace-id-utils.ts`). Malformed auxiliary JSON +/// keys are preserved verbatim in `preserved_raw_entries` instead of aborting the workspace import. +pub fn parse_allowlisted_entries( + entries: &BTreeMap, +) -> Result { + let mut snapshot = LegacyLocalStorageSnapshot::default(); + + if let Some(raw) = entries.get(KEY_LOCAL_WORKSPACE_LIST) { + let parsed: Value = + serde_json::from_str(raw).map_err(|err| LegacyImportError::MalformedJson { + key: KEY_LOCAL_WORKSPACE_LIST.to_string(), + message: err.to_string(), + })?; + let Some(items) = parsed.as_array() else { + return Err(LegacyImportError::MalformedJson { + key: KEY_LOCAL_WORKSPACE_LIST.to_string(), + message: "expected JSON array for affine-local-workspace".to_string(), + }); + }; + let ids: Vec = items + .iter() + .filter_map(|v| v.as_str().filter(|s| !s.is_empty()).map(str::to_string)) + .collect(); + snapshot.local_workspace_ids = dedupe_preserve_order(ids); + snapshot.has_local_workspace_key = true; + } + + if let Some(raw) = entries.get(KEY_SERVER_LIST) { + match serde_json::from_str::>(raw) { + Ok(parsed) => { + snapshot.server_list = parsed; + snapshot.has_server_list_key = true; + } + Err(_) => { + snapshot + .preserved_raw_entries + .insert(KEY_SERVER_LIST.to_string(), raw.clone()); + } + } + } + + if let Some(raw) = entries.get(KEY_I18N_LNG) { + snapshot.i18n_lng = decode_optional_json_string(raw); + } + + if let Some(raw) = entries.get(KEY_LAST_WORKSPACE_ID) { + snapshot.last_workspace_id = non_empty_trimmed(raw); + } + + if let Some(raw) = entries.get(KEY_LAST_WORKSPACE_FLAVOUR) { + snapshot.last_workspace_flavour = non_empty_trimmed(raw); + } + + if let Some(raw) = entries.get(KEY_AFFINE_SETTINGS) { + match serde_json::from_str::(raw) { + Ok(parsed) => snapshot.affine_settings = Some(parsed), + Err(_) => { + snapshot + .preserved_raw_entries + .insert(KEY_AFFINE_SETTINGS.to_string(), raw.clone()); + } + } + } + + if let Some(raw) = entries.get(KEY_THEME) { + snapshot.theme = decode_optional_json_string(raw); + } + + for (key, raw) in entries { + if let Some(server_id) = key.strip_prefix(PREFIX_SERVER_CONFIG) + && !server_id.is_empty() + { + match serde_json::from_str::(raw) { + Ok(parsed) => { + snapshot + .server_configs + .insert(server_id.to_string(), parsed); + } + Err(_) => { + snapshot + .preserved_raw_entries + .insert(key.clone(), raw.clone()); + } + } + } else if is_cloud_workspace_cache_key(key) { + snapshot + .cloud_workspace_caches + .insert(key.clone(), raw.clone()); + } else if let Some((flag_name, is_global_state)) = parse_feature_flag_key(key) { + let parsed = + serde_json::from_str::(raw).unwrap_or_else(|_| Value::String(raw.clone())); + snapshot.feature_flags.insert(flag_name.to_string(), parsed); + if is_global_state { + snapshot + .global_state_flag_names + .insert(flag_name.to_string()); + } else { + snapshot.global_state_flag_names.remove(flag_name); + } + } else if let Some(server_id) = parse_canonical_server_auth_key(key) { + match serde_json::from_str::(raw) { + Ok(parsed) => { + snapshot + .server_auth_sessions + .insert(server_id.to_string(), parsed); + } + Err(_) => { + snapshot + .preserved_raw_entries + .insert(key.clone(), raw.clone()); + } + } + } else if is_legacy_bare_auth_key(key) { + snapshot + .preserved_raw_entries + .insert(key.clone(), raw.clone()); + } + } + + Ok(snapshot) +} + +/// Deduplicate workspace IDs preserving order and exact original strings (zero `.trim()`). +pub(crate) fn dedupe_preserve_order(ids: Vec) -> Vec { + let mut out = Vec::with_capacity(ids.len()); + for id in ids { + if !id.is_empty() && !out.iter().any(|existing: &String| existing == &id) { + out.push(id); + } + } + out +} + +fn decode_optional_json_string(raw: &str) -> Option { + let trimmed = raw.trim(); + if trimmed.is_empty() || trimmed == "null" { + return None; + } + if let Ok(Value::String(s)) = serde_json::from_str::(trimmed) { + return non_empty_trimmed(&s); + } + non_empty_trimmed(trimmed) +} + +fn non_empty_trimmed(raw: &str) -> Option { + let trimmed = raw.trim(); + if trimmed.is_empty() { + None + } else { + Some(trimmed.to_string()) + } +} + +#[cfg(test)] +mod tests { + use serde_json::json; + + use super::*; + + #[test] + fn allowlist_fault_tolerant_parse_cloud_cache_and_writeback_roundtrip() { + assert!(is_allowlisted_key("affine-local-workspace")); + assert!(is_allowlisted_key("global-state:serverList")); + assert!(is_allowlisted_key("global-state:serverConfig:self-1")); + assert!(is_allowlisted_key("global-state:affine-cloud-auth")); + assert!(is_allowlisted_key("global-state:cloud-workspace:acct-1")); + assert!(is_allowlisted_key( + "global-state:selfhosted-workspace-self-1:acct-2" + )); + assert!(is_allowlisted_key("affine-flag:enable_ai")); + assert!(is_allowlisted_key("global-state:affine-flag:enable_ai")); + // Bare `-auth` is NOT an official allowlisted key (does not block fresh install). + assert!(!is_allowlisted_key("foo-auth")); + assert!(!is_allowlisted_key("random-third-party-key")); + assert!(!is_allowlisted_key("global-state:bad:nested-auth")); + + // Mixed valid workspace IDs with null/number/duplicate + corrupt auxiliary settings + + // cloud workspace cache + bare probe auth key. + let entries = BTreeMap::from([ + ( + "affine-local-workspace".into(), + r#"[" ws-raw ", null, 123, "", "ws-b", " ws-raw "]"#.into(), + ), + ("affine-settings".into(), "{corrupt-json".into()), + ( + "global-state:affine-cloud-auth".into(), + r#"{"account":{"id":"u1"}}"#.into(), + ), + ( + "global-state:cloud-workspace:acct-1".into(), + r#"[{"id":"cloud-ws-1"}]"#.into(), + ), + ("foo-auth".into(), "not-even-json".into()), + ("theme".into(), "dark".into()), + ]); + let keys: Vec = entries + .keys() + .cloned() + .chain(std::iter::once("__cap_noise__".into())) + .collect(); + let sentinel = WebViewStorageSentinel { + origin: "capacitor://localhost".into(), + length: keys.len(), + keys, + entries: entries.clone(), + }; + + let (eval, snap) = import_from_sentinel(&sentinel, &["capacitor://localhost"]).unwrap(); + assert_eq!( + eval, + SentinelEvaluation::ValidPopulated { + has_allowlisted_keys: true + } + ); + // Workspace IDs preserve exact strings without trimming and filter non-string/empty items. + assert_eq!(snap.local_workspace_ids, vec![" ws-raw ", "ws-b"]); + assert_eq!( + snap.cloud_workspace_caches + .get("global-state:cloud-workspace:acct-1") + .map(String::as_str), + Some(r#"[{"id":"cloud-ws-1"}]"#) + ); + assert_eq!( + snap.preserved_raw_entries + .get("affine-settings") + .map(String::as_str), + Some("{corrupt-json") + ); + assert_eq!( + snap.preserved_raw_entries + .get("foo-auth") + .map(String::as_str), + Some("not-even-json") + ); + assert_eq!( + snap.server_auth_sessions["affine-cloud"]["account"]["id"], + json!("u1") + ); + + // Mutating theme preserves corrupt auxiliary keys and cloud caches verbatim on writeback. + let mut next = snap.clone(); + next.theme = Some("light".into()); + next.local_workspace_ids.clear(); + let changes = build_writeback_changeset(&snap, &next).unwrap(); + assert!(changes.contains(&LocalStorageMutation::Set { + key: KEY_LOCAL_WORKSPACE_LIST.into(), + value: "[]".into(), + })); + assert!(!changes.iter().any(|m| m.key() == "affine-settings")); + assert!(!changes.iter().any(|m| m.key() == "foo-auth")); + assert!( + !changes + .iter() + .any(|m| m.key() == "global-state:cloud-workspace:acct-1") + ); + + // Non-array `affine-local-workspace` MUST return an error to block silent wipe. + let bad_ws = + BTreeMap::from([("affine-local-workspace".into(), r#"{"not":"array"}"#.into())]); + assert!(parse_allowlisted_entries(&bad_ws).is_err()); + + // Corrupt `global-state:serverList` stays untouched (0 mutations) when unedited, + // and writes `"[]"` only after explicit `set_server_list(vec![])`. + let corrupt_srv = BTreeMap::from([ + ("affine-local-workspace".into(), r#"["ws-1"]"#.into()), + ("global-state:serverList".into(), "{broken".into()), + ]); + let parsed_srv = parse_allowlisted_entries(&corrupt_srv).unwrap(); + assert!( + build_writeback_changeset(&parsed_srv, &parsed_srv) + .unwrap() + .is_empty() + ); + let mut cleared_srv = parsed_srv.clone(); + cleared_srv.set_server_list(Vec::new()); + assert_eq!( + build_writeback_changeset(&parsed_srv, &cleared_srv).unwrap(), + vec![LocalStorageMutation::Set { + key: KEY_SERVER_LIST.into(), + value: "[]".into(), + }] + ); + } +} diff --git a/packages/frontend/legacy-import/src/sentinel.rs b/packages/frontend/legacy-import/src/sentinel.rs new file mode 100644 index 0000000000..073943af30 --- /dev/null +++ b/packages/frontend/legacy-import/src/sentinel.rs @@ -0,0 +1,216 @@ +//! Positive sentinel validation state machine for Capacitor WebView `localStorage`. +//! +//! Enforces bidirectional integrity between `keys` and `entries`: +//! - `length == keys.len()` with zero duplicates +//! - Every key in `entries` exists in `keys` and is a permitted entry key +//! - Every core allowlisted key present in `keys` MUST exist in `entries` (`MissingAllowlistedEntry`) +//! - Optional cloud workspace cache keys and legacy bare `-auth` keys stay cross-slice compatible +//! with `S2-iOS` and `S2-Android` probes. + +use std::collections::{BTreeMap, BTreeSet}; + +use serde::{Deserialize, Serialize}; + +use super::{is_allowlisted_key, is_core_sentinel_required_key, is_permitted_sentinel_entry_key}; + +/// Positive sentinel payload captured atomically inside the legacy WebView context. +#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)] +pub struct WebViewStorageSentinel { + pub origin: String, + pub length: usize, + pub keys: Vec, + pub entries: BTreeMap, +} + +/// Specific reason why a WebView sentinel read was rejected. +#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] +pub enum SentinelFailureReason { + EmptyOrigin, + OriginMismatch { + actual: String, + }, + LengthMismatch { + reported_length: usize, + observed_keys: usize, + }, + DuplicateKeys, + EntryKeyMissingFromKeyList { + key: String, + }, + DisallowedEntryKey { + key: String, + }, + MissingAllowlistedEntry { + key: String, + }, +} + +/// Result of evaluating a [`WebViewStorageSentinel`]. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum SentinelEvaluation { + /// Verified allowlisted origin with zero stored keys (genuine fresh install). + ValidEmpty, + /// Verified allowlisted origin with consistent key list and entry map. + /// `has_allowlisted_keys` is `false` when only unrelated third-party keys exist. + ValidPopulated { has_allowlisted_keys: bool }, + /// WebView was unready, returned an unexpected origin, or yielded inconsistent storage data. + /// Callers MUST NOT clear state, create a default workspace, or scan `*.db` files. + UnreadyOrMismatch(SentinelFailureReason), +} + +impl SentinelEvaluation { + /// Return `true` only when the WebView is verified healthy and contains zero allowlisted AFFiNE keys. + pub fn should_initialize_fresh_workspace(&self) -> bool { + matches!( + self, + Self::ValidEmpty + | Self::ValidPopulated { + has_allowlisted_keys: false + } + ) + } + + pub fn is_safe_to_import(&self) -> bool { + matches!(self, Self::ValidEmpty | Self::ValidPopulated { .. }) + } +} + +/// Validate `{ origin, length, keys, entries }` against `allowed_origins`. +pub fn evaluate_sentinel( + sentinel: &WebViewStorageSentinel, + allowed_origins: &[&str], +) -> SentinelEvaluation { + let origin = sentinel.origin.trim(); + if origin.is_empty() || origin == "null" || origin == "about:blank" { + return SentinelEvaluation::UnreadyOrMismatch(SentinelFailureReason::EmptyOrigin); + } + + if !allowed_origins + .iter() + .any(|allowed| allowed.eq_ignore_ascii_case(origin)) + { + return SentinelEvaluation::UnreadyOrMismatch(SentinelFailureReason::OriginMismatch { + actual: origin.to_string(), + }); + } + + if sentinel.length != sentinel.keys.len() { + return SentinelEvaluation::UnreadyOrMismatch(SentinelFailureReason::LengthMismatch { + reported_length: sentinel.length, + observed_keys: sentinel.keys.len(), + }); + } + + let mut unique_keys = BTreeSet::new(); + for key in &sentinel.keys { + if !unique_keys.insert(key.as_str()) { + return SentinelEvaluation::UnreadyOrMismatch(SentinelFailureReason::DuplicateKeys); + } + } + + for entry_key in sentinel.entries.keys() { + if !unique_keys.contains(entry_key.as_str()) { + return SentinelEvaluation::UnreadyOrMismatch( + SentinelFailureReason::EntryKeyMissingFromKeyList { + key: entry_key.clone(), + }, + ); + } + if !is_permitted_sentinel_entry_key(entry_key) { + return SentinelEvaluation::UnreadyOrMismatch( + SentinelFailureReason::DisallowedEntryKey { + key: entry_key.clone(), + }, + ); + } + } + + // Reverse completeness check: every core allowlisted key reported in `keys` MUST be present in `entries`. + for key in &sentinel.keys { + if is_core_sentinel_required_key(key) && !sentinel.entries.contains_key(key) { + return SentinelEvaluation::UnreadyOrMismatch( + SentinelFailureReason::MissingAllowlistedEntry { key: key.clone() }, + ); + } + } + + if sentinel.length == 0 { + SentinelEvaluation::ValidEmpty + } else { + let has_allowlisted_keys = sentinel.keys.iter().any(|k| is_allowlisted_key(k)); + SentinelEvaluation::ValidPopulated { + has_allowlisted_keys, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::import_from_sentinel; + + #[test] + fn sentinel_enforces_reverse_completeness_and_cross_slice_noise_compatibility() { + let allowed = ["capacitor://localhost", "https://localhost"]; + + // 1. Mixed 1 allowlisted key + 1 non-allowlisted noise key (noise excluded from `entries`). + let mixed = WebViewStorageSentinel { + origin: "capacitor://localhost".into(), + length: 2, + keys: vec!["__cap_noise__".into(), "affine-local-workspace".into()], + entries: BTreeMap::from([("affine-local-workspace".into(), r#"["ws-1"]"#.into())]), + }; + let (eval, snap) = import_from_sentinel(&mixed, &allowed).unwrap(); + assert_eq!( + eval, + SentinelEvaluation::ValidPopulated { + has_allowlisted_keys: true + } + ); + assert_eq!(snap.local_workspace_ids, vec!["ws-1"]); + + // 2. Missing allowlisted entry in `entries` MUST fail with MissingAllowlistedEntry. + let missing = WebViewStorageSentinel { + origin: "capacitor://localhost".into(), + length: 1, + keys: vec!["affine-local-workspace".into()], + entries: BTreeMap::new(), + }; + assert_eq!( + evaluate_sentinel(&missing, &allowed), + SentinelEvaluation::UnreadyOrMismatch(SentinelFailureReason::MissingAllowlistedEntry { + key: "affine-local-workspace".into() + }) + ); + + // 3. Bare third-party `foo-auth` does NOT block fresh-install initialization. + let third_party_auth = WebViewStorageSentinel { + origin: "capacitor://localhost".into(), + length: 1, + keys: vec!["foo-auth".into()], + entries: BTreeMap::from([("foo-auth".into(), "opaque".into())]), + }; + let eval_tp = evaluate_sentinel(&third_party_auth, &allowed); + assert_eq!( + eval_tp, + SentinelEvaluation::ValidPopulated { + has_allowlisted_keys: false + } + ); + assert!(eval_tp.should_initialize_fresh_workspace()); + + // 4. Optional cloud cache key in `keys` only (older probe) does NOT trigger MissingAllowlistedEntry. + let cloud_key_only = WebViewStorageSentinel { + origin: "capacitor://localhost".into(), + length: 1, + keys: vec!["global-state:cloud-workspace:acct-1".into()], + entries: BTreeMap::new(), + }; + assert_eq!( + evaluate_sentinel(&cloud_key_only, &allowed), + SentinelEvaluation::ValidPopulated { + has_allowlisted_keys: true + } + ); + } +} diff --git a/packages/frontend/legacy-import/src/writeback.rs b/packages/frontend/legacy-import/src/writeback.rs new file mode 100644 index 0000000000..1f6696a704 --- /dev/null +++ b/packages/frontend/legacy-import/src/writeback.rs @@ -0,0 +1,245 @@ +//! Rollback-window `localStorage` writeback serializer and readback verifier. + +use std::collections::{BTreeMap, BTreeSet}; + +use serde::{Deserialize, Serialize}; + +use super::{ + KEY_AFFINE_SETTINGS, KEY_I18N_LNG, KEY_LAST_WORKSPACE_FLAVOUR, KEY_LAST_WORKSPACE_ID, + KEY_LOCAL_WORKSPACE_LIST, KEY_SERVER_LIST, KEY_THEME, LegacyImportError, + LegacyLocalStorageSnapshot, PREFIX_FEATURE_FLAG, PREFIX_GLOBAL_STATE, + PREFIX_GLOBAL_STATE_FEATURE_FLAG, PREFIX_SERVER_CONFIG, SUFFIX_SERVER_AUTH, + dedupe_preserve_order, is_allowlisted_key, is_cloud_workspace_cache_key, + is_permitted_sentinel_entry_key, +}; + +/// Atomic `localStorage` mutation to apply during the rollback window. +#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] +pub enum LocalStorageMutation { + Set { key: String, value: String }, + Remove { key: String }, +} + +impl LocalStorageMutation { + pub fn key(&self) -> &str { + match self { + Self::Set { key, .. } | Self::Remove { key } => key, + } + } +} + +/// Verification report comparing expected writeback mutations against a readback map. +#[derive(Clone, Debug, Default, Eq, PartialEq)] +pub struct WritebackReadbackReport { + pub verified_keys: Vec, + pub mismatched_keys: Vec, +} + +impl WritebackReadbackReport { + pub fn is_ok(&self) -> bool { + self.mismatched_keys.is_empty() + } +} + +/// Serialize a [`LegacyLocalStorageSnapshot`] into canonical allowlisted `localStorage` key/value pairs. +pub fn serialize_snapshot_entries( + snapshot: &LegacyLocalStorageSnapshot, +) -> Result, LegacyImportError> { + let mut out = BTreeMap::new(); + + // Preserve unparsed/opaque entries first so structured fields can supersede them if fixed. + for (key, raw) in &snapshot.preserved_raw_entries { + if !is_permitted_sentinel_entry_key(key) { + return Err(LegacyImportError::DisallowedKey(key.clone())); + } + out.insert(key.clone(), raw.clone()); + } + + if !snapshot + .preserved_raw_entries + .contains_key(KEY_LOCAL_WORKSPACE_LIST) + && (!snapshot.local_workspace_ids.is_empty() || snapshot.has_local_workspace_key) + { + let deduped = dedupe_preserve_order(snapshot.local_workspace_ids.clone()); + out.insert( + KEY_LOCAL_WORKSPACE_LIST.to_string(), + serde_json::to_string(&deduped).map_err(|err| LegacyImportError::MalformedJson { + key: KEY_LOCAL_WORKSPACE_LIST.to_string(), + message: err.to_string(), + })?, + ); + } + + if !snapshot.preserved_raw_entries.contains_key(KEY_SERVER_LIST) + && (!snapshot.server_list.is_empty() || snapshot.has_server_list_key) + { + out.insert( + KEY_SERVER_LIST.to_string(), + serde_json::to_string(&snapshot.server_list).map_err(|err| { + LegacyImportError::MalformedJson { + key: KEY_SERVER_LIST.to_string(), + message: err.to_string(), + } + })?, + ); + } + + for (server_id, config) in &snapshot.server_configs { + let key = format!("{PREFIX_SERVER_CONFIG}{server_id}"); + if !is_allowlisted_key(&key) { + return Err(LegacyImportError::DisallowedKey(key)); + } + out.insert( + key.clone(), + serde_json::to_string(config).map_err(|err| LegacyImportError::MalformedJson { + key, + message: err.to_string(), + })?, + ); + } + + for (server_id, auth) in &snapshot.server_auth_sessions { + let key = format!("{PREFIX_GLOBAL_STATE}{server_id}{SUFFIX_SERVER_AUTH}"); + if !is_allowlisted_key(&key) { + return Err(LegacyImportError::DisallowedKey(key)); + } + out.insert( + key.clone(), + serde_json::to_string(auth).map_err(|err| LegacyImportError::MalformedJson { + key, + message: err.to_string(), + })?, + ); + } + + for (key, raw) in &snapshot.cloud_workspace_caches { + if !is_cloud_workspace_cache_key(key) { + return Err(LegacyImportError::DisallowedKey(key.clone())); + } + out.insert(key.clone(), raw.clone()); + } + + for (flag, val) in &snapshot.feature_flags { + let key = if snapshot.global_state_flag_names.contains(flag) { + format!("{PREFIX_GLOBAL_STATE_FEATURE_FLAG}{flag}") + } else { + format!("{PREFIX_FEATURE_FLAG}{flag}") + }; + if !is_allowlisted_key(&key) { + return Err(LegacyImportError::DisallowedKey(key)); + } + out.insert( + key.clone(), + serde_json::to_string(val).map_err(|err| LegacyImportError::MalformedJson { + key, + message: err.to_string(), + })?, + ); + } + + if let Some(ref lng) = snapshot.i18n_lng { + out.insert( + KEY_I18N_LNG.to_string(), + serde_json::to_string(lng).map_err(|err| LegacyImportError::MalformedJson { + key: KEY_I18N_LNG.to_string(), + message: err.to_string(), + })?, + ); + } + + if let Some(ref id) = snapshot.last_workspace_id { + out.insert(KEY_LAST_WORKSPACE_ID.to_string(), id.clone()); + } + + if let Some(ref flavour) = snapshot.last_workspace_flavour { + out.insert(KEY_LAST_WORKSPACE_FLAVOUR.to_string(), flavour.clone()); + } + + if let Some(ref settings) = snapshot.affine_settings { + out.insert( + KEY_AFFINE_SETTINGS.to_string(), + serde_json::to_string(settings).map_err(|err| LegacyImportError::MalformedJson { + key: KEY_AFFINE_SETTINGS.to_string(), + message: err.to_string(), + })?, + ); + } + + if let Some(ref theme) = snapshot.theme { + out.insert(KEY_THEME.to_string(), theme.clone()); + } + + Ok(out) +} + +/// Compute the minimal deterministic `localStorage` changeset between `before` and `after`. +/// +/// Mirrors `0.27.5` `setLocalWorkspaceIds([])` and `ServerListStore.removeServer`: clearing all +/// local workspaces or self-hosted servers writes `"[]"` rather than removing the key. +pub fn build_writeback_changeset( + before: &LegacyLocalStorageSnapshot, + after: &LegacyLocalStorageSnapshot, +) -> Result, LegacyImportError> { + let prev = serialize_snapshot_entries(before)?; + let mut effective_after = after.clone(); + if prev.contains_key(KEY_LOCAL_WORKSPACE_LIST) + && !effective_after + .preserved_raw_entries + .contains_key(KEY_LOCAL_WORKSPACE_LIST) + { + effective_after.has_local_workspace_key = true; + } + if prev.contains_key(KEY_SERVER_LIST) + && !effective_after + .preserved_raw_entries + .contains_key(KEY_SERVER_LIST) + { + effective_after.has_server_list_key = true; + } + let next = serialize_snapshot_entries(&effective_after)?; + + let mut all_keys = BTreeSet::new(); + all_keys.extend(prev.keys().cloned()); + all_keys.extend(next.keys().cloned()); + + let mut mutations = Vec::new(); + for key in all_keys { + match (prev.get(&key), next.get(&key)) { + (Some(old_val), Some(new_val)) if old_val == new_val => {} + (_, Some(new_val)) => mutations.push(LocalStorageMutation::Set { + key, + value: new_val.clone(), + }), + (Some(_), None) => mutations.push(LocalStorageMutation::Remove { key }), + (None, None) => {} + } + } + Ok(mutations) +} + +/// Verify that every mutation in `expected` matches the observed `readback` entries. +pub fn verify_writeback_readback( + expected: &[LocalStorageMutation], + readback: &BTreeMap, +) -> WritebackReadbackReport { + let mut report = WritebackReadbackReport::default(); + for mutation in expected { + match mutation { + LocalStorageMutation::Set { key, value } => { + if readback.get(key) == Some(value) { + report.verified_keys.push(key.clone()); + } else { + report.mismatched_keys.push(key.clone()); + } + } + LocalStorageMutation::Remove { key } => { + if !readback.contains_key(key) { + report.verified_keys.push(key.clone()); + } else { + report.mismatched_keys.push(key.clone()); + } + } + } + } + report +}