Skip to main content

Crate coven

Crate coven 

Source
Expand description

coven — host integration for end-to-end encrypted, multi-writer, bring-your-own-storage SQLite sync. The engine lives in coven-core; this crate wires it to the filesystem, the platform keyring, and cloud providers, and re-exports the curated host API.

The public API is exactly the crate-root re-exports below. The engine’s implementation modules are pub(crate), so a host reaches coven only through these names — never through coven::sync::… or coven::blob::…. In particular the sync driver is private: it starts only through CovenHandle::connect_sync, which holds the lifecycle lock, so a host cannot drive the loop out from under the handle.

// `sync` is a private module; the sync driver is unreachable from outside.
let _ = coven::sync::sync_manager::SyncManager::start_sync;

Re-exports§

pub use coven_core::rusqlite;

Structs§

ActivatedContinuation
Exact durable state required to continue an activated Store device.
AffectedRow
One table/primary-key identity affected by the shared part of a write.
BlobBody
A blob as a sized stream of already-final bytes: sealed chunks for an encrypted home, plaintext for a browsable one. Encryption-agnostic and concrete (no dyn Stream). next_part hands the bytes to a streaming upload in bounded windows so a large blob is never held whole in memory; the only collect is the single-request path for blobs at or below a provider’s multipart threshold.
BlobDecl
Where a blob-bearing table’s blob columns live, declared by the host so coven can derive every blob a row references without a runtime callback. Resolved against the live schema into a [crate::blob::decl::BlobDecls] each cycle.
BlobRef
A blob a row references: its cloud identity, encryption scope, and the two declared properties (provenance + fill). coven derives it from the row’s declared columns (crate::sync::session::BlobDecl) via [decl::BlobDecls]. Where its bytes live depends on its locality and provenance: a user-provided Local blob is the user’s file at its path; a host-provided Local blob is in coven’s local store (storage/local/<namespace>/<id>); a Remote blob’s device-local copy is a cache copy (storage/pinned/<namespace>/<id> / storage/cache/<namespace>/<id>, built from the validated namespace + id — see [cache]).
BlobStore
Storage implementation for managed local storage.
CircleId
A self-certifying 128-bit circle identity encoded as canonical lowercase base32.
CircleInfo
CircleOperationInfo
CloudHeadVersion
Opaque provider revision returned by an authoritative coordination read.
CloudHomeConfig
The cloud home: which provider backs sync and its per-provider settings. One cohesive unit — connecting picks a provider and fills its fields; disconnecting resets the whole thing to default.
CloudKitAcceptedShare
CloudKitAcceptedShareRecord
CloudKitAtomicCreateBatch
CloudKitProviderIdentity
CloudKitRecordCreate
CloudKitRecordVersion
CloudKitShare
CloudVersionedHead
Config
Sync + storage configuration for one store.
Coven
CovenBuilder
CovenConfig
CovenHandle
The handle over one coven store.
CovenReadHandle
A read-only handle over one coven store, for a same-store secondary reader.
CrossPrincipalProbeReceipt
DeviceActivity
Activity summary for a single remote device.
DeviceJoinAbandonment
DeviceJoinActivation
DeviceJoinAttemptId
DeviceJoinAttemptRef
DeviceJoinCancellation
DeviceJoinCleanupActivation
DeviceJoinCleanupReceipt
DeviceJoinClient
A joining device’s local half of the four-transfer admission exchange. The journal lives outside the incomplete store directory, so every method can be retried after process termination without losing its exact predecessor.
DeviceJoinJournalDatabase
Durable role journal. Each row stores a closed progress value; SQLite’s compare-and-swap update rejects stale or skipped transitions.
DeviceJoinJournalRecord
DeviceJoinOffer
DeviceJoinProducerWriteRevocation
DeviceJoinReadiness
DeviceProviderAccessRequest
DeviceProviderAdmissionApproval
DeviceProviderAdmissionCompletion
DeviceRegistrationRequest
EncryptionService
Manages encryption keys and provides XChaCha20-Poly1305 encryption/decryption
ExactSlotProbeReceipt
FixedClock
Every now() returns the same instant.
HeldStorePosition
Hlc
Hybrid Logical Clock.
InMemoryCloudHome
In-memory CloudHome backed by a HashMap. Clone shares one backing store, so clones act as separate devices reading and writing the same cloud bucket, and a test can keep its own handle for direct at-rest assertions while each device owns a Box<dyn CloudHome> clone.
JoinedStore
JoinerJoinClosure
MasterKeyring
A store’s master key material: every key it holds. This is the value custody implementations store, unlock, and re-protect — never a cipher. coven builds the EncryptionService cipher from it internally; custody never touches cipher machinery.
MemberInfo
MembershipCoord
Migration
One ordered step in the host’s synced-schema ladder.
OAuthClientCreds
OAuth client credentials for one provider — the consuming app’s registered OAuth application. coven ships no app credentials of its own; the host registers them at startup via set_oauth_client_creds.
OAuthClientCredsConflict
Registering OAuth client credentials a second time with values that differ from the first registration — a startup contradiction the host must resolve, not a value coven may silently pick between.
OAuthTokens
Tokens returned from an OAuth authorization or refresh.
ObjectHash
ObjectSlot
Exact logical and physical location persisted before an immutable write.
OwnerRecoveryAuthority
Exact Owner grant and recovery-stream authority used to create a replacement device when no activated device continuation survives.
Passphrase
A memorized secret that wraps a payload under Argon2id. Held zeroizing — the whole struct is cleared on drop, so no copy of the passphrase outlives it.
PendingBranch
PendingBranchId
Stable identity of the one ordered provisional Serial branch.
PendingWrite
Durable write information returned by CovenHandle::pending_writes.
ProviderAdminGrantId
ProviderAdminGrantRecord
ProviderAdminJoinClosure
ProviderAdminState
ProviderCapabilityProof
ProviderDeviceBinding
ProviderProbeId
ProviderReadyDeviceBootstrap
ProvisionalDeviceBootstrap
ResolvedProviderBinding
RestoreCode
Everything needed to restore a store from cloud storage.
RestoreSource
Cloud provider source for restore: the join info a restore code carries plus the extras it can’t (RestoreCode omits OAuth tokens because they expire — the user re-authenticates on restore — and holds no live CloudKit driver).
RowBlobRef
One exact blob-bearing row version. A reference becomes stale when the live row stamp or any declared blob value changes.
RowChange
One row change extracted from a changeset.
S3CloudHome
S3-backed cloud home.
SequentialIdProvider
Deterministic but unique: "{prefix}-0", "{prefix}-1", … Preserves the per-entity uniqueness invariant while being reproducible across runs.
SerialCoordinationProbeReceipt
SerializationConflict
A Serial branch ran against base, but storage now commits current.
SqlContext
Host SQL inside one journaled write transaction.
SteppingClock
Advances a fixed delta per now() call: the first call returns start, the next start + step, and so on. For tests that assert ordering.
StoreBatchCommitRef
Exact identity of one signed Store commit candidate.
StoreDir
Typed wrapper for a store directory path.
StoreKeys
One store’s key material: the encryption master key, cloud-home credentials, and OAuth tokens, each stored under a store-scoped keyring account ({base}:{store_id}). The store’s signing identity is not here — it goes through crate::identity_custody::IdentityCustody, the same way the master key goes through crate::custody::KeyCustody.
StoreLayout
The host’s on-disk layout for stores: where they live and what the database file is called. One rule shared by create, open, join, and restore, so a host that wants libraries/<id>/library.db instead of coven’s default stores/<id>/store.db names it once here rather than each flow hardwiring (or working around) coven’s own choice.
SyncLoopAlerts
SyncLoopSuccess
SyncedTable
A table that participates in changeset sync, declared at startup by the host and passed to [crate::CovenBuilder::synced_tables].
SystemClock
Production clock: real wall time.
Timestamp
A parsed HLC timestamp.
UpdatedAtStamper
A cloneable handle that mints _updated_at register values from a shared Hlc — the register-stamping capability, sliced off the whole [crate::sync::sync_manager::SyncManager].
UserKeypair
Ed25519 keypair for signing changesets and membership changes. The same seed can derive an X25519 keypair for key wrapping.
UuidProvider
Production provider: random v4 UUIDs.
WriteBatch
WriteId
Stable identity of one successfully committed host transaction.
WriteReceipt
Result of one successful host transaction and its durable publication identity.

