1#![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#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
79pub struct Settings {
80 #[serde(default)]
82 pub general: General,
83 #[serde(default)]
85 pub admin: Admin,
86 #[serde(default, skip_serializing_if = "Option::is_none")]
88 pub project: Option<Project>,
89}
90
91impl Settings {
92 pub fn to_json(&self) -> Result<String, Error> {
94 Ok(serde_json::to_string(self)?)
95 }
96
97 pub fn to_json_pretty(&self) -> Result<String, Error> {
99 Ok(serde_json::to_string_pretty(self)?)
100 }
101
102 pub fn encode(&self) -> Result<String, Error> {
104 encode(self)
105 }
106
107 pub fn decode(payload: &str) -> Result<Settings, Error> {
109 decode(payload)
110 }
111
112 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
175fn 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}