Skip to main content

Workspace

Struct Workspace 

Source
pub struct Workspace { /* private fields */ }
Expand description

An offline Capsule workspace over a client library directory.

Implementations§

Source§

impl Workspace

Source

pub fn create_album(&mut self, name: &str) -> Result<Uuid, LifecycleError>

Create a container album: mint AMK_v1 + write-tier + admin keys and an attested authority, then persist the album keystore. Returns the new album id.

Fallible because the keys only exist once they are on disk: a workspace that reports an album it could not persist would hand the caller an album whose assets become undecryptable at the next close.

Source

pub fn create_album_with_id( &mut self, album_id: Uuid, name: &str, ) -> Result<Uuid, LifecycleError>

Create an album with a specific id (e.g. the derived default-album id).

Refuses with LifecycleError::AlbumExists if the workspace already holds key material for album_id: minting over it would discard the AMKs every existing asset in that album was encrypted under. Use ensure_album for resolve-or-create.

The name follows the label rule, as rename_album’s does, so creation never accepts a name a rename would refuse: LifecycleError::InvalidLabel before any key is minted.

Source

pub fn ensure_album( &mut self, album_id: Uuid, name: &str, ) -> Result<Uuid, LifecycleError>

Resolve album_id to the album this workspace already holds, or create it under name.

This is the verb a client’s “default album” wiring wants: minting a fresh Imports album on every run would leave a reopened library unable to decrypt or extend its own prior imports.

Source

pub fn has_album(&self, album_id: &Uuid) -> bool

Whether this workspace holds key material for album_id.

Source

pub fn albums(&self) -> Vec<(Uuid, String)>

Every album this workspace holds key material for, as (album_id, name), in the album order (AlbumRecency): the album with the most recent visible, untrashed asset first; an empty album by its id’s creation time; ties by ascending id. Every client lists albums in this order rather than sorting its own.

Recency is read from the index on each call. Should that read fail, the albums are listed by creation time and id alone (logged at ERROR): a listing that is complete but coarser rather than one that loses albums.

Source

pub fn album_key_escrow( &self, album_id: &Uuid, ) -> Result<Vec<u8>, LifecycleError>

album_id’s server-side key escrow: the whole album — every epoch’s AMK, its signing seeds and its authority — sealed under the account master key ([PersistedAlbum::seal_escrow]). The bytes a client stores at PUT /v1/auth/escrow/albums/{album_id}; the master key never leaves the workspace.

§Errors

LifecycleError::NotFound for an album this workspace holds no keys for, and LifecycleError::AlbumStore when the album does not encode.

Source

pub fn plan_album_key_escrows( &self, escrowed: &BTreeMap<Uuid, Vec<u8>>, ) -> Result<AlbumKeyEscrowPlan, LifecycleError>

What to do about each album’s key escrow, given escrowed (album id → the escrow the server holds): which albums to store, and which this device’s epochs the server’s escrow does not cover and cannot safely be made to.

An escrow is never shrunk. An album is stored only when the server holds none for it, or holds one this album strictly extends ([EscrowCoverage::Superseded]). An escrow that holds epochs this device lacks ([EscrowCoverage::Behind], another device rotated further), or the same epochs plus a signing seed or authority this device lacks (a read-only device restored from a backup), is left alone and counts as covering this device’s epochs. One that disagrees with this device ([EscrowCoverage::Divergent]) or does not open under this master key ([EscrowCoverage::Unreadable]) is left alone too, and the album is reported uncovered: replacing it could lose epochs a recovery needs, so the caller holds the album’s assets back instead.

Network-free. A client fetches what the server holds, asks this, and stores album_key_escrow for each album in to_store — before any asset of that album or epoch leaves the device, so the server never holds ciphertext whose key it does not also hold sealed under the master key.

§Errors

LifecycleError::AlbumStore when the live album state cannot be captured.

Source

pub fn adopt_album_key_escrows( &mut self, escrowed: &[(Uuid, Vec<u8>)], ) -> Result<AdoptedAlbumKeys, LifecycleError>

Adopt the account’s escrowed albums into this library — the step capsule auth recover runs on a library it has just created from the master key, before anything calls ensure_album. An album recovered here is held as the device that escrowed it held it, so ensure_album resolves the derived default album rather than minting a fresh AMK under an id the account’s other devices already wrote under.

Every escrow is opened and every carried authority re-verified before the keystore is written, and an escrow that opens but is inconsistent refuses the whole adoption with nothing persisted — a library that silently lacked one album would mint over it at the next ensure_album. An album this workspace already holds keeps its own keys and is counted in AdoptedAlbumKeys::already_held: a held content key is never swapped underneath the authority that attests it.

An escrow that does not open under this master key is skipped and counted in AdoptedAlbumKeys::unopenable. It is sealed under another master key — the escrow was later replaced from another library of the account — and its albums are that key’s, never this one’s: their ids cannot collide with this master key’s derived default album, and refusing them would lock the account out of recovery for good, since nothing can remove them. Skipping one costs no more than a server omitting it from the listing would.

§Errors

LifecycleError::AlbumStore when an escrow opens but is not an album key escrow, holds another album than the id it was served under, or carries an authority that does not re-verify, or when the keystore cannot be written.

Source

pub fn rotate_epoch(&mut self, album_id: Uuid) -> Result<u32, LifecycleError>

Rotate album_id to a fresh epoch: mint AMK_v{n+1} and a new write-tier key, have the album admin attest the new epoch, and advance the current epoch — the design’s “AMK bump + write-tier rotation are one commit” atomicity. The admin key (the ledger root) is stable across epochs, and existing assets stay verifiable under their original epoch. Returns the new epoch. Membership changes / the MLS Welcome flow remain deferred (see SLICES.md).

Source§

impl Workspace

Source

pub fn album_doc(&self, album_id: &Uuid) -> Result<AlbumDocV1, LifecycleError>

album_id’s label record: the persisted one, or — for an album that predates the record — one holding the keystore’s name under the legacy stamp.

§Errors

LifecycleError::NotFound for an album this workspace holds no keys for; LifecycleError::UnverifiedDocument when the persisted record does not verify.

Source

pub fn rename_album( &mut self, album_id: Uuid, name: &str, ) -> Result<(), LifecycleError>

Rename an album: a stamped write to its record’s name register, so concurrent renames on two devices converge on the later one. The name follows the label rule.

Source

pub fn add_album_label( &mut self, album_id: Uuid, label: &str, ) -> Result<(), LifecycleError>

Add a label to an album.

Source

pub fn remove_album_label( &mut self, album_id: Uuid, label: &str, ) -> Result<usize, LifecycleError>

Remove a label from an album: every add of it this device has observed. Returns how many adds were removed (0 when the album does not carry the label).

Source

pub fn album_labels( &self, album_id: &Uuid, ) -> Result<BTreeSet<String>, LifecycleError>

The album’s current labels.

Source

pub fn seal_album_doc(&self, album_id: &Uuid) -> Result<Vec<u8>, LifecycleError>

Seal the album’s record under its current-epoch AMK — the bytes that travel to the album’s other members and into a backup.

Source

pub fn apply_remote_album_doc( &mut self, album_id: Uuid, wire: &[u8], ) -> Result<(), LifecycleError>

Open a sealed record another device of this account sent for album_id, verify it under this account’s identity key, and merge it into the local one. Every epoch this workspace holds is tried, newest first, since the sender may be an epoch ahead or behind.

§Errors

LifecycleError::Document when no held AMK opens it or it does not decode; LifecycleError::UnverifiedDocument when it does not verify. Nothing is merged.

Source§

impl Workspace

Source

pub fn escrow_master_key( &self, recovery_secret: &[u8], tier: DeviceTier, ) -> Result<WrappedSecret, LifecycleError>

Wrap this account’s master key under recovery_secret into the escrow blob a client stores server-side (PUT /backup/escrow; driven from the SDK by capsule_sdk::recovery).

The master key never leaves this workspace: the raw bytes are handed straight to [backup::escrow_master_key] and what comes back out is the passphrase-wrapped blob. That is the whole reason this verb lives here rather than a master_key_bytes() accessor — an FFI surface that could read the master key would be a far larger hazard than one that can only mint an escrow of it.

recovery_secret is the ≥128-bit secret shown to the user exactly once (capsule_sdk::recovery::MintedSecret); tier selects the Argon2id cost, which is recorded in the blob so any device can unwrap it.

Source

pub fn sealed_identity(&self) -> Vec<u8> ⓘ

This account’s user identity key sealed under its master key — the blob a new device passes to create_from_master beside the recovered master key, so it opens as the same account under the same identity the server has pinned.

