BlueGit

timfa posprint

Drop noconfirm referrer verify and trusted sites.

Browser protocol prompts already gate consent; keep noconfirm as plain auto-print and ignore legacy referrer=.

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

timfa Tim Falken · pushed by timfa

Authored 2026-08-05 · 3 months ago

Hash
127cb3945e7eea090706af120416f97305d3a179
Parent
c59e32ea
15 files changed +58 −612
docs/ARCHITECTURE.md +3 −4
@@ -33,7 +33,6 @@ 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 ├── referrer_verify.rs # noconfirm referrer GET (HTTP 200)
37 36 ├── editor_assist.rs # @ autocomplete, Insert snippets
38 37 ├── help_view.rs # Markdown help renderer
39 38 ├── io/mod.rs # PosFile, PosMetadata
@@ -72,11 +71,11 @@ ESC/POS generation is **in-tree** (`escpos.rs`), not the `escpos` crates.io pack
72 71 |------|--------|-------------|
73 72 | **Design** | `app.rs` | Editor + side preview |
74 73 | **Help** | `help_view.rs` | `docs/HELP.md` via `include_str!` |
75 | **Settings** | `app.rs` | Default page width; trusted `noconfirm` origins |
74 | **Settings** | `app.rs` | Default page width for new documents |
76 75 | Toolbar | `app.rs` | New, Open, Save, Save As, Insert, Print |
77 76 | Document page width / zoom | `app.rs` | Per-document width (mm), preview zoom |
78 77 | Print dialog | `print_dialog.rs` | Parameters + multi-transport printer picker |
79 | App config | `config.rs` | `%APPDATA%/posprint/config.json` (Windows) / `~/.config/posprint/config.json` (trusted origins, default width, last printer) |
78 | App config | `config.rs` | `%APPDATA%/posprint/config.json` (Windows) / `~/.config/posprint/config.json` (default width, last printer) |
80 79
81 80 While the print dialog is open, the main UI is disabled and editor autocomplete does not steal focus.
82 81
@@ -156,7 +155,7 @@ Legacy JSON fields `preview_mode` and `cut_after_print` are ignored if present.
156 155 |------|---------|
157 156 | Template + metadata | `.pos` file |
158 157 | Last parameter values | In-memory (`print_dialog.last_params`) |
159 | Default page width / trusted origins / last printer | `config.rs` → platform config JSON |
158 | Default page width / last printer | `config.rs` → platform config JSON |
160 159 | Recent files | Not persisted |
161 160
162 161 ---
@@ -33,7 +33,6 @@ 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├── referrer_verify.rs # noconfirm referrer GET (HTTP 200)
37├── editor_assist.rs # @ autocomplete, Insert snippets
36├── editor_assist.rs # @ autocomplete, Insert snippets
38├── help_view.rs # Markdown help renderer
37├── help_view.rs # Markdown help renderer
39├── io/mod.rs # PosFile, PosMetadata
38├── io/mod.rs # PosFile, PosMetadata
@@ -72,11 +71,11 @@ ESC/POS generation is **in-tree** (`escpos.rs`), not the `escpos` crates.io pack
72|------|--------|-------------|
71|------|--------|-------------|
73| **Design** | `app.rs` | Editor + side preview |
72| **Design** | `app.rs` | Editor + side preview |
74| **Help** | `help_view.rs` | `docs/HELP.md` via `include_str!` |
73| **Help** | `help_view.rs` | `docs/HELP.md` via `include_str!` |
75| **Settings** | `app.rs` | Default page width; trusted `noconfirm` origins |
74| **Settings** | `app.rs` | Default page width for new documents |
76| Toolbar | `app.rs` | New, Open, Save, Save As, Insert, Print |
75| Toolbar | `app.rs` | New, Open, Save, Save As, Insert, Print |
77| Document page width / zoom | `app.rs` | Per-document width (mm), preview zoom |
76| Document page width / zoom | `app.rs` | Per-document width (mm), preview zoom |
78| Print dialog | `print_dialog.rs` | Parameters + multi-transport printer picker |
77| Print dialog | `print_dialog.rs` | Parameters + multi-transport printer picker |
79| App config | `config.rs` | `%APPDATA%/posprint/config.json` (Windows) / `~/.config/posprint/config.json` (trusted origins, default width, last printer) |
78| App config | `config.rs` | `%APPDATA%/posprint/config.json` (Windows) / `~/.config/posprint/config.json` (default width, last printer) |
80
79
81While the print dialog is open, the main UI is disabled and editor autocomplete does not steal focus.
80While the print dialog is open, the main UI is disabled and editor autocomplete does not steal focus.
82
81
@@ -156,7 +155,7 @@ Legacy JSON fields `preview_mode` and `cut_after_print` are ignored if present.
156|------|---------|
155|------|---------|
157| Template + metadata | `.pos` file |
156| Template + metadata | `.pos` file |
158| Last parameter values | In-memory (`print_dialog.last_params`) |
157| Last parameter values | In-memory (`print_dialog.last_params`) |
159| Default page width / trusted origins / last printer | `config.rs` → platform config JSON |
158| Default page width / last printer | `config.rs` → platform config JSON |
160| Recent files | Not persisted |
159| Recent files | Not persisted |
161
160
162---
161---
docs/HELP.md +2 −2
@@ -10,7 +10,7 @@ Built-in reference for the template editor and POS markup language.
10 10 |-----|---------|
11 11 | **Design** | Side-by-side template editor and live preview |
12 12 | **Help** | This documentation |
13 | **Settings** | Default page width for new documents; trusted sites for `noconfirm` |
13 | **Settings** | Default page width for new documents |
14 14
15 15 ## Toolbar actions
16 16
@@ -317,7 +317,7 @@ Websites can open the print dialog with an embedded template:
317 317 posprint://print?v=1&d=…
318 318 ```
319 319
320 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**). Auto-print uses the last printer that printed successfully when that device is still available. Encoding helpers live in [`lib/`](../lib/). Full guide: [POSPRINT-URL.md](POSPRINT-URL.md).
320 Add `&noconfirm=1` to auto-print once a printer is ready (the browser’s protocol prompt is the consent step). Auto-print uses the last printer that printed successfully when that device is still available. Encoding helpers live in [`lib/`](../lib/). Full guide: [POSPRINT-URL.md](POSPRINT-URL.md).
321 321
322 322 `@image` may use `https://…` or `http://…` (downloaded when preview/print needs the image).
323 323
@@ -10,7 +10,7 @@ Built-in reference for the template editor and POS markup language.
10|-----|---------|
10|-----|---------|
11| **Design** | Side-by-side template editor and live preview |
11| **Design** | Side-by-side template editor and live preview |
12| **Help** | This documentation |
12| **Help** | This documentation |
13| **Settings** | Default page width for new documents; trusted sites for `noconfirm` |
13| **Settings** | Default page width for new documents |
14
14
15## Toolbar actions
15## Toolbar actions
16
16
@@ -317,7 +317,7 @@ Websites can open the print dialog with an embedded template:
317posprint://print?v=1&d=…
317posprint://print?v=1&d=…
318```
318```
319
319
320Add `&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**). Auto-print uses the last printer that printed successfully when that device is still available. Encoding helpers live in [`lib/`](../lib/). Full guide: [POSPRINT-URL.md](POSPRINT-URL.md).
320Add `&noconfirm=1` to auto-print once a printer is ready (the browser’s protocol prompt is the consent step). Auto-print uses the last printer that printed successfully when that device is still available. Encoding helpers live in [`lib/`](../lib/). Full guide: [POSPRINT-URL.md](POSPRINT-URL.md).
321
321
322`@image` may use `https://…` or `http://…` (downloaded when preview/print needs the image).
322`@image` may use `https://…` or `http://…` (downloaded when preview/print needs the image).
323
323
docs/POSPRINT-URL.md +6 −25
@@ -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&referrer=website.com%2Fbonnen%2Fverify%3Fcode%3D84923
18 posprint://print?v=1&d=…&noconfirm=1
19 19 ```
20 20
21 21 | Part | Meaning |
@@ -24,35 +24,19 @@ posprint://print?v=1&d=…&noconfirm=1&referrer=website.com%2Fbonnen%2Fverify%3F
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 referrer verification (+ domain trust) |
28 | `referrer=` | **Percent-encoded** verification URL on the issuer’s domain (see below) |
27 | `noconfirm=1` | Start printing as soon as a printer is ready (no Print click) |
29 28
30 29 **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 30
32 31 **Images:** keep logos out of the URL. Use `@image https://…` (or `http://…`) in the template body; posprint downloads them when needed.
33 32
34 ### Auto-print (`noconfirm`) and referrer verification
33 ### Auto-print (`noconfirm`)
35 34
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
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 |----------------------------------------|------------------------|
48 | posprint shows **Trust this site?** | If trusted, prints without asking |
49 | **Trust and print** stores the hostname | Revoke under **Settings → Trusted sites** |
35 Add `&noconfirm=1` to print without waiting for the Print button. Consent to open posprint is handled by the **browser** (protocol launch prompt), not by a second trust dialog in the app.
50 36
51 37 After a successful print, posprint remembers that printer. On the next `noconfirm` (and in the interactive dialog), it selects that printer again **if it is still connected**; otherwise it keeps the usual first/default selection.
52 38
53 Without `referrer`, `noconfirm=1` is rejected. Without `noconfirm`, behaviour is unchanged (interactive print dialog).
54
55 Localhost / loopback verification URLs are allowed. Other private LAN addresses (e.g. `192.168.x.x`) are blocked.
39 Legacy `&referrer=…` in old URLs is ignored.
56 40
57 41 ### Browser “Open posprint?” prompt
58 42
@@ -109,10 +93,9 @@ $url = posprint_url([
109 93 'metadata' => ['page_width_mm' => 53, 'chars_per_line' => 32],
110 94 'body' => "@barcode RASTER CODE128 \${data}\nHello\n@cut\n",
111 95 ]);
112 // Auto-print: site must expose a verify URL that returns HTTP 200 for this code:
96 // Auto-print (browser protocol prompt is the consent gate):
113 97 $auto = posprint_url($pos, [
114 98 'noconfirm' => true,
115 'referrer' => 'https://shop.example.com/bonnen/verify?code=' . urlencode($code),
116 99 ]);
117 100 // <a href="<?= htmlspecialchars($url) ?>">Print</a>
118 101 ```
@@ -130,7 +113,6 @@ const url = posprintUrl({
130 113
131 114 const auto = posprintUrl(pos, {
132 115 noconfirm: true,
133 referrer: `https://shop.example.com/bonnen/verify?code=${encodeURIComponent(code)}`,
134 116 });
135 117 ```
136 118
@@ -146,7 +128,6 @@ const auto = posprintUrl(pos, {
146 128 });
147 129 const auto = await posprintUrl(pos, {
148 130 noconfirm: true,
149 referrer: `https://${location.host}/bonnen/verify?code=${encodeURIComponent(code)}`,
150 131 });
151 132 location.href = auto;
152 133 </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&referrer=website.com%2Fbonnen%2Fverify%3Fcode%3D84923
18posprint://print?v=1&d=…&noconfirm=1
19```
19```
20
20
21| Part | Meaning |
21| Part | Meaning |
@@ -24,35 +24,19 @@ posprint://print?v=1&d=…&noconfirm=1&referrer=website.com%2Fbonnen%2Fverify%3F
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 referrer verification (+ domain trust) |
27| `noconfirm=1` | Start printing as soon as a printer is ready (no Print click) |
28| `referrer=` | **Percent-encoded** verification URL on the issuer’s domain (see below) |
29
28
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`.
29**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
30
32**Images:** keep logos out of the URL. Use `@image https://…` (or `http://…`) in the template body; posprint downloads them when needed.
31**Images:** keep logos out of the URL. Use `@image https://…` (or `http://…`) in the template body; posprint downloads them when needed.
33
32
34### Auto-print (`noconfirm`) and referrer verification
33### Auto-print (`noconfirm`)
35
34
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:
35Add `&noconfirm=1` to print without waiting for the Print button. Consent to open posprint is handled by the **browser** (protocol launch prompt), not by a second trust dialog in the app.
37
381. Embed `&noconfirm=1&referrer=<URL-encoded verification URL>`.
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|----------------------------------------|------------------------|
48| posprint shows **Trust this site?** | If trusted, prints without asking |
49| **Trust and print** stores the hostname | Revoke under **Settings → Trusted sites** |
50
36
51After a successful print, posprint remembers that printer. On the next `noconfirm` (and in the interactive dialog), it selects that printer again **if it is still connected**; otherwise it keeps the usual first/default selection.
37After a successful print, posprint remembers that printer. On the next `noconfirm` (and in the interactive dialog), it selects that printer again **if it is still connected**; otherwise it keeps the usual first/default selection.
52
38
53Without `referrer`, `noconfirm=1` is rejected. Without `noconfirm`, behaviour is unchanged (interactive print dialog).
39Legacy `&referrer=…` in old URLs is ignored.
54
55Localhost / loopback verification URLs are allowed. Other private LAN addresses (e.g. `192.168.x.x`) are blocked.
56
40
57### Browser “Open posprint?” prompt
41### Browser “Open posprint?” prompt
58
42
@@ -109,10 +93,9 @@ $url = posprint_url([
109 'metadata' => ['page_width_mm' => 53, 'chars_per_line' => 32],
93 'metadata' => ['page_width_mm' => 53, 'chars_per_line' => 32],
110 'body' => "@barcode RASTER CODE128 \${data}\nHello\n@cut\n",
94 'body' => "@barcode RASTER CODE128 \${data}\nHello\n@cut\n",
111]);
95]);
112// Auto-print: site must expose a verify URL that returns HTTP 200 for this code:
96// Auto-print (browser protocol prompt is the consent gate):
113$auto = posprint_url($pos, [
97$auto = posprint_url($pos, [
114 'noconfirm' => true,
98 'noconfirm' => true,
115 'referrer' => 'https://shop.example.com/bonnen/verify?code=' . urlencode($code),
116]);
99]);
117// <a href="<?= htmlspecialchars($url) ?>">Print</a>
100// <a href="<?= htmlspecialchars($url) ?>">Print</a>
118```
101```
@@ -130,7 +113,6 @@ const url = posprintUrl({
130
113
131const auto = posprintUrl(pos, {
114const auto = posprintUrl(pos, {
132 noconfirm: true,
115 noconfirm: true,
133 referrer: `https://shop.example.com/bonnen/verify?code=${encodeURIComponent(code)}`,
134});
116});
135```
117```
136
118
@@ -146,7 +128,6 @@ const auto = posprintUrl(pos, {
146 });
128 });
147 const auto = await posprintUrl(pos, {
129 const auto = await posprintUrl(pos, {
148 noconfirm: true,
130 noconfirm: true,
149 referrer: `https://${location.host}/bonnen/verify?code=${encodeURIComponent(code)}`,
150 });
131 });
151 location.href = auto;
132 location.href = auto;
152</script>
133</script>
lib/browser/examples.md +2 −5
@@ -31,11 +31,8 @@ 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 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 // });
34 // Auto-print (browser protocol prompt is the consent gate):
35 // const url = await posprintUrl(pos, { noconfirm: true });
39 36 window.location.href = url;
40 37 });
41 38 </script>
@@ -31,11 +31,8 @@ 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 verify URL returns 200 (and domain trust):
34 // Auto-print (browser protocol prompt is the consent gate):
35 // const url = await posprintUrl(pos, {
35 // const url = await posprintUrl(pos, { noconfirm: true });
36 // noconfirm: true,
37 // referrer: `https://${location.host}/api/posprint/verify?code=${code}`,
38 // });
39 window.location.href = url;
36 window.location.href = url;
40 });
37 });
41</script>
38</script>
lib/browser/posprint_url.js +1 −7
@@ -5,7 +5,7 @@
5 5 * Requires CompressionStream('deflate-raw') (modern browsers).
6 6 *
7 7 * @param {object|string} pos
8 * @param {{ noconfirm?: boolean, referrer?: string }} [options]
8 * @param {{ noconfirm?: boolean }} [options]
9 9 * @returns {Promise<string>}
10 10 */
11 11 export async function posprintUrl(pos, options = {}) {
@@ -21,12 +21,6 @@ export async function posprintUrl(pos, options = {}) {
21 21 if (options.noconfirm) {
22 22 url += '&noconfirm=1';
23 23 }
24 if (options.referrer) {
25 const ref = String(options.referrer).trim();
26 if (ref) {
27 url += `&referrer=${encodeURIComponent(ref)}`;
28 }
29 }
30 24 return url;
31 25 }
32 26
@@ -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, referrer?: string }} [options]
8 * @param {{ noconfirm?: boolean }} [options]
9 * @returns {Promise<string>}
9 * @returns {Promise<string>}
10 */
10 */
11export async function posprintUrl(pos, options = {}) {
11export async function posprintUrl(pos, options = {}) {
@@ -21,12 +21,6 @@ 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.referrer) {
25 const ref = String(options.referrer).trim();
26 if (ref) {
27 url += `&referrer=${encodeURIComponent(ref)}`;
28 }
29 }
30 return url;
24 return url;
31}
25}
32
26
lib/node/posprint_url.js +1 −7
@@ -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, referrer?: string }} [options]
11 * @param {{ noconfirm?: boolean }} [options]
12 12 * @returns {string}
13 13 */
14 14 function posprintUrl(pos, options = {}) {
@@ -19,12 +19,6 @@ function posprintUrl(pos, options = {}) {
19 19 if (options.noconfirm) {
20 20 url += '&noconfirm=1';
21 21 }
22 if (options.referrer) {
23 const ref = String(options.referrer).trim();
24 if (ref) {
25 url += `&referrer=${encodeURIComponent(ref)}`;
26 }
27 }
28 22 return url;
29 23 }
30 24
@@ -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, referrer?: string }} [options]
11 * @param {{ noconfirm?: boolean }} [options]
12 * @returns {string}
12 * @returns {string}
13 */
13 */
14function posprintUrl(pos, options = {}) {
14function posprintUrl(pos, options = {}) {
@@ -19,12 +19,6 @@ 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.referrer) {
23 const ref = String(options.referrer).trim();
24 if (ref) {
25 url += `&referrer=${encodeURIComponent(ref)}`;
26 }
27 }
28 return url;
22 return url;
29}
23}
30
24
lib/php/posprint_url.php +1 −7
@@ -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, referrer?: string} $options Optional URL flags
8 * @param array{noconfirm?: bool} $options Optional URL flags
9 9 * @return string posprint://print?v=1&d=…
10 10 * @throws InvalidArgumentException
11 11 */
@@ -33,12 +33,6 @@ function posprint_url($pos, array $options = []): string
33 33 if (!empty($options['noconfirm'])) {
34 34 $url .= '&noconfirm=1';
35 35 }
36 if (!empty($options['referrer'])) {
37 $ref = trim((string) $options['referrer']);
38 if ($ref !== '') {
39 $url .= '&referrer=' . rawurlencode($ref);
40 }
41 }
42 36
43 37 return $url;
44 38 }
@@ -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, referrer?: string} $options Optional URL flags
8 * @param array{noconfirm?: bool} $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,12 +33,6 @@ 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['referrer'])) {
37 $ref = trim((string) $options['referrer']);
38 if ($ref !== '') {
39 $url .= '&referrer=' . rawurlencode($ref);
40 }
41 }
42
36
43 return $url;
37 return $url;
44}
38}
scripts/test-noconfirm/README.md +8 −28
@@ -1,35 +1,15 @@
1 # Local noconfirm + referrer test
1 # Local noconfirm test
2 2
3 Docs: [docs/POSPRINT-URL.md](../../docs/POSPRINT-URL.md).
3 `noconfirm=1` auto-prints once printers are discovered (no referrer verify / trust dialog).
4 The browser’s “Open posprint?” prompt is the user consent gate.
4 5
5 Loopback (`127.0.0.1` / `localhost`) is allowed for referrer verification.
6
7 ## 1. Start the verify server
8
9 ```powershell
10 python scripts/test-noconfirm/server.py
11 ```
12
13 - `GET http://127.0.0.1:8765/verify?code=84923` → **200**
14 - `GET http://127.0.0.1:8765/verify?code=wrong` → **403**
15
16 ## 2. Build and open the test URL
6 ## Quick check
17 7
18 8 ```powershell
19 cargo build
20 9 $base = cargo run --quiet -- link examples/noconfirm-demo.pos
21 $ref = [uri]::EscapeDataString("http://127.0.0.1:8765/verify?code=84923")
22 $url = "$base&noconfirm=1&referrer=$ref"
23 $url
24 # Prefer the built GUI binary (no console flash):
25 Start-Process ".\target\debug\posprint.exe" $url
10 $url = "$base&noconfirm=1"
11 Write-Output $url
12 Start-Process ".\target\release\posprint.exe" $url
26 13 ```
27 14
28 First run: trust dialog for `127.0.0.1`. After **Trust and print**, the next open should print without asking (while the server still returns 200).
29
30 Bad code (should fail verification):
31
32 ```powershell
33 $refBad = [uri]::EscapeDataString("http://127.0.0.1:8765/verify?code=nope")
34 Start-Process ".\target\debug\posprint.exe" "$base&noconfirm=1&referrer=$refBad"
35 ```
15 With a connected printer that was used successfully before, print should start without confirmation inside posprint.
@@ -1,35 +1,15 @@
1# Local noconfirm + referrer test
1# Local noconfirm test
2
2
3Docs: [docs/POSPRINT-URL.md](../../docs/POSPRINT-URL.md).
3`noconfirm=1` auto-prints once printers are discovered (no referrer verify / trust dialog).
4The browser’s “Open posprint?” prompt is the user consent gate.
4
5
5Loopback (`127.0.0.1` / `localhost`) is allowed for referrer verification.
6## Quick check
6
7## 1. Start the verify server
8
9```powershell
10python scripts/test-noconfirm/server.py
11```
12
13- `GET http://127.0.0.1:8765/verify?code=84923` → **200**
14- `GET http://127.0.0.1:8765/verify?code=wrong` → **403**
15
16## 2. Build and open the test URL
17
7
18```powershell
8```powershell
19cargo build
20$base = cargo run --quiet -- link examples/noconfirm-demo.pos
9$base = cargo run --quiet -- link examples/noconfirm-demo.pos
21$ref = [uri]::EscapeDataString("http://127.0.0.1:8765/verify?code=84923")
10$url = "$base&noconfirm=1"
22$url = "$base&noconfirm=1&referrer=$ref"
11Write-Output $url
23$url
12Start-Process ".\target\release\posprint.exe" $url
24# Prefer the built GUI binary (no console flash):
25Start-Process ".\target\debug\posprint.exe" $url
26```
13```
27
14
28First run: trust dialog for `127.0.0.1`. After **Trust and print**, the next open should print without asking (while the server still returns 200).
15With a connected printer that was used successfully before, print should start without confirmation inside posprint.
29
30Bad code (should fail verification):
31
32```powershell
33$refBad = [uri]::EscapeDataString("http://127.0.0.1:8765/verify?code=nope")
34Start-Process ".\target\debug\posprint.exe" "$base&noconfirm=1&referrer=$refBad"
35```
scripts/test-noconfirm/server.py deleted +0 −56
@@ -1,56 +0,0 @@
1 #!/usr/bin/env python3
2 """Minimal verify server for local noconfirm testing.
3
4 GET /verify?code=84923 -> 200
5 GET /verify?code=other -> 403
6 GET anything else -> 404
7
8 Run:
9 python scripts/test-noconfirm/server.py
10 """
11
12 from __future__ import annotations
13
14 from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
15 from urllib.parse import parse_qs, urlparse
16
17 HOST = "127.0.0.1"
18 PORT = 8765
19 VALID_CODE = "84923"
20
21
22 class Handler(BaseHTTPRequestHandler):
23 def log_message(self, fmt: str, *args) -> None:
24 print(f"[verify] {self.address_string()} {fmt % args}")
25
26 def do_GET(self) -> None:
27 parsed = urlparse(self.path)
28 if parsed.path.rstrip("/") != "/verify":
29 self._reply(404, "not found")
30 return
31 code = parse_qs(parsed.query).get("code", [None])[0]
32 if code == VALID_CODE:
33 self._reply(200, "ok")
34 else:
35 self._reply(403, "invalid code")
36
37 def _reply(self, status: int, body: str) -> None:
38 data = body.encode("utf-8")
39 self.send_response(status)
40 self.send_header("Content-Type", "text/plain; charset=utf-8")
41 self.send_header("Content-Length", str(len(data)))
42 self.end_headers()
43 self.wfile.write(data)
44
45
46 def main() -> None:
47 server = ThreadingHTTPServer((HOST, PORT), Handler)
48 print(f"Listening on http://{HOST}:{PORT}")
49 print(f"Valid: http://{HOST}:{PORT}/verify?code={VALID_CODE} -> 200")
50 print(f"Invalid: http://{HOST}:{PORT}/verify?code=wrong -> 403")
51 print("Ctrl+C to stop")
52 server.serve_forever()
53
54
55 if __name__ == "__main__":
56 main()
@@ -1,56 +0,0 @@
1#!/usr/bin/env python3
2"""Minimal verify server for local noconfirm testing.
3
4GET /verify?code=84923 -> 200
5GET /verify?code=other -> 403
6GET anything else -> 404
7
8Run:
9 python scripts/test-noconfirm/server.py
10"""
11
12from __future__ import annotations
13
14from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
15from urllib.parse import parse_qs, urlparse
16
17HOST = "127.0.0.1"
18PORT = 8765
19VALID_CODE = "84923"
20
21
22class Handler(BaseHTTPRequestHandler):
23 def log_message(self, fmt: str, *args) -> None:
24 print(f"[verify] {self.address_string()} {fmt % args}")
25
26 def do_GET(self) -> None:
27 parsed = urlparse(self.path)
28 if parsed.path.rstrip("/") != "/verify":
29 self._reply(404, "not found")
30 return
31 code = parse_qs(parsed.query).get("code", [None])[0]
32 if code == VALID_CODE:
33 self._reply(200, "ok")
34 else:
35 self._reply(403, "invalid code")
36
37 def _reply(self, status: int, body: str) -> None:
38 data = body.encode("utf-8")
39 self.send_response(status)
40 self.send_header("Content-Type", "text/plain; charset=utf-8")
41 self.send_header("Content-Length", str(len(data)))
42 self.end_headers()
43 self.wfile.write(data)
44
45
46def main() -> None:
47 server = ThreadingHTTPServer((HOST, PORT), Handler)
48 print(f"Listening on http://{HOST}:{PORT}")
49 print(f"Valid: http://{HOST}:{PORT}/verify?code={VALID_CODE} -> 200")
50 print(f"Invalid: http://{HOST}:{PORT}/verify?code=wrong -> 403")
51 print("Ctrl+C to stop")
52 server.serve_forever()
53
54
55if __name__ == "__main__":
56 main()
src/app.rs +0 −38
@@ -132,44 +132,6 @@ impl PosPrintApp {
132 132 });
133 133 ui.label("Applies when you choose New. The current document width is unchanged.");
134 134
135 ui.add_space(16.0);
136 ui.heading("Trusted sites (noconfirm)");
137 ui.label(
138 "Sites listed here may use posprint://…&noconfirm=1&referrer=… after their verify URL returns HTTP 200.",
139 );
140
141 if self.config.trusted_origins.is_empty() {
142 ui.label("No trusted sites yet.");
143 } else {
144 let origins = self.config.trusted_origins.clone();
145 for origin in origins {
146 ui.horizontal(|ui| {
147 ui.label(&origin);
148 if ui.button("Revoke").clicked() {
149 self.config.revoke_origin(&origin);
150 match self.config.save() {
151 Ok(()) => {
152 self.settings_status =
153 Some(format!("Revoked trust for {origin}"))
154 }
155 Err(e) => {
156 self.settings_status = Some(format!("Save failed: {e}"))
157 }
158 }
159 }
160 });
161 }
162 if ui.button("Revoke all").clicked() {
163 self.config.trusted_origins.clear();
164 match self.config.save() {
165 Ok(()) => {
166 self.settings_status = Some("Cleared all trusted sites.".into())
167 }
168 Err(e) => self.settings_status = Some(format!("Save failed: {e}")),
169 }
170 }
171 }
172
173 135 ui.add_space(16.0);
174 136 if ui.button("Save settings").clicked() {
175 137 match self.config.save() {
@@ -132,44 +132,6 @@ impl PosPrintApp {
132 });
132 });
133 ui.label("Applies when you choose New. The current document width is unchanged.");
133 ui.label("Applies when you choose New. The current document width is unchanged.");
134
134
135 ui.add_space(16.0);
136 ui.heading("Trusted sites (noconfirm)");
137 ui.label(
138 "Sites listed here may use posprint://…&noconfirm=1&referrer=… after their verify URL returns HTTP 200.",
139 );
140
141 if self.config.trusted_origins.is_empty() {
142 ui.label("No trusted sites yet.");
143 } else {
144 let origins = self.config.trusted_origins.clone();
145 for origin in origins {
146 ui.horizontal(|ui| {
147 ui.label(&origin);
148 if ui.button("Revoke").clicked() {
149 self.config.revoke_origin(&origin);
150 match self.config.save() {
151 Ok(()) => {
152 self.settings_status =
153 Some(format!("Revoked trust for {origin}"))
154 }
155 Err(e) => {
156 self.settings_status = Some(format!("Save failed: {e}"))
157 }
158 }
159 }
160 });
161 }
162 if ui.button("Revoke all").clicked() {
163 self.config.trusted_origins.clear();
164 match self.config.save() {
165 Ok(()) => {
166 self.settings_status = Some("Cleared all trusted sites.".into())
167 }
168 Err(e) => self.settings_status = Some(format!("Save failed: {e}")),
169 }
170 }
171 }
172
173 ui.add_space(16.0);
135 ui.add_space(16.0);
174 if ui.button("Save settings").clicked() {
136 if ui.button("Save settings").clicked() {
175 match self.config.save() {
137 match self.config.save() {
src/config.rs +22 −90
@@ -1,4 +1,4 @@
1 //! Persisted app preferences (trusted URL origins, default page width).
1 //! Persisted app preferences (default page width, last printer).
2 2
3 3 use std::fs;
4 4 use std::path::PathBuf;
@@ -14,12 +14,12 @@ pub struct AppConfig {
14 14 /// Default paper width for **New** documents (mm).
15 15 #[serde(default = "default_page_width_mm")]
16 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 17 /// Last printer that printed successfully (`serial:…`, `winspool:…`, `usb:vid:pid`, or `manual:…`).
21 18 #[serde(default)]
22 19 pub last_printer_key: Option<String>,
20 /// Ignored legacy field from older configs (trusted noconfirm hosts).
21 #[serde(default, skip_serializing)]
22 trusted_origins: Vec<String>,
23 23 }
24 24
25 25 fn default_config_version() -> u32 {
@@ -35,8 +35,8 @@ impl Default for AppConfig {
35 35 Self {
36 36 version: CONFIG_VERSION,
37 37 default_page_width_mm: default_page_width_mm(),
38 trusted_origins: Vec::new(),
39 38 last_printer_key: None,
39 trusted_origins: Vec::new(),
40 40 }
41 41 }
42 42 }
@@ -73,31 +73,6 @@ impl AppConfig {
73 73 fs::write(path, json).map_err(|e| e.to_string())
74 74 }
75 75
76 pub fn is_trusted(&self, origin: &str) -> bool {
77 let Some(host) = normalize_origin(origin) else {
78 return false;
79 };
80 self.trusted_origins.iter().any(|o| o == &host)
81 }
82
83 pub fn trust_origin(&mut self, origin: &str) -> bool {
84 let Some(host) = normalize_origin(origin) else {
85 return false;
86 };
87 if !self.trusted_origins.iter().any(|o| o == &host) {
88 self.trusted_origins.push(host);
89 self.trusted_origins.sort();
90 }
91 true
92 }
93
94 pub fn revoke_origin(&mut self, origin: &str) {
95 let Some(host) = normalize_origin(origin) else {
96 return;
97 };
98 self.trusted_origins.retain(|o| o != &host);
99 }
100
101 76 pub fn remember_printer(&mut self, key: impl Into<String>) {
102 77 let key = key.into();
103 78 if key.is_empty() {
@@ -108,19 +83,12 @@ impl AppConfig {
108 83
109 84 fn normalize(&mut self) {
110 85 self.version = CONFIG_VERSION;
86 self.trusted_origins.clear();
111 87 if !self.default_page_width_mm.is_finite() || self.default_page_width_mm < 40.0 {
112 88 self.default_page_width_mm = 40.0;
113 89 } else if self.default_page_width_mm > 120.0 {
114 90 self.default_page_width_mm = 120.0;
115 91 }
116 let mut hosts: Vec<String> = self
117 .trusted_origins
118 .iter()
119 .filter_map(|o| normalize_origin(o))
120 .collect();
121 hosts.sort();
122 hosts.dedup();
123 self.trusted_origins = hosts;
124 92 if let Some(key) = &self.last_printer_key {
125 93 let trimmed = key.trim();
126 94 if trimmed.is_empty() {
@@ -154,73 +122,37 @@ pub fn config_path() -> PathBuf {
154 122 }
155 123 }
156 124
157 /// Normalize a caller-supplied origin to a lowercase hostname.
158 /// Accepts `example.com`, `https://example.com/path`, `http://localhost:3000`.
159 pub fn normalize_origin(raw: &str) -> Option<String> {
160 let s = raw.trim();
161 if s.is_empty() {
162 return None;
163 }
164 let without_scheme = s
165 .strip_prefix("https://")
166 .or_else(|| s.strip_prefix("http://"))
167 .or_else(|| s.strip_prefix("HTTPS://"))
168 .or_else(|| s.strip_prefix("HTTP://"))
169 .unwrap_or(s);
170 let host_port = without_scheme.split('/').next()?.trim();
171 if host_port.is_empty() {
172 return None;
173 }
174 // Drop port for trust matching (example.com:443 → example.com).
175 let host = host_port.split(':').next()?.trim();
176 if host.is_empty() {
177 return None;
178 }
179 Some(host.to_ascii_lowercase())
180 }
181
182 125 #[cfg(test)]
183 126 mod tests {
184 127 use super::*;
185 128
186 #[test]
187 fn normalize_strips_scheme_path_and_port() {
188 assert_eq!(
189 normalize_origin("https://Shop.Example.com/checkout").as_deref(),
190 Some("shop.example.com")
191 );
192 assert_eq!(
193 normalize_origin("http://localhost:5173/").as_deref(),
194 Some("localhost")
195 );
196 assert_eq!(normalize_origin("example.com").as_deref(), Some("example.com"));
197 assert_eq!(normalize_origin(" ").as_deref(), None);
198 }
199
200 #[test]
201 fn trust_and_revoke_roundtrip() {
202 let mut cfg = AppConfig::default();
203 assert!(!cfg.is_trusted("https://a.example"));
204 assert!(cfg.trust_origin("https://a.example/x"));
205 assert!(cfg.is_trusted("a.example"));
206 assert!(cfg.is_trusted("HTTPS://A.Example"));
207 cfg.revoke_origin("a.example");
208 assert!(!cfg.is_trusted("a.example"));
209 }
210
211 129 #[test]
212 130 fn save_load_roundtrip_in_temp_dir() {
213 131 let dir = tempfile::tempdir().unwrap();
214 132 let path = dir.path().join("posprint").join("config.json");
215 133 let mut cfg = AppConfig::default();
216 134 cfg.default_page_width_mm = 58.0;
217 cfg.trust_origin("pos.example");
218 135 cfg.remember_printer("winspool:POS-58");
219 136 cfg.save_to_path(&path).unwrap();
220 137
221 138 let loaded = AppConfig::load_from_path(&path);
222 139 assert_eq!(loaded.default_page_width_mm, 58.0);
223 assert!(loaded.is_trusted("pos.example"));
224 140 assert_eq!(loaded.last_printer_key.as_deref(), Some("winspool:POS-58"));
225 141 }
142
143 #[test]
144 fn loads_legacy_trusted_origins_without_keeping_them() {
145 let dir = tempfile::tempdir().unwrap();
146 let path = dir.path().join("config.json");
147 fs::write(
148 &path,
149 r#"{"version":1,"default_page_width_mm":80.0,"trusted_origins":["shop.example"],"last_printer_key":null}"#,
150 )
151 .unwrap();
152 let loaded = AppConfig::load_from_path(&path);
153 assert!(loaded.trusted_origins.is_empty());
154 loaded.save_to_path(&path).unwrap();
155 let text = fs::read_to_string(&path).unwrap();
156 assert!(!text.contains("trusted_origins"));
157 }
226 158 }
@@ -1,4 +1,4 @@
1//! Persisted app preferences (trusted URL origins, default page width).
1//! Persisted app preferences (default page width, last printer).
2
2
3use std::fs;
3use std::fs;
4use std::path::PathBuf;
4use std::path::PathBuf;
@@ -14,12 +14,12 @@ pub struct AppConfig {
14 /// Default paper width for **New** documents (mm).
14 /// Default paper width for **New** documents (mm).
15 #[serde(default = "default_page_width_mm")]
15 #[serde(default = "default_page_width_mm")]
16 pub default_page_width_mm: f32,
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 /// Last printer that printed successfully (`serial:…`, `winspool:…`, `usb:vid:pid`, or `manual:…`).
17 /// Last printer that printed successfully (`serial:…`, `winspool:…`, `usb:vid:pid`, or `manual:…`).
21 #[serde(default)]
18 #[serde(default)]
22 pub last_printer_key: Option<String>,
19 pub last_printer_key: Option<String>,
20 /// Ignored legacy field from older configs (trusted noconfirm hosts).
21 #[serde(default, skip_serializing)]
22 trusted_origins: Vec<String>,
23}
23}
24
24
25fn default_config_version() -> u32 {
25fn default_config_version() -> u32 {
@@ -35,8 +35,8 @@ impl Default for AppConfig {
35 Self {
35 Self {
36 version: CONFIG_VERSION,
36 version: CONFIG_VERSION,
37 default_page_width_mm: default_page_width_mm(),
37 default_page_width_mm: default_page_width_mm(),
38 trusted_origins: Vec::new(),
39 last_printer_key: None,
38 last_printer_key: None,
39 trusted_origins: Vec::new(),
40 }
40 }
41 }
41 }
42}
42}
@@ -73,31 +73,6 @@ impl AppConfig {
73 fs::write(path, json).map_err(|e| e.to_string())
73 fs::write(path, json).map_err(|e| e.to_string())
74 }
74 }
75
75
76 pub fn is_trusted(&self, origin: &str) -> bool {
77 let Some(host) = normalize_origin(origin) else {
78 return false;
79 };
80 self.trusted_origins.iter().any(|o| o == &host)
81 }
82
83 pub fn trust_origin(&mut self, origin: &str) -> bool {
84 let Some(host) = normalize_origin(origin) else {
85 return false;
86 };
87 if !self.trusted_origins.iter().any(|o| o == &host) {
88 self.trusted_origins.push(host);
89 self.trusted_origins.sort();
90 }
91 true
92 }
93
94 pub fn revoke_origin(&mut self, origin: &str) {
95 let Some(host) = normalize_origin(origin) else {
96 return;
97 };
98 self.trusted_origins.retain(|o| o != &host);
99 }
100
101 pub fn remember_printer(&mut self, key: impl Into<String>) {
76 pub fn remember_printer(&mut self, key: impl Into<String>) {
102 let key = key.into();
77 let key = key.into();
103 if key.is_empty() {
78 if key.is_empty() {
@@ -108,19 +83,12 @@ impl AppConfig {
108
83
109 fn normalize(&mut self) {
84 fn normalize(&mut self) {
110 self.version = CONFIG_VERSION;
85 self.version = CONFIG_VERSION;
86 self.trusted_origins.clear();
111 if !self.default_page_width_mm.is_finite() || self.default_page_width_mm < 40.0 {
87 if !self.default_page_width_mm.is_finite() || self.default_page_width_mm < 40.0 {
112 self.default_page_width_mm = 40.0;
88 self.default_page_width_mm = 40.0;
113 } else if self.default_page_width_mm > 120.0 {
89 } else if self.default_page_width_mm > 120.0 {
114 self.default_page_width_mm = 120.0;
90 self.default_page_width_mm = 120.0;
115 }
91 }
116 let mut hosts: Vec<String> = self
117 .trusted_origins
118 .iter()
119 .filter_map(|o| normalize_origin(o))
120 .collect();
121 hosts.sort();
122 hosts.dedup();
123 self.trusted_origins = hosts;
124 if let Some(key) = &self.last_printer_key {
92 if let Some(key) = &self.last_printer_key {
125 let trimmed = key.trim();
93 let trimmed = key.trim();
126 if trimmed.is_empty() {
94 if trimmed.is_empty() {
@@ -154,73 +122,37 @@ pub fn config_path() -> PathBuf {
154 }
122 }
155}
123}
156
124
157/// Normalize a caller-supplied origin to a lowercase hostname.
158/// Accepts `example.com`, `https://example.com/path`, `http://localhost:3000`.
159pub fn normalize_origin(raw: &str) -> Option<String> {
160 let s = raw.trim();
161 if s.is_empty() {
162 return None;
163 }
164 let without_scheme = s
165 .strip_prefix("https://")
166 .or_else(|| s.strip_prefix("http://"))
167 .or_else(|| s.strip_prefix("HTTPS://"))
168 .or_else(|| s.strip_prefix("HTTP://"))
169 .unwrap_or(s);
170 let host_port = without_scheme.split('/').next()?.trim();
171 if host_port.is_empty() {
172 return None;
173 }
174 // Drop port for trust matching (example.com:443 → example.com).
175 let host = host_port.split(':').next()?.trim();
176 if host.is_empty() {
177 return None;
178 }
179 Some(host.to_ascii_lowercase())
180}
181
182#[cfg(test)]
125#[cfg(test)]
183mod tests {
126mod tests {
184 use super::*;
127 use super::*;
185
128
186 #[test]
187 fn normalize_strips_scheme_path_and_port() {
188 assert_eq!(
189 normalize_origin("https://Shop.Example.com/checkout").as_deref(),
190 Some("shop.example.com")
191 );
192 assert_eq!(
193 normalize_origin("http://localhost:5173/").as_deref(),
194 Some("localhost")
195 );
196 assert_eq!(normalize_origin("example.com").as_deref(), Some("example.com"));
197 assert_eq!(normalize_origin(" ").as_deref(), None);
198 }
199
200 #[test]
201 fn trust_and_revoke_roundtrip() {
202 let mut cfg = AppConfig::default();
203 assert!(!cfg.is_trusted("https://a.example"));
204 assert!(cfg.trust_origin("https://a.example/x"));
205 assert!(cfg.is_trusted("a.example"));
206 assert!(cfg.is_trusted("HTTPS://A.Example"));
207 cfg.revoke_origin("a.example");
208 assert!(!cfg.is_trusted("a.example"));
209 }
210
211 #[test]
129 #[test]
212 fn save_load_roundtrip_in_temp_dir() {
130 fn save_load_roundtrip_in_temp_dir() {
213 let dir = tempfile::tempdir().unwrap();
131 let dir = tempfile::tempdir().unwrap();
214 let path = dir.path().join("posprint").join("config.json");
132 let path = dir.path().join("posprint").join("config.json");
215 let mut cfg = AppConfig::default();
133 let mut cfg = AppConfig::default();
216 cfg.default_page_width_mm = 58.0;
134 cfg.default_page_width_mm = 58.0;
217 cfg.trust_origin("pos.example");
218 cfg.remember_printer("winspool:POS-58");
135 cfg.remember_printer("winspool:POS-58");
219 cfg.save_to_path(&path).unwrap();
136 cfg.save_to_path(&path).unwrap();
220
137
221 let loaded = AppConfig::load_from_path(&path);
138 let loaded = AppConfig::load_from_path(&path);
222 assert_eq!(loaded.default_page_width_mm, 58.0);
139 assert_eq!(loaded.default_page_width_mm, 58.0);
223 assert!(loaded.is_trusted("pos.example"));
224 assert_eq!(loaded.last_printer_key.as_deref(), Some("winspool:POS-58"));
140 assert_eq!(loaded.last_printer_key.as_deref(), Some("winspool:POS-58"));
225 }
141 }
142
143 #[test]
144 fn loads_legacy_trusted_origins_without_keeping_them() {
145 let dir = tempfile::tempdir().unwrap();
146 let path = dir.path().join("config.json");
147 fs::write(
148 &path,
149 r#"{"version":1,"default_page_width_mm":80.0,"trusted_origins":["shop.example"],"last_printer_key":null}"#,
150 )
151 .unwrap();
152 let loaded = AppConfig::load_from_path(&path);
153 assert!(loaded.trusted_origins.is_empty());
154 loaded.save_to_path(&path).unwrap();
155 let text = fs::read_to_string(&path).unwrap();
156 assert!(!text.contains("trusted_origins"));
157 }
226}
158}
src/lib.rs +0 −1
@@ -14,7 +14,6 @@ pub mod preview;
14 14 pub mod print;
15 15 pub mod protocol_url;
16 16 pub mod raster;
17 pub mod referrer_verify;
18 17 pub mod text_wrap;
19 18 pub mod undo;
20 19
@@ -14,7 +14,6 @@ pub mod preview;
14pub mod print;
14pub mod print;
15pub mod protocol_url;
15pub mod protocol_url;
16pub mod raster;
16pub mod raster;
17pub mod referrer_verify;
18pub mod text_wrap;
17pub mod text_wrap;
19pub mod undo;
18pub mod undo;
20
19
src/print_only_app.rs +3 −114
@@ -1,14 +1,11 @@
1 1 //! Print dialog + live preview, then exit.
2 2
3 3 use std::path::PathBuf;
4 use std::sync::mpsc::{self, Receiver, TryRecvError};
5 4
6 5 use eframe::egui;
7 6
8 use posprint::config::AppConfig;
9 7 use posprint::io::{PosFile, PosMetadata};
10 8 use posprint::protocol_url::PosprintLaunch;
11 use posprint::referrer_verify;
12 9
13 10 use crate::preview_panel::show_preview_panel;
14 11 use crate::print_dialog::{PrintDialog, PrintDialogAction, PrintExecuteResult};
@@ -23,14 +20,9 @@ pub struct PrintOnlyApp {
23 20 preview_zoom: f32,
24 21 fatal_error: Option<String>,
25 22 exit_requested: bool,
26 /// Auto-print once printers are ready (after trust if needed).
23 /// Auto-print once printers are ready (`noconfirm=1`).
27 24 auto_print: bool,
28 /// Pending first-time trust confirmation for this hostname.
29 pending_trust: Option<String>,
30 25 auto_print_attempted: bool,
31 /// Background GET of `referrer=` for noconfirm.
32 referrer_rx: Option<Receiver<Result<String, String>>>,
33 verifying_referrer: bool,
34 26 }
35 27
36 28 impl PrintOnlyApp {
@@ -71,20 +63,8 @@ impl PrintOnlyApp {
71 63 .clone()
72 64 .unwrap_or_else(|| "posprint://".into());
73 65 let mut app = Self::from_pos_file(launch.file, label);
74 if !launch.noconfirm {
75 return app;
76 }
77
78 match launch.referrer {
79 None => {
80 app.fatal_error = Some(
81 "noconfirm=1 requires referrer=<https://host/path?…> so posprint can verify the print with that site."
82 .into(),
83 );
84 }
85 Some(referrer) => {
86 app.start_referrer_verification(referrer);
87 }
66 if launch.noconfirm {
67 app.auto_print = true;
88 68 }
89 69 app
90 70 }
@@ -107,49 +87,7 @@ impl PrintOnlyApp {
107 87 fatal_error: None,
108 88 exit_requested: false,
109 89 auto_print: false,
110 pending_trust: None,
111 90 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 }
153 91 }
154 92 }
155 93
@@ -197,57 +135,8 @@ impl eframe::App for PrintOnlyApp {
197 135 }
198 136
199 137 self.dialog.poll_printer_discovery(ctx);
200 self.poll_referrer_verification(ctx);
201 138 ctx.send_viewport_cmd(egui::ViewportCommand::Title(self.title()));
202 139
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
218 if let Some(origin) = self.pending_trust.clone() {
219 egui::CentralPanel::default().show(ctx, |ui| {
220 ui.heading("Trust this site?");
221 ui.separator();
222 ui.label(format!(
223 "“{origin}” verified this print request and wants to print without confirmation (noconfirm)."
224 ));
225 ui.label(
226 "If you trust this site, future verified noconfirm prints from this domain will not ask again.",
227 );
228 ui.add_space(12.0);
229 ui.horizontal(|ui| {
230 if ui.button("Trust and print").clicked() {
231 let mut cfg = AppConfig::load();
232 cfg.trust_origin(&origin);
233 if let Err(e) = cfg.save() {
234 self.fatal_error = Some(format!("Could not save trust setting: {e}"));
235 self.pending_trust = None;
236 } else {
237 self.pending_trust = None;
238 self.auto_print = true;
239 }
240 }
241 if ui.button("Cancel").clicked() {
242 self.request_exit();
243 }
244 });
245 ui.add_space(8.0);
246 ui.label("You can revoke trust later under Settings in the designer.");
247 });
248 return;
249 }
250
251 140 if let Some(err) = self.fatal_error.clone() {
252 141 egui::CentralPanel::default().show(ctx, |ui| {
253 142 ui.heading("Print");
@@ -1,14 +1,11 @@
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};
5
4
6use eframe::egui;
5use eframe::egui;
7
6
8use posprint::config::AppConfig;
9use posprint::io::{PosFile, PosMetadata};
7use posprint::io::{PosFile, PosMetadata};
10use posprint::protocol_url::PosprintLaunch;
8use posprint::protocol_url::PosprintLaunch;
11use posprint::referrer_verify;
12
9
13use crate::preview_panel::show_preview_panel;
10use crate::preview_panel::show_preview_panel;
14use crate::print_dialog::{PrintDialog, PrintDialogAction, PrintExecuteResult};
11use crate::print_dialog::{PrintDialog, PrintDialogAction, PrintExecuteResult};
@@ -23,14 +20,9 @@ pub struct PrintOnlyApp {
23 preview_zoom: f32,
20 preview_zoom: f32,
24 fatal_error: Option<String>,
21 fatal_error: Option<String>,
25 exit_requested: bool,
22 exit_requested: bool,
26 /// Auto-print once printers are ready (after trust if needed).
23 /// Auto-print once printers are ready (`noconfirm=1`).
27 auto_print: bool,
24 auto_print: bool,
28 /// Pending first-time trust confirmation for this hostname.
29 pending_trust: Option<String>,
30 auto_print_attempted: bool,
25 auto_print_attempted: bool,
31 /// Background GET of `referrer=` for noconfirm.
32 referrer_rx: Option<Receiver<Result<String, String>>>,
33 verifying_referrer: bool,
34}
26}
35
27
36impl PrintOnlyApp {
28impl PrintOnlyApp {
@@ -71,20 +63,8 @@ impl PrintOnlyApp {
71 .clone()
63 .clone()
72 .unwrap_or_else(|| "posprint://".into());
64 .unwrap_or_else(|| "posprint://".into());
73 let mut app = Self::from_pos_file(launch.file, label);
65 let mut app = Self::from_pos_file(launch.file, label);
74 if !launch.noconfirm {
66 if launch.noconfirm {
75 return app;
67 app.auto_print = true;
76 }
77
78 match launch.referrer {
79 None => {
80 app.fatal_error = Some(
81 "noconfirm=1 requires referrer=<https://host/path?…> so posprint can verify the print with that site."
82 .into(),
83 );
84 }
85 Some(referrer) => {
86 app.start_referrer_verification(referrer);
87 }
88 }
68 }
89 app
69 app
90 }
70 }
@@ -107,49 +87,7 @@ impl PrintOnlyApp {
107 fatal_error: None,
87 fatal_error: None,
108 exit_requested: false,
88 exit_requested: false,
109 auto_print: false,
89 auto_print: false,
110 pending_trust: None,
111 auto_print_attempted: false,
90 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 }
153 }
91 }
154 }
92 }
155
93
@@ -197,57 +135,8 @@ impl eframe::App for PrintOnlyApp {
197 }
135 }
198
136
199 self.dialog.poll_printer_discovery(ctx);
137 self.dialog.poll_printer_discovery(ctx);
200 self.poll_referrer_verification(ctx);
201 ctx.send_viewport_cmd(egui::ViewportCommand::Title(self.title()));
138 ctx.send_viewport_cmd(egui::ViewportCommand::Title(self.title()));
202
139
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
218 if let Some(origin) = self.pending_trust.clone() {
219 egui::CentralPanel::default().show(ctx, |ui| {
220 ui.heading("Trust this site?");
221 ui.separator();
222 ui.label(format!(
223 "“{origin}” verified this print request and wants to print without confirmation (noconfirm)."
224 ));
225 ui.label(
226 "If you trust this site, future verified noconfirm prints from this domain will not ask again.",
227 );
228 ui.add_space(12.0);
229 ui.horizontal(|ui| {
230 if ui.button("Trust and print").clicked() {
231 let mut cfg = AppConfig::load();
232 cfg.trust_origin(&origin);
233 if let Err(e) = cfg.save() {
234 self.fatal_error = Some(format!("Could not save trust setting: {e}"));
235 self.pending_trust = None;
236 } else {
237 self.pending_trust = None;
238 self.auto_print = true;
239 }
240 }
241 if ui.button("Cancel").clicked() {
242 self.request_exit();
243 }
244 });
245 ui.add_space(8.0);
246 ui.label("You can revoke trust later under Settings in the designer.");
247 });
248 return;
249 }
250
251 if let Some(err) = self.fatal_error.clone() {
140 if let Some(err) = self.fatal_error.clone() {
252 egui::CentralPanel::default().show(ctx, |ui| {
141 egui::CentralPanel::default().show(ctx, |ui| {
253 ui.heading("Print");
142 ui.heading("Print");
src/protocol_url.rs +9 −52
@@ -55,18 +55,14 @@ impl From<serde_json::Error> for ProtocolUrlError {
55 55 #[derive(Debug, Clone, PartialEq)]
56 56 pub struct PosprintLaunch {
57 57 pub file: PosFile,
58 /// When true, print without waiting for the Print button (subject to referrer verify + trust).
58 /// When true, print without waiting for the Print button.
59 59 pub noconfirm: bool,
60 /// Verification URL from `referrer=` (percent-decoded; may be scheme-less).
61 pub referrer: Option<String>,
62 60 }
63 61
64 62 /// Optional extras when encoding a URL.
65 63 #[derive(Debug, Clone, Default)]
66 64 pub struct EncodeOptions {
67 65 pub noconfirm: bool,
68 /// Full verification URL or `host/path?query` (stored percent-encoded in the posprint URL).
69 pub referrer: Option<String>,
70 66 }
71 67
72 68 /// True when `s` looks like a `posprint:` / `posprint://` protocol URL.
@@ -81,7 +77,7 @@ pub fn encode_posprint_url(file: &PosFile) -> Result<String, ProtocolUrlError> {
81 77 encode_posprint_url_with_options(file, &EncodeOptions::default())
82 78 }
83 79
84 /// Encode with optional `noconfirm` / `referrer` query parameters.
80 /// Encode with optional `noconfirm` query parameter.
85 81 pub fn encode_posprint_url_with_options(
86 82 file: &PosFile,
87 83 options: &EncodeOptions,
@@ -99,13 +95,6 @@ pub fn encode_posprint_url_with_options(
99 95 if options.noconfirm {
100 96 url.push_str("&noconfirm=1");
101 97 }
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 98 Ok(url)
110 99 }
111 100
@@ -136,7 +125,6 @@ pub fn parse_posprint_url(url: &str) -> Result<PosprintLaunch, ProtocolUrlError>
136 125 let mut version: Option<String> = None;
137 126 let mut payload: Option<String> = None;
138 127 let mut noconfirm = false;
139 let mut referrer: Option<String> = None;
140 128 for pair in query.split('&') {
141 129 if pair.is_empty() {
142 130 continue;
@@ -147,12 +135,8 @@ pub fn parse_posprint_url(url: &str) -> Result<PosprintLaunch, ProtocolUrlError>
147 135 "v" => version = Some(percent_decode_str(value)?),
148 136 "d" => payload = Some(percent_decode_str(value)?),
149 137 "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 }
138 // Legacy `referrer=` is ignored (browser protocol prompt is the trust gate).
139 "referrer" => {}
156 140 _ => {}
157 141 }
158 142 }
@@ -178,11 +162,7 @@ pub fn parse_posprint_url(url: &str) -> Result<PosprintLaunch, ProtocolUrlError>
178 162 return Err(ProtocolUrlError::UnsupportedPosVersion(file.version));
179 163 }
180 164
181 Ok(PosprintLaunch {
182 file,
183 noconfirm,
184 referrer,
185 })
165 Ok(PosprintLaunch { file, noconfirm })
186 166 }
187 167
188 168 fn parse_bool_flag(value: &str) -> bool {
@@ -196,19 +176,6 @@ fn parse_bool_flag(value: &str) -> bool {
196 176 )
197 177 }
198 178
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 179 fn percent_decode_str(input: &str) -> Result<String, ProtocolUrlError> {
213 180 let bytes = percent_decode_bytes(input.as_bytes())?;
214 181 String::from_utf8(bytes).map_err(|e| ProtocolUrlError::InvalidEncoding(e.to_string()))
@@ -281,39 +248,29 @@ mod tests {
281 248 let decoded = parse_posprint_url(&url).unwrap();
282 249 assert_eq!(decoded.file, file);
283 250 assert!(!decoded.noconfirm);
284 assert!(decoded.referrer.is_none());
285 251 }
286 252
287 253 #[test]
288 fn encodes_and_parses_noconfirm_and_referrer() {
254 fn encodes_and_parses_noconfirm() {
289 255 let file = sample_file();
290 256 let url = encode_posprint_url_with_options(
291 257 &file,
292 &EncodeOptions {
293 noconfirm: true,
294 referrer: Some("website.com/bonnen/verify?code=84923".into()),
295 },
258 &EncodeOptions { noconfirm: true },
296 259 )
297 260 .unwrap();
298 261 assert!(url.contains("&noconfirm=1"));
299 assert!(url.contains("&referrer="));
300 assert!(url.contains("code%3D84923") || url.contains("code%3d84923"));
262 assert!(!url.contains("referrer"));
301 263 let launch = parse_posprint_url(&url).unwrap();
302 264 assert!(launch.noconfirm);
303 assert_eq!(
304 launch.referrer.as_deref(),
305 Some("website.com/bonnen/verify?code=84923")
306 );
307 265 }
308 266
309 267 #[test]
310 fn parses_noconfirm_without_value() {
268 fn parses_noconfirm_and_ignores_legacy_referrer() {
311 269 let file = sample_file();
312 270 let base = encode_posprint_url(&file).unwrap();
313 271 let url = format!("{base}&noconfirm&referrer=shop.example%2Fv");
314 272 let launch = parse_posprint_url(&url).unwrap();
315 273 assert!(launch.noconfirm);
316 assert_eq!(launch.referrer.as_deref(), Some("shop.example/v"));
317 274 }
318 275
319 276 #[test]
@@ -55,18 +55,14 @@ impl From<serde_json::Error> for ProtocolUrlError {
55#[derive(Debug, Clone, PartialEq)]
55#[derive(Debug, Clone, PartialEq)]
56pub struct PosprintLaunch {
56pub struct PosprintLaunch {
57 pub file: PosFile,
57 pub file: PosFile,
58 /// When true, print without waiting for the Print button (subject to referrer verify + trust).
58 /// When true, print without waiting for the Print button.
59 pub noconfirm: bool,
59 pub noconfirm: bool,
60 /// Verification URL from `referrer=` (percent-decoded; may be scheme-less).
61 pub referrer: Option<String>,
62}
60}
63
61
64/// Optional extras when encoding a URL.
62/// Optional extras when encoding a URL.
65#[derive(Debug, Clone, Default)]
63#[derive(Debug, Clone, Default)]
66pub struct EncodeOptions {
64pub struct EncodeOptions {
67 pub noconfirm: bool,
65 pub noconfirm: bool,
68 /// Full verification URL or `host/path?query` (stored percent-encoded in the posprint URL).
69 pub referrer: Option<String>,
70}
66}
71
67
72/// True when `s` looks like a `posprint:` / `posprint://` protocol URL.
68/// True when `s` looks like a `posprint:` / `posprint://` protocol URL.
@@ -81,7 +77,7 @@ pub fn encode_posprint_url(file: &PosFile) -> Result<String, ProtocolUrlError> {
81 encode_posprint_url_with_options(file, &EncodeOptions::default())
77 encode_posprint_url_with_options(file, &EncodeOptions::default())
82}
78}
83
79
84/// Encode with optional `noconfirm` / `referrer` query parameters.
80/// Encode with optional `noconfirm` query parameter.
85pub fn encode_posprint_url_with_options(
81pub fn encode_posprint_url_with_options(
86 file: &PosFile,
82 file: &PosFile,
87 options: &EncodeOptions,
83 options: &EncodeOptions,
@@ -99,13 +95,6 @@ pub fn encode_posprint_url_with_options(
99 if options.noconfirm {
95 if options.noconfirm {
100 url.push_str("&noconfirm=1");
96 url.push_str("&noconfirm=1");
101 }
97 }
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)
98 Ok(url)
110}
99}
111
100
@@ -136,7 +125,6 @@ pub fn parse_posprint_url(url: &str) -> Result<PosprintLaunch, ProtocolUrlError>
136 let mut version: Option<String> = None;
125 let mut version: Option<String> = None;
137 let mut payload: Option<String> = None;
126 let mut payload: Option<String> = None;
138 let mut noconfirm = false;
127 let mut noconfirm = false;
139 let mut referrer: Option<String> = None;
140 for pair in query.split('&') {
128 for pair in query.split('&') {
141 if pair.is_empty() {
129 if pair.is_empty() {
142 continue;
130 continue;
@@ -147,12 +135,8 @@ pub fn parse_posprint_url(url: &str) -> Result<PosprintLaunch, ProtocolUrlError>
147 "v" => version = Some(percent_decode_str(value)?),
135 "v" => version = Some(percent_decode_str(value)?),
148 "d" => payload = Some(percent_decode_str(value)?),
136 "d" => payload = Some(percent_decode_str(value)?),
149 "noconfirm" => noconfirm = parse_bool_flag(value),
137 "noconfirm" => noconfirm = parse_bool_flag(value),
150 "referrer" => {
138 // Legacy `referrer=` is ignored (browser protocol prompt is the trust gate).
151 let decoded = percent_decode_str(value)?;
139 "referrer" => {}
152 if !decoded.trim().is_empty() {
153 referrer = Some(decoded);
154 }
155 }
156 _ => {}
140 _ => {}
157 }
141 }
158 }
142 }
@@ -178,11 +162,7 @@ pub fn parse_posprint_url(url: &str) -> Result<PosprintLaunch, ProtocolUrlError>
178 return Err(ProtocolUrlError::UnsupportedPosVersion(file.version));
162 return Err(ProtocolUrlError::UnsupportedPosVersion(file.version));
179 }
163 }
180
164
181 Ok(PosprintLaunch {
165 Ok(PosprintLaunch { file, noconfirm })
182 file,
183 noconfirm,
184 referrer,
185 })
186}
166}
187
167
188fn parse_bool_flag(value: &str) -> bool {
168fn parse_bool_flag(value: &str) -> bool {
@@ -196,19 +176,6 @@ fn parse_bool_flag(value: &str) -> bool {
196 )
176 )
197}
177}
198
178
199fn 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
212fn percent_decode_str(input: &str) -> Result<String, ProtocolUrlError> {
179fn percent_decode_str(input: &str) -> Result<String, ProtocolUrlError> {
213 let bytes = percent_decode_bytes(input.as_bytes())?;
180 let bytes = percent_decode_bytes(input.as_bytes())?;
214 String::from_utf8(bytes).map_err(|e| ProtocolUrlError::InvalidEncoding(e.to_string()))
181 String::from_utf8(bytes).map_err(|e| ProtocolUrlError::InvalidEncoding(e.to_string()))
@@ -281,39 +248,29 @@ mod tests {
281 let decoded = parse_posprint_url(&url).unwrap();
248 let decoded = parse_posprint_url(&url).unwrap();
282 assert_eq!(decoded.file, file);
249 assert_eq!(decoded.file, file);
283 assert!(!decoded.noconfirm);
250 assert!(!decoded.noconfirm);
284 assert!(decoded.referrer.is_none());
285 }
251 }
286
252
287 #[test]
253 #[test]
288 fn encodes_and_parses_noconfirm_and_referrer() {
254 fn encodes_and_parses_noconfirm() {
289 let file = sample_file();
255 let file = sample_file();
290 let url = encode_posprint_url_with_options(
256 let url = encode_posprint_url_with_options(
291 &file,
257 &file,
292 &EncodeOptions {
258 &EncodeOptions { noconfirm: true },
293 noconfirm: true,
294 referrer: Some("website.com/bonnen/verify?code=84923".into()),
295 },
296 )
259 )
297 .unwrap();
260 .unwrap();
298 assert!(url.contains("&noconfirm=1"));
261 assert!(url.contains("&noconfirm=1"));
299 assert!(url.contains("&referrer="));
262 assert!(!url.contains("referrer"));
300 assert!(url.contains("code%3D84923") || url.contains("code%3d84923"));
301 let launch = parse_posprint_url(&url).unwrap();
263 let launch = parse_posprint_url(&url).unwrap();
302 assert!(launch.noconfirm);
264 assert!(launch.noconfirm);
303 assert_eq!(
304 launch.referrer.as_deref(),
305 Some("website.com/bonnen/verify?code=84923")
306 );
307 }
265 }
308
266
309 #[test]
267 #[test]
310 fn parses_noconfirm_without_value() {
268 fn parses_noconfirm_and_ignores_legacy_referrer() {
311 let file = sample_file();
269 let file = sample_file();
312 let base = encode_posprint_url(&file).unwrap();
270 let base = encode_posprint_url(&file).unwrap();
313 let url = format!("{base}&noconfirm&referrer=shop.example%2Fv");
271 let url = format!("{base}&noconfirm&referrer=shop.example%2Fv");
314 let launch = parse_posprint_url(&url).unwrap();
272 let launch = parse_posprint_url(&url).unwrap();
315 assert!(launch.noconfirm);
273 assert!(launch.noconfirm);
316 assert_eq!(launch.referrer.as_deref(), Some("shop.example/v"));
317 }
274 }
318
275
319 #[test]
276 #[test]
src/referrer_verify.rs deleted +0 −176
@@ -1,176 +0,0 @@
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 // Loopback is allowed (local verify servers / dev). Block other private LAN hosts.
93 if h == "localhost" || h.ends_with(".localhost") {
94 return false;
95 }
96 if let Ok(ip) = h.parse::<IpAddr>() {
97 return match ip {
98 IpAddr::V4(v4) => {
99 !v4.is_loopback()
100 && (v4.is_private() || v4.is_link_local() || v4.is_unspecified())
101 }
102 IpAddr::V6(v6) => !v6.is_loopback() && v6.is_unspecified(),
103 };
104 }
105 false
106 }
107
108 /// True when an HTTP status means the print request is authorized by the site.
109 pub fn is_verification_success(status: u16) -> bool {
110 status == 200
111 }
112
113 /// GET `referrer_url` (no redirects). On HTTP 200 returns the trust hostname.
114 pub fn verify_referrer(referrer_url: &str) -> Result<String, ReferrerVerifyError> {
115 let url = normalize_referrer_url(referrer_url)?;
116 let host = referrer_trust_host(&url)
117 .ok_or_else(|| ReferrerVerifyError::InvalidUrl("missing host".into()))?;
118
119 let agent = ureq::AgentBuilder::new()
120 .timeout_connect(Duration::from_secs(VERIFY_TIMEOUT_SECS))
121 .timeout_read(Duration::from_secs(VERIFY_TIMEOUT_SECS))
122 .redirects(0)
123 .build();
124
125 let response = agent.get(&url).call().map_err(|e| match e {
126 ureq::Error::Status(code, _) => ReferrerVerifyError::HttpStatus(code),
127 other => ReferrerVerifyError::Network(other.to_string()),
128 })?;
129
130 let status = response.status();
131 if !is_verification_success(status) {
132 return Err(ReferrerVerifyError::HttpStatus(status));
133 }
134 Ok(host)
135 }
136
137 #[cfg(test)]
138 mod tests {
139 use super::*;
140
141 #[test]
142 fn normalizes_bare_host_path_to_https() {
143 let url = normalize_referrer_url("website.com/bonnen/verify?code=84923").unwrap();
144 assert_eq!(url, "https://website.com/bonnen/verify?code=84923");
145 assert_eq!(referrer_trust_host(&url).as_deref(), Some("website.com"));
146 }
147
148 #[test]
149 fn rejects_non_http_schemes() {
150 let err = normalize_referrer_url("file:///etc/passwd").unwrap_err();
151 assert!(matches!(err, ReferrerVerifyError::UnsupportedScheme(_)));
152 }
153
154 #[test]
155 fn allows_loopback_hosts() {
156 let url = normalize_referrer_url("http://127.0.0.1:8765/verify?code=1").unwrap();
157 assert_eq!(url, "http://127.0.0.1:8765/verify?code=1");
158 assert!(normalize_referrer_url("http://localhost/verify").is_ok());
159 }
160
161 #[test]
162 fn blocks_private_lan_hosts() {
163 let err = normalize_referrer_url("http://192.168.1.10/verify").unwrap_err();
164 assert!(matches!(err, ReferrerVerifyError::BlockedHost(_)));
165 let err = normalize_referrer_url("http://10.0.0.5/x").unwrap_err();
166 assert!(matches!(err, ReferrerVerifyError::BlockedHost(_)));
167 }
168
169 #[test]
170 fn only_http_200_counts_as_success() {
171 assert!(is_verification_success(200));
172 assert!(!is_verification_success(204));
173 assert!(!is_verification_success(404));
174 assert!(!is_verification_success(302));
175 }
176 }
@@ -1,176 +0,0 @@
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 // Loopback is allowed (local verify servers / dev). Block other private LAN hosts.
93 if h == "localhost" || h.ends_with(".localhost") {
94 return false;
95 }
96 if let Ok(ip) = h.parse::<IpAddr>() {
97 return match ip {
98 IpAddr::V4(v4) => {
99 !v4.is_loopback()
100 && (v4.is_private() || v4.is_link_local() || v4.is_unspecified())
101 }
102 IpAddr::V6(v6) => !v6.is_loopback() && v6.is_unspecified(),
103 };
104 }
105 false
106}
107
108/// True when an HTTP status means the print request is authorized by the site.
109pub fn is_verification_success(status: u16) -> bool {
110 status == 200
111}
112
113/// GET `referrer_url` (no redirects). On HTTP 200 returns the trust hostname.
114pub fn verify_referrer(referrer_url: &str) -> Result<String, ReferrerVerifyError> {
115 let url = normalize_referrer_url(referrer_url)?;
116 let host = referrer_trust_host(&url)
117 .ok_or_else(|| ReferrerVerifyError::InvalidUrl("missing host".into()))?;
118
119 let agent = ureq::AgentBuilder::new()
120 .timeout_connect(Duration::from_secs(VERIFY_TIMEOUT_SECS))
121 .timeout_read(Duration::from_secs(VERIFY_TIMEOUT_SECS))
122 .redirects(0)
123 .build();
124
125 let response = agent.get(&url).call().map_err(|e| match e {
126 ureq::Error::Status(code, _) => ReferrerVerifyError::HttpStatus(code),
127 other => ReferrerVerifyError::Network(other.to_string()),
128 })?;
129
130 let status = response.status();
131 if !is_verification_success(status) {
132 return Err(ReferrerVerifyError::HttpStatus(status));
133 }
134 Ok(host)
135}
136
137#[cfg(test)]
138mod tests {
139 use super::*;
140
141 #[test]
142 fn normalizes_bare_host_path_to_https() {
143 let url = normalize_referrer_url("website.com/bonnen/verify?code=84923").unwrap();
144 assert_eq!(url, "https://website.com/bonnen/verify?code=84923");
145 assert_eq!(referrer_trust_host(&url).as_deref(), Some("website.com"));
146 }
147
148 #[test]
149 fn rejects_non_http_schemes() {
150 let err = normalize_referrer_url("file:///etc/passwd").unwrap_err();
151 assert!(matches!(err, ReferrerVerifyError::UnsupportedScheme(_)));
152 }
153
154 #[test]
155 fn allows_loopback_hosts() {
156 let url = normalize_referrer_url("http://127.0.0.1:8765/verify?code=1").unwrap();
157 assert_eq!(url, "http://127.0.0.1:8765/verify?code=1");
158 assert!(normalize_referrer_url("http://localhost/verify").is_ok());
159 }
160
161 #[test]
162 fn blocks_private_lan_hosts() {
163 let err = normalize_referrer_url("http://192.168.1.10/verify").unwrap_err();
164 assert!(matches!(err, ReferrerVerifyError::BlockedHost(_)));
165 let err = normalize_referrer_url("http://10.0.0.5/x").unwrap_err();
166 assert!(matches!(err, ReferrerVerifyError::BlockedHost(_)));
167 }
168
169 #[test]
170 fn only_http_200_counts_as_success() {
171 assert!(is_verification_success(200));
172 assert!(!is_verification_success(204));
173 assert!(!is_verification_success(404));
174 assert!(!is_verification_success(302));
175 }
176}