Skip to main content

mobiler_core/
clipboard.rs

1//! A copy with options (ADR-0052): `cx.copy_with` / `cx.copy_sensitive`. The request goes to the built-in
2//! `clipboard_with` capability, not `clipboard`, so a shell that predates it answers `ok: false` instead of copying a
3//! secret in plain text.
4
5use std::time::Duration;
6
7/// How [`Cx::copy_with`](crate::Cx::copy_with) copies. [`CopyOptions::new`] is a plain copy (like `cx.copy`, but with
8/// a reply); [`CopyOptions::sensitive`] is the preset for a password, a recovery code or a TOTP secret.
9///
10/// What each platform honours:
11/// - `mark_sensitive`: Android hides the text in the clipboard preview (Android 13+) and asks keyboards not to keep it
12///   (some, e.g. Gboard, honour that). iOS has no system flag; it attaches the `org.nspasteboard.ConcealedType`
13///   convention, which only some Mac clipboard managers honour, and only if the copy reaches a Mac (`local_only` off).
14///   The web can't.
15/// - `expires_after`: iOS removes the item itself. On Android it is **best effort**: the shell clears the clipboard
16///   when the time is up, but only while it still holds this copy. Android 10+ lets only the app in front read the
17///   clipboard, so there, after the user switches away (say, to paste the secret into another app), it clears within
18///   seconds of the app coming back to the front (Android 8–9 clear on time from the background), gives up an hour after the deadline, and never clears if the process dies first.
19///   Android 13+ clears the clipboard itself after about an hour. The hidden preview is Android's dependable
20///   protection. The web can't expire a copy.
21/// - `local_only`: iOS keeps the item out of Universal Clipboard. No effect on Android (an OEM or companion-app
22///   clipboard sync may still carry it) or the web.
23///
24/// A shell that predates `clipboard_with` answers `ok: false`. Don't fall back to `cx.copy` then: that is the plain
25/// copy this exists to avoid.
26#[derive(Clone, Debug, PartialEq)]
27pub struct CopyOptions {
28    sensitive: bool,
29    expires_after: Option<Duration>,
30    local_only: bool,
31}
32
33impl Default for CopyOptions {
34    fn default() -> Self {
35        Self::new()
36    }
37}
38
39impl CopyOptions {
40    /// A plain copy: not sensitive, never expires, may sync to the user's other devices.
41    #[must_use]
42    pub fn new() -> Self {
43        Self { sensitive: false, expires_after: None, local_only: false }
44    }
45
46    /// Sensitive, expires after 2 minutes, kept off other devices (iOS). Every field can still be changed.
47    #[must_use]
48    pub fn sensitive() -> Self {
49        Self { sensitive: true, expires_after: Some(Duration::from_secs(120)), local_only: true }
50    }
51
52    /// Mark the copy sensitive: Android hides the preview (13+) and asks keyboards not to keep it; iOS attaches the
53    /// `org.nspasteboard.ConcealedType` convention (see [`CopyOptions`]).
54    #[must_use]
55    pub fn mark_sensitive(mut self, on: bool) -> Self {
56        self.sensitive = on;
57        self
58    }
59
60    /// Remove the copy after `d` (at least 1 s); best effort on Android, see [`CopyOptions`].
61    #[must_use]
62    pub fn expires_after(mut self, d: Duration) -> Self {
63        self.expires_after = Some(d.max(Duration::from_secs(1)));
64        self
65    }
66
67    /// Leave the copy on the clipboard until something replaces it.
68    #[must_use]
69    pub fn never_expires(mut self) -> Self {
70        self.expires_after = None;
71        self
72    }
73
74    /// Keep the copy on this device (iOS: out of Universal Clipboard).
75    #[must_use]
76    pub fn local_only(mut self, on: bool) -> Self {
77        self.local_only = on;
78        self
79    }
80
81    /// The `clipboard_with` request's input: every key always present (ADR-0052).
82    pub(crate) fn to_input(&self, text: &str) -> String {
83        let expires_ms = self.expires_after.map(|d| u64::try_from(d.as_millis()).unwrap_or(u64::MAX));
84        serde_json::json!({
85            "text": text,
86            "sensitive": self.sensitive,
87            "expires_ms": expires_ms,
88            "local_only": self.local_only,
89        })
90        .to_string()
91    }
92}
93
94/// What a `clipboard_with` shell applied to a copy it made (ADR-0053), read from an `ok: true` reply with
95/// [`CopyApplied::from_response`].
96#[derive(Clone, Copy, Debug, PartialEq, Eq)]
97pub struct CopyApplied {
98    /// A sensitive marker was attached to the copy. Whether anything honours it depends on who reads the clipboard:
99    /// on Android the `IS_SENSITIVE` extra hides the preview on 13+ and asks keyboards not to keep it (some honour
100    /// it); on iOS `org.nspasteboard.ConcealedType` is honoured only by some Mac clipboard managers, and only if the
101    /// copy reaches a Mac (`local_only` off). Never on the web. It is not proof that the text is hidden.
102    pub sensitive: bool,
103    /// Who removes the copy when its time is up: who would, not when. A huge `expires_after` is reported like any other.
104    pub expires: CopyExpiry,
105    /// The platform keeps the copy off the user's other devices (iOS `.localOnly`). Never on Android or the web.
106    pub local_only: bool,
107}
108
109/// How a copy expires, as the shell reported it. Non-exhaustive: a later shell may report a new kind, which this core
110/// reads as an unknown report.
111///
112/// An app's `match` needs a wildcard arm:
113///
114/// ```compile_fail
115/// use mobiler_core::CopyExpiry;
116/// fn who(e: CopyExpiry) -> &'static str {
117///     match e {
118///         CopyExpiry::System => "system",
119///         CopyExpiry::BestEffort => "best effort",
120///         CopyExpiry::Never => "never",
121///     }
122/// }
123/// ```
124#[derive(Clone, Copy, Debug, PartialEq, Eq)]
125#[non_exhaustive]
126pub enum CopyExpiry {
127    /// The OS removes it (iOS `.expirationDate`).
128    System,
129    /// The shell clears it if the clipboard still holds it (Android; ADR-0052).
130    BestEffort,
131    /// It doesn't expire: none was asked, or the platform can't (the web). `"none"` on the wire.
132    Never,
133}
134
135impl CopyApplied {
136    /// The report in an `ok: true` reply, or `None` when there is none to trust: the copy failed, the output is
137    /// empty (a shell from CLI 0.68 reports nothing), it doesn't parse, or it names an expiry this core doesn't know.
138    /// `None` means *unknown*: an app that needs a protected copy treats it as not protected.
139    pub fn from_response(resp: &crate::PluginResponse) -> Option<Self> {
140        if !resp.ok {
141            return None;
142        }
143        let v: serde_json::Value = serde_json::from_slice(&resp.output).ok()?;
144        let expires = match v.get("expires")?.as_str()? {
145            "system" => CopyExpiry::System,
146            "best_effort" => CopyExpiry::BestEffort,
147            "none" => CopyExpiry::Never,
148            _ => return None,
149        };
150        Some(Self { sensitive: v.get("sensitive")?.as_bool()?, expires, local_only: v.get("local_only")?.as_bool()? })
151    }
152}
153
154#[cfg(test)]
155mod tests {
156    use super::*;
157    use crate::PluginResponse;
158
159    fn ok(s: &str) -> PluginResponse {
160        PluginResponse::text(true, s)
161    }
162
163    #[test]
164    fn each_shells_sensitive_report_parses() {
165        let android = ok(r#"{"sensitive":true,"expires":"best_effort","local_only":false}"#);
166        let ios = ok(r#"{"sensitive":true,"expires":"system","local_only":true}"#);
167        let web = ok(r#"{"sensitive":false,"expires":"none","local_only":false}"#);
168        assert_eq!(CopyApplied::from_response(&android), Some(CopyApplied { sensitive: true, expires: CopyExpiry::BestEffort, local_only: false }));
169        assert_eq!(CopyApplied::from_response(&ios), Some(CopyApplied { sensitive: true, expires: CopyExpiry::System, local_only: true }));
170        assert_eq!(CopyApplied::from_response(&web), Some(CopyApplied { sensitive: false, expires: CopyExpiry::Never, local_only: false }));
171    }
172
173    #[test]
174    fn an_empty_report_is_unknown() {
175        // A shell from CLI 0.68 answers ok:true with an empty output.
176        assert_eq!(CopyApplied::from_response(&ok("")), None);
177    }
178
179    #[test]
180    fn a_failed_copy_has_no_report() {
181        let failed = PluginResponse::text(false, r#"{"sensitive":true,"expires":"system","local_only":true}"#);
182        assert_eq!(CopyApplied::from_response(&failed), None);
183    }
184
185    #[test]
186    fn an_unknown_expiry_is_unknown() {
187        assert_eq!(CopyApplied::from_response(&ok(r#"{"sensitive":true,"expires":"later","local_only":true}"#)), None);
188    }
189
190    #[test]
191    fn a_malformed_or_partial_report_is_unknown() {
192        assert_eq!(CopyApplied::from_response(&ok("not json")), None);
193        assert_eq!(CopyApplied::from_response(&ok(r#"{"sensitive":true,"expires":"system"}"#)), None);
194        assert_eq!(CopyApplied::from_response(&ok(r#"{"sensitive":"yes","expires":"system","local_only":true}"#)), None);
195    }
196}