Like escrow_master_key, the private key never leaves the workspace in the clear: only the holder of the master key can open what this returns.

Source

pub fn verify_escrow( &self, blob: &WrappedSecret, recovery_secret: &[u8], ) -> RecoveryVerdict

Local, network-free check that recovery_secret still opens blob to this device’s master key — the derived-tag compare that backs the recovery verification cadence.

Delegates wholesale to [backup::verify_recovery_secret]; nothing is compared here, and no key bytes are surfaced either way. The stale-cache rule (refresh the blob once before recording a genuine failure) belongs to the networked caller, not to this predicate.

Source

pub fn local_heads(&self) -> BTreeMap<Uuid, Hash32>

The current provenance head hash for each managed asset (for backup reconciliation), and for each purged one the head of its kept chain, its final delete. A purged asset is held at that head, so an import or a peer offer never reads it as absent and re-applies an older copy as new.

Source

pub fn export_backup( &self, out: &Path, passphrase: &[u8], ) -> Result<(), LifecycleError>

Export every managed asset to a portable backup artifact.

The AMK ledger is wrapped at the production Argon2id cost ([backup::WRAP_PARAMS]) and there is no way to ask for another: this method takes no cost argument and [backup::export] takes none either, so no caller reachable from a production build can write a brute-forceable artifact.

Source

pub fn peer_export(&self) -> Result<PeerExport, LifecycleError>

Every managed asset as a backup artifact carries it, with the album key each one is sealed under: what a peer’s delta artifact is cut from (capsule_sdk::peering::DeltaExport). The same assets export_backup writes, without the library-wide records (album authorities, label records, attestation pins) a peer delta does not carry.

§Errors

When an asset’s upload bundle cannot be rebuilt or its evidence logs cannot be read: a delta silently missing an asset is not offered.

Source

pub fn exporter_verifying_key(&self) -> HybridVerifyingKey

This device’s signing public key (the exporter key a peer verifies a backup against).

Source

pub fn import_backup( &mut self, archive: &Path, passphrase: &[u8], exporter_pub: &HybridVerifyingKey, ) -> Result<usize, LifecycleError>

Open a backup artifact and restore (commit) its assets into this workspace, writing decrypted plaintext + provenance into the library. exporter_pub is the exporting device’s signing key (resolved from the user’s device directory). Returns the count of assets added.

Source

pub fn apply_peer_restored( &mut self, restored: &RestoredAsset, ) -> Result<(), LifecycleError>

Write one asset a peer’s delta artifact restored (capsule_sdk::peering::PeerRestore’s applied) into this library: a new asset, or a forward update of one this library holds, whose chain extends the local head.

The asset’s album, and the epoch its head manifest is sealed under, must already be held: a peer delta carries no album authority or label record, so an asset of an album this library does not hold would be one it could neither push nor export. A forward update keeps the held asset’s media path (its extension and date bucket) and stack placement, so the original is rewritten in place, and keeps any evidence log this device already holds over the peer’s copy. The sidecar written is the one the peer’s sealed metadata blob carries, opened and verified, so the peer’s metadata arrives and none of what was held before its head is lost.

§Errors

LifecycleError::Purged for an asset this workspace purged, LifecycleError::NotFound when the album or its epoch is not held, and LifecycleError::RestoredMetadata when the sealed metadata does not stand (nothing is written in either case), or the I/O, chain or index failure that stopped the write.

Source§

impl Workspace

The public (fragment) half of an issued upload link, if this workspace issued it. Exposed for tests and clients rebuilding the .../u/{opaque-id}#{drop_pubkey} URL.

The opaque URL-path id of an issued upload link (the .../u/{opaque-id} component).

The optional Argon2id write-abuse verifier of an issued link — the record the serve path consults to gate a drop-session on passphrase possession.

RFC 3339 issuance time of an issued upload link.

Whether an issued upload link is still live at now (not revoked, not past expiry).

Source

pub fn receive_drop( &mut self, via_link: UploadLinkId, sealed: SealedDrop, ) -> Result<DropId, DropError>

Stage a guest’s [SealedDrop] into this owner’s inbox, modeling the server’s stage step so the offline core can drive the full seal → stage → adopt path. Refuses a drop through an unknown or revoked link (a fail-closed stand-in for the serve path’s cap/quota checks). Returns the new inbox drop id.

Source§

impl Workspace

Source

pub fn enrollment_initiator_keys(&self) -> InitiatorKeys

What this device advertises as the initiator of a cross-device add, with a nonce freshly drawn by this call. Call it once per ceremony and keep the result: it is both what A sends and what A computes its safety code over.

Source

pub fn enrollment_enrollee_keys(&self) -> EnrolleeKeys

What this device advertises as the enrollee of a cross-device add: the signing key it actually signs with (a hardware signer’s, when one was supplied), its DEK, and a nonce freshly drawn by this call. Call it once per ceremony and keep the result: B commits to, reveals, and computes its safety code over this one bundle.

Source

pub fn cross_sign_device( &mut self, entry: DeviceEntry, ) -> Result<DeviceDirectory, LifecycleError>

Cross-sign a new device into this account’s directory: append entry at the next directory_version, re-sign under the user IK, adopt it as this workspace’s directory, and return it for publication and for relaying to the new device.

Call this only after the safety codes matched. Refused with LifecycleError::Directory, leaving the directory unchanged, when the entry’s id or signing key is already listed or the entry is revoked.

The re-signed directory is persisted beside the account before it is adopted, so open restores it and the next directory this device signs builds on it; a failed write is a LifecycleError::Io and also leaves the directory unchanged. The caller still publishes the returned directory.

Source§

impl Workspace

Source

pub fn create_album_group( &mut self, album_id: Uuid, group_name: &str, home_server: &str, ) -> Result<AlbumGroupInvite, LifecycleError>

Create an aggregated album by minting a fresh group_id and writing this workspace’s own album_id constituent’s [AlbumGroupAssertion] (device-signed, stamped for LWW convergence). Returns the [AlbumGroupInvite] the creator hands to contributors — the group_id plus the creator’s own constituent as a sibling hint. The interactive membership ceremony is not performed here; this produces the invite data. home_server is this constituent’s origin identity.

Source

pub fn join_album_group( &mut self, album_id: Uuid, invite: &AlbumGroupInvite, home_server: &str, ) -> Result<(), LifecycleError>

Join an existing group as a contributor: write this workspace’s own album_id constituent’s assertion (asserting the invite’s group_id, seeded with the invite’s siblings + this constituent), device-signed. Rides the existing album invite as data; the membership ceremony itself is not performed here. home_server is this constituent’s origin.

Source

pub fn rename_album_group( &mut self, album_id: Uuid, new_name: &str, ) -> Result<(), LifecycleError>

LWW-rename the group on this workspace’s own album_id constituent (a fresh stamped write), re-signing the assertion. Concurrent renames on sibling constituents converge by LWW.

Source

pub fn merge_album_group_assertion( &mut self, their_album_id: Uuid, remote: &AlbumGroupAssertion, ) -> bool

Fold a peer constituent’s assertion (read from the feed for their_album_id) into the reconciled local view: LWW-converges the group name and unions the advisory hints. If the local user already holds a reconciled assertion for that album it merges in place; otherwise the peer assertion is adopted verbatim. A peer assertion for a different group than an existing local one is refused (no cross-talk). Returns whether it was applied.

Source

pub fn leave_album_group( &mut self, album_id: Uuid, unshare: bool, ) -> Result<bool, LifecycleError>

Leave the group from this workspace’s album_id constituent: remove the assertion, so the constituent drops out of every participant’s aggregate on their next sync. Optionally unshare (bump the AMK epoch + rotate the write tier) to cut read access to the historical photos too — the honest limitation being that this only stops others from seeing your photos, never removes anyone else’s constituent (a true group kick is the v2 problem). Returns whether an assertion was present to remove.

Source

pub fn album_group_assertion( &self, album_id: &Uuid, ) -> Option<&AlbumGroupAssertion>

The reconciled group assertion for album_id, if the workspace holds one.

Source

pub fn seal_album_group_op( &self, album_id: &Uuid, ) -> Result<Vec<u8>, LifecycleError>

Seal album_id’s current group assertion into the AMK-sealed operation the op path carries — the wire bytes a server stores. AEAD-encrypted under the album’s current-epoch AMK, so the server (and any non-member) learns nothing of the group: the plaintext group_id/name never appears in these bytes. This is the write half of the op path.

Source

pub fn open_album_group_op( &self, album_id: &Uuid, wire: &[u8], ) -> Result<AlbumGroupAssertion, LifecycleError>