Enums§

Audience
The one audience a synced row belongs to.
AwsPrincipal
BlobCacheError
Why a blob-cache operation failed.
BlobReplacement
A blob’s replacement story: whether the row carrying it may ever be repointed at a different blob. Orthogonal to Provenance and CacheFill; a blob declares all three.
BlobScope
Which key encrypts a blob, as a host names it on a BlobRef.
BootstrapError
Why joining or restoring a store failed. Both are the same operation — bootstrap a store from the cloud — differing only in their entry data (an invite that wraps the store key vs a restore code that carries the bucket credentials), so they share one error shape rather than two that duplicate most of their variants and then have to map between each other.
CacheFill
A blob’s Remote story: how a device gets the bytes once the blob is Remote. A cache-mechanism setting — it describes a blob only while Remote — that applies to ANY blob regardless of Provenance. Orthogonal to provenance; a blob declares both.
ChangeOp
The operation type for a changeset entry.
CircleOperationState
CircleRole
CloudAccessOutcome
CloudAccessState
CloudCipher
How a cloud home protects its objects at rest. An Encrypted home seals every object under the store key (the default); a Plaintext home stores objects in the clear so the bucket is browsable, and drops the .enc suffix.
CloudFileReadError
CloudHeadCreateError
CloudHeadReplaceError
CloudHomeCredentials
Credentials for the cloud home, stored as a single JSON keyring entry.
CloudHomeError
Errors from raw cloud storage operations.
CloudHomeJoinInfo
Information needed to join a cloud home from another device.
CloudKitEnvironment
CloudKitScope
CloudKitShareAcceptance
CloudKitSharePermission
CloudProvider
Cloud home provider selection.
ConfigError
Configuration errors.
CovenError
CustomS3ExactSlots
Local operator assertion required before a custom S3 endpoint may provide exact protocol and blob slots. This is local configuration and is never accepted from invite or restore data.
CustomS3Serial
Operator assertion required before a custom S3 endpoint may coordinate a serial Store. AWS S3 itself is selected by leaving s3_endpoint absent.
DbError
An error from the owned database.
DeviceJoinAction
DeviceJoinAuthorization
DeviceJoinCleanupProgress
DeviceJoinError
DeviceJoinProducer
DeviceJoinRole
DeviceJoinStatus
DeviceProviderAdmission
DeviceProviderReadiness
EncryptionError
GoogleDriveCorpus
HeldStoreCoordinate
HeldStorePositionReason
HomeStorage
How a cloud home stores its objects: opaque (encrypted, unreadable to anyone who can read the bucket) or browsable (stored in the clear at readable paths). This is not about who can reach the bucket — the storage provider’s own access control applies either way; it is about whether what they store is legible. The host picks it once, when it creates the home; it cannot change later (it determines how every object is written). One choice drives two mechanisms together:
IdentityCustody
How a store’s device-signing identity is protected. Selected on the builder, resolved once per store — the identity sibling of crate::custody::KeyCustody, same shape.
IdentityError
Why a CovenHandle initialize_identity call failed.
JoinCodeError
JoinerJoinTerminal
KeyCustody
How a store’s master key is protected. The builder accepts this and never sees a cipher again — coven resolves the selection into a MasterKeyCustody and builds every cipher from what it supplies.
KeyError
MakeLocalError
Why a make_local could not complete.
MakeRemoteError
Why a make_remote (or its cancel) could not be started.
MasterKeyError
Why a CovenHandle master-key lifecycle call (initialize_master_key, import_master_key) failed.
MemberRole
MigrationStep
How a migration applies its change to the synced schema.
OAuthClientCredsError
A provider’s OAuth client credentials were requested before the host registered them via set_oauth_client_creds: either no registration ran at all, or the registered map has no entry for this provider. Surfaced at the OAuth-flow boundary so a mis-configured host gets a typed error naming the startup step, not an empty client_id that fails deep inside a provider flow.
OAuthError
PhysicalObjectLocator
Provider-specific physical address for a caller-reserved immutable slot.
Provenance
A blob’s Local story: where its bytes live while the blob is Local, and whether bringing it back from Remote needs a destination path. Orthogonal to CacheFill (the Remote story) — a blob declares both.
ProviderAdminChange
ProviderAdminJoinTerminal
ProviderAdminMembershipChange
ProviderPrincipalId
PublishedPosition
Exact policy-specific position that made a write visible to peers.
RestoreAuthority
The closed authority a restore operation may exercise.
RowBlobAuthority
The authority state that determines where one row version’s blob lives. A remote-audience blob remains PendingRemote while its verified plaintext is local and no cloud object has been created; Remote carries the exact package authority needed to open its committed object.
RowIdentity
How (table, id) names one logical row across every device.
S3EndpointBinding
SealError
Why sealing or opening a host’s app-data failed.
StoreCommitCoord
Closed coordinate of one Store commit under the Store’s signed policy.
StoreProviderBinding
Provider namespace/corpus facts signed once by the Store root.
SyncError
SyncLoopStatus
A sync-loop status the host renders. The loop reports provider reachability, publication, and one terminal status. Conflict and Blocked are successful storage cycles with unresolved durable writes; Synchronized has none, while Failed means the cycle itself failed. The in-progress marker is the variant itself, so there is no separate “syncing” flag.
WriteBlock
A semantic write fault. Retrying transport cannot change this result.
WritePolicy
Store-wide ordering policy selected by the application and signed into the Store protocol root.
WriteResolution
WriteStatus
Current durable state of one host transaction.

