BlueGit

timfa posprint

Files

posprint / src / protocol_url.rs

protocol_url.rs

protocol_url.rs 10.6 KiB Download Raw
1//! `posprint://` URLs that embed a compressed `.pos` document (magnet-style).
2
3use std::fmt;
4use std::io::{Read, Write};
5
6use base64::engine::general_purpose::URL_SAFE_NO_PAD;
7use base64::Engine;
8use flate2::read::DeflateDecoder;
9use flate2::write::DeflateEncoder;
10use flate2::Compression;
11
12use crate::config::normalize_origin;
13use crate::io::PosFile;
14
15/// Soft warning threshold for cross-platform protocol handoff (~Windows cmdline limit).
16pub const WARN_URL_LEN: usize = 7000;
17
18#[derive(Debug)]
19pub enum ProtocolUrlError {
20 NotPosprintUrl,
21 UnsupportedVersion(String),
22 MissingPayload,
23 InvalidEncoding(String),
24 Base64(String),
25 Inflate(String),
26 Json(String),
27 UnsupportedPosVersion(u32),
28}
29
30impl fmt::Display for ProtocolUrlError {
31 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
32 match self {
33 Self::NotPosprintUrl => write!(f, "not a posprint:// URL"),
34 Self::UnsupportedVersion(v) => {
35 write!(f, "unsupported URL version '{v}' (expected 1)")
36 }
37 Self::MissingPayload => write!(f, "missing document payload (d=)"),
38 Self::InvalidEncoding(e) => write!(f, "invalid URL / percent-encoding: {e}"),
39 Self::Base64(e) => write!(f, "invalid base64 payload: {e}"),
40 Self::Inflate(e) => write!(f, "decompression failed: {e}"),
41 Self::Json(e) => write!(f, "invalid .pos JSON: {e}"),
42 Self::UnsupportedPosVersion(v) => write!(f, "unsupported .pos version {v}"),
43 }
44 }
45}
46
47impl std::error::Error for ProtocolUrlError {}
48
49impl From<serde_json::Error> for ProtocolUrlError {
50 fn from(value: serde_json::Error) -> Self {
51 Self::Json(value.to_string())
52 }
53}
54
55/// Decoded `posprint://` launch request.
56#[derive(Debug, Clone, PartialEq)]
57pub struct PosprintLaunch {
58 pub file: PosFile,
59 /// When true, print without waiting for the Print button (subject to domain trust).
60 pub noconfirm: bool,
61 /// Normalized hostname from `origin=` (required for first-time trust when noconfirm).
62 pub origin: Option<String>,
63}
64
65/// Optional extras when encoding a URL.
66#[derive(Debug, Clone, Default)]
67pub struct EncodeOptions {
68 pub noconfirm: bool,
69 pub origin: Option<String>,
70}
71
72/// True when `s` looks like a `posprint:` / `posprint://` protocol URL.
73pub fn is_posprint_url(s: &str) -> bool {
74 let s = s.trim();
75 let lower = s.to_ascii_lowercase();
76 lower.starts_with("posprint://") || lower.starts_with("posprint:")
77}
78
79/// Encode a `.pos` file as `posprint://print?v=1&d=…` (raw deflate + base64url, no padding).
80pub fn encode_posprint_url(file: &PosFile) -> Result<String, ProtocolUrlError> {
81 encode_posprint_url_with_options(file, &EncodeOptions::default())
82}
83
84/// Encode with optional `noconfirm` / `origin` query parameters.
85pub fn encode_posprint_url_with_options(
86 file: &PosFile,
87 options: &EncodeOptions,
88) -> Result<String, ProtocolUrlError> {
89 let json = serde_json::to_vec(file)?;
90 let mut encoder = DeflateEncoder::new(Vec::new(), Compression::best());
91 encoder
92 .write_all(&json)
93 .map_err(|e| ProtocolUrlError::Inflate(e.to_string()))?;
94 let compressed = encoder
95 .finish()
96 .map_err(|e| ProtocolUrlError::Inflate(e.to_string()))?;
97 let b64 = URL_SAFE_NO_PAD.encode(compressed);
98 let mut url = format!("posprint://print?v=1&d={b64}");
99 if options.noconfirm {
100 url.push_str("&noconfirm=1");
101 }
102 if let Some(raw) = options.origin.as_deref() {
103 if let Some(host) = normalize_origin(raw) {
104 url.push_str("&origin=");
105 url.push_str(&percent_encode_component(&host));
106 }
107 }
108 Ok(url)
109}
110
111/// Decode a `posprint://print?v=1&d=…` URL into a [`PosprintLaunch`].
112pub fn parse_posprint_url(url: &str) -> Result<PosprintLaunch, ProtocolUrlError> {
113 let url = url.trim();
114 if !is_posprint_url(url) {
115 return Err(ProtocolUrlError::NotPosprintUrl);
116 }
117
118 let after_scheme = url
119 .split_once(':')
120 .map(|(_, rest)| rest)
121 .ok_or(ProtocolUrlError::NotPosprintUrl)?;
122 let after_scheme = after_scheme.strip_prefix("//").unwrap_or(after_scheme);
123
124 let (path, query) = match after_scheme.split_once('?') {
125 Some((path, query)) => (path, query),
126 None => (after_scheme, ""),
127 };
128 let path = path.trim_matches('/');
129 if !path.is_empty() && !path.eq_ignore_ascii_case("print") {
130 return Err(ProtocolUrlError::InvalidEncoding(format!(
131 "unknown action '{path}' (expected print)"
132 )));
133 }
134
135 let mut version: Option<String> = None;
136 let mut payload: Option<String> = None;
137 let mut noconfirm = false;
138 let mut origin_raw: Option<String> = None;
139 for pair in query.split('&') {
140 if pair.is_empty() {
141 continue;
142 }
143 let (key, value) = pair.split_once('=').unwrap_or((pair, ""));
144 let key = percent_decode_str(key)?;
145 match key.as_str() {
146 "v" => version = Some(percent_decode_str(value)?),
147 "d" => payload = Some(percent_decode_str(value)?),
148 "noconfirm" => noconfirm = parse_bool_flag(value),
149 "origin" => origin_raw = Some(percent_decode_str(value)?),
150 _ => {}
151 }
152 }
153
154 match version.as_deref() {
155 None | Some("1") => {}
156 Some(other) => return Err(ProtocolUrlError::UnsupportedVersion(other.to_string())),
157 }
158
159 let payload = payload.ok_or(ProtocolUrlError::MissingPayload)?;
160 let compressed = URL_SAFE_NO_PAD
161 .decode(payload.trim())
162 .map_err(|e| ProtocolUrlError::Base64(e.to_string()))?;
163
164 let mut decoder = DeflateDecoder::new(compressed.as_slice());
165 let mut json = Vec::new();
166 decoder
167 .read_to_end(&mut json)
168 .map_err(|e| ProtocolUrlError::Inflate(e.to_string()))?;
169
170 let file: PosFile = serde_json::from_slice(&json)?;
171 if file.version != 1 {
172 return Err(ProtocolUrlError::UnsupportedPosVersion(file.version));
173 }
174
175 let origin = origin_raw.as_deref().and_then(normalize_origin);
176 Ok(PosprintLaunch {
177 file,
178 noconfirm,
179 origin,
180 })
181}
182
183fn parse_bool_flag(value: &str) -> bool {
184 let v = value.trim();
185 if v.is_empty() {
186 return true;
187 }
188 matches!(
189 v.to_ascii_lowercase().as_str(),
190 "1" | "true" | "yes" | "on"
191 )
192}
193
194fn percent_encode_component(input: &str) -> String {
195 let mut out = String::with_capacity(input.len());
196 for b in input.bytes() {
197 match b {
198 b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
199 out.push(b as char);
200 }
201 _ => out.push_str(&format!("%{b:02X}")),
202 }
203 }
204 out
205}
206
207fn percent_decode_str(input: &str) -> Result<String, ProtocolUrlError> {
208 let bytes = percent_decode_bytes(input.as_bytes())?;
209 String::from_utf8(bytes).map_err(|e| ProtocolUrlError::InvalidEncoding(e.to_string()))
210}
211
212fn percent_decode_bytes(input: &[u8]) -> Result<Vec<u8>, ProtocolUrlError> {
213 let mut out = Vec::with_capacity(input.len());
214 let mut i = 0;
215 while i < input.len() {
216 match input[i] {
217 b'+' => {
218 out.push(b' ');
219 i += 1;
220 }
221 b'%' if i + 2 < input.len() => {
222 let h = from_hex(input[i + 1])?;
223 let l = from_hex(input[i + 2])?;
224 out.push((h << 4) | l);
225 i += 3;
226 }
227 b'%' => {
228 return Err(ProtocolUrlError::InvalidEncoding(
229 "truncated percent-escape".into(),
230 ));
231 }
232 c => {
233 out.push(c);
234 i += 1;
235 }
236 }
237 }
238 Ok(out)
239}
240
241fn from_hex(b: u8) -> Result<u8, ProtocolUrlError> {
242 match b {
243 b'0'..=b'9' => Ok(b - b'0'),
244 b'a'..=b'f' => Ok(b - b'a' + 10),
245 b'A'..=b'F' => Ok(b - b'A' + 10),
246 _ => Err(ProtocolUrlError::InvalidEncoding(format!(
247 "invalid hex digit {}",
248 b as char
249 ))),
250 }
251}
252
253#[cfg(test)]
254mod tests {
255 use super::*;
256 use crate::io::PosMetadata;
257
258 fn sample_file() -> PosFile {
259 PosFile {
260 version: 1,
261 metadata: PosMetadata {
262 title: Some("Demo".into()),
263 page_width_mm: 53.0,
264 chars_per_line: Some(32),
265 codepage: Some("CP437".into()),
266 },
267 body: "@barcode RASTER CODE128 ${data}\nHello\n@cut\n".into(),
268 }
269 }
270
271 #[test]
272 fn round_trips_pos_file() {
273 let file = sample_file();
274 let url = encode_posprint_url(&file).unwrap();
275 assert!(url.starts_with("posprint://print?v=1&d="));
276 let decoded = parse_posprint_url(&url).unwrap();
277 assert_eq!(decoded.file, file);
278 assert!(!decoded.noconfirm);
279 assert!(decoded.origin.is_none());
280 }
281
282 #[test]
283 fn encodes_and_parses_noconfirm_and_origin() {
284 let file = sample_file();
285 let url = encode_posprint_url_with_options(
286 &file,
287 &EncodeOptions {
288 noconfirm: true,
289 origin: Some("https://Shop.Example.com/x".into()),
290 },
291 )
292 .unwrap();
293 assert!(url.contains("&noconfirm=1"));
294 assert!(url.contains("&origin=shop.example.com"));
295 let launch = parse_posprint_url(&url).unwrap();
296 assert!(launch.noconfirm);
297 assert_eq!(launch.origin.as_deref(), Some("shop.example.com"));
298 }
299
300 #[test]
301 fn parses_noconfirm_without_value() {
302 let file = sample_file();
303 let base = encode_posprint_url(&file).unwrap();
304 let url = format!("{base}&noconfirm&origin=pos.local");
305 let launch = parse_posprint_url(&url).unwrap();
306 assert!(launch.noconfirm);
307 assert_eq!(launch.origin.as_deref(), Some("pos.local"));
308 }
309
310 #[test]
311 fn rejects_bad_version() {
312 let err = parse_posprint_url("posprint://print?v=99&d=aa").unwrap_err();
313 assert!(matches!(err, ProtocolUrlError::UnsupportedVersion(_)));
314 }
315
316 #[test]
317 fn rejects_missing_payload() {
318 let err = parse_posprint_url("posprint://print?v=1").unwrap_err();
319 assert!(matches!(err, ProtocolUrlError::MissingPayload));
320 }
321
322 #[test]
323 fn detects_scheme() {
324 assert!(is_posprint_url("posprint://print?v=1&d=x"));
325 assert!(is_posprint_url("POSPRINT:print?v=1&d=x"));
326 assert!(!is_posprint_url("https://example.com"));
327 }
328}