Open an AMK-sealed group-assertion operation for album_id — the read half. Requires the album’s AMK: a non-member (no AMK) physically cannot decrypt, which is exactly why a stranger’s assertion can never inject itself into the view. Restricted to the current epoch.

Source

pub fn local_constituent( &self, album_id: Uuid, home_server: &str, reachable: bool, blocked: bool, ) -> Constituent

Build the [Constituent] view of one of this workspace’s own albums for the aggregate renderer: it is a member (holds the AMK), carries its reconciled assertion (if any), and contributes its non-trashed assets keyed by capture time. reachable / blocked are the per-origin flags the caller supplies (own albums are normally reachable + unblocked).

Source§

impl Workspace

Source

pub fn import_asset( &mut self, album_id: Uuid, src: &Path, ) -> Result<Uuid, LifecycleError>

Import a file into album_id: encrypt, build the signed create manifest + provenance, write the signed sidecar, and self-verify through verify_asset and the metadata↔manifest binding. Follows the sealing order so the manifest commits to the content address of the sidecar it seals, without a cycle. Returns the asset id.

Source

pub fn import_bytes( &mut self, album_id: Uuid, file_name: &str, bytes: &[u8], ) -> Result<Uuid, LifecycleError>

Import bytes already in memory into album_id under the file name file_name (consulted for its extension and nothing else), returning the asset id.

This is the entry point a platform app needs and the CLI does not: PhotoKit, the Android MediaStore, and a browser upload all hand over a byte buffer rather than a path the library may read at leisure. It stages those bytes in the library’s own scratch directory and drives the one signed write path — import_asset_with in Move mode, so the staged copy is released by the same durable-commit rule that releases any other moved source. There is no second sealing implementation here and none is wanted: the file key derivation, STREAM encryption, manifest, sidecar, provenance chain, and verify_asset self-check are byte-for-byte the path a file import takes.

EXIF is read back off the staged file, so a JPEG carrying capture time and GPS is scanned exactly as it would be on a file import.

Source

pub fn import_asset_with( &mut self, album_id: Uuid, src: &Path, opts: &SignedImportOptions, ) -> Result<SignedImport, LifecycleError>

As import_asset but with executor-supplied SignedImportOptions (Move-mode source release + stack placement). This is the single signed write path the import executor drives: every imported member lands as a signed SidecarV1 + manifest + append-only provenance, self-verified through verify_asset, and — when the still decodes — with a chromahash lqip in the sidecar and signed thumbnail derivatives on disk (the private prepare_still).

Returns a SignedImport: the asset id, the DerivativeStatus saying whether derivatives were generated and, if not, why, and the per-format deferral count. A format this build has no codec for still imports — the original is the backup, the thumbnail is a bonus — so the status is a report, never a rejection.

Source

pub fn import_asset_streaming( &mut self, album_id: Uuid, src: &Path, move_source: bool, stack: Option<StackMembership>, enrichment: Option<SidecarEnrichment>, ) -> Result<StreamedImport, LifecycleError>

Import a file on the signed path for a streaming import: identical to import_asset_with but with defer_source_release forced on, and returning the StreamedImport descriptor the streaming window drives its per-asset upload → verify → release step from. The local original (and any Move-mode source) is left in place — the streaming executor releases it only after the server’s durable verdict + custody receipt clear the release gate.

enrichment carries the folded third-party exporter metadata for this file exactly as import_asset_with takes it. It is a parameter and not a hard-wired None because the enrichment is written inside the signed sidecar: dropping it here would make a streamed Takeout import silently lossier than a bulk one, and the difference would be unrecoverable without re-importing.

Source

pub fn release_move_source<V: StorageVerifier + ?Sized>( &self, verifier: &V, asset_id: Uuid, src: &Path, ) -> Result<ReleaseDecision, LifecycleError>

Delete a Move-mode src that the library holds as asset_id — only on server custody (invariant 7), and only when both copies still read back as the signed original.

In order, and every step before the delete is a reason to keep the source:

  1. Read-back. The library’s copy and src are each read back and hashed; both must equal the hash the signed sidecar commits to. A library copy that is torn or missing, or a source edited since it was imported, is RetainReason::ReadBackMismatch — whatever the server says, deleting src could lose bytes nothing else holds.
  2. The gate. release_move_source over verifier for the asset’s required blobs (original ciphertext and sealed metadata blob), with a fresh verify_asset as the crypto half: a durable verdict and a verified custody receipt, or the source stays.

src that resolves to the asset’s own media file is never deleted.

§Errors

LifecycleError::NotFound when the workspace does not hold asset_id.

Source§

impl Workspace

Source

pub fn tag_add( &mut self, asset_id: &Uuid, tag: &str, ) -> Result<(), LifecycleError>

Add a user tag (OR-set) and emit a metadata-update provenance record.

The tag is an asset label and follows the one label rule ([normalize_label]: NFC, trimmed, 1–256 bytes); a tag the rule refuses is LifecycleError::InvalidLabel and nothing is appended. Tags already stored are read as they are: only new writes are normalized.

Source

pub fn tag_remove( &mut self, asset_id: &Uuid, tag: &str, ) -> Result<usize, LifecycleError>

Remove a user tag: every add of it this device has observed (OR-set observed-remove), as one metadata-update provenance record. Returns how many adds were removed; 0 means the asset does not carry the tag, and nothing is appended.

The tag is matched both exactly as given and after the label rule ([normalize_label]), so it names the label tag_add stored and also a tag stored before the rule existed, spelled as it is listed. A tag the rule refuses, and that the asset does not carry verbatim, is LifecycleError::InvalidLabel. An add this device has not yet seen (a concurrent add on another device) survives the merge, as an OR-set’s add-wins rule says.

Source

pub fn set_caption( &mut self, asset_id: &Uuid, caption: &str, ) -> Result<(), LifecycleError>

Set the caption (LWW register) and emit a metadata-update provenance record.

An empty caption clears it: the register is stamped with "", and the index projects that as no caption. The index row’s caption column is refreshed by the same append_lifecycle write, so the caption reads back from the catalog without a rebuild.

Source

pub fn set_capture_timestamp( &mut self, asset_id: &Uuid, capture: Timestamp, ) -> Result<(), LifecycleError>

Record the user’s capture time for the asset, as a new signed revision: one metadata-update record, with the sidecar re-signed and its sealed blob re-sealed under a fresh nonce, exactly as any other metadata edit lands.

The correction is written to the capture_timestamp_user LWW register, stamped with this device id and now, so concurrent corrections from two devices converge under the (ts, device_id) rule. The as-imported capture_timestamp is never overwritten: it stays what the original said, and the effective instant (SidecarV1::effective_capture_timestamp) is the correction.

The media bundle is not relocated. The media/{YYYY}/{YYYY-MM} directory is the shard fixed at import (AssetState::capture_utc) from the as-imported value, and the design treats bucket-vs-timestamp drift after a correction as expected rather than as a fault (Maintenance — Structural Validation). The index row follows the effective instant (asset_row_from_state), so the timeline shows the correction immediately rather than after a rebuild.

Takes a [Timestamp] rather than raw seconds so an out-of-range instant is unrepresentable at the call site instead of being clamped to the epoch here.

Source

pub fn correct_imported_capture_timestamp( &mut self, asset_id: &Uuid, capture: Timestamp, ) -> Result<(), LifecycleError>

Re-record the asset’s as-imported capture time, leaving any user correction alone.

Reserved for re-deriving what the import should have recorded from the original’s own metadata — the capsule repair capture-time pass, for libraries imported while the EXIF parser could not read DateTimeOriginal. It is not a user edit: a user’s correction goes through set_capture_timestamp, which this never displaces. One signed metadata-update; the bundle is not relocated.

Source

pub fn set_location( &mut self, asset_id: &Uuid, lat: f64, lon: f64, datum: GpsDatum, ) -> Result<(), LifecycleError>

Record the user’s location for the asset: a [GpsSource::Manual] fix in datum, written to the gps_user LWW register as one signed metadata-update, stamped with this device id and now so concurrent edits converge under the (ts, device_id) rule.

The as-imported gps is never overwritten; the effective location (SidecarV1::effective_gps) is this edit. The coordinate is stored verbatim in datum, never converted. A latitude outside [-90, 90], a longitude outside [-180, 180], or a non-finite value is LifecycleError::InvalidLocation and nothing is appended.

Source

pub fn clear_location(&mut self, asset_id: &Uuid) -> Result<(), LifecycleError>

Record that the asset has no location, as the user’s edit: a stamped None in the gps_user register. The as-imported gps stays in the sidecar, hidden from the effective view, so a later edit can restore it.

Source

