BlueGit

timfa posprint

Files

posprint / src / config.rs

config.rs

config.rs 6.3 KiB Download Raw
1//! Persisted app preferences (trusted URL origins, default page width).
2
3use std::fs;
4use std::path::PathBuf;
5
6use serde::{Deserialize, Serialize};
7
8const CONFIG_VERSION: u32 = 1;
9
10#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
11pub struct AppConfig {
12 #[serde(default = "default_config_version")]
13 pub version: u32,
14 /// Default paper width for **New** documents (mm).
15 #[serde(default = "default_page_width_mm")]
16 pub default_page_width_mm: f32,
17 /// Hostnames allowed to use `noconfirm=1` without asking again.
18 #[serde(default)]
19 pub trusted_origins: Vec<String>,
20}
21
22fn default_config_version() -> u32 {
23 CONFIG_VERSION
24}
25
26fn default_page_width_mm() -> f32 {
27 80.0
28}
29
30impl Default for AppConfig {
31 fn default() -> Self {
32 Self {
33 version: CONFIG_VERSION,
34 default_page_width_mm: default_page_width_mm(),
35 trusted_origins: Vec::new(),
36 }
37 }
38}
39
40impl AppConfig {
41 pub fn load() -> Self {
42 Self::load_from_path(&config_path())
43 }
44
45 pub fn load_from_path(path: &std::path::Path) -> Self {
46 match fs::read_to_string(path) {
47 Ok(text) => match serde_json::from_str::<AppConfig>(&text) {
48 Ok(mut cfg) => {
49 cfg.normalize();
50 cfg
51 }
52 Err(_) => Self::default(),
53 },
54 Err(_) => Self::default(),
55 }
56 }
57
58 pub fn save(&self) -> Result<(), String> {
59 self.save_to_path(&config_path())
60 }
61
62 pub fn save_to_path(&self, path: &std::path::Path) -> Result<(), String> {
63 if let Some(parent) = path.parent() {
64 fs::create_dir_all(parent).map_err(|e| e.to_string())?;
65 }
66 let mut cfg = self.clone();
67 cfg.normalize();
68 let json = serde_json::to_string_pretty(&cfg).map_err(|e| e.to_string())?;
69 fs::write(path, json).map_err(|e| e.to_string())
70 }
71
72 pub fn is_trusted(&self, origin: &str) -> bool {
73 let Some(host) = normalize_origin(origin) else {
74 return false;
75 };
76 self.trusted_origins.iter().any(|o| o == &host)
77 }
78
79 pub fn trust_origin(&mut self, origin: &str) -> bool {
80 let Some(host) = normalize_origin(origin) else {
81 return false;
82 };
83 if !self.trusted_origins.iter().any(|o| o == &host) {
84 self.trusted_origins.push(host);
85 self.trusted_origins.sort();
86 }
87 true
88 }
89
90 pub fn revoke_origin(&mut self, origin: &str) {
91 let Some(host) = normalize_origin(origin) else {
92 return;
93 };
94 self.trusted_origins.retain(|o| o != &host);
95 }
96
97 fn normalize(&mut self) {
98 self.version = CONFIG_VERSION;
99 if !self.default_page_width_mm.is_finite() || self.default_page_width_mm < 40.0 {
100 self.default_page_width_mm = 40.0;
101 } else if self.default_page_width_mm > 120.0 {
102 self.default_page_width_mm = 120.0;
103 }
104 let mut hosts: Vec<String> = self
105 .trusted_origins
106 .iter()
107 .filter_map(|o| normalize_origin(o))
108 .collect();
109 hosts.sort();
110 hosts.dedup();
111 self.trusted_origins = hosts;
112 }
113}
114
115/// Config file path: `%APPDATA%/posprint/config.json` (Windows) or
116/// `$XDG_CONFIG_HOME/posprint/config.json` / `~/.config/posprint/config.json` (Unix).
117pub fn config_path() -> PathBuf {
118 #[cfg(windows)]
119 {
120 let base = std::env::var_os("APPDATA")
121 .map(PathBuf::from)
122 .unwrap_or_else(|| PathBuf::from("."));
123 base.join("posprint").join("config.json")
124 }
125 #[cfg(not(windows))]
126 {
127 let base = std::env::var_os("XDG_CONFIG_HOME")
128 .map(PathBuf::from)
129 .or_else(|| {
130 std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".config"))
131 })
132 .unwrap_or_else(|| PathBuf::from("."));
133 base.join("posprint").join("config.json")
134 }
135}
136
137/// Normalize a caller-supplied origin to a lowercase hostname.
138/// Accepts `example.com`, `https://example.com/path`, `http://localhost:3000`.
139pub fn normalize_origin(raw: &str) -> Option<String> {
140 let s = raw.trim();
141 if s.is_empty() {
142 return None;
143 }
144 let without_scheme = s
145 .strip_prefix("https://")
146 .or_else(|| s.strip_prefix("http://"))
147 .or_else(|| s.strip_prefix("HTTPS://"))
148 .or_else(|| s.strip_prefix("HTTP://"))
149 .unwrap_or(s);
150 let host_port = without_scheme.split('/').next()?.trim();
151 if host_port.is_empty() {
152 return None;
153 }
154 // Drop port for trust matching (example.com:443 → example.com).
155 let host = host_port.split(':').next()?.trim();
156 if host.is_empty() {
157 return None;
158 }
159 Some(host.to_ascii_lowercase())
160}
161
162#[cfg(test)]
163mod tests {
164 use super::*;
165
166 #[test]
167 fn normalize_strips_scheme_path_and_port() {
168 assert_eq!(
169 normalize_origin("https://Shop.Example.com/checkout").as_deref(),
170 Some("shop.example.com")
171 );
172 assert_eq!(
173 normalize_origin("http://localhost:5173/").as_deref(),
174 Some("localhost")
175 );
176 assert_eq!(normalize_origin("example.com").as_deref(), Some("example.com"));
177 assert_eq!(normalize_origin(" ").as_deref(), None);
178 }
179
180 #[test]
181 fn trust_and_revoke_roundtrip() {
182 let mut cfg = AppConfig::default();
183 assert!(!cfg.is_trusted("https://a.example"));
184 assert!(cfg.trust_origin("https://a.example/x"));
185 assert!(cfg.is_trusted("a.example"));
186 assert!(cfg.is_trusted("HTTPS://A.Example"));
187 cfg.revoke_origin("a.example");
188 assert!(!cfg.is_trusted("a.example"));
189 }
190
191 #[test]
192 fn save_load_roundtrip_in_temp_dir() {
193 let dir = tempfile::tempdir().unwrap();
194 let path = dir.path().join("posprint").join("config.json");
195 let mut cfg = AppConfig::default();
196 cfg.default_page_width_mm = 58.0;
197 cfg.trust_origin("pos.example");
198 cfg.save_to_path(&path).unwrap();
199
200 let loaded = AppConfig::load_from_path(&path);
201 assert_eq!(loaded.default_page_width_mm, 58.0);
202 assert!(loaded.is_trusted("pos.example"));
203 }
204}