BlueGit

timfa posprint

Verify noconfirm via referrer HTTP GET instead of spoofable origin.

Co-authored-by: Cursor <cursoragent@cursor.com>

timfa Tim Falken · pushed by timfa

Authored 2026-07-22 · 3 months ago

Hash
fa182b1ab5b0fb720a8c2104b05b6695550ca45b
Parent
30d96b9e
12 files changed +316 −113
docs/ARCHITECTURE.md +1 −1
@@ -33,7 +33,7 @@ src/
33 33 ├── raster.rs # Barcode / QR bitmaps
34 34 ├── image_load.rs # Local + http(s) @image loading
35 35 ├── protocol_url.rs # posprint:// encode/decode
36 ├── config.rs # Trusted origins + default page width
36 ├── referrer_verify.rs # noconfirm referrer GET (HTTP 200)
37 37 ├── editor_assist.rs # @ autocomplete, Insert snippets
38 38 ├── help_view.rs # Markdown help renderer
39 39 ├── io/mod.rs # PosFile, PosMetadata
@@ -33,7 +33,7 @@ src/
33├── raster.rs # Barcode / QR bitmaps
33├── raster.rs # Barcode / QR bitmaps
34├── image_load.rs # Local + http(s) @image loading
34├── image_load.rs # Local + http(s) @image loading
35├── protocol_url.rs # posprint:// encode/decode
35├── protocol_url.rs # posprint:// encode/decode
36├── config.rs # Trusted origins + default page width
36├── referrer_verify.rs # noconfirm referrer GET (HTTP 200)
37├── editor_assist.rs # @ autocomplete, Insert snippets
37├── editor_assist.rs # @ autocomplete, Insert snippets
38├── help_view.rs # Markdown help renderer
38├── help_view.rs # Markdown help renderer
39├── io/mod.rs # PosFile, PosMetadata
39├── io/mod.rs # PosFile, PosMetadata
docs/HELP.md +1 −1
@@ -309,7 +309,7 @@ Websites can open the print dialog with an embedded template:
309 309 posprint://print?v=1&d=…
310 310 ```
311 311
312 Add `&noconfirm=1&origin=shop.example.com` to print immediately after the user trusts that domain once (see **Settings → Trusted sites**). Encoding helpers live in [`lib/`](../lib/). Full guide: [POSPRINT-URL.md](POSPRINT-URL.md).
312 Add `&noconfirm=1&referrer=<percent-encoded verify URL>` to print after the site’s verify endpoint returns HTTP 200 and (on first use) the user trusts that domain (**Settings → Trusted sites**). Encoding helpers live in [`lib/`](../lib/). Full guide: [POSPRINT-URL.md](POSPRINT-URL.md).
313 313
314 314 `@image` may use `https://…` or `http://…` (downloaded when preview/print needs the image).
315 315
@@ -309,7 +309,7 @@ Websites can open the print dialog with an embedded template:
309posprint://print?v=1&d=…
309posprint://print?v=1&d=…
310```
310```
311
311
312Add `&noconfirm=1&origin=shop.example.com` to print immediately after the user trusts that domain once (see **Settings → Trusted sites**). Encoding helpers live in [`lib/`](../lib/). Full guide: [POSPRINT-URL.md](POSPRINT-URL.md).
312Add `&noconfirm=1&referrer=<percent-encoded verify URL>` to print after the site’s verify endpoint returns HTTP 200 and (on first use) the user trusts that domain (**Settings → Trusted sites**). Encoding helpers live in [`lib/`](../lib/). Full guide: [POSPRINT-URL.md](POSPRINT-URL.md).
313
313
314`@image` may use `https://…` or `http://…` (downloaded when preview/print needs the image).
314`@image` may use `https://…` or `http://…` (downloaded when preview/print needs the image).
315
315
docs/POSPRINT-URL.md +23 −13
@@ -15,7 +15,7 @@ posprint://print?v=1&d=<BASE64URL(raw_deflate(utf8(.pos JSON)))>
15 15 Optional auto-print:
16 16
17 17 ```
18 posprint://print?v=1&d=…&noconfirm=1&origin=shop.example.com
18 posprint://print?v=1&d=…&noconfirm=1&referrer=website.com%2Fbonnen%2Fverify%3Fcode%3D84923
19 19 ```
20 20
21 21 | Part | Meaning |
@@ -24,23 +24,33 @@ posprint://print?v=1&d=…&noconfirm=1&origin=shop.example.com
24 24 | `print` | Open the print-only dialog (same UX as `posprint --print`) |
25 25 | `v=1` | URL payload version |
26 26 | `d=` | Compressed `.pos` file (JSON with `version`, `metadata`, `body`) |
27 | `noconfirm=1` | Start printing immediately (after domain trust; see below) |
28 | `origin=` | Hostname of the calling site (required with `noconfirm`) |
27 | `noconfirm=1` | Start printing immediately after referrer verification (+ domain trust) |
28 | `referrer=` | **Percent-encoded** verification URL on the issuer’s domain (see below) |
29 29
30 30 **Template parameters are not in the URL.** With a normal link the user fills `${Name}` / `$[Name]` in the dialog. Prefer templates without unresolved parameters when using `noconfirm`.
31 31
32 32 **Images:** keep logos out of the URL. Use `@image https://…` (or `http://…`) in the template body; posprint downloads them when needed.
33 33
34 ### Auto-print (`noconfirm`) and trusted domains
34 ### Auto-print (`noconfirm`) and referrer verification
35 35
36 The OS protocol handler only receives the URL string — not the browser Referer. Callers that want silent print must pass **`origin=<hostname>`** (e.g. `shop.example.com` or `https://shop.example.com/checkout`).
36 The OS protocol handler only receives the URL string — not the browser Referer. A site that wants silent print must prove control of its domain:
37 37
38 | First visit from that origin | Later visits |
39 |------------------------------|--------------|
38 1. Embed `&noconfirm=1&referrer=<URL-encoded verification URL>`.
39 2. Example referrer value (before encoding): `website.com/bonnen/verify?code=84923`
40 (scheme optional → treated as `https://…`; or pass a full `https://…` URL).
41 3. posprint **GETs** that URL with **no redirects**.
42 4. **HTTP 200** → verification OK; trust host = hostname of the referrer URL (`website.com`).
43 5. **Any other status** (typically 4xx) → print refused.
44 6. Code format and how long it stays valid are **entirely up to the website**.
45
46 | First successful verify from that host | Later verified visits |
47 |----------------------------------------|------------------------|
40 48 | posprint shows **Trust this site?** | If trusted, prints without asking |
41 | **Trust and print** stores the hostname and continues | Revoke under **Settings → Trusted sites** |
49 | **Trust and print** stores the hostname | Revoke under **Settings → Trusted sites** |
50
51 Without `referrer`, `noconfirm=1` is rejected. Without `noconfirm`, behaviour is unchanged (interactive print dialog).
42 52
43 Without `origin`, `noconfirm=1` is rejected with an error. Without `noconfirm`, behaviour is unchanged (interactive print dialog).
53 Localhost / private IP verification URLs are blocked.
44 54
45 55 ---
46 56
@@ -87,10 +97,10 @@ $url = posprint_url([
87 97 'metadata' => ['page_width_mm' => 53, 'chars_per_line' => 32],
88 98 'body' => "@barcode RASTER CODE128 \${data}\nHello\n@cut\n",
89 99 ]);
90 // Auto-print (after the user trusts this site once):
100 // Auto-print: site must expose a verify URL that returns HTTP 200 for this code:
91 101 $auto = posprint_url($pos, [
92 102 'noconfirm' => true,
93 'origin' => 'https://shop.example.com',
103 'referrer' => 'https://shop.example.com/bonnen/verify?code=' . urlencode($code),
94 104 ]);
95 105 // <a href="<?= htmlspecialchars($url) ?>">Print</a>
96 106 ```
@@ -108,7 +118,7 @@ const url = posprintUrl({
108 118
109 119 const auto = posprintUrl(pos, {
110 120 noconfirm: true,
111 origin: location.hostname, // or 'shop.example.com'
121 referrer: `https://shop.example.com/bonnen/verify?code=${encodeURIComponent(code)}`,
112 122 });
113 123 ```
114 124
@@ -124,7 +134,7 @@ const auto = posprintUrl(pos, {
124 134 });
125 135 const auto = await posprintUrl(pos, {
126 136 noconfirm: true,
127 origin: location.origin,
137 referrer: `https://${location.host}/bonnen/verify?code=${encodeURIComponent(code)}`,
128 138 });
129 139 location.href = auto;
130 140 </script>
@@ -15,7 +15,7 @@ posprint://print?v=1&d=<BASE64URL(raw_deflate(utf8(.pos JSON)))>
15Optional auto-print:
15Optional auto-print:
16
16
17```
17```
18posprint://print?v=1&d=…&noconfirm=1&origin=shop.example.com
18posprint://print?v=1&d=…&noconfirm=1&referrer=website.com%2Fbonnen%2Fverify%3Fcode%3D84923
19```
19```
20
20
21| Part | Meaning |
21| Part | Meaning |
@@ -24,23 +24,33 @@ posprint://print?v=1&d=…&noconfirm=1&origin=shop.example.com
24| `print` | Open the print-only dialog (same UX as `posprint --print`) |
24| `print` | Open the print-only dialog (same UX as `posprint --print`) |
25| `v=1` | URL payload version |
25| `v=1` | URL payload version |
26| `d=` | Compressed `.pos` file (JSON with `version`, `metadata`, `body`) |
26| `d=` | Compressed `.pos` file (JSON with `version`, `metadata`, `body`) |
27| `noconfirm=1` | Start printing immediately (after domain trust; see below) |
27| `noconfirm=1` | Start printing immediately after referrer verification (+ domain trust) |
28| `origin=` | Hostname of the calling site (required with `noconfirm`) |
28| `referrer=` | **Percent-encoded** verification URL on the issuer’s domain (see below) |
29
29
30**Template parameters are not in the URL.** With a normal link the user fills `${Name}` / `$[Name]` in the dialog. Prefer templates without unresolved parameters when using `noconfirm`.
30**Template parameters are not in the URL.** With a normal link the user fills `${Name}` / `$[Name]` in the dialog. Prefer templates without unresolved parameters when using `noconfirm`.
31
31
32**Images:** keep logos out of the URL. Use `@image https://…` (or `http://…`) in the template body; posprint downloads them when needed.
32**Images:** keep logos out of the URL. Use `@image https://…` (or `http://…`) in the template body; posprint downloads them when needed.
33
33
34### Auto-print (`noconfirm`) and trusted domains
34### Auto-print (`noconfirm`) and referrer verification
35
35
36The OS protocol handler only receives the URL string — not the browser Referer. Callers that want silent print must pass **`origin=<hostname>`** (e.g. `shop.example.com` or `https://shop.example.com/checkout`).
36The OS protocol handler only receives the URL string — not the browser Referer. A site that wants silent print must prove control of its domain:
37
37
38| First visit from that origin | Later visits |
381. Embed `&noconfirm=1&referrer=<URL-encoded verification URL>`.
39|------------------------------|--------------|
392. Example referrer value (before encoding): `website.com/bonnen/verify?code=84923`
40 (scheme optional → treated as `https://…`; or pass a full `https://…` URL).
413. posprint **GETs** that URL with **no redirects**.
424. **HTTP 200** → verification OK; trust host = hostname of the referrer URL (`website.com`).
435. **Any other status** (typically 4xx) → print refused.
446. Code format and how long it stays valid are **entirely up to the website**.
45
46| First successful verify from that host | Later verified visits |
47|----------------------------------------|------------------------|
40| posprint shows **Trust this site?** | If trusted, prints without asking |
48| posprint shows **Trust this site?** | If trusted, prints without asking |
41| **Trust and print** stores the hostname and continues | Revoke under **Settings → Trusted sites** |
49| **Trust and print** stores the hostname | Revoke under **Settings → Trusted sites** |
50
51Without `referrer`, `noconfirm=1` is rejected. Without `noconfirm`, behaviour is unchanged (interactive print dialog).
42
52
43Without `origin`, `noconfirm=1` is rejected with an error. Without `noconfirm`, behaviour is unchanged (interactive print dialog).
53Localhost / private IP verification URLs are blocked.
44
54
45---
55---
46
56
@@ -87,10 +97,10 @@ $url = posprint_url([
87 'metadata' => ['page_width_mm' => 53, 'chars_per_line' => 32],
97 'metadata' => ['page_width_mm' => 53, 'chars_per_line' => 32],
88 'body' => "@barcode RASTER CODE128 \${data}\nHello\n@cut\n",
98 'body' => "@barcode RASTER CODE128 \${data}\nHello\n@cut\n",
89]);
99]);
90// Auto-print (after the user trusts this site once):
100// Auto-print: site must expose a verify URL that returns HTTP 200 for this code:
91$auto = posprint_url($pos, [
101$auto = posprint_url($pos, [
92 'noconfirm' => true,
102 'noconfirm' => true,
93 'origin' => 'https://shop.example.com',
103 'referrer' => 'https://shop.example.com/bonnen/verify?code=' . urlencode($code),
94]);
104]);
95// <a href="<?= htmlspecialchars($url) ?>">Print</a>
105// <a href="<?= htmlspecialchars($url) ?>">Print</a>
96```
106```
@@ -108,7 +118,7 @@ const url = posprintUrl({
108
118
109const auto = posprintUrl(pos, {
119const auto = posprintUrl(pos, {
110 noconfirm: true,
120 noconfirm: true,
111 origin: location.hostname, // or 'shop.example.com'
121 referrer: `https://shop.example.com/bonnen/verify?code=${encodeURIComponent(code)}`,
112});
122});
113```
123```
114
124
@@ -124,7 +134,7 @@ const auto = posprintUrl(pos, {
124 });
134 });
125 const auto = await posprintUrl(pos, {
135 const auto = await posprintUrl(pos, {
126 noconfirm: true,
136 noconfirm: true,
127 origin: location.origin,
137 referrer: `https://${location.host}/bonnen/verify?code=${encodeURIComponent(code)}`,
128 });
138 });
129 location.href = auto;
139 location.href = auto;
130</script>
140</script>
lib/browser/examples.md +5 −2
@@ -31,8 +31,11 @@ Build the document in JavaScript and open the link:
31 31 },
32 32 body: '@barcode RASTER CODE128 ${data}\nHello\n@cut\n',
33 33 });
34 // Silent print after the user trusts this origin once:
35 // const url = await posprintUrl(pos, { noconfirm: true, origin: location.hostname });
34 // Silent print after verify URL returns 200 (and domain trust):
35 // const url = await posprintUrl(pos, {
36 // noconfirm: true,
37 // referrer: `https://${location.host}/api/posprint/verify?code=${code}`,
38 // });
36 39 window.location.href = url;
37 40 });
38 41 </script>
@@ -31,8 +31,11 @@ Build the document in JavaScript and open the link:
31 },
31 },
32 body: '@barcode RASTER CODE128 ${data}\nHello\n@cut\n',
32 body: '@barcode RASTER CODE128 ${data}\nHello\n@cut\n',
33 });
33 });
34 // Silent print after the user trusts this origin once:
34 // Silent print after verify URL returns 200 (and domain trust):
35 // const url = await posprintUrl(pos, { noconfirm: true, origin: location.hostname });
35 // const url = await posprintUrl(pos, {
36 // noconfirm: true,
37 // referrer: `https://${location.host}/api/posprint/verify?code=${code}`,
38 // });
36 window.location.href = url;
39 window.location.href = url;
37 });
40 });
38</script>
41</script>
lib/browser/posprint_url.js +5 −18
@@ -5,7 +5,7 @@
5 5 * Requires CompressionStream('deflate-raw') (modern browsers).
6 6 *
7 7 * @param {object|string} pos
8 * @param {{ noconfirm?: boolean, origin?: string }} [options]
8 * @param {{ noconfirm?: boolean, referrer?: string }} [options]
9 9 * @returns {Promise<string>}
10 10 */
11 11 export async function posprintUrl(pos, options = {}) {
@@ -21,28 +21,15 @@ export async function posprintUrl(pos, options = {}) {
21 21 if (options.noconfirm) {
22 22 url += '&noconfirm=1';
23 23 }
24 if (options.origin) {
25 const host = normalizeOrigin(options.origin);
26 if (host) {
27 url += `&origin=${encodeURIComponent(host)}`;
24 if (options.referrer) {
25 const ref = String(options.referrer).trim();
26 if (ref) {
27 url += `&referrer=${encodeURIComponent(ref)}`;
28 28 }
29 29 }
30 30 return url;
31 31 }
32 32
33 function normalizeOrigin(raw) {
34 const s = String(raw).trim();
35 if (!s) return null;
36 try {
37 if (/^https?:\/\//i.test(s)) {
38 return new URL(s).hostname.toLowerCase();
39 }
40 } catch (_) {
41 /* fall through */
42 }
43 return s.split('/')[0].split(':')[0].toLowerCase() || null;
44 }
45
46 33 function bytesToBase64Url(bytes) {
47 34 let binary = '';
48 35 for (let i = 0; i < bytes.length; i++) {
@@ -5,7 +5,7 @@
5 * Requires CompressionStream('deflate-raw') (modern browsers).
5 * Requires CompressionStream('deflate-raw') (modern browsers).
6 *
6 *
7 * @param {object|string} pos
7 * @param {object|string} pos
8 * @param {{ noconfirm?: boolean, origin?: string }} [options]
8 * @param {{ noconfirm?: boolean, referrer?: string }} [options]
9 * @returns {Promise<string>}
9 * @returns {Promise<string>}
10 */
10 */
11export async function posprintUrl(pos, options = {}) {
11export async function posprintUrl(pos, options = {}) {
@@ -21,28 +21,15 @@ export async function posprintUrl(pos, options = {}) {
21 if (options.noconfirm) {
21 if (options.noconfirm) {
22 url += '&noconfirm=1';
22 url += '&noconfirm=1';
23 }
23 }
24 if (options.origin) {
24 if (options.referrer) {
25 const host = normalizeOrigin(options.origin);
25 const ref = String(options.referrer).trim();
26 if (host) {
26 if (ref) {
27 url += `&origin=${encodeURIComponent(host)}`;
27 url += `&referrer=${encodeURIComponent(ref)}`;
28 }
28 }
29 }
29 }
30 return url;
30 return url;
31}
31}
32
32
33function normalizeOrigin(raw) {
34 const s = String(raw).trim();
35 if (!s) return null;
36 try {
37 if (/^https?:\/\//i.test(s)) {
38 return new URL(s).hostname.toLowerCase();
39 }
40 } catch (_) {
41 /* fall through */
42 }
43 return s.split('/')[0].split(':')[0].toLowerCase() || null;
44}
45
46function bytesToBase64Url(bytes) {
33function bytesToBase64Url(bytes) {
47 let binary = '';
34 let binary = '';
48 for (let i = 0; i < bytes.length; i++) {
35 for (let i = 0; i < bytes.length; i++) {
lib/node/posprint_url.js +5 −18
@@ -8,7 +8,7 @@ const zlib = require('zlib');
8 8 * Encoding: UTF-8 JSON → raw deflate → base64url (no padding).
9 9 *
10 10 * @param {object|string} pos
11 * @param {{ noconfirm?: boolean, origin?: string }} [options]
11 * @param {{ noconfirm?: boolean, referrer?: string }} [options]
12 12 * @returns {string}
13 13 */
14 14 function posprintUrl(pos, options = {}) {
@@ -19,26 +19,13 @@ function posprintUrl(pos, options = {}) {
19 19 if (options.noconfirm) {
20 20 url += '&noconfirm=1';
21 21 }
22 if (options.origin) {
23 const host = normalizeOrigin(options.origin);
24 if (host) {
25 url += `&origin=${encodeURIComponent(host)}`;
22 if (options.referrer) {
23 const ref = String(options.referrer).trim();
24 if (ref) {
25 url += `&referrer=${encodeURIComponent(ref)}`;
26 26 }
27 27 }
28 28 return url;
29 29 }
30 30
31 function normalizeOrigin(raw) {
32 const s = String(raw).trim();
33 if (!s) return null;
34 try {
35 if (/^https?:\/\//i.test(s)) {
36 return new URL(s).hostname.toLowerCase();
37 }
38 } catch (_) {
39 /* fall through */
40 }
41 return s.split('/')[0].split(':')[0].toLowerCase() || null;
42 }
43
44 31 module.exports = { posprintUrl };
@@ -8,7 +8,7 @@ const zlib = require('zlib');
8 * Encoding: UTF-8 JSON → raw deflate → base64url (no padding).
8 * Encoding: UTF-8 JSON → raw deflate → base64url (no padding).
9 *
9 *
10 * @param {object|string} pos
10 * @param {object|string} pos
11 * @param {{ noconfirm?: boolean, origin?: string }} [options]
11 * @param {{ noconfirm?: boolean, referrer?: string }} [options]
12 * @returns {string}
12 * @returns {string}
13 */
13 */
14function posprintUrl(pos, options = {}) {
14function posprintUrl(pos, options = {}) {
@@ -19,26 +19,13 @@ function posprintUrl(pos, options = {}) {
19 if (options.noconfirm) {
19 if (options.noconfirm) {
20 url += '&noconfirm=1';
20 url += '&noconfirm=1';
21 }
21 }
22 if (options.origin) {
22 if (options.referrer) {
23 const host = normalizeOrigin(options.origin);
23 const ref = String(options.referrer).trim();
24 if (host) {
24 if (ref) {
25 url += `&origin=${encodeURIComponent(host)}`;
25 url += `&referrer=${encodeURIComponent(ref)}`;
26 }
26 }
27 }
27 }
28 return url;
28 return url;
29}
29}
30
30
31function normalizeOrigin(raw) {
32 const s = String(raw).trim();
33 if (!s) return null;
34 try {
35 if (/^https?:\/\//i.test(s)) {
36 return new URL(s).hostname.toLowerCase();
37 }
38 } catch (_) {
39 /* fall through */
40 }
41 return s.split('/')[0].split(':')[0].toLowerCase() || null;
42}
43
44module.exports = { posprintUrl };
31module.exports = { posprintUrl };
lib/php/posprint_url.php +5 −24
@@ -5,7 +5,7 @@
5 5 * Encoding: UTF-8 JSON → raw deflate (gzdeflate) → base64url (no padding).
6 6 *
7 7 * @param array|string $pos PosFile as associative array or JSON string
8 * @param array{noconfirm?: bool, origin?: string} $options Optional URL flags
8 * @param array{noconfirm?: bool, referrer?: string} $options Optional URL flags
9 9 * @return string posprint://print?v=1&d=…
10 10 * @throws InvalidArgumentException
11 11 */
@@ -33,31 +33,12 @@ function posprint_url($pos, array $options = []): string
33 33 if (!empty($options['noconfirm'])) {
34 34 $url .= '&noconfirm=1';
35 35 }
36 if (!empty($options['origin'])) {
37 $host = posprint_normalize_origin((string) $options['origin']);
38 if ($host !== null) {
39 $url .= '&origin=' . rawurlencode($host);
36 if (!empty($options['referrer'])) {
37 $ref = trim((string) $options['referrer']);
38 if ($ref !== '') {
39 $url .= '&referrer=' . rawurlencode($ref);
40 40 }
41 41 }
42 42
43 43 return $url;
44 44 }
45
46 /**
47 * @return string|null lowercase hostname
48 */
49 function posprint_normalize_origin(string $raw): ?string
50 {
51 $s = trim($raw);
52 if ($s === '') {
53 return null;
54 }
55 if (preg_match('#^https?://#i', $s) === 1) {
56 $host = parse_url($s, PHP_URL_HOST);
57 return is_string($host) && $host !== '' ? strtolower($host) : null;
58 }
59 $host = explode('/', $s, 2)[0];
60 $host = explode(':', $host, 2)[0];
61 $host = trim($host);
62 return $host !== '' ? strtolower($host) : null;
63 }
@@ -5,7 +5,7 @@
5 * Encoding: UTF-8 JSON → raw deflate (gzdeflate) → base64url (no padding).
5 * Encoding: UTF-8 JSON → raw deflate (gzdeflate) → base64url (no padding).
6 *
6 *
7 * @param array|string $pos PosFile as associative array or JSON string
7 * @param array|string $pos PosFile as associative array or JSON string
8 * @param array{noconfirm?: bool, origin?: string} $options Optional URL flags
8 * @param array{noconfirm?: bool, referrer?: string} $options Optional URL flags
9 * @return string posprint://print?v=1&d=…
9 * @return string posprint://print?v=1&d=…
10 * @throws InvalidArgumentException
10 * @throws InvalidArgumentException
11 */
11 */
@@ -33,31 +33,12 @@ function posprint_url($pos, array $options = []): string
33 if (!empty($options['noconfirm'])) {
33 if (!empty($options['noconfirm'])) {
34 $url .= '&noconfirm=1';
34 $url .= '&noconfirm=1';
35 }
35 }
36 if (!empty($options['origin'])) {
36 if (!empty($options['referrer'])) {
37 $host = posprint_normalize_origin((string) $options['origin']);
37 $ref = trim((string) $options['referrer']);
38 if ($host !== null) {
38 if ($ref !== '') {
39 $url .= '&origin=' . rawurlencode($host);
39 $url .= '&referrer=' . rawurlencode($ref);
40 }
40 }
41 }
41 }
42
42
43 return $url;
43 return $url;
44}
44}
45
46/**
47 * @return string|null lowercase hostname
48 */
49function posprint_normalize_origin(string $raw): ?string
50{
51 $s = trim($raw);
52 if ($s === '') {
53 return null;
54 }
55 if (preg_match('#^https?://#i', $s) === 1) {
56 $host = parse_url($s, PHP_URL_HOST);
57 return is_string($host) && $host !== '' ? strtolower($host) : null;
58 }
59 $host = explode('/', $s, 2)[0];
60 $host = explode(':', $host, 2)[0];
61 $host = trim($host);
62 return $host !== '' ? strtolower($host) : null;
63}
src/app.rs +1 −1
@@ -135,7 +135,7 @@ impl PosPrintApp {
135 135 ui.add_space(16.0);
136 136 ui.heading("Trusted sites (noconfirm)");
137 137 ui.label(
138 "Sites listed here may use posprint://…&noconfirm=1&origin=… without asking again.",
138 "Sites listed here may use posprint://…&noconfirm=1&referrer=… after their verify URL returns HTTP 200.",
139 139 );
140 140
141 141 if self.config.trusted_origins.is_empty() {
@@ -135,7 +135,7 @@ impl PosPrintApp {
135 ui.add_space(16.0);
135 ui.add_space(16.0);
136 ui.heading("Trusted sites (noconfirm)");
136 ui.heading("Trusted sites (noconfirm)");
137 ui.label(
137 ui.label(
138 "Sites listed here may use posprint://…&noconfirm=1&origin=… without asking again.",
138 "Sites listed here may use posprint://…&noconfirm=1&referrer=… after their verify URL returns HTTP 200.",
139 );
139 );
140
140
141 if self.config.trusted_origins.is_empty() {
141 if self.config.trusted_origins.is_empty() {
src/lib.rs +1 −0
@@ -13,6 +13,7 @@ pub mod preview;
13 13 pub mod print;
14 14 pub mod protocol_url;
15 15 pub mod raster;
16 pub mod referrer_verify;
16 17 pub mod text_wrap;
17 18 pub mod undo;
18 19
@@ -13,6 +13,7 @@ pub mod preview;
13pub mod print;
13pub mod print;
14pub mod protocol_url;
14pub mod protocol_url;
15pub mod raster;
15pub mod raster;
16pub mod referrer_verify;
16pub mod text_wrap;
17pub mod text_wrap;
17pub mod undo;
18pub mod undo;
18
19
src/print_only_app.rs +68 −14
@@ -1,12 +1,14 @@
1 1 //! Print dialog + live preview, then exit.
2 2
3 3 use std::path::PathBuf;
4 use std::sync::mpsc::{self, Receiver, TryRecvError};
4 5
5 6 use eframe::egui;
6 7
7 8 use posprint::config::AppConfig;
8 9 use posprint::io::{PosFile, PosMetadata};
9 10 use posprint::protocol_url::PosprintLaunch;
11 use posprint::referrer_verify;
10 12
11 13 use crate::preview_panel::show_preview_panel;
12 14 use crate::print_dialog::{PrintDialog, PrintDialogAction, PrintExecuteResult};
@@ -26,6 +28,9 @@ pub struct PrintOnlyApp {
26 28 /// Pending first-time trust confirmation for this hostname.
27 29 pending_trust: Option<String>,
28 30 auto_print_attempted: bool,
31 /// Background GET of `referrer=` for noconfirm.
32 referrer_rx: Option<Receiver<Result<String, String>>>,
33 verifying_referrer: bool,
29 34 }
30 35
31 36 impl PrintOnlyApp {
@@ -70,20 +75,15 @@ impl PrintOnlyApp {
70 75 return app;
71 76 }
72 77
73 match launch.origin.as_deref() {
78 match launch.referrer {
74 79 None => {
75 80 app.fatal_error = Some(
76 "noconfirm=1 requires origin=<hostname> so posprint can ask whether to trust that site."
81 "noconfirm=1 requires referrer=<https://host/path?…> so posprint can verify the print with that site."
77 82 .into(),
78 83 );
79 84 }
80 Some(origin) => {
81 let cfg = AppConfig::load();
82 if cfg.is_trusted(origin) {
83 app.auto_print = true;
84 } else {
85 app.pending_trust = Some(origin.to_string());
86 }
85 Some(referrer) => {
86 app.start_referrer_verification(referrer);
87 87 }
88 88 }
89 89 app
@@ -109,6 +109,47 @@ impl PrintOnlyApp {
109 109 auto_print: false,
110 110 pending_trust: None,
111 111 auto_print_attempted: false,
112 referrer_rx: None,
113 verifying_referrer: false,
114 }
115 }
116
117 fn start_referrer_verification(&mut self, referrer: String) {
118 self.verifying_referrer = true;
119 let (tx, rx) = mpsc::channel();
120 self.referrer_rx = Some(rx);
121 std::thread::spawn(move || {
122 let result = referrer_verify::verify_referrer(&referrer).map_err(|e| e.to_string());
123 let _ = tx.send(result);
124 });
125 }
126
127 fn poll_referrer_verification(&mut self, ctx: &egui::Context) {
128 let Some(rx) = &self.referrer_rx else {
129 return;
130 };
131 match rx.try_recv() {
132 Ok(Ok(host)) => {
133 self.referrer_rx = None;
134 self.verifying_referrer = false;
135 let cfg = AppConfig::load();
136 if cfg.is_trusted(&host) {
137 self.auto_print = true;
138 } else {
139 self.pending_trust = Some(host);
140 }
141 }
142 Ok(Err(e)) => {
143 self.referrer_rx = None;
144 self.verifying_referrer = false;
145 self.fatal_error = Some(e);
146 }
147 Err(TryRecvError::Empty) => ctx.request_repaint(),
148 Err(TryRecvError::Disconnected) => {
149 self.referrer_rx = None;
150 self.verifying_referrer = false;
151 self.fatal_error = Some("referrer verification interrupted".into());
152 }
112 153 }
113 154 }
114 155
@@ -145,7 +186,6 @@ impl PrintOnlyApp {
145 186 {
146 187 self.request_exit();
147 188 }
148 // On failure, keep the dialog open so the user can fix params/printer.
149 189 }
150 190 }
151 191
@@ -157,17 +197,33 @@ impl eframe::App for PrintOnlyApp {
157 197 }
158 198
159 199 self.dialog.poll_printer_discovery(ctx);
200 self.poll_referrer_verification(ctx);
160 201 ctx.send_viewport_cmd(egui::ViewportCommand::Title(self.title()));
161 202
203 if self.verifying_referrer {
204 egui::CentralPanel::default().show(ctx, |ui| {
205 ui.heading("Verifying print request…");
206 ui.separator();
207 ui.horizontal(|ui| {
208 ui.spinner();
209 ui.label("Checking referrer URL with the issuing website.");
210 });
211 if ui.button("Cancel").clicked() {
212 self.request_exit();
213 }
214 });
215 return;
216 }
217
162 218 if let Some(origin) = self.pending_trust.clone() {
163 219 egui::CentralPanel::default().show(ctx, |ui| {
164 220 ui.heading("Trust this site?");
165 221 ui.separator();
166 222 ui.label(format!(
167 "A page from “{origin}” wants to print without confirmation (noconfirm)."
223 "“{origin}” verified this print request and wants to print without confirmation (noconfirm)."
168 224 ));
169 225 ui.label(
170 "If you trust this site, posprint will allow future noconfirm prints from this domain without asking again.",
226 "If you trust this site, future verified noconfirm prints from this domain will not ask again.",
171 227 );
172 228 ui.add_space(12.0);
173 229 ui.horizontal(|ui| {
@@ -210,7 +266,6 @@ impl eframe::App for PrintOnlyApp {
210 266
211 267 egui::CentralPanel::default().show(ctx, |ui| {
212 268 let available = ui.available_size();
213 // Preview left (~55%), print controls right.
214 269 let preview_width = (available.x * 0.55).clamp(280.0, available.x - 320.0);
215 270
216 271 ui.horizontal(|ui| {
@@ -256,7 +311,6 @@ impl eframe::App for PrintOnlyApp {
256 311 egui::vec2(ui.available_width(), available.y),
257 312 egui::Layout::top_down(egui::Align::Min),
258 313 |ui| {
259 // No outer ScrollArea: nested scroll steals wheel events from the printer list.
260 314 action = self.dialog.show_ui(ui);
261 315 },
262 316 );
@@ -1,12 +1,14 @@
1//! Print dialog + live preview, then exit.
1//! Print dialog + live preview, then exit.
2
2
3use std::path::PathBuf;
3use std::path::PathBuf;
4use std::sync::mpsc::{self, Receiver, TryRecvError};
4
5
5use eframe::egui;
6use eframe::egui;
6
7
7use posprint::config::AppConfig;
8use posprint::config::AppConfig;
8use posprint::io::{PosFile, PosMetadata};
9use posprint::io::{PosFile, PosMetadata};
9use posprint::protocol_url::PosprintLaunch;
10use posprint::protocol_url::PosprintLaunch;
11use posprint::referrer_verify;
10
12
11use crate::preview_panel::show_preview_panel;
13use crate::preview_panel::show_preview_panel;
12use crate::print_dialog::{PrintDialog, PrintDialogAction, PrintExecuteResult};
14use crate::print_dialog::{PrintDialog, PrintDialogAction, PrintExecuteResult};
@@ -26,6 +28,9 @@ pub struct PrintOnlyApp {
26 /// Pending first-time trust confirmation for this hostname.
28 /// Pending first-time trust confirmation for this hostname.
27 pending_trust: Option<String>,
29 pending_trust: Option<String>,
28 auto_print_attempted: bool,
30 auto_print_attempted: bool,
31 /// Background GET of `referrer=` for noconfirm.
32 referrer_rx: Option<Receiver<Result<String, String>>>,
33 verifying_referrer: bool,
29}
34}
30
35
31impl PrintOnlyApp {
36impl PrintOnlyApp {
@@ -70,20 +75,15 @@ impl PrintOnlyApp {
70 return app;
75 return app;
71 }
76 }
72
77
73 match launch.origin.as_deref() {
78 match launch.referrer {
74 None => {
79 None => {
75 app.fatal_error = Some(
80 app.fatal_error = Some(
76 "noconfirm=1 requires origin=<hostname> so posprint can ask whether to trust that site."
81 "noconfirm=1 requires referrer=<https://host/path?…> so posprint can verify the print with that site."
77 .into(),
82 .into(),
78 );
83 );
79 }
84 }
80 Some(origin) => {
85 Some(referrer) => {
81 let cfg = AppConfig::load();
86 app.start_referrer_verification(referrer);
82 if cfg.is_trusted(origin) {
83 app.auto_print = true;
84 } else {
85 app.pending_trust = Some(origin.to_string());
86 }
87 }
87 }
88 }
88 }
89 app
89 app
@@ -109,6 +109,47 @@ impl PrintOnlyApp {
109 auto_print: false,
109 auto_print: false,
110 pending_trust: None,
110 pending_trust: None,
111 auto_print_attempted: false,
111 auto_print_attempted: false,
112 referrer_rx: None,
113 verifying_referrer: false,
114 }
115 }
116
117 fn start_referrer_verification(&mut self, referrer: String) {
118 self.verifying_referrer = true;
119 let (tx, rx) = mpsc::channel();
120 self.referrer_rx = Some(rx);
121 std::thread::spawn(move || {
122 let result = referrer_verify::verify_referrer(&referrer).map_err(|e| e.to_string());
123 let _ = tx.send(result);
124 });
125 }
126
127 fn poll_referrer_verification(&mut self, ctx: &egui::Context) {
128 let Some(rx) = &self.referrer_rx else {
129 return;
130 };
131 match rx.try_recv() {
132 Ok(Ok(host)) => {
133 self.referrer_rx = None;
134 self.verifying_referrer = false;
135 let cfg = AppConfig::load();
136 if cfg.is_trusted(&host) {
137 self.auto_print = true;
138 } else {
139 self.pending_trust = Some(host);
140 }
141 }
142 Ok(Err(e)) => {
143 self.referrer_rx = None;
144 self.verifying_referrer = false;
145 self.fatal_error = Some(e);
146 }
147 Err(TryRecvError::Empty) => ctx.request_repaint(),
148 Err(TryRecvError::Disconnected) => {
149 self.referrer_rx = None;
150 self.verifying_referrer = false;
151 self.fatal_error = Some("referrer verification interrupted".into());
152 }
112 }
153 }
113 }
154 }
114
155
@@ -145,7 +186,6 @@ impl PrintOnlyApp {
145 {
186 {
146 self.request_exit();
187 self.request_exit();
147 }
188 }
148 // On failure, keep the dialog open so the user can fix params/printer.
149 }
189 }
150}
190}
151
191
@@ -157,17 +197,33 @@ impl eframe::App for PrintOnlyApp {
157 }
197 }
158
198
159 self.dialog.poll_printer_discovery(ctx);
199 self.dialog.poll_printer_discovery(ctx);
200 self.poll_referrer_verification(ctx);
160 ctx.send_viewport_cmd(egui::ViewportCommand::Title(self.title()));
201 ctx.send_viewport_cmd(egui::ViewportCommand::Title(self.title()));
161
202
203 if self.verifying_referrer {
204 egui::CentralPanel::default().show(ctx, |ui| {
205 ui.heading("Verifying print request…");
206 ui.separator();
207 ui.horizontal(|ui| {
208 ui.spinner();
209 ui.label("Checking referrer URL with the issuing website.");
210 });
211 if ui.button("Cancel").clicked() {
212 self.request_exit();
213 }
214 });
215 return;
216 }
217
162 if let Some(origin) = self.pending_trust.clone() {
218 if let Some(origin) = self.pending_trust.clone() {
163 egui::CentralPanel::default().show(ctx, |ui| {
219 egui::CentralPanel::default().show(ctx, |ui| {
164 ui.heading("Trust this site?");
220 ui.heading("Trust this site?");
165 ui.separator();
221 ui.separator();
166 ui.label(format!(
222 ui.label(format!(
167 "A page from “{origin}” wants to print without confirmation (noconfirm)."
223 "“{origin}” verified this print request and wants to print without confirmation (noconfirm)."
168 ));
224 ));
169 ui.label(
225 ui.label(
170 "If you trust this site, posprint will allow future noconfirm prints from this domain without asking again.",
226 "If you trust this site, future verified noconfirm prints from this domain will not ask again.",
171 );
227 );
172 ui.add_space(12.0);
228 ui.add_space(12.0);
173 ui.horizontal(|ui| {
229 ui.horizontal(|ui| {
@@ -210,7 +266,6 @@ impl eframe::App for PrintOnlyApp {
210
266
211 egui::CentralPanel::default().show(ctx, |ui| {
267 egui::CentralPanel::default().show(ctx, |ui| {
212 let available = ui.available_size();
268 let available = ui.available_size();
213 // Preview left (~55%), print controls right.
214 let preview_width = (available.x * 0.55).clamp(280.0, available.x - 320.0);
269 let preview_width = (available.x * 0.55).clamp(280.0, available.x - 320.0);
215
270
216 ui.horizontal(|ui| {
271 ui.horizontal(|ui| {
@@ -256,7 +311,6 @@ impl eframe::App for PrintOnlyApp {
256 egui::vec2(ui.available_width(), available.y),
311 egui::vec2(ui.available_width(), available.y),
257 egui::Layout::top_down(egui::Align::Min),
312 egui::Layout::top_down(egui::Align::Min),
258 |ui| {
313 |ui| {
259 // No outer ScrollArea: nested scroll steals wheel events from the printer list.
260 action = self.dialog.show_ui(ui);
314 action = self.dialog.show_ui(ui);
261 },
315 },
262 );
316 );
src/protocol_url.rs +30 −21
@@ -9,7 +9,6 @@ use flate2::read::DeflateDecoder;
9 9 use flate2::write::DeflateEncoder;
10 10 use flate2::Compression;
11 11
12 use crate::config::normalize_origin;
13 12 use crate::io::PosFile;
14 13
15 14 /// Soft warning threshold for cross-platform protocol handoff (~Windows cmdline limit).
@@ -56,17 +55,18 @@ impl From<serde_json::Error> for ProtocolUrlError {
56 55 #[derive(Debug, Clone, PartialEq)]
57 56 pub struct PosprintLaunch {
58 57 pub file: PosFile,
59 /// When true, print without waiting for the Print button (subject to domain trust).
58 /// When true, print without waiting for the Print button (subject to referrer verify + trust).
60 59 pub noconfirm: bool,
61 /// Normalized hostname from `origin=` (required for first-time trust when noconfirm).
62 pub origin: Option<String>,
60 /// Verification URL from `referrer=` (percent-decoded; may be scheme-less).
61 pub referrer: Option<String>,
63 62 }
64 63
65 64 /// Optional extras when encoding a URL.
66 65 #[derive(Debug, Clone, Default)]
67 66 pub struct EncodeOptions {
68 67 pub noconfirm: bool,
69 pub origin: Option<String>,
68 /// Full verification URL or `host/path?query` (stored percent-encoded in the posprint URL).
69 pub referrer: Option<String>,
70 70 }
71 71
72 72 /// True when `s` looks like a `posprint:` / `posprint://` protocol URL.
@@ -81,7 +81,7 @@ pub fn encode_posprint_url(file: &PosFile) -> Result<String, ProtocolUrlError> {
81 81 encode_posprint_url_with_options(file, &EncodeOptions::default())
82 82 }
83 83
84 /// Encode with optional `noconfirm` / `origin` query parameters.
84 /// Encode with optional `noconfirm` / `referrer` query parameters.
85 85 pub fn encode_posprint_url_with_options(
86 86 file: &PosFile,
87 87 options: &EncodeOptions,
@@ -99,10 +99,11 @@ pub fn encode_posprint_url_with_options(
99 99 if options.noconfirm {
100 100 url.push_str("&noconfirm=1");
101 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));
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));
106 107 }
107 108 }
108 109 Ok(url)
@@ -135,7 +136,7 @@ pub fn parse_posprint_url(url: &str) -> Result<PosprintLaunch, ProtocolUrlError>
135 136 let mut version: Option<String> = None;
136 137 let mut payload: Option<String> = None;
137 138 let mut noconfirm = false;
138 let mut origin_raw: Option<String> = None;
139 let mut referrer: Option<String> = None;
139 140 for pair in query.split('&') {
140 141 if pair.is_empty() {
141 142 continue;
@@ -146,7 +147,12 @@ pub fn parse_posprint_url(url: &str) -> Result<PosprintLaunch, ProtocolUrlError>
146 147 "v" => version = Some(percent_decode_str(value)?),
147 148 "d" => payload = Some(percent_decode_str(value)?),
148 149 "noconfirm" => noconfirm = parse_bool_flag(value),
149 "origin" => origin_raw = Some(percent_decode_str(value)?),
150 "referrer" => {
151 let decoded = percent_decode_str(value)?;
152 if !decoded.trim().is_empty() {
153 referrer = Some(decoded);
154 }
155 }
150 156 _ => {}
151 157 }
152 158 }
@@ -172,11 +178,10 @@ pub fn parse_posprint_url(url: &str) -> Result<PosprintLaunch, ProtocolUrlError>
172 178 return Err(ProtocolUrlError::UnsupportedPosVersion(file.version));
173 179 }
174 180
175 let origin = origin_raw.as_deref().and_then(normalize_origin);
176 181 Ok(PosprintLaunch {
177 182 file,
178 183 noconfirm,
179 origin,
184 referrer,
180 185 })
181 186 }
182 187
@@ -276,35 +281,39 @@ mod tests {
276 281 let decoded = parse_posprint_url(&url).unwrap();
277 282 assert_eq!(decoded.file, file);
278 283 assert!(!decoded.noconfirm);
279 assert!(decoded.origin.is_none());
284 assert!(decoded.referrer.is_none());
280 285 }
281 286
282 287 #[test]
283 fn encodes_and_parses_noconfirm_and_origin() {
288 fn encodes_and_parses_noconfirm_and_referrer() {
284 289 let file = sample_file();
285 290 let url = encode_posprint_url_with_options(
286 291 &file,
287 292 &EncodeOptions {
288 293 noconfirm: true,
289 origin: Some("https://Shop.Example.com/x".into()),
294 referrer: Some("website.com/bonnen/verify?code=84923".into()),
290 295 },
291 296 )
292 297 .unwrap();
293 298 assert!(url.contains("&noconfirm=1"));
294 assert!(url.contains("&origin=shop.example.com"));
299 assert!(url.contains("&referrer="));
300 assert!(url.contains("code%3D84923") || url.contains("code%3d84923"));
295 301 let launch = parse_posprint_url(&url).unwrap();
296 302 assert!(launch.noconfirm);
297 assert_eq!(launch.origin.as_deref(), Some("shop.example.com"));
303 assert_eq!(
304 launch.referrer.as_deref(),
305 Some("website.com/bonnen/verify?code=84923")
306 );
298 307 }
299 308
300 309 #[test]
301 310 fn parses_noconfirm_without_value() {
302 311 let file = sample_file();
303 312 let base = encode_posprint_url(&file).unwrap();
304 let url = format!("{base}&noconfirm&origin=pos.local");
313 let url = format!("{base}&noconfirm&referrer=shop.example%2Fv");
305 314 let launch = parse_posprint_url(&url).unwrap();
306 315 assert!(launch.noconfirm);
307 assert_eq!(launch.origin.as_deref(), Some("pos.local"));
316 assert_eq!(launch.referrer.as_deref(), Some("shop.example/v"));
308 317 }
309 318
310 319 #[test]
@@ -9,7 +9,6 @@ use flate2::read::DeflateDecoder;
9use flate2::write::DeflateEncoder;
9use flate2::write::DeflateEncoder;
10use flate2::Compression;
10use flate2::Compression;
11
11
12use crate::config::normalize_origin;
13use crate::io::PosFile;
12use crate::io::PosFile;
14
13
15/// Soft warning threshold for cross-platform protocol handoff (~Windows cmdline limit).
14/// Soft warning threshold for cross-platform protocol handoff (~Windows cmdline limit).
@@ -56,17 +55,18 @@ impl From<serde_json::Error> for ProtocolUrlError {
56#[derive(Debug, Clone, PartialEq)]
55#[derive(Debug, Clone, PartialEq)]
57pub struct PosprintLaunch {
56pub struct PosprintLaunch {
58 pub file: PosFile,
57 pub file: PosFile,
59 /// When true, print without waiting for the Print button (subject to domain trust).
58 /// When true, print without waiting for the Print button (subject to referrer verify + trust).
60 pub noconfirm: bool,
59 pub noconfirm: bool,
61 /// Normalized hostname from `origin=` (required for first-time trust when noconfirm).
60 /// Verification URL from `referrer=` (percent-decoded; may be scheme-less).
62 pub origin: Option<String>,
61 pub referrer: Option<String>,
63}
62}
64
63
65/// Optional extras when encoding a URL.
64/// Optional extras when encoding a URL.
66#[derive(Debug, Clone, Default)]
65#[derive(Debug, Clone, Default)]
67pub struct EncodeOptions {
66pub struct EncodeOptions {
68 pub noconfirm: bool,
67 pub noconfirm: bool,
69 pub origin: Option<String>,
68 /// Full verification URL or `host/path?query` (stored percent-encoded in the posprint URL).
69 pub referrer: Option<String>,
70}
70}
71
71
72/// True when `s` looks like a `posprint:` / `posprint://` protocol URL.
72/// True when `s` looks like a `posprint:` / `posprint://` protocol URL.
@@ -81,7 +81,7 @@ pub fn encode_posprint_url(file: &PosFile) -> Result<String, ProtocolUrlError> {
81 encode_posprint_url_with_options(file, &EncodeOptions::default())
81 encode_posprint_url_with_options(file, &EncodeOptions::default())
82}
82}
83
83
84/// Encode with optional `noconfirm` / `origin` query parameters.
84/// Encode with optional `noconfirm` / `referrer` query parameters.
85pub fn encode_posprint_url_with_options(
85pub fn encode_posprint_url_with_options(
86 file: &PosFile,
86 file: &PosFile,
87 options: &EncodeOptions,
87 options: &EncodeOptions,
@@ -99,10 +99,11 @@ pub fn encode_posprint_url_with_options(
99 if options.noconfirm {
99 if options.noconfirm {
100 url.push_str("&noconfirm=1");
100 url.push_str("&noconfirm=1");
101 }
101 }
102 if let Some(raw) = options.origin.as_deref() {
102 if let Some(raw) = options.referrer.as_deref() {
103 if let Some(host) = normalize_origin(raw) {
103 let trimmed = raw.trim();
104 url.push_str("&origin=");
104 if !trimmed.is_empty() {
105 url.push_str(&percent_encode_component(&host));
105 url.push_str("&referrer=");
106 url.push_str(&percent_encode_component(trimmed));
106 }
107 }
107 }
108 }
108 Ok(url)
109 Ok(url)
@@ -135,7 +136,7 @@ pub fn parse_posprint_url(url: &str) -> Result<PosprintLaunch, ProtocolUrlError>
135 let mut version: Option<String> = None;
136 let mut version: Option<String> = None;
136 let mut payload: Option<String> = None;
137 let mut payload: Option<String> = None;
137 let mut noconfirm = false;
138 let mut noconfirm = false;
138 let mut origin_raw: Option<String> = None;
139 let mut referrer: Option<String> = None;
139 for pair in query.split('&') {
140 for pair in query.split('&') {
140 if pair.is_empty() {
141 if pair.is_empty() {
141 continue;
142 continue;
@@ -146,7 +147,12 @@ pub fn parse_posprint_url(url: &str) -> Result<PosprintLaunch, ProtocolUrlError>
146 "v" => version = Some(percent_decode_str(value)?),
147 "v" => version = Some(percent_decode_str(value)?),
147 "d" => payload = Some(percent_decode_str(value)?),
148 "d" => payload = Some(percent_decode_str(value)?),
148 "noconfirm" => noconfirm = parse_bool_flag(value),
149 "noconfirm" => noconfirm = parse_bool_flag(value),
149 "origin" => origin_raw = Some(percent_decode_str(value)?),
150 "referrer" => {
151 let decoded = percent_decode_str(value)?;
152 if !decoded.trim().is_empty() {
153 referrer = Some(decoded);
154 }
155 }
150 _ => {}
156 _ => {}
151 }
157 }
152 }
158 }
@@ -172,11 +178,10 @@ pub fn parse_posprint_url(url: &str) -> Result<PosprintLaunch, ProtocolUrlError>
172 return Err(ProtocolUrlError::UnsupportedPosVersion(file.version));
178 return Err(ProtocolUrlError::UnsupportedPosVersion(file.version));
173 }
179 }
174
180
175 let origin = origin_raw.as_deref().and_then(normalize_origin);
176 Ok(PosprintLaunch {
181 Ok(PosprintLaunch {
177 file,
182 file,
178 noconfirm,
183 noconfirm,
179 origin,
184 referrer,
180 })
185 })
181}
186}
182
187
@@ -276,35 +281,39 @@ mod tests {
276 let decoded = parse_posprint_url(&url).unwrap();
281 let decoded = parse_posprint_url(&url).unwrap();
277 assert_eq!(decoded.file, file);
282 assert_eq!(decoded.file, file);
278 assert!(!decoded.noconfirm);
283 assert!(!decoded.noconfirm);
279 assert!(decoded.origin.is_none());
284 assert!(decoded.referrer.is_none());
280 }
285 }
281
286
282 #[test]
287 #[test]
283 fn encodes_and_parses_noconfirm_and_origin() {
288 fn encodes_and_parses_noconfirm_and_referrer() {
284 let file = sample_file();
289 let file = sample_file();
285 let url = encode_posprint_url_with_options(
290 let url = encode_posprint_url_with_options(
286 &file,
291 &file,
287 &EncodeOptions {
292 &EncodeOptions {
288 noconfirm: true,
293 noconfirm: true,
289 origin: Some("https://Shop.Example.com/x".into()),
294 referrer: Some("website.com/bonnen/verify?code=84923".into()),
290 },
295 },
291 )
296 )
292 .unwrap();
297 .unwrap();
293 assert!(url.contains("&noconfirm=1"));
298 assert!(url.contains("&noconfirm=1"));
294 assert!(url.contains("&origin=shop.example.com"));
299 assert!(url.contains("&referrer="));
300 assert!(url.contains("code%3D84923") || url.contains("code%3d84923"));
295 let launch = parse_posprint_url(&url).unwrap();
301 let launch = parse_posprint_url(&url).unwrap();
296 assert!(launch.noconfirm);
302 assert!(launch.noconfirm);
297 assert_eq!(launch.origin.as_deref(), Some("shop.example.com"));
303 assert_eq!(
304 launch.referrer.as_deref(),
305 Some("website.com/bonnen/verify?code=84923")
306 );
298 }
307 }
299
308
300 #[test]
309 #[test]
301 fn parses_noconfirm_without_value() {
310 fn parses_noconfirm_without_value() {
302 let file = sample_file();
311 let file = sample_file();
303 let base = encode_posprint_url(&file).unwrap();
312 let base = encode_posprint_url(&file).unwrap();
304 let url = format!("{base}&noconfirm&origin=pos.local");
313 let url = format!("{base}&noconfirm&referrer=shop.example%2Fv");
305 let launch = parse_posprint_url(&url).unwrap();
314 let launch = parse_posprint_url(&url).unwrap();
306 assert!(launch.noconfirm);
315 assert!(launch.noconfirm);
307 assert_eq!(launch.origin.as_deref(), Some("pos.local"));
316 assert_eq!(launch.referrer.as_deref(), Some("shop.example/v"));
308 }
317 }
309
318
310 #[test]
319 #[test]
src/referrer_verify.rs added +171 −0
@@ -0,0 +1,171 @@
1 //! Verify `noconfirm` print requests via a caller-controlled HTTP(S) referrer URL.
2
3 use std::net::IpAddr;
4 use std::time::Duration;
5
6 use crate::config::normalize_origin;
7
8 const VERIFY_TIMEOUT_SECS: u64 = 10;
9
10 #[derive(Debug, Clone, PartialEq, Eq)]
11 pub enum ReferrerVerifyError {
12 Empty,
13 UnsupportedScheme(String),
14 InvalidUrl(String),
15 BlockedHost(String),
16 HttpStatus(u16),
17 Network(String),
18 }
19
20 impl std::fmt::Display for ReferrerVerifyError {
21 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
22 match self {
23 Self::Empty => write!(f, "referrer URL is empty"),
24 Self::UnsupportedScheme(s) => {
25 write!(f, "referrer must be http(s), got '{s}'")
26 }
27 Self::InvalidUrl(e) => write!(f, "invalid referrer URL: {e}"),
28 Self::BlockedHost(h) => {
29 write!(f, "referrer host '{h}' is not allowed for verification")
30 }
31 Self::HttpStatus(code) => write!(
32 f,
33 "referrer verification failed (HTTP {code}); expected 200"
34 ),
35 Self::Network(e) => write!(f, "referrer verification network error: {e}"),
36 }
37 }
38 }
39
40 impl std::error::Error for ReferrerVerifyError {}
41
42 /// Normalize a referrer parameter into an absolute `http://` or `https://` URL.
43 /// Bare values like `shop.example/verify?code=1` become `https://shop.example/verify?code=1`.
44 pub fn normalize_referrer_url(raw: &str) -> Result<String, ReferrerVerifyError> {
45 let s = raw.trim();
46 if s.is_empty() {
47 return Err(ReferrerVerifyError::Empty);
48 }
49
50 let absolute = if let Some(rest) = s.strip_prefix("https://") {
51 format!("https://{rest}")
52 } else if let Some(rest) = s.strip_prefix("http://") {
53 format!("http://{rest}")
54 } else if let Some(idx) = s.find("://") {
55 let scheme = &s[..idx];
56 return Err(ReferrerVerifyError::UnsupportedScheme(scheme.to_string()));
57 } else {
58 format!("https://{s}")
59 };
60
61 let host = host_from_http_url(&absolute)
62 .ok_or_else(|| ReferrerVerifyError::InvalidUrl("missing host".into()))?;
63 if is_blocked_verify_host(&host) {
64 return Err(ReferrerVerifyError::BlockedHost(host));
65 }
66 Ok(absolute)
67 }
68
69 /// Hostname used for trust storage after a successful verification GET.
70 pub fn referrer_trust_host(referrer_url: &str) -> Option<String> {
71 normalize_origin(referrer_url)
72 }
73
74 fn host_from_http_url(url: &str) -> Option<String> {
75 let rest = url
76 .strip_prefix("https://")
77 .or_else(|| url.strip_prefix("http://"))?;
78 let host_port = rest.split('/').next()?.split('?').next()?.trim();
79 if host_port.is_empty() {
80 return None;
81 }
82 let host = host_port.split(':').next()?.trim();
83 if host.is_empty() {
84 None
85 } else {
86 Some(host.to_ascii_lowercase())
87 }
88 }
89
90 fn is_blocked_verify_host(host: &str) -> bool {
91 let h = host.to_ascii_lowercase();
92 if h == "localhost" || h.ends_with(".localhost") || h == "0.0.0.0" {
93 return true;
94 }
95 if let Ok(ip) = h.parse::<IpAddr>() {
96 return match ip {
97 IpAddr::V4(v4) => {
98 v4.is_loopback()
99 || v4.is_private()
100 || v4.is_link_local()
101 || v4.is_unspecified()
102 || v4.octets()[0] == 169 && v4.octets()[1] == 254
103 }
104 IpAddr::V6(v6) => v6.is_loopback() || v6.is_unspecified(),
105 };
106 }
107 false
108 }
109
110 /// True when an HTTP status means the print request is authorized by the site.
111 pub fn is_verification_success(status: u16) -> bool {
112 status == 200
113 }
114
115 /// GET `referrer_url` (no redirects). On HTTP 200 returns the trust hostname.
116 pub fn verify_referrer(referrer_url: &str) -> Result<String, ReferrerVerifyError> {
117 let url = normalize_referrer_url(referrer_url)?;
118 let host = referrer_trust_host(&url)
119 .ok_or_else(|| ReferrerVerifyError::InvalidUrl("missing host".into()))?;
120
121 let agent = ureq::AgentBuilder::new()
122 .timeout_connect(Duration::from_secs(VERIFY_TIMEOUT_SECS))
123 .timeout_read(Duration::from_secs(VERIFY_TIMEOUT_SECS))
124 .redirects(0)
125 .build();
126
127 let response = agent.get(&url).call().map_err(|e| match e {
128 ureq::Error::Status(code, _) => ReferrerVerifyError::HttpStatus(code),
129 other => ReferrerVerifyError::Network(other.to_string()),
130 })?;
131
132 let status = response.status();
133 if !is_verification_success(status) {
134 return Err(ReferrerVerifyError::HttpStatus(status));
135 }
136 Ok(host)
137 }
138
139 #[cfg(test)]
140 mod tests {
141 use super::*;
142
143 #[test]
144 fn normalizes_bare_host_path_to_https() {
145 let url = normalize_referrer_url("website.com/bonnen/verify?code=84923").unwrap();
146 assert_eq!(url, "https://website.com/bonnen/verify?code=84923");
147 assert_eq!(referrer_trust_host(&url).as_deref(), Some("website.com"));
148 }
149
150 #[test]
151 fn rejects_non_http_schemes() {
152 let err = normalize_referrer_url("file:///etc/passwd").unwrap_err();
153 assert!(matches!(err, ReferrerVerifyError::UnsupportedScheme(_)));
154 }
155
156 #[test]
157 fn blocks_localhost() {
158 let err = normalize_referrer_url("http://127.0.0.1/verify").unwrap_err();
159 assert!(matches!(err, ReferrerVerifyError::BlockedHost(_)));
160 let err = normalize_referrer_url("https://localhost/x").unwrap_err();
161 assert!(matches!(err, ReferrerVerifyError::BlockedHost(_)));
162 }
163
164 #[test]
165 fn only_http_200_counts_as_success() {
166 assert!(is_verification_success(200));
167 assert!(!is_verification_success(204));
168 assert!(!is_verification_success(404));
169 assert!(!is_verification_success(302));
170 }
171 }
@@ -0,0 +1,171 @@
1//! Verify `noconfirm` print requests via a caller-controlled HTTP(S) referrer URL.
2
3use std::net::IpAddr;
4use std::time::Duration;
5
6use crate::config::normalize_origin;
7
8const VERIFY_TIMEOUT_SECS: u64 = 10;
9
10#[derive(Debug, Clone, PartialEq, Eq)]
11pub enum ReferrerVerifyError {
12 Empty,
13 UnsupportedScheme(String),
14 InvalidUrl(String),
15 BlockedHost(String),
16 HttpStatus(u16),
17 Network(String),
18}
19
20impl std::fmt::Display for ReferrerVerifyError {
21 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
22 match self {
23 Self::Empty => write!(f, "referrer URL is empty"),
24 Self::UnsupportedScheme(s) => {
25 write!(f, "referrer must be http(s), got '{s}'")
26 }
27 Self::InvalidUrl(e) => write!(f, "invalid referrer URL: {e}"),
28 Self::BlockedHost(h) => {
29 write!(f, "referrer host '{h}' is not allowed for verification")
30 }
31 Self::HttpStatus(code) => write!(
32 f,
33 "referrer verification failed (HTTP {code}); expected 200"
34 ),
35 Self::Network(e) => write!(f, "referrer verification network error: {e}"),
36 }
37 }
38}
39
40impl std::error::Error for ReferrerVerifyError {}
41
42/// Normalize a referrer parameter into an absolute `http://` or `https://` URL.
43/// Bare values like `shop.example/verify?code=1` become `https://shop.example/verify?code=1`.
44pub fn normalize_referrer_url(raw: &str) -> Result<String, ReferrerVerifyError> {
45 let s = raw.trim();
46 if s.is_empty() {
47 return Err(ReferrerVerifyError::Empty);
48 }
49
50 let absolute = if let Some(rest) = s.strip_prefix("https://") {
51 format!("https://{rest}")
52 } else if let Some(rest) = s.strip_prefix("http://") {
53 format!("http://{rest}")
54 } else if let Some(idx) = s.find("://") {
55 let scheme = &s[..idx];
56 return Err(ReferrerVerifyError::UnsupportedScheme(scheme.to_string()));
57 } else {
58 format!("https://{s}")
59 };
60
61 let host = host_from_http_url(&absolute)
62 .ok_or_else(|| ReferrerVerifyError::InvalidUrl("missing host".into()))?;
63 if is_blocked_verify_host(&host) {
64 return Err(ReferrerVerifyError::BlockedHost(host));
65 }
66 Ok(absolute)
67}
68
69/// Hostname used for trust storage after a successful verification GET.
70pub fn referrer_trust_host(referrer_url: &str) -> Option<String> {
71 normalize_origin(referrer_url)
72}
73
74fn host_from_http_url(url: &str) -> Option<String> {
75 let rest = url
76 .strip_prefix("https://")
77 .or_else(|| url.strip_prefix("http://"))?;
78 let host_port = rest.split('/').next()?.split('?').next()?.trim();
79 if host_port.is_empty() {
80 return None;
81 }
82 let host = host_port.split(':').next()?.trim();
83 if host.is_empty() {
84 None
85 } else {
86 Some(host.to_ascii_lowercase())
87 }
88}
89
90fn is_blocked_verify_host(host: &str) -> bool {
91 let h = host.to_ascii_lowercase();
92 if h == "localhost" || h.ends_with(".localhost") || h == "0.0.0.0" {
93 return true;
94 }
95 if let Ok(ip) = h.parse::<IpAddr>() {
96 return match ip {
97 IpAddr::V4(v4) => {
98 v4.is_loopback()
99 || v4.is_private()
100 || v4.is_link_local()
101 || v4.is_unspecified()
102 || v4.octets()[0] == 169 && v4.octets()[1] == 254
103 }
104 IpAddr::V6(v6) => v6.is_loopback() || v6.is_unspecified(),
105 };
106 }
107 false
108}
109
110/// True when an HTTP status means the print request is authorized by the site.
111pub fn is_verification_success(status: u16) -> bool {
112 status == 200
113}
114
115/// GET `referrer_url` (no redirects). On HTTP 200 returns the trust hostname.
116pub fn verify_referrer(referrer_url: &str) -> Result<String, ReferrerVerifyError> {
117 let url = normalize_referrer_url(referrer_url)?;
118 let host = referrer_trust_host(&url)
119 .ok_or_else(|| ReferrerVerifyError::InvalidUrl("missing host".into()))?;
120
121 let agent = ureq::AgentBuilder::new()
122 .timeout_connect(Duration::from_secs(VERIFY_TIMEOUT_SECS))
123 .timeout_read(Duration::from_secs(VERIFY_TIMEOUT_SECS))
124 .redirects(0)
125 .build();
126
127 let response = agent.get(&url).call().map_err(|e| match e {
128 ureq::Error::Status(code, _) => ReferrerVerifyError::HttpStatus(code),
129 other => ReferrerVerifyError::Network(other.to_string()),
130 })?;
131
132 let status = response.status();
133 if !is_verification_success(status) {
134 return Err(ReferrerVerifyError::HttpStatus(status));
135 }
136 Ok(host)
137}
138
139#[cfg(test)]
140mod tests {
141 use super::*;
142
143 #[test]
144 fn normalizes_bare_host_path_to_https() {
145 let url = normalize_referrer_url("website.com/bonnen/verify?code=84923").unwrap();
146 assert_eq!(url, "https://website.com/bonnen/verify?code=84923");
147 assert_eq!(referrer_trust_host(&url).as_deref(), Some("website.com"));
148 }
149
150 #[test]
151 fn rejects_non_http_schemes() {
152 let err = normalize_referrer_url("file:///etc/passwd").unwrap_err();
153 assert!(matches!(err, ReferrerVerifyError::UnsupportedScheme(_)));
154 }
155
156 #[test]
157 fn blocks_localhost() {
158 let err = normalize_referrer_url("http://127.0.0.1/verify").unwrap_err();
159 assert!(matches!(err, ReferrerVerifyError::BlockedHost(_)));
160 let err = normalize_referrer_url("https://localhost/x").unwrap_err();
161 assert!(matches!(err, ReferrerVerifyError::BlockedHost(_)));
162 }
163
164 #[test]
165 fn only_http_200_counts_as_success() {
166 assert!(is_verification_success(200));
167 assert!(!is_verification_success(204));
168 assert!(!is_verification_success(404));
169 assert!(!is_verification_success(302));
170 }
171}