Skip to main content

capsule_library/lifecycle/
mod.rs

1//! The offline asset lifecycle — the integration layer that ties the cryptographic data
2//! plane to the on-disk client library, and the substrate the CLI showcase drives.
3//!
4//! A [`Workspace`] holds an unlocked [`Account`], the per-album key material + its
5//! [`ReferenceAuthority`], and the signed device directory. Each operation produces the
6//! design's real artifacts and self-checks them through [`verify_asset`]:
7//!
8//! - [`import_asset`](Workspace::import_asset) — derive the file key, STREAM-encrypt to get
9//!   the content hash, build + sign the create manifest, append the provenance chain, write
10//!   the signed [`SidecarV1`], and gate on `verify_asset == Accept`.
11//! - [`tag_add`](Workspace::tag_add) / [`set_caption`](Workspace::set_caption) — CRDT edits
12//!   emitting a `metadata-update` provenance record.
13//! - [`soft_delete`](Workspace::soft_delete) / [`restore`](Workspace::restore) /
14//!   [`purge`](Workspace::purge) — `delete` (with a signed retention window) and
15//!   `trash-restore` lifecycle records, and the hard delete, each judged by the signed
16//!   `retention_until`.
17//! - [`export_backup`](Workspace::export_backup) / [`import_backup`](Workspace::import_backup)
18//!   — the portable artifact round-trip; the client stores plaintext, so ciphertext is
19//!   regenerated deterministically from the manifest's recorded nonce prefix.
20//! - [`adopt_remote_head`](Workspace::adopt_remote_head) /
21//!   [`adopt_remote_original`](Workspace::adopt_remote_original) /
22//!   [`adopt_remote_history`](Workspace::adopt_remote_history) — hold an asset another
23//!   device wrote, from a verified sync entry (and, for an asset first seen past its create,
24//!   its fetched earlier records): its chain, sidecar, sealed metadata blob and original under
25//!   `media/`, indexed, so the verbs above work on it as on an import.
26//!
27//! Clients store **plaintext** locally (original + signed sidecar + provenance chain);
28//! encryption produces the artifacts that cross a boundary. Offline epoch rotation is supported
29//! ([`rotate_epoch`](Workspace::rotate_epoch)); the MLS membership ceremony (`Welcome`,
30//! add/remove) remains deferred (see `SLICES.md`).
31//!
32//! [`verify_asset`]: capsule_core::crypto::verify_asset::verify_asset
33//! [`ReferenceAuthority`]: capsule_core::crypto::authority::ReferenceAuthority
34
35mod album;
36mod backup;
37mod derivatives;
38mod drops;
39mod enrollment;
40mod groups;
41mod import;
42mod metadata;
43mod open;
44mod organize;
45mod provenance;
46mod reseal;
47mod sharing;
48mod sync_apply;
49mod unanchored;
50mod upload;
51
52use std::collections::{BTreeMap, HashMap};
53use std::fs;
54use std::path::{Path, PathBuf};
55
56use capsule_core::backup::BackupError;
57use capsule_core::crypto::CryptoError;
58use capsule_core::crypto::authority::Authority;
59use capsule_core::crypto::hash::Hash32;
60use capsule_core::crypto::keys::albumstore::AlbumStoreError;
61use capsule_core::crypto::keys::{
62    Account, DeviceDirectory, DirectoryError, HybridSigningKey, HybridVerifyingKey, Signer,
63};
64use capsule_core::crypto::primitives::Argon2Params;
65use capsule_core::crypto::provenance::{Action, ProvenanceChain};
66use capsule_core::crypto::verify_asset::{MetadataBinding, VerifyOutcome};
67pub use capsule_core::derivative_format::DerivativeStatus;
68use capsule_core::drop::{DropId, UploadLinkId};
69use capsule_core::federation::AlbumGroupAssertion;
70use capsule_core::metadata::crdt::Counter;
71use capsule_core::sharing::{ShareLinkId, ShareLinkRecord};
72use capsule_core::sidecar::sidecar_v1::{Gps, SidecarV1, StackMembership, StackRole};
73use capsule_core::sidecar::{DocError, LabelError, RegionError};
74use jiff::Timestamp;
75use thiserror::Error;
76use uuid::Uuid;
77
78pub use self::album::{AdoptedAlbumKeys, AlbumKeyEscrowPlan};
79pub use self::backup::PeerExport;
80use self::drops::{InboxEntry, IssuedLink};
81pub use self::enrollment::{
82    ENROLLMENT_NONCE_LEN, ENROLLMENT_PAYLOAD_VERSION, EnrolleeKeys, EnrollmentPayload,
83    EnrollmentPayloadError, InitiatorKeys, MAX_ENROLLMENT_PAYLOAD_CHARS, enrollment_safety_code,
84};
85pub use self::open::HardwareDekBinding;
86pub use self::organize::{FeedDrain, PurgeOutcome, TrashEntry};
87pub use self::reseal::{ResealOutcome, ResealRefusal};
88pub use self::sync_apply::{
89    Adoption, QuarantineReason, RemoteAssetFacts, RemoteEntry, RemoteHead, RemoteOriginal,
90    SyncApplyOutcome, hash_ciphertext_from,
91};
92pub use self::unanchored::{UnanchoredShape, UnanchoredSidecar, unanchored_sidecars};
93pub use self::upload::{
94    DerivativeBlob, OPAQUE_CONTENT_TYPE, OriginalChanged, OriginalCiphertext, UploadBundle,
95    WIRE_ORIGINAL_CONTENT_TYPES, wire_content_type,
96};
97pub use crate::account::HardwareSignerBinding;
98use crate::db::DatabaseDriver;
99use crate::library::{Library, LibraryError};
100
101/// Errors from lifecycle operations.
102#[derive(Debug, Error)]
103pub enum LifecycleError {
104    /// Filesystem error.
105    #[error("io: {0}")]
106    Io(String),
107    /// Unknown album / asset id.
108    #[error("not found: {0}")]
109    NotFound(String),
110    /// A restore or purge named an asset that is not in the trash. Nothing was written.
111    #[error("asset {0} is not in the trash")]
112    NotInTrash(Uuid),
113    /// A peer copy named an asset this workspace purged: its tombstone refuses every copy, so
114    /// a purged asset is never resurrected. Nothing was written.
115    #[error("asset {0} was purged; its tombstone refuses any copy")]
116    Purged(Uuid),
117    /// A `trash-restore` at or after the signed `retention_until` of the asset's `delete`
118    /// record. Nothing was written; the asset stays in the trash until it is purged.
119    #[error("asset {asset_id}'s retention window closed at {retention_until}")]
120    RetentionElapsed {
121        /// The asset the restore was asked for.
122        asset_id: Uuid,
123        /// The signed retention floor the restore came too late for (RFC 3339).
124        retention_until: String,
125    },
126    /// An asset failed its own `verify_asset` self-check (a bug — should never happen).
127    #[error("verify_asset self-check failed: {0:?}")]
128    SelfVerify(VerifyOutcome),
129    /// A sealed metadata blob failed its own metadata↔manifest binding self-check (a bug —
130    /// the sidecar the workspace just wrote does not round-trip to the committed hash).
131    #[error("metadata binding self-check failed: {0:?}")]
132    MetadataUnbound(MetadataBinding),
133    /// A restored asset's sealed metadata blob (a backup's, or a peer delta's) is not the one
134    /// its chain commits to, or does not open, decode or verify under the account's user IK.
135    /// Nothing of the asset is written.
136    #[error("restored metadata refused: {0}")]
137    RestoredMetadata(String),
138    /// Cryptographic error.
139    #[error(transparent)]
140    Crypto(#[from] CryptoError),
141    /// Backup error.
142    #[error(transparent)]
143    Backup(#[from] BackupError),
144    /// CBOR (de)serialization error.
145    #[error("cbor: {0}")]
146    Cbor(String),
147    /// Library index (SQLite) error.
148    #[error("db: {0}")]
149    Db(String),
150    /// The on-disk library could not be opened. Typed rather than stringified so a caller
151    /// can act on the one open failure with its own recovery — a catalog stamped by a newer
152    /// build ([`LibraryError::CatalogTooNew`]) — instead of matching on text.
153    #[error("open library: {0}")]
154    Library(#[from] LibraryError),
155    /// The durable album-key store could not be read or written. Never
156    /// swallowed: losing album keys silently is exactly the failure this store exists to fix.
157    #[error(transparent)]
158    AlbumStore(#[from] AlbumStoreError),
159    /// The album holds AMKs but no write capability — it was recovered from a backup artifact,
160    /// which escrows content keys (read access) but never the write-tier / admin signing keys or
161    /// the admin-signed epoch ledger. Its assets decrypt and re-export; authoring a *new* write
162    /// into it needs its authority re-established first.
163    #[error("album {0} is read-only: recovered without write-tier/admin key material")]
164    AlbumReadOnly(Uuid),
165    /// The ciphertext re-derived from a manifest's recorded `nonce_prefix` does not
166    /// content-address to that manifest's `ciphertext_hash` — the library's bytes and its own
167    /// signed manifest disagree. Never papered over: it is the one signal that what would go
168    /// on the wire is not what the asset's provenance vouches for.
169    #[error("asset {0}: re-derived ciphertext does not match the manifest's ciphertext_hash")]
170    CiphertextMismatch(Uuid),
171    /// The plaintext original handed to [`adopt_remote_original`](Workspace::adopt_remote_original)
172    /// does not hash to the digest the entry's signed sidecar commits to: it is not the original
173    /// the chokepoint vouched for. Nothing of the asset was written.
174    #[error("asset {0}: the original handed over does not hash to its signed sidecar's digest")]
175    OriginalMismatch(Uuid),
176    /// [`upload_bundle`](Workspace::upload_bundle) was asked for an asset whose `create` binds a
177    /// metadata blob the library no longer holds: an edit replaced it before the library kept
178    /// the create's blob beside the chain, so neither copy answers the create's
179    /// `metadata_blob_hash`. An upload carries the create, so it cannot be built; nothing was
180    /// sent.
181    #[error(
182        "asset {0}: the metadata blob its create record binds was replaced by a later edit, so \
183         the create cannot be uploaded"
184    )]
185    CreateMetadataSuperseded(Uuid),
186    /// [`create_album_with_id`](Workspace::create_album_with_id) was called for an album that
187    /// already holds key material. Minting over it would discard the AMKs every existing asset in
188    /// that album was encrypted under, so it is refused; use
189    /// [`ensure_album`](Workspace::ensure_album) for resolve-or-create.
190    #[error("album {0} already exists")]
191    AlbumExists(Uuid),
192    /// [`bind_account_id`](Workspace::bind_account_id) was refused: the library already holds
193    /// assets whose signed manifests name its current account id, so adopting another would
194    /// contradict its own history.
195    #[error("account id cannot be rebound: {0}")]
196    AccountRebind(String),
197    /// [`cross_sign_device`](Workspace::cross_sign_device) was refused: the device or its
198    /// signing key is already in the directory, the entry arrived revoked, or the directory
199    /// version cannot advance. The directory is left unchanged.
200    #[error("device directory: {0}")]
201    Directory(#[from] DirectoryError),
202    /// [`extend_account_directory`](Workspace::extend_account_directory) was handed a directory
203    /// this workspace must not build on: its signature does not verify under this account's
204    /// user IK, or it names another account. Nothing is adopted.
205    #[error("untrusted account directory: {0}")]
206    UntrustedDirectory(String),
207    /// A label (or album name) was refused by the label rule: NFC, trimmed, 1–256 bytes.
208    #[error(transparent)]
209    InvalidLabel(#[from] LabelError),
210    /// A region shape broke the normalized-coordinate contract.
211    #[error(transparent)]
212    InvalidRegion(#[from] RegionError),
213    /// A location edit named a coordinate outside latitude `[-90, 90]` / longitude
214    /// `[-180, 180]`, or one that is not finite. Nothing is appended.
215    #[error("invalid location: lat {lat}, lon {lon}")]
216    InvalidLocation {
217        /// The refused latitude.
218        lat: f64,
219        /// The refused longitude.
220        lon: f64,
221    },
222    /// A stack or album label document could not be decoded, sealed or opened.
223    #[error(transparent)]
224    Document(#[from] DocError),
225    /// A stack or album label document does not verify under this account's user IK. Nothing
226    /// is merged.
227    #[error("document {0} does not verify under this account's identity key")]
228    UnverifiedDocument(Uuid),
229    /// Joining the asset to the stack would split the stack across container albums: every
230    /// member of a stack belongs to the same album.
231    #[error("stack {stack_id} lives in album {stack_album}; asset is in album {asset_album}")]
232    StackAlbumMismatch {
233        /// The stack being joined.
234        stack_id: Uuid,
235        /// The album the stack's members (or its label document) live in.
236        stack_album: Uuid,
237        /// The album of the asset that tried to join.
238        asset_album: Uuid,
239    },
240    /// [`reseal_create`](Workspace::reseal_create) was refused: the asset is not a create this
241    /// device can safely re-seal at the album's current epoch. Nothing was written.
242    #[error("asset {asset_id} cannot be re-sealed: {reason}")]
243    ResealRefused {
244        /// The asset the re-seal was asked for.
245        asset_id: Uuid,
246        /// Why it was refused.
247        reason: ResealRefusal,
248    },
249}
250
251type Result<T> = std::result::Result<T, LifecycleError>;
252
253/// One album's key material across one or more epochs.
254///
255/// Capsule separates **secrecy** from **authorization**: the per-epoch `amks` are the content
256/// keys (read access), while `write_tier` / `admin` are signing *capabilities*. A backup artifact
257/// escrows only the former, so an album restored into a library that never held it arrives with
258/// its content keys and no capabilities — see [`AlbumStore`](capsule_core::crypto::keys::AlbumStore).
259/// That state is modelled honestly here rather than papered over by minting fresh signing keys
260/// that attest nothing and no peer trusts.
261pub struct AlbumKeys {
262    /// Album id.
263    pub album_id: Uuid,
264    /// Display name.
265    pub name: String,
266    /// AMKs by epoch.
267    pub amks: BTreeMap<u32, [u8; 32]>,
268    /// Per-album write-tier signing key; `None` for a read-only recovered album.
269    pub write_tier: Option<HybridSigningKey>,
270    /// Per-album admin signing key (the epoch-ledger root); `None` for a read-only recovered
271    /// album.
272    pub admin: Option<HybridSigningKey>,
273    /// The current (highest) epoch — the one new imports are written under.
274    pub current_epoch: u32,
275}
276
277impl AlbumKeys {
278    /// The write-tier signing key every asset manifest in this album is signed under, or
279    /// [`LifecycleError::AlbumReadOnly`] if this album carries no write capability.
280    pub fn write_tier_signer(&self) -> Result<&HybridSigningKey> {
281        self.write_tier
282            .as_ref()
283            .ok_or(LifecycleError::AlbumReadOnly(self.album_id))
284    }
285
286    /// The admin signing key that roots the epoch ledger, or [`LifecycleError::AlbumReadOnly`].
287    pub fn admin_signer(&self) -> Result<&HybridSigningKey> {
288        self.admin
289            .as_ref()
290            .ok_or(LifecycleError::AlbumReadOnly(self.album_id))
291    }
292}
293
294/// In-memory state for one managed asset.
295pub struct AssetState {
296    /// Asset id (== file_id).
297    pub asset_id: Uuid,
298    /// Owning album.
299    pub album_id: Uuid,
300    /// Original file extension (lowercase).
301    pub ext: String,
302    /// UTC seconds used for date bucketing on disk.
303    pub capture_utc: i64,
304    /// The provenance chain.
305    pub chain: ProvenanceChain,
306    /// The signed sidecar.
307    pub sidecar: SidecarV1,
308    /// The **exact** sealed metadata-blob wire bytes the current metadata-bearing manifest
309    /// commits to via `metadata_blob_hash`. Because [`seal_metadata_blob`] draws a fresh nonce
310    /// per call (folded into the blob key), the blob cannot be regenerated deterministically
311    /// from the plaintext sidecar (unlike the asset ciphertext, which is re-derived from the
312    /// recorded `nonce_prefix`), so the bytes are retained to keep the content address stable
313    /// across export. Re-sealed on every
314    /// metadata-bearing write ([`Action::binds_metadata_blob`]); untouched by `delete` /
315    /// `trash-restore`, which mint no new blob.
316    ///
317    /// [`seal_metadata_blob`]: capsule_core::crypto::encryption::seal_metadata_blob
318    pub metadata_blob: Vec<u8>,
319    /// Placement within a multi-file stack (RAW+JPEG, Live Photo, …) when this asset was
320    /// imported as a stack member; `None` for a standalone asset. Drives the queryable index
321    /// row's `stack_id` / `is_stack_hidden` so a hidden secondary member stays out of the
322    /// timeline exactly as the legacy importer arranged.
323    pub stack: Option<StackPlacement>,
324}
325
326/// The **index projection** of an asset's stack membership: the two `assets` columns
327/// (`stack_id`, `is_stack_hidden`) that keep a non-primary member out of the timeline.
328///
329/// This is a *derived* value, not a source of truth: the durable record is the
330/// sidecar's signed `stack_membership` register, which both the importer and
331/// [`Workspace::set_stack_membership`] write. It survives here for the one case the register
332/// cannot serve — an asset imported **before** the importer wrote that register, whose
333/// placement was written only to the index and therefore exists nowhere else (see [`Workspace::open`] step (6) and
334/// [`library::rebuild_index`](crate::library::rebuild_index)).
335#[derive(Debug, Clone)]
336pub struct StackPlacement {
337    /// The shared stack id (the `asset_stacks` row id the members belong to).
338    pub stack_id: String,
339    /// Whether this member is hidden from the timeline (true for every non-primary member).
340    pub hidden: bool,
341}
342
343impl StackPlacement {
344    /// The index projection of a signed [`StackMembership`] — the one mapping the write path and
345    /// [`library::rebuild`](crate::library::rebuild) must agree on: a member is suppressed from
346    /// the timeline exactly when it is not the stack's primary.
347    pub(crate) fn from_membership(m: &StackMembership) -> Self {
348        Self {
349            stack_id: m.stack_id.to_string(),
350            hidden: m.role != StackRole::Primary,
351        }
352    }
353}
354
355/// Out-of-band metadata a third-party [source adapter](crate::import::SourceAdapter) folded for
356/// one media file, in the shape the signed sidecar stores it.
357///
358/// The [precedence rule] is resolved in two places, and this type is what keeps the two halves
359/// apart:
360///
361/// - [`capture_time`](Self::capture_time) and [`gps`](Self::gps) are **fallbacks**. The file's
362///   own embedded EXIF wins wherever it yields a value; these are consulted only where it does
363///   not. Because the adapter already folded EXIF-over-exporter at extraction, the value carried
364///   here is the *winner* of that fold — so an EXIF capture time the write site cannot resolve
365///   to a UTC instant by itself (a floating `DateTimeOriginal` carrying no offset) still beats
366///   the exporter's record instead of silently losing to it.
367/// - [`caption`](Self::caption), [`rating`](Self::rating) and [`tags`](Self::tags) are
368///   **exporter-authoritative** — constructs the file bytes never carried — so they are written
369///   unconditionally, stamped `(now, device_id)` like any other register write.
370///
371/// Every field left empty writes nothing, so an import carrying no exporter record produces a
372/// sidecar byte-identical to a plain filesystem import's. The provider-specific mapping that
373/// fills this in lives in [`import::sidecar_enrichment`](crate::import::sidecar_enrichment).
374///
375/// [precedence rule]: https://docs/design/import/pipeline/#third-party-importers
376#[derive(Debug, Clone, Default, PartialEq)]
377pub struct SidecarEnrichment {
378    /// The adapter's folded capture time — used only when the file's own EXIF resolves none.
379    pub capture_time: Option<Timestamp>,
380    /// The adapter's folded GPS fix — used only when the file's own EXIF carries none.
381    pub gps: Option<Gps>,
382    /// The exporter's user-typed description, bounded to the schema's caption limit.
383    pub caption: Option<String>,
384    /// The exporter's favorite/star flag, already mapped onto the sidecar's star scale.
385    pub rating: Option<u8>,
386    /// Exporter-authoritative user tags (Takeout's album membership); each becomes one
387    /// `tags_user` OR-set add with its own `add_id`, after the label rule
388    /// ([`normalize_label`](capsule_core::sidecar::normalize_label)); a tag the rule refuses is
389    /// dropped and the import proceeds.
390    pub tags: Vec<String>,
391}
392
393/// Options for a signed import driven by the import executor. Defaults (`Copy` mode, no stack,
394/// no exporter metadata) reproduce the standalone [`Workspace::import_asset`] behaviour.
395#[derive(Debug, Clone, Default)]
396pub struct SignedImportOptions {
397    /// Delete the source file after a durable commit (Move mode).
398    pub move_source: bool,
399    /// Defer Move-mode source deletion to the caller's verify-before-destroy gate
400    /// ([`release_move_source`](crate::library::release_move_source)) instead of
401    /// releasing on the local durable commit. Set by every import of a user's file — the
402    /// executor and streaming import — because the source is the only other copy until
403    /// the *server* durably holds it (invariant 7); the caller releases it through
404    /// [`Workspace::release_move_source`]. Left `false` only where the source is scratch the
405    /// library made itself ([`Workspace::import_bytes`]).
406    pub defer_source_release: bool,
407    /// Signed stack membership for a multi-file candidate member. Written into the
408    /// sidecar's `stack_membership` LWW register — the same durable write
409    /// [`Workspace::set_stack_membership`] performs — and projected from there onto the index
410    /// row. `None` imports a standalone asset and leaves the register wire-absent.
411    pub stack: Option<StackMembership>,
412    /// Folded third-party exporter metadata for this file, attached by the
413    /// [executor](crate::import::execute_with_source_metadata) when the import came
414    /// from a [source adapter](crate::import::SourceAdapter). `None` — a plain filesystem
415    /// import — leaves every enriched field exactly as it was before this change.
416    pub enrichment: Option<SidecarEnrichment>,
417}
418
419/// What one signed import produced: the asset's id plus whether derivatives could be generated
420/// for it.
421///
422/// Returned by [`Workspace::import_asset_with`] so the executor can report the derivative gap
423/// without re-deriving it from the file extension.
424/// [`import_asset`](Workspace::import_asset) keeps returning the bare [`Uuid`] for the many
425/// callers that only need the id.
426#[derive(Debug, Clone, Copy, PartialEq, Eq)]
427pub struct SignedImport {
428    /// The imported asset's id.
429    pub asset_id: Uuid,
430    /// Whether thumbnail/preview derivatives were generated, and if not, why.
431    pub derivatives: DerivativeStatus,
432    /// How many `(tier, format)` pairs the tier table commits to and this build cannot encode
433    /// — the per-format half of the no-codec gap, which is orthogonal to
434    /// [`derivatives`](Self::derivatives): a `Decoded` asset can still carry deferred formats.
435    /// Zero when the still did not decode at all, because nothing was attempted.
436    pub deferred_formats: u32,
437}
438
439/// A streamed import: everything the [streaming window](crate::import::execute_streaming) needs
440/// about one just-imported asset to drive its upload → verify → release step, without exposing
441/// workspace internals. Produced by [`Workspace::import_asset_streaming`], which commits on the
442/// signed path with source release **deferred** to the server-side verify-before-destroy gate,
443/// since in streaming mode the local bytes are the only copy until the *server* durably
444/// holds them.
445#[derive(Debug, Clone)]
446pub struct StreamedImport {
447    /// The imported asset's id.
448    pub asset_id: Uuid,
449    /// The declared blob content-addresses the release gate re-checks: the original ciphertext
450    /// and the sealed metadata blob (the always-present required blobs).
451    pub blob_hashes: Vec<Hash32>,
452    /// The local library original's path — released (its file deleted and owned-original
453    /// representation row dropped) only on a `durable` verdict.
454    pub local_original: PathBuf,
455    /// The external Move-mode source path, if any — deleted only on a `durable` verdict.
456    pub move_source: Option<PathBuf>,
457}
458
459/// An offline Capsule workspace over a client library directory.
460pub struct Workspace {
461    root: PathBuf,
462    account: Account,
463    /// Signs the device directory and every asset manifest with the device DSK. A software key
464    /// by default; a [hardware-backed signer](capsule_core::crypto::keys::HardwareBackedSigner) when
465    /// the device key lives in a secure element. The account's own software DSK is retained
466    /// (sealed) but unused for signing when a hardware signer is supplied.
467    device_signer: Box<dyn Signer>,
468    directory: DeviceDirectory,
469    /// The `client_version` / `generated_by_client` this workspace stamps on every manifest and
470    /// derivative it authors. Defaults to the bare-core
471    /// [`capsule-core/{semver}+{commit}`](capsule_core::client_build::core_client_version) identity; an
472    /// app injects its own product id via [`with_client_id`](Self::with_client_id) (CLI) or the
473    /// FFI constructor (native apps) so each client reports itself rather than `capsule-core`.
474    client_version: String,
475    counter: Counter,
476    albums: HashMap<Uuid, AlbumKeys>,
477    /// Per-album write authority behind the [`AlbumAuthority`](capsule_core::crypto::authority::AlbumAuthority)
478    /// seam (`&Authority` coerces to `&dyn AlbumAuthority` at every `verify_asset` call site). The
479    /// offline [`ReferenceAuthority`](capsule_core::crypto::authority::ReferenceAuthority) is the shipped
480    /// default; the enum lets the live
481    /// [`OpenMlsAuthority`](capsule_core::crypto::authority::OpenMlsAuthority) drop in without the
482    /// lifecycle naming a concrete backend. **Persisted** alongside the album keys in
483    /// [`AlbumStore`](capsule_core::crypto::keys::AlbumStore) and restored on open — without
484    /// it a reopened library could hold an AMK and still not verify a single manifest.
485    authorities: HashMap<Uuid, Authority>,
486    assets: HashMap<Uuid, AssetState>,
487    /// The reconciled [aggregated-album](capsule_core::federation) group assertion for each album the
488    /// workspace can see, keyed by album id. An own album's entry is self-authored via
489    /// [`create_album_group`](Self::create_album_group) / [`join_album_group`](Self::join_album_group);
490    /// a peer constituent's entry is folded in from the feed via
491    /// [`merge_album_group_assertion`](Self::merge_album_group_assertion). Removing an entry is a
492    /// group *leave* — it drops the constituent from every viewer's aggregate on their next sync.
493    ///
494    /// **Deliberately session-scoped**: every entry is a self-verifying signed
495    /// assertion that the federation feed re-delivers, so it is a cache of reconcilable state,
496    /// not key material. Losing it on close costs one reconcile, not access.
497    group_assertions: HashMap<Uuid, AlbumGroupAssertion>,
498    /// The open, locked library — its `library.sqlite` is the queryable index the crypto
499    /// lifecycle writes through to. Held for the workspace's lifetime so the lock is retained.
500    library: Library,
501    /// Argon2id cost the account was created under; reused for the optional passphrase wrap
502    /// on share links so a share's cost matches the device tier.
503    argon2_params: Argon2Params,
504    /// Issued share links keyed by their revocation handle — the authoritative link records
505    /// the serving endpoint consults for scope, expiry, and revocation state.
506    ///
507    /// **Deliberately session-scoped**: the durable registry these mirror lives on the
508    /// serving side, and a link's *secret* travels in the URL rather than here, so persisting the
509    /// local copy is a link-management concern (revoke-after-restart) rather than a data-plane
510    /// key-loss one. Tracked with the share-link slices, not with album keys.
511    share_links: HashMap<ShareLinkId, ShareLinkRecord>,
512    /// Issued upload (guest-drop) links keyed by their revocation handle. Each holds the
513    /// escrow-wrapped Drop Key private half so any of this owner's adopting devices can
514    /// later decapsulate a drop sealed to it (SSoT: [Web Upload]).
515    ///
516    /// **Session-scoped, and the one deferral here that is real key material**: closing
517    /// a workspace with an outstanding upload link drops the escrowed Drop Key private half, so a
518    /// drop sealed to that link can no longer be adopted. It is deferred rather than folded into
519    /// [`AlbumStore`](capsule_core::crypto::keys::AlbumStore) because the link registry is
520    /// server-authoritative and its durable shape belongs with the guest-drop slices — an album
521    /// keystore is the wrong home for a per-link escrow table. Until then a guest-drop flow must
522    /// complete within one workspace session.
523    ///
524    /// [Web Upload]: https://docs/design/web-upload/
525    upload_links: HashMap<UploadLinkId, IssuedLink>,
526    /// Pending guest drops in this user's inbox, keyed by drop id. Models the server's
527    /// staging store (the server's drop module) so the offline core can drive the
528    /// full seal → stage → adopt path; a real client fills it from server responses.
529    ///
530    /// **Deliberately session-scoped**: the server's staging store is the authority and
531    /// a client refills this from it, so there is nothing here to lose.
532    inbox: HashMap<DropId, InboxEntry>,
533    /// The `{uuid}.cbor` files under `media/` that no provenance chain anchors, found at
534    /// [`open`](Self::open): the debris of an interrupted write, a torn or foreign file, or a
535    /// retired unsigned record. Empty for a library with no debris.
536    unanchored: Vec<UnanchoredSidecar>,
537    /// The purged assets, each with the whole provenance chain a purge keeps on disk, headed
538    /// by the `delete` that ended it. This is the peering tombstone the workspace owns, and the
539    /// chain a held delete (and an early purge's re-issue) is delivered from once the server
540    /// indexes the create. It is filled by [`purge_at`](Self::purge_at) and, on
541    /// [`open`](Self::open), from every kept chain whose head is a `delete` with no sidecar
542    /// beside it, so a reopen or rebuild reproduces it from the provenance file alone.
543    purged: BTreeMap<Uuid, ProvenanceChain>,
544}
545
546fn now_rfc3339() -> String {
547    Timestamp::now().to_string()
548}
549
550/// The shard subdirectory holding the metadata blob each superseded `create` binds
551/// ([`Workspace::create_metadata_blob_path`]).
552const CREATE_METADATA_DIR: &str = "create-metadata";
553
554fn media_dir(root: &Path, capture_utc: i64) -> PathBuf {
555    let date = Timestamp::from_second(capture_utc)
556        .unwrap_or(Timestamp::UNIX_EPOCH)
557        .to_zoned_datetime(jiff::tz::TimeZone::UTC)
558        .date();
559    root.join("media")
560        .join(format!("{:04}", date.year()))
561        .join(format!("{:04}-{:02}", date.year(), date.month()))
562}
563
564/// `media/{YYYY}/{YYYY-MM}/{uuid}.{ext}` — an asset's original, nameable before its
565/// [`AssetState`] exists (an import stages the original there while it encrypts it).
566fn media_file_path(root: &Path, capture_utc: i64, asset_id: Uuid, ext: &str) -> PathBuf {
567    media_dir(root, capture_utc).join(format!("{}.{ext}", asset_id.simple()))
568}
569
570/// Whether an asset is currently in trash — derived by replaying its provenance chain's
571/// lifecycle actions (a `delete` moves it to trash; a later `trash-restore` brings it back).
572/// The chain is the single source of truth, so a swept (reject-swept) asset is exactly one
573/// whose head lifecycle state is deleted.
574fn asset_is_deleted(asset: &AssetState) -> bool {
575    let mut deleted = false;
576    for rec in asset.chain.records() {
577        match rec.manifest.core.action {
578            Action::Delete => deleted = true,
579            Action::TrashRestore => deleted = false,
580            _ => {}
581        }
582    }
583    deleted
584}
585
586impl Workspace {
587    /// The account's user id.
588    pub fn user_id(&self) -> Uuid {
589        self.account.user_id
590    }
591
592    /// This account's user identity **public** key — the key an album-group assertion (and any
593    /// user-IK-signed artifact this workspace authors) verifies against.
594    pub fn user_ik_public(&self) -> HybridVerifyingKey {
595        self.account.user_ik.verifying_key()
596    }
597
598    /// This device's stable id — the `created_by_device` every manifest this workspace
599    /// authors carries, and the [`DeviceEntry`](capsule_core::crypto::keys::DeviceEntry)
600    /// key under which its signing key is published in the device directory.
601    pub fn device_id(&self) -> Uuid {
602        self.account.device.device_id
603    }
604
605    /// This device's hybrid **device signer** — the key published for
606    /// [`device_id`](Self::device_id) in the device directory: the account's software device key,
607    /// or the hardware-backed signer the workspace was created with. A peering handshake signs its
608    /// channel binding with it to prove this device's identity to a peer. The private key never
609    /// leaves the signer; this lends the signing capability, not the key.
610    pub fn device_signer(&self) -> &dyn Signer {
611        self.device_signer.as_ref()
612    }
613
614    /// This workspace's **signed device directory** — the user-IK-signed list of enrolled
615    /// device signing keys `verify_asset` resolves a manifest's `created_by_device` against.
616    ///
617    /// Exposed so a client can publish it (the device-directory surface, driven from
618    /// the SDK by `capsule_sdk::directory`). The directory is a signed, self-verifying
619    /// document: it carries no private key material, and a reader checks it under
620    /// [`user_ik_public`](Self::user_ik_public) before trusting a single entry.
621    pub fn device_directory(&self) -> &DeviceDirectory {
622        &self.directory
623    }
624
625    /// The account's default album id (derived from the master key).
626    pub fn default_album_id(&self) -> Uuid {
627        self.account.master.derive_default_album_id()
628    }
629
630    /// The library root directory this workspace writes through. The streaming executor probes
631    /// its volume's free space ([`available_bytes`](crate::library::available_bytes)) for the
632    /// minimum-headroom check.
633    pub fn root(&self) -> &Path {
634        &self.root
635    }
636
637    fn provenance_path(&self, asset: &AssetState) -> PathBuf {
638        media_dir(&self.root, asset.capture_utc)
639            .join(format!("{}.provenance.cbor", asset.asset_id.simple()))
640    }
641    fn sidecar_path(&self, asset: &AssetState) -> PathBuf {
642        media_dir(&self.root, asset.capture_utc).join(format!("{}.cbor", asset.asset_id.simple()))
643    }
644    fn media_path(&self, asset: &AssetState) -> PathBuf {
645        media_file_path(&self.root, asset.capture_utc, asset.asset_id, &asset.ext)
646    }
647    /// `media/{YYYY}/{YYYY-MM}/{uuid}.metadata.bin` — the **exact** sealed metadata-blob wire
648    /// bytes the asset's metadata-bearing manifest commits to via `metadata_blob_hash`
649    /// ([`AssetState::metadata_blob`]).
650    ///
651    /// Persisted to disk. The blob is AMK ciphertext, so it is safe at rest beside the
652    /// plaintext original, and it cannot be regenerated: [`seal_metadata_blob`] draws a fresh
653    /// nonce per call which is folded into the blob key, so re-sealing the same sidecar produces
654    /// different bytes and a different content address. Without these bytes on disk a reopened
655    /// library can neither `export_backup` nor upload the asset.
656    ///
657    /// [`seal_metadata_blob`]: capsule_core::crypto::encryption::seal_metadata_blob
658    fn metadata_blob_path(&self, asset: &AssetState) -> PathBuf {
659        media_dir(&self.root, asset.capture_utc)
660            .join(format!("{}.metadata.bin", asset.asset_id.simple()))
661    }
662    /// `media/{YYYY}/{YYYY-MM}/create-metadata/{uuid}.bin` — the **exact** sealed metadata blob
663    /// the asset's `create` record binds, kept once a later edit has replaced
664    /// [`AssetState::metadata_blob`] (written by `append_lifecycle`, read by
665    /// [`upload_bundle`](Self::upload_bundle)).
666    ///
667    /// An upload carries the create, and the server takes the create only with the bytes its
668    /// `metadata_blob_hash` names, which cannot be re-sealed. So the first edit copies them here
669    /// before it replaces them, and they stay for the asset's life, whichever servers have since
670    /// taken the create: only a purge removes them. (A re-seal never meets one: it replaces only
671    /// a chain that is its create alone, and the file appears with the first record after it.)
672    ///
673    /// A subdirectory of the shard rather than a `{uuid}.*` sibling, so a client that predates it
674    /// cannot take it for the original (its `original_extension` reads only `{uuid}.*` names);
675    /// a library without the file reads exactly as before.
676    fn create_metadata_blob_path_of(&self, asset: &AssetState) -> PathBuf {
677        media_dir(&self.root, asset.capture_utc)
678            .join(CREATE_METADATA_DIR)
679            .join(format!("{}.bin", asset.asset_id.simple()))
680    }
681
682    /// The on-disk path of the metadata blob kept for a managed asset's `create` record, or
683    /// `None` for an unknown id. The file exists only once an edit superseded that blob. Exposed
684    /// so a client test can stand in for a library written before the blob was kept.
685    pub fn create_metadata_blob_path(&self, asset_id: &Uuid) -> Option<PathBuf> {
686        self.assets
687            .get(asset_id)
688            .map(|asset| self.create_metadata_blob_path_of(asset))
689    }
690
691    /// The plaintext bytes of a managed asset (reads from disk).
692    pub fn read_plaintext(&self, asset_id: &Uuid) -> Result<Vec<u8>> {
693        let asset = self
694            .assets
695            .get(asset_id)
696            .ok_or_else(|| LifecycleError::NotFound(format!("asset {asset_id}")))?;
697        fs::read(self.media_path(asset)).map_err(|e| LifecycleError::Io(e.to_string()))
698    }
699
700    /// All managed asset ids.
701    pub fn asset_ids(&self) -> Vec<Uuid> {
702        self.assets.keys().copied().collect()
703    }
704
705    /// The on-disk path of a managed asset's plaintext original, or `None` for an unknown id.
706    ///
707    /// The path is derived from the asset's **shard** (`AssetState::capture_utc`), which is
708    /// fixed at import — so it keeps resolving after a capture-time correction
709    /// ([`set_capture_timestamp`](Self::set_capture_timestamp)) even though the sidecar's
710    /// timestamp no longer names the month directory. Exposed for the repair pass, which has
711    /// to re-read each original's EXIF without loading every file through
712    /// [`read_plaintext`](Self::read_plaintext).
713    pub fn original_path(&self, asset_id: &Uuid) -> Option<PathBuf> {
714        self.assets
715            .get(asset_id)
716            .map(|asset| self.media_path(asset))
717    }
718
719    /// Whether a managed asset is currently in trash — a replay of its provenance chain's
720    /// lifecycle actions (a `delete` moves it to trash, a later `trash-restore` brings it
721    /// back), which is the single source of truth the workspace itself applies. `false` for an
722    /// unknown id. Exposed so a client can report or skip trashed assets without re-deriving
723    /// the rule from the chain.
724    pub fn is_trashed(&self, asset_id: &Uuid) -> bool {
725        self.assets.get(asset_id).is_some_and(asset_is_deleted)
726    }
727
728    /// A managed asset's current state.
729    pub fn asset(&self, asset_id: &Uuid) -> Option<&AssetState> {
730        self.assets.get(asset_id)
731    }
732
733    /// The library's queryable SQLite index — the timeline, user tags, and cached representations
734    /// the crypto lifecycle writes through to.
735    pub fn db(&self) -> &DatabaseDriver {
736        &self.library.db
737    }
738
739    /// This device's published **DEK** public encapsulation key — the bytes a peer (or this
740    /// account's own escrow path) wraps a key to so only this device can open it.
741    ///
742    /// Length-tagged by composition: 1216 bytes for the software X-Wing DEK, 1249 for
743    /// the hardware-bound P-256 hybrid, so a recipient never has to be told which it is holding
744    /// and the two can never be confused for one another.
745    pub fn device_dek_public(&self) -> Vec<u8> {
746        self.account.device.dek.public_bytes()
747    }
748
749    /// Recover the 32-byte shared secret from a ciphertext sealed to
750    /// [`device_dek_public`](Self::device_dek_public).
751    ///
752    /// When the DEK is hardware-bound this performs the classical ECDH **inside the secure
753    /// element** — the device's P-256 scalar is never in this process's memory — so it can fail on
754    /// a cancelled biometric or an evicted key as well as on a malformed ciphertext.
755    pub fn device_dek_decapsulate(&self, ciphertext: &[u8]) -> Result<[u8; 32]> {
756        Ok(self.account.device.dek.decapsulate(ciphertext)?)
757    }
758
759    /// Whether this workspace's DEK has its classical half in a secure element rather
760    /// than in software — the honest answer to "is this device actually hardware-bound", read
761    /// from the account's own recorded binding rather than from whether an element was offered.
762    pub fn device_dek_is_hardware_bound(&self) -> bool {
763        self.account.device.dek.is_hardware_bound()
764    }
765}
766
767/// The trivially-fast Argon2id cost the `lifecycle` suite derives under. Named, rather than
768/// spelled out per call, because a test now hands it to explicit-parameter entry points
769/// (`Workspace::create_with_params`, `Workspace::export_backup_with_params`) instead of getting
770/// a cheap cost from a `#[cfg(test)]` fork inside the library.
771#[cfg(test)]
772const FAST_PARAMS: Argon2Params = Argon2Params {
773    mem_kib: 64,
774    t_cost: 1,
775    p_cost: 1,
776};
777
778/// A fast-Argon2 workspace over `dir` — the shared fixture every `lifecycle` test module
779/// builds on (the production cost would dominate the suite's runtime).
780#[cfg(test)]
781fn fast_workspace(dir: &Path) -> Workspace {
782    Workspace::create_with_params(dir, b"passphrase", FAST_PARAMS).unwrap()
783}