Skip to main content

collect_settings/
lib.rs

1//! Build, encode and decode the configuration QR codes used by
2//! [ODK Collect](https://docs.getodk.org/collect-import-export/) and its
3//! rebrand KoboCollect.
4//!
5//! A configuration QR code carries a JSON document with three sections:
6//!
7//! * [`General`] — unprotected settings: server, account, form management,
8//!   user interface;
9//! * [`Admin`] — protected settings: the admin password and every
10//!   access-control switch (`true` = the interviewer may use it);
11//! * [`Project`] — the name, icon and colour shown in the project switcher.
12//!
13//! The JSON is compressed with zlib, encoded as base64 and rendered as a QR
14//! code. Any setting the code omits is reset to its default when scanned, so
15//! the model keeps every field optional and serialises only what you set.
16//!
17//! ```
18//! use collect_settings::{Settings, General, Admin, Project, Autosend, FormUpdateMode};
19//!
20//! let settings = Settings {
21//!     general: General {
22//!         server_url: Some("https://kc.kobotoolbox.org".into()),
23//!         username: Some("interviewer01".into()),
24//!         password: Some("secret".into()),
25//!         autosend: Some(Autosend::WifiAndCellular),
26//!         form_update_mode: Some(FormUpdateMode::MatchExactly),
27//!         automatic_update: Some(true),
28//!         ..General::default()
29//!     },
30//!     admin: Admin::locked_interviewer("admin-pw"),
31//!     project: Some(Project::new("Household survey").icon('H').color("#6b63e6")),
32//! };
33//!
34//! let payload = settings.encode().unwrap();           // base64(zlib(json))
35//! let back = Settings::decode(&payload).unwrap();
36//! assert_eq!(back.general.username.as_deref(), Some("interviewer01"));
37//!
38//! # #[cfg(feature = "qr")] {
39//! let svg = settings.qr_svg(4).unwrap();              // ready to embed or print
40//! assert!(svg.starts_with("<svg"));
41//! # }
42//! ```
43//!
44//! The key names follow the current `ProjectKeys` / `ProtectedProjectKeys` of
45//! ODK Collect. Keys that were renamed between releases (`save_as` →
46//! `save_as_draft`, `mark_as_finalized` → `finalize_in_form_entry`) are
47//! emitted under both names so one code works on old and new app versions;
48//! Collect silently drops the keys it does not know.
49
50#![forbid(unsafe_code)]
51#![warn(missing_docs)]
52
53mod admin;
54mod codec;
55mod general;
56mod project;
57#[cfg(feature = "qr")]
58mod qr;
59
60pub use admin::Admin;
61pub use codec::{decode, encode, encode_json, Error};
62pub use general::{
63    Autosend, BasemapSource, ConstraintBehavior, FontSize, FormUpdateMode, General, GuidanceHint,
64    ImageSize, Navigation, PeriodicCheck, Theme,
65};
66pub use project::Project;
67#[cfg(feature = "qr")]
68pub use qr::{render_svg, QrOptions};
69#[cfg(feature = "qr")]
70pub use qrcode::{EcLevel, QrCode};
71
72use serde::{Deserialize, Serialize};
73
74/// The complete document carried by a configuration QR code.
75///
76/// `general` and `admin` are always serialised (Collect requires both keys,
77/// even when empty); `project` is written only when present.
78#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
79pub struct Settings {
80    /// Unprotected settings (server, account, forms, interface).
81    #[serde(default)]
82    pub general: General,
83    /// Protected settings (admin password and access control).
84    #[serde(default)]
85    pub admin: Admin,
86    /// Project name, icon and colour.
87    #[serde(default, skip_serializing_if = "Option::is_none")]
88    pub project: Option<Project>,
89}
90
91impl Settings {
92    /// Compact JSON exactly as it goes into the QR code (before compression).
93    pub fn to_json(&self) -> Result<String, Error> {
94        Ok(serde_json::to_string(self)?)
95    }
96
97    /// Pretty JSON, for display and review.
98    pub fn to_json_pretty(&self) -> Result<String, Error> {
99        Ok(serde_json::to_string_pretty(self)?)
100    }
101
102    /// `base64(zlib(json))` — the string a QR code must contain.
103    pub fn encode(&self) -> Result<String, Error> {
104        encode(self)
105    }
106
107    /// Parse the string read from a configuration QR code.
108    pub fn decode(payload: &str) -> Result<Settings, Error> {
109        decode(payload)
110    }
111
112    /// Human-readable warnings about combinations that usually surprise people
113    /// in the field. An empty list does not prove the configuration is right;
114    /// it only means none of the known traps is present.
115    pub fn warnings(&self) -> Vec<String> {
116        let mut w = Vec::new();
117        let g = &self.general;
118        let a = &self.admin;
119        match g.server_url.as_deref() {
120            None | Some("") => w.push("general.server_url is empty: the app will keep its current server".into()),
121            Some(u) if !u.starts_with("https://") => {
122                w.push(format!("server_url `{u}` is not https: Collect refuses Basic auth over plain http"))
123            }
124            Some(u) if is_kpi_host(u) => w.push(format!(
125                "server_url `{u}` looks like the KoboToolbox web interface (KPI); the app must point at the KoboCAT host (kc.… / kc-eu.…)"
126            )),
127            _ => {}
128        }
129        if a.admin_pw.as_deref().map_or(true, str::is_empty) && a.locks_anything() {
130            w.push("admin section locks features but admin_pw is empty: anyone can open the protected menu".into());
131        }
132        if a.qr_code_scanner == Some(true) && a.locks_anything() {
133            w.push("qr_code_scanner is allowed: any other QR code can undo these locks".into());
134        }
135        if a.change_server == Some(true) && a.locks_anything() {
136            w.push("change_server is allowed: the interviewer can switch account or server".into());
137        }
138        if g.form_update_mode == Some(FormUpdateMode::MatchExactly)
139            && g.automatic_update == Some(false)
140        {
141            w.push("form_update_mode is match_exactly but automatic_update is false: new versions will wait for a manual refresh".into());
142        }
143        if g.form_update_mode.is_some()
144            && g.form_update_mode != Some(FormUpdateMode::Manual)
145            && g.periodic_form_updates_check.is_none()
146        {
147            w.push("periodic_form_updates_check is unset: the app will use its default interval (every 24 hours)".into());
148        }
149        if a.get_blank == Some(false)
150            && g.form_update_mode
151                .map_or(true, |m| m == FormUpdateMode::Manual)
152        {
153            w.push("get_blank is hidden and form_update_mode is manual: nobody can download forms on the device".into());
154        }
155        if a.send_finalized == Some(false) && g.autosend.map_or(true, |m| m == Autosend::Off) {
156            w.push(
157                "send_finalized is hidden and autosend is off: finalized forms can never be sent"
158                    .into(),
159            );
160        }
161        if g.delete_send == Some(true) {
162            w.push(
163                "delete_send is true: the local copy is removed as soon as a form is sent".into(),
164            );
165        }
166        if let Some(p) = &self.project {
167            if p.icon.as_ref().is_some_and(|i| i.chars().count() > 1) {
168                w.push("project.icon should be a single character".into());
169            }
170        }
171        w
172    }
173}
174
175/// The KoboToolbox *web* hosts (`kf.`, `eu.kobotoolbox.org`), which Collect
176/// cannot talk to. The KoboCAT hosts (`kc.`, `kc-eu.`) are the right ones.
177fn is_kpi_host(url: &str) -> bool {
178    let host = url
179        .trim_start_matches("https://")
180        .trim_start_matches("http://")
181        .split(['/', '?', '#'])
182        .next()
183        .unwrap_or("")
184        .split('@')
185        .next_back()
186        .unwrap_or("")
187        .split(':')
188        .next()
189        .unwrap_or("")
190        .to_ascii_lowercase();
191    host.starts_with("kf.") || host == "eu.kobotoolbox.org"
192}
193
194#[cfg(test)]
195mod tests {
196    use super::*;
197
198    #[test]
199    fn kpi_host_detection() {
200        assert!(is_kpi_host("https://kf.kobotoolbox.org"));
201        assert!(is_kpi_host("https://eu.kobotoolbox.org/"));
202        assert!(is_kpi_host("https://kf.prompt.tec.br"));
203        assert!(!is_kpi_host("https://kc-eu.kobotoolbox.org"));
204        assert!(!is_kpi_host("https://kc.kobotoolbox.org/owner"));
205        assert!(!is_kpi_host(
206            "https://central.example.org/v1/key/abc/projects/1"
207        ));
208    }
209
210    #[test]
211    fn roundtrip() {
212        let s = Settings {
213            general: General {
214                server_url: Some("https://kc.example.org".into()),
215                username: Some("u".into()),
216                password: Some("p".into()),
217                autosend: Some(Autosend::WifiOnly),
218                ..Default::default()
219            },
220            admin: Admin::locked_interviewer("x"),
221            project: Some(Project::new("P").icon('P').color("#000000")),
222        };
223        let enc = s.encode().unwrap();
224        assert_eq!(Settings::decode(&enc).unwrap(), s);
225    }
226
227    #[test]
228    fn empty_sections_are_present() {
229        let json = Settings::default().to_json().unwrap();
230        assert_eq!(json, r#"{"general":{},"admin":{}}"#);
231    }
232
233    #[test]
234    fn warns_about_kpi_host() {
235        let s = Settings {
236            general: General {
237                server_url: Some("https://kf.kobotoolbox.org".into()),
238                ..Default::default()
239            },
240            ..Default::default()
241        };
242        assert!(s.warnings().iter().any(|w| w.contains("KoboCAT")));
243    }
244}