Merge branch 'feature/noconfirm-trusted-domains'
@@ -7,7 +7,7 @@ posprint is a **single Rust binary** using **egui** (eframe). No separate fronte
7
7
```
8
8
┌──────────────────────────────────────────────────┐
9
9
│ posprint (Rust + egui) │
10
│ - Design (editor + preview) / Help │
10
│ - Design / Help / Settings │
11
11
│ - DSL parse → AST → preview + ESC/POS │
12
12
│ - USB-direct / Win spooler / serial printing │
13
13
│ - `.pos` JSON load/save (serde) │
@@ -33,6 +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
├── referrer_verify.rs # noconfirm referrer GET (HTTP 200)
36
37
├── editor_assist.rs # @ autocomplete, Insert snippets
37
38
├── help_view.rs # Markdown help renderer
38
39
├── io/mod.rs # PosFile, PosMetadata
@@ -71,9 +72,11 @@ ESC/POS generation is **in-tree** (`escpos.rs`), not the `escpos` crates.io pack
71
72
|------|--------|-------------|
72
73
| **Design** | `app.rs` | Editor + side preview |
73
74
| **Help** | `help_view.rs` | `docs/HELP.md` via `include_str!` |
75
| **Settings** | `app.rs` | Default page width; trusted `noconfirm` origins |
74
76
| Toolbar | `app.rs` | New, Open, Save, Save As, Insert, Print |
75
| Settings | `app.rs` | Page width (mm), preview zoom |
77
| Document page width / zoom | `app.rs` | Per-document width (mm), preview zoom |
76
78
| Print dialog | `print_dialog.rs` | Parameters + multi-transport printer picker |
79
| App config | `config.rs` | `%APPDATA%/posprint/config.json` (Windows) / `~/.config/posprint/config.json` |
77
80
78
81
While the print dialog is open, the main UI is disabled and editor autocomplete does not steal focus.
79
82
@@ -152,6 +155,7 @@ Legacy JSON fields `preview_mode` and `cut_after_print` are ignored if present.
152
155
|------|---------|
153
156
| Template + metadata | `.pos` file |
154
157
| Last parameter values | In-memory (`print_dialog.last_params`) |
158
| Default page width / trusted origins | `config.rs` → platform config JSON |
155
159
| Recent files / selected printer | Not persisted |
156
160
157
161
---
@@ -7,7 +7,7 @@ posprint is a **single Rust binary** using **egui** (eframe). No separate fronte7
```7
```8
┌──────────────────────────────────────────────────┐8
┌──────────────────────────────────────────────────┐9
│ posprint (Rust + egui) │9
│ posprint (Rust + egui) │10
│ - Design (editor + preview) / Help │10
│ - Design / Help / Settings │11
│ - DSL parse → AST → preview + ESC/POS │11
│ - DSL parse → AST → preview + ESC/POS │12
│ - USB-direct / Win spooler / serial printing │12
│ - USB-direct / Win spooler / serial printing │13
│ - `.pos` JSON load/save (serde) │13
│ - `.pos` JSON load/save (serde) │@@ -33,6 +33,7 @@ src/33
├── raster.rs # Barcode / QR bitmaps33
├── raster.rs # Barcode / QR bitmaps34
├── image_load.rs # Local + http(s) @image loading34
├── image_load.rs # Local + http(s) @image loading35
├── protocol_url.rs # posprint:// encode/decode35
├── protocol_url.rs # posprint:// encode/decode36
├── referrer_verify.rs # noconfirm referrer GET (HTTP 200)36
├── editor_assist.rs # @ autocomplete, Insert snippets37
├── editor_assist.rs # @ autocomplete, Insert snippets37
├── help_view.rs # Markdown help renderer38
├── help_view.rs # Markdown help renderer38
├── io/mod.rs # PosFile, PosMetadata39
├── io/mod.rs # PosFile, PosMetadata@@ -71,9 +72,11 @@ ESC/POS generation is **in-tree** (`escpos.rs`), not the `escpos` crates.io pack71
|------|--------|-------------|72
|------|--------|-------------|72
| **Design** | `app.rs` | Editor + side preview |73
| **Design** | `app.rs` | Editor + side preview |73
| **Help** | `help_view.rs` | `docs/HELP.md` via `include_str!` |74
| **Help** | `help_view.rs` | `docs/HELP.md` via `include_str!` |75
| **Settings** | `app.rs` | Default page width; trusted `noconfirm` origins |74
| Toolbar | `app.rs` | New, Open, Save, Save As, Insert, Print |76
| Toolbar | `app.rs` | New, Open, Save, Save As, Insert, Print |75
| Settings | `app.rs` | Page width (mm), preview zoom |77
| Document page width / zoom | `app.rs` | Per-document width (mm), preview zoom |76
| Print dialog | `print_dialog.rs` | Parameters + multi-transport printer picker |78
| Print dialog | `print_dialog.rs` | Parameters + multi-transport printer picker |79
| App config | `config.rs` | `%APPDATA%/posprint/config.json` (Windows) / `~/.config/posprint/config.json` |77
80
78
While the print dialog is open, the main UI is disabled and editor autocomplete does not steal focus.81
While the print dialog is open, the main UI is disabled and editor autocomplete does not steal focus.79
82
@@ -152,6 +155,7 @@ Legacy JSON fields `preview_mode` and `cut_after_print` are ignored if present.152
|------|---------|155
|------|---------|153
| Template + metadata | `.pos` file |156
| Template + metadata | `.pos` file |154
| Last parameter values | In-memory (`print_dialog.last_params`) |157
| Last parameter values | In-memory (`print_dialog.last_params`) |158
| Default page width / trusted origins | `config.rs` → platform config JSON |155
| Recent files / selected printer | Not persisted |159
| Recent files / selected printer | Not persisted |156
160
157
---161
---@@ -10,6 +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
14
14
15
## Toolbar actions
15
16
@@ -308,7 +309,7 @@ Websites can open the print dialog with an embedded template:
308
309
posprint://print?v=1&d=…
309
310
```
310
311
311
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).
312
313
313
314
`@image` may use `https://…` or `http://…` (downloaded when preview/print needs the image).
314
315
@@ -10,6 +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
14
14
## Toolbar actions15
## Toolbar actions15
16
@@ -308,7 +309,7 @@ Websites can open the print dialog with an embedded template:308
posprint://print?v=1&d=…309
posprint://print?v=1&d=…309
```310
```310
311
311
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).312
313
313
`@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).314
315
@@ -12,17 +12,46 @@ Full reference: create URLs from PHP, Node.js, or browser JavaScript using the h
12
12
posprint://print?v=1&d=<BASE64URL(raw_deflate(utf8(.pos JSON)))>
13
13
```
14
14
15
Optional auto-print:
16
17
```
18
posprint://print?v=1&d=…&noconfirm=1&referrer=website.com%2Fbonnen%2Fverify%3Fcode%3D84923
19
```
20
15
21
| Part | Meaning |
16
22
|------|---------|
17
23
| `posprint://` | Custom protocol (registered on install / first run) |
18
24
| `print` | Open the print-only dialog (same UX as `posprint --print`) |
19
25
| `v=1` | URL payload version |
20
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) |
21
29
22
**Parameters are not in the URL.** The user fills `${Name}` / `$[Name]` in the dialog.
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`.
23
31
24
32
**Images:** keep logos out of the URL. Use `@image https://…` (or `http://…`) in the template body; posprint downloads them when needed.
25
33
34
### Auto-print (`noconfirm`) and referrer verification
35
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** |
50
51
Without `referrer`, `noconfirm=1` is rejected. Without `noconfirm`, behaviour is unchanged (interactive print dialog).
52
53
Localhost / private IP verification URLs are blocked by default. For local harnesses only, set `POSPRINT_ALLOW_LOCAL_REFERRER=1` (see `scripts/test-noconfirm/`).
54
26
55
---
27
56
28
57
## Size limits
@@ -68,6 +97,11 @@ $url = posprint_url([
68
97
'metadata' => ['page_width_mm' => 53, 'chars_per_line' => 32],
69
98
'body' => "@barcode RASTER CODE128 \${data}\nHello\n@cut\n",
70
99
]);
100
// Auto-print: site must expose a verify URL that returns HTTP 200 for this code:
101
$auto = posprint_url($pos, [
102
'noconfirm' => true,
103
'referrer' => 'https://shop.example.com/bonnen/verify?code=' . urlencode($code),
104
]);
71
105
// <a href="<?= htmlspecialchars($url) ?>">Print</a>
72
106
```
73
107
@@ -81,6 +115,11 @@ const url = posprintUrl({
81
115
metadata: { page_width_mm: 53, chars_per_line: 32 },
82
116
body: '@barcode RASTER CODE128 ${data}\nHello\n@cut\n',
83
117
});
118
119
const auto = posprintUrl(pos, {
120
noconfirm: true,
121
referrer: `https://shop.example.com/bonnen/verify?code=${encodeURIComponent(code)}`,
122
});
84
123
```
85
124
86
125
#### Browser
@@ -93,7 +132,11 @@ const url = posprintUrl({
93
132
metadata: { page_width_mm: 53 },
94
133
body: '@barcode RASTER CODE128 ${data}\nHello\n@cut\n',
95
134
});
96
location.href = url;
135
const auto = await posprintUrl(pos, {
136
noconfirm: true,
137
referrer: `https://${location.host}/bonnen/verify?code=${encodeURIComponent(code)}`,
138
});
139
location.href = auto;
97
140
</script>
98
141
```
99
142
@@ -12,17 +12,46 @@ Full reference: create URLs from PHP, Node.js, or browser JavaScript using the h12
posprint://print?v=1&d=<BASE64URL(raw_deflate(utf8(.pos JSON)))>12
posprint://print?v=1&d=<BASE64URL(raw_deflate(utf8(.pos JSON)))>13
```13
```14
14
15
Optional auto-print:16
17
```18
posprint://print?v=1&d=…&noconfirm=1&referrer=website.com%2Fbonnen%2Fverify%3Fcode%3D8492319
```20
15
| Part | Meaning |21
| Part | Meaning |16
|------|---------|22
|------|---------|17
| `posprint://` | Custom protocol (registered on install / first run) |23
| `posprint://` | Custom protocol (registered on install / first run) |18
| `print` | Open the print-only dialog (same UX as `posprint --print`) |24
| `print` | Open the print-only dialog (same UX as `posprint --print`) |19
| `v=1` | URL payload version |25
| `v=1` | URL payload version |20
| `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) |28
| `referrer=` | **Percent-encoded** verification URL on the issuer’s domain (see below) |21
29
22
**Parameters are not in the URL.** The user fills `${Name}` / `$[Name]` in the dialog.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`.23
31
24
**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.25
33
34
### Auto-print (`noconfirm`) and referrer verification35
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** |50
51
Without `referrer`, `noconfirm=1` is rejected. Without `noconfirm`, behaviour is unchanged (interactive print dialog).52
53
Localhost / private IP verification URLs are blocked by default. For local harnesses only, set `POSPRINT_ALLOW_LOCAL_REFERRER=1` (see `scripts/test-noconfirm/`).54
26
---55
---27
56
28
## Size limits57
## Size limits@@ -68,6 +97,11 @@ $url = posprint_url([68
'metadata' => ['page_width_mm' => 53, 'chars_per_line' => 32],97
'metadata' => ['page_width_mm' => 53, 'chars_per_line' => 32],69
'body' => "@barcode RASTER CODE128 \${data}\nHello\n@cut\n",98
'body' => "@barcode RASTER CODE128 \${data}\nHello\n@cut\n",70
]);99
]);100
// Auto-print: site must expose a verify URL that returns HTTP 200 for this code:101
$auto = posprint_url($pos, [102
'noconfirm' => true,103
'referrer' => 'https://shop.example.com/bonnen/verify?code=' . urlencode($code),104
]);71
// <a href="<?= htmlspecialchars($url) ?>">Print</a>105
// <a href="<?= htmlspecialchars($url) ?>">Print</a>72
```106
```73
107
@@ -81,6 +115,11 @@ const url = posprintUrl({81
metadata: { page_width_mm: 53, chars_per_line: 32 },115
metadata: { page_width_mm: 53, chars_per_line: 32 },82
body: '@barcode RASTER CODE128 ${data}\nHello\n@cut\n',116
body: '@barcode RASTER CODE128 ${data}\nHello\n@cut\n',83
});117
});118
119
const auto = posprintUrl(pos, {120
noconfirm: true,121
referrer: `https://shop.example.com/bonnen/verify?code=${encodeURIComponent(code)}`,122
});84
```123
```85
124
86
#### Browser125
#### Browser@@ -93,7 +132,11 @@ const url = posprintUrl({93
metadata: { page_width_mm: 53 },132
metadata: { page_width_mm: 53 },94
body: '@barcode RASTER CODE128 ${data}\nHello\n@cut\n',133
body: '@barcode RASTER CODE128 ${data}\nHello\n@cut\n',95
});134
});96
location.href = url;135
const auto = await posprintUrl(pos, {136
noconfirm: true,137
referrer: `https://${location.host}/bonnen/verify?code=${encodeURIComponent(code)}`,138
});139
location.href = auto;97
</script>140
</script>98
```141
```99
142
@@ -0,0 +1,9 @@
1
{
2
"version": 1,
3
"metadata": {
4
"title": "noconfirm demo",
5
"page_width_mm": 53,
6
"chars_per_line": 32
7
},
8
"body": "# noconfirm OK\n\nVerified print demo\n\n@cut\n"
9
}
@@ -0,0 +1,9 @@1
{
2
"version": 1,
3
"metadata": {
4
"title": "noconfirm demo",
5
"page_width_mm": 53,
6
"chars_per_line": 32
7
},
8
"body": "# noconfirm OK\n\nVerified print demo\n\n@cut\n"
9
}
@@ -31,6 +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 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
39
window.location.href = url;
35
40
});
36
41
</script>
@@ -31,6 +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 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
window.location.href = url;39
window.location.href = url;35
});40
});36
</script>41
</script>@@ -5,9 +5,10 @@
5
5
* Requires CompressionStream('deflate-raw') (modern browsers).
6
6
*
7
7
* @param {object|string} pos
8
* @param {{ noconfirm?: boolean, referrer?: string }} [options]
8
9
* @returns {Promise<string>}
9
10
*/
10
export async function posprintUrl(pos) {
11
export async function posprintUrl(pos, options = {}) {
11
12
const json = typeof pos === 'string' ? pos : JSON.stringify(pos);
12
13
if (typeof CompressionStream === 'undefined') {
13
14
throw new Error("CompressionStream('deflate-raw') is not available in this browser");
@@ -16,7 +17,17 @@ export async function posprintUrl(pos) {
16
17
const stream = new Blob([json]).stream().pipeThrough(new CompressionStream('deflate-raw'));
17
18
const buffer = await new Response(stream).arrayBuffer();
18
19
const b64 = bytesToBase64Url(new Uint8Array(buffer));
19
return `posprint://print?v=1&d=${b64}`;
20
let url = `posprint://print?v=1&d=${b64}`;
21
if (options.noconfirm) {
22
url += '&noconfirm=1';
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;
20
31
}
21
32
22
33
function bytesToBase64Url(bytes) {
@@ -5,9 +5,10 @@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
* @returns {Promise<string>}
9
* @returns {Promise<string>}
9
*/
10
*/
10
export async function posprintUrl(pos) {
11
export async function posprintUrl(pos, options = {}) {
11
const json = typeof pos === 'string' ? pos : JSON.stringify(pos);
12
const json = typeof pos === 'string' ? pos : JSON.stringify(pos);
12
if (typeof CompressionStream === 'undefined') {
13
if (typeof CompressionStream === 'undefined') {
13
throw new Error("CompressionStream('deflate-raw') is not available in this browser");
14
throw new Error("CompressionStream('deflate-raw') is not available in this browser");
@@ -16,7 +17,17 @@ export async function posprintUrl(pos) {16
const stream = new Blob([json]).stream().pipeThrough(new CompressionStream('deflate-raw'));
17
const stream = new Blob([json]).stream().pipeThrough(new CompressionStream('deflate-raw'));
17
const buffer = await new Response(stream).arrayBuffer();
18
const buffer = await new Response(stream).arrayBuffer();
18
const b64 = bytesToBase64Url(new Uint8Array(buffer));
19
const b64 = bytesToBase64Url(new Uint8Array(buffer));
19
return `posprint://print?v=1&d=${b64}`;
20
let url = `posprint://print?v=1&d=${b64}`;
21
if (options.noconfirm) {
22
url += '&noconfirm=1';
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;
20
}
31
}
21
32
22
function bytesToBase64Url(bytes) {
33
function bytesToBase64Url(bytes) {
@@ -8,13 +8,24 @@ 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
12
* @returns {string}
12
13
*/
13
function posprintUrl(pos) {
14
function posprintUrl(pos, options = {}) {
14
15
const json = typeof pos === 'string' ? pos : JSON.stringify(pos);
15
16
const compressed = zlib.deflateRawSync(Buffer.from(json, 'utf8'), { level: 9 });
16
17
const b64 = compressed.toString('base64url');
17
return `posprint://print?v=1&d=${b64}`;
18
let url = `posprint://print?v=1&d=${b64}`;
19
if (options.noconfirm) {
20
url += '&noconfirm=1';
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;
18
29
}
19
30
20
31
module.exports = { posprintUrl };
@@ -8,13 +8,24 @@ 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
* @returns {string}
12
* @returns {string}
12
*/
13
*/
13
function posprintUrl(pos) {
14
function posprintUrl(pos, options = {}) {
14
const json = typeof pos === 'string' ? pos : JSON.stringify(pos);
15
const json = typeof pos === 'string' ? pos : JSON.stringify(pos);
15
const compressed = zlib.deflateRawSync(Buffer.from(json, 'utf8'), { level: 9 });
16
const compressed = zlib.deflateRawSync(Buffer.from(json, 'utf8'), { level: 9 });
16
const b64 = compressed.toString('base64url');
17
const b64 = compressed.toString('base64url');
17
return `posprint://print?v=1&d=${b64}`;
18
let url = `posprint://print?v=1&d=${b64}`;
19
if (options.noconfirm) {
20
url += '&noconfirm=1';
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;
18
}
29
}
19
30
20
module.exports = { posprintUrl };
31
module.exports = { posprintUrl };
@@ -5,10 +5,11 @@
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
9
* @return string posprint://print?v=1&d=…
9
10
* @throws InvalidArgumentException
10
11
*/
11
function posprint_url($pos): string
12
function posprint_url($pos, array $options = []): string
12
13
{
13
14
if (is_array($pos)) {
14
15
$json = json_encode($pos, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
@@ -27,5 +28,17 @@ function posprint_url($pos): string
27
28
}
28
29
29
30
$b64 = rtrim(strtr(base64_encode($compressed), '+/', '-_'), '=');
30
return 'posprint://print?v=1&d=' . $b64;
31
$url = 'posprint://print?v=1&d=' . $b64;
32
33
if (!empty($options['noconfirm'])) {
34
$url .= '&noconfirm=1';
35
}
36
if (!empty($options['referrer'])) {
37
$ref = trim((string) $options['referrer']);
38
if ($ref !== '') {
39
$url .= '&referrer=' . rawurlencode($ref);
40
}
41
}
42
43
return $url;
31
44
}
@@ -5,10 +5,11 @@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
* @return string posprint://print?v=1&d=…
9
* @return string posprint://print?v=1&d=…
9
* @throws InvalidArgumentException
10
* @throws InvalidArgumentException
10
*/
11
*/
11
function posprint_url($pos): string
12
function posprint_url($pos, array $options = []): string
12
{
13
{
13
if (is_array($pos)) {
14
if (is_array($pos)) {
14
$json = json_encode($pos, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
15
$json = json_encode($pos, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
@@ -27,5 +28,17 @@ function posprint_url($pos): string27
}
28
}
28
29
29
$b64 = rtrim(strtr(base64_encode($compressed), '+/', '-_'), '=');
30
$b64 = rtrim(strtr(base64_encode($compressed), '+/', '-_'), '=');
30
return 'posprint://print?v=1&d=' . $b64;
31
$url = 'posprint://print?v=1&d=' . $b64;
32
33
if (!empty($options['noconfirm'])) {
34
$url .= '&noconfirm=1';
35
}
36
if (!empty($options['referrer'])) {
37
$ref = trim((string) $options['referrer']);
38
if ($ref !== '') {
39
$url .= '&referrer=' . rawurlencode($ref);
40
}
41
}
42
43
return $url;
31
}
44
}
@@ -0,0 +1,52 @@
1
# Local noconfirm + referrer test
2
3
Docs: [docs/POSPRINT-URL.md](../../docs/POSPRINT-URL.md).
4
5
Production blocks localhost referrers. For this harness set:
6
7
```powershell
8
$env:POSPRINT_ALLOW_LOCAL_REFERRER = "1"
9
```
10
11
## 1. Start the verify server
12
13
```powershell
14
python scripts/test-noconfirm/server.py
15
```
16
17
- `GET http://127.0.0.1:8765/verify?code=84923` → **200**
18
- `GET http://127.0.0.1:8765/verify?code=wrong` → **403**
19
20
## 2. Build a debug posprint with the feature branch / master
21
22
```powershell
23
cargo build
24
$env:POSPRINT_ALLOW_LOCAL_REFERRER = "1"
25
```
26
27
## 3. Open the test URL
28
29
Generate (from repo root):
30
31
```powershell
32
cargo run --quiet -- link examples/noconfirm-demo.pos
33
```
34
35
Then append (PowerShell):
36
37
```powershell
38
$base = cargo run --quiet -- link examples/noconfirm-demo.pos
39
$ref = [uri]::EscapeDataString("http://127.0.0.1:8765/verify?code=84923")
40
$url = "$base&noconfirm=1&referrer=$ref"
41
$url
42
Start-Process $url
43
```
44
45
First run: trust dialog for `127.0.0.1`. After **Trust and print**, the next open with the same URL should print without asking (while the server still returns 200).
46
47
Try a bad code to confirm refusal:
48
49
```powershell
50
$refBad = [uri]::EscapeDataString("http://127.0.0.1:8765/verify?code=nope")
51
Start-Process "$base&noconfirm=1&referrer=$refBad"
52
```
@@ -0,0 +1,52 @@1
# Local noconfirm + referrer test2
3
Docs: [docs/POSPRINT-URL.md](../../docs/POSPRINT-URL.md).4
5
Production blocks localhost referrers. For this harness set:6
7
```powershell8
$env:POSPRINT_ALLOW_LOCAL_REFERRER = "1"9
```10
11
## 1. Start the verify server12
13
```powershell14
python scripts/test-noconfirm/server.py15
```16
17
- `GET http://127.0.0.1:8765/verify?code=84923` → **200**18
- `GET http://127.0.0.1:8765/verify?code=wrong` → **403**19
20
## 2. Build a debug posprint with the feature branch / master21
22
```powershell23
cargo build24
$env:POSPRINT_ALLOW_LOCAL_REFERRER = "1"25
```26
27
## 3. Open the test URL28
29
Generate (from repo root):30
31
```powershell32
cargo run --quiet -- link examples/noconfirm-demo.pos33
```34
35
Then append (PowerShell):36
37
```powershell38
$base = cargo run --quiet -- link examples/noconfirm-demo.pos39
$ref = [uri]::EscapeDataString("http://127.0.0.1:8765/verify?code=84923")40
$url = "$base&noconfirm=1&referrer=$ref"41
$url42
Start-Process $url43
```44
45
First run: trust dialog for `127.0.0.1`. After **Trust and print**, the next open with the same URL should print without asking (while the server still returns 200).46
47
Try a bad code to confirm refusal:48
49
```powershell50
$refBad = [uri]::EscapeDataString("http://127.0.0.1:8765/verify?code=nope")51
Start-Process "$base&noconfirm=1&referrer=$refBad"52
```@@ -0,0 +1,56 @@
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()
@@ -0,0 +1,56 @@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()
@@ -2,6 +2,7 @@ use std::path::PathBuf;
2
2
3
3
use eframe::egui;
4
4
5
use posprint::config::AppConfig;
5
6
use posprint::dsl::{self, parse};
6
7
use posprint::editor_assist::{
7
8
apply_directive_completion, at_directive_prefix, barcode_insert_options, char_index_to_byte,
@@ -20,6 +21,7 @@ use crate::print_dialog::{PrintDialog, PrintDialogAction, PrintExecuteResult};
20
21
enum ViewMode {
21
22
Design,
22
23
Help,
24
Settings,
23
25
}
24
26
25
27
pub struct PosPrintApp {
@@ -35,14 +37,19 @@ pub struct PosPrintApp {
35
37
editor_cursor: usize,
36
38
undo: TextUndo,
37
39
preview_zoom: f32,
40
config: AppConfig,
41
settings_status: Option<String>,
38
42
}
39
43
40
44
impl Default for PosPrintApp {
41
45
fn default() -> Self {
46
let config = AppConfig::load();
47
let mut metadata = PosMetadata::default();
48
metadata.page_width_mm = config.default_page_width_mm;
42
49
Self {
43
50
view_mode: ViewMode::Design,
44
51
body: default_template(),
45
metadata: PosMetadata::default(),
52
metadata,
46
53
file_path: None,
47
54
dirty: false,
48
55
parse_error: None,
@@ -52,6 +59,8 @@ impl Default for PosPrintApp {
52
59
editor_cursor: 0,
53
60
undo: TextUndo::default(),
54
61
preview_zoom: 1.0,
62
config,
63
settings_status: None,
55
64
}
56
65
}
57
66
}
@@ -105,6 +114,74 @@ impl PosPrintApp {
105
114
*self = Self::default();
106
115
}
107
116
117
fn show_settings(&mut self, ui: &mut egui::Ui) {
118
ui.heading("Settings");
119
ui.separator();
120
121
ui.heading("New documents");
122
ui.horizontal(|ui| {
123
ui.label("Default page width (mm):");
124
let mut width = self.config.default_page_width_mm;
125
if ui
126
.add(egui::DragValue::new(&mut width).range(40.0..=120.0).speed(1.0))
127
.changed()
128
{
129
self.config.default_page_width_mm = width;
130
self.settings_status = None;
131
}
132
});
133
ui.label("Applies when you choose New. The current document width is unchanged.");
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);
174
if ui.button("Save settings").clicked() {
175
match self.config.save() {
176
Ok(()) => self.settings_status = Some("Settings saved.".into()),
177
Err(e) => self.settings_status = Some(format!("Save failed: {e}")),
178
}
179
}
180
if let Some(status) = &self.settings_status {
181
ui.label(status);
182
}
183
}
184
108
185
fn open_file_dialog(&mut self) {
109
186
if let Some(path) = rfd::FileDialog::new()
110
187
.add_filter("POS template", &["pos"])
@@ -342,6 +419,7 @@ impl eframe::App for PosPrintApp {
342
419
ui.horizontal(|ui| {
343
420
ui.selectable_value(&mut self.view_mode, ViewMode::Design, "Design");
344
421
ui.selectable_value(&mut self.view_mode, ViewMode::Help, "Help");
422
ui.selectable_value(&mut self.view_mode, ViewMode::Settings, "Settings");
345
423
if let Ok(doc) = parse(&self.body) {
346
424
if !dsl::document_ends_with_cut(&doc) {
347
425
ui.colored_label(
@@ -398,6 +476,13 @@ impl eframe::App for PosPrintApp {
398
476
});
399
477
});
400
478
}
479
ViewMode::Settings => {
480
egui::CentralPanel::default().show(ctx, |ui| {
481
ui.add_enabled_ui(main_enabled, |ui| {
482
self.show_settings(ui);
483
});
484
});
485
}
401
486
}
402
487
403
488
if self.show_print_dialog {
@@ -2,6 +2,7 @@ use std::path::PathBuf;2
2
3
use eframe::egui;
3
use eframe::egui;
4
4
5
use posprint::config::AppConfig;
5
use posprint::dsl::{self, parse};
6
use posprint::dsl::{self, parse};
6
use posprint::editor_assist::{
7
use posprint::editor_assist::{
7
apply_directive_completion, at_directive_prefix, barcode_insert_options, char_index_to_byte,
8
apply_directive_completion, at_directive_prefix, barcode_insert_options, char_index_to_byte,
@@ -20,6 +21,7 @@ use crate::print_dialog::{PrintDialog, PrintDialogAction, PrintExecuteResult};20
enum ViewMode {
21
enum ViewMode {
21
Design,
22
Design,
22
Help,
23
Help,
24
Settings,
23
}
25
}
24
26
25
pub struct PosPrintApp {
27
pub struct PosPrintApp {
@@ -35,14 +37,19 @@ pub struct PosPrintApp {35
editor_cursor: usize,
37
editor_cursor: usize,
36
undo: TextUndo,
38
undo: TextUndo,
37
preview_zoom: f32,
39
preview_zoom: f32,
40
config: AppConfig,
41
settings_status: Option<String>,
38
}
42
}
39
43
40
impl Default for PosPrintApp {
44
impl Default for PosPrintApp {
41
fn default() -> Self {
45
fn default() -> Self {
46
let config = AppConfig::load();
47
let mut metadata = PosMetadata::default();
48
metadata.page_width_mm = config.default_page_width_mm;
42
Self {
49
Self {
43
view_mode: ViewMode::Design,
50
view_mode: ViewMode::Design,
44
body: default_template(),
51
body: default_template(),
45
metadata: PosMetadata::default(),
52
metadata,
46
file_path: None,
53
file_path: None,
47
dirty: false,
54
dirty: false,
48
parse_error: None,
55
parse_error: None,
@@ -52,6 +59,8 @@ impl Default for PosPrintApp {52
editor_cursor: 0,
59
editor_cursor: 0,
53
undo: TextUndo::default(),
60
undo: TextUndo::default(),
54
preview_zoom: 1.0,
61
preview_zoom: 1.0,
62
config,
63
settings_status: None,
55
}
64
}
56
}
65
}
57
}
66
}
@@ -105,6 +114,74 @@ impl PosPrintApp {105
*self = Self::default();
114
*self = Self::default();
106
}
115
}
107
116
117
fn show_settings(&mut self, ui: &mut egui::Ui) {
118
ui.heading("Settings");
119
ui.separator();
120
121
ui.heading("New documents");
122
ui.horizontal(|ui| {
123
ui.label("Default page width (mm):");
124
let mut width = self.config.default_page_width_mm;
125
if ui
126
.add(egui::DragValue::new(&mut width).range(40.0..=120.0).speed(1.0))
127
.changed()
128
{
129
self.config.default_page_width_mm = width;
130
self.settings_status = None;
131
}
132
});
133
ui.label("Applies when you choose New. The current document width is unchanged.");
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);
174
if ui.button("Save settings").clicked() {
175
match self.config.save() {
176
Ok(()) => self.settings_status = Some("Settings saved.".into()),
177
Err(e) => self.settings_status = Some(format!("Save failed: {e}")),
178
}
179
}
180
if let Some(status) = &self.settings_status {
181
ui.label(status);
182
}
183
}
184
108
fn open_file_dialog(&mut self) {
185
fn open_file_dialog(&mut self) {
109
if let Some(path) = rfd::FileDialog::new()
186
if let Some(path) = rfd::FileDialog::new()
110
.add_filter("POS template", &["pos"])
187
.add_filter("POS template", &["pos"])
@@ -342,6 +419,7 @@ impl eframe::App for PosPrintApp {342
ui.horizontal(|ui| {
419
ui.horizontal(|ui| {
343
ui.selectable_value(&mut self.view_mode, ViewMode::Design, "Design");
420
ui.selectable_value(&mut self.view_mode, ViewMode::Design, "Design");
344
ui.selectable_value(&mut self.view_mode, ViewMode::Help, "Help");
421
ui.selectable_value(&mut self.view_mode, ViewMode::Help, "Help");
422
ui.selectable_value(&mut self.view_mode, ViewMode::Settings, "Settings");
345
if let Ok(doc) = parse(&self.body) {
423
if let Ok(doc) = parse(&self.body) {
346
if !dsl::document_ends_with_cut(&doc) {
424
if !dsl::document_ends_with_cut(&doc) {
347
ui.colored_label(
425
ui.colored_label(
@@ -398,6 +476,13 @@ impl eframe::App for PosPrintApp {398
});
476
});
399
});
477
});
400
}
478
}
479
ViewMode::Settings => {
480
egui::CentralPanel::default().show(ctx, |ui| {
481
ui.add_enabled_ui(main_enabled, |ui| {
482
self.show_settings(ui);
483
});
484
});
485
}
401
}
486
}
402
487
403
if self.show_print_dialog {
488
if self.show_print_dialog {
@@ -0,0 +1,204 @@
1
//! Persisted app preferences (trusted URL origins, default page width).
2
3
use std::fs;
4
use std::path::PathBuf;
5
6
use serde::{Deserialize, Serialize};
7
8
const CONFIG_VERSION: u32 = 1;
9
10
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
11
pub struct AppConfig {
12
#[serde(default = "default_config_version")]
13
pub version: u32,
14
/// Default paper width for **New** documents (mm).
15
#[serde(default = "default_page_width_mm")]
16
pub default_page_width_mm: f32,
17
/// Hostnames allowed to use `noconfirm=1` without asking again.
18
#[serde(default)]
19
pub trusted_origins: Vec<String>,
20
}
21
22
fn default_config_version() -> u32 {
23
CONFIG_VERSION
24
}
25
26
fn default_page_width_mm() -> f32 {
27
80.0
28
}
29
30
impl Default for AppConfig {
31
fn default() -> Self {
32
Self {
33
version: CONFIG_VERSION,
34
default_page_width_mm: default_page_width_mm(),
35
trusted_origins: Vec::new(),
36
}
37
}
38
}
39
40
impl AppConfig {
41
pub fn load() -> Self {
42
Self::load_from_path(&config_path())
43
}
44
45
pub fn load_from_path(path: &std::path::Path) -> Self {
46
match fs::read_to_string(path) {
47
Ok(text) => match serde_json::from_str::<AppConfig>(&text) {
48
Ok(mut cfg) => {
49
cfg.normalize();
50
cfg
51
}
52
Err(_) => Self::default(),
53
},
54
Err(_) => Self::default(),
55
}
56
}
57
58
pub fn save(&self) -> Result<(), String> {
59
self.save_to_path(&config_path())
60
}
61
62
pub fn save_to_path(&self, path: &std::path::Path) -> Result<(), String> {
63
if let Some(parent) = path.parent() {
64
fs::create_dir_all(parent).map_err(|e| e.to_string())?;
65
}
66
let mut cfg = self.clone();
67
cfg.normalize();
68
let json = serde_json::to_string_pretty(&cfg).map_err(|e| e.to_string())?;
69
fs::write(path, json).map_err(|e| e.to_string())
70
}
71
72
pub fn is_trusted(&self, origin: &str) -> bool {
73
let Some(host) = normalize_origin(origin) else {
74
return false;
75
};
76
self.trusted_origins.iter().any(|o| o == &host)
77
}
78
79
pub fn trust_origin(&mut self, origin: &str) -> bool {
80
let Some(host) = normalize_origin(origin) else {
81
return false;
82
};
83
if !self.trusted_origins.iter().any(|o| o == &host) {
84
self.trusted_origins.push(host);
85
self.trusted_origins.sort();
86
}
87
true
88
}
89
90
pub fn revoke_origin(&mut self, origin: &str) {
91
let Some(host) = normalize_origin(origin) else {
92
return;
93
};
94
self.trusted_origins.retain(|o| o != &host);
95
}
96
97
fn normalize(&mut self) {
98
self.version = CONFIG_VERSION;
99
if !self.default_page_width_mm.is_finite() || self.default_page_width_mm < 40.0 {
100
self.default_page_width_mm = 40.0;
101
} else if self.default_page_width_mm > 120.0 {
102
self.default_page_width_mm = 120.0;
103
}
104
let mut hosts: Vec<String> = self
105
.trusted_origins
106
.iter()
107
.filter_map(|o| normalize_origin(o))
108
.collect();
109
hosts.sort();
110
hosts.dedup();
111
self.trusted_origins = hosts;
112
}
113
}
114
115
/// Config file path: `%APPDATA%/posprint/config.json` (Windows) or
116
/// `$XDG_CONFIG_HOME/posprint/config.json` / `~/.config/posprint/config.json` (Unix).
117
pub fn config_path() -> PathBuf {
118
#[cfg(windows)]
119
{
120
let base = std::env::var_os("APPDATA")
121
.map(PathBuf::from)
122
.unwrap_or_else(|| PathBuf::from("."));
123
base.join("posprint").join("config.json")
124
}
125
#[cfg(not(windows))]
126
{
127
let base = std::env::var_os("XDG_CONFIG_HOME")
128
.map(PathBuf::from)
129
.or_else(|| {
130
std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".config"))
131
})
132
.unwrap_or_else(|| PathBuf::from("."));
133
base.join("posprint").join("config.json")
134
}
135
}
136
137
/// Normalize a caller-supplied origin to a lowercase hostname.
138
/// Accepts `example.com`, `https://example.com/path`, `http://localhost:3000`.
139
pub fn normalize_origin(raw: &str) -> Option<String> {
140
let s = raw.trim();
141
if s.is_empty() {
142
return None;
143
}
144
let without_scheme = s
145
.strip_prefix("https://")
146
.or_else(|| s.strip_prefix("http://"))
147
.or_else(|| s.strip_prefix("HTTPS://"))
148
.or_else(|| s.strip_prefix("HTTP://"))
149
.unwrap_or(s);
150
let host_port = without_scheme.split('/').next()?.trim();
151
if host_port.is_empty() {
152
return None;
153
}
154
// Drop port for trust matching (example.com:443 → example.com).
155
let host = host_port.split(':').next()?.trim();
156
if host.is_empty() {
157
return None;
158
}
159
Some(host.to_ascii_lowercase())
160
}
161
162
#[cfg(test)]
163
mod tests {
164
use super::*;
165
166
#[test]
167
fn normalize_strips_scheme_path_and_port() {
168
assert_eq!(
169
normalize_origin("https://Shop.Example.com/checkout").as_deref(),
170
Some("shop.example.com")
171
);
172
assert_eq!(
173
normalize_origin("http://localhost:5173/").as_deref(),
174
Some("localhost")
175
);
176
assert_eq!(normalize_origin("example.com").as_deref(), Some("example.com"));
177
assert_eq!(normalize_origin(" ").as_deref(), None);
178
}
179
180
#[test]
181
fn trust_and_revoke_roundtrip() {
182
let mut cfg = AppConfig::default();
183
assert!(!cfg.is_trusted("https://a.example"));
184
assert!(cfg.trust_origin("https://a.example/x"));
185
assert!(cfg.is_trusted("a.example"));
186
assert!(cfg.is_trusted("HTTPS://A.Example"));
187
cfg.revoke_origin("a.example");
188
assert!(!cfg.is_trusted("a.example"));
189
}
190
191
#[test]
192
fn save_load_roundtrip_in_temp_dir() {
193
let dir = tempfile::tempdir().unwrap();
194
let path = dir.path().join("posprint").join("config.json");
195
let mut cfg = AppConfig::default();
196
cfg.default_page_width_mm = 58.0;
197
cfg.trust_origin("pos.example");
198
cfg.save_to_path(&path).unwrap();
199
200
let loaded = AppConfig::load_from_path(&path);
201
assert_eq!(loaded.default_page_width_mm, 58.0);
202
assert!(loaded.is_trusted("pos.example"));
203
}
204
}
@@ -0,0 +1,204 @@1
//! Persisted app preferences (trusted URL origins, default page width).
2
3
use std::fs;
4
use std::path::PathBuf;
5
6
use serde::{Deserialize, Serialize};
7
8
const CONFIG_VERSION: u32 = 1;
9
10
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
11
pub struct AppConfig {
12
#[serde(default = "default_config_version")]
13
pub version: u32,
14
/// Default paper width for **New** documents (mm).
15
#[serde(default = "default_page_width_mm")]
16
pub default_page_width_mm: f32,
17
/// Hostnames allowed to use `noconfirm=1` without asking again.
18
#[serde(default)]
19
pub trusted_origins: Vec<String>,
20
}
21
22
fn default_config_version() -> u32 {
23
CONFIG_VERSION
24
}
25
26
fn default_page_width_mm() -> f32 {
27
80.0
28
}
29
30
impl Default for AppConfig {
31
fn default() -> Self {
32
Self {
33
version: CONFIG_VERSION,
34
default_page_width_mm: default_page_width_mm(),
35
trusted_origins: Vec::new(),
36
}
37
}
38
}
39
40
impl AppConfig {
41
pub fn load() -> Self {
42
Self::load_from_path(&config_path())
43
}
44
45
pub fn load_from_path(path: &std::path::Path) -> Self {
46
match fs::read_to_string(path) {
47
Ok(text) => match serde_json::from_str::<AppConfig>(&text) {
48
Ok(mut cfg) => {
49
cfg.normalize();
50
cfg
51
}
52
Err(_) => Self::default(),
53
},
54
Err(_) => Self::default(),
55
}
56
}
57
58
pub fn save(&self) -> Result<(), String> {
59
self.save_to_path(&config_path())
60
}
61
62
pub fn save_to_path(&self, path: &std::path::Path) -> Result<(), String> {
63
if let Some(parent) = path.parent() {
64
fs::create_dir_all(parent).map_err(|e| e.to_string())?;
65
}
66
let mut cfg = self.clone();
67
cfg.normalize();
68
let json = serde_json::to_string_pretty(&cfg).map_err(|e| e.to_string())?;
69
fs::write(path, json).map_err(|e| e.to_string())
70
}
71
72
pub fn is_trusted(&self, origin: &str) -> bool {
73
let Some(host) = normalize_origin(origin) else {
74
return false;
75
};
76
self.trusted_origins.iter().any(|o| o == &host)
77
}
78
79
pub fn trust_origin(&mut self, origin: &str) -> bool {
80
let Some(host) = normalize_origin(origin) else {
81
return false;
82
};
83
if !self.trusted_origins.iter().any(|o| o == &host) {
84
self.trusted_origins.push(host);
85
self.trusted_origins.sort();
86
}
87
true
88
}
89
90
pub fn revoke_origin(&mut self, origin: &str) {
91
let Some(host) = normalize_origin(origin) else {
92
return;
93
};
94
self.trusted_origins.retain(|o| o != &host);
95
}
96
97
fn normalize(&mut self) {
98
self.version = CONFIG_VERSION;
99
if !self.default_page_width_mm.is_finite() || self.default_page_width_mm < 40.0 {
100
self.default_page_width_mm = 40.0;
101
} else if self.default_page_width_mm > 120.0 {
102
self.default_page_width_mm = 120.0;
103
}
104
let mut hosts: Vec<String> = self
105
.trusted_origins
106
.iter()
107
.filter_map(|o| normalize_origin(o))
108
.collect();
109
hosts.sort();
110
hosts.dedup();
111
self.trusted_origins = hosts;
112
}
113
}
114
115
/// Config file path: `%APPDATA%/posprint/config.json` (Windows) or
116
/// `$XDG_CONFIG_HOME/posprint/config.json` / `~/.config/posprint/config.json` (Unix).
117
pub fn config_path() -> PathBuf {
118
#[cfg(windows)]
119
{
120
let base = std::env::var_os("APPDATA")
121
.map(PathBuf::from)
122
.unwrap_or_else(|| PathBuf::from("."));
123
base.join("posprint").join("config.json")
124
}
125
#[cfg(not(windows))]
126
{
127
let base = std::env::var_os("XDG_CONFIG_HOME")
128
.map(PathBuf::from)
129
.or_else(|| {
130
std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".config"))
131
})
132
.unwrap_or_else(|| PathBuf::from("."));
133
base.join("posprint").join("config.json")
134
}
135
}
136
137
/// Normalize a caller-supplied origin to a lowercase hostname.
138
/// Accepts `example.com`, `https://example.com/path`, `http://localhost:3000`.
139
pub fn normalize_origin(raw: &str) -> Option<String> {
140
let s = raw.trim();
141
if s.is_empty() {
142
return None;
143
}
144
let without_scheme = s
145
.strip_prefix("https://")
146
.or_else(|| s.strip_prefix("http://"))
147
.or_else(|| s.strip_prefix("HTTPS://"))
148
.or_else(|| s.strip_prefix("HTTP://"))
149
.unwrap_or(s);
150
let host_port = without_scheme.split('/').next()?.trim();
151
if host_port.is_empty() {
152
return None;
153
}
154
// Drop port for trust matching (example.com:443 → example.com).
155
let host = host_port.split(':').next()?.trim();
156
if host.is_empty() {
157
return None;
158
}
159
Some(host.to_ascii_lowercase())
160
}
161
162
#[cfg(test)]
163
mod tests {
164
use super::*;
165
166
#[test]
167
fn normalize_strips_scheme_path_and_port() {
168
assert_eq!(
169
normalize_origin("https://Shop.Example.com/checkout").as_deref(),
170
Some("shop.example.com")
171
);
172
assert_eq!(
173
normalize_origin("http://localhost:5173/").as_deref(),
174
Some("localhost")
175
);
176
assert_eq!(normalize_origin("example.com").as_deref(), Some("example.com"));
177
assert_eq!(normalize_origin(" ").as_deref(), None);
178
}
179
180
#[test]
181
fn trust_and_revoke_roundtrip() {
182
let mut cfg = AppConfig::default();
183
assert!(!cfg.is_trusted("https://a.example"));
184
assert!(cfg.trust_origin("https://a.example/x"));
185
assert!(cfg.is_trusted("a.example"));
186
assert!(cfg.is_trusted("HTTPS://A.Example"));
187
cfg.revoke_origin("a.example");
188
assert!(!cfg.is_trusted("a.example"));
189
}
190
191
#[test]
192
fn save_load_roundtrip_in_temp_dir() {
193
let dir = tempfile::tempdir().unwrap();
194
let path = dir.path().join("posprint").join("config.json");
195
let mut cfg = AppConfig::default();
196
cfg.default_page_width_mm = 58.0;
197
cfg.trust_origin("pos.example");
198
cfg.save_to_path(&path).unwrap();
199
200
let loaded = AppConfig::load_from_path(&path);
201
assert_eq!(loaded.default_page_width_mm, 58.0);
202
assert!(loaded.is_trusted("pos.example"));
203
}
204
}
@@ -1,4 +1,5 @@
1
1
pub mod cli;
2
pub mod config;
2
3
pub mod datetime;
3
4
pub mod dsl;
4
5
pub mod editor_assist;
@@ -12,6 +13,7 @@ pub mod preview;
12
13
pub mod print;
13
14
pub mod protocol_url;
14
15
pub mod raster;
16
pub mod referrer_verify;
15
17
pub mod text_wrap;
16
18
pub mod undo;
17
19
@@ -1,4 +1,5 @@1
pub mod cli;
1
pub mod cli;
2
pub mod config;
2
pub mod datetime;
3
pub mod datetime;
3
pub mod dsl;
4
pub mod dsl;
4
pub mod editor_assist;
5
pub mod editor_assist;
@@ -12,6 +13,7 @@ pub mod preview;12
pub mod print;
13
pub mod print;
13
pub mod protocol_url;
14
pub mod protocol_url;
14
pub mod raster;
15
pub mod raster;
16
pub mod referrer_verify;
15
pub mod text_wrap;
17
pub mod text_wrap;
16
pub mod undo;
18
pub mod undo;
17
19
@@ -10,7 +10,6 @@ use std::sync::Arc;
10
10
11
11
use clap::Parser;
12
12
13
use posprint::io::PosFile;
14
13
use posprint::protocol_url::{self, is_posprint_url};
15
14
16
15
fn load_viewport_icon() -> Option<Arc<eframe::egui::IconData>> {
@@ -25,7 +24,7 @@ fn main() -> eframe::Result<()> {
25
24
// Protocol URLs must be handled before clap: browsers pass the full URL as argv.
26
25
if let Some(url) = std::env::args().nth(1).filter(|a| is_posprint_url(a)) {
27
26
return match protocol_url::parse_posprint_url(&url) {
28
Ok(file) => run_print_only_pos_file(file),
27
Ok(launch) => run_print_only_launch(launch),
29
28
Err(e) => run_print_only_error(format!("Invalid posprint:// URL: {e}")),
30
29
};
31
30
}
@@ -67,13 +66,8 @@ fn run_print_only_path(path: std::path::PathBuf) -> eframe::Result<()> {
67
66
run_print_only_app(print_only_app::PrintOnlyApp::new(path))
68
67
}
69
68
70
fn run_print_only_pos_file(file: PosFile) -> eframe::Result<()> {
71
let label = file
72
.metadata
73
.title
74
.clone()
75
.unwrap_or_else(|| "posprint://".into());
76
run_print_only_app(print_only_app::PrintOnlyApp::from_pos_file(file, label))
69
fn run_print_only_launch(launch: protocol_url::PosprintLaunch) -> eframe::Result<()> {
70
run_print_only_app(print_only_app::PrintOnlyApp::from_launch(launch))
77
71
}
78
72
79
73
fn run_print_only_error(message: String) -> eframe::Result<()> {
@@ -10,7 +10,6 @@ use std::sync::Arc;10
10
11
use clap::Parser;
11
use clap::Parser;
12
12
13
use posprint::io::PosFile;
14
use posprint::protocol_url::{self, is_posprint_url};
13
use posprint::protocol_url::{self, is_posprint_url};
15
14
16
fn load_viewport_icon() -> Option<Arc<eframe::egui::IconData>> {
15
fn load_viewport_icon() -> Option<Arc<eframe::egui::IconData>> {
@@ -25,7 +24,7 @@ fn main() -> eframe::Result<()> {25
// Protocol URLs must be handled before clap: browsers pass the full URL as argv.
24
// Protocol URLs must be handled before clap: browsers pass the full URL as argv.
26
if let Some(url) = std::env::args().nth(1).filter(|a| is_posprint_url(a)) {
25
if let Some(url) = std::env::args().nth(1).filter(|a| is_posprint_url(a)) {
27
return match protocol_url::parse_posprint_url(&url) {
26
return match protocol_url::parse_posprint_url(&url) {
28
Ok(file) => run_print_only_pos_file(file),
27
Ok(launch) => run_print_only_launch(launch),
29
Err(e) => run_print_only_error(format!("Invalid posprint:// URL: {e}")),
28
Err(e) => run_print_only_error(format!("Invalid posprint:// URL: {e}")),
30
};
29
};
31
}
30
}
@@ -67,13 +66,8 @@ fn run_print_only_path(path: std::path::PathBuf) -> eframe::Result<()> {67
run_print_only_app(print_only_app::PrintOnlyApp::new(path))
66
run_print_only_app(print_only_app::PrintOnlyApp::new(path))
68
}
67
}
69
68
70
fn run_print_only_pos_file(file: PosFile) -> eframe::Result<()> {
69
fn run_print_only_launch(launch: protocol_url::PosprintLaunch) -> eframe::Result<()> {
71
let label = file
70
run_print_only_app(print_only_app::PrintOnlyApp::from_launch(launch))
72
.metadata
73
.title
74
.clone()
75
.unwrap_or_else(|| "posprint://".into());
76
run_print_only_app(print_only_app::PrintOnlyApp::from_pos_file(file, label))
77
}
71
}
78
72
79
fn run_print_only_error(message: String) -> eframe::Result<()> {
73
fn run_print_only_error(message: String) -> eframe::Result<()> {
@@ -1,10 +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
8
use posprint::config::AppConfig;
7
9
use posprint::io::{PosFile, PosMetadata};
10
use posprint::protocol_url::PosprintLaunch;
11
use posprint::referrer_verify;
8
12
9
13
use crate::preview_panel::show_preview_panel;
10
14
use crate::print_dialog::{PrintDialog, PrintDialogAction, PrintExecuteResult};
@@ -19,20 +23,20 @@ pub struct PrintOnlyApp {
19
23
preview_zoom: f32,
20
24
fatal_error: Option<String>,
21
25
exit_requested: bool,
26
/// Auto-print once printers are ready (after trust if needed).
27
auto_print: bool,
28
/// Pending first-time trust confirmation for this hostname.
29
pending_trust: Option<String>,
30
auto_print_attempted: bool,
31
/// Background GET of `referrer=` for noconfirm.
32
referrer_rx: Option<Receiver<Result<String, String>>>,
33
verifying_referrer: bool,
22
34
}
23
35
24
36
impl PrintOnlyApp {
25
37
pub fn new(path: PathBuf) -> Self {
26
let mut app = Self {
27
body: String::new(),
28
metadata: PosMetadata::default(),
29
file_path: Some(path.clone()),
30
title_override: None,
31
dialog: PrintDialog::default(),
32
preview_zoom: 1.0,
33
fatal_error: None,
34
exit_requested: false,
35
};
38
let mut app = Self::blank();
39
app.file_path = Some(path.clone());
36
40
37
41
match PosFile::load_from_path(&path) {
38
42
Ok(file) => {
@@ -49,32 +53,103 @@ impl PrintOnlyApp {
49
53
}
50
54
51
55
pub fn from_pos_file(file: PosFile, source_label: impl Into<String>) -> Self {
52
let mut app = Self {
53
body: file.body,
54
metadata: file.metadata,
55
file_path: None,
56
title_override: Some(source_label.into()),
57
dialog: PrintDialog::default(),
58
preview_zoom: 1.0,
59
fatal_error: None,
60
exit_requested: false,
61
};
56
let mut app = Self::blank();
57
app.body = file.body;
58
app.metadata = file.metadata;
59
app.title_override = Some(source_label.into());
62
60
if let Err(e) = app.dialog.prepare(&app.body) {
63
61
app.fatal_error = Some(e);
64
62
}
65
63
app
66
64
}
67
65
66
pub fn from_launch(launch: PosprintLaunch) -> Self {
67
let label = launch
68
.file
69
.metadata
70
.title
71
.clone()
72
.unwrap_or_else(|| "posprint://".into());
73
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
}
88
}
89
app
90
}
91
68
92
pub fn from_error(message: impl Into<String>) -> Self {
93
let mut app = Self::blank();
94
app.title_override = Some("posprint://".into());
95
app.fatal_error = Some(message.into());
96
app
97
}
98
99
fn blank() -> Self {
69
100
Self {
70
101
body: String::new(),
71
102
metadata: PosMetadata::default(),
72
103
file_path: None,
73
title_override: Some("posprint://".into()),
104
title_override: None,
74
105
dialog: PrintDialog::default(),
75
106
preview_zoom: 1.0,
76
fatal_error: Some(message.into()),
107
fatal_error: None,
77
108
exit_requested: false,
109
auto_print: false,
110
pending_trust: None,
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
}
78
153
}
79
154
}
80
155
@@ -94,6 +169,24 @@ impl PrintOnlyApp {
94
169
fn request_exit(&mut self) {
95
170
self.exit_requested = true;
96
171
}
172
173
fn try_auto_print(&mut self, ctx: &egui::Context) {
174
if !self.auto_print || self.auto_print_attempted || self.fatal_error.is_some() {
175
return;
176
}
177
if self.dialog.printers_loading {
178
ctx.request_repaint();
179
return;
180
}
181
self.auto_print_attempted = true;
182
if self
183
.dialog
184
.execute_print(&self.body, &self.metadata, self.file_path.as_ref())
185
== PrintExecuteResult::Printed
186
{
187
self.request_exit();
188
}
189
}
97
190
}
98
191
99
192
impl eframe::App for PrintOnlyApp {
@@ -104,8 +197,57 @@ impl eframe::App for PrintOnlyApp {
104
197
}
105
198
106
199
self.dialog.poll_printer_discovery(ctx);
200
self.poll_referrer_verification(ctx);
107
201
ctx.send_viewport_cmd(egui::ViewportCommand::Title(self.title()));
108
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
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
109
251
if let Some(err) = self.fatal_error.clone() {
110
252
egui::CentralPanel::default().show(ctx, |ui| {
111
253
ui.heading("Print");
@@ -118,11 +260,12 @@ impl eframe::App for PrintOnlyApp {
118
260
return;
119
261
}
120
262
263
self.try_auto_print(ctx);
264
121
265
let mut action = PrintDialogAction::None;
122
266
123
267
egui::CentralPanel::default().show(ctx, |ui| {
124
268
let available = ui.available_size();
125
// Preview left (~55%), print controls right.
126
269
let preview_width = (available.x * 0.55).clamp(280.0, available.x - 320.0);
127
270
128
271
ui.horizontal(|ui| {
@@ -168,7 +311,6 @@ impl eframe::App for PrintOnlyApp {
168
311
egui::vec2(ui.available_width(), available.y),
169
312
egui::Layout::top_down(egui::Align::Min),
170
313
|ui| {
171
// No outer ScrollArea: nested scroll steals wheel events from the printer list.
172
314
action = self.dialog.show_ui(ui);
173
315
},
174
316
);
@@ -1,10 +1,14 @@1
//! Print dialog + live preview, then exit.
1
//! Print dialog + live preview, then exit.
2
2
3
use std::path::PathBuf;
3
use std::path::PathBuf;
4
use std::sync::mpsc::{self, Receiver, TryRecvError};
4
5
5
use eframe::egui;
6
use eframe::egui;
6
7
8
use posprint::config::AppConfig;
7
use posprint::io::{PosFile, PosMetadata};
9
use posprint::io::{PosFile, PosMetadata};
10
use posprint::protocol_url::PosprintLaunch;
11
use posprint::referrer_verify;
8
12
9
use crate::preview_panel::show_preview_panel;
13
use crate::preview_panel::show_preview_panel;
10
use crate::print_dialog::{PrintDialog, PrintDialogAction, PrintExecuteResult};
14
use crate::print_dialog::{PrintDialog, PrintDialogAction, PrintExecuteResult};
@@ -19,20 +23,20 @@ pub struct PrintOnlyApp {19
preview_zoom: f32,
23
preview_zoom: f32,
20
fatal_error: Option<String>,
24
fatal_error: Option<String>,
21
exit_requested: bool,
25
exit_requested: bool,
26
/// Auto-print once printers are ready (after trust if needed).
27
auto_print: bool,
28
/// Pending first-time trust confirmation for this hostname.
29
pending_trust: Option<String>,
30
auto_print_attempted: bool,
31
/// Background GET of `referrer=` for noconfirm.
32
referrer_rx: Option<Receiver<Result<String, String>>>,
33
verifying_referrer: bool,
22
}
34
}
23
35
24
impl PrintOnlyApp {
36
impl PrintOnlyApp {
25
pub fn new(path: PathBuf) -> Self {
37
pub fn new(path: PathBuf) -> Self {
26
let mut app = Self {
38
let mut app = Self::blank();
27
body: String::new(),
39
app.file_path = Some(path.clone());
28
metadata: PosMetadata::default(),
29
file_path: Some(path.clone()),
30
title_override: None,
31
dialog: PrintDialog::default(),
32
preview_zoom: 1.0,
33
fatal_error: None,
34
exit_requested: false,
35
};
36
40
37
match PosFile::load_from_path(&path) {
41
match PosFile::load_from_path(&path) {
38
Ok(file) => {
42
Ok(file) => {
@@ -49,32 +53,103 @@ impl PrintOnlyApp {49
}
53
}
50
54
51
pub fn from_pos_file(file: PosFile, source_label: impl Into<String>) -> Self {
55
pub fn from_pos_file(file: PosFile, source_label: impl Into<String>) -> Self {
52
let mut app = Self {
56
let mut app = Self::blank();
53
body: file.body,
57
app.body = file.body;
54
metadata: file.metadata,
58
app.metadata = file.metadata;
55
file_path: None,
59
app.title_override = Some(source_label.into());
56
title_override: Some(source_label.into()),
57
dialog: PrintDialog::default(),
58
preview_zoom: 1.0,
59
fatal_error: None,
60
exit_requested: false,
61
};
62
if let Err(e) = app.dialog.prepare(&app.body) {
60
if let Err(e) = app.dialog.prepare(&app.body) {
63
app.fatal_error = Some(e);
61
app.fatal_error = Some(e);
64
}
62
}
65
app
63
app
66
}
64
}
67
65
66
pub fn from_launch(launch: PosprintLaunch) -> Self {
67
let label = launch
68
.file
69
.metadata
70
.title
71
.clone()
72
.unwrap_or_else(|| "posprint://".into());
73
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
}
88
}
89
app
90
}
91
68
pub fn from_error(message: impl Into<String>) -> Self {
92
pub fn from_error(message: impl Into<String>) -> Self {
93
let mut app = Self::blank();
94
app.title_override = Some("posprint://".into());
95
app.fatal_error = Some(message.into());
96
app
97
}
98
99
fn blank() -> Self {
69
Self {
100
Self {
70
body: String::new(),
101
body: String::new(),
71
metadata: PosMetadata::default(),
102
metadata: PosMetadata::default(),
72
file_path: None,
103
file_path: None,
73
title_override: Some("posprint://".into()),
104
title_override: None,
74
dialog: PrintDialog::default(),
105
dialog: PrintDialog::default(),
75
preview_zoom: 1.0,
106
preview_zoom: 1.0,
76
fatal_error: Some(message.into()),
107
fatal_error: None,
77
exit_requested: false,
108
exit_requested: false,
109
auto_print: false,
110
pending_trust: None,
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
}
78
}
153
}
79
}
154
}
80
155
@@ -94,6 +169,24 @@ impl PrintOnlyApp {94
fn request_exit(&mut self) {
169
fn request_exit(&mut self) {
95
self.exit_requested = true;
170
self.exit_requested = true;
96
}
171
}
172
173
fn try_auto_print(&mut self, ctx: &egui::Context) {
174
if !self.auto_print || self.auto_print_attempted || self.fatal_error.is_some() {
175
return;
176
}
177
if self.dialog.printers_loading {
178
ctx.request_repaint();
179
return;
180
}
181
self.auto_print_attempted = true;
182
if self
183
.dialog
184
.execute_print(&self.body, &self.metadata, self.file_path.as_ref())
185
== PrintExecuteResult::Printed
186
{
187
self.request_exit();
188
}
189
}
97
}
190
}
98
191
99
impl eframe::App for PrintOnlyApp {
192
impl eframe::App for PrintOnlyApp {
@@ -104,8 +197,57 @@ impl eframe::App for PrintOnlyApp {104
}
197
}
105
198
106
self.dialog.poll_printer_discovery(ctx);
199
self.dialog.poll_printer_discovery(ctx);
200
self.poll_referrer_verification(ctx);
107
ctx.send_viewport_cmd(egui::ViewportCommand::Title(self.title()));
201
ctx.send_viewport_cmd(egui::ViewportCommand::Title(self.title()));
108
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
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
109
if let Some(err) = self.fatal_error.clone() {
251
if let Some(err) = self.fatal_error.clone() {
110
egui::CentralPanel::default().show(ctx, |ui| {
252
egui::CentralPanel::default().show(ctx, |ui| {
111
ui.heading("Print");
253
ui.heading("Print");
@@ -118,11 +260,12 @@ impl eframe::App for PrintOnlyApp {118
return;
260
return;
119
}
261
}
120
262
263
self.try_auto_print(ctx);
264
121
let mut action = PrintDialogAction::None;
265
let mut action = PrintDialogAction::None;
122
266
123
egui::CentralPanel::default().show(ctx, |ui| {
267
egui::CentralPanel::default().show(ctx, |ui| {
124
let available = ui.available_size();
268
let available = ui.available_size();
125
// Preview left (~55%), print controls right.
126
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);
127
270
128
ui.horizontal(|ui| {
271
ui.horizontal(|ui| {
@@ -168,7 +311,6 @@ impl eframe::App for PrintOnlyApp {168
egui::vec2(ui.available_width(), available.y),
311
egui::vec2(ui.available_width(), available.y),
169
egui::Layout::top_down(egui::Align::Min),
312
egui::Layout::top_down(egui::Align::Min),
170
|ui| {
313
|ui| {
171
// No outer ScrollArea: nested scroll steals wheel events from the printer list.
172
action = self.dialog.show_ui(ui);
314
action = self.dialog.show_ui(ui);
173
},
315
},
174
);
316
);
@@ -51,6 +51,24 @@ impl From<serde_json::Error> for ProtocolUrlError {
51
51
}
52
52
}
53
53
54
/// Decoded `posprint://` launch request.
55
#[derive(Debug, Clone, PartialEq)]
56
pub struct PosprintLaunch {
57
pub file: PosFile,
58
/// When true, print without waiting for the Print button (subject to referrer verify + trust).
59
pub noconfirm: bool,
60
/// Verification URL from `referrer=` (percent-decoded; may be scheme-less).
61
pub referrer: Option<String>,
62
}
63
64
/// Optional extras when encoding a URL.
65
#[derive(Debug, Clone, Default)]
66
pub struct EncodeOptions {
67
pub noconfirm: bool,
68
/// Full verification URL or `host/path?query` (stored percent-encoded in the posprint URL).
69
pub referrer: Option<String>,
70
}
71
54
72
/// True when `s` looks like a `posprint:` / `posprint://` protocol URL.
55
73
pub fn is_posprint_url(s: &str) -> bool {
56
74
let s = s.trim();
@@ -60,6 +78,14 @@ pub fn is_posprint_url(s: &str) -> bool {
60
78
61
79
/// Encode a `.pos` file as `posprint://print?v=1&d=…` (raw deflate + base64url, no padding).
62
80
pub fn encode_posprint_url(file: &PosFile) -> Result<String, ProtocolUrlError> {
81
encode_posprint_url_with_options(file, &EncodeOptions::default())
82
}
83
84
/// Encode with optional `noconfirm` / `referrer` query parameters.
85
pub fn encode_posprint_url_with_options(
86
file: &PosFile,
87
options: &EncodeOptions,
88
) -> Result<String, ProtocolUrlError> {
63
89
let json = serde_json::to_vec(file)?;
64
90
let mut encoder = DeflateEncoder::new(Vec::new(), Compression::best());
65
91
encoder
@@ -69,11 +95,22 @@ pub fn encode_posprint_url(file: &PosFile) -> Result<String, ProtocolUrlError> {
69
95
.finish()
70
96
.map_err(|e| ProtocolUrlError::Inflate(e.to_string()))?;
71
97
let b64 = URL_SAFE_NO_PAD.encode(compressed);
72
Ok(format!("posprint://print?v=1&d={b64}"))
98
let mut url = format!("posprint://print?v=1&d={b64}");
99
if options.noconfirm {
100
url.push_str("&noconfirm=1");
101
}
102
if let Some(raw) = options.referrer.as_deref() {
103
let trimmed = raw.trim();
104
if !trimmed.is_empty() {
105
url.push_str("&referrer=");
106
url.push_str(&percent_encode_component(trimmed));
107
}
108
}
109
Ok(url)
73
110
}
74
111
75
/// Decode a `posprint://print?v=1&d=…` URL into a [`PosFile`].
76
pub fn parse_posprint_url(url: &str) -> Result<PosFile, ProtocolUrlError> {
112
/// Decode a `posprint://print?v=1&d=…` URL into a [`PosprintLaunch`].
113
pub fn parse_posprint_url(url: &str) -> Result<PosprintLaunch, ProtocolUrlError> {
77
114
let url = url.trim();
78
115
if !is_posprint_url(url) {
79
116
return Err(ProtocolUrlError::NotPosprintUrl);
@@ -98,6 +135,8 @@ pub fn parse_posprint_url(url: &str) -> Result<PosFile, ProtocolUrlError> {
98
135
99
136
let mut version: Option<String> = None;
100
137
let mut payload: Option<String> = None;
138
let mut noconfirm = false;
139
let mut referrer: Option<String> = None;
101
140
for pair in query.split('&') {
102
141
if pair.is_empty() {
103
142
continue;
@@ -107,6 +146,13 @@ pub fn parse_posprint_url(url: &str) -> Result<PosFile, ProtocolUrlError> {
107
146
match key.as_str() {
108
147
"v" => version = Some(percent_decode_str(value)?),
109
148
"d" => payload = Some(percent_decode_str(value)?),
149
"noconfirm" => noconfirm = parse_bool_flag(value),
150
"referrer" => {
151
let decoded = percent_decode_str(value)?;
152
if !decoded.trim().is_empty() {
153
referrer = Some(decoded);
154
}
155
}
110
156
_ => {}
111
157
}
112
158
}
@@ -131,7 +177,36 @@ pub fn parse_posprint_url(url: &str) -> Result<PosFile, ProtocolUrlError> {
131
177
if file.version != 1 {
132
178
return Err(ProtocolUrlError::UnsupportedPosVersion(file.version));
133
179
}
134
Ok(file)
180
181
Ok(PosprintLaunch {
182
file,
183
noconfirm,
184
referrer,
185
})
186
}
187
188
fn parse_bool_flag(value: &str) -> bool {
189
let v = value.trim();
190
if v.is_empty() {
191
return true;
192
}
193
matches!(
194
v.to_ascii_lowercase().as_str(),
195
"1" | "true" | "yes" | "on"
196
)
197
}
198
199
fn percent_encode_component(input: &str) -> String {
200
let mut out = String::with_capacity(input.len());
201
for b in input.bytes() {
202
match b {
203
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
204
out.push(b as char);
205
}
206
_ => out.push_str(&format!("%{b:02X}")),
207
}
208
}
209
out
135
210
}
136
211
137
212
fn percent_decode_str(input: &str) -> Result<String, ProtocolUrlError> {
@@ -204,7 +279,41 @@ mod tests {
204
279
let url = encode_posprint_url(&file).unwrap();
205
280
assert!(url.starts_with("posprint://print?v=1&d="));
206
281
let decoded = parse_posprint_url(&url).unwrap();
207
assert_eq!(decoded, file);
282
assert_eq!(decoded.file, file);
283
assert!(!decoded.noconfirm);
284
assert!(decoded.referrer.is_none());
285
}
286
287
#[test]
288
fn encodes_and_parses_noconfirm_and_referrer() {
289
let file = sample_file();
290
let url = encode_posprint_url_with_options(
291
&file,
292
&EncodeOptions {
293
noconfirm: true,
294
referrer: Some("website.com/bonnen/verify?code=84923".into()),
295
},
296
)
297
.unwrap();
298
assert!(url.contains("&noconfirm=1"));
299
assert!(url.contains("&referrer="));
300
assert!(url.contains("code%3D84923") || url.contains("code%3d84923"));
301
let launch = parse_posprint_url(&url).unwrap();
302
assert!(launch.noconfirm);
303
assert_eq!(
304
launch.referrer.as_deref(),
305
Some("website.com/bonnen/verify?code=84923")
306
);
307
}
308
309
#[test]
310
fn parses_noconfirm_without_value() {
311
let file = sample_file();
312
let base = encode_posprint_url(&file).unwrap();
313
let url = format!("{base}&noconfirm&referrer=shop.example%2Fv");
314
let launch = parse_posprint_url(&url).unwrap();
315
assert!(launch.noconfirm);
316
assert_eq!(launch.referrer.as_deref(), Some("shop.example/v"));
208
317
}
209
318
210
319
#[test]
@@ -51,6 +51,24 @@ impl From<serde_json::Error> for ProtocolUrlError {51
}
51
}
52
}
52
}
53
53
54
/// Decoded `posprint://` launch request.
55
#[derive(Debug, Clone, PartialEq)]
56
pub struct PosprintLaunch {
57
pub file: PosFile,
58
/// When true, print without waiting for the Print button (subject to referrer verify + trust).
59
pub noconfirm: bool,
60
/// Verification URL from `referrer=` (percent-decoded; may be scheme-less).
61
pub referrer: Option<String>,
62
}
63
64
/// Optional extras when encoding a URL.
65
#[derive(Debug, Clone, Default)]
66
pub struct EncodeOptions {
67
pub noconfirm: bool,
68
/// Full verification URL or `host/path?query` (stored percent-encoded in the posprint URL).
69
pub referrer: Option<String>,
70
}
71
54
/// True when `s` looks like a `posprint:` / `posprint://` protocol URL.
72
/// True when `s` looks like a `posprint:` / `posprint://` protocol URL.
55
pub fn is_posprint_url(s: &str) -> bool {
73
pub fn is_posprint_url(s: &str) -> bool {
56
let s = s.trim();
74
let s = s.trim();
@@ -60,6 +78,14 @@ pub fn is_posprint_url(s: &str) -> bool {60
78
61
/// Encode a `.pos` file as `posprint://print?v=1&d=…` (raw deflate + base64url, no padding).
79
/// Encode a `.pos` file as `posprint://print?v=1&d=…` (raw deflate + base64url, no padding).
62
pub fn encode_posprint_url(file: &PosFile) -> Result<String, ProtocolUrlError> {
80
pub fn encode_posprint_url(file: &PosFile) -> Result<String, ProtocolUrlError> {
81
encode_posprint_url_with_options(file, &EncodeOptions::default())
82
}
83
84
/// Encode with optional `noconfirm` / `referrer` query parameters.
85
pub fn encode_posprint_url_with_options(
86
file: &PosFile,
87
options: &EncodeOptions,
88
) -> Result<String, ProtocolUrlError> {
63
let json = serde_json::to_vec(file)?;
89
let json = serde_json::to_vec(file)?;
64
let mut encoder = DeflateEncoder::new(Vec::new(), Compression::best());
90
let mut encoder = DeflateEncoder::new(Vec::new(), Compression::best());
65
encoder
91
encoder
@@ -69,11 +95,22 @@ pub fn encode_posprint_url(file: &PosFile) -> Result<String, ProtocolUrlError> {69
.finish()
95
.finish()
70
.map_err(|e| ProtocolUrlError::Inflate(e.to_string()))?;
96
.map_err(|e| ProtocolUrlError::Inflate(e.to_string()))?;
71
let b64 = URL_SAFE_NO_PAD.encode(compressed);
97
let b64 = URL_SAFE_NO_PAD.encode(compressed);
72
Ok(format!("posprint://print?v=1&d={b64}"))
98
let mut url = format!("posprint://print?v=1&d={b64}");
99
if options.noconfirm {
100
url.push_str("&noconfirm=1");
101
}
102
if let Some(raw) = options.referrer.as_deref() {
103
let trimmed = raw.trim();
104
if !trimmed.is_empty() {
105
url.push_str("&referrer=");
106
url.push_str(&percent_encode_component(trimmed));
107
}
108
}
109
Ok(url)
73
}
110
}
74
111
75
/// Decode a `posprint://print?v=1&d=…` URL into a [`PosFile`].
112
/// Decode a `posprint://print?v=1&d=…` URL into a [`PosprintLaunch`].
76
pub fn parse_posprint_url(url: &str) -> Result<PosFile, ProtocolUrlError> {
113
pub fn parse_posprint_url(url: &str) -> Result<PosprintLaunch, ProtocolUrlError> {
77
let url = url.trim();
114
let url = url.trim();
78
if !is_posprint_url(url) {
115
if !is_posprint_url(url) {
79
return Err(ProtocolUrlError::NotPosprintUrl);
116
return Err(ProtocolUrlError::NotPosprintUrl);
@@ -98,6 +135,8 @@ pub fn parse_posprint_url(url: &str) -> Result<PosFile, ProtocolUrlError> {98
135
99
let mut version: Option<String> = None;
136
let mut version: Option<String> = None;
100
let mut payload: Option<String> = None;
137
let mut payload: Option<String> = None;
138
let mut noconfirm = false;
139
let mut referrer: Option<String> = None;
101
for pair in query.split('&') {
140
for pair in query.split('&') {
102
if pair.is_empty() {
141
if pair.is_empty() {
103
continue;
142
continue;
@@ -107,6 +146,13 @@ pub fn parse_posprint_url(url: &str) -> Result<PosFile, ProtocolUrlError> {107
match key.as_str() {
146
match key.as_str() {
108
"v" => version = Some(percent_decode_str(value)?),
147
"v" => version = Some(percent_decode_str(value)?),
109
"d" => payload = Some(percent_decode_str(value)?),
148
"d" => payload = Some(percent_decode_str(value)?),
149
"noconfirm" => noconfirm = parse_bool_flag(value),
150
"referrer" => {
151
let decoded = percent_decode_str(value)?;
152
if !decoded.trim().is_empty() {
153
referrer = Some(decoded);
154
}
155
}
110
_ => {}
156
_ => {}
111
}
157
}
112
}
158
}
@@ -131,7 +177,36 @@ pub fn parse_posprint_url(url: &str) -> Result<PosFile, ProtocolUrlError> {131
if file.version != 1 {
177
if file.version != 1 {
132
return Err(ProtocolUrlError::UnsupportedPosVersion(file.version));
178
return Err(ProtocolUrlError::UnsupportedPosVersion(file.version));
133
}
179
}
134
Ok(file)
180
181
Ok(PosprintLaunch {
182
file,
183
noconfirm,
184
referrer,
185
})
186
}
187
188
fn parse_bool_flag(value: &str) -> bool {
189
let v = value.trim();
190
if v.is_empty() {
191
return true;
192
}
193
matches!(
194
v.to_ascii_lowercase().as_str(),
195
"1" | "true" | "yes" | "on"
196
)
197
}
198
199
fn percent_encode_component(input: &str) -> String {
200
let mut out = String::with_capacity(input.len());
201
for b in input.bytes() {
202
match b {
203
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
204
out.push(b as char);
205
}
206
_ => out.push_str(&format!("%{b:02X}")),
207
}
208
}
209
out
135
}
210
}
136
211
137
fn percent_decode_str(input: &str) -> Result<String, ProtocolUrlError> {
212
fn percent_decode_str(input: &str) -> Result<String, ProtocolUrlError> {
@@ -204,7 +279,41 @@ mod tests {204
let url = encode_posprint_url(&file).unwrap();
279
let url = encode_posprint_url(&file).unwrap();
205
assert!(url.starts_with("posprint://print?v=1&d="));
280
assert!(url.starts_with("posprint://print?v=1&d="));
206
let decoded = parse_posprint_url(&url).unwrap();
281
let decoded = parse_posprint_url(&url).unwrap();
207
assert_eq!(decoded, file);
282
assert_eq!(decoded.file, file);
283
assert!(!decoded.noconfirm);
284
assert!(decoded.referrer.is_none());
285
}
286
287
#[test]
288
fn encodes_and_parses_noconfirm_and_referrer() {
289
let file = sample_file();
290
let url = encode_posprint_url_with_options(
291
&file,
292
&EncodeOptions {
293
noconfirm: true,
294
referrer: Some("website.com/bonnen/verify?code=84923".into()),
295
},
296
)
297
.unwrap();
298
assert!(url.contains("&noconfirm=1"));
299
assert!(url.contains("&referrer="));
300
assert!(url.contains("code%3D84923") || url.contains("code%3d84923"));
301
let launch = parse_posprint_url(&url).unwrap();
302
assert!(launch.noconfirm);
303
assert_eq!(
304
launch.referrer.as_deref(),
305
Some("website.com/bonnen/verify?code=84923")
306
);
307
}
308
309
#[test]
310
fn parses_noconfirm_without_value() {
311
let file = sample_file();
312
let base = encode_posprint_url(&file).unwrap();
313
let url = format!("{base}&noconfirm&referrer=shop.example%2Fv");
314
let launch = parse_posprint_url(&url).unwrap();
315
assert!(launch.noconfirm);
316
assert_eq!(launch.referrer.as_deref(), Some("shop.example/v"));
208
}
317
}
209
318
210
#[test]
319
#[test]
@@ -0,0 +1,197 @@
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 allow_local_referrer() -> bool {
91
matches!(
92
std::env::var("POSPRINT_ALLOW_LOCAL_REFERRER")
93
.unwrap_or_default()
94
.to_ascii_lowercase()
95
.as_str(),
96
"1" | "true" | "yes"
97
)
98
}
99
100
fn is_blocked_verify_host(host: &str) -> bool {
101
let h = host.to_ascii_lowercase();
102
let is_loopback_name = h == "localhost" || h.ends_with(".localhost") || h == "0.0.0.0";
103
if let Ok(ip) = h.parse::<IpAddr>() {
104
let loopback = match ip {
105
IpAddr::V4(v4) => v4.is_loopback() || v4.is_unspecified(),
106
IpAddr::V6(v6) => v6.is_loopback() || v6.is_unspecified(),
107
};
108
if loopback {
109
return !allow_local_referrer();
110
}
111
return match ip {
112
IpAddr::V4(v4) => v4.is_private() || v4.is_link_local(),
113
IpAddr::V6(_) => false,
114
};
115
}
116
if is_loopback_name {
117
return !allow_local_referrer();
118
}
119
false
120
}
121
122
/// True when an HTTP status means the print request is authorized by the site.
123
pub fn is_verification_success(status: u16) -> bool {
124
status == 200
125
}
126
127
/// GET `referrer_url` (no redirects). On HTTP 200 returns the trust hostname.
128
pub fn verify_referrer(referrer_url: &str) -> Result<String, ReferrerVerifyError> {
129
let url = normalize_referrer_url(referrer_url)?;
130
let host = referrer_trust_host(&url)
131
.ok_or_else(|| ReferrerVerifyError::InvalidUrl("missing host".into()))?;
132
133
let agent = ureq::AgentBuilder::new()
134
.timeout_connect(Duration::from_secs(VERIFY_TIMEOUT_SECS))
135
.timeout_read(Duration::from_secs(VERIFY_TIMEOUT_SECS))
136
.redirects(0)
137
.build();
138
139
let response = agent.get(&url).call().map_err(|e| match e {
140
ureq::Error::Status(code, _) => ReferrerVerifyError::HttpStatus(code),
141
other => ReferrerVerifyError::Network(other.to_string()),
142
})?;
143
144
let status = response.status();
145
if !is_verification_success(status) {
146
return Err(ReferrerVerifyError::HttpStatus(status));
147
}
148
Ok(host)
149
}
150
151
#[cfg(test)]
152
mod tests {
153
use super::*;
154
use std::sync::Mutex;
155
156
static ENV_LOCK: Mutex<()> = Mutex::new(());
157
158
#[test]
159
fn normalizes_bare_host_path_to_https() {
160
let url = normalize_referrer_url("website.com/bonnen/verify?code=84923").unwrap();
161
assert_eq!(url, "https://website.com/bonnen/verify?code=84923");
162
assert_eq!(referrer_trust_host(&url).as_deref(), Some("website.com"));
163
}
164
165
#[test]
166
fn rejects_non_http_schemes() {
167
let err = normalize_referrer_url("file:///etc/passwd").unwrap_err();
168
assert!(matches!(err, ReferrerVerifyError::UnsupportedScheme(_)));
169
}
170
171
#[test]
172
fn blocks_localhost() {
173
let _g = ENV_LOCK.lock().unwrap();
174
std::env::remove_var("POSPRINT_ALLOW_LOCAL_REFERRER");
175
let err = normalize_referrer_url("http://127.0.0.1/verify").unwrap_err();
176
assert!(matches!(err, ReferrerVerifyError::BlockedHost(_)));
177
let err = normalize_referrer_url("https://localhost/x").unwrap_err();
178
assert!(matches!(err, ReferrerVerifyError::BlockedHost(_)));
179
}
180
181
#[test]
182
fn allows_localhost_when_env_set() {
183
let _g = ENV_LOCK.lock().unwrap();
184
std::env::set_var("POSPRINT_ALLOW_LOCAL_REFERRER", "1");
185
let url = normalize_referrer_url("http://127.0.0.1:8765/verify?code=1").unwrap();
186
assert_eq!(url, "http://127.0.0.1:8765/verify?code=1");
187
std::env::remove_var("POSPRINT_ALLOW_LOCAL_REFERRER");
188
}
189
190
#[test]
191
fn only_http_200_counts_as_success() {
192
assert!(is_verification_success(200));
193
assert!(!is_verification_success(204));
194
assert!(!is_verification_success(404));
195
assert!(!is_verification_success(302));
196
}
197
}
@@ -0,0 +1,197 @@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 allow_local_referrer() -> bool {
91
matches!(
92
std::env::var("POSPRINT_ALLOW_LOCAL_REFERRER")
93
.unwrap_or_default()
94
.to_ascii_lowercase()
95
.as_str(),
96
"1" | "true" | "yes"
97
)
98
}
99
100
fn is_blocked_verify_host(host: &str) -> bool {
101
let h = host.to_ascii_lowercase();
102
let is_loopback_name = h == "localhost" || h.ends_with(".localhost") || h == "0.0.0.0";
103
if let Ok(ip) = h.parse::<IpAddr>() {
104
let loopback = match ip {
105
IpAddr::V4(v4) => v4.is_loopback() || v4.is_unspecified(),
106
IpAddr::V6(v6) => v6.is_loopback() || v6.is_unspecified(),
107
};
108
if loopback {
109
return !allow_local_referrer();
110
}
111
return match ip {
112
IpAddr::V4(v4) => v4.is_private() || v4.is_link_local(),
113
IpAddr::V6(_) => false,
114
};
115
}
116
if is_loopback_name {
117
return !allow_local_referrer();
118
}
119
false
120
}
121
122
/// True when an HTTP status means the print request is authorized by the site.
123
pub fn is_verification_success(status: u16) -> bool {
124
status == 200
125
}
126
127
/// GET `referrer_url` (no redirects). On HTTP 200 returns the trust hostname.
128
pub fn verify_referrer(referrer_url: &str) -> Result<String, ReferrerVerifyError> {
129
let url = normalize_referrer_url(referrer_url)?;
130
let host = referrer_trust_host(&url)
131
.ok_or_else(|| ReferrerVerifyError::InvalidUrl("missing host".into()))?;
132
133
let agent = ureq::AgentBuilder::new()
134
.timeout_connect(Duration::from_secs(VERIFY_TIMEOUT_SECS))
135
.timeout_read(Duration::from_secs(VERIFY_TIMEOUT_SECS))
136
.redirects(0)
137
.build();
138
139
let response = agent.get(&url).call().map_err(|e| match e {
140
ureq::Error::Status(code, _) => ReferrerVerifyError::HttpStatus(code),
141
other => ReferrerVerifyError::Network(other.to_string()),
142
})?;
143
144
let status = response.status();
145
if !is_verification_success(status) {
146
return Err(ReferrerVerifyError::HttpStatus(status));
147
}
148
Ok(host)
149
}
150
151
#[cfg(test)]
152
mod tests {
153
use super::*;
154
use std::sync::Mutex;
155
156
static ENV_LOCK: Mutex<()> = Mutex::new(());
157
158
#[test]
159
fn normalizes_bare_host_path_to_https() {
160
let url = normalize_referrer_url("website.com/bonnen/verify?code=84923").unwrap();
161
assert_eq!(url, "https://website.com/bonnen/verify?code=84923");
162
assert_eq!(referrer_trust_host(&url).as_deref(), Some("website.com"));
163
}
164
165
#[test]
166
fn rejects_non_http_schemes() {
167
let err = normalize_referrer_url("file:///etc/passwd").unwrap_err();
168
assert!(matches!(err, ReferrerVerifyError::UnsupportedScheme(_)));
169
}
170
171
#[test]
172
fn blocks_localhost() {
173
let _g = ENV_LOCK.lock().unwrap();
174
std::env::remove_var("POSPRINT_ALLOW_LOCAL_REFERRER");
175
let err = normalize_referrer_url("http://127.0.0.1/verify").unwrap_err();
176
assert!(matches!(err, ReferrerVerifyError::BlockedHost(_)));
177
let err = normalize_referrer_url("https://localhost/x").unwrap_err();
178
assert!(matches!(err, ReferrerVerifyError::BlockedHost(_)));
179
}
180
181
#[test]
182
fn allows_localhost_when_env_set() {
183
let _g = ENV_LOCK.lock().unwrap();
184
std::env::set_var("POSPRINT_ALLOW_LOCAL_REFERRER", "1");
185
let url = normalize_referrer_url("http://127.0.0.1:8765/verify?code=1").unwrap();
186
assert_eq!(url, "http://127.0.0.1:8765/verify?code=1");
187
std::env::remove_var("POSPRINT_ALLOW_LOCAL_REFERRER");
188
}
189
190
#[test]
191
fn only_http_200_counts_as_success() {
192
assert!(is_verification_success(200));
193
assert!(!is_verification_success(204));
194
assert!(!is_verification_success(404));
195
assert!(!is_verification_success(302));
196
}
197
}