Constants§

CHUNK_SIZE
64KB plaintext chunks

Traits§

BlobTransitionObserver
Notified about coven’s blob transitions, for host-specific bookkeeping and UI: per-blob upload progress while a make_remote uploads, per-blob materialize progress while a make_local copies files back, and a completion hook per direction the host turns into its own UI event.
Clock
Wall-clock source. Returns a full DateTime<Utc>; callers derive .timestamp() / .to_rfc3339() as they need.
CloudHome
CloudKitOps
Synchronous interface for raw CloudKit record operations. Implemented by a host bridge to its platform CloudKit driver. Methods block the calling thread while CloudKit async operations complete.
DeviceIdentityCustody
A device’s signing identity’s custody FOR ONE STORE: who unlocks it, where a newly established one is written, and how it is removed. The signing-key sibling of MasterKeyCustody, same three-method shape and the same per-store selection, over UserKeypair instead of a store’s master keyring.
DeviceProviderAccessAdministrator
ExactSlotStorage
Low-level cloud storage. Implementations handle a single store.
IdProvider
Identifier source. Yields a fresh unique id per call.
MasterKeyCustody
A store’s master keyring’s custody: who unlocks it, where a newly established or rotated one is written, and how it is removed. Implemented once per protection policy (the OS keyring, a passphrase-wrapped file, an in-memory session value, or a host’s own).
PartSink
The one per-provider streaming-upload surface: a session that accepts ordered parts and commits. The central [write_blob] driver opens one of these for a large blob and pumps BlobBody parts into it — no backend writes its own upload loop, collect, or progress call.

