Skip to main content

weirdnet_update/
policy.rs

1//! Opt-in consent policy. Updates are never forced.
2//!
3//! Per app the user picks a [`ConsentMode`]: ask for each update (the default), install
4//! automatically, notify only, or off. The F-Droid flavor defaults to off. Which update kinds
5//! a build may take at all depends on its [`Flavor`]. New capabilities always ask again, even
6//! in automatic mode. Declining is remembered and never blocks the app.
7
8use crate::manifest::{UpdateKind, UpdateManifest};
9use crate::{Error, Result, Timestamp};
10use serde::{Deserialize, Serialize};
11use std::collections::BTreeSet;
12
13/// The user's choice for an app.
14#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
15#[serde(rename_all = "kebab-case")]
16pub enum ConsentMode {
17    /// Ask for each update (default).
18    #[default]
19    Ask,
20    /// Install updates automatically (opt-in). New capabilities still ask.
21    Auto,
22    /// Show that an update exists; never download it.
23    NotifyOnly,
24    /// No update checks.
25    Off,
26}
27
28/// How the app was distributed; decides which update kinds it may take.
29#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
30#[serde(rename_all = "kebab-case")]
31pub enum Flavor {
32    /// Desktop builds outside a store.
33    Desktop,
34    /// Sideloaded Android or iOS outside a store.
35    Sideload,
36    /// Google Play: no full updates.
37    Play,
38    /// Apple App Store and TestFlight: assets, Wasm and store notices only.
39    AppStore,
40    /// Mac App Store: store notices only.
41    MacAppStore,
42    /// F-Droid: opt-in assets and Wasm only, off by default.
43    FDroid,
44}
45
46impl Flavor {
47    /// The mode a fresh install starts in.
48    pub fn default_mode(self) -> ConsentMode {
49        match self {
50            Self::FDroid => ConsentMode::Off,
51            _ => ConsentMode::Ask,
52        }
53    }
54
55    /// Whether this flavor may take `kind`. Dart patches also need `dart_patches`, which no
56    /// client turns on until the engine support exists.
57    pub fn allows(self, kind: &UpdateKind, dart_patches: bool) -> bool {
58        match kind {
59            UpdateKind::StoreNotice { .. } => true,
60            UpdateKind::Assets | UpdateKind::Wasm { .. } => !matches!(self, Self::MacAppStore),
61            UpdateKind::Full(_) => matches!(self, Self::Desktop | Self::Sideload),
62            UpdateKind::DartPatch(_) => dart_patches && matches!(self, Self::Desktop | Self::Sideload | Self::Play),
63        }
64    }
65}
66
67/// The per-app policy.
68#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
69pub struct Policy {
70    /// Distribution flavor.
71    pub flavor: Flavor,
72    /// Dart patches enabled for this build (placeholder; keep `false`).
73    #[serde(default)]
74    pub dart_patches: bool,
75}
76
77/// A recorded user choice.
78#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
79#[serde(rename_all = "kebab-case")]
80pub enum Choice {
81    /// Install this update, with the capabilities it listed.
82    Accepted,
83    /// Don't install this update.
84    Declined,
85    /// Switched the app's mode.
86    Mode(ConsentMode),
87    /// Agreed to the F-Droid wording ("you're choosing to bypass F-Droid's checks").
88    FDroidBypassAcknowledged,
89}
90
91/// One timestamped choice.
92#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
93pub struct ConsentRecord {
94    /// The update the choice is about; `None` for mode changes.
95    pub update_id: Option<String>,
96    /// The choice.
97    pub choice: Choice,
98    /// When it was made.
99    pub at: Timestamp,
100}
101
102/// The app's consent history, stored locally by the app.
103#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
104pub struct ConsentLog {
105    /// Records, oldest first.
106    pub records: Vec<ConsentRecord>,
107}
108
109impl ConsentLog {
110    /// Records a per-update choice.
111    pub fn decide(&mut self, update_id: &str, accepted: bool, at: Timestamp) {
112        let choice = if accepted { Choice::Accepted } else { Choice::Declined };
113        self.records.push(ConsentRecord { update_id: Some(update_id.to_owned()), choice, at });
114    }
115
116    /// Records a mode change. Leaving `Off` in the F-Droid flavor needs the F-Droid
117    /// acknowledgement first.
118    pub fn set_mode(&mut self, flavor: Flavor, mode: ConsentMode, at: Timestamp) -> Result<()> {
119        if flavor == Flavor::FDroid && mode != ConsentMode::Off && !self.fdroid_acknowledged() {
120            return Err(Error::invalid("consent", "F-Droid builds need the bypass acknowledgement before updates are enabled"));
121        }
122        self.records.push(ConsentRecord { update_id: None, choice: Choice::Mode(mode), at });
123        Ok(())
124    }
125
126    /// Records the F-Droid acknowledgement.
127    pub fn acknowledge_fdroid(&mut self, at: Timestamp) {
128        self.records.push(ConsentRecord { update_id: None, choice: Choice::FDroidBypassAcknowledged, at });
129    }
130
131    fn fdroid_acknowledged(&self) -> bool {
132        self.records.iter().any(|r| r.choice == Choice::FDroidBypassAcknowledged)
133    }
134
135    /// The current mode: the last mode change, or the flavor's default.
136    pub fn mode(&self, flavor: Flavor) -> ConsentMode {
137        self.records
138            .iter()
139            .rev()
140            .find_map(|r| match r.choice {
141                Choice::Mode(m) => Some(m),
142                _ => None,
143            })
144            .unwrap_or(flavor.default_mode())
145    }
146
147    /// The latest accept or decline for an update.
148    pub fn choice_for(&self, update_id: &str) -> Option<bool> {
149        self.records.iter().rev().find_map(|r| match (&r.update_id, &r.choice) {
150            (Some(id), Choice::Accepted) if id == update_id => Some(true),
151            (Some(id), Choice::Declined) if id == update_id => Some(false),
152            _ => None,
153        })
154    }
155}
156
157/// Why the client should ask.
158#[derive(Clone, Debug, PartialEq, Eq)]
159pub enum AskReason {
160    /// The mode is "ask for each update".
161    PerUpdate,
162    /// Auto mode, but the update requests capabilities not granted before.
163    NewCapabilities,
164}
165
166/// Why nothing happens.
167#[derive(Clone, Copy, Debug, PartialEq, Eq)]
168pub enum SkipReason {
169    /// Updates are off.
170    Off,
171    /// The user declined this update.
172    Declined,
173    /// This build's flavor can't take this kind.
174    KindNotAllowed,
175}
176
177/// What the client does with a verified, targeted update.
178#[derive(Clone, Debug, PartialEq, Eq)]
179pub enum Decision {
180    /// Download and install (the user opted in to auto mode, or accepted this update).
181    Install,
182    /// Show the consent prompt.
183    Ask {
184        /// Why.
185        reason: AskReason,
186        /// Capabilities not granted before (always shown).
187        new_capabilities: Vec<String>,
188        /// Security label present: show the distinct badge.
189        security: bool,
190    },
191    /// Show a notice only (notify-only mode, or a store notice).
192    Notify {
193        /// Security label present: show it prominently.
194        security: bool,
195    },
196    /// Do nothing.
197    Skip(SkipReason),
198}
199
200/// Decides what to do with an update. `granted` holds capabilities the user already approved.
201pub fn decide(policy: &Policy, log: &ConsentLog, update: &UpdateManifest, granted: &BTreeSet<String>) -> Decision {
202    if !policy.flavor.allows(&update.kind, policy.dart_patches) {
203        return Decision::Skip(SkipReason::KindNotAllowed);
204    }
205    let mode = log.mode(policy.flavor);
206    let security = update.labels.security.is_some();
207    if mode == ConsentMode::Off {
208        return Decision::Skip(SkipReason::Off);
209    }
210    if matches!(update.kind, UpdateKind::StoreNotice { .. }) {
211        return Decision::Notify { security };
212    }
213    match log.choice_for(&update.update_id) {
214        Some(false) => return Decision::Skip(SkipReason::Declined),
215        Some(true) => return Decision::Install,
216        None => {}
217    }
218    let new_capabilities: Vec<String> = update.capabilities.iter().filter(|c| !granted.contains(*c)).cloned().collect();
219    match mode {
220        ConsentMode::NotifyOnly => Decision::Notify { security },
221        ConsentMode::Ask => Decision::Ask { reason: AskReason::PerUpdate, new_capabilities, security },
222        ConsentMode::Auto if new_capabilities.is_empty() => Decision::Install,
223        ConsentMode::Auto => Decision::Ask { reason: AskReason::NewCapabilities, new_capabilities, security },
224        ConsentMode::Off => Decision::Skip(SkipReason::Off),
225    }
226}