pub fn add_ai_tags( &mut self, asset_id: &Uuid, tags: Vec<AiTag>, ) -> Result<(), LifecycleError>

Add AI-suggested tags to the asset’s tags_ai OR-set — a namespace structurally separate from tags_user, so an AI suggestion can never overwrite a user tag. Emits one metadata-update; each tag gets a fresh add_id (pre-issued from this device’s monotonic counter) so it can later be dismissed or promoted individually. A no-op (no record) if tags is empty. Each [AiTag] carries its producing (model_id, model_version) so a superseded suggestion is excluded by current_ai_tags.

Source

pub fn ai_tags( &self, asset_id: &Uuid, ) -> Result<Vec<(AddId, AiTag)>, LifecycleError>

The asset’s current AI tags paired with their add_ids — the surface a client uses to dismiss or promote a specific suggestion. Reads the signed sidecar OR-set (the source of truth), not a query cache.

Source

pub fn dismiss_ai_tag( &mut self, asset_id: &Uuid, add_id: AddId, ) -> Result<(), LifecycleError>

Dismiss an AI tag: an OR-set remove on tags_ai keyed by its add_id, emitting a metadata-update. Rejects an add_id never observed locally (a fabricated remove) rather than silently no-oping.

Source

pub fn promote_ai_tag( &mut self, asset_id: &Uuid, tag: &str, ) -> Result<(), LifecycleError>

Promote an AI tag to a user tag: copy its text into tags_user with a fresh user-scoped add_id, leaving the AI entry intact (still independently dismissable). An explicit, signed lifecycle operation — never automatic (ai § AI Output Containment).

The copied text becomes an asset label, so it passes through [normalize_label]: an AI tag whose text the label rule refuses cannot be promoted (LifecycleError::InvalidLabel), nothing is appended, and the AI entry is untouched.

Source

pub fn current_ai_tags( &self, registry: &Registry, asset_id: &Uuid, ) -> Result<Vec<AiTag>, LifecycleError>

The asset’s AI tags that are current under registry — their (model_id, model_version) is the canonical pair for the model’s task. Stale suggestions (a superseded model version) are excluded until regenerated, mirroring the vector-index stale rule; the sidecar retains every AI tag regardless (it is the source of truth).

Source§

impl Workspace

Source

pub fn create( root: &Path, passphrase: &[u8], tier: DeviceTier, ) -> Result<Self, LifecycleError>

Create a fresh workspace: initialise the library directory and a new account, and publish a device directory. passphrase guards the on-disk account; tier sets the Argon2id cost.

Source

pub fn create_with_params( root: &Path, passphrase: &[u8], params: Argon2Params, ) -> Result<Self, LifecycleError>

As create but with explicit Argon2id parameters (tests use a fast cost).

Source

pub fn create_with_hardware_signer( root: &Path, passphrase: &[u8], params: Argon2Params, device_signer: Box<dyn Signer>, ) -> Result<Self, LifecycleError>

As create_with_params but signs with a caller-supplied device signer — e.g. a hardware-backed key (Secure Enclave / StrongBox / TPM). The published device directory and every asset manifest are then signed by device_signer, and its public half is what peers trust.

Source

pub fn create_with_p256_hardware_signer( root: &Path, passphrase: &[u8], params: Argon2Params, binding: HardwareSignerBinding, ml_seed: &[u8; 32], ) -> Result<Self, LifecycleError>

As create_with_params but with the device signing key’s classical half enrolled in binding’s secure element over ECDSA-P256, composed with the ML-DSA-65 half derived from ml_seed. Unlike create_with_hardware_signer, which signs only for the session that created the library, this records the binding (alias, sealed ml_seed, published key) beside the account, so open_with_hardware_signer rebuilds the same key on every later launch.

The element is enrolled before anything is written under root, so a refusal leaves no library behind. Nothing falls back to the software key: a caller that accepts software keys calls create_with_params itself.

Source

pub fn create_with_hardware_dek( root: &Path, passphrase: &[u8], params: Argon2Params, binding: HardwareDekBinding, ) -> Result<Self, LifecycleError>

As create_with_params but with the device encryption key’s classical half generated inside binding’s secure element and never leaving it. The ML-KEM-768 half is software-sealed under the master key as usual, so the account file round-trips; reopening the library needs the same element back, via open_with_hardware_dek.

This is the DEK counterpart of create_with_hardware_signer; the two are independent (an element may back one, the other, or both — see create_with_hardware_keys).

Source

pub fn create_with_hardware_keys( root: &Path, passphrase: &[u8], params: Argon2Params, device_signer: Option<Box<dyn Signer>>, dek_binding: Option<HardwareDekBinding>, ) -> Result<Self, LifecycleError>

The general hardware-binding constructor: bind the device signing key, the device encryption key, both, or neither. None/None is exactly create_with_params — the software fallback the design keeps for hosts with no secure element.

Source

pub fn create_from_master( root: &Path, passphrase: &[u8], params: Argon2Params, master: MasterKey, user_id: Uuid, sealed_identity: &[u8], ) -> Result<Self, LifecycleError>

Create a fresh library on a new device that opens as an existing account: the recovery path (“bootstrap a new device via passphrase and escrow”, design/backup-recovery).

  • master is the account master key, e.g. from recover_master_key over the server escrow;
  • user_id is the account’s id — the server’s id for a registered account, so the directory and every manifest this library authors name the account the server knows;
  • sealed_identity is the account’s user identity key sealed under master (Workspace::sealed_identity on a device that has it). The IK is random, not derived from the master key, and the server pins it on first publish, so a recovered device must carry the same one rather than mint its own.

The device is new — a fresh device_id, software DSK and software DEK — and the default album id is the account’s, since it derives from master. Album keys are not here: they arrive through import_backup or MLS, exactly as on any new device.

Fails with [CryptoError::Auth] (before anything is written under root) when sealed_identity was not sealed under master — which is also the check that master is this account’s key at all.

The directory this returns lists only the new device, at directory_version 1. That is not publishable on an account that already has a directory: the server refuses it as stale, and accepting it would drop every other device. Before publishing, fetch the account’s signed directory and pass it to extend_account_directory, then publish what that returns.

Source

pub fn bind_account_id(&mut self, user_id: Uuid) -> Result<(), LifecycleError>

Rebind this library to the account id the server assigned at registration.

A library mints its own user_id when it is created; a server mints another when the account registers, and refuses a device directory or a manifest that names any id but its own. This adopts the server’s id: the account file is rewritten (the id is stored beside the wrapped keys, not inside them, so no passphrase is needed) and the device directory is re-signed at the next directory_version naming it.

Refused with LifecycleError::AccountRebind once the library holds any asset: every manifest already signed names the old id as created_by_user, and rebinding under them would leave a library whose history contradicts its own account. Binding the same id again is a no-op.

Source

pub fn extend_account_directory( &mut self, published: &DeviceDirectory, ) -> Result<Option<DeviceDirectory>, LifecycleError>

