Skip to main content

capsule_sdk/ffi/
workspace.rs

1//! The **workspace verbs** of the `capsule_sdk` uniffi namespace — enroll,
2//! create an album, seal + import an asset, verify, sync-apply, mint an escrow, publish a
3//! directory, label regions, stacks and albums, move assets through the trash — over
4//! `capsule-core`'s [`Workspace`].
5//!
6//! # What this layer is, and is not
7//!
8//! It is **orchestration and shape**: it locks one `Workspace`, converts ids and blobs at the
9//! boundary, and flattens core's rich enums into `Ffi*` mirrors an app can switch on. Every
10//! cryptographic step — key derivation, STREAM encryption, manifest signing, the
11//! [`verify_asset`] chokepoint, metadata sealing and opening, escrow wrapping — happens inside
12//! `capsule-core`, reached through exactly one call per verb. There is no second implementation
13//! of any of it here, and adding one would be a defect rather than an optimization.
14//!
15//! # Core's seams, declared in this namespace
16//!
17//! `capsule-core` exports no uniffi namespace (ADR-0005): its hardware seams are plain Rust
18//! traits. So the seams a native element implements are declared here in *this* namespace —
19//! [`FfiHardwareSigner`], [`FfiHardwareKeyAgreement`] and [`FfiHardwareSignerError`] mirror
20//! core's `HardwareSigner`, `HardwareKeyAgreement` and `HardwareSignerError`, and
21//! `ForeignHardwareSigner` / `ForeignKeyAgreement` adapt one to the other. They are declarations of the same contract,
22//! not a second implementation of it: not a byte of signing or key-agreement logic lives here.
23//!
24//! # Transport independence
25//!
26//! Every verb below is `capsule-core`-facing. None of them names the SDK's network stack, so
27//! the pending re-fronting of the sync half on REST changes nothing in this file's signatures:
28//! the bytes a feed entry carries are the same bytes whatever delivered them, and
29//! [`FfiWorkspace::upload_blobs`] hands back requests that
30//! [`FfiSession::upload`](crate::ffi::FfiSession::upload) drives regardless of what is
31//! underneath it.
32//!
33//! [`verify_asset`]: capsule_core::crypto::verify_asset::verify_asset
34//! [`Workspace`]: capsule_library::lifecycle::Workspace
35
36use std::collections::HashMap;
37use std::path::{Path, PathBuf};
38use std::sync::{Arc, Mutex};
39
40use capsule_core::crypto::hash::{Hash32, hash_bytes};
41use capsule_core::crypto::keys::{
42    HardwareBackedSigner, HardwareKeyAgreement, HardwareSigner, HardwareSignerError, P256HybridDek,
43    Signer, encapsulate_to_p256_public,
44};
45use capsule_core::crypto::primitives::DeviceTier;
46use capsule_core::crypto::provenance::ProvenanceRecord;
47use capsule_core::crypto::verify_asset::VerifyOutcome;
48use capsule_core::sidecar::{
49    LabelError, Region, RegionError, RegionShape, SidecarV1, normalize_label,
50};
51use capsule_library::lifecycle::{
52    Adoption, FeedDrain, HardwareSignerBinding, LifecycleError, QuarantineReason, RemoteAssetFacts,
53    RemoteEntry, RemoteHead, RemoteOriginal, SyncApplyOutcome, TrashEntry, UploadBundle, Workspace,
54    hash_ciphertext_from,
55};
56use jiff::Timestamp;
57use uuid::Uuid;
58
59use super::{FfiError, FfiUploadRequest};
60use crate::upload::UploadError;
61
62// ─── Hardware-signer seam (this namespace's declaration of core's contract) ───
63
64/// Failure surfaced by a foreign [`FfiHardwareSigner`]. Mirrors `capsule-core`'s
65/// `HardwareSignerError` variant for variant — it is the same contract, declared in the
66/// `capsule_sdk` namespace because core's own type carries no uniffi derive.
67///
68/// The error is **thrown by foreign code** — it is the declared error of the
69/// [`FfiHardwareSigner`] and [`FfiHardwareKeyAgreement`] foreign traits — so Rust must *lift*
70/// it, and uniffi lifts only a non-flat error. Every variant therefore carries a named
71/// `detail` field (the element's own English diagnostic), which also gives the Kotlin
72/// exceptions and Swift cases the same `(detail)` shape. Core's error keeps `detail` only on
73/// [`Backend`](Self::Backend); for the other variants it is logged at the seam and dropped.
74#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error, uniffi::Error)]
75pub enum FfiHardwareSignerError {
76    /// The user cancelled the biometric / the element refused authentication.
77    #[error("hardware authentication cancelled: {detail}")]
78    AuthCancelled {
79        /// The element's English diagnostic.
80        detail: String,
81    },
82    /// No secure element is available on this device.
83    #[error("hardware secure element unavailable: {detail}")]
84    Unavailable {
85        /// The element's English diagnostic.
86        detail: String,
87    },
88    /// No key exists for the requested alias.
89    #[error("hardware key not found: {detail}")]
90    NotFound {
91        /// The element's English diagnostic.
92        detail: String,
93    },
94    /// The private key was readable — non-exportability is violated (a failure).
95    #[error("hardware private key is exportable: {detail}")]
96    Exportable {
97        /// The element's English diagnostic.
98        detail: String,
99    },
100    /// Any other backend error.
101    #[error("hardware backend error: {detail}")]
102    Backend {
103        /// The element's English diagnostic.
104        detail: String,
105    },
106}
107
108/// A foreign element that throws something other than [`FfiHardwareSignerError`] (an
109/// unchecked `KeyStoreException`, a Swift error of another type) or breaks the FFI contract
110/// reaches Rust as an *unexpected* callback error. Without this conversion uniffi panics on
111/// it — inside a workspace call, with the workspace lock held — so it is lifted as a typed
112/// [`Backend`](FfiHardwareSignerError::Backend) failure instead.
113impl From<uniffi::UnexpectedUniFFICallbackError> for FfiHardwareSignerError {
114    fn from(err: uniffi::UnexpectedUniFFICallbackError) -> Self {
115        tracing::warn!(reason = %err.reason, "ffi: hardware element threw an undeclared error");
116        Self::Backend { detail: err.reason }
117    }
118}
119
120impl From<FfiHardwareSignerError> for HardwareSignerError {
121    fn from(err: FfiHardwareSignerError) -> Self {
122        tracing::debug!(error = %err, "ffi: hardware element refused");
123        match err {
124            FfiHardwareSignerError::AuthCancelled { .. } => Self::AuthCancelled,
125            FfiHardwareSignerError::Unavailable { .. } => Self::Unavailable,
126            FfiHardwareSignerError::NotFound { .. } => Self::NotFound,
127            FfiHardwareSignerError::Exportable { .. } => Self::Exportable,
128            FfiHardwareSignerError::Backend { detail } => Self::Backend(detail),
129        }
130    }
131}
132
133/// The per-platform secure element (Secure Enclave, StrongBox, TPM), implemented by native
134/// Swift/Kotlin over the uniffi foreign-trait boundary.
135///
136/// The byte shapes are fixed by the constructor the element is handed to, not by the trait:
137///
138/// - [`FfiWorkspace::create_with_p256_hardware_signer`] and
139///   [`FfiWorkspace::open_with_p256_hardware_signer`] — the **P-256** shape shipping
140///   elements actually provide: [`enroll`](Self::enroll) /
141///   [`classical_public_key`](Self::classical_public_key) return a SEC1 public key and
142///   [`sign_classical`](Self::sign_classical) a **DER-encoded ECDSA** signature over
143///   `SHA-256(msg)`.
144/// - [`FfiWorkspace::create_with_hardware_signer`] — the **Ed25519** shape: a 32-byte public
145///   key and a 64-byte signature over `msg`. No shipping secure element holds Ed25519 keys, so
146///   this is the software/TPM reference path.
147///
148/// Either way Rust composes the classical half with a software-sealed ML-DSA-65 half into the
149/// published hybrid device key.
150#[uniffi::export(with_foreign)]
151pub trait FfiHardwareSigner: Send + Sync {
152    /// Generate (or bind to) the hardware keypair for `key_alias`, returning its public key in
153    /// the constructor's shape: a SEC1 P-256 key for
154    /// [`FfiWorkspace::create_with_p256_hardware_signer`], a 32-byte Ed25519 key for
155    /// [`FfiWorkspace::create_with_hardware_signer`]. Idempotent per alias.
156    fn enroll(&self, key_alias: String) -> Result<Vec<u8>, FfiHardwareSignerError>;
157
158    /// The public key for an already-enrolled `key_alias`, in the same constructor-dependent
159    /// shape [`enroll`](Self::enroll) returns (SEC1 P-256, or 32-byte Ed25519).
160    fn classical_public_key(&self, key_alias: String) -> Result<Vec<u8>, FfiHardwareSignerError>;
161
162    /// Sign `msg` with the hardware key for `key_alias`, in the constructor's shape: a
163    /// DER-encoded ECDSA signature over `SHA-256(msg)` for
164    /// [`FfiWorkspace::create_with_p256_hardware_signer`], a 64-byte Ed25519 signature over
165    /// `msg` for [`FfiWorkspace::create_with_hardware_signer`].
166    fn sign_classical(
167        &self,
168        key_alias: String,
169        msg: Vec<u8>,
170    ) -> Result<Vec<u8>, FfiHardwareSignerError>;
171
172    /// Non-exportability assertion: a conforming element MUST refuse to reveal the private
173    /// bytes, returning [`FfiHardwareSignerError::Exportable`] if they can be read.
174    fn assert_non_exportable(&self, key_alias: String) -> Result<(), FfiHardwareSignerError>;
175}
176
177/// Adapts a foreign [`FfiHardwareSigner`] to `capsule-core`'s `HardwareSigner`, so the core
178/// composition (`P256HybridSigningKey::enroll`) drives the native element unchanged. Pure
179/// delegation — every call forwards, and only the error type is translated.
180struct ForeignHardwareSigner(Arc<dyn FfiHardwareSigner>);
181
182impl HardwareSigner for ForeignHardwareSigner {
183    fn enroll(&self, key_alias: String) -> Result<Vec<u8>, HardwareSignerError> {
184        self.0.enroll(key_alias).map_err(Into::into)
185    }
186    fn classical_public_key(&self, key_alias: String) -> Result<Vec<u8>, HardwareSignerError> {
187        self.0.classical_public_key(key_alias).map_err(Into::into)
188    }
189    fn sign_classical(
190        &self,
191        key_alias: String,
192        msg: Vec<u8>,
193    ) -> Result<Vec<u8>, HardwareSignerError> {
194        self.0.sign_classical(key_alias, msg).map_err(Into::into)
195    }
196    fn assert_non_exportable(&self, key_alias: String) -> Result<(), HardwareSignerError> {
197        self.0.assert_non_exportable(key_alias).map_err(Into::into)
198    }
199}
200
201/// The per-platform **key-agreement** element (Secure Enclave `P256.KeyAgreement`, StrongBox
202/// ECDH, TPM 2.0 ECDH), implemented by native Swift/Kotlin over the uniffi foreign-trait
203/// boundary — the ECDH analogue of [`FfiHardwareSigner`], and this namespace's declaration of
204/// `capsule-core`'s `HardwareKeyAgreement` contract.
205///
206/// It backs the hardware-bound classical half of the device **encryption** key:
207/// the element holds a static P-256 private key and performs the ECDH, so the scalar never
208/// leaves hardware, while Rust drives the software-sealed ML-KEM-768 half and the hybrid
209/// combiner. Failures reuse [`FfiHardwareSignerError`], exactly as core's trait reuses its
210/// signer error.
211#[uniffi::export(with_foreign)]
212pub trait FfiHardwareKeyAgreement: Send + Sync {
213    /// Generate (or bind to) the hardware P-256 key-agreement keypair for `key_alias`,
214    /// returning its public key as **uncompressed SEC1** (`0x04‖x‖y`, 65 bytes). Idempotent per
215    /// alias.
216    fn enroll(&self, key_alias: String) -> Result<Vec<u8>, FfiHardwareSignerError>;
217
218    /// The uncompressed-SEC1 P-256 public key for an already-enrolled `key_alias`.
219    fn public_key(&self, key_alias: String) -> Result<Vec<u8>, FfiHardwareSignerError>;
220
221    /// ECDH against `peer_public` (the sender's ephemeral P-256 public key, uncompressed SEC1)
222    /// with the hardware key for `key_alias`, returning the **raw 32-byte shared secret** (the
223    /// big-endian x-coordinate, before any KDF).
224    fn key_agreement(
225        &self,
226        key_alias: String,
227        peer_public: Vec<u8>,
228    ) -> Result<Vec<u8>, FfiHardwareSignerError>;
229
230    /// Non-exportability assertion: a conforming element MUST refuse to reveal the private
231    /// bytes, returning [`FfiHardwareSignerError::Exportable`] if they can be read.
232    fn assert_non_exportable(&self, key_alias: String) -> Result<(), FfiHardwareSignerError>;
233}
234
235/// Adapts a foreign [`FfiHardwareKeyAgreement`] to `capsule-core`'s `HardwareKeyAgreement`, so
236/// the core composition (`P256HybridDek::enroll`) drives the native element unchanged. Pure
237/// delegation — only the error type is translated.
238struct ForeignKeyAgreement(Arc<dyn FfiHardwareKeyAgreement>);
239
240impl HardwareKeyAgreement for ForeignKeyAgreement {
241    fn enroll(&self, key_alias: String) -> Result<Vec<u8>, HardwareSignerError> {
242        self.0.enroll(key_alias).map_err(Into::into)
243    }
244    fn public_key(&self, key_alias: String) -> Result<Vec<u8>, HardwareSignerError> {
245        self.0.public_key(key_alias).map_err(Into::into)
246    }
247    fn key_agreement(
248        &self,
249        key_alias: String,
250        peer_public: Vec<u8>,
251    ) -> Result<Vec<u8>, HardwareSignerError> {
252        self.0
253            .key_agreement(key_alias, peer_public)
254            .map_err(Into::into)
255    }
256    fn assert_non_exportable(&self, key_alias: String) -> Result<(), HardwareSignerError> {
257        self.0.assert_non_exportable(key_alias).map_err(Into::into)
258    }
259}
260
261/// Parse the 32-byte software-sealed post-quantum seed every hardware composition takes, as a
262/// typed error rather than a panic at the boundary.
263fn parse_ml_seed(bytes: &[u8]) -> Result<[u8; 32], FfiError> {
264    bytes.try_into().map_err(|_| FfiError::InvalidArgument {
265        detail: "ml_seed must be exactly 32 bytes".into(),
266    })
267}
268
269/// Smoke the **hardware-bound P-256 device encryption key** across the FFI seam:
270/// enroll a key-agreement key in `hardware` under `key_alias`, publish the hybrid public key,
271/// encapsulate a fresh shared secret to it **in software** (the sender side), then
272/// **decapsulate through the element's ECDH**. Returns `true` iff the two secrets match —
273/// proving the element's ECDH composes into the hybrid KEM without the private scalar leaving
274/// hardware. `ml_seed` (32 bytes) is the software-sealed ML-KEM-768 half.
275///
276/// The DEK is not yet wired into workspace creation, so this focused round-trip is the
277/// composition's on-device check — the DEK analogue of
278/// [`FfiWorkspace::create_with_p256_hardware_signer`]. Every step is one `capsule-core` call.
279#[uniffi::export]
280pub fn p256_hardware_dek_round_trip(
281    hardware: Arc<dyn FfiHardwareKeyAgreement>,
282    key_alias: String,
283    ml_seed: Vec<u8>,
284) -> Result<bool, FfiError> {
285    let seed = parse_ml_seed(&ml_seed)?;
286    let dek = P256HybridDek::enroll(Arc::new(ForeignKeyAgreement(hardware)), key_alias, &seed)
287        .map_err(|e| FfiError::Workspace {
288            detail: format!("hardware P-256 DEK enrollment failed: {e}"),
289        })?;
290    let workspace_error = |e: capsule_core::crypto::CryptoError| FfiError::Workspace {
291        detail: e.to_string(),
292    };
293    let (ciphertext, sender_secret) =
294        encapsulate_to_p256_public(&dek.public_bytes()).map_err(workspace_error)?;
295    let receiver_secret = dek.decapsulate(&ciphertext).map_err(workspace_error)?;
296    let matched = sender_secret == receiver_secret;
297    tracing::debug!(matched, "hardware P-256 DEK round trip");
298    Ok(matched)
299}
300
301// ─── Small mirrors ───────────────────────────────────────────────────────────
302
303/// Device hardware tier, selecting the Argon2id cost at wrap time. Mirrors core's `DeviceTier`
304/// in this namespace (see the module docs on why it is not shared).
305#[derive(Debug, Clone, Copy, uniffi::Enum)]
306pub enum FfiDeviceTier {
307    /// ≤ 2 GiB total RAM (entry-level Android / embedded).
308    LowRam,
309    /// Default for phones and laptops.
310    Normal,
311    /// ≥ 8 GiB; used when wrapping new escrow blobs from a desktop.
312    Desktop,
313}
314
315impl From<FfiDeviceTier> for DeviceTier {
316    fn from(tier: FfiDeviceTier) -> Self {
317        match tier {
318            FfiDeviceTier::LowRam => Self::LowRam,
319            FfiDeviceTier::Normal => Self::Normal,
320            FfiDeviceTier::Desktop => Self::Desktop,
321        }
322    }
323}
324
325/// A foreign client's self-reported build identity: its product id and own semver.
326/// The git commit + dirty flag come from the core this app links, together composing the
327/// `client_id/semver+commit` `client_version` every manifest carries — so a defect in a shipped
328/// app build is traceable across the assets it produced.
329#[derive(Debug, Clone, uniffi::Record)]
330pub struct FfiClientBuild {
331    /// The app's product id, e.g. `capsule-ios`.
332    pub client_id: String,
333    /// The app's own semantic version, e.g. `1.4.2`.
334    pub semver: String,
335}
336
337/// One album this workspace holds key material for.
338#[derive(Debug, Clone, uniffi::Record)]
339pub struct FfiAlbum {
340    /// Album id (UUID string).
341    pub album_id: String,
342    /// Display name, which lives only in the client's own state — it never crosses the wire.
343    pub name: String,
344}
345
346/// The verification verdict, flattened for FFI (reasons as stable reason-code strings).
347#[derive(Debug, Clone, uniffi::Enum)]
348pub enum FfiVerifyOutcome {
349    /// The asset verified and may enter the trusted set.
350    Accept,
351    /// The asset is permanently rejected (quarantined); `reason` is the reason code.
352    TerminalReject {
353        /// Stable reason-code string (e.g. `RemovedWriter`).
354        reason: String,
355    },
356    /// The asset is recoverable-pending (held + retried); `reason` is the reason code.
357    Pending {
358        /// Stable reason-code string (e.g. `AmkNotYetLocal`).
359        reason: String,
360    },
361}
362
363impl From<VerifyOutcome> for FfiVerifyOutcome {
364    fn from(outcome: VerifyOutcome) -> Self {
365        match outcome {
366            VerifyOutcome::Accept => Self::Accept,
367            VerifyOutcome::TerminalReject(reason) => Self::TerminalReject {
368                reason: format!("{reason:?}"),
369            },
370            VerifyOutcome::Pending(reason) => Self::Pending {
371                reason: format!("{reason:?}"),
372            },
373        }
374    }
375}
376
377// ─── Seal + import → upload bridge ───────────────────────────────────────────
378
379/// One transferable blob of a sealed asset, paired with the `POST /upload` body that declares
380/// it. Hand [`request`](Self::request) and [`bytes`](Self::bytes) straight to
381/// [`FfiSession::upload`](crate::ffi::FfiSession::upload) — this record exists so an app never
382/// has to assemble a manifest envelope itself.
383///
384/// The blobs come back in **ladder order**: the metadata blob (T0 — the index tier that makes
385/// the asset visible), then derivatives (T1), then the original (T2).
386///
387/// [`bytes`](Self::bytes) holds each blob whole, the original included, so an original costs
388/// its full size in memory here. [`FfiSession::push_asset`](crate::ffi::FfiSession::push_asset)
389/// pushes the same blobs with the original streamed, and is the path for an original of any
390/// size.
391#[derive(uniffi::Record)]
392pub struct FfiUploadBlob {
393    /// The ladder tier this blob occupies (`index` / `preview` / `original`).
394    pub tier: String,
395    /// The blob's content address (lowercase hex) — the value the server dedups on.
396    pub hash: String,
397    /// The `POST /upload` body for this blob, with the manifest envelope already projected.
398    pub request: FfiUploadRequest,
399    /// The bytes to transfer.
400    pub bytes: Vec<u8>,
401}
402
403// ─── Sync-apply ──────────────────────────────────────────────────────────────
404
405/// One remote feed entry to apply, as a sync feed delivers it.
406///
407/// `album_id` and the two id-bearing fields carry the feed's own **16-byte UUID** form (the
408/// `bytes album_id` of `capsule.sync.v1.SyncEntry`), so an entry from
409/// [`FfiSession::sync_pull`](crate::ffi::FfiSession::sync_pull) is passed through unchanged.
410#[derive(Debug, uniffi::Record)]
411pub struct FfiSyncEntry {
412    /// The album the feed claims this entry belongs to — 16 raw UUID bytes. Cross-checked
413    /// against the manifest by the chokepoint itself, never trusted on its own.
414    pub album_id: Vec<u8>,
415    /// The signed `AssetManifest` as opaque canonical CBOR, carried verbatim.
416    pub manifest_cbor: Vec<u8>,
417    /// The sealed metadata blob the manifest commits to.
418    pub metadata_blob: Vec<u8>,
419    /// The asset's original ciphertext. Required: the chokepoint's content-integrity step
420    /// hashes it against the manifest's declared content address, and there is no variant of
421    /// that check which skips it — so fetch the original blob before applying.
422    ///
423    /// It crosses whole, so this record costs the original's full size in memory. An original
424    /// of any size is received with
425    /// [`FfiSession::fetch_blob_to_path`](crate::ffi::FfiSession::fetch_blob_to_path), and
426    /// applied and opened from that file with an [`FfiSyncHead`] through
427    /// [`FfiWorkspace::apply_sync_entry_from_file`] and [`FfiWorkspace::open_synced_original`],
428    /// in bounded memory.
429    pub original_ciphertext: Vec<u8>,
430    /// The 32-byte provenance head your catalog already holds for this asset, or `None` if it
431    /// has never seen it. This is what decides replay and fork; feed back
432    /// [`FfiAssetFacts::provenance_head`] after a successful apply.
433    pub local_chain_head: Option<Vec<u8>>,
434}
435
436/// One remote feed entry whose original is **on disk** rather than in hand: an
437/// [`FfiSyncEntry`] without its `original_ciphertext`, which
438/// [`FfiWorkspace::apply_sync_entry_from_file`] and [`FfiWorkspace::open_synced_original`] read
439/// from the file [`FfiSession::fetch_blob_to_path`](crate::ffi::FfiSession::fetch_blob_to_path)
440/// produced, in memory bounded by one STREAM chunk whatever the original's size.
441#[derive(Debug, Clone, uniffi::Record)]
442pub struct FfiSyncHead {
443    /// As [`FfiSyncEntry::album_id`].
444    pub album_id: Vec<u8>,
445    /// As [`FfiSyncEntry::manifest_cbor`].
446    pub manifest_cbor: Vec<u8>,
447    /// As [`FfiSyncEntry::metadata_blob`].
448    pub metadata_blob: Vec<u8>,
449    /// As [`FfiSyncEntry::local_chain_head`].
450    pub local_chain_head: Option<Vec<u8>>,
451}
452
453/// How [`FfiWorkspace::open_synced_original`] resolved. Only `Opened` leaves anything at the
454/// destination path.
455// `Opened` and the other verdicts carry a whole flattened facts record or apply outcome; see
456// `FfiSyncApplyOutcome` for why the payload is not boxed.
457#[allow(clippy::large_enum_variant)]
458#[derive(Debug, Clone, uniffi::Enum)]
459pub enum FfiOpenedOriginal {
460    /// Verified end to end and decrypted: the destination now holds the original's plaintext,
461    /// which hashes to the signed sidecar's digest.
462    Opened {
463        /// The verified facts of the entry.
464        facts: FfiAssetFacts,
465    },
466    /// The entry did not apply, exactly as
467    /// [`apply_sync_entry`](FfiWorkspace::apply_sync_entry) would say: held pending or
468    /// quarantined. A ciphertext file that is not the original the manifest commits to is
469    /// quarantined as `Rejected.CiphertextHashMismatch`.
470    Refused {
471        /// The verdict, never `Applied`.
472        outcome: FfiSyncApplyOutcome,
473    },
474    /// The entry applied, but its file key could not be recovered or its ciphertext failed
475    /// authentication under it.
476    Undecryptable {
477        /// The verified facts of the entry.
478        facts: FfiAssetFacts,
479    },
480    /// The ciphertext opened, but the plaintext does not hash to the signed sidecar's digest.
481    DigestMismatch {
482        /// The verified facts of the entry.
483        facts: FfiAssetFacts,
484    },
485}
486
487impl<W> From<RemoteOriginal<W>> for FfiOpenedOriginal {
488    fn from(original: RemoteOriginal<W>) -> Self {
489        match original {
490            RemoteOriginal::Opened { facts, .. } => Self::Opened {
491                facts: (*facts).into(),
492            },
493            RemoteOriginal::Refused(outcome) => Self::Refused {
494                outcome: outcome.into(),
495            },
496            RemoteOriginal::Undecryptable { facts } => Self::Undecryptable {
497                facts: (*facts).into(),
498            },
499            RemoteOriginal::DigestMismatch { facts } => Self::DigestMismatch {
500                facts: (*facts).into(),
501            },
502        }
503    }
504}
505
506impl FfiSyncHead {
507    /// The entry's structural arguments, parsed: the album id and the caller's chain head.
508    /// Cheap, so a verb checks them before it reads any file.
509    fn parsed(&self) -> Result<(Uuid, Option<Hash32>), FfiError> {
510        Ok((
511            uuid_from_bytes("album_id", &self.album_id)?,
512            chain_head(self.local_chain_head.as_deref())?,
513        ))
514    }
515
516    /// The core head for this entry, its original named by `original_ciphertext_hash`.
517    fn remote(&self, original_ciphertext_hash: Hash32) -> Result<RemoteHead<'_>, FfiError> {
518        let (album_id, local_chain_head) = self.parsed()?;
519        Ok(RemoteHead {
520            album_id,
521            manifest_cbor: &self.manifest_cbor,
522            metadata_blob: &self.metadata_blob,
523            original_ciphertext_hash,
524            local_chain_head,
525        })
526    }
527}
528
529/// The verified facts one applied entry contributes, flattened for a catalog upsert.
530#[derive(Debug, Clone, uniffi::Record)]
531pub struct FfiAssetFacts {
532    /// The asset id (UUID string).
533    pub asset_id: String,
534    /// The album id (UUID string).
535    pub album_id: String,
536    /// The AMK epoch the asset is sealed under.
537    pub amk_version: u32,
538    /// The original's ciphertext content address (lowercase hex).
539    pub ciphertext_hash: String,
540    /// The original's plaintext length in bytes.
541    pub plaintext_size: u64,
542    /// The head manifest's lifecycle action (`create`, `metadata-update`, `delete`, …).
543    pub action: String,
544    /// RFC3339 authoring timestamp of the head manifest.
545    pub timestamp: String,
546    /// The device that authored it (UUID string), resolved in the signed device directory.
547    pub created_by_device: String,
548    /// The 32-byte provenance head this entry establishes — persist it and pass it back as
549    /// [`FfiSyncEntry::local_chain_head`] next time.
550    pub provenance_head: Vec<u8>,
551    /// The decrypted, signature-checked metadata.
552    ///
553    /// `None` exactly when the action mints no metadata blob — a `delete` tombstone or a
554    /// `trash-restore`. Those are fully-verified entries that simply carry no metadata, so an
555    /// app applies the lifecycle change and leaves the row's metadata as it stands.
556    pub metadata: Option<FfiAssetMetadata>,
557    /// Whether this workspace now holds the asset at this entry's record: it adopted the
558    /// entry, writing the asset's chain, sidecar, sealed metadata and original under `media/`
559    /// and its index row and user tags into the library catalog, so the trash verbs and tag
560    /// edits work on it. When `true` the catalog already describes the asset and an app writes
561    /// nothing of its own for it; when `false` (an asset first seen past its create, a fork, or
562    /// a verb that applies without adopting) the facts are the app's to upsert. An asset first
563    /// seen past its create is adopted from its earlier records:
564    /// [`FfiSession::fetch_provenance_history`](crate::ffi::FfiSession::fetch_provenance_history),
565    /// then [`FfiWorkspace::open_synced_history`].
566    #[uniffi(default = false)]
567    pub adopted: bool,
568}
569
570/// The decrypted sidecar's facts, flattened for a catalog upsert.
571#[derive(Debug, Clone, uniffi::Record)]
572pub struct FfiAssetMetadata {
573    /// Sidecar schema version.
574    pub sidecar_schema: u16,
575    /// The original's MIME type.
576    pub content_type: String,
577    /// RFC3339 capture time the asset is dated by: the user's correction when one is recorded,
578    /// else the as-imported value.
579    pub capture_timestamp: String,
580    /// Pixel width, when the sidecar records dimensions.
581    pub width: Option<u32>,
582    /// Pixel height, when the sidecar records dimensions.
583    pub height: Option<u32>,
584    /// LQIP chromahash bytes — renderable the instant metadata syncs, at zero extra request.
585    pub lqip_chromahash: Option<Vec<u8>>,
586    /// LQIP dominant colour, as three RGB bytes.
587    pub lqip_dominant_color: Option<Vec<u8>>,
588    /// The caption LWW register's current value, if any.
589    pub caption: Option<String>,
590    /// The user-tag OR-set's current members, sorted.
591    pub tags: Vec<String>,
592    /// The rating LWW register's current value, if any.
593    pub rating: Option<u8>,
594    /// Whether the asset is hidden from default views.
595    pub hidden: bool,
596}
597
598impl From<SidecarV1> for FfiAssetMetadata {
599    fn from(sidecar: SidecarV1) -> Self {
600        let capture_timestamp = sidecar.effective_capture_timestamp().to_owned();
601        Self {
602            sidecar_schema: sidecar.sidecar_schema,
603            content_type: sidecar.content_type,
604            capture_timestamp,
605            width: sidecar.dimensions.as_ref().map(|d| d.width),
606            height: sidecar.dimensions.as_ref().map(|d| d.height),
607            lqip_chromahash: sidecar.lqip.as_ref().map(|l| l.chromahash.clone()),
608            lqip_dominant_color: sidecar.lqip.as_ref().map(|l| l.dominant_color.to_vec()),
609            caption: sidecar.caption.get().cloned(),
610            tags: sidecar.tags_user.value().into_iter().collect(),
611            rating: sidecar.rating.get().copied(),
612            hidden: sidecar.hidden.get().copied().unwrap_or(false),
613        }
614    }
615}
616
617impl From<RemoteAssetFacts> for FfiAssetFacts {
618    fn from(facts: RemoteAssetFacts) -> Self {
619        Self {
620            asset_id: facts.asset_id.to_string(),
621            album_id: facts.album_id.to_string(),
622            amk_version: facts.amk_version,
623            ciphertext_hash: facts.ciphertext_hash.to_hex(),
624            plaintext_size: facts.plaintext_size,
625            action: wire_enum(&facts.action),
626            timestamp: facts.timestamp,
627            created_by_device: facts.created_by_device.to_string(),
628            provenance_head: facts.provenance_head.as_bytes().to_vec(),
629            metadata: facts.sidecar.map(FfiAssetMetadata::from),
630            adopted: false,
631        }
632    }
633}
634
635impl FfiSyncApplyOutcome {
636    /// This verdict with its facts marked [`adopted`](FfiAssetFacts::adopted) when `adoption`
637    /// left the workspace holding the asset.
638    fn adopted(mut self, adoption: Option<Adoption>) -> Self {
639        if let Self::Applied { facts } = &mut self {
640            facts.adopted = adoption.is_some_and(Adoption::holds);
641        }
642        self
643    }
644}
645
646/// How applying one remote entry resolved — the three verdicts the client validation duties
647/// permit. There is no "ignored" case: a failure is always a named quarantine or a hold.
648// The `Applied` variant is a whole flattened facts record and the refusal variants are two
649// strings, so the sizes are inherently lopsided. Boxing the payload is the usual fix and is not
650// available here: uniffi lowers a record by value, and an indirection it cannot express would
651// buy nothing on a type that crosses the FFI boundary once per feed entry.
652#[allow(clippy::large_enum_variant)]
653#[derive(Debug, Clone, uniffi::Enum)]
654pub enum FfiSyncApplyOutcome {
655    /// Verified end to end; upsert the facts.
656    Applied {
657        /// The verified facts.
658        facts: FfiAssetFacts,
659    },
660    /// Authorization is intact but the epoch's AMK has not arrived locally yet. Hold and retry
661    /// — never quarantine.
662    Pending {
663        /// Stable reason-code string (`AmkNotYetLocal`).
664        reason: String,
665    },
666    /// Refused. `reason` is a stable, switchable code; `detail` is English developer text.
667    Quarantined {
668        /// A stable code, dotted where a sub-reason applies — e.g. `Rejected.ForgedChain`,
669        /// `Binding.BlobHashMismatch`, `SidecarSignature`, `LegacyInheritedDevice` (a pre-fix
670        /// continuation attributed to the wrong device of the same account; not a forgery),
671        /// `Purged` (this device purged the asset; its tombstone refuses every later entry).
672        reason: String,
673        /// English detail, when the refusal carries one (a parse message, an album or asset id).
674        detail: Option<String>,
675    },
676}
677
678impl From<SyncApplyOutcome> for FfiSyncApplyOutcome {
679    fn from(outcome: SyncApplyOutcome) -> Self {
680        match outcome {
681            SyncApplyOutcome::Applied(facts) => Self::Applied {
682                facts: (*facts).into(),
683            },
684            SyncApplyOutcome::Pending(reason) => Self::Pending {
685                reason: format!("{reason:?}"),
686            },
687            SyncApplyOutcome::Quarantined(reason) => {
688                let (reason, detail) = match reason {
689                    QuarantineReason::MalformedManifest(detail) => {
690                        ("MalformedManifest".to_string(), Some(detail))
691                    }
692                    QuarantineReason::UnsupportedRecordVersion { found, max_known } => (
693                        "UnsupportedRecordVersion".to_string(),
694                        Some(format!(
695                            "record version {found} is newer than this build reads ({max_known})"
696                        )),
697                    ),
698                    QuarantineReason::UnknownAlbum(album) => {
699                        ("UnknownAlbum".to_string(), Some(album.to_string()))
700                    }
701                    QuarantineReason::Rejected(reject) => (format!("Rejected.{reject:?}"), None),
702                    QuarantineReason::LegacyInheritedDevice {
703                        named_device,
704                        signing_device,
705                        record_hash,
706                    } => (
707                        "LegacyInheritedDevice".to_string(),
708                        Some(format!(
709                            "record {record_hash} names device {named_device} but was signed by \
710                             device {signing_device}; the chain stalls at this record"
711                        )),
712                    ),
713                    QuarantineReason::Binding(binding) => (format!("Binding.{binding:?}"), None),
714                    QuarantineReason::MalformedSidecar(detail) => {
715                        ("MalformedSidecar".to_string(), Some(detail))
716                    }
717                    QuarantineReason::SidecarSignature => ("SidecarSignature".to_string(), None),
718                    QuarantineReason::Purged(asset) => {
719                        ("Purged".to_string(), Some(asset.to_string()))
720                    }
721                };
722                Self::Quarantined { reason, detail }
723            }
724        }
725    }
726}
727
728// ─── Labels and regions ──────────────────────────────────────────────────────
729
730/// A region's outline, in coordinates normalized to `[0, 1]` over the original's display
731/// orientation. Mirrors `capsule_core::sidecar::RegionShape`, single precision included, so a
732/// shape that validates on one side validates on the other.
733#[derive(Debug, Clone, Copy, PartialEq, uniffi::Enum)]
734pub enum FfiRegionShape {
735    /// A circle centred at `(cx, cy)` (fractions of width and height) with radius `r`, a
736    /// fraction of the image's shorter side.
737    Circle {
738        /// Centre, horizontal.
739        cx: f32,
740        /// Centre, vertical.
741        cy: f32,
742        /// Radius.
743        r: f32,
744    },
745    /// A rectangle with its top-left corner at `(x, y)`.
746    Rect {
747        /// Left edge.
748        x: f32,
749        /// Top edge.
750        y: f32,
751        /// Width.
752        w: f32,
753        /// Height.
754        h: f32,
755    },
756}
757
758impl From<FfiRegionShape> for RegionShape {
759    fn from(shape: FfiRegionShape) -> Self {
760        match shape {
761            FfiRegionShape::Circle { cx, cy, r } => Self::Circle { cx, cy, r },
762            FfiRegionShape::Rect { x, y, w, h } => Self::Rect { x, y, w, h },
763        }
764    }
765}
766
767impl From<RegionShape> for FfiRegionShape {
768    fn from(shape: RegionShape) -> Self {
769        match shape {
770            RegionShape::Circle { cx, cy, r } => Self::Circle { cx, cy, r },
771            RegionShape::Rect { x, y, w, h } => Self::Rect { x, y, w, h },
772        }
773    }
774}
775
776/// One live region of an asset and its labels.
777#[derive(Debug, Clone, PartialEq, uniffi::Record)]
778pub struct FfiRegion {
779    /// The region id (UUIDv7, minted fresh per create, never reused).
780    pub region_id: String,
781    /// The outline.
782    pub shape: FfiRegionShape,
783    /// The region's labels, sorted.
784    pub labels: Vec<String>,
785}
786
787impl FfiRegion {
788    fn new(region_id: Uuid, region: &Region) -> Self {
789        Self {
790            region_id: region_id.to_string(),
791            shape: region.shape.into(),
792            labels: region.labels.value().into_iter().collect(),
793        }
794    }
795}
796
797/// What a label attaches to beyond the asset itself, whose own labels are its user tags. The
798/// label rule is the same at every level.
799#[derive(Debug, Clone, PartialEq, Eq, uniffi::Enum)]
800pub enum FfiLabelTarget {
801    /// A region of an asset.
802    Region {
803        /// The asset (UUID string).
804        asset_id: String,
805        /// The region (UUID string).
806        region_id: String,
807    },
808    /// A stack (UUID string).
809    Stack {
810        /// The stack.
811        stack_id: String,
812    },
813    /// A container album (UUID string).
814    Album {
815        /// The album.
816        album_id: String,
817    },
818}
819
820/// A label target with its ids parsed.
821#[derive(Debug, Clone, Copy)]
822enum LabelTarget {
823    Region { asset_id: Uuid, region_id: Uuid },
824    Stack(Uuid),
825    Album(Uuid),
826}
827
828impl TryFrom<&FfiLabelTarget> for LabelTarget {
829    type Error = FfiError;
830
831    fn try_from(target: &FfiLabelTarget) -> Result<Self, FfiError> {
832        Ok(match target {
833            FfiLabelTarget::Region {
834                asset_id,
835                region_id,
836            } => Self::Region {
837                asset_id: parse_uuid("asset_id", asset_id)?,
838                region_id: parse_uuid("region_id", region_id)?,
839            },
840            FfiLabelTarget::Stack { stack_id } => Self::Stack(parse_uuid("stack_id", stack_id)?),
841            FfiLabelTarget::Album { album_id } => Self::Album(parse_uuid("album_id", album_id)?),
842        })
843    }
844}
845
846/// Why a label or region edit was refused ([`FfiError::Label`]). Nothing was written.
847#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)]
848pub enum FfiLabelRefusal {
849    /// The asset, region, stack or album does not exist, or no longer does.
850    NotFound,
851    /// The label is empty once trimmed.
852    LabelEmpty,
853    /// The normalized label is this many UTF-8 bytes, past the 256-byte bound.
854    LabelTooLong {
855        /// The normalized label's length.
856        bytes: u64,
857    },
858    /// A coordinate is not a finite number in `[0, 1]`.
859    RegionOutOfRange,
860    /// A radius, width or height is zero.
861    RegionEmpty,
862    /// The shape extends past an edge of the image.
863    RegionPastEdge,
864}
865
866/// A label or region verb's failure: the refusals an editor names as [`FfiError::Label`],
867/// everything else as the workspace failure it is.
868fn label_error(error: LifecycleError) -> FfiError {
869    let refusal = match &error {
870        LifecycleError::NotFound(_) => FfiLabelRefusal::NotFound,
871        LifecycleError::InvalidLabel(LabelError::Empty) => FfiLabelRefusal::LabelEmpty,
872        LifecycleError::InvalidLabel(LabelError::TooLong(bytes)) => FfiLabelRefusal::LabelTooLong {
873            bytes: u64::try_from(*bytes).unwrap_or(u64::MAX),
874        },
875        LifecycleError::InvalidRegion(RegionError::OutOfRange) => FfiLabelRefusal::RegionOutOfRange,
876        LifecycleError::InvalidRegion(RegionError::Empty) => FfiLabelRefusal::RegionEmpty,
877        LifecycleError::InvalidRegion(RegionError::PastEdge) => FfiLabelRefusal::RegionPastEdge,
878        _ => return error.into(),
879    };
880    tracing::debug!(?refusal, %error, "ffi: label edit refused");
881    FfiError::Label {
882        refusal,
883        detail: error.to_string(),
884    }
885}
886
887/// The labels `target` carries, sorted.
888fn target_labels(ws: &Workspace, target: LabelTarget) -> Result<Vec<String>, LifecycleError> {
889    Ok(match target {
890        LabelTarget::Region {
891            asset_id,
892            region_id,
893        } => ws
894            .regions(&asset_id)
895            .into_iter()
896            .find(|(id, _)| *id == region_id)
897            .ok_or_else(|| LifecycleError::NotFound(format!("region {region_id} of {asset_id}")))?
898            .1
899            .labels
900            .value()
901            .into_iter()
902            .collect(),
903        LabelTarget::Stack(stack_id) => ws.stack_labels(stack_id)?.into_iter().collect(),
904        LabelTarget::Album(album_id) => ws.album_labels(&album_id)?.into_iter().collect(),
905    })
906}
907
908/// `asset_id`'s live regions, oldest first, or [`LifecycleError::NotFound`] for an asset the
909/// workspace does not hold.
910fn asset_regions(ws: &Workspace, asset_id: Uuid) -> Result<Vec<FfiRegion>, LifecycleError> {
911    if ws.asset(&asset_id).is_none() {
912        return Err(LifecycleError::NotFound(format!("asset {asset_id}")));
913    }
914    // Region ids are UUIDv7 and the map is ordered by id, so id order is creation order.
915    Ok(ws
916        .regions(&asset_id)
917        .iter()
918        .map(|(id, region)| FfiRegion::new(*id, region))
919        .collect())
920}
921
922// ─── Trash ───────────────────────────────────────────────────────────────────
923
924/// One asset in the trash, as its latest signed `delete` record describes it.
925#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
926pub struct FfiTrashEntry {
927    /// The trashed asset (UUID string).
928    pub asset_id: String,
929    /// When the `delete` was signed (RFC 3339, UTC).
930    pub deleted_at: String,
931    /// The signed retention floor (RFC 3339, UTC): a restore is refused at or after it. `None`
932    /// for a `delete` that carries no readable window, which never expires.
933    pub retention_until: Option<String>,
934    /// Whether a restore is accepted now, by this device's clock. Computed by the workspace so
935    /// no app re-implements the window; the server judges the same floor by its own clock.
936    pub restorable: bool,
937}
938
939impl FfiTrashEntry {
940    fn new(entry: &TrashEntry, now: Timestamp) -> Self {
941        Self {
942            asset_id: entry.asset_id.to_string(),
943            deleted_at: entry.deleted_at.to_string(),
944            retention_until: entry.retention_until.map(|until| until.to_string()),
945            restorable: entry.is_restorable_at(now),
946        }
947    }
948}
949
950/// What a [`FfiWorkspace::purge_asset`] did.
951#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
952pub struct FfiPurgeOutcome {
953    /// The purged asset (UUID string).
954    pub asset_id: String,
955    /// The signed shorter-retention `delete` an early purge appended, as the opaque canonical
956    /// CBOR provenance record [`FfiWorkspace::provenance_head`] would have returned. It goes to
957    /// the album's ops surface so the server may purge too, through
958    /// [`FfiSession::deliver_purge`](super::FfiSession::deliver_purge), which sends it with any
959    /// `delete` it chains onto that the server never saw; when that delivery fails,
960    /// [`FfiWorkspace::purged_record`] hands the same record back from the kept chain. `None`
961    /// when the window had closed.
962    pub reissue_record: Option<Vec<u8>>,
963}
964
965/// A sync that drained the feed to its head, the evidence [`FfiWorkspace::expired_trash`]
966/// needs before it judges a retention deadline.
967#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
968pub struct FfiFeedDrain {
969    /// The latest server `changed_at` the drain saw (RFC 3339), or `None` for a drain that saw
970    /// no entry. Deadlines are judged at it alone, never by this device's clock, so with
971    /// `None` nothing has expired.
972    pub latest_changed_at: Option<String>,
973    /// Every asset the server's feed lists, keyed by its id as the feed names it, with the
974    /// `manifest_cbor` of its latest entry (empty for an entry that carries no record). An
975    /// asset whose latest `delete` is not that head or before it is a held delete, which
976    /// never expires. Ids that are not UUIDs name no asset of this workspace and are ignored.
977    ///
978    /// The map must cover the whole feed: a drain from the feed's start (no cursor), or the
979    /// heads this app kept, entry by entry, across every cursored drain since one. A drain
980    /// resumed from a cursor lists only the assets that changed after it, so passing it alone
981    /// leaves out every asset whose `delete` an earlier sync indexed: each is judged held and
982    /// never expires, and the trash grows until the user empties it. That loses nothing, but
983    /// the sweep stops working.
984    pub server_heads: HashMap<String, Vec<u8>>,
985}
986
987impl FfiFeedDrain {
988    fn parse(&self) -> Result<FeedDrain, FfiError> {
989        let latest_changed_at = self
990            .latest_changed_at
991            .as_deref()
992            .map(str::parse::<Timestamp>)
993            .transpose()
994            .map_err(|e| FfiError::InvalidArgument {
995                detail: format!("latest_changed_at: not an RFC 3339 timestamp ({e})"),
996            })?;
997        let server_heads = self
998            .server_heads
999            .iter()
1000            .filter_map(|(asset_id, head)| {
1001                let asset_id = Uuid::parse_str(asset_id).ok()?;
1002                let head = (!head.is_empty()).then(|| hash_bytes(head));
1003                Some((asset_id, head))
1004            })
1005            .collect();
1006        Ok(FeedDrain {
1007            latest_changed_at,
1008            server_heads,
1009        })
1010    }
1011}
1012
1013/// Why a trash verb was refused ([`FfiError::Trash`]). Nothing was written.
1014#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)]
1015pub enum FfiTrashRefusal {
1016    /// The workspace holds no such asset.
1017    NotFound,
1018    /// The asset is not in the trash: a restore has nothing to undo, and a purge never skips
1019    /// the trash.
1020    NotInTrash,
1021    /// The signed retention window has closed, so the asset can no longer be restored. It
1022    /// stays in the trash until it is purged.
1023    RetentionElapsed,
1024}
1025
1026/// A trash verb's failure: the refusals a trash view names as [`FfiError::Trash`], everything
1027/// else as the workspace failure it is.
1028pub(super) fn trash_error(error: LifecycleError) -> FfiError {
1029    let (refusal, code, retention_until) = match &error {
1030        LifecycleError::NotFound(_) => (FfiTrashRefusal::NotFound, None, None),
1031        LifecycleError::NotInTrash(_) => (FfiTrashRefusal::NotInTrash, None, None),
1032        LifecycleError::RetentionElapsed {
1033            retention_until, ..
1034        } => (
1035            FfiTrashRefusal::RetentionElapsed,
1036            Some(capsule_i18n::error_codes::UPLOAD_RETENTION_ELAPSED.to_owned()),
1037            Some(retention_until.clone()),
1038        ),
1039        _ => return error.into(),
1040    };
1041    tracing::debug!(?refusal, %error, "ffi: trash verb refused");
1042    FfiError::Trash {
1043        refusal,
1044        code,
1045        retention_until,
1046        detail: error.to_string(),
1047    }
1048}
1049
1050// ─── The workspace object ────────────────────────────────────────────────────
1051
1052/// A Capsule workspace, callable from Swift/Kotlin: the durable library at a filesystem root
1053/// plus everything an app does with it.
1054///
1055/// `Workspace` mutates through `&mut self` while uniffi objects expose only `&self`; the
1056/// `Mutex` supplies the interior mutability and serializes concurrent foreign calls.
1057#[derive(uniffi::Object)]
1058pub struct FfiWorkspace {
1059    inner: Mutex<Workspace>,
1060}
1061
1062impl FfiWorkspace {
1063    /// Run `f` under the workspace lock, surfacing a poisoned lock as a typed error rather
1064    /// than a panic across the boundary.
1065    pub(super) fn with<T>(
1066        &self,
1067        f: impl FnOnce(&mut Workspace) -> Result<T, FfiError>,
1068    ) -> Result<T, FfiError> {
1069        let mut guard = self.inner.lock().map_err(|_| FfiError::Workspace {
1070            detail: "workspace lock poisoned".into(),
1071        })?;
1072        f(&mut guard)
1073    }
1074
1075    fn wrap(workspace: Workspace) -> Arc<Self> {
1076        Arc::new(Self {
1077            inner: Mutex::new(workspace),
1078        })
1079    }
1080
1081    /// The asset's upload bundle, built under the lock and returned owned, so a push drives it
1082    /// across the network without holding the workspace. Its original is a re-derivable
1083    /// source, never a buffer.
1084    pub(super) fn bundle(&self, asset_id: &str) -> Result<UploadBundle, FfiError> {
1085        let asset_id = parse_uuid("asset_id", asset_id)?;
1086        self.with(|ws| Ok(ws.upload_bundle(&asset_id)?))
1087    }
1088
1089    /// Forget `asset_id`'s upload source guard, under the lock: every blob of its bundle is
1090    /// `Completed`, or nothing will re-derive its original again. Forgetting it is
1091    /// housekeeping, so a refusal costs a log line, never the push it follows.
1092    pub(super) fn release_upload_guard(&self, asset_id: &Uuid) {
1093        match self.with(|ws| Ok(ws.release_upload_guard(asset_id)?)) {
1094            Ok(released) => {
1095                tracing::debug!(%asset_id, released, "ffi: the original's upload guard released");
1096            }
1097            Err(error) => {
1098                tracing::warn!(%asset_id, %error, "ffi: the original's upload guard could not be released");
1099            }
1100        }
1101    }
1102
1103    /// Re-seal a create the server `refused` at the album's current epoch, under the lock
1104    /// (issue #822).
1105    ///
1106    /// A re-seal that cannot happen is reported as the push failure it is: an
1107    /// [`FfiError::Upload`] carrying the server's code, with a detail naming why the asset
1108    /// cannot be re-sealed. When this device holds no newer epoch than the asset's, the detail
1109    /// says only that there is no newer epoch to re-seal at, because the server refuses a revoked
1110    /// device or withdrawn write access the same way and no key need be missing.
1111    pub(super) fn reseal(&self, asset_id: &Uuid, refused: &UploadError) -> Result<(), FfiError> {
1112        self.with(|ws| match ws.reseal_create(asset_id) {
1113            Ok(outcome) => {
1114                tracing::info!(
1115                    asset_id = %asset_id,
1116                    from_epoch = outcome.from_epoch,
1117                    to_epoch = outcome.to_epoch,
1118                    derivatives = outcome.derivatives,
1119                    "ffi: refused create re-sealed at the album's current epoch"
1120                );
1121                Ok(())
1122            }
1123            Err(error) => {
1124                tracing::warn!(asset_id = %asset_id, %error, "ffi: the refused create cannot be re-sealed");
1125                let code = match refused {
1126                    UploadError::Rejected { code, .. } => code.clone(),
1127                    _ => None,
1128                };
1129                Err(FfiError::Upload {
1130                    code,
1131                    detail: format!("the server refused this create ({refused}); {error}"),
1132                })
1133            }
1134        })
1135    }
1136}
1137
1138/// Parse a UUID from foreign code into a typed error rather than panicking at the boundary.
1139pub(super) fn parse_uuid(field: &str, value: &str) -> Result<Uuid, FfiError> {
1140    Uuid::parse_str(value).map_err(|e| FfiError::InvalidArgument {
1141        detail: format!("{field}: {value:?} is not a UUID ({e})"),
1142    })
1143}
1144
1145/// Parse the feed's 16-byte UUID form.
1146fn uuid_from_bytes(field: &str, bytes: &[u8]) -> Result<Uuid, FfiError> {
1147    Uuid::from_slice(bytes).map_err(|e| FfiError::InvalidArgument {
1148        detail: format!("{field}: expected 16 UUID bytes ({e})"),
1149    })
1150}
1151
1152/// Parse an optional 32-byte provenance head.
1153fn chain_head(head: Option<&[u8]>) -> Result<Option<Hash32>, FfiError> {
1154    head.map(|head| {
1155        <[u8; 32]>::try_from(head)
1156            .map(Hash32::from_bytes)
1157            .map_err(|_| FfiError::InvalidArgument {
1158                detail: "local_chain_head must be exactly 32 bytes".into(),
1159            })
1160    })
1161    .transpose()
1162}
1163
1164/// A local file failure, as the workspace error it is.
1165fn local_io(action: &str, path: &Path, error: &std::io::Error) -> FfiError {
1166    FfiError::Workspace {
1167        detail: format!("{action} {}: {error}", path.display()),
1168    }
1169}
1170
1171/// A fresh hidden file beside `destination`, on the same filesystem so that renaming it into
1172/// place is atomic, and named uniquely so that two opens never share one.
1173fn staging_path(destination: &Path) -> Result<PathBuf, FfiError> {
1174    let name = destination
1175        .file_name()
1176        .ok_or_else(|| FfiError::InvalidArgument {
1177            detail: format!("destination_path: {} names no file", destination.display()),
1178        })?;
1179    let mut staged = std::ffi::OsString::from(".");
1180    staged.push(name);
1181    staged.push(format!(".{}.part", Uuid::now_v7()));
1182    Ok(destination.with_file_name(staged))
1183}
1184
1185/// Move a fully written staging file into place as `target`, so that `target` is either
1186/// untouched or the complete original: flushed and synced to disk, then renamed.
1187fn commit_staged(
1188    sink: std::io::BufWriter<std::fs::File>,
1189    staged: &Path,
1190    target: &Path,
1191) -> std::io::Result<()> {
1192    finish_staged(sink)?;
1193    place_staged(staged, target)
1194}
1195
1196/// Flush and sync a fully written staging file, so it can be read back before it is placed.
1197fn finish_staged(sink: std::io::BufWriter<std::fs::File>) -> std::io::Result<()> {
1198    sink.into_inner()
1199        .map_err(std::io::IntoInnerError::into_error)?
1200        .sync_all()
1201}
1202
1203/// Rename a finished staging file into place as `target`.
1204fn place_staged(staged: &Path, target: &Path) -> std::io::Result<()> {
1205    std::fs::rename(staged, target)?;
1206    // Persist the rename itself. Best effort: not every platform opens a directory for sync.
1207    if let Some(parent) = target.parent()
1208        && let Ok(dir) = std::fs::File::open(parent)
1209    {
1210        let _ = dir.sync_all();
1211    }
1212    Ok(())
1213}
1214
1215/// Remove a staging file that will not be renamed into place.
1216fn discard_staged(staged: &Path) {
1217    match std::fs::remove_file(staged) {
1218        Ok(()) => {
1219            tracing::debug!(staged = %staged.display(), "ffi: unverified staging file removed");
1220        }
1221        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
1222        Err(error) => {
1223            tracing::warn!(staged = %staged.display(), %error, "ffi: staging file could not be removed");
1224        }
1225    }
1226}
1227
1228/// The ladder tier's stable lowercase name (`index` / `preview` / `original`) — the same three
1229/// rungs the transfer download tier ladder names, so an app's progress UI can key on one vocabulary
1230/// in both directions.
1231pub(super) fn tier_name(tier: capsule_library::import::UploadTier) -> String {
1232    use capsule_library::import::UploadTier;
1233    match tier {
1234        UploadTier::Index => "index",
1235        UploadTier::Preview => "preview",
1236        UploadTier::Original => "original",
1237    }
1238    .to_string()
1239}
1240
1241/// Serialize a wire enum (`Action`, …) to its bare protocol string, the same projection the
1242/// upload envelope uses.
1243fn wire_enum<T: serde::Serialize>(value: &T) -> String {
1244    serde_json::to_value(value)
1245        .ok()
1246        .and_then(|v| v.as_str().map(str::to_string))
1247        .unwrap_or_default()
1248}
1249
1250#[uniffi::export]
1251impl FfiWorkspace {
1252    /// **Enroll**: create a brand-new library at `root`, guarded by `passphrase` at the
1253    /// Argon2id cost for `tier`. Mints the account, the device key, and the signed device
1254    /// directory, and seeds the durable album keystore.
1255    ///
1256    /// `client` is the app's own build identity: every manifest this workspace authors then
1257    /// reports `client_id/semver+commit` rather than the bare `capsule-core` default.
1258    #[uniffi::constructor]
1259    pub fn create(
1260        root: String,
1261        passphrase: Vec<u8>,
1262        tier: FfiDeviceTier,
1263        client: FfiClientBuild,
1264    ) -> Result<Arc<Self>, FfiError> {
1265        let workspace = Workspace::create(&PathBuf::from(root), &passphrase, tier.into())?
1266            .with_client_id(&client.client_id, &client.semver);
1267        tracing::info!(user_id = %workspace.user_id(), "workspace created");
1268        Ok(Self::wrap(workspace))
1269    }
1270
1271    /// **Enroll with a hardware-bound Ed25519 device key**: as [`create`](Self::create), but
1272    /// the classical half of the device signing key is produced by `hardware` under
1273    /// `key_alias` over **Ed25519** (a 32-byte public key, 64-byte signatures). The
1274    /// post-quantum ML-DSA-65 half is the software-sealed `ml_seed` (32 bytes).
1275    ///
1276    /// No shipping secure element holds Ed25519 keys, so this is the software/TPM reference
1277    /// composition; phones use
1278    /// [`create_with_p256_hardware_signer`](Self::create_with_p256_hardware_signer). It is the
1279    /// same core call (`HardwareBackedSigner::enroll`) reached through this namespace's
1280    /// [`FfiHardwareSigner`] seam.
1281    #[uniffi::constructor]
1282    pub fn create_with_hardware_signer(
1283        root: String,
1284        passphrase: Vec<u8>,
1285        tier: FfiDeviceTier,
1286        hardware: Arc<dyn FfiHardwareSigner>,
1287        key_alias: String,
1288        ml_seed: Vec<u8>,
1289        client: FfiClientBuild,
1290    ) -> Result<Arc<Self>, FfiError> {
1291        let seed = parse_ml_seed(&ml_seed)?;
1292        let signer = HardwareBackedSigner::enroll(
1293            Arc::new(ForeignHardwareSigner(hardware)),
1294            key_alias,
1295            &seed,
1296        )
1297        .map_err(|e| FfiError::Workspace {
1298            detail: format!("hardware Ed25519 key enrollment failed: {e}"),
1299        })?;
1300        let workspace = Workspace::create_with_hardware_signer(
1301            &PathBuf::from(root),
1302            &passphrase,
1303            DeviceTier::from(tier).params(),
1304            Box::new(signer) as Box<dyn Signer>,
1305        )?
1306        .with_client_id(&client.client_id, &client.semver);
1307        tracing::info!(
1308            user_id = %workspace.user_id(),
1309            "workspace created with a hardware-bound Ed25519 device key"
1310        );
1311        Ok(Self::wrap(workspace))
1312    }
1313
1314    /// **Enroll with a hardware-bound device key**: as [`create`](Self::create), but the
1315    /// classical half of the device signing key is produced by `hardware` (a native Secure
1316    /// Enclave / StrongBox / TPM element) under `key_alias`, over **ECDSA-P256** — the
1317    /// composition shipping secure elements actually provide, none of which do Ed25519. The
1318    /// post-quantum ML-DSA-65 half is the software-sealed `ml_seed` (32 bytes).
1319    ///
1320    /// The published device key carries the P-256 tag and `verify_asset` dispatches on it. The
1321    /// library records the binding (the alias, `ml_seed` sealed under the account master key,
1322    /// and the published key), so every later launch reopens it with
1323    /// [`open_with_p256_hardware_signer`](Self::open_with_p256_hardware_signer) on the same
1324    /// key; plain [`open`](Self::open) refuses such a library. An element that refuses
1325    /// enrollment fails this call before anything is written under `root`.
1326    #[uniffi::constructor]
1327    pub fn create_with_p256_hardware_signer(
1328        root: String,
1329        passphrase: Vec<u8>,
1330        tier: FfiDeviceTier,
1331        hardware: Arc<dyn FfiHardwareSigner>,
1332        key_alias: String,
1333        ml_seed: Vec<u8>,
1334        client: FfiClientBuild,
1335    ) -> Result<Arc<Self>, FfiError> {
1336        let seed = parse_ml_seed(&ml_seed)?;
1337        let workspace = Workspace::create_with_p256_hardware_signer(
1338            &PathBuf::from(root),
1339            &passphrase,
1340            DeviceTier::from(tier).params(),
1341            HardwareSignerBinding {
1342                element: Arc::new(ForeignHardwareSigner(hardware)),
1343                key_alias,
1344            },
1345            &seed,
1346        )?
1347        .with_client_id(&client.client_id, &client.semver);
1348        tracing::info!(
1349            user_id = %workspace.user_id(),
1350            "workspace created with a hardware-bound P-256 device key"
1351        );
1352        Ok(Self::wrap(workspace))
1353    }
1354
1355    /// **Open** the existing library at `root` as [`open`](Self::open) does, re-attaching
1356    /// `hardware`, the element that holds this device's P-256 signing key. Required for a
1357    /// library made by
1358    /// [`create_with_p256_hardware_signer`](Self::create_with_p256_hardware_signer): the element
1359    /// is asked for the key under the alias the library recorded, never to make a new one, and
1360    /// the rebuilt key must be the one this device published. An element that lost the key or
1361    /// is unavailable fails the open with [`FfiError::Workspace`] rather than letting the
1362    /// library sign with another key.
1363    ///
1364    /// The library's record decides, not the caller: a library created with the software key
1365    /// opens on it and `hardware` is not used. `key_alias` is used only when `root` holds a
1366    /// laid-out library with no account yet, whose fresh account is then enrolled under it.
1367    #[uniffi::constructor]
1368    pub fn open_with_p256_hardware_signer(
1369        root: String,
1370        passphrase: Vec<u8>,
1371        tier: FfiDeviceTier,
1372        hardware: Arc<dyn FfiHardwareSigner>,
1373        key_alias: String,
1374        client: FfiClientBuild,
1375    ) -> Result<Arc<Self>, FfiError> {
1376        let workspace = Workspace::open_with_hardware_signer(
1377            &PathBuf::from(root),
1378            &passphrase,
1379            DeviceTier::from(tier).params(),
1380            HardwareSignerBinding {
1381                element: Arc::new(ForeignHardwareSigner(hardware)),
1382                key_alias,
1383            },
1384        )?
1385        .with_client_id(&client.client_id, &client.semver);
1386        tracing::info!(
1387            user_id = %workspace.user_id(),
1388            albums = workspace.albums().len(),
1389            "workspace opened with a hardware signing element attached"
1390        );
1391        Ok(Self::wrap(workspace))
1392    }
1393
1394    /// **Open** the existing library at `root` under `passphrase`, restoring its album keys and
1395    /// authorities, every managed asset, and the `add_id` counter from disk. This is
1396    /// what makes an app relaunch resume rather than re-enroll.
1397    #[uniffi::constructor]
1398    pub fn open(
1399        root: String,
1400        passphrase: Vec<u8>,
1401        tier: FfiDeviceTier,
1402        client: FfiClientBuild,
1403    ) -> Result<Arc<Self>, FfiError> {
1404        let workspace = Workspace::open(
1405            &PathBuf::from(root),
1406            &passphrase,
1407            DeviceTier::from(tier).params(),
1408        )?
1409        .with_client_id(&client.client_id, &client.semver);
1410        tracing::info!(
1411            user_id = %workspace.user_id(),
1412            albums = workspace.albums().len(),
1413            "workspace opened"
1414        );
1415        Ok(Self::wrap(workspace))
1416    }
1417
1418    /// The account owner's user id (UUID string).
1419    pub fn user_id(&self) -> Result<String, FfiError> {
1420        self.with(|ws| Ok(ws.user_id().to_string()))
1421    }
1422
1423    /// This device's id (UUID string) — the `created_by_device` of every manifest it authors,
1424    /// and the id to report as the session's `device_id`.
1425    pub fn device_id(&self) -> Result<String, FfiError> {
1426        self.with(|ws| Ok(ws.device_id().to_string()))
1427    }
1428
1429    /// The default album's id, derived deterministically from the account master key — so every
1430    /// device of this account computes the same value with nothing to synchronize.
1431    pub fn default_album_id(&self) -> Result<String, FfiError> {
1432        self.with(|ws| Ok(ws.default_album_id().to_string()))
1433    }
1434
1435    /// Create an album (minting AMK_v1, its write-tier and admin keys, and an attested
1436    /// authority, then persisting the keystore). Returns the album id.
1437    pub fn create_album(&self, name: String) -> Result<String, FfiError> {
1438        self.with(|ws| Ok(ws.create_album(&name)?.to_string()))
1439    }
1440
1441    /// Resolve `album_id` to the album this workspace already holds, or create it under `name`.
1442    /// This is the verb first-run wiring wants for the default album: it is idempotent across
1443    /// relaunches, where [`create_album`](Self::create_album) would refuse.
1444    pub fn ensure_album(&self, album_id: String, name: String) -> Result<String, FfiError> {
1445        let album_id = parse_uuid("album_id", &album_id)?;
1446        self.with(|ws| Ok(ws.ensure_album(album_id, &name)?.to_string()))
1447    }
1448
1449    /// Every album this workspace holds key material for, in the one album order every app
1450    /// shows as is: the album with the most recent visible, untrashed asset first, an empty
1451    /// album by its creation time, ties by ascending id (`Workspace::albums`).
1452    pub fn albums(&self) -> Result<Vec<FfiAlbum>, FfiError> {
1453        self.with(|ws| {
1454            Ok(ws
1455                .albums()
1456                .into_iter()
1457                .map(|(album_id, name)| FfiAlbum {
1458                    album_id: album_id.to_string(),
1459                    name,
1460                })
1461                .collect())
1462        })
1463    }
1464
1465    /// **Seal + import**: take bytes the app already holds (a PhotoKit / MediaStore export),
1466    /// derive the file key, STREAM-encrypt, author and sign the create manifest, seal the
1467    /// signed sidecar into its metadata blob, append the provenance chain, and self-verify
1468    /// through the `verify_asset` chokepoint. Returns the asset id.
1469    ///
1470    /// `file_name` is consulted for its extension and nothing else. One call, one core call:
1471    /// the whole sealing order is `capsule-core`'s.
1472    pub fn seal_asset(
1473        &self,
1474        album_id: String,
1475        file_name: String,
1476        bytes: Vec<u8>,
1477    ) -> Result<String, FfiError> {
1478        let album_id = parse_uuid("album_id", &album_id)?;
1479        self.with(|ws| Ok(ws.import_bytes(album_id, &file_name, &bytes)?.to_string()))
1480    }
1481
1482    /// Everything needed to push one sealed asset, in ladder order: for each blob, the
1483    /// `POST /upload` body (manifest envelope projected per the server's invariant-15 rule)
1484    /// and the bytes. Feed each straight to
1485    /// [`FfiSession::upload`](crate::ffi::FfiSession::upload).
1486    ///
1487    /// The index tier (`T0`) is **two** blobs — the provenance record then the sealed metadata
1488    /// blob — because the server publishes an asset to other devices only once it holds both
1489    /// roles. Push all of them: an app that stopped after the metadata blob would upload an
1490    /// asset no device, its own included, could ever see.
1491    ///
1492    /// The original's ciphertext is re-derived from the manifest's recorded nonce prefix and
1493    /// gated on the manifest's own content address, so what reaches the network is what the
1494    /// signed manifest vouches for.
1495    ///
1496    /// Every blob comes back whole, the original included. To push without holding the
1497    /// original in memory, use [`FfiSession::push_asset`](crate::ffi::FfiSession::push_asset).
1498    ///
1499    /// Building the bundle records the original's upload source guard; once every blob is
1500    /// materialised nothing re-derives the original from this bundle again, so the guard is
1501    /// released before the blobs are returned. A later call re-verifies the plaintext against
1502    /// the signed content address and records it afresh.
1503    pub fn upload_blobs(&self, asset_id: String) -> Result<Vec<FfiUploadBlob>, FfiError> {
1504        let asset_id = parse_uuid("asset_id", &asset_id)?;
1505        self.with(|ws| {
1506            let bundle = ws.upload_bundle(&asset_id)?;
1507            let blobs = crate::push::bundle_blobs(&bundle)
1508                .into_iter()
1509                .map(|(blob, hash)| {
1510                    // The FFI hands each blob across as one buffer, so the original is
1511                    // materialised here; the SDK's own push streams it instead.
1512                    let bytes = blob.bytes.to_vec().map_err(|e| FfiError::Workspace {
1513                        detail: format!("reading the original of {asset_id}: {e}"),
1514                    })?;
1515                    Ok(FfiUploadBlob {
1516                        tier: tier_name(blob.tier),
1517                        request: crate::push::create_request(&bundle, &blob, &hash).into(),
1518                        bytes,
1519                        hash,
1520                    })
1521                })
1522                .collect::<Result<Vec<_>, FfiError>>()?;
1523            // Released under the same lock, so no bundle built in between loses its guard.
1524            match ws.release_upload_guard(&asset_id) {
1525                Ok(released) => tracing::debug!(
1526                    %asset_id,
1527                    released,
1528                    "ffi: every blob materialised; the original's upload guard released"
1529                ),
1530                Err(error) => tracing::warn!(
1531                    %asset_id,
1532                    %error,
1533                    "ffi: the original's upload guard could not be released"
1534                ),
1535            }
1536            Ok(blobs)
1537        })
1538    }
1539
1540    /// Run the `verify_asset` chokepoint over a managed asset, regenerating its ciphertext
1541    /// deterministically. This is the same single chokepoint sync-apply routes through — it is
1542    /// exposed here so an app can re-check its own library (an integrity sweep), never as a
1543    /// second verification path.
1544    pub fn verify_asset(&self, asset_id: String) -> Result<FfiVerifyOutcome, FfiError> {
1545        let asset_id = parse_uuid("asset_id", &asset_id)?;
1546        self.with(|ws| Ok(ws.verify(&asset_id)?.into()))
1547    }
1548
1549    /// The plaintext bytes of a managed asset (what a gallery renders for a locally-held
1550    /// original).
1551    pub fn read_plaintext(&self, asset_id: String) -> Result<Vec<u8>, FfiError> {
1552        let asset_id = parse_uuid("asset_id", &asset_id)?;
1553        self.with(|ws| Ok(ws.read_plaintext(&asset_id)?))
1554    }
1555
1556    /// Every managed asset id (UUID strings).
1557    pub fn asset_ids(&self) -> Result<Vec<String>, FfiError> {
1558        self.with(|ws| Ok(ws.asset_ids().iter().map(Uuid::to_string).collect()))
1559    }
1560
1561    /// The asset's **head provenance record** as opaque canonical CBOR — the exact bytes the
1562    /// `provenance` blob carries, the feed serves back as `manifest_cbor`, and a receiving
1563    /// device runs through [`apply_sync_entry`](Self::apply_sync_entry).
1564    ///
1565    /// The record wraps the head signed manifest with its chain position. That wrapper is not
1566    /// optional: the server's chain head is the SHA-256 of these bytes while a client's next
1567    /// `prior_provenance_hash` is the record's own hash, so the bare manifest is the one
1568    /// encoding under which no lifecycle op can ever chain. Canonical CBOR is deterministic, so
1569    /// the manifest inside is byte-identical to its own signed bytes — nothing is re-authored
1570    /// and the two signatures still verify over exactly what they covered.
1571    ///
1572    /// Use [`signed_manifest`](Self::signed_manifest) when the *manifest* is what is wanted.
1573    pub fn provenance_head(&self, asset_id: String) -> Result<Vec<u8>, FfiError> {
1574        let asset_id = parse_uuid("asset_id", &asset_id)?;
1575        // Read off the chain head directly: the upload bundle carries the create record, which
1576        // is the head only until the first delete, restore or edit.
1577        self.with(|ws| {
1578            let asset = ws.asset(&asset_id).ok_or_else(|| FfiError::Workspace {
1579                detail: format!("asset {asset_id} is not managed by this workspace"),
1580            })?;
1581            let head = asset
1582                .chain
1583                .records()
1584                .last()
1585                .ok_or_else(|| FfiError::Workspace {
1586                    detail: format!("asset {asset_id} has an empty provenance chain"),
1587                })?;
1588            capsule_core::cbor::to_canonical_vec(head).map_err(|e| FfiError::Workspace {
1589                detail: format!("reading the provenance head of {asset_id}: {e}"),
1590            })
1591        })
1592    }
1593
1594    /// The asset's **head signed manifest** as opaque canonical CBOR.
1595    ///
1596    /// This is a serialization of an already-signed structure, not a re-authoring: the two
1597    /// signatures the manifest carries are covered by these bytes, which is why they travel
1598    /// verbatim and are never re-modeled on any wire.
1599    ///
1600    /// **Not what the sync feed carries** — that is
1601    /// [`provenance_head`](Self::provenance_head), the record that wraps this manifest with its
1602    /// chain position. Handing these bytes to
1603    /// [`apply_sync_entry`](Self::apply_sync_entry) is refused as malformed.
1604    pub fn signed_manifest(&self, asset_id: String) -> Result<Vec<u8>, FfiError> {
1605        let asset_id = parse_uuid("asset_id", &asset_id)?;
1606        self.with(|ws| {
1607            let asset = ws.asset(&asset_id).ok_or_else(|| FfiError::Workspace {
1608                detail: format!("asset {asset_id} is not managed by this workspace"),
1609            })?;
1610            let head = asset
1611                .chain
1612                .records()
1613                .last()
1614                .ok_or_else(|| FfiError::Workspace {
1615                    detail: format!("asset {asset_id} has an empty provenance chain"),
1616                })?;
1617            capsule_core::cbor::to_canonical_vec(&head.manifest).map_err(|e| FfiError::Workspace {
1618                detail: format!("encoding the signed manifest failed: {e}"),
1619            })
1620        })
1621    }
1622
1623    /// **Sync-apply**: verify one remote feed entry through the `verify_asset` chokepoint,
1624    /// bind and decrypt its metadata blob, and return either the facts to upsert or a named
1625    /// quarantine/hold verdict.
1626    ///
1627    /// Never silently drops and never silently accepts: a refused entry is a
1628    /// [`FfiSyncApplyOutcome::Quarantined`] the app must surface, not an error that aborts the
1629    /// page. Errors are reserved for a failure of this workspace itself.
1630    ///
1631    /// An applied record that chains onto an asset this workspace holds is **adopted**: appended
1632    /// to the asset's chain with the metadata it binds, written and indexed, and the facts say
1633    /// so ([`FfiAssetFacts::adopted`]). A `create` is adopted only by
1634    /// [`open_synced_original`](Self::open_synced_original), which has its original.
1635    pub fn apply_sync_entry(&self, entry: FfiSyncEntry) -> Result<FfiSyncApplyOutcome, FfiError> {
1636        let album_id = uuid_from_bytes("album_id", &entry.album_id)?;
1637        let local_chain_head = chain_head(entry.local_chain_head.as_deref())?;
1638        self.with(|ws| {
1639            let (outcome, adoption) = ws.adopt_remote_head(
1640                RemoteEntry {
1641                    album_id,
1642                    manifest_cbor: &entry.manifest_cbor,
1643                    metadata_blob: &entry.metadata_blob,
1644                    original_ciphertext: &entry.original_ciphertext,
1645                    local_chain_head,
1646                }
1647                .head(),
1648            )?;
1649            Ok(FfiSyncApplyOutcome::from(outcome).adopted(adoption))
1650        })
1651    }
1652
1653    /// [`apply_sync_entry`](Self::apply_sync_entry) for an entry whose original ciphertext is
1654    /// the file at `ciphertext_path` — the one
1655    /// [`FfiSession::fetch_blob_to_path`](crate::ffi::FfiSession::fetch_blob_to_path) wrote —
1656    /// read in memory bounded by one STREAM chunk whatever the original's size.
1657    ///
1658    /// The same chokepoint and verdicts: the file is hashed, and that digest is what the
1659    /// content-integrity step checks against the manifest's content address, so a file that is
1660    /// not the committed ciphertext is quarantined as `Rejected.CiphertextHashMismatch`, as
1661    /// `apply_sync_entry` quarantines those bytes. The ciphertext file is only read.
1662    ///
1663    /// An applied record is adopted as [`apply_sync_entry`](Self::apply_sync_entry) adopts one:
1664    /// a `delete`, `trash-restore` or edit of an asset this workspace holds is appended to its
1665    /// chain, written under `media/` and indexed, and the facts say so
1666    /// ([`FfiAssetFacts::adopted`]).
1667    ///
1668    /// A malformed `album_id` or `local_chain_head` is refused before the file is opened, so a
1669    /// bad argument never costs a read of the original. The file is hashed before the workspace
1670    /// is locked, so other verbs are not held up while a large original is read.
1671    pub fn apply_sync_entry_from_file(
1672        &self,
1673        entry: FfiSyncHead,
1674        ciphertext_path: String,
1675    ) -> Result<FfiSyncApplyOutcome, FfiError> {
1676        let (album_id, local_chain_head) = entry.parsed()?;
1677        let path = PathBuf::from(ciphertext_path);
1678        let file = std::fs::File::open(&path)
1679            .map_err(|e| local_io("opening the ciphertext file", &path, &e))?;
1680        let (digest, bytes) = hash_ciphertext_from(file)?;
1681        tracing::debug!(path = %path.display(), bytes, "ffi: synced original hashed from disk");
1682        let head = RemoteHead {
1683            album_id,
1684            manifest_cbor: &entry.manifest_cbor,
1685            metadata_blob: &entry.metadata_blob,
1686            original_ciphertext_hash: digest,
1687            local_chain_head,
1688        };
1689        self.with(|ws| {
1690            let (outcome, adoption) = ws.adopt_remote_head(head)?;
1691            Ok(FfiSyncApplyOutcome::from(outcome).adopted(adoption))
1692        })
1693    }
1694
1695    /// [`apply_sync_entry_from_file`](Self::apply_sync_entry_from_file) for an entry of an asset
1696    /// this workspace **holds**, with no original fetched: the original is the one the held
1697    /// chain's head commits to, which this workspace verified when it adopted or imported it.
1698    ///
1699    /// This is how a `delete` on an album page — which names no metadata blob and no blob — is
1700    /// applied to an asset held here: the delete binds no metadata blob and commits to the
1701    /// original the asset already has, so the same chokepoint and adoption as the apply verb
1702    /// verify it against the entry's `local_chain_head`, and the asset moves to this device's
1703    /// trash. A record committing to another original than the held one is quarantined as
1704    /// `Rejected.CiphertextHashMismatch`, and one that binds a metadata blob the entry does not
1705    /// carry is refused by the binding check: neither is adopted.
1706    ///
1707    /// # Errors
1708    ///
1709    /// [`FfiError::InvalidArgument`] for a malformed `album_id` or `local_chain_head`;
1710    /// [`FfiError::Workspace`] when the record names an asset this workspace does not hold, or
1711    /// the workspace itself fails. A record that does not decode is a quarantined verdict, as the
1712    /// apply verb answers one.
1713    pub fn apply_held_sync_entry(
1714        &self,
1715        entry: FfiSyncHead,
1716    ) -> Result<FfiSyncApplyOutcome, FfiError> {
1717        entry.parsed()?;
1718        self.with(|ws| {
1719            // A record that does not decode names no asset; the chokepoint quarantines it before
1720            // the digest is looked at.
1721            let committed = match ProvenanceRecord::decode(&entry.manifest_cbor) {
1722                Ok(record) => {
1723                    let asset_id = record.manifest.core.file_id;
1724                    let held = ws
1725                        .asset(&asset_id)
1726                        .and_then(|asset| asset.chain.records().last())
1727                        .map(|head| head.manifest.core.ciphertext_hash);
1728                    held.ok_or_else(|| FfiError::Workspace {
1729                        detail: format!("asset {asset_id} is not managed by this workspace"),
1730                    })?
1731                }
1732                Err(_) => Hash32::from_bytes([0; 32]),
1733            };
1734            let head = entry.remote(committed)?;
1735            let (outcome, adoption) = ws.adopt_remote_head(head)?;
1736            tracing::info!(
1737                ?adoption,
1738                "ffi: a held asset's entry applied against its held original"
1739            );
1740            Ok(FfiSyncApplyOutcome::from(outcome).adopted(adoption))
1741        })
1742    }
1743
1744    /// **Open a synced original** from the ciphertext file at `ciphertext_path` to its plaintext
1745    /// at `destination_path`, in memory bounded by a few STREAM chunks whatever its size.
1746    ///
1747    /// The entry goes through the chokepoint as
1748    /// [`apply_sync_entry_from_file`](Self::apply_sync_entry_from_file) would take it, then the
1749    /// file is hashed while it is decrypted: it opens only if it is the ciphertext the manifest
1750    /// commits to, every chunk authenticates, and the plaintext hashes to the signed sidecar's
1751    /// digest. The plaintext is written to a hidden staging file beside the destination and
1752    /// renamed into place only once all of that holds, so `destination_path` is untouched by
1753    /// any other verdict and never holds a partial or unverified original. An existing file there
1754    /// is replaced only by a verified one.
1755    ///
1756    /// An opened entry is then **adopted**: a `create` of an asset this workspace does not hold
1757    /// makes it held, with its chain, sidecar and sealed metadata written under `media/`, the
1758    /// opened original copied there as its own library copy, and its row and user
1759    /// tags indexed; a later record of a held asset is appended as
1760    /// [`apply_sync_entry_from_file`](Self::apply_sync_entry_from_file) appends one. The facts
1761    /// say whether it was ([`FfiAssetFacts::adopted`]). `destination_path` still holds the
1762    /// plaintext either way, for the caller to keep or remove.
1763    ///
1764    /// The workspace stays locked while the original decrypts and is adopted.
1765    ///
1766    /// # Errors
1767    ///
1768    /// [`FfiError::Workspace`] when a file cannot be read or written, or the workspace itself
1769    /// fails (an adoption whose write failed included, after the original was placed at
1770    /// `destination_path`); [`FfiError::InvalidArgument`] for a malformed entry or a destination
1771    /// with no file name. A refused entry is a verdict, never an error.
1772    pub fn open_synced_original(
1773        &self,
1774        entry: FfiSyncHead,
1775        ciphertext_path: String,
1776        destination_path: String,
1777    ) -> Result<FfiOpenedOriginal, FfiError> {
1778        let source = PathBuf::from(ciphertext_path);
1779        let destination = PathBuf::from(destination_path);
1780        // The claim the chokepoint checks first is the manifest's own content address, because
1781        // nothing has read the file yet. It is a claim only: `open_remote_original_from` hashes
1782        // every byte it decrypts and refuses the original unless that hash is this address. A
1783        // record that does not decode is quarantined by the apply before the claim is looked at.
1784        let committed = ProvenanceRecord::decode(&entry.manifest_cbor)
1785            .map_or(Hash32::from_bytes([0; 32]), |record| {
1786                record.manifest.core.ciphertext_hash
1787            });
1788        let head = entry.remote(committed)?;
1789        let ciphertext = std::fs::File::open(&source)
1790            .map_err(|e| local_io("opening the ciphertext file", &source, &e))?;
1791        let staged = staging_path(&destination)?;
1792        let sink = std::fs::File::create_new(&staged)
1793            .map(std::io::BufWriter::new)
1794            .map_err(|e| local_io("creating the staging file", &staged, &e))?;
1795        self.with(|ws| {
1796            let (facts, sink) = match ws.open_remote_original_from(head, ciphertext, sink) {
1797                Ok(RemoteOriginal::Opened { facts, plaintext }) => (facts, plaintext),
1798                Ok(refused) => {
1799                    discard_staged(&staged);
1800                    tracing::warn!(source = %source.display(), "ffi: synced original not opened; nothing placed");
1801                    return Ok(refused.into());
1802                }
1803                Err(error) => {
1804                    discard_staged(&staged);
1805                    return Err(error.into());
1806                }
1807            };
1808            if let Err(e) = commit_staged(sink, &staged, &destination) {
1809                discard_staged(&staged);
1810                return Err(local_io(
1811                    "moving the original into place at",
1812                    &destination,
1813                    &e,
1814                ));
1815            }
1816            tracing::info!(
1817                asset_id = %facts.asset_id,
1818                destination = %destination.display(),
1819                "ffi: synced original verified and opened to disk"
1820            );
1821            // Still under the lock the open took, so the workspace is the one that verified it.
1822            let (_, adoption) = ws.adopt_remote_original(head, &destination)?;
1823            let mut facts = FfiAssetFacts::from(*facts);
1824            facts.adopted = adoption.is_some_and(Adoption::holds);
1825            Ok(FfiOpenedOriginal::Opened { facts })
1826        })
1827    }
1828
1829    /// [`open_synced_original`](Self::open_synced_original) for an asset this workspace does not
1830    /// hold and first sees **past its create**, with `history` the records before the entry's,
1831    /// oldest first from the create — what
1832    /// [`FfiSession::fetch_provenance_history`](crate::ffi::FfiSession::fetch_provenance_history)
1833    /// returns for the entry's `manifest_cbor`.
1834    ///
1835    /// The entry is applied against the last record of `history`, whatever its
1836    /// `local_chain_head` says, and its original opened from `ciphertext_path` as
1837    /// `open_synced_original` opens one. Then every record of `history` is verified through
1838    /// the chokepoint in order from the create, the sidecar is opened from the entry's
1839    /// `metadata_blob` (the asset's live one, which the server's metadata role names: a
1840    /// superseded metadata blob is collected), and the asset is **adopted**, held from its
1841    /// create with the opened original as its library copy. The facts say whether it was
1842    /// ([`FfiAssetFacts::adopted`]); a held asset's `delete`, `trash-restore` or edit then works
1843    /// on this device as on one it imported.
1844    ///
1845    /// An entry that names no metadata blob or original — a `delete` on an album page, the
1846    /// surface a writer member's device reads — is opened the same way once they are fetched:
1847    /// [`synced_history_sources`](crate::ffi::synced_history_sources) names both from the entry
1848    /// and `history`, the fetched metadata blob goes in the entry's `metadata_blob`, and the
1849    /// fetched original is `ciphertext_path`. Left empty, the `metadata_blob` binds to nothing
1850    /// and the entry is refused.
1851    ///
1852    /// A history that does not verify, or a live metadata blob that does not bind, is
1853    /// [`FfiOpenedOriginal::Refused`] with the verdict that refused it, and
1854    /// `destination_path` is untouched: the original is placed there only once the asset it
1855    /// belongs to verifies from its create. An empty `history` is `open_synced_original`, and so
1856    /// is an entry of an asset this workspace already holds: its history is not read, so none of
1857    /// its records can refuse the entry, and the entry is applied against its own
1858    /// `local_chain_head`.
1859    ///
1860    /// # Errors
1861    ///
1862    /// As [`open_synced_original`](Self::open_synced_original); an adoption whose write failed
1863    /// leaves nothing at `destination_path`.
1864    pub fn open_synced_history(
1865        &self,
1866        entry: FfiSyncHead,
1867        history: Vec<Vec<u8>>,
1868        ciphertext_path: String,
1869        destination_path: String,
1870    ) -> Result<FfiOpenedOriginal, FfiError> {
1871        // An asset held here already extends its own chain, so its history is not read:
1872        // `adopt_remote_history` adopts it as `adopt_remote_original` does, and the entry is
1873        // opened against its own `local_chain_head`, as `open_synced_original` opens it.
1874        let held = ProvenanceRecord::decode(&entry.manifest_cbor).is_ok_and(|record| {
1875            self.with(|ws| Ok(ws.asset(&record.manifest.core.file_id).is_some()))
1876                .unwrap_or(false)
1877        });
1878        if history.is_empty() || held {
1879            return self.open_synced_original(entry, ciphertext_path, destination_path);
1880        }
1881        // The head chains onto the last record handed over; the adoption verifies that record,
1882        // and every one before it, from the create.
1883        let chains_onto = match history.last().map(|bytes| ProvenanceRecord::decode(bytes)) {
1884            Some(Ok(record)) => Some(record.record_hash()),
1885            Some(Err(error)) => {
1886                tracing::warn!(%error, "ffi: the last record of a synced history does not decode");
1887                return Ok(FfiOpenedOriginal::Refused {
1888                    outcome: SyncApplyOutcome::Quarantined(QuarantineReason::MalformedManifest(
1889                        error.to_string(),
1890                    ))
1891                    .into(),
1892                });
1893            }
1894            None => None,
1895        };
1896        let source = PathBuf::from(ciphertext_path);
1897        let destination = PathBuf::from(destination_path);
1898        // The claim the chokepoint checks first, as `open_synced_original` makes it.
1899        let committed = ProvenanceRecord::decode(&entry.manifest_cbor)
1900            .map_or(Hash32::from_bytes([0; 32]), |record| {
1901                record.manifest.core.ciphertext_hash
1902            });
1903        let head = RemoteHead {
1904            local_chain_head: chains_onto,
1905            ..entry.remote(committed)?
1906        };
1907        let ciphertext = std::fs::File::open(&source)
1908            .map_err(|e| local_io("opening the ciphertext file", &source, &e))?;
1909        let staged = staging_path(&destination)?;
1910        let sink = std::fs::File::create_new(&staged)
1911            .map(std::io::BufWriter::new)
1912            .map_err(|e| local_io("creating the staging file", &staged, &e))?;
1913        self.with(|ws| {
1914            let (facts, sink) = match ws.open_remote_original_from(head, ciphertext, sink) {
1915                Ok(RemoteOriginal::Opened { facts, plaintext }) => (facts, plaintext),
1916                Ok(refused) => {
1917                    discard_staged(&staged);
1918                    tracing::warn!(source = %source.display(), "ffi: synced original not opened; nothing placed");
1919                    return Ok(refused.into());
1920                }
1921                Err(error) => {
1922                    discard_staged(&staged);
1923                    return Err(error.into());
1924                }
1925            };
1926            if let Err(e) = finish_staged(sink) {
1927                discard_staged(&staged);
1928                return Err(local_io("writing the staging file", &staged, &e));
1929            }
1930            // Adopted from the staged plaintext, which the library copies, so the destination
1931            // is written only once the asset verifies from its create.
1932            let (outcome, adoption) = match ws.adopt_remote_history(head, &history, &staged) {
1933                Ok(adopted) => adopted,
1934                Err(error) => {
1935                    discard_staged(&staged);
1936                    return Err(error.into());
1937                }
1938            };
1939            if !matches!(outcome, SyncApplyOutcome::Applied(_)) {
1940                discard_staged(&staged);
1941                tracing::warn!(
1942                    asset_id = %facts.asset_id,
1943                    records = history.len(),
1944                    "ffi: a synced history did not verify; nothing adopted or placed"
1945                );
1946                return Ok(FfiOpenedOriginal::Refused {
1947                    outcome: outcome.into(),
1948                });
1949            }
1950            if let Err(e) = place_staged(&staged, &destination) {
1951                discard_staged(&staged);
1952                return Err(local_io(
1953                    "moving the original into place at",
1954                    &destination,
1955                    &e,
1956                ));
1957            }
1958            tracing::info!(
1959                asset_id = %facts.asset_id,
1960                records = history.len(),
1961                ?adoption,
1962                destination = %destination.display(),
1963                "ffi: synced original opened and its asset adopted from its history"
1964            );
1965            let mut facts = FfiAssetFacts::from(*facts);
1966            facts.adopted = adoption.is_some_and(Adoption::holds);
1967            Ok(FfiOpenedOriginal::Opened { facts })
1968        })
1969    }
1970
1971    /// Mint the **master-key escrow blob** under `recovery_secret`, as opaque canonical CBOR —
1972    /// the bytes [`FfiSession::escrow_put`](crate::ffi::FfiSession::escrow_put) stores.
1973    ///
1974    /// The master key never crosses this boundary: it is wrapped inside `capsule-core` and only
1975    /// the wrapped blob comes out. `recovery_secret` is the ≥128-bit secret shown to the user
1976    /// exactly once at first-device enrollment.
1977    pub fn escrow_blob(
1978        &self,
1979        recovery_secret: Vec<u8>,
1980        tier: FfiDeviceTier,
1981    ) -> Result<Vec<u8>, FfiError> {
1982        self.with(|ws| {
1983            let blob = ws.escrow_master_key(&recovery_secret, tier.into())?;
1984            capsule_core::cbor::to_canonical_vec(&blob).map_err(|e| FfiError::Workspace {
1985                detail: format!("encoding the escrow blob failed: {e}"),
1986            })
1987        })
1988    }
1989
1990    /// Local, network-free check that `recovery_secret` still opens `blob` to *this* device's
1991    /// master key — the recovery verification cadence's predicate. `blob` is the canonical CBOR
1992    /// [`FfiSession::escrow_get`](crate::ffi::FfiSession::escrow_get) returns.
1993    ///
1994    /// A `false` is not necessarily a wrong secret: the cached blob may be stale after a
1995    /// rotation on another device, so refresh it and re-check once before telling the user
1996    /// anything.
1997    pub fn verify_escrow_blob(
1998        &self,
1999        blob: Vec<u8>,
2000        recovery_secret: Vec<u8>,
2001    ) -> Result<bool, FfiError> {
2002        let blob =
2003            capsule_core::cbor::from_slice(&blob).map_err(|e| FfiError::InvalidArgument {
2004                detail: format!("escrow blob is not a canonical WrappedSecret: {e}"),
2005            })?;
2006        self.with(|ws| {
2007            Ok(ws.verify_escrow(&blob, &recovery_secret)
2008                == capsule_core::backup::VerifyOutcome::Verified)
2009        })
2010    }
2011
2012    /// This workspace's **signed device directory** as opaque canonical CBOR — the bytes
2013    /// [`FfiSession::publish_device_directory`](crate::ffi::FfiSession::publish_device_directory)
2014    /// sends. Until this is published, every asset this device signs is an unknown device to
2015    /// every other device, so first-device enrollment publishes before it uploads.
2016    pub fn signed_device_directory(&self) -> Result<Vec<u8>, FfiError> {
2017        self.with(|ws| {
2018            capsule_core::cbor::to_canonical_vec(ws.device_directory()).map_err(|e| {
2019                FfiError::Workspace {
2020                    detail: format!("encoding the device directory failed: {e}"),
2021                }
2022            })
2023        })
2024    }
2025
2026    /// This account's user identity **public** key — the pin a fetched device directory is
2027    /// verified against.
2028    pub fn user_ik_public(&self) -> Result<Vec<u8>, FfiError> {
2029        self.with(|ws| Ok(ws.user_ik_public().to_bytes()))
2030    }
2031
2032    // ── Labels and regions ───────────────────────────────────────────────────
2033    //
2034    // Every edit is metadata-only: a region edit is a `metadata-update` of the asset's signed
2035    // sidecar, a stack or album label edit rewrites that record. Labels go in as typed; the
2036    // workspace normalizes them (NFC, trimmed, 1–256 bytes) and refuses one the rule refuses
2037    // before anything is written. Every write answers with what its target holds afterwards.
2038
2039    /// The labels `target` carries, sorted. An unknown target is [`FfiError::Label`] with
2040    /// [`FfiLabelRefusal::NotFound`].
2041    pub fn labels(&self, target: FfiLabelTarget) -> Result<Vec<String>, FfiError> {
2042        let target = LabelTarget::try_from(&target)?;
2043        self.with(|ws| target_labels(ws, target).map_err(label_error))
2044    }
2045
2046    /// Add `label` to `target` and return its labels afterwards.
2047    pub fn add_label(
2048        &self,
2049        target: FfiLabelTarget,
2050        label: String,
2051    ) -> Result<Vec<String>, FfiError> {
2052        let target = LabelTarget::try_from(&target)?;
2053        self.with(|ws| {
2054            match target {
2055                LabelTarget::Region {
2056                    asset_id,
2057                    region_id,
2058                } => ws.add_region_label(&asset_id, &region_id, &label),
2059                LabelTarget::Stack(stack_id) => ws.add_stack_label(stack_id, &label),
2060                LabelTarget::Album(album_id) => ws.add_album_label(album_id, &label),
2061            }
2062            .map_err(label_error)?;
2063            tracing::info!(?target, "ffi: label added");
2064            target_labels(ws, target).map_err(label_error)
2065        })
2066    }
2067
2068    /// Remove `label` from `target` (every add of it this device has observed) and return its
2069    /// labels afterwards. A label the target does not carry writes nothing and answers the
2070    /// unchanged list.
2071    pub fn remove_label(
2072        &self,
2073        target: FfiLabelTarget,
2074        label: String,
2075    ) -> Result<Vec<String>, FfiError> {
2076        let target = LabelTarget::try_from(&target)?;
2077        self.with(|ws| {
2078            let removed = match target {
2079                LabelTarget::Region {
2080                    asset_id,
2081                    region_id,
2082                } => ws.remove_region_label(&asset_id, &region_id, &label),
2083                LabelTarget::Stack(stack_id) => ws.remove_stack_label(stack_id, &label),
2084                LabelTarget::Album(album_id) => ws.remove_album_label(album_id, &label),
2085            }
2086            .map_err(label_error)?;
2087            tracing::info!(?target, removed, "ffi: label removed");
2088            target_labels(ws, target).map_err(label_error)
2089        })
2090    }
2091
2092    /// The asset's live regions, oldest first.
2093    pub fn regions(&self, asset_id: String) -> Result<Vec<FfiRegion>, FfiError> {
2094        let asset_id = parse_uuid("asset_id", &asset_id)?;
2095        self.with(|ws| asset_regions(ws, asset_id).map_err(label_error))
2096    }
2097
2098    /// Mark a region of `asset_id` with its first `labels`, and return it.
2099    ///
2100    /// Every label is checked before the region is written, so a refused label leaves no
2101    /// unlabelled region behind; then the shape, then the asset. A refusal writes nothing.
2102    pub fn add_region(
2103        &self,
2104        asset_id: String,
2105        shape: FfiRegionShape,
2106        labels: Vec<String>,
2107    ) -> Result<FfiRegion, FfiError> {
2108        let asset_id = parse_uuid("asset_id", &asset_id)?;
2109        for label in &labels {
2110            normalize_label(label)
2111                .map_err(LifecycleError::from)
2112                .map_err(label_error)?;
2113        }
2114        self.with(|ws| {
2115            let region_id = ws
2116                .add_region(&asset_id, shape.into())
2117                .map_err(label_error)?;
2118            for label in &labels {
2119                ws.add_region_label(&asset_id, &region_id, label)
2120                    .map_err(label_error)?;
2121            }
2122            tracing::info!(%asset_id, %region_id, labels = labels.len(), "ffi: region added");
2123            ws.regions(&asset_id)
2124                .iter()
2125                .find(|(id, _)| *id == region_id)
2126                .map(|(id, region)| FfiRegion::new(*id, region))
2127                .ok_or_else(|| FfiError::Workspace {
2128                    detail: format!("region {region_id} was written and is not live"),
2129                })
2130        })
2131    }
2132
2133    /// Delete a region. **Final**: a concurrent or later edit of it on another device does not
2134    /// bring it back once the two merge, and its id is never live again.
2135    pub fn delete_region(&self, asset_id: String, region_id: String) -> Result<(), FfiError> {
2136        let asset_id = parse_uuid("asset_id", &asset_id)?;
2137        let region_id = parse_uuid("region_id", &region_id)?;
2138        self.with(|ws| {
2139            ws.delete_region(&asset_id, &region_id)
2140                .map_err(label_error)?;
2141            tracing::info!(%asset_id, %region_id, "ffi: region deleted");
2142            Ok(())
2143        })
2144    }
2145
2146    // ── Trash ────────────────────────────────────────────────────────────────
2147    //
2148    // The whole deletion state machine is the workspace's: every transition is a signed
2149    // provenance record, so it syncs and survives an index rebuild, and every judgement of the
2150    // retention window reads the `retention_until` signed into the `delete` record. An app
2151    // calls these and keeps no retention logic of its own. A refusal is [`FfiError::Trash`].
2152
2153    /// Move an asset to the trash: sign a `delete` whose retention window is `retain_days` days
2154    /// from now, and return its trash entry. An asset already in the trash keeps the window it
2155    /// was deleted with and signs nothing, so a retried delete never extends it.
2156    pub fn delete_asset(
2157        &self,
2158        asset_id: String,
2159        retain_days: u32,
2160    ) -> Result<FfiTrashEntry, FfiError> {
2161        let asset_id = parse_uuid("asset_id", &asset_id)?;
2162        self.with(|ws| {
2163            if let Some(entry) = ws.trash_entry(&asset_id) {
2164                tracing::debug!(%asset_id, "ffi: delete of an asset already in the trash; nothing signed");
2165                return Ok(FfiTrashEntry::new(&entry, Timestamp::now()));
2166            }
2167            ws.soft_delete(&asset_id, i64::from(retain_days))
2168                .map_err(trash_error)?;
2169            tracing::info!(%asset_id, retain_days, "ffi: asset moved to the trash");
2170            let entry = ws.trash_entry(&asset_id).ok_or_else(|| FfiError::Workspace {
2171                detail: format!("asset {asset_id} was deleted and is not in the trash"),
2172            })?;
2173            Ok(FfiTrashEntry::new(&entry, Timestamp::now()))
2174        })
2175    }
2176
2177    /// Restore an asset from the trash: sign a `trash-restore`. Refused with
2178    /// [`FfiTrashRefusal::RetentionElapsed`] (and the `error.upload.retention_elapsed` code) at
2179    /// or after the signed `retention_until`, and with [`FfiTrashRefusal::NotInTrash`] for an
2180    /// asset that is not in the trash.
2181    pub fn restore_asset(&self, asset_id: String) -> Result<(), FfiError> {
2182        let asset_id = parse_uuid("asset_id", &asset_id)?;
2183        self.with(|ws| {
2184            ws.restore(&asset_id).map_err(trash_error)?;
2185            tracing::info!(%asset_id, "ffi: asset restored from the trash");
2186            Ok(())
2187        })
2188    }
2189
2190    /// Permanently delete a trashed asset: its original, every derivative and local cache
2191    /// entry, its sidecar and its index row. The provenance chain is kept as the record of the
2192    /// deletion. Before `retention_until` a signed shorter-retention `delete` is appended first
2193    /// and handed back in [`FfiPurgeOutcome::reissue_record`] to send to the server.
2194    pub fn purge_asset(&self, asset_id: String) -> Result<FfiPurgeOutcome, FfiError> {
2195        let asset_id = parse_uuid("asset_id", &asset_id)?;
2196        self.with(|ws| {
2197            let outcome = ws.purge(&asset_id).map_err(trash_error)?;
2198            let reissue_record = outcome
2199                .reissue
2200                .as_ref()
2201                .map(capsule_core::cbor::to_canonical_vec)
2202                .transpose()
2203                .map_err(|e| FfiError::Workspace {
2204                    detail: format!("encoding the re-issued delete of {asset_id}: {e}"),
2205                })?;
2206            tracing::info!(%asset_id, removed_files = outcome.removed_files, reissued = reissue_record.is_some(), "ffi: asset purged");
2207            Ok(FfiPurgeOutcome {
2208                asset_id: asset_id.to_string(),
2209                reissue_record,
2210            })
2211        })
2212    }
2213
2214    /// Every asset in the trash with its signed retention window, most recently deleted first.
2215    ///
2216    /// This is the retention data, not the Recently Deleted *view*: a surface that shows the
2217    /// trash still opens it behind the SR1 fresh-local-auth gate, as `Catalog::query_trash`
2218    /// does.
2219    pub fn trash(&self) -> Result<Vec<FfiTrashEntry>, FfiError> {
2220        let now = Timestamp::now();
2221        self.with(|ws| {
2222            Ok(ws
2223                .trash()
2224                .iter()
2225                .map(|entry| FfiTrashEntry::new(entry, now))
2226                .collect())
2227        })
2228    }
2229
2230    /// The trash entries whose signed retention window has closed: the retention sweep's
2231    /// input, each one ready for [`purge_asset`](Self::purge_asset).
2232    ///
2233    /// A deadline is judged only after a sync drained the feed to its head, so a restore on a
2234    /// later page lands first: pass that drain as `drain`, its `server_heads` covering the whole
2235    /// feed as [`FfiFeedDrain::server_heads`] requires. The deadline is judged by the
2236    /// drain's latest server `changed_at` alone, never by this device's clock, and an asset
2237    /// whose `delete` the server has not indexed (a held delete) never expires. With no drain
2238    /// (`None`: the sync failed, or this device has no server), or a drain that saw no entry,
2239    /// nothing has expired, and the trash keeps every asset until the user empties it.
2240    ///
2241    /// # Errors
2242    ///
2243    /// [`FfiError::InvalidArgument`] for a `latest_changed_at` that is not RFC 3339.
2244    pub fn expired_trash(
2245        &self,
2246        drain: Option<FfiFeedDrain>,
2247    ) -> Result<Vec<FfiTrashEntry>, FfiError> {
2248        let drain = drain.as_ref().map(FfiFeedDrain::parse).transpose()?;
2249        // Every entry the sweep returns was judged at this reading; with none it returns none.
2250        let judged_at = drain.as_ref().and_then(FeedDrain::judged_at);
2251        self.with(|ws| {
2252            Ok(ws
2253                .expired_trash_after_drain(drain.as_ref())
2254                .iter()
2255                .filter_map(|entry| judged_at.map(|at| FfiTrashEntry::new(entry, at)))
2256                .collect())
2257        })
2258    }
2259
2260    /// The signed `delete` that ended a purged asset, the head of its kept provenance chain, as
2261    /// the opaque canonical CBOR record [`FfiPurgeOutcome::reissue_record`] carries. After an
2262    /// early purge it is that same re-issue, so a delivery to the album's ops surface that
2263    /// failed can be resent from here, also after a reopen
2264    /// ([`FfiSession::apply_lifecycle_op`](super::FfiSession::apply_lifecycle_op), or
2265    /// [`FfiSession::deliver_purge`](super::FfiSession::deliver_purge) for the whole stretch).
2266    /// `None` for an asset this workspace has not purged.
2267    pub fn purged_record(&self, asset_id: String) -> Result<Option<Vec<u8>>, FfiError> {
2268        let asset_id = parse_uuid("asset_id", &asset_id)?;
2269        self.with(|ws| {
2270            ws.purge_record(&asset_id)
2271                .map(capsule_core::cbor::to_canonical_vec)
2272                .transpose()
2273                .map_err(|e| FfiError::Workspace {
2274                    detail: format!("encoding the purge record of {asset_id}: {e}"),
2275                })
2276        })
2277    }
2278}