From be5c6accc1f3d5d60a626cd3ab5d9e1012dcfe8d Mon Sep 17 00:00:00 2001 From: William Dunn Date: Sat, 7 Nov 2026 08:22:02 -0500 Subject: [PATCH] craft-esign: add the e-sign contract and craft-ui's esign feature This carries over crates/esign and craft-ui's esign dialog from the cut-down #160 branch, with minimal workspace wiring. The esign dialog speaks only craft_cloud::Contact and craft_esign types. This also brings crates/cloud along as a dependency until PR #160 lands on main. --- Cargo.toml | 2 + crates/esign/Cargo.toml | 19 ++ crates/esign/src/error.rs | 63 ++++ crates/esign/src/lib.rs | 195 +++++++++++ crates/esign/src/types.rs | 172 ++++++++++ crates/ui/Cargo.toml | 8 +- crates/ui/src/esign/backend.rs | 92 +++++ crates/ui/src/esign/mod.rs | 607 +++++++++++++++++++++++++++++++++ crates/ui/src/lib.rs | 2 + 9 files changed, 1158 insertions(+), 2 deletions(-) create mode 100644 crates/esign/Cargo.toml create mode 100644 crates/esign/src/error.rs create mode 100644 crates/esign/src/lib.rs create mode 100644 crates/esign/src/types.rs create mode 100644 crates/ui/src/esign/backend.rs create mode 100644 crates/ui/src/esign/mod.rs diff --git a/Cargo.toml b/Cargo.toml index 319e0c1e8..f79734650 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -62,6 +62,7 @@ craft-atomic = { path = "crates/atomic" } craft-xtask = { path = "crates/xtask" } craft-captions = { path = "crates/captions" } craft-cfb = { path = "crates/cfb" } +craft-cloud = { path = "crates/cloud" } craft-codepage = { path = "crates/codepage" } craft-cms = { path = "crates/cms" } craft-cloud = { path = "crates/cloud" } @@ -95,6 +96,7 @@ craft-dpx = { path = "crates/dpx" } craft-dwg = { path = "crates/dwg" } craft-fcproj-format = { path = "crates/fcproj-format" } craft-ecproj-format = { path = "crates/ecproj-format" } +craft-esign = { path = "crates/esign" } craft-figma-rest = { path = "crates/figma-rest" } craft-exr = { path = "crates/exr" } craft-flags = { path = "crates/flags" } diff --git a/crates/esign/Cargo.toml b/crates/esign/Cargo.toml new file mode 100644 index 000000000..7a2efc324 --- /dev/null +++ b/crates/esign/Cargo.toml @@ -0,0 +1,19 @@ +[package] +name = "craft-esign" +version.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true +rust-version.workspace = true +description = "What an e-sign service offers the Craft apps: envelopes, recipients and events as contracts, with no vendor and no IO" + +[lints] +workspace = true + +[dependencies] +craft-cloud = { workspace = true } +serde = { workspace = true } +thiserror = { workspace = true } + +[dev-dependencies] +serde_json = { workspace = true } diff --git a/crates/esign/src/error.rs b/crates/esign/src/error.rs new file mode 100644 index 000000000..fca354b45 --- /dev/null +++ b/crates/esign/src/error.rs @@ -0,0 +1,63 @@ +//! One error type for every e-sign contract. +//! +//! Cloud failures are wrapped so a host can surface sign-in and reachability +//! the same way it already does for files. The e-sign-only cases are the ones +//! a UI acts on differently: declined, voided, expired, identity check. + +use thiserror::Error; + +#[derive(Debug, Error)] +pub enum Error { + /// Something the cloud contracts already classify. + #[error(transparent)] + Cloud(#[from] craft_cloud::Error), + + /// A recipient refused to sign. + #[error("declined: {0}")] + Declined(String), + + /// The sender voided the envelope. + #[error("voided: {0}")] + Voided(String), + + /// The envelope passed its deadline without completing. + #[error("expired: {0}")] + Expired(String), + + /// The provider rejected the signer's identity check. + #[error("identity check failed: {0}")] + IdentityCheck(String), + + /// The chosen provider refuses this request under its policy. + #[error("provider policy: {0}")] + ProviderPolicy(String), + + /// The service does not offer this at all. + #[error("this signing service does not support {0}")] + Unsupported(&'static str), + + /// The answer did not match the protocol. + #[error("malformed {what}: {detail}")] + Malformed { what: &'static str, detail: String }, + + /// A field the caller supplied could not be used safely. + #[error("invalid {what}: {detail}")] + Invalid { what: &'static str, detail: String }, +} + +impl Error { + pub fn malformed(what: &'static str, detail: impl Into) -> Error { + Error::Malformed { what, detail: detail.into() } + } + + pub fn invalid(what: &'static str, detail: impl Into) -> Error { + Error::Invalid { what, detail: detail.into() } + } + + /// Whether trying again could succeed without the user doing anything. + pub fn is_transient(&self) -> bool { + matches!(self, Error::Cloud(e) if e.is_transient()) + } +} + +pub type Result = std::result::Result; diff --git a/crates/esign/src/lib.rs b/crates/esign/src/lib.rs new file mode 100644 index 000000000..4efb15116 --- /dev/null +++ b/crates/esign/src/lib.rs @@ -0,0 +1,195 @@ +//! What an e-sign service has to offer the Craft apps, and nothing about who +//! provides it. +//! +//! An envelope is a ceremony: a document snapshot, a set of recipients, field +//! placements, and a status. The legal audit trail, identity checks and +//! invitation mail belong to the signing service. This crate only names the +//! contracts an app needs to create, send, watch and finish that ceremony. +//! +//! Nothing in this crate opens a socket. Each trait is implemented by a host +//! (CollabCraft, a desktop adapter, a test double) that brings its own +//! transport. No type here names a vendor. No type here knows about PDF +//! structure: a document is opaque bytes plus a content hash. +//! +//! This crate sits beside `craft-cloud`. It reuses [`craft_cloud::Identity`] +//! and the idea of a contact for autocomplete, but it does not extend +//! [`craft_cloud::Provider`] or [`craft_cloud::Capability`]. Signing is not +//! file access, and a signer role is not a share permission. + +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +mod error; +mod types; + +pub use error::{Error, Result}; +pub use types::{ + CompletedDocument, Envelope, EnvelopeDraft, EnvelopeEvent, EnvelopeStatus, EsignCapability, FieldPlacement, Recipient, RecipientStatus, +}; + +/// Creating and driving envelopes. +/// +/// Methods that a minimal service may omit are defaulted to +/// [`Error::Unsupported`], the same pattern [`craft_cloud::Conversations`] +/// uses for optional cloud features. +pub trait Envelopes { + /// Create a draft from a document snapshot. + /// + /// `document` is the exact byte sequence the ceremony seals. The + /// implementation hashes it and stores `content_sha256` on the envelope. + /// `idempotency_key` makes a retried create return the same envelope. + fn create(&self, draft: &EnvelopeDraft, document: &[u8], idempotency_key: &str) -> Result; + + /// Send invitations and move the envelope to [`EnvelopeStatus::Sent`]. + fn send(&self, envelope: &str) -> Result; + + /// Current status, including per-recipient progress. + fn status(&self, envelope: &str) -> Result; + + /// The finished document and provider evidence. + /// + /// Fails unless status is [`EnvelopeStatus::Completed`]. + fn completed(&self, envelope: &str) -> Result; + + /// Cancel an in-flight envelope. + fn void(&self, _envelope: &str, _reason: &str) -> Result<()> { + Err(Error::Unsupported("void")) + } + + /// Nudge one recipient who has not signed yet. + fn remind(&self, _envelope: &str, _recipient: &str) -> Result<()> { + Err(Error::Unsupported("reminders")) + } + + /// A URL the recipient opens to sign inside the provider's UI. + fn signing_url(&self, _envelope: &str, _recipient: &str, _return_to: &str) -> Result { + Err(Error::Unsupported("embedded signing")) + } +} + +/// Turning provider webhooks into [`EnvelopeEvent`]s. +/// +/// Server-side only. A desktop host that implements [`Envelopes`] never needs +/// a webhook secret and need not implement this beyond refusing. +pub trait EventIntake { + /// Verify authenticity and parse zero or more events from one HTTP body. + fn verify_event(&self, headers: &[(String, String)], body: &[u8]) -> Result>; +} + +/// Everything one signing service can do. +/// +/// A service implements the capabilities it has and reports the rest as +/// absent, so a caller can hide void on a stub that only supports the happy +/// path rather than offering a control that fails on use. +pub trait SigningService: Envelopes + EventIntake { + /// A stable identifier, such as `stub` or `documenso`. Used in + /// configuration and logs, never shown to a user. + fn id(&self) -> &str; + + /// What this service actually supports. + fn capabilities(&self) -> Vec; + + fn supports(&self, capability: EsignCapability) -> bool { + self.capabilities().contains(&capability) + } + + /// The party that holds legal and compliance responsibility for the + /// ceremony. Shown to senders before they send (upstream #2315). + fn responsible_party(&self) -> String; +} + +#[cfg(test)] +mod tests { + use super::*; + use craft_cloud::Identity; + + struct RefuseAll; + + impl Envelopes for RefuseAll { + fn create(&self, _: &EnvelopeDraft, _: &[u8], _: &str) -> Result { + Err(Error::Unsupported("create")) + } + + fn send(&self, _: &str) -> Result { + Err(Error::Unsupported("send")) + } + + fn status(&self, _: &str) -> Result { + Err(Error::Unsupported("status")) + } + + fn completed(&self, _: &str) -> Result { + Err(Error::Unsupported("completed")) + } + } + + impl EventIntake for RefuseAll { + fn verify_event(&self, _: &[(String, String)], _: &[u8]) -> Result> { + Err(Error::Unsupported("webhooks")) + } + } + + impl SigningService for RefuseAll { + fn id(&self) -> &str { + "refuse" + } + + fn capabilities(&self) -> Vec { + Vec::new() + } + + fn responsible_party(&self) -> String { + "nobody".into() + } + } + + #[test] + fn defaulted_methods_are_unsupported() { + let s = RefuseAll; + assert!(matches!(s.void("e", "x"), Err(Error::Unsupported("void")))); + assert!(matches!(s.remind("e", "r"), Err(Error::Unsupported("reminders")))); + assert!(matches!(s.signing_url("e", "r", "https://example"), Err(Error::Unsupported("embedded signing")))); + assert!(!s.supports(EsignCapability::Envelopes)); + assert_eq!(s.responsible_party(), "nobody"); + } + + #[test] + fn draft_round_trips_json() { + let draft = EnvelopeDraft { + title: "NDA".into(), + message: Some("please sign".into()), + sender: Identity { id: "u1".into(), display: "Ada".into(), email: Some("ada@example.com".into()), avatar: None }, + document_id: Some("doc-1".into()), + document_etag: Some("\"abc\"".into()), + recipients: vec![Recipient { + id: "r1".into(), + name: "Bob".into(), + email: "bob@example.com".into(), + role: "Signer".into(), + required: true, + status: RecipientStatus::Pending, + }], + placements: vec![FieldPlacement { + role: "Signer".into(), + page: 0, + x: 0.1, + y: 0.2, + w: 0.3, + h: 0.05, + kind: "signature".into(), + required: true, + }], + expires: Some("2026-12-31".into()), + }; + let json = serde_json::to_string(&draft).expect("serialize"); + let back: EnvelopeDraft = serde_json::from_str(&json).expect("deserialize"); + assert_eq!(back, draft); + } + + #[test] + fn cloud_errors_wrap_and_report_transient() { + let err = Error::from(craft_cloud::Error::Unreachable("down".into())); + assert!(err.is_transient()); + let err = Error::Declined("no".into()); + assert!(!err.is_transient()); + } +} diff --git a/crates/esign/src/types.rs b/crates/esign/src/types.rs new file mode 100644 index 000000000..c75f99a67 --- /dev/null +++ b/crates/esign/src/types.rs @@ -0,0 +1,172 @@ +//! The data the e-sign contracts pass around. +//! +//! Every type here is plain and vendor-neutral. A field that only means +//! something to one product belongs in that provider's crate. Nothing here +//! knows about PDF structure; a document is opaque bytes plus a content hash. + +use craft_cloud::Identity; +use serde::{Deserialize, Serialize}; + +/// What a signing service can do. +/// +/// Reported rather than assumed, so a caller hides void or remind on a service +/// that only supports create/send/status/completed. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum EsignCapability { + /// Create, send, poll status, and fetch the completed document. + Envelopes, + /// Cancel an in-flight envelope. + Void, + /// Nudge a recipient who has not signed yet. + Reminders, + /// Return a URL the recipient opens to sign in the provider's UI. + EmbeddedSigning, + /// Accept provider webhooks and turn them into [`EnvelopeEvent`]s. + Webhooks, +} + +/// Where an envelope is in its life. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum EnvelopeStatus { + /// Created but not yet sent to recipients. + Draft, + /// At least one recipient still owes a signature. + Sent, + /// Every required recipient has signed. + Completed, + /// The sender cancelled it. + Voided, + /// A recipient declined. + Declined, + /// The deadline passed without completion. + Expired, +} + +/// What one recipient still owes, or has done. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum RecipientStatus { + Pending, + Viewed, + Signed, + Declined, +} + +/// Who must sign, as the dialog and the service agree. +/// +/// Built from a [`craft_cloud::Contact`] by an explicit conversion at the host +/// boundary. Never a [`craft_cloud::ShareTarget`]: signing is not access. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Recipient { + /// Opaque handle the service wants back. + pub id: String, + /// What to show. A display name where there is one. + pub name: String, + /// Delivery address. Required for invitation mail. + pub email: String, + /// Signer role label, such as "Client" or "Countersign". Colours and + /// field placement key off this string within one envelope. + pub role: String, + /// Whether the envelope cannot complete without this person. + pub required: bool, + pub status: RecipientStatus, +} + +/// One signature (or initials / date) placement on the document. +/// +/// Coordinates are normalised page space: origin top-left, `x`/`y`/`w`/`h` in +/// `[0.0, 1.0]` of the page. The document implementation maps these onto its +/// own field model; this crate never sees PDF objects. +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct FieldPlacement { + /// Recipient role this field belongs to. + pub role: String, + /// Zero-based page index. + pub page: u32, + pub x: f32, + pub y: f32, + pub w: f32, + pub h: f32, + /// Machine-readable kind: `signature`, `initials`, `date`, `text`. + pub kind: String, + pub required: bool, +} + +impl PartialEq for FieldPlacement { + fn eq(&self, other: &Self) -> bool { + self.role == other.role + && self.page == other.page + && self.kind == other.kind + && self.required == other.required + && self.x.to_bits() == other.x.to_bits() + && self.y.to_bits() == other.y.to_bits() + && self.w.to_bits() == other.w.to_bits() + && self.h.to_bits() == other.h.to_bits() + } +} + +impl Eq for FieldPlacement {} + +/// What the caller wants to send, before the service assigns an id. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct EnvelopeDraft { + /// Human title for the ceremony. + pub title: String, + /// Optional note shown to recipients. + pub message: Option, + /// Who is asking for signatures. Bound to the active account at send time. + pub sender: Identity, + /// Cloud document identity at the moment of the snapshot, when known. + pub document_id: Option, + pub document_etag: Option, + pub recipients: Vec, + pub placements: Vec, + /// `YYYY-MM-DD`. After this the envelope expires if still open. + pub expires: Option, +} + +/// An envelope the service knows about. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Envelope { + pub id: String, + pub title: String, + pub message: Option, + pub sender: Identity, + pub document_id: Option, + pub document_etag: Option, + /// SHA-256 of the document bytes at create time, lowercase hex. + pub content_sha256: String, + pub recipients: Vec, + pub placements: Vec, + pub status: EnvelopeStatus, + pub expires: Option, + /// RFC 3339. + pub created: Option, + /// RFC 3339 when status became [`EnvelopeStatus::Completed`]. + pub completed_at: Option, +} + +/// The finished document plus whatever evidence the provider returns. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct CompletedDocument { + pub envelope_id: String, + /// Signed document bytes. Opaque to this crate. + pub bytes: Vec, + /// Provider evidence (certificate of completion, audit export, …). + pub evidence: Vec, +} + +/// Something that happened to an envelope. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct EnvelopeEvent { + pub envelope_id: String, + /// Machine-readable kind: `sent`, `viewed`, `signed`, `declined`, `voided`, `completed`. + pub kind: String, + /// Recipient id when the event is about one person. + pub recipient_id: Option, + /// RFC 3339. + pub at: Option, + pub detail: Option, +} diff --git a/crates/ui/Cargo.toml b/crates/ui/Cargo.toml index ac5085cd9..cbb7b8dfe 100644 --- a/crates/ui/Cargo.toml +++ b/crates/ui/Cargo.toml @@ -19,9 +19,11 @@ log = "0.4" serde = { version = "1", features = ["derive"], optional = true } # Same version as epaint's, for reading a face's character map. skrifa = { version = "0.44", default-features = false, features = ["std"] } -# The vendor-neutral vocabulary the share dialog speaks. No IO and no -# vendor, so this stays buildable for the web. +# The vendor-neutral vocabulary the share and e-sign dialogs speak. No IO and +# no vendor, so this stays buildable for the web. craft-cloud = { workspace = true, optional = true } +# The e-sign contract the request-signatures dialog states its work through. +craft-esign = { workspace = true, optional = true } # The control channel's report of the cloud state. One serialiser here # rather than one per application. No IO and no vendor. serde_json = { workspace = true, optional = true } @@ -65,6 +67,8 @@ share = ["dep:craft-cloud"] # Open and Save against cloud storage. Needs the share dialog, which a # document's overflow menu and the Share split button both open. cloud = ["share", "dep:serde_json"] +# Request-signatures dialog. +esign = ["dep:craft-cloud", "dep:craft-esign"] [dev-dependencies] # serde: the IME tests read events that only the suite's egui fork has from JSON. diff --git a/crates/ui/src/esign/backend.rs b/crates/ui/src/esign/backend.rs new file mode 100644 index 000000000..8d80a18f4 --- /dev/null +++ b/crates/ui/src/esign/backend.rs @@ -0,0 +1,92 @@ +//! Where the e-sign dialog's work happens, which is never on the frame. +//! +//! Same shape as [`crate::share::ShareBackend`]: the dialog states what it +//! wants, something behind this trait does the waiting, and answers arrive on +//! a channel keyed by sequence number. + +use craft_cloud::Contact; +use craft_esign::{CompletedDocument, Envelope, EnvelopeDraft, EsignCapability}; + +/// One thing the dialog needs done. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Request { + /// What the signing service can actually do, and who is legally responsible. + Capabilities, + /// People matching what has been typed so far (cloud contacts). + Lookup { query: String, limit: usize }, + /// Create a draft from a document snapshot, then optionally send it. + Create { draft: Box, document: Vec, idempotency_key: String, send: bool }, + /// Current status of one envelope. + Status { envelope: String }, + /// Finished document bytes. + Completed { envelope: String }, + /// Cancel an in-flight envelope. + Void { envelope: String, reason: String }, + /// Nudge one recipient. + Remind { envelope: String, recipient: String }, +} + +/// What came back. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Answer { + Capabilities { + capabilities: Vec, + responsible_party: String, + /// Whether a cloud account is attached so invitations can leave. + linked: bool, + }, + Lookup(Vec), + Created(Envelope), + Status(Envelope), + Completed(CompletedDocument), + Voided { + envelope: String, + }, + Reminded { + envelope: String, + recipient: String, + }, +} + +/// Where one answer goes. +pub struct Replier { + seq: u64, + tx: std::sync::mpsc::Sender<(u64, Result)>, +} + +impl Replier { + pub(crate) fn new(seq: u64, tx: std::sync::mpsc::Sender<(u64, Result)>) -> Replier { + Replier { seq, tx } + } + + pub fn seq(&self) -> u64 { + self.seq + } + + pub fn dup(&self) -> Replier { + Replier { seq: self.seq, tx: self.tx.clone() } + } + + pub fn answer(self, answer: Answer) { + self.deliver(Ok(answer)); + } + + pub fn refuse(self, reason: impl Into) { + self.deliver(Err(reason.into())); + } + + fn deliver(self, result: Result) { + let _ = self.tx.send((self.seq, result)); + } +} + +impl std::fmt::Debug for Replier { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Replier").field("seq", &self.seq).finish() + } +} + +/// Somewhere a [`Request`] can run without blocking a frame. +pub trait EsignBackend { + fn submit(&self, request: Request, reply: Replier); +} diff --git a/crates/ui/src/esign/mod.rs b/crates/ui/src/esign/mod.rs new file mode 100644 index 000000000..7bfd017fa --- /dev/null +++ b/crates/ui/src/esign/mod.rs @@ -0,0 +1,607 @@ +//! Request-signatures dialog, the same one in every Craft app that sends PDFs. +//! +//! Nothing here opens a socket. Every call goes through [`EsignBackend`]. +//! Nothing here blocks: answers arrive on a channel and are read once per +//! frame. Signing is not sharing: recipients are never [`craft_cloud::ShareTarget`]s. + +use std::sync::mpsc::{Receiver, Sender}; +use std::time::Duration; + +use craft_cloud::{Contact, Identity}; +use craft_esign::{Envelope, EnvelopeDraft, EnvelopeStatus, EsignCapability, FieldPlacement, Recipient, RecipientStatus}; +use egui::{Context, RichText, Ui}; + +mod backend; + +pub use backend::{Answer, EsignBackend, Replier, Request}; + +/// How long after the last keystroke the dialog asks for matches. +pub const DEBOUNCE: Duration = Duration::from_millis(200); + +const MATCHES: usize = 8; +const MIN_QUERY: usize = 2; +const RETRY: f64 = 20.0; + +type Inbox = (u64, Result); + +/// Every string the dialog shows. +#[derive(Clone, Debug)] +pub struct EsignLabels { + pub title: String, + pub recipients: String, + pub recipient_hint: String, + pub searching: String, + pub no_matches: String, + pub add_address: String, + pub role: String, + pub message: String, + pub send: String, + pub sending: String, + pub close: String, + pub loading: String, + pub responsible: String, + pub no_service: String, + pub sign_in_first: String, + pub need_recipient: String, + pub status: String, + pub void: String, + pub remind: String, + pub download: String, + pub request: String, +} + +impl Default for EsignLabels { + fn default() -> EsignLabels { + EsignLabels { + title: "Request signatures".into(), + recipients: "Signers".into(), + recipient_hint: "Name or email".into(), + searching: "Searching…".into(), + no_matches: "No matches".into(), + add_address: "Add email address".into(), + role: "Role".into(), + message: "Message".into(), + send: "Send".into(), + sending: "Sending…".into(), + close: "Close".into(), + loading: "Loading…".into(), + responsible: "Signing is provided by {party}. That party holds legal and compliance responsibility for the ceremony.".into(), + no_service: "Signatures cannot be requested here.".into(), + sign_in_first: "Sign in to request signatures.".into(), + need_recipient: "Add at least one signer.".into(), + status: "Status".into(), + void: "Void".into(), + remind: "Remind".into(), + download: "Download completed".into(), + request: "Request signatures".into(), + } + } +} + +/// What the application must supply when the user presses Send. +/// +/// The dialog holds recipients and copy; the application owns the document +/// bytes and encodes them, then submits [`Request::Create`] through the backend. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct SendRequest { + pub draft: EnvelopeDraft, + pub idempotency_key: String, +} + +/// One Request signatures dialog. +pub struct EsignDialog { + open: bool, + labels: EsignLabels, + backend: Option>, + capabilities: Option>, + responsible: Option, + linked: bool, + asked_caps_at: Option, + caps_seq: Option, + draft_idempotency_key: Option, + seq: u64, + tx: Sender, + rx: Receiver, + newest: u64, + document_id: String, + document_etag: Option, + document_title: String, + sender: Option, + query: String, + query_changed_at: f64, + lookup_seq: u64, + last_lookup_query: String, + matches: Vec, + looking: bool, + recipients: Vec, + message: String, + placements: Vec, + busy: bool, + error: Option, + envelope: Option, + send_out: Option, + completed_bytes: Option>, + account_fingerprint: Option, +} + +impl Default for EsignDialog { + fn default() -> EsignDialog { + let (tx, rx) = std::sync::mpsc::channel(); + EsignDialog { + open: false, + labels: EsignLabels::default(), + backend: None, + capabilities: None, + responsible: None, + linked: false, + asked_caps_at: None, + caps_seq: None, + draft_idempotency_key: None, + seq: 0, + tx, + rx, + newest: 0, + document_id: String::new(), + document_etag: None, + document_title: String::new(), + sender: None, + query: String::new(), + query_changed_at: 0.0, + lookup_seq: 0, + last_lookup_query: String::new(), + matches: Vec::new(), + looking: false, + recipients: Vec::new(), + message: String::new(), + placements: Vec::new(), + busy: false, + error: None, + envelope: None, + send_out: None, + completed_bytes: None, + account_fingerprint: None, + } + } +} + +impl EsignDialog { + pub fn new() -> EsignDialog { + EsignDialog::default() + } + + pub fn labels(mut self, labels: EsignLabels) -> EsignDialog { + self.labels = labels; + self + } + + pub fn set_backend(&mut self, backend: impl EsignBackend + 'static) { + self.backend = Some(Box::new(backend)); + self.capabilities = None; + self.asked_caps_at = None; + self.caps_seq = None; + } + + /// False until the service reports [`EsignCapability::Envelopes`]. + pub fn available(&self) -> bool { + self.capabilities.as_ref().is_some_and(|c| c.contains(&EsignCapability::Envelopes)) + } + + pub fn is_open(&self) -> bool { + self.open + } + + /// Open for a document. `sender` is the active account identity. + pub fn open(&mut self, document_id: String, document_title: String, document_etag: Option, sender: Identity) { + let fingerprint = format!("{}@{}", sender.id, sender.email.as_deref().unwrap_or("")); + let account_changed = self.account_fingerprint.as_deref() != Some(fingerprint.as_str()); + let document_changed = self.document_id != document_id; + if account_changed || document_changed { + self.recipients.clear(); + self.message.clear(); + self.envelope = None; + self.completed_bytes = None; + self.error = None; + self.draft_idempotency_key = None; + } + self.account_fingerprint = Some(fingerprint); + self.document_id = document_id; + self.document_title = document_title; + self.document_etag = document_etag; + self.sender = Some(sender); + self.open = true; + self.query.clear(); + self.matches.clear(); + } + + pub fn close(&mut self) { + self.open = false; + } + + /// Field placements the app prepared (page-normalised). Replaces any prior set. + pub fn set_placements(&mut self, placements: Vec) { + self.placements = placements; + } + + /// What Send asked the application to encode and submit, if anything. + pub fn take_send_request(&mut self) -> Option { + self.send_out.take() + } + + /// Submit a request through the host backend (for example after the app + /// encoded document bytes for a [`SendRequest`]). + pub fn submit_request(&mut self, request: Request) { + let _ = self.submit(request); + } + + /// Completed document bytes after a successful download request. + pub fn take_completed_bytes(&mut self) -> Option> { + self.completed_bytes.take() + } + + /// Tell the dialog create/send finished (or failed) after the app submitted. + pub fn note_create_result(&mut self, result: Result) { + self.busy = false; + match result { + Ok(env) => { + self.envelope = Some(env); + self.error = None; + } + Err(reason) => self.error = Some(reason), + } + } + + fn submit(&mut self, request: Request) -> u64 { + self.seq = self.seq.saturating_add(1); + let seq = self.seq; + self.newest = seq; + if let Some(backend) = self.backend.as_ref() { + backend.submit(request, Replier::new(seq, self.tx.clone())); + } else { + let _ = self.tx.send((seq, Err("no e-sign backend".into()))); + } + seq + } + + fn pump(&mut self, now: f64) { + while let Ok((seq, result)) = self.rx.try_recv() { + if self.caps_seq == Some(seq) { + self.caps_seq = None; + } + if seq < self.newest && !matches!(result, Ok(Answer::Capabilities { .. })) { + // Stale lookup or status; keep capabilities even if older. + if !matches!(&result, Ok(Answer::Lookup(_))) { + continue; + } + if seq != self.lookup_seq { + continue; + } + } + match result { + Ok(Answer::Capabilities { capabilities, responsible_party, linked }) => { + self.capabilities = Some(capabilities); + self.responsible = Some(responsible_party); + self.linked = linked; + } + Ok(Answer::Lookup(contacts)) if seq == self.lookup_seq => { + self.matches = contacts; + self.looking = false; + } + Ok(Answer::Created(env)) | Ok(Answer::Status(env)) => { + self.busy = false; + self.envelope = Some(env); + self.error = None; + } + Ok(Answer::Completed(doc)) => { + self.busy = false; + self.completed_bytes = Some(doc.bytes); + self.error = None; + } + Ok(Answer::Voided { .. }) => { + self.busy = false; + if let Some(env) = self.envelope.as_mut() { + env.status = EnvelopeStatus::Voided; + } + } + Ok(Answer::Reminded { .. }) => { + self.busy = false; + } + Err(reason) => { + self.busy = false; + self.looking = false; + self.error = Some(reason); + } + _ => {} + } + } + + if self.backend.is_some() && self.caps_seq.is_none() { + let first = self.capabilities.is_none() && self.asked_caps_at.is_none(); + let retry = self.asked_caps_at.is_some_and(|asked| !self.available() && now - asked >= RETRY); + if first || retry { + self.asked_caps_at = Some(now); + self.caps_seq = Some(self.submit(Request::Capabilities)); + } + } + } + + fn maybe_lookup(&mut self, now: f64) { + if !self.open || self.query.len() < MIN_QUERY { + return; + } + if (now - self.query_changed_at) < DEBOUNCE.as_secs_f64() { + return; + } + if self.looking || self.last_lookup_query == self.query { + return; + } + self.looking = true; + self.last_lookup_query = self.query.clone(); + self.lookup_seq = self.submit(Request::Lookup { query: self.query.clone(), limit: MATCHES }); + } + + fn add_contact(&mut self, contact: Contact) { + let email = contact.email.clone().unwrap_or_else(|| contact.id.clone()); + if self.recipients.iter().any(|r| r.email.eq_ignore_ascii_case(&email)) { + return; + } + let role = format!("Signer {}", self.recipients.len() + 1); + self.recipients.push(Recipient { id: contact.id, name: contact.name, email, role, required: true, status: RecipientStatus::Pending }); + self.draft_idempotency_key = None; + self.query.clear(); + self.matches.clear(); + } + + fn add_email(&mut self, email: String) { + let email = email.trim().to_string(); + if email.is_empty() || !email.contains('@') { + return; + } + if self.recipients.iter().any(|r| r.email.eq_ignore_ascii_case(&email)) { + return; + } + let role = format!("Signer {}", self.recipients.len() + 1); + self.recipients.push(Recipient { id: email.clone(), name: email.clone(), email, role, required: true, status: RecipientStatus::Pending }); + self.draft_idempotency_key = None; + self.query.clear(); + self.matches.clear(); + } + + fn queue_send(&mut self) { + let Some(sender) = self.sender.clone() else { + self.error = Some(self.labels.sign_in_first.clone()); + return; + }; + if self.recipients.is_empty() { + self.error = Some(self.labels.need_recipient.clone()); + return; + } + if !self.linked { + self.error = Some(self.labels.sign_in_first.clone()); + return; + } + let draft = EnvelopeDraft { + title: if self.document_title.is_empty() { "Document".into() } else { self.document_title.clone() }, + message: if self.message.trim().is_empty() { None } else { Some(self.message.clone()) }, + sender, + document_id: if self.document_id.is_empty() { None } else { Some(self.document_id.clone()) }, + document_etag: self.document_etag.clone(), + recipients: self.recipients.clone(), + placements: self.placements.clone(), + expires: None, + }; + if self.draft_idempotency_key.is_none() { + self.draft_idempotency_key = Some(format!("esign-{}-{}", self.document_id, self.seq.saturating_add(1))); + } + let idempotency_key = self.draft_idempotency_key.clone().unwrap_or_default(); + self.busy = true; + self.error = None; + self.send_out = Some(SendRequest { draft, idempotency_key }); + } + + /// Draw the dialog when open. Call every frame (even when closed) so + /// capability probes and inbox pumping continue. + pub fn show(&mut self, ctx: &Context) { + let now = ctx.input(|i| i.time); + self.pump(now); + if self.open { + self.maybe_lookup(now); + } + if !self.open { + return; + } + + let mut open = self.open; + let labels = self.labels.clone(); + egui::Window::new(&labels.title).open(&mut open).resizable(true).default_width(420.0).show(ctx, |ui| { + self.ui(ui); + }); + self.open = open; + } + + fn ui(&mut self, ui: &mut Ui) { + if let Some(err) = &self.error { + ui.colored_label(ui.visuals().error_fg_color, err); + ui.add_space(4.0); + } + + if !self.available() { + ui.label(if self.capabilities.is_none() { self.labels.loading.as_str() } else { self.labels.no_service.as_str() }); + return; + } + + if let Some(party) = &self.responsible { + ui.label(RichText::new(self.labels.responsible.replace("{party}", party)).small()); + ui.add_space(6.0); + } + + if let Some(env) = self.envelope.clone() { + self.status_panel(ui, &env); + return; + } + + ui.label(RichText::new(&self.document_title).strong()); + ui.add_space(4.0); + + ui.label(&self.labels.recipients); + let response = ui.add(egui::TextEdit::singleline(&mut self.query).hint_text(&self.labels.recipient_hint)); + if response.changed() { + self.query_changed_at = ui.input(|i| i.time); + self.matches.clear(); + self.looking = false; + self.lookup_seq = 0; + self.last_lookup_query.clear(); + } + if self.looking { + ui.spinner(); + ui.label(&self.labels.searching); + } else if self.query.len() >= MIN_QUERY && self.matches.is_empty() { + ui.horizontal(|ui| { + ui.label(&self.labels.no_matches); + if ui.button(&self.labels.add_address).clicked() { + self.add_email(self.query.clone()); + } + }); + } + for contact in self.matches.clone() { + let label = match &contact.email { + Some(email) => format!("{} <{}>", contact.name, email), + None => contact.name.clone(), + }; + if ui.selectable_label(false, label).clicked() { + self.add_contact(contact); + } + } + + ui.add_space(4.0); + let mut remove: Option = None; + for (i, recipient) in self.recipients.iter().enumerate() { + ui.horizontal(|ui| { + ui.label(format!("{} — {}", recipient.name, recipient.email)); + ui.label(RichText::new(&recipient.role).small()); + if ui.small_button("×").clicked() { + remove = Some(i); + } + }); + } + if let Some(i) = remove { + self.recipients.remove(i); + self.draft_idempotency_key = None; + } + + ui.add_space(6.0); + ui.label(&self.labels.message); + let message = ui.add(egui::TextEdit::multiline(&mut self.message).desired_rows(3)); + if message.changed() { + self.draft_idempotency_key = None; + } + + ui.add_space(8.0); + ui.horizontal(|ui| { + let can_send = !self.busy && self.linked && !self.recipients.is_empty(); + if ui.add_enabled(can_send, egui::Button::new(if self.busy { &self.labels.sending } else { &self.labels.send })).clicked() { + self.queue_send(); + } + if ui.button(&self.labels.close).clicked() { + self.open = false; + } + }); + } + + fn status_panel(&mut self, ui: &mut Ui, env: &Envelope) { + ui.label(RichText::new(&env.title).strong()); + ui.label(format!("{}: {:?}", self.labels.status, env.status)); + for r in &env.recipients { + ui.label(format!("{} — {:?} ({})", r.name, r.status, r.role)); + } + ui.add_space(8.0); + ui.horizontal(|ui| { + let caps = self.capabilities.clone().unwrap_or_default(); + if caps.contains(&EsignCapability::Reminders) + && ui.add_enabled(!self.busy, egui::Button::new(&self.labels.remind)).clicked() + && let Some(r) = env.recipients.iter().find(|r| r.status == RecipientStatus::Pending) + { + self.busy = true; + let _ = self.submit(Request::Remind { envelope: env.id.clone(), recipient: r.id.clone() }); + } + if caps.contains(&EsignCapability::Void) + && env.status == EnvelopeStatus::Sent + && ui.add_enabled(!self.busy, egui::Button::new(&self.labels.void)).clicked() + { + self.busy = true; + let _ = self.submit(Request::Void { envelope: env.id.clone(), reason: "voided by sender".into() }); + } + if env.status == EnvelopeStatus::Completed && ui.add_enabled(!self.busy, egui::Button::new(&self.labels.download)).clicked() { + self.busy = true; + let _ = self.submit(Request::Completed { envelope: env.id.clone() }); + } + if ui.button(&self.labels.close).clicked() { + self.open = false; + } + }); + if ui.button("Refresh status").clicked() { + self.busy = true; + let _ = self.submit(Request::Status { envelope: env.id.clone() }); + } + } +} + +/// Split button that opens the request-signatures dialog. +/// +/// `open` is called when the primary action is chosen. The chevron offers +/// status refresh when an envelope id is known. +pub fn request_button(ui: &mut Ui, labels: &EsignLabels, available: bool, menu: &[crate::menu::MenuItem]) -> Option { + if !available { + return None; + } + let menu_labels = crate::menu::MenuLabels::default(); + crate::menu::split(ui, &labels.request, menu, &menu_labels) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::{Arc, Mutex}; + + struct Capture { + last: Mutex>, + } + + impl EsignBackend for Arc { + fn submit(&self, request: Request, reply: Replier) { + *self.last.lock().expect("lock") = Some(request); + reply.answer(Answer::Capabilities { + capabilities: vec![EsignCapability::Envelopes, EsignCapability::Void], + responsible_party: "Stub Signing".into(), + linked: true, + }); + } + } + + #[test] + fn available_after_capabilities() { + let capture = Arc::new(Capture { last: Mutex::new(None) }); + let mut dialog = EsignDialog::default(); + dialog.set_backend(capture); + let ctx = Context::default(); + dialog.show(&ctx); + dialog.show(&ctx); + assert!(dialog.available()); + assert_eq!(dialog.responsible.as_deref(), Some("Stub Signing")); + } + + #[test] + fn send_request_needs_recipient_and_sender() { + let mut dialog = EsignDialog { + linked: true, + sender: Some(Identity { id: "u".into(), display: "Ada".into(), email: Some("ada@example.com".into()), avatar: None }), + ..Default::default() + }; + dialog.queue_send(); + assert!(dialog.take_send_request().is_none()); + dialog.add_email("bob@example.com".into()); + dialog.queue_send(); + let req = dialog.take_send_request().expect("send"); + assert_eq!(req.draft.recipients.len(), 1); + assert_eq!(req.draft.recipients[0].email, "bob@example.com"); + } +} diff --git a/crates/ui/src/lib.rs b/crates/ui/src/lib.rs index 0c6d42740..a1c091ff1 100644 --- a/crates/ui/src/lib.rs +++ b/crates/ui/src/lib.rs @@ -15,6 +15,8 @@ pub mod cloud; pub mod combo; pub mod direction; pub mod docking; +#[cfg(feature = "esign")] +pub mod esign; mod focus; pub mod fonts; pub mod icons;