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