Build this device’s directory on the account’s published one instead of replacing it (#550): the step a device that joined an existing account — a recovered device from create_from_master — takes before it publishes.

published is the account’s current signed directory as the server serves it. It is verified under this workspace’s user IK (the one opened from the sealed identity) and must name this workspace’s account; then this device’s own entry is appended at published.directory_version + 1, the result is re-signed under the user IK, adopted as this workspace’s directory, and returned for publication. Every device published lists is kept, revoked entries included.

Returns Ok(None) when published already lists this device under the signing key it signs with: the published directory is adopted unchanged and there is nothing to publish. A recovered device that extends again after publishing lands here. Either way the adopted directory is persisted, so open restores it.

Refused, leaving this workspace’s directory unchanged, with LifecycleError::UntrustedDirectory when published does not verify or names another account, and with LifecycleError::Directory when it lists this device’s id under another key (or revoked), lists this device’s signing key under another id, or its version cannot advance.

Source

pub fn with_client_id(self, client_id: &str, semver: &str) -> Self

Set the reporting client identity every manifest and derivative this workspace authors carries: client_id names the product (capsule-cli, capsule-ios, …) and semver is that client’s own version. The build-embedded commit + dirty flag are appended per the client_version grammar, so an in-repo app supplies only its id and version. Without this, a workspace reports the bare-core capsule-core/{semver}+{commit} default.

Source

pub fn open( root: &Path, passphrase: &[u8], params: Argon2Params, ) -> Result<Self, LifecycleError>

Open an existing library at root as a signed workspace, unlocking (or, on first use, creating + persisting) the account under passphrase. params sets the Argon2id cost for a first-time account and the share-link wrap tier.

This restores the workspace’s durable state rather than starting empty:

  • album keys + authorities from the sealed [AlbumStore], so a reopened library can decrypt and keep writing into the albums it already has;
  • every managed asset from its signed artifacts on disk (chain, sidecar, sealed metadata blob), a warn-and-skip per asset rather than a failed open;
  • the add_id counter, reseeded past everything this device has ever written;
  • the signed device directory from {root}/.library/directory.cbor (#562), once it verifies under the user IK and lists this device live (re-signed under this account’s id at the next version when it still names the id from before a rebind); otherwise a fresh version-1 directory listing only this device, with a warn naming why.

A library with no albums.cbor predates this and opens with zero albums plus a warn naming backup restore — see [AlbumStore::load].

A library holding sidecars no provenance chain anchors — an interrupted write, a torn or foreign file, a retired unsigned pre-signed-path record — still opens: those assets are not restored, but each is reported through unanchored_sidecars with a warn, and never touched.

Still session-scoped by design, and dropped on close: the federation group assertions (re-delivered by the feed), the pending guest-drop inbox (server-authoritative), and the issued share/upload link records — see the Workspace fields for why each is deferred.

A library whose device signing key is hardware-bound is refused here; it opens through open_with_hardware_signer.

Source

pub fn open_with_hardware_dek( root: &Path, passphrase: &[u8], params: Argon2Params, binding: HardwareDekBinding, ) -> Result<Self, LifecycleError>

As open, re-attaching the secure element that holds this device’s hardware-bound DEK. Required for a library created by create_with_hardware_dek: its DEK’s classical half is non-exportable, so plain open refuses it rather than degrading to software.

Safe to call for a software-DEK library too — the binding recorded in the account file decides, and a software account simply ignores the element. On a first open of an empty library (no account yet) the fresh account is created hardware-bound under binding.key_alias.

Source

pub fn open_with_hardware_signer( root: &Path, passphrase: &[u8], params: Argon2Params, binding: HardwareSignerBinding, ) -> Result<Self, LifecycleError>

As open, re-attaching the secure element that holds this device’s hardware-bound signing key. Required for a library created by create_with_p256_hardware_signer: the element is asked for the key under the alias the library recorded, the ML-DSA-65 half is rebuilt from its sealed seed, and the result must be the key this device published. Plain open refuses such a library rather than signing with the software key, which would change the key the device directory publishes.

The recorded binding decides, never the caller: a library with no record (every library created with the software key, including those from before this binding existed) opens on its software key and ignores the element. On a first open of an empty library (no account yet) the fresh account’s signing key is enrolled in the element under binding.key_alias with a freshly drawn ML-DSA-65 seed.

Refused with [CryptoError::Key] when the element does not hold the recorded key (it was removed, or the element is unavailable) or holds another key under that alias; the element is never asked to mint a replacement.

Source§

impl Workspace

Source

pub fn soft_delete( &mut self, asset_id: &Uuid, retain_days: i64, ) -> Result<(), LifecycleError>

Soft-delete: emit a delete record carrying a signed retention window.

Source

pub fn restore(&mut self, asset_id: &Uuid) -> Result<(), LifecycleError>

Restore a soft-deleted asset by this device’s clock; see restore_at.

Source

pub fn restore_at( &mut self, asset_id: &Uuid, now: Timestamp, ) -> Result<(), LifecycleError>

Restore a soft-deleted asset: emit a trash-restore record, judged at now.

§Errors

LifecycleError::NotFound for an unknown asset, LifecycleError::NotInTrash for one that is not in the trash, and LifecycleError::RetentionElapsed at or after its signed retention_until. A refusal signs nothing.

Source

pub fn trash_entry(&self, asset_id: &Uuid) -> Option<TrashEntry>

The trash entry asset_id is in, or None when it is unknown or not in the trash.

Source

pub fn trash(&self) -> Vec<TrashEntry>

Every asset in the trash, most recently deleted first (ties by id, for determinism).

Source

pub fn expired_trash(&self, now: Timestamp) -> Vec<TrashEntry>

The trash entries whose signed retention window has closed at now: the retention sweep’s input. Judged by retention_until alone, never by how long ago the delete was.

Source

pub fn expired_trash_after_drain( &self, drain: Option<&FeedDrain>, ) -> Vec<TrashEntry>

The retention sweep’s input after a sync: expired_trash judged at the instant FeedDrain::judged_at gives, less every held delete. Nothing at all when no sync drained the feed to its head (drain is None) or the drain saw no entry, which leaves no reading of the server’s clock to judge by.

Waiting for the drain means a restore on a later feed page lands before any deadline is judged, so the sweep never purges an asset that page restored. Judging by the server’s clock alone means a device clock running ahead never purges early. A held delete (one the server has not indexed, FeedDrain::server_heads) never expires: the server has no window running for it, so only the user’s own purge removes it.

Source

pub fn tombstones(&self) -> BTreeSet<Uuid>

Every asset this workspace has purged: the peering tombstones a backup import or a peer ingest must never resurrect.

Source

pub fn purge_record(&self, asset_id: &Uuid) -> Option<&ProvenanceRecord>

The head of a purged asset’s kept provenance chain: the delete that ended it. After an early purge this is the shorter-retention re-issue, so a delivery that failed can be retried from it after purge returned, and after a reopen. None for an asset this workspace has not purged.

Source

pub fn purged_chain(&self, asset_id: &Uuid) -> Option<&[ProvenanceRecord]>

A purged asset’s whole kept provenance chain, oldest first, headed by purge_record. A held delivery reads the stretch after the server’s head from it, so a delete the server never saw (and the shorter-retention re-issue an early purge appended) is sent from the tombstone once another device’s upload of the create is indexed. None for an asset this workspace has not purged.

Source

pub fn purge(&mut self, asset_id: &Uuid) -> Result<PurgeOutcome, LifecycleError>

Purge a trashed asset by this device’s clock; see purge_at.

Source

pub fn purge_at( &mut self, asset_id: &Uuid, now: Timestamp, ) -> Result<PurgeOutcome, LifecycleError>

Hard-delete a trashed asset, judged at now.

Before retention_until (an early purge, which the user asked for), a delete whose retention_until is now is signed and appended first: the server refuses a purge before the signed floor, so without the re-issue the server would keep the asset for the rest of the old window.

Then the original, every derivative, every local cache entry, the signed sidecar and the sealed metadata blob are removed, and the asset leaves the index and this workspace. The provenance chain stays on disk: it is the record that the asset was deleted, and without it the purge could not be told from a lost file. The original goes first, so a failure part-way leaves the asset in the trash for a retry rather than its bytes behind a vanished row.

§Errors

LifecycleError::NotFound for an unknown asset, LifecycleError::NotInTrash for one that is not in the trash (a purge never skips the trash), LifecycleError::Io when a file cannot be removed, and LifecycleError::Db when the index cannot be updated.

Source§

impl Workspace

Source

pub fn set_cull( &mut self, asset_id: &Uuid, flag: CullFlag, ) -> Result<(), LifecycleError>

Flag an asset for culling: write the trinary [CullFlag] LWW register and emit a metadata-update. Neutral clears a prior flag — flagging is fully reversible and never touches asset bytes. Stamped with this device id + now, so concurrent flags from two devices converge under the LWW (ts, device_id) rule.

Source

pub fn cull_flag(&self, asset_id: &Uuid) -> CullFlag

The asset’s current culling flag — [CullFlag::Neutral] if never flagged or the asset is unknown (the wire-absent default).

Source

pub fn apply_remote_cull( &mut self, asset_id: &Uuid, remote: &Lww<CullFlag>, ) -> Result<(), LifecycleError>

Apply a peer device’s cull register into the local one (the CRDT sync-apply path) and emit a metadata-update. The merge is the [Lww] merge, so the flag converges to the same value regardless of which device’s write arrives first.

Source

pub fn cull_register(&self, asset_id: &Uuid) -> Option<&Lww<CullFlag>>

The current cull register for an asset (for driving a sync/merge with a peer replica).

Source

pub fn assets_by_cull(&self, flag: CullFlag) -> Vec<Uuid>

The cull-filtered view: managed, non-trashed assets currently carrying flag (sorted for determinism). Filtering by [CullFlag::Neutral] returns the never-flagged assets too, since an unwritten register reads as Neutral.

Source

pub fn set_hidden( &mut self, asset_id: &Uuid, hidden: bool, ) -> Result<(), LifecycleError>

Hide (true) or unhide (false) an asset: write the hidden LWW register and emit a metadata-update. Stamped with this device id + now, so concurrent writes from two devices converge under the LWW (ts, device_id) rule.

The index row is refreshed by the same append_lifecycle write, so the asset leaves the default projections and enters the gated Hidden view immediately — no rebuild required.

Source

pub fn is_hidden(&self, asset_id: &Uuid) -> bool

Whether an asset is currently hidden — false if never written or the asset is unknown (the wire-absent default is visible).

Source

pub fn apply_remote_hidden( &mut self, asset_id: &Uuid, remote: &Lww<bool>, ) -> Result<(), LifecycleError>

Apply a peer device’s hidden register into the local one (the CRDT sync-apply path) and emit a metadata-update. The merge is the [Lww] merge, so the flag converges to the same value regardless of which device’s write arrives first.

Source

pub fn hidden_register(&self, asset_id: &Uuid) -> Option<&Lww<bool>>

The current hidden register for an asset (for driving a sync/merge with a peer replica).

Source

pub fn set_stack_membership( &mut self, asset_id: &Uuid, membership: Option<StackMembership>, ) -> Result<(), LifecycleError>

Set (or clear, with None) this asset’s stack membership (LWW register) and emit a metadata-update. The companion write to group_cull_state: a stack is the set of assets sharing a stack_id, and grouping converges under the same (ts, device_id) rule as every LWW field.

Source

pub fn group_cull_state(&self, stack_id: Uuid) -> Option<GroupCullState>

The derived cull state of a stack/group (owner: Organization — Culling): computed from its members’ flags every time, never stored, so it cannot diverge from the per-asset flags. None when the stack has no (non-trashed) members.

Source

pub fn flag_stack( &mut self, stack_id: Uuid, flag: CullFlag, ) -> Result<Vec<Uuid>, LifecycleError>

Apply flag to every member of stack_id — the doc’s “flagging a collapsed stack applies the flag to each member”, one metadata-update per member. Returns the members flagged (sorted).

Source

pub fn reject_sweep( &mut self, retain_days: i64, ) -> Result<Vec<Uuid>, LifecycleError>

The reject-sweep: batch-move every Reject-flagged, not-already-trashed managed asset to trash — a soft delete carrying the signed retain_days retention window. This is the only destructive step of culling and is reversible via restore until the retention window elapses. Returns the swept asset ids (sorted).

Source

pub fn add_region( &mut self, asset_id: &Uuid, shape: RegionShape, ) -> Result<Uuid, LifecycleError>

Mark a region of asset_id and return its new id (UUIDv7). The shape is in coordinates normalized to [0, 1] over the original’s display orientation.

Source

pub fn delete_region( &mut self, asset_id: &Uuid, region_id: &Uuid, ) -> Result<(), LifecycleError>

Delete a region. Final: a concurrent or later edit of it on another device does not bring it back once the two merge.

Source

pub fn add_region_label( &mut self, asset_id: &Uuid, region_id: &Uuid, label: &str, ) -> Result<(), LifecycleError>

Add a label to a region.

Source

pub fn remove_region_label( &mut self, asset_id: &Uuid, region_id: &Uuid, label: &str, ) -> Result<usize, LifecycleError>

Remove a label from a region: every add of it this device has observed. Returns how many adds were removed; 0 writes nothing.

Source

pub fn regions(&self, asset_id: &Uuid) -> Vec<(Uuid, Region)>

The asset’s live regions, by id. Empty for an unknown asset.

Source

pub fn apply_remote_regions( &mut self, asset_id: &Uuid, remote: &Regions, ) -> Result<(), LifecycleError>

Merge a peer device’s region map into the asset’s (the CRDT sync-apply path) and emit a metadata-update.

Source

pub fn stack_doc(&self, stack_id: Uuid) -> Result<StackDocV1, LifecycleError>

stack_id’s label record: the persisted one, or an empty one in its container album.

§Errors

LifecycleError::NotFound for a stack with no members and no record; LifecycleError::UnverifiedDocument when the persisted record does not verify.

Source

pub fn add_stack_label( &mut self, stack_id: Uuid, label: &str, ) -> Result<(), LifecycleError>

Add a label to a stack.

Source

pub fn remove_stack_label( &mut self, stack_id: Uuid, label: &str, ) -> Result<usize, LifecycleError>

Remove a label from a stack: every add of it this device has observed. Returns how many adds were removed; 0 writes nothing.

Source

pub fn stack_labels( &self, stack_id: Uuid, ) -> Result<BTreeSet<String>, LifecycleError>

The stack’s current labels.

Source

pub fn seal_stack_doc(&self, stack_id: Uuid) -> Result<Vec<u8>, LifecycleError>

Seal the stack’s record under its container album’s current-epoch AMK.

Source

pub fn apply_remote_stack_doc( &mut self, stack_id: Uuid, album_id: Uuid, wire: &[u8], ) -> Result<(), LifecycleError>

Open a sealed stack record another device of this account sent, verify it under this account’s identity key, and merge it into the local one. Every epoch of album_id this workspace holds is tried, newest first.

§Errors

LifecycleError::Document when no held AMK opens it, it does not decode, or it places the stack in another album than the local record; LifecycleError::UnverifiedDocument when it does not verify. Nothing is merged.

Source§

impl Workspace

Source

pub fn verify(&self, asset_id: &Uuid) -> Result<VerifyOutcome, LifecycleError>

Run verify_asset for a managed asset (regenerating its ciphertext deterministically).

Source§

impl Workspace

Source

pub fn reseal_create( &mut self, asset_id: &Uuid, ) -> Result<ResealOutcome, LifecycleError>

Re-seal a never-published create at the album’s current epoch, replacing its genesis record, so a create the server refused because the album’s epoch moved past it can be pushed again instead of being stranded on the device.

An epoch rotation is a confidentiality boundary, so everything sealed under the old epoch is sealed again under the current one: the original under a fresh nonce_prefix, the unchanged signed sidecar under a fresh metadata-blob nonce, and the derivatives regenerated as fresh chains. No prefix or nonce the asset has spent is drawn again, and the old derivative bundle is removed before the new one is written.

The caller is a push that the server refused with an epoch regression; this re-checks every precondition locally rather than trusting it, and refuses with LifecycleError::ResealRefused when the asset is not a lone create, holds a custody receipt, has a wrapped file key, or when this device holds no newer epoch. A read-only album is LifecycleError::AlbumReadOnly. A plaintext on disk that no longer hashes to the signed sidecar is LifecycleError::CiphertextMismatch.

The new create self-verifies through verify_asset and the metadata binding before anything is written. On success the asset’s next upload_bundle carries the new epoch, the new original ciphertext, the new metadata blob and the new derivatives, and nothing sealed under the old epoch.

Source§

impl Workspace

The issuer-held record for a share link, if this workspace issued it. Exposes the authoritative scope / expiry / revocation state the serving endpoint consults.

Source

pub fn shared_assets( &self, scope: ShareScope, privacy: ExportPrivacy, ) -> Result<Vec<SharedAsset>, SharingError>

The per-asset records a link over scope covers (#622): for each asset, the key-free parameters a viewer needs to fetch its original’s ciphertext and decrypt it under the opened scope, read off the asset’s head manifest and signed sidecar.

  • Asset scope covers that one asset. The scope material carries its file key directly, so the record says amk_version = 0, derived, and no wrapped key, as [SharedAsset] documents for an asset-scoped grant: the wrapped key would be a field the viewer never reads.
  • Album scope covers every asset in the album that is not in trash, in asset-id order so the same album publishes the same record. Each keeps its manifest’s epoch, key mode and wrapped key, because the viewer recovers the file key from the grant’s AMKs.

An asset in trash is not shareable: asset scope refuses it with [SharingError::ScopeUnavailable], and album scope leaves it out.

Each record carries the asset’s sidecar as it may cross the boundary: the Privacy on Export strip ([sidecar_for_export]) under privacy, the per-export choice the caller passes for this one link. The workspace never stores it, and its own sidecar is untouched.

§Errors

[SharingError::ScopeUnavailable] when the scope is not managed by this workspace, or an asset-scoped asset is in trash.

Everything the server needs to serve link (#622): the sealed share-metadata/v1 record over shared_assets, its content address, the serves set, and for a passphrase link the wrapped secret — [publish_share] under the link’s own fragment, opaque id, scope encapsulation and expiry.

The record is sealed with a fresh nonce on every call, so two calls for one link yield two different metadata_hashes; publish once per link and register what that call returned.

privacy is this export’s Privacy on Export choice: every covered sidecar is stripped under it before the record is sealed, so the blob the server stores is already stripped. [ExportPrivacy::default] strips every row; an opt-in applies to this link only and is never stored.

§Errors

What shared_assets and [publish_share] return.

Source§

impl Workspace

Source

pub fn apply_remote_entry( &self, entry: RemoteEntry<'_>, ) -> Result<SyncApplyOutcome, LifecycleError>

Apply one remote feed entry: verify it through the verify_asset chokepoint, bind and open its metadata blob, and project the result into RemoteAssetFacts.

Read-only with respect to this workspace — it decides what is true and leaves what to persist to the caller’s catalog. That split is deliberate: the same verdict feeds an iOS gallery upsert, a CLI sync report, and a quarantine surface, none of which want this layer writing to their index. A client whose catalog is this workspace’s own adopts the entry instead (adopt_remote_head).

Err is reserved for a failure of this workspace (an unreadable album keystore, say). A refused entry is never an Err — it is a SyncApplyOutcome::Quarantined, because a hostile feed must not be able to abort a whole sync by handing over one bad row.

Source

pub fn apply_remote_head( &self, entry: RemoteHead<'_>, ) -> Result<SyncApplyOutcome, LifecycleError>

apply_remote_entry for an entry whose original is named by its SHA-256 (RemoteHead): the same chokepoint, metadata binding and verdicts, with the content-integrity step run against the digest.

An Applied verdict here attests the manifest and its metadata, and that the manifest commits to original_ciphertext_hash; it says nothing about any bytes until the caller has hashed them to that digest. open_remote_original_from is the caller that does.

§Errors

As apply_remote_entry.

Source

pub fn open_remote_original( &self, entry: RemoteEntry<'_>, ) -> Result<RemoteOriginal, LifecycleError>

Verify a remote entry and open its original: run it through apply_remote_entry, recover the original’s file key from this workspace’s album keys (honouring the manifest’s key_mode), decrypt the STREAM ciphertext, and check the plaintext digest against the signed sidecar’s hash.

The read half of a restore: what comes back as RemoteOriginal::Opened is byte for byte the original the account’s device signed, because every link from the bytes to a signature has been checked — the ciphertext against the manifest’s ciphertext_hash (inside the chokepoint), every chunk against its AEAD tag, and the plaintext against the sidecar’s digest, which the account’s identity key signs. A head that binds no metadata blob (a trash-restore, say) has no sidecar, so its plaintext stands on the first two.

An entry that does not apply is handed back unchanged as RemoteOriginal::Refused — nothing is decrypted. Read-only with respect to this workspace, like the apply it wraps.

§Errors

As apply_remote_entry: only a failure of this workspace itself. A file key that cannot be recovered or bytes that do not open are verdicts (RemoteOriginal::Undecryptable, RemoteOriginal::DigestMismatch), never errors.

Source

pub fn open_remote_original_from<R: Read, W: Write>( &self, entry: RemoteHead<'_>, ciphertext: R, plaintext: W, ) -> Result<RemoteOriginal<W>, LifecycleError>

open_remote_original in bounded memory: the original’s ciphertext is read from ciphertext and its plaintext written to plaintext one STREAM chunk at a time, so opening an original of any size holds a few chunks of it.

The checks are open_remote_original’s, in an order a stream allows. The head goes through the chokepoint first (apply_remote_head), against its claimed original_ciphertext_hash; then every ciphertext byte read is hashed while it is decrypted, and the original opens only if that hash is the manifest’s ciphertext_hash, every chunk authenticated, and the plaintext hashes to the signed sidecar’s digest. Bytes that are not the committed ciphertext are refused as the chokepoint refuses them ([RejectReason::CiphertextHashMismatch]), whichever check they fail first.

Plaintext reaches plaintext before those checks finish, so the writer holds unverified bytes until this returns RemoteOriginal::Opened, which hands the writer back. On any other outcome the caller must discard what it wrote. An entry that does not apply is refused before anything is read or written.

§Errors

As open_remote_original, plus LifecycleError::Io when ciphertext cannot be read or plaintext cannot be written.

Source§

impl Workspace

Source

pub fn adopt_remote_head( &mut self, entry: RemoteHead<'_>, ) -> Result<(SyncApplyOutcome, Option<Adoption>), LifecycleError>

apply_remote_head, then adopt what applied: a record that chains onto an asset this workspace holds is appended to its chain, with the sealed metadata it binds, and written under media/ and indexed, so the asset’s next signed record chains onto the head the server holds.

A record that needs the original’s plaintext (a create, or a replace) is not adopted here: it answers Adoption::NeedsOriginal, and adopt_remote_original adopts it. A record that does not change the original needs none, because the held original is the one it commits to.

The verdict is exactly apply_remote_head’s, and the Adoption is Some only for an Applied one.

§Errors

As apply_remote_head, plus the I/O or index failure that stopped an adoption’s write.

Source

pub fn adopt_remote_original( &mut self, entry: RemoteHead<'_>, plaintext: &Path, ) -> Result<(SyncApplyOutcome, Option<Adoption>), LifecycleError>

adopt_remote_head for an entry whose original’s verified plaintext is the file at plaintext — the one an open_remote_original_from of the same head answered RemoteOriginal::Opened for. This is what adopts a create: the asset is held with that original as its library copy.

The file is not trusted for being handed over. It is placed only if it hashes to the digest the entry’s signed sidecar commits to, and is copied into media/ (never hard-linked), so plaintext is left in place for its owner to keep or remove, and nothing later written to it reaches the library original. An entry that does not need the original adopts as adopt_remote_head would, without reading the file.

§Errors

As adopt_remote_head, and LifecycleError::OriginalMismatch when the file is not the signed original (nothing of the asset is written).

Source

pub fn adopt_remote_history( &mut self, entry: RemoteHead<'_>, history: &[Vec<u8>], plaintext: &Path, ) -> Result<(SyncApplyOutcome, Option<Adoption>), LifecycleError>

adopt_remote_original for an asset first seen past its create: history is every record of its chain before the entry’s, oldest first and starting at its create, each the canonical CBOR the server stores (the provenance blob a record’s successor names by prior_provenance_hash). This is what adopts an asset adopt_remote_head answers Adoption::MissingHistory for.

Every record goes through the chokepoint in order, each against the hash of the one before it and the create against no head, so the chain held is one that verifies from its start; the entry’s record is then applied against the last of them, whatever RemoteHead::local_chain_head says. A superseded record’s content-integrity step is checked against the ciphertext it commits to itself: the original it named may have been replaced since, and the original held is the entry’s, which the entry’s own check binds.

A superseded record’s sealed metadata is not on the server any more (a newer blob replaced it and the collector reclaimed it), so the sidecar is opened from the entry’s metadata_blob, the asset’s live one: bound to the entry’s record when it binds one, and otherwise to the newest record of history that does. The original at plaintext is placed only if it hashes to that sidecar’s digest.

The verdict returned is the first one that is not Applied, in chain order: a record of history that does not verify, a record naming another asset, or a live metadata blob that does not bind, refuses the whole adoption and writes nothing. An empty history adopts as adopt_remote_original would, and so does an entry of an asset this workspace already holds: the history is not read, so none of its records can refuse the entry, and the entry is checked against RemoteHead::local_chain_head.

§Errors

As adopt_remote_original.

Source§

impl Workspace

Source

pub fn unanchored_sidecars(&self) -> &[UnanchoredSidecar]

The sidecar files open found under media/ that no provenance chain anchors — assets this workspace cannot see, verify, export, or upload. Empty for a library with no debris.

Source§

impl Workspace

Source

pub fn upload_bundle( &self, asset_id: &Uuid, ) -> Result<UploadBundle, LifecycleError>

Build the UploadBundle for one managed asset: its create record and the bytes that record commits to.

An upload establishes an asset on the server, and the server takes nothing but a create through it. So the bundle carries the chain’s genesis whatever the chain holds now: an asset deleted and restored, or edited, before its first upload is uploaded as the create it began as, and every record after it reaches the server as a lifecycle op once the create is indexed (Organization — Deletion State Machine, “Held records”).

Re-derives the original ciphertext from the create’s recorded nonce_prefix (clients hold plaintext; ciphertext is regenerated deterministically) and gates it on the manifest’s own content address, so a bundle that reaches the network is one the signed manifest vouches for. The sealed metadata blob the create binds is carried verbatim — it cannot be regenerated, because seal_metadata_blob draws a fresh nonce per call — so an asset edited since its import carries the copy its first edit kept, not its current blob.

§Errors

LifecycleError::CreateMetadataSuperseded when the create binds a metadata blob the library no longer holds: an edit made before the library kept that blob replaced it. LifecycleError::CiphertextMismatch when the plaintext on disk no longer re-derives to the signed ciphertext. LifecycleError::Db when the original’s source guard cannot be persisted.

The hashing pass that verifies the original records its source guards (identity and every STREAM chunk’s tag), and the bundle persists them in the catalog until release_upload_guard or a purge forgets them.

Source

pub fn release_upload_guard( &self, asset_id: &Uuid, ) -> Result<bool, LifecycleError>

Forget asset_id’s upload source guard: every blob of its bundle is custody-confirmed, or the bundle is abandoned. Returns whether one was recorded. The next upload_bundle records it again.

§Errors

LifecycleError::Db when the catalog refuses the delete.

Source

pub fn has_upload_guard(&self, asset_id: &Uuid) -> Result<bool, LifecycleError>

Whether asset_id has an upload source guard recorded: a bundle of it was built and has not been custody-confirmed or abandoned since.

§Errors

LifecycleError::Db when the catalog cannot be read.

Source§

impl Workspace

Source

pub fn user_id(&self) -> Uuid

The account’s user id.

Source

pub fn user_ik_public(&self) -> HybridVerifyingKey

This account’s user identity public key — the key an album-group assertion (and any user-IK-signed artifact this workspace authors) verifies against.

Source

pub fn device_id(&self) -> Uuid

This device’s stable id — the created_by_device every manifest this workspace authors carries, and the DeviceEntry key under which its signing key is published in the device directory.

Source

pub fn device_signer(&self) -> &dyn Signer

This device’s hybrid device signer — the key published for device_id in the device directory: the account’s software device key, or the hardware-backed signer the workspace was created with. A peering handshake signs its channel binding with it to prove this device’s identity to a peer. The private key never leaves the signer; this lends the signing capability, not the key.

Source

pub fn device_directory(&self) -> &DeviceDirectory

This workspace’s signed device directory — the user-IK-signed list of enrolled device signing keys verify_asset resolves a manifest’s created_by_device against.

Exposed so a client can publish it (the device-directory surface, driven from the SDK by capsule_sdk::directory). The directory is a signed, self-verifying document: it carries no private key material, and a reader checks it under user_ik_public before trusting a single entry.

Source

pub fn default_album_id(&self) -> Uuid

The account’s default album id (derived from the master key).

Source

pub fn root(&self) -> &Path

The library root directory this workspace writes through. The streaming executor probes its volume’s free space (available_bytes) for the minimum-headroom check.

Source

pub fn create_metadata_blob_path(&self, asset_id: &Uuid) -> Option<PathBuf>

The on-disk path of the metadata blob kept for a managed asset’s create record, or None for an unknown id. The file exists only once an edit superseded that blob. Exposed so a client test can stand in for a library written before the blob was kept.

Source

pub fn read_plaintext(&self, asset_id: &Uuid) -> Result<Vec<u8>, LifecycleError>

The plaintext bytes of a managed asset (reads from disk).

Source

pub fn asset_ids(&self) -> Vec<Uuid>

All managed asset ids.

Source

pub fn original_path(&self, asset_id: &Uuid) -> Option<PathBuf>

The on-disk path of a managed asset’s plaintext original, or None for an unknown id.

The path is derived from the asset’s shard (AssetState::capture_utc), which is fixed at import — so it keeps resolving after a capture-time correction (set_capture_timestamp) even though the sidecar’s timestamp no longer names the month directory. Exposed for the repair pass, which has to re-read each original’s EXIF without loading every file through read_plaintext.

Source

pub fn is_trashed(&self, asset_id: &Uuid) -> bool

Whether a managed asset is currently in trash — a replay of its provenance chain’s lifecycle actions (a delete moves it to trash, a later trash-restore brings it back), which is the single source of truth the workspace itself applies. false for an unknown id. Exposed so a client can report or skip trashed assets without re-deriving the rule from the chain.

Source

pub fn asset(&self, asset_id: &Uuid) -> Option<&AssetState>

A managed asset’s current state.

Source

pub fn db(&self) -> &DatabaseDriver

The library’s queryable SQLite index — the timeline, user tags, and cached representations the crypto lifecycle writes through to.

Source

pub fn device_dek_public(&self) -> Vec<u8> ⓘ

This device’s published DEK public encapsulation key — the bytes a peer (or this account’s own escrow path) wraps a key to so only this device can open it.

Length-tagged by composition: 1216 bytes for the software X-Wing DEK, 1249 for the hardware-bound P-256 hybrid, so a recipient never has to be told which it is holding and the two can never be confused for one another.

Source

pub fn device_dek_decapsulate( &self, ciphertext: &[u8], ) -> Result<[u8; 32], LifecycleError>

Recover the 32-byte shared secret from a ciphertext sealed to device_dek_public.

When the DEK is hardware-bound this performs the classical ECDH inside the secure element — the device’s P-256 scalar is never in this process’s memory — so it can fail on a cancelled biometric or an evicted key as well as on a malformed ciphertext.

Source

pub fn device_dek_is_hardware_bound(&self) -> bool

Whether this workspace’s DEK has its classical half in a secure element rather than in software — the honest answer to “is this device actually hardware-bound”, read from the account’s own recorded binding rather than from whether an element was offered.

Trait Implementations§

Source§

impl AiTagSink for Workspace

The write half: AI tags produced by inference land in tags_ai as a signed metadata-update, exactly as a direct Workspace::add_ai_tags call would.

Source§

fn add_ai_tags( &mut self, asset_id: &Uuid, tags: Vec<AiTag>, ) -> Result<(), LifecycleError>

Add tags to the asset’s tags_ai namespace (never tags_user), as one signed metadata update. An empty tags is a no-op.
Source§

impl AssetSource for Workspace

The read half of the inference seam: the orchestrator decodes an asset’s plaintext and indexes vectors through the workspace’s own catalog. A thin forward to the inherent methods — the indirection exists to reverse a module edge, not to change behaviour.

Source§

type Error = LifecycleError

How this store reports a failed read. Type-erased into [StoreError] on the way out, so ml never names a concrete store error.
Source§

type Index = DatabaseDriver

The vector index this store’s embeddings live in.
Source§

fn read_plaintext(&self, asset_id: &Uuid) -> Result<Vec<u8>, LifecycleError>

The decoded-asset plaintext bytes inference runs over.
Source§

fn vector_index(&self) -> &DatabaseDriver

The catalog holding this store’s vector index.
Source§

impl DropAdopter for Workspace

Source§

fn list_inbox(&self) -> Result<Vec<PendingDrop>, DropError>

This owner’s pending drops, newest-arrival order unspecified.

Source§

fn adopt( &mut self, drop: DropId, album_id: Uuid, ) -> Result<AdoptedDrop, DropError>

Adopt a pending drop into album_id in place (no byte re-upload): decapsulate the guest-chosen K, run the import’s still pipeline over the plaintext (prepare_still: header-derived content_type, pixel dimensions, LQIP, signed thumbnail derivatives — never fatal over pixels, reported in [AdoptedDrop::derivatives]), rewrap K under the album AMK (asset-keywrap/v1), author + sign a create manifest with key_mode = wrapped whose ciphertext_hash references the staged blob, self-verify through [verify_asset], register the asset in the library (chain, sidecar, sealed metadata blob, plaintext, derivatives, index row — the same writes commit_signed_create makes for an import), and only then drop the inbox row. A registration failure leaves the drop in the inbox. Returns the [AdoptedDrop]: the signed manifest plus the metadata blob and provenance record a push publishes. SSoT: Web Upload — Review and adopt-in-place.

Source§

fn discard(&mut self, drop: DropId) -> Result<(), DropError>

Discard a pending drop the owner rejects; its bytes are GC’d and the quota freed.

Source§

impl ShareLinkIssuer for Workspace

Issue a view-only share link: resolve the scope’s decryption material, encapsulate it around a fresh CSPRNG link secret (and, if a passphrase is given, an Argon2id layer on top), draw a 128-bit opaque id, and record the link for revocation. The fragment secret is returned to the caller and never persisted server-side.

Publish a revocation record for link; the serve path then refuses it. Revoking an unknown link is [SharingError::NotFound]; revoking an already-revoked link is idempotent (the original revocation timestamp is kept).

Source§

impl UploadLinkIssuer for Workspace

Provision an upload link: mint a fresh Drop Key (X-Wing KEM), escrow its private half under the account master key (the OGK re-wrap that lets any enrolled device decapsulate rides the multi-device escrow seam), draw a 128-bit opaque id, derive the optional Argon2id write-abuse verifier, and record the link for revocation. The public half is returned for the URL fragment and never persisted server-side. SSoT: Web Upload.

Revoke a link; the serve path refuses it within its fail-closed cache window. Revoking an unknown link is [DropError::NotFound]; re-revocation keeps the original timestamp (idempotent).

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
§

impl<T> Pointable for T

§

const ALIGN: usize

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a [WithDispatch] wrapper. Read more