Functions§

abandon_join_request
Abandon a join request this device generated but never completed — removes the pending identity generate_join_request minted for it. Ok whether or not one was still pending.
authorize_provider
Run an OAuth authorization flow for the given cloud provider (desktop: opens a browser and captures the redirect on coven’s localhost callback server).
build_authorize_request_for_provider
Build an OAuth authorization request for provider redirecting to redirect_uri, for hosts that capture the redirect themselves (a mobile OS auth session). Pair the returned request, callback code, callback state, and same redirect_uri with exchange_code_for_provider.
create_cloud_home
Build a CloudHome from config, surfacing a missing or malformed provider configuration as a non-retryable CloudHomeError::Configuration so a host can tell “fix your settings” apart from a transient failure it should keep retrying.
decode_invite_code_info
Decode an invite code and return UI-ready info.
decode_join_request
decode_restore_code_info
Decode a restore code and return UI-ready info.
entry_for_test
Test-only: reaches [entry_for] across the crate boundary. Exists so an integration test can install a specific keyring store and assert which entry-construction path the chokepoint took, without re-implementing its dispatch.
exchange_code_for_provider
Exchange an authorization code captured by the host for provider’s tokens. redirect_uri, request, and callback_state must match the originating build_authorize_request_for_provider call.
fetch_account_email
Fetch the email of the account tokens authenticated, for the given OAuth provider. The joining device calls this right after authenticating so the approver can share the OAuth folder to its provider-account email.
generate_join_request
Build a join request carrying a freshly minted pending identity (see [crate::keys::mint_pending_identity]) — the joiner sends its public key before it learns which store the invite names, so the keypair is generated now and held under a pending slot keyed by that public key. Completing the join with crate::DeviceJoinClient (constructed with this same code) promotes it into the joined store’s own identity; crate::abandon_join_request discards it if the request is abandoned instead.
generate_restore_code
Build a RestoreCode from config and custody, then encode it.
keyring_service
The registered keyring service name. Err when the host never ran the startup set_keyring_service call — surfaced so a mis-ordered host gets a typed error, not a panic deep inside a key operation.
restore_from_cloud
Restore a store from cloud storage.
restore_from_code
Restore a store from a restore code string.
rewrap_passphrase_custody
Re-wrap a store’s passphrase-protected master keyring under a new passphrase — the store-side half of covenpass’s “change passphrase”. The <store_dir>/master.keyring envelope is decrypted with old and re-sealed under new (fresh salt and nonce). Errors if nothing is established there (KeyError::Persistence) or if old is wrong (KeyError::Crypto), leaving the existing file untouched on either failure. After it returns, the store’s custody is re-opened under new.
rewrap_passphrase_identity_custody
Re-wrap a store’s passphrase-protected signing identity under a new passphrase — the identity half of a host’s “change passphrase”, the sibling of crate::custody::rewrap_passphrase_custody. The store’s identity.envelope is decrypted with old and re-sealed under new (fresh salt and nonce). Errors if nothing is established there (KeyError::Persistence) or if old is wrong (KeyError::Crypto), leaving the existing file untouched on either failure. After it returns, the identity is re-opened under new.
set_keyring_service
Register the process-wide keyring: the service name every entry is stored under, and the platform keyring store that backs it. Both are one-time startup registration and must run before any key operation. The store is installed before the name is recorded, so a failed installation leaves no registration behind. Re-registering the same name is a no-op; a different name is a startup contradiction and fails. Fails with KeyError::UnsupportedKeyringPlatform on a target with no bundled store.
set_oauth_client_creds
Register the host’s OAuth client credentials, keyed by provider name ("google_drive", "dropbox", "onedrive"). Call once at startup, before any OAuth flow. Providers absent from the map get empty credentials. Re-registering the same map is a no-op; a differing map is a startup contradiction and returns OAuthClientCredsConflict.
sign_in_dropbox
Dropbox OAuth sign-in: authorize, create the store folder, save tokens to the keyring. Returns the folder path for the host to persist in its config.
sign_in_google_drive
Google Drive OAuth sign-in: authorize, find/create the store folder, save tokens to the keyring. Returns the folder id for the host to persist in its own config (coven never writes the host’s config).
sign_in_onedrive
OneDrive OAuth sign-in: authorize, resolve the default drive, create the app folder, save tokens to the keyring. Returns (drive_id, folder_id) for the host to persist in its config.
write_cloud_object_stream

Type Aliases§

BoxPartSink
A boxed PartSink borrowing its home for 'a.
ClockRef
Shared handle to a clock. Held by Clone types (CovenHandle, CovenReadHandle) so they clone the handle, not the implementation.
CloudObjectStream
CovenResult
IdRef
Shared handle to an id provider. Held by Clone types that need to share one id source, so they clone the handle, not the implementation.
StoreSerialPredecessor
UploadProgress
Reports how many bytes of a write have reached the backend so far. Called with the cumulative byte count as the body uploads; backends that can’t observe sub-call progress call it once at the end with the full size. The count is of the bytes handed to write (the encrypted payload).