Merge branch 'fix/no-console-allow-localhost'
@@ -384,7 +384,7 @@ checksum = "ae36dc4177970ef04fde5178d3e2429882def40e57a451f919c098f72baa6cec"
384
384
dependencies = [
385
385
"proc-macro2",
386
386
"quote",
387
"syn 3.0.2",
387
"syn 3.0.3",
388
388
]
389
389
390
390
[[package]]
@@ -686,9 +686,9 @@ dependencies = [
686
686
687
687
[[package]]
688
688
name = "clap"
689
version = "4.6.3"
689
version = "4.6.4"
690
690
source = "registry+https://github.com/rust-lang/crates.io-index"
691
checksum = "0fb99565819980999fb7b4a1796046a5c949e6d4ff132cf5fadf5a641e20d776"
691
checksum = "d91e0c145792ef73a6ad36d27c75ac09f1832222a3c209689d90f534685ee5b7"
692
692
dependencies = [
693
693
"clap_builder",
694
694
"clap_derive",
@@ -708,14 +708,14 @@ dependencies = [
708
708
709
709
[[package]]
710
710
name = "clap_derive"
711
version = "4.6.3"
711
version = "4.6.4"
712
712
source = "registry+https://github.com/rust-lang/crates.io-index"
713
checksum = "32f2392eae7f16557a3d727ef3a12e57b2b2ca6f98566a5f4fb41ffe305df077"
713
checksum = "d012d2b9d65aca7f18f4d9878a045bc17899bba951561ba5ec3c2ba1eed9a061"
714
714
dependencies = [
715
715
"heck",
716
716
"proc-macro2",
717
717
"quote",
718
"syn 2.0.119",
718
"syn 3.0.3",
719
719
]
720
720
721
721
[[package]]
@@ -1912,9 +1912,9 @@ checksum = "7a79a3332a6609480d7d0c9eab957bca6b455b91bb84e66d19f5ff66294b85b8"
1912
1912
1913
1913
[[package]]
1914
1914
name = "libc"
1915
version = "0.2.188"
1915
version = "0.2.189"
1916
1916
source = "registry+https://github.com/rust-lang/crates.io-index"
1917
checksum = "22053b6a34f84abc97f9129e61334f40174659a1b9bd18c970b83db6a9a6348b"
1917
checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"
1918
1918
1919
1919
[[package]]
1920
1920
name = "libfuzzer-sys"
@@ -2786,7 +2786,7 @@ checksum = "2f3a9f18d041e6d0e102a0a46750538147e5e8992d3b4873aaafee2520b00ce3"
2786
2786
2787
2787
[[package]]
2788
2788
name = "posprint"
2789
version = "0.5.2"
2789
version = "0.5.3"
2790
2790
dependencies = [
2791
2791
"barcoders",
2792
2792
"base64",
@@ -3316,7 +3316,7 @@ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
3316
3316
dependencies = [
3317
3317
"proc-macro2",
3318
3318
"quote",
3319
"syn 3.0.2",
3319
"syn 3.0.3",
3320
3320
]
3321
3321
3322
3322
[[package]]
@@ -3340,7 +3340,7 @@ checksum = "8d3b1629de253c70a0508c3899572da79ca359fdab27c7920ff00406df418906"
3340
3340
dependencies = [
3341
3341
"proc-macro2",
3342
3342
"quote",
3343
"syn 3.0.2",
3343
"syn 3.0.3",
3344
3344
]
3345
3345
3346
3346
[[package]]
@@ -3570,9 +3570,9 @@ dependencies = [
3570
3570
3571
3571
[[package]]
3572
3572
name = "syn"
3573
version = "3.0.2"
3573
version = "3.0.3"
3574
3574
source = "registry+https://github.com/rust-lang/crates.io-index"
3575
checksum = "a207d6d6a2b7fc470b80443726053f18a2481b7e1eee970597051596567987a3"
3575
checksum = "53e9bae58849f64dfa4f5d5ae372c8341f7305f82a3868709269343628b659a3"
3576
3576
dependencies = [
3577
3577
"proc-macro2",
3578
3578
"quote",
@@ -3649,7 +3649,7 @@ checksum = "43cbfe0cf76104d42a574802844187e84a305e531ed54455f11fbde0f10541cd"
3649
3649
dependencies = [
3650
3650
"proc-macro2",
3651
3651
"quote",
3652
"syn 3.0.2",
3652
"syn 3.0.3",
3653
3653
]
3654
3654
3655
3655
[[package]]
@@ -384,7 +384,7 @@ checksum = "ae36dc4177970ef04fde5178d3e2429882def40e57a451f919c098f72baa6cec"384
dependencies = [384
dependencies = [385
"proc-macro2",385
"proc-macro2",386
"quote",386
"quote",387
"syn 3.0.2",387
"syn 3.0.3",388
]388
]389
389
390
[[package]]390
[[package]]@@ -686,9 +686,9 @@ dependencies = [686
686
687
[[package]]687
[[package]]688
name = "clap"688
name = "clap"689
version = "4.6.3"689
version = "4.6.4"690
source = "registry+https://github.com/rust-lang/crates.io-index"690
source = "registry+https://github.com/rust-lang/crates.io-index"691
checksum = "0fb99565819980999fb7b4a1796046a5c949e6d4ff132cf5fadf5a641e20d776"691
checksum = "d91e0c145792ef73a6ad36d27c75ac09f1832222a3c209689d90f534685ee5b7"692
dependencies = [692
dependencies = [693
"clap_builder",693
"clap_builder",694
"clap_derive",694
"clap_derive",@@ -708,14 +708,14 @@ dependencies = [708
708
709
[[package]]709
[[package]]710
name = "clap_derive"710
name = "clap_derive"711
version = "4.6.3"711
version = "4.6.4"712
source = "registry+https://github.com/rust-lang/crates.io-index"712
source = "registry+https://github.com/rust-lang/crates.io-index"713
checksum = "32f2392eae7f16557a3d727ef3a12e57b2b2ca6f98566a5f4fb41ffe305df077"713
checksum = "d012d2b9d65aca7f18f4d9878a045bc17899bba951561ba5ec3c2ba1eed9a061"714
dependencies = [714
dependencies = [715
"heck",715
"heck",716
"proc-macro2",716
"proc-macro2",717
"quote",717
"quote",718
"syn 2.0.119",718
"syn 3.0.3",719
]719
]720
720
721
[[package]]721
[[package]]@@ -1912,9 +1912,9 @@ checksum = "7a79a3332a6609480d7d0c9eab957bca6b455b91bb84e66d19f5ff66294b85b8"1912
1912
1913
[[package]]1913
[[package]]1914
name = "libc"1914
name = "libc"1915
version = "0.2.188"1915
version = "0.2.189"1916
source = "registry+https://github.com/rust-lang/crates.io-index"1916
source = "registry+https://github.com/rust-lang/crates.io-index"1917
checksum = "22053b6a34f84abc97f9129e61334f40174659a1b9bd18c970b83db6a9a6348b"1917
checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"1918
1918
1919
[[package]]1919
[[package]]1920
name = "libfuzzer-sys"1920
name = "libfuzzer-sys"@@ -2786,7 +2786,7 @@ checksum = "2f3a9f18d041e6d0e102a0a46750538147e5e8992d3b4873aaafee2520b00ce3"2786
2786
2787
[[package]]2787
[[package]]2788
name = "posprint"2788
name = "posprint"2789
version = "0.5.2"2789
version = "0.5.3"2790
dependencies = [2790
dependencies = [2791
"barcoders",2791
"barcoders",2792
"base64",2792
"base64",@@ -3316,7 +3316,7 @@ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"3316
dependencies = [3316
dependencies = [3317
"proc-macro2",3317
"proc-macro2",3318
"quote",3318
"quote",3319
"syn 3.0.2",3319
"syn 3.0.3",3320
]3320
]3321
3321
3322
[[package]]3322
[[package]]@@ -3340,7 +3340,7 @@ checksum = "8d3b1629de253c70a0508c3899572da79ca359fdab27c7920ff00406df418906"3340
dependencies = [3340
dependencies = [3341
"proc-macro2",3341
"proc-macro2",3342
"quote",3342
"quote",3343
"syn 3.0.2",3343
"syn 3.0.3",3344
]3344
]3345
3345
3346
[[package]]3346
[[package]]@@ -3570,9 +3570,9 @@ dependencies = [3570
3570
3571
[[package]]3571
[[package]]3572
name = "syn"3572
name = "syn"3573
version = "3.0.2"3573
version = "3.0.3"3574
source = "registry+https://github.com/rust-lang/crates.io-index"3574
source = "registry+https://github.com/rust-lang/crates.io-index"3575
checksum = "a207d6d6a2b7fc470b80443726053f18a2481b7e1eee970597051596567987a3"3575
checksum = "53e9bae58849f64dfa4f5d5ae372c8341f7305f82a3868709269343628b659a3"3576
dependencies = [3576
dependencies = [3577
"proc-macro2",3577
"proc-macro2",3578
"quote",3578
"quote",@@ -3649,7 +3649,7 @@ checksum = "43cbfe0cf76104d42a574802844187e84a305e531ed54455f11fbde0f10541cd"3649
dependencies = [3649
dependencies = [3650
"proc-macro2",3650
"proc-macro2",3651
"quote",3651
"quote",3652
"syn 3.0.2",3652
"syn 3.0.3",3653
]3653
]3654
3654
3655
[[package]]3655
[[package]]@@ -1,6 +1,6 @@
1
1
[package]
2
2
name = "posprint"
3
version = "0.5.2"
3
version = "0.5.3"
4
4
edition = "2021"
5
5
rust-version = "1.88"
6
6
description = "Designer for POS-print documents"
@@ -1,6 +1,6 @@1
[package]
1
[package]
2
name = "posprint"
2
name = "posprint"
3
version = "0.5.2"
3
version = "0.5.3"
4
edition = "2021"
4
edition = "2021"
5
rust-version = "1.88"
5
rust-version = "1.88"
6
description = "Designer for POS-print documents"
6
description = "Designer for POS-print documents"
@@ -6,7 +6,7 @@ Cross-platform designer for POS (point-of-sale) receipt documents. Edit template
6
6
7
7
## Status
8
8
9
**v0.5.2** — AUR CI publish hardened (BUILDDIR perms, slim job); scrollable printer list, USB-serial filtering.
9
**v0.5.3** — `noconfirm` + trusted domains; no console flash; loopback referrer; last successful printer preference; spooler temp-file lock fix.
10
10
11
11
## Build and run
12
12
@@ -6,7 +6,7 @@ Cross-platform designer for POS (point-of-sale) receipt documents. Edit template6
6
7
## Status7
## Status8
8
9
**v0.5.2** — AUR CI publish hardened (BUILDDIR perms, slim job); scrollable printer list, USB-serial filtering.9
**v0.5.3** — `noconfirm` + trusted domains; no console flash; loopback referrer; last successful printer preference; spooler temp-file lock fix.10
10
11
## Build and run11
## Build and run12
12
@@ -76,7 +76,7 @@ ESC/POS generation is **in-tree** (`escpos.rs`), not the `escpos` crates.io pack
76
76
| Toolbar | `app.rs` | New, Open, Save, Save As, Insert, Print |
77
77
| Document page width / zoom | `app.rs` | Per-document width (mm), preview zoom |
78
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` |
79
| App config | `config.rs` | `%APPDATA%/posprint/config.json` (Windows) / `~/.config/posprint/config.json` (trusted origins, default width, last printer) |
80
80
81
81
While the print dialog is open, the main UI is disabled and editor autocomplete does not steal focus.
82
82
@@ -155,8 +155,8 @@ Legacy JSON fields `preview_mode` and `cut_after_print` are ignored if present.
155
155
|------|---------|
156
156
| Template + metadata | `.pos` file |
157
157
| Last parameter values | In-memory (`print_dialog.last_params`) |
158
| Default page width / trusted origins | `config.rs` → platform config JSON |
159
| Recent files / selected printer | Not persisted |
158
| Default page width / trusted origins / last printer | `config.rs` → platform config JSON |
159
| Recent files | Not persisted |
160
160
161
161
---
162
162
@@ -76,7 +76,7 @@ ESC/POS generation is **in-tree** (`escpos.rs`), not the `escpos` crates.io pack76
| Toolbar | `app.rs` | New, Open, Save, Save As, Insert, Print |76
| Toolbar | `app.rs` | New, Open, Save, Save As, Insert, Print |77
| Document page width / zoom | `app.rs` | Per-document width (mm), preview zoom |77
| Document page width / zoom | `app.rs` | Per-document width (mm), preview zoom |78
| 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` |79
| App config | `config.rs` | `%APPDATA%/posprint/config.json` (Windows) / `~/.config/posprint/config.json` (trusted origins, default width, last printer) |80
80
81
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.82
82
@@ -155,8 +155,8 @@ Legacy JSON fields `preview_mode` and `cut_after_print` are ignored if present.155
|------|---------|155
|------|---------|156
| Template + metadata | `.pos` file |156
| Template + metadata | `.pos` file |157
| 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 |158
| Default page width / trusted origins / last printer | `config.rs` → platform config JSON |159
| Recent files / selected printer | Not persisted |159
| Recent files | Not persisted |160
160
161
---161
---162
162
@@ -309,7 +309,7 @@ Websites can open the print dialog with an embedded template:
309
309
posprint://print?v=1&d=…
310
310
```
311
311
312
Add `&noconfirm=1&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
Add `&noconfirm=1&referrer=<percent-encoded verify URL>` to print after the site’s verify endpoint returns HTTP 200 and (on first use) the user trusts that domain (**Settings → Trusted sites**). Auto-print uses the last printer that printed successfully when that device is still available. Encoding helpers live in [`lib/`](../lib/). Full guide: [POSPRINT-URL.md](POSPRINT-URL.md).
313
313
314
314
`@image` may use `https://…` or `http://…` (downloaded when preview/print needs the image).
315
315
@@ -309,7 +309,7 @@ Websites can open the print dialog with an embedded template:309
posprint://print?v=1&d=…309
posprint://print?v=1&d=…310
```310
```311
311
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
Add `&noconfirm=1&referrer=<percent-encoded verify URL>` to print after the site’s verify endpoint returns HTTP 200 and (on first use) the user trusts that domain (**Settings → Trusted sites**). Auto-print uses the last printer that printed successfully when that device is still available. Encoding helpers live in [`lib/`](../lib/). Full guide: [POSPRINT-URL.md](POSPRINT-URL.md).313
313
314
`@image` may use `https://…` or `http://…` (downloaded when preview/print needs the image).314
`@image` may use `https://…` or `http://…` (downloaded when preview/print needs the image).315
315
@@ -48,9 +48,21 @@ The OS protocol handler only receives the URL string — not the browser Referer
48
48
| posprint shows **Trust this site?** | If trusted, prints without asking |
49
49
| **Trust and print** stores the hostname | Revoke under **Settings → Trusted sites** |
50
50
51
After a successful print, posprint remembers that printer. On the next `noconfirm` (and in the interactive dialog), it selects that printer again **if it is still connected**; otherwise it keeps the usual first/default selection.
52
51
53
Without `referrer`, `noconfirm=1` is rejected. Without `noconfirm`, behaviour is unchanged (interactive print dialog).
52
54
53
Localhost / private IP verification URLs are blocked by default. For local harnesses only, set `POSPRINT_ALLOW_LOCAL_REFERRER=1` (see `scripts/test-noconfirm/`).
55
Localhost / loopback verification URLs are allowed. Other private LAN addresses (e.g. `192.168.x.x`) are blocked.
56
57
### Browser “Open posprint?” prompt
58
59
Browsers (Chrome / Edge) always ask before launching a custom protocol. That dialog is **not** controlled by posprint.
60
61
- Typing or pasting `posprint://…` in the address bar usually offers **no** “always allow” option (no site origin).
62
- A real click from an **https://** page can show “Always allow this site to open…” once the browser remembers the choice for that origin.
63
- `http://127.0.0.1` / localhost test pages often never get a persistent allow checkbox.
64
65
No extra posprint registry or config is required for protocol registration beyond what install / first run already does.
54
66
55
67
---
56
68
@@ -48,9 +48,21 @@ The OS protocol handler only receives the URL string — not the browser Referer48
| posprint shows **Trust this site?** | If trusted, prints without asking |48
| posprint shows **Trust this site?** | If trusted, prints without asking |49
| **Trust and print** stores the hostname | Revoke under **Settings → Trusted sites** |49
| **Trust and print** stores the hostname | Revoke under **Settings → Trusted sites** |50
50
51
After a successful print, posprint remembers that printer. On the next `noconfirm` (and in the interactive dialog), it selects that printer again **if it is still connected**; otherwise it keeps the usual first/default selection.52
51
Without `referrer`, `noconfirm=1` is rejected. Without `noconfirm`, behaviour is unchanged (interactive print dialog).53
Without `referrer`, `noconfirm=1` is rejected. Without `noconfirm`, behaviour is unchanged (interactive print dialog).52
54
53
Localhost / private IP verification URLs are blocked by default. For local harnesses only, set `POSPRINT_ALLOW_LOCAL_REFERRER=1` (see `scripts/test-noconfirm/`).55
Localhost / loopback verification URLs are allowed. Other private LAN addresses (e.g. `192.168.x.x`) are blocked.56
57
### Browser “Open posprint?” prompt58
59
Browsers (Chrome / Edge) always ask before launching a custom protocol. That dialog is **not** controlled by posprint.60
61
- Typing or pasting `posprint://…` in the address bar usually offers **no** “always allow” option (no site origin).62
- A real click from an **https://** page can show “Always allow this site to open…” once the browser remembers the choice for that origin.63
- `http://127.0.0.1` / localhost test pages often never get a persistent allow checkbox.64
65
No extra posprint registry or config is required for protocol registration beyond what install / first run already does.54
66
55
---67
---56
68
@@ -1,6 +1,6 @@
1
1
# Maintainer: posprint contributors
2
2
pkgname=posprint
3
pkgver=0.5.2
3
pkgver=0.5.3
4
4
pkgrel=1
5
5
pkgdesc="Designer for POS-print documents with live preview and USB ESC/POS printing"
6
6
arch=('x86_64')
@@ -1,6 +1,6 @@1
# Maintainer: posprint contributors1
# Maintainer: posprint contributors2
pkgname=posprint2
pkgname=posprint3
pkgver=0.5.23
pkgver=0.5.34
pkgrel=14
pkgrel=15
pkgdesc="Designer for POS-print documents with live preview and USB ESC/POS printing"5
pkgdesc="Designer for POS-print documents with live preview and USB ESC/POS printing"6
arch=('x86_64')6
arch=('x86_64')@@ -1,6 +1,6 @@
1
1
pkgbase = posprint
2
2
pkgdesc = Designer for POS-print documents with live preview and USB ESC/POS printing
3
pkgver = 0.5.2
3
pkgver = 0.5.3
4
4
pkgrel = 1
5
5
url = https://gitlab.com/Timfa/posprint
6
6
arch = x86_64
@@ -21,7 +21,7 @@ pkgbase = posprint
21
21
depends = freetype2
22
22
depends = libglvnd
23
23
options = !lto
24
source = https://gitlab.com/Timfa/posprint/-/archive/0.5.2/posprint-0.5.2.tar.gz
24
source = https://gitlab.com/Timfa/posprint/-/archive/0.5.3/posprint-0.5.3.tar.gz
25
25
sha256sums = SKIP
26
26
27
27
pkgname = posprint
@@ -1,6 +1,6 @@1
pkgbase = posprint1
pkgbase = posprint2
pkgdesc = Designer for POS-print documents with live preview and USB ESC/POS printing2
pkgdesc = Designer for POS-print documents with live preview and USB ESC/POS printing3
pkgver = 0.5.23
pkgver = 0.5.34
pkgrel = 14
pkgrel = 15
url = https://gitlab.com/Timfa/posprint5
url = https://gitlab.com/Timfa/posprint6
arch = x86_646
arch = x86_64@@ -21,7 +21,7 @@ pkgbase = posprint21
depends = freetype221
depends = freetype222
depends = libglvnd22
depends = libglvnd23
options = !lto23
options = !lto24
source = https://gitlab.com/Timfa/posprint/-/archive/0.5.2/posprint-0.5.2.tar.gz24
source = https://gitlab.com/Timfa/posprint/-/archive/0.5.3/posprint-0.5.3.tar.gz25
sha256sums = SKIP25
sha256sums = SKIP26
26
27
pkgname = posprint27
pkgname = posprint@@ -1,6 +1,6 @@
1
1
# Maintainer: posprint contributors
2
2
pkgname=posprint
3
pkgver=0.5.2
3
pkgver=0.5.3
4
4
pkgrel=1
5
5
pkgdesc="Designer for POS-print documents with live preview and USB ESC/POS printing"
6
6
arch=('x86_64')
@@ -1,6 +1,6 @@1
# Maintainer: posprint contributors1
# Maintainer: posprint contributors2
pkgname=posprint2
pkgname=posprint3
pkgver=0.5.23
pkgver=0.5.34
pkgrel=14
pkgrel=15
pkgdesc="Designer for POS-print documents with live preview and USB ESC/POS printing"5
pkgdesc="Designer for POS-print documents with live preview and USB ESC/POS printing"6
arch=('x86_64')6
arch=('x86_64')@@ -2,11 +2,7 @@
2
2
3
3
Docs: [docs/POSPRINT-URL.md](../../docs/POSPRINT-URL.md).
4
4
5
Production blocks localhost referrers. For this harness set:
6
7
```powershell
8
$env:POSPRINT_ALLOW_LOCAL_REFERRER = "1"
9
```
5
Loopback (`127.0.0.1` / `localhost`) is allowed for referrer verification.
10
6
11
7
## 1. Start the verify server
12
8
@@ -17,36 +13,23 @@ python scripts/test-noconfirm/server.py
17
13
- `GET http://127.0.0.1:8765/verify?code=84923` → **200**
18
14
- `GET http://127.0.0.1:8765/verify?code=wrong` → **403**
19
15
20
## 2. Build a debug posprint with the feature branch / master
16
## 2. Build and open the test URL
21
17
22
18
```powershell
23
19
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
20
$base = cargo run --quiet -- link examples/noconfirm-demo.pos
39
21
$ref = [uri]::EscapeDataString("http://127.0.0.1:8765/verify?code=84923")
40
22
$url = "$base&noconfirm=1&referrer=$ref"
41
23
$url
42
Start-Process $url
24
# Prefer the built GUI binary (no console flash):
25
Start-Process ".\target\debug\posprint.exe" $url
43
26
```
44
27
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).
28
First run: trust dialog for `127.0.0.1`. After **Trust and print**, the next open should print without asking (while the server still returns 200).
46
29
47
Try a bad code to confirm refusal:
30
Bad code (should fail verification):
48
31
49
32
```powershell
50
33
$refBad = [uri]::EscapeDataString("http://127.0.0.1:8765/verify?code=nope")
51
Start-Process "$base&noconfirm=1&referrer=$refBad"
34
Start-Process ".\target\debug\posprint.exe" "$base&noconfirm=1&referrer=$refBad"
52
35
```
@@ -2,11 +2,7 @@2
2
3
Docs: [docs/POSPRINT-URL.md](../../docs/POSPRINT-URL.md).3
Docs: [docs/POSPRINT-URL.md](../../docs/POSPRINT-URL.md).4
4
5
Production blocks localhost referrers. For this harness set:5
Loopback (`127.0.0.1` / `localhost`) is allowed for referrer verification.6
7
```powershell8
$env:POSPRINT_ALLOW_LOCAL_REFERRER = "1"9
```10
6
11
## 1. Start the verify server7
## 1. Start the verify server12
8
@@ -17,36 +13,23 @@ python scripts/test-noconfirm/server.py17
- `GET http://127.0.0.1:8765/verify?code=84923` → **200**13
- `GET http://127.0.0.1:8765/verify?code=84923` → **200**18
- `GET http://127.0.0.1:8765/verify?code=wrong` → **403**14
- `GET http://127.0.0.1:8765/verify?code=wrong` → **403**19
15
20
## 2. Build a debug posprint with the feature branch / master16
## 2. Build and open the test URL21
17
22
```powershell18
```powershell23
cargo build19
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.pos20
$base = cargo run --quiet -- link examples/noconfirm-demo.pos39
$ref = [uri]::EscapeDataString("http://127.0.0.1:8765/verify?code=84923")21
$ref = [uri]::EscapeDataString("http://127.0.0.1:8765/verify?code=84923")40
$url = "$base&noconfirm=1&referrer=$ref"22
$url = "$base&noconfirm=1&referrer=$ref"41
$url23
$url42
Start-Process $url24
# Prefer the built GUI binary (no console flash):25
Start-Process ".\target\debug\posprint.exe" $url43
```26
```44
27
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).28
First run: trust dialog for `127.0.0.1`. After **Trust and print**, the next open should print without asking (while the server still returns 200).46
29
47
Try a bad code to confirm refusal:30
Bad code (should fail verification):48
31
49
```powershell32
```powershell50
$refBad = [uri]::EscapeDataString("http://127.0.0.1:8765/verify?code=nope")33
$refBad = [uri]::EscapeDataString("http://127.0.0.1:8765/verify?code=nope")51
Start-Process "$base&noconfirm=1&referrer=$refBad"34
Start-Process ".\target\debug\posprint.exe" "$base&noconfirm=1&referrer=$refBad"52
```35
```@@ -17,6 +17,9 @@ pub struct AppConfig {
17
17
/// Hostnames allowed to use `noconfirm=1` without asking again.
18
18
#[serde(default)]
19
19
pub trusted_origins: Vec<String>,
20
/// Last printer that printed successfully (`serial:…`, `winspool:…`, `usb:vid:pid`, or `manual:…`).
21
#[serde(default)]
22
pub last_printer_key: Option<String>,
20
23
}
21
24
22
25
fn default_config_version() -> u32 {
@@ -33,6 +36,7 @@ impl Default for AppConfig {
33
36
version: CONFIG_VERSION,
34
37
default_page_width_mm: default_page_width_mm(),
35
38
trusted_origins: Vec::new(),
39
last_printer_key: None,
36
40
}
37
41
}
38
42
}
@@ -94,6 +98,14 @@ impl AppConfig {
94
98
self.trusted_origins.retain(|o| o != &host);
95
99
}
96
100
101
pub fn remember_printer(&mut self, key: impl Into<String>) {
102
let key = key.into();
103
if key.is_empty() {
104
return;
105
}
106
self.last_printer_key = Some(key);
107
}
108
97
109
fn normalize(&mut self) {
98
110
self.version = CONFIG_VERSION;
99
111
if !self.default_page_width_mm.is_finite() || self.default_page_width_mm < 40.0 {
@@ -109,6 +121,14 @@ impl AppConfig {
109
121
hosts.sort();
110
122
hosts.dedup();
111
123
self.trusted_origins = hosts;
124
if let Some(key) = &self.last_printer_key {
125
let trimmed = key.trim();
126
if trimmed.is_empty() {
127
self.last_printer_key = None;
128
} else if trimmed != key.as_str() {
129
self.last_printer_key = Some(trimmed.to_string());
130
}
131
}
112
132
}
113
133
}
114
134
@@ -195,10 +215,12 @@ mod tests {
195
215
let mut cfg = AppConfig::default();
196
216
cfg.default_page_width_mm = 58.0;
197
217
cfg.trust_origin("pos.example");
218
cfg.remember_printer("winspool:POS-58");
198
219
cfg.save_to_path(&path).unwrap();
199
220
200
221
let loaded = AppConfig::load_from_path(&path);
201
222
assert_eq!(loaded.default_page_width_mm, 58.0);
202
223
assert!(loaded.is_trusted("pos.example"));
224
assert_eq!(loaded.last_printer_key.as_deref(), Some("winspool:POS-58"));
203
225
}
204
226
}
@@ -17,6 +17,9 @@ pub struct AppConfig {17
/// Hostnames allowed to use `noconfirm=1` without asking again.
17
/// Hostnames allowed to use `noconfirm=1` without asking again.
18
#[serde(default)]
18
#[serde(default)]
19
pub trusted_origins: Vec<String>,
19
pub trusted_origins: Vec<String>,
20
/// Last printer that printed successfully (`serial:…`, `winspool:…`, `usb:vid:pid`, or `manual:…`).
21
#[serde(default)]
22
pub last_printer_key: Option<String>,
20
}
23
}
21
24
22
fn default_config_version() -> u32 {
25
fn default_config_version() -> u32 {
@@ -33,6 +36,7 @@ impl Default for AppConfig {33
version: CONFIG_VERSION,
36
version: CONFIG_VERSION,
34
default_page_width_mm: default_page_width_mm(),
37
default_page_width_mm: default_page_width_mm(),
35
trusted_origins: Vec::new(),
38
trusted_origins: Vec::new(),
39
last_printer_key: None,
36
}
40
}
37
}
41
}
38
}
42
}
@@ -94,6 +98,14 @@ impl AppConfig {94
self.trusted_origins.retain(|o| o != &host);
98
self.trusted_origins.retain(|o| o != &host);
95
}
99
}
96
100
101
pub fn remember_printer(&mut self, key: impl Into<String>) {
102
let key = key.into();
103
if key.is_empty() {
104
return;
105
}
106
self.last_printer_key = Some(key);
107
}
108
97
fn normalize(&mut self) {
109
fn normalize(&mut self) {
98
self.version = CONFIG_VERSION;
110
self.version = CONFIG_VERSION;
99
if !self.default_page_width_mm.is_finite() || self.default_page_width_mm < 40.0 {
111
if !self.default_page_width_mm.is_finite() || self.default_page_width_mm < 40.0 {
@@ -109,6 +121,14 @@ impl AppConfig {109
hosts.sort();
121
hosts.sort();
110
hosts.dedup();
122
hosts.dedup();
111
self.trusted_origins = hosts;
123
self.trusted_origins = hosts;
124
if let Some(key) = &self.last_printer_key {
125
let trimmed = key.trim();
126
if trimmed.is_empty() {
127
self.last_printer_key = None;
128
} else if trimmed != key.as_str() {
129
self.last_printer_key = Some(trimmed.to_string());
130
}
131
}
112
}
132
}
113
}
133
}
114
134
@@ -195,10 +215,12 @@ mod tests {195
let mut cfg = AppConfig::default();
215
let mut cfg = AppConfig::default();
196
cfg.default_page_width_mm = 58.0;
216
cfg.default_page_width_mm = 58.0;
197
cfg.trust_origin("pos.example");
217
cfg.trust_origin("pos.example");
218
cfg.remember_printer("winspool:POS-58");
198
cfg.save_to_path(&path).unwrap();
219
cfg.save_to_path(&path).unwrap();
199
220
200
let loaded = AppConfig::load_from_path(&path);
221
let loaded = AppConfig::load_from_path(&path);
201
assert_eq!(loaded.default_page_width_mm, 58.0);
222
assert_eq!(loaded.default_page_width_mm, 58.0);
202
assert!(loaded.is_trusted("pos.example"));
223
assert!(loaded.is_trusted("pos.example"));
224
assert_eq!(loaded.last_printer_key.as_deref(), Some("winspool:POS-58"));
203
}
225
}
204
}
226
}
@@ -1,4 +1,4 @@
1
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
1
#![windows_subsystem = "windows"]
2
2
3
3
mod app;
4
4
mod preview_panel;
@@ -18,7 +18,24 @@ fn load_viewport_icon() -> Option<Arc<eframe::egui::IconData>> {
18
18
.map(Arc::new)
19
19
}
20
20
21
/// Attach to the parent console when launched from cmd/PowerShell so CLI output works
22
/// with `windows_subsystem = "windows"` (no black console flash for GUI / protocol launches).
23
#[cfg(windows)]
24
fn attach_parent_console_if_present() {
25
#[link(name = "kernel32")]
26
extern "system" {
27
fn AttachConsole(dw_process_id: u32) -> i32;
28
}
29
const ATTACH_PARENT_PROCESS: u32 = 0xFFFF_FFFF;
30
unsafe {
31
let _ = AttachConsole(ATTACH_PARENT_PROCESS);
32
}
33
}
34
21
35
fn main() -> eframe::Result<()> {
36
#[cfg(windows)]
37
attach_parent_console_if_present();
38
22
39
shell_integration::ensure_shell_integration();
23
40
24
41
// Protocol URLs must be handled before clap: browsers pass the full URL as argv.
@@ -1,4 +1,4 @@1
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
1
#![windows_subsystem = "windows"]
2
2
3
mod app;
3
mod app;
4
mod preview_panel;
4
mod preview_panel;
@@ -18,7 +18,24 @@ fn load_viewport_icon() -> Option<Arc<eframe::egui::IconData>> {18
.map(Arc::new)
18
.map(Arc::new)
19
}
19
}
20
20
21
/// Attach to the parent console when launched from cmd/PowerShell so CLI output works
22
/// with `windows_subsystem = "windows"` (no black console flash for GUI / protocol launches).
23
#[cfg(windows)]
24
fn attach_parent_console_if_present() {
25
#[link(name = "kernel32")]
26
extern "system" {
27
fn AttachConsole(dw_process_id: u32) -> i32;
28
}
29
const ATTACH_PARENT_PROCESS: u32 = 0xFFFF_FFFF;
30
unsafe {
31
let _ = AttachConsole(ATTACH_PARENT_PROCESS);
32
}
33
}
34
21
fn main() -> eframe::Result<()> {
35
fn main() -> eframe::Result<()> {
36
#[cfg(windows)]
37
attach_parent_console_if_present();
38
22
shell_integration::ensure_shell_integration();
39
shell_integration::ensure_shell_integration();
23
40
24
// Protocol URLs must be handled before clap: browsers pass the full URL as argv.
41
// Protocol URLs must be handled before clap: browsers pass the full URL as argv.
@@ -200,6 +200,33 @@ pub fn print_bytes<T: PrinterTransport + ?Sized>(transport: &mut T, data: &[u8])
200
200
Ok(())
201
201
}
202
202
203
/// Stable key for remembering the last successful printer across reconnects.
204
/// USB uses vid:pid only (bus/address change when replugged).
205
pub fn printer_preference_key(target: &PrinterTarget) -> String {
206
match target {
207
PrinterTarget::Serial(port) => format!("serial:{port}"),
208
PrinterTarget::WinSpooler(name) => format!("winspool:{name}"),
209
PrinterTarget::UsbDirect { vid, pid, .. } => {
210
format!("usb:{vid:04x}:{pid:04x}")
211
}
212
}
213
}
214
215
pub fn manual_printer_preference_key(name: &str) -> String {
216
format!("manual:{}", name.trim())
217
}
218
219
/// Index of a discovered printer matching a stored preference key, if still connected.
220
pub fn find_preferred_printer_index(printers: &[PrinterDevice], key: &str) -> Option<usize> {
221
let key = key.trim();
222
if key.is_empty() || key.starts_with("manual:") {
223
return None;
224
}
225
printers
226
.iter()
227
.position(|p| printer_preference_key(&p.target) == key)
228
}
229
203
230
pub struct MockTransport {
204
231
pub written: Vec<u8>,
205
232
}
@@ -263,4 +290,47 @@ mod tests {
263
290
});
264
291
assert!(is_usb_serial_candidate(&usb));
265
292
}
293
294
#[test]
295
fn preference_key_ignores_usb_bus_address() {
296
let a = PrinterTarget::UsbDirect {
297
vid: 0x0416,
298
pid: 0x5011,
299
bus: 1,
300
address: 2,
301
};
302
let b = PrinterTarget::UsbDirect {
303
vid: 0x0416,
304
pid: 0x5011,
305
bus: 3,
306
address: 9,
307
};
308
assert_eq!(printer_preference_key(&a), printer_preference_key(&b));
309
assert_eq!(printer_preference_key(&a), "usb:0416:5011");
310
}
311
312
#[test]
313
fn finds_preferred_printer_by_key() {
314
let printers = vec![
315
PrinterDevice {
316
id: "serial:COM1".into(),
317
display_name: "COM1".into(),
318
target: PrinterTarget::Serial("COM1".into()),
319
},
320
PrinterDevice {
321
id: "winspool:POS".into(),
322
display_name: "POS".into(),
323
target: PrinterTarget::WinSpooler("POS".into()),
324
},
325
];
326
assert_eq!(
327
find_preferred_printer_index(&printers, "winspool:POS"),
328
Some(1)
329
);
330
assert_eq!(find_preferred_printer_index(&printers, "serial:COM9"), None);
331
assert_eq!(
332
find_preferred_printer_index(&printers, "manual:COM3"),
333
None
334
);
335
}
266
336
}
@@ -200,6 +200,33 @@ pub fn print_bytes<T: PrinterTransport + ?Sized>(transport: &mut T, data: &[u8])200
Ok(())
200
Ok(())
201
}
201
}
202
202
203
/// Stable key for remembering the last successful printer across reconnects.
204
/// USB uses vid:pid only (bus/address change when replugged).
205
pub fn printer_preference_key(target: &PrinterTarget) -> String {
206
match target {
207
PrinterTarget::Serial(port) => format!("serial:{port}"),
208
PrinterTarget::WinSpooler(name) => format!("winspool:{name}"),
209
PrinterTarget::UsbDirect { vid, pid, .. } => {
210
format!("usb:{vid:04x}:{pid:04x}")
211
}
212
}
213
}
214
215
pub fn manual_printer_preference_key(name: &str) -> String {
216
format!("manual:{}", name.trim())
217
}
218
219
/// Index of a discovered printer matching a stored preference key, if still connected.
220
pub fn find_preferred_printer_index(printers: &[PrinterDevice], key: &str) -> Option<usize> {
221
let key = key.trim();
222
if key.is_empty() || key.starts_with("manual:") {
223
return None;
224
}
225
printers
226
.iter()
227
.position(|p| printer_preference_key(&p.target) == key)
228
}
229
203
pub struct MockTransport {
230
pub struct MockTransport {
204
pub written: Vec<u8>,
231
pub written: Vec<u8>,
205
}
232
}
@@ -263,4 +290,47 @@ mod tests {263
});
290
});
264
assert!(is_usb_serial_candidate(&usb));
291
assert!(is_usb_serial_candidate(&usb));
265
}
292
}
293
294
#[test]
295
fn preference_key_ignores_usb_bus_address() {
296
let a = PrinterTarget::UsbDirect {
297
vid: 0x0416,
298
pid: 0x5011,
299
bus: 1,
300
address: 2,
301
};
302
let b = PrinterTarget::UsbDirect {
303
vid: 0x0416,
304
pid: 0x5011,
305
bus: 3,
306
address: 9,
307
};
308
assert_eq!(printer_preference_key(&a), printer_preference_key(&b));
309
assert_eq!(printer_preference_key(&a), "usb:0416:5011");
310
}
311
312
#[test]
313
fn finds_preferred_printer_by_key() {
314
let printers = vec![
315
PrinterDevice {
316
id: "serial:COM1".into(),
317
display_name: "COM1".into(),
318
target: PrinterTarget::Serial("COM1".into()),
319
},
320
PrinterDevice {
321
id: "winspool:POS".into(),
322
display_name: "POS".into(),
323
target: PrinterTarget::WinSpooler("POS".into()),
324
},
325
];
326
assert_eq!(
327
find_preferred_printer_index(&printers, "winspool:POS"),
328
Some(1)
329
);
330
assert_eq!(find_preferred_printer_index(&printers, "serial:COM9"), None);
331
assert_eq!(
332
find_preferred_printer_index(&printers, "manual:COM3"),
333
None
334
);
335
}
266
}
336
}
@@ -139,14 +139,14 @@ impl WinSpoolerTransport {
139
139
140
140
impl super::PrinterTransport for WinSpoolerTransport {
141
141
fn write_all(&mut self, data: &[u8]) -> io::Result<()> {
142
// Close the handle before PowerShell reads: NamedTempFile keeps the file
143
// open, and on Windows that blocks ReadAllBytes ("used by another process").
142
144
let tmp = tempfile::NamedTempFile::new()?;
143
145
std::fs::write(tmp.path(), data)?;
146
let tmp_path = tmp.into_temp_path();
144
147
145
148
let safe_printer = self.printer_name.replace('\'', "''");
146
let safe_file = tmp
147
.path()
148
.to_string_lossy()
149
.replace('\'', "''");
149
let safe_file = tmp_path.to_string_lossy().replace('\'', "''");
150
150
151
151
let script = format!(
152
152
r#"
@@ -229,6 +229,9 @@ Write-Output 'OK'
229
229
.output()
230
230
.map_err(io::Error::other)?;
231
231
232
// Keep tmp_path alive until PowerShell has finished reading it.
233
drop(tmp_path);
234
232
235
if !output.status.success() {
233
236
let stderr = String::from_utf8_lossy(&output.stderr);
234
237
return Err(io::Error::other(stderr.trim()));
@@ -260,4 +263,14 @@ mod tests {
260
263
assert!(is_com_port("COM3"));
261
264
assert!(!is_com_port("USB001"));
262
265
}
266
267
#[test]
268
fn temp_payload_readable_after_handle_closed() {
269
// Mirrors write_all: PowerShell ReadAllBytes needs the file closed on Windows.
270
let tmp = tempfile::NamedTempFile::new().unwrap();
271
std::fs::write(tmp.path(), b"escpos").unwrap();
272
let path = tmp.into_temp_path();
273
let bytes = std::fs::read(&path).unwrap();
274
assert_eq!(bytes, b"escpos");
275
}
263
276
}
@@ -139,14 +139,14 @@ impl WinSpoolerTransport {139
139
140
impl super::PrinterTransport for WinSpoolerTransport {
140
impl super::PrinterTransport for WinSpoolerTransport {
141
fn write_all(&mut self, data: &[u8]) -> io::Result<()> {
141
fn write_all(&mut self, data: &[u8]) -> io::Result<()> {
142
// Close the handle before PowerShell reads: NamedTempFile keeps the file
143
// open, and on Windows that blocks ReadAllBytes ("used by another process").
142
let tmp = tempfile::NamedTempFile::new()?;
144
let tmp = tempfile::NamedTempFile::new()?;
143
std::fs::write(tmp.path(), data)?;
145
std::fs::write(tmp.path(), data)?;
146
let tmp_path = tmp.into_temp_path();
144
147
145
let safe_printer = self.printer_name.replace('\'', "''");
148
let safe_printer = self.printer_name.replace('\'', "''");
146
let safe_file = tmp
149
let safe_file = tmp_path.to_string_lossy().replace('\'', "''");
147
.path()
148
.to_string_lossy()
149
.replace('\'', "''");
150
150
151
let script = format!(
151
let script = format!(
152
r#"
152
r#"
@@ -229,6 +229,9 @@ Write-Output 'OK'229
.output()
229
.output()
230
.map_err(io::Error::other)?;
230
.map_err(io::Error::other)?;
231
231
232
// Keep tmp_path alive until PowerShell has finished reading it.
233
drop(tmp_path);
234
232
if !output.status.success() {
235
if !output.status.success() {
233
let stderr = String::from_utf8_lossy(&output.stderr);
236
let stderr = String::from_utf8_lossy(&output.stderr);
234
return Err(io::Error::other(stderr.trim()));
237
return Err(io::Error::other(stderr.trim()));
@@ -260,4 +263,14 @@ mod tests {260
assert!(is_com_port("COM3"));
263
assert!(is_com_port("COM3"));
261
assert!(!is_com_port("USB001"));
264
assert!(!is_com_port("USB001"));
262
}
265
}
266
267
#[test]
268
fn temp_payload_readable_after_handle_closed() {
269
// Mirrors write_all: PowerShell ReadAllBytes needs the file closed on Windows.
270
let tmp = tempfile::NamedTempFile::new().unwrap();
271
std::fs::write(tmp.path(), b"escpos").unwrap();
272
let path = tmp.into_temp_path();
273
let bytes = std::fs::read(&path).unwrap();
274
assert_eq!(bytes, b"escpos");
275
}
263
}
276
}
@@ -11,8 +11,10 @@ use posprint::io::{PosFile, PosMetadata};
11
11
use posprint::params::{collect_parameters, parse_bool_value, ParamKind, ParamSpec};
12
12
use posprint::pipeline;
13
13
use posprint::print::{
14
list_printers, open_printer, open_printer_by_name, print_bytes, PrintError, PrinterDevice,
14
find_preferred_printer_index, list_printers, manual_printer_preference_key, open_printer,
15
open_printer_by_name, print_bytes, printer_preference_key, PrintError, PrinterDevice,
15
16
};
17
use posprint::config::AppConfig;
16
18
17
19
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18
20
pub enum PrintExecuteResult {
@@ -98,9 +100,7 @@ impl PrintDialog {
98
100
match result {
99
101
Ok(list) => {
100
102
self.printers = list;
101
if self.selected_printer.is_none() && !self.printers.is_empty() {
102
self.selected_printer = Some(0);
103
}
103
self.apply_preferred_printer(AppConfig::load().last_printer_key.as_deref());
104
104
}
105
105
Err(e) => self.error = Some(format!("{e:?}")),
106
106
}
@@ -119,6 +119,51 @@ impl PrintDialog {
119
119
self.start_printer_discovery();
120
120
}
121
121
122
/// Prefer the last successful printer when still connected; otherwise keep/default selection.
123
pub fn apply_preferred_printer(&mut self, preferred_key: Option<&str>) {
124
if let Some(key) = preferred_key.map(str::trim).filter(|k| !k.is_empty()) {
125
if let Some(name) = key.strip_prefix("manual:") {
126
let name = name.trim();
127
if !name.is_empty() {
128
self.use_manual_port = true;
129
self.manual_port = name.to_string();
130
return;
131
}
132
} else if let Some(i) = find_preferred_printer_index(&self.printers, key) {
133
self.use_manual_port = false;
134
self.selected_printer = Some(i);
135
return;
136
}
137
}
138
if self.selected_printer.is_none() && !self.printers.is_empty() {
139
self.selected_printer = Some(0);
140
}
141
}
142
143
fn remember_successful_printer(&self) {
144
let key = if self.use_manual_port {
145
let name = self.manual_port.trim();
146
if name.is_empty() {
147
None
148
} else {
149
Some(manual_printer_preference_key(name))
150
}
151
} else {
152
self.selected_printer
153
.and_then(|i| self.printers.get(i))
154
.map(|p| printer_preference_key(&p.target))
155
};
156
let Some(key) = key else {
157
return;
158
};
159
let mut cfg = AppConfig::load();
160
if cfg.last_printer_key.as_deref() == Some(key.as_str()) {
161
return;
162
}
163
cfg.remember_printer(key);
164
let _ = cfg.save();
165
}
166
122
167
pub fn apply_inputs_to_last_params(&mut self) {
123
168
self.last_params = self.param_inputs.clone();
124
169
}
@@ -184,7 +229,10 @@ impl PrintDialog {
184
229
185
230
match transport_result {
186
231
Ok(mut transport) => match print_bytes(transport.as_mut(), &bytes) {
187
Ok(()) => PrintExecuteResult::Printed,
232
Ok(()) => {
233
self.remember_successful_printer();
234
PrintExecuteResult::Printed
235
}
188
236
Err(e) => {
189
237
self.error = Some(format!("{e:?}"));
190
238
PrintExecuteResult::StillOpen
@@ -312,3 +360,49 @@ pub enum PrintDialogAction {
312
360
None,
313
361
Print,
314
362
}
363
364
#[cfg(test)]
365
mod tests {
366
use super::*;
367
use posprint::print::PrinterTarget;
368
369
#[test]
370
fn prefers_last_connected_printer_over_first() {
371
let mut dialog = PrintDialog::default();
372
dialog.printers = vec![
373
PrinterDevice {
374
id: "a".into(),
375
display_name: "First".into(),
376
target: PrinterTarget::Serial("COM1".into()),
377
},
378
PrinterDevice {
379
id: "b".into(),
380
display_name: "Last".into(),
381
target: PrinterTarget::WinSpooler("POS".into()),
382
},
383
];
384
dialog.apply_preferred_printer(Some("winspool:POS"));
385
assert_eq!(dialog.selected_printer, Some(1));
386
assert!(!dialog.use_manual_port);
387
}
388
389
#[test]
390
fn falls_back_to_first_when_preferred_missing() {
391
let mut dialog = PrintDialog::default();
392
dialog.printers = vec![PrinterDevice {
393
id: "a".into(),
394
display_name: "Only".into(),
395
target: PrinterTarget::Serial("COM1".into()),
396
}];
397
dialog.apply_preferred_printer(Some("winspool:Gone"));
398
assert_eq!(dialog.selected_printer, Some(0));
399
}
400
401
#[test]
402
fn restores_manual_preference() {
403
let mut dialog = PrintDialog::default();
404
dialog.apply_preferred_printer(Some("manual:COM9"));
405
assert!(dialog.use_manual_port);
406
assert_eq!(dialog.manual_port, "COM9");
407
}
408
}
@@ -11,8 +11,10 @@ use posprint::io::{PosFile, PosMetadata};11
use posprint::params::{collect_parameters, parse_bool_value, ParamKind, ParamSpec};
11
use posprint::params::{collect_parameters, parse_bool_value, ParamKind, ParamSpec};
12
use posprint::pipeline;
12
use posprint::pipeline;
13
use posprint::print::{
13
use posprint::print::{
14
list_printers, open_printer, open_printer_by_name, print_bytes, PrintError, PrinterDevice,
14
find_preferred_printer_index, list_printers, manual_printer_preference_key, open_printer,
15
open_printer_by_name, print_bytes, printer_preference_key, PrintError, PrinterDevice,
15
};
16
};
17
use posprint::config::AppConfig;
16
18
17
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18
pub enum PrintExecuteResult {
20
pub enum PrintExecuteResult {
@@ -98,9 +100,7 @@ impl PrintDialog {98
match result {
100
match result {
99
Ok(list) => {
101
Ok(list) => {
100
self.printers = list;
102
self.printers = list;
101
if self.selected_printer.is_none() && !self.printers.is_empty() {
103
self.apply_preferred_printer(AppConfig::load().last_printer_key.as_deref());
102
self.selected_printer = Some(0);
103
}
104
}
104
}
105
Err(e) => self.error = Some(format!("{e:?}")),
105
Err(e) => self.error = Some(format!("{e:?}")),
106
}
106
}
@@ -119,6 +119,51 @@ impl PrintDialog {119
self.start_printer_discovery();
119
self.start_printer_discovery();
120
}
120
}
121
121
122
/// Prefer the last successful printer when still connected; otherwise keep/default selection.
123
pub fn apply_preferred_printer(&mut self, preferred_key: Option<&str>) {
124
if let Some(key) = preferred_key.map(str::trim).filter(|k| !k.is_empty()) {
125
if let Some(name) = key.strip_prefix("manual:") {
126
let name = name.trim();
127
if !name.is_empty() {
128
self.use_manual_port = true;
129
self.manual_port = name.to_string();
130
return;
131
}
132
} else if let Some(i) = find_preferred_printer_index(&self.printers, key) {
133
self.use_manual_port = false;
134
self.selected_printer = Some(i);
135
return;
136
}
137
}
138
if self.selected_printer.is_none() && !self.printers.is_empty() {
139
self.selected_printer = Some(0);
140
}
141
}
142
143
fn remember_successful_printer(&self) {
144
let key = if self.use_manual_port {
145
let name = self.manual_port.trim();
146
if name.is_empty() {
147
None
148
} else {
149
Some(manual_printer_preference_key(name))
150
}
151
} else {
152
self.selected_printer
153
.and_then(|i| self.printers.get(i))
154
.map(|p| printer_preference_key(&p.target))
155
};
156
let Some(key) = key else {
157
return;
158
};
159
let mut cfg = AppConfig::load();
160
if cfg.last_printer_key.as_deref() == Some(key.as_str()) {
161
return;
162
}
163
cfg.remember_printer(key);
164
let _ = cfg.save();
165
}
166
122
pub fn apply_inputs_to_last_params(&mut self) {
167
pub fn apply_inputs_to_last_params(&mut self) {
123
self.last_params = self.param_inputs.clone();
168
self.last_params = self.param_inputs.clone();
124
}
169
}
@@ -184,7 +229,10 @@ impl PrintDialog {184
229
185
match transport_result {
230
match transport_result {
186
Ok(mut transport) => match print_bytes(transport.as_mut(), &bytes) {
231
Ok(mut transport) => match print_bytes(transport.as_mut(), &bytes) {
187
Ok(()) => PrintExecuteResult::Printed,
232
Ok(()) => {
233
self.remember_successful_printer();
234
PrintExecuteResult::Printed
235
}
188
Err(e) => {
236
Err(e) => {
189
self.error = Some(format!("{e:?}"));
237
self.error = Some(format!("{e:?}"));
190
PrintExecuteResult::StillOpen
238
PrintExecuteResult::StillOpen
@@ -312,3 +360,49 @@ pub enum PrintDialogAction {312
None,
360
None,
313
Print,
361
Print,
314
}
362
}
363
364
#[cfg(test)]
365
mod tests {
366
use super::*;
367
use posprint::print::PrinterTarget;
368
369
#[test]
370
fn prefers_last_connected_printer_over_first() {
371
let mut dialog = PrintDialog::default();
372
dialog.printers = vec![
373
PrinterDevice {
374
id: "a".into(),
375
display_name: "First".into(),
376
target: PrinterTarget::Serial("COM1".into()),
377
},
378
PrinterDevice {
379
id: "b".into(),
380
display_name: "Last".into(),
381
target: PrinterTarget::WinSpooler("POS".into()),
382
},
383
];
384
dialog.apply_preferred_printer(Some("winspool:POS"));
385
assert_eq!(dialog.selected_printer, Some(1));
386
assert!(!dialog.use_manual_port);
387
}
388
389
#[test]
390
fn falls_back_to_first_when_preferred_missing() {
391
let mut dialog = PrintDialog::default();
392
dialog.printers = vec![PrinterDevice {
393
id: "a".into(),
394
display_name: "Only".into(),
395
target: PrinterTarget::Serial("COM1".into()),
396
}];
397
dialog.apply_preferred_printer(Some("winspool:Gone"));
398
assert_eq!(dialog.selected_printer, Some(0));
399
}
400
401
#[test]
402
fn restores_manual_preference() {
403
let mut dialog = PrintDialog::default();
404
dialog.apply_preferred_printer(Some("manual:COM9"));
405
assert!(dialog.use_manual_port);
406
assert_eq!(dialog.manual_port, "COM9");
407
}
408
}
@@ -87,35 +87,21 @@ fn host_from_http_url(url: &str) -> Option<String> {
87
87
}
88
88
}
89
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
90
fn is_blocked_verify_host(host: &str) -> bool {
101
91
let h = host.to_ascii_lowercase();
102
let is_loopback_name = h == "localhost" || h.ends_with(".localhost") || h == "0.0.0.0";
92
// Loopback is allowed (local verify servers / dev). Block other private LAN hosts.
93
if h == "localhost" || h.ends_with(".localhost") {
94
return false;
95
}
103
96
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
97
return match ip {
112
IpAddr::V4(v4) => v4.is_private() || v4.is_link_local(),
113
IpAddr::V6(_) => false,
98
IpAddr::V4(v4) => {
99
!v4.is_loopback()
100
&& (v4.is_private() || v4.is_link_local() || v4.is_unspecified())
101
}
102
IpAddr::V6(v6) => !v6.is_loopback() && v6.is_unspecified(),
114
103
};
115
104
}
116
if is_loopback_name {
117
return !allow_local_referrer();
118
}
119
105
false
120
106
}
121
107
@@ -151,9 +137,6 @@ pub fn verify_referrer(referrer_url: &str) -> Result<String, ReferrerVerifyError
151
137
#[cfg(test)]
152
138
mod tests {
153
139
use super::*;
154
use std::sync::Mutex;
155
156
static ENV_LOCK: Mutex<()> = Mutex::new(());
157
140
158
141
#[test]
159
142
fn normalizes_bare_host_path_to_https() {
@@ -169,22 +152,18 @@ mod tests {
169
152
}
170
153
171
154
#[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(_)));
155
fn allows_loopback_hosts() {
156
let url = normalize_referrer_url("http://127.0.0.1:8765/verify?code=1").unwrap();
157
assert_eq!(url, "http://127.0.0.1:8765/verify?code=1");
158
assert!(normalize_referrer_url("http://localhost/verify").is_ok());
179
159
}
180
160
181
161
#[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");
162
fn blocks_private_lan_hosts() {
163
let err = normalize_referrer_url("http://192.168.1.10/verify").unwrap_err();
164
assert!(matches!(err, ReferrerVerifyError::BlockedHost(_)));
165
let err = normalize_referrer_url("http://10.0.0.5/x").unwrap_err();
166
assert!(matches!(err, ReferrerVerifyError::BlockedHost(_)));
188
167
}
189
168
190
169
#[test]
@@ -87,35 +87,21 @@ fn host_from_http_url(url: &str) -> Option<String> {87
}
87
}
88
}
88
}
89
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 {
90
fn is_blocked_verify_host(host: &str) -> bool {
101
let h = host.to_ascii_lowercase();
91
let h = host.to_ascii_lowercase();
102
let is_loopback_name = h == "localhost" || h.ends_with(".localhost") || h == "0.0.0.0";
92
// Loopback is allowed (local verify servers / dev). Block other private LAN hosts.
93
if h == "localhost" || h.ends_with(".localhost") {
94
return false;
95
}
103
if let Ok(ip) = h.parse::<IpAddr>() {
96
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 {
97
return match ip {
112
IpAddr::V4(v4) => v4.is_private() || v4.is_link_local(),
98
IpAddr::V4(v4) => {
113
IpAddr::V6(_) => false,
99
!v4.is_loopback()
100
&& (v4.is_private() || v4.is_link_local() || v4.is_unspecified())
101
}
102
IpAddr::V6(v6) => !v6.is_loopback() && v6.is_unspecified(),
114
};
103
};
115
}
104
}
116
if is_loopback_name {
117
return !allow_local_referrer();
118
}
119
false
105
false
120
}
106
}
121
107
@@ -151,9 +137,6 @@ pub fn verify_referrer(referrer_url: &str) -> Result<String, ReferrerVerifyError151
#[cfg(test)]
137
#[cfg(test)]
152
mod tests {
138
mod tests {
153
use super::*;
139
use super::*;
154
use std::sync::Mutex;
155
156
static ENV_LOCK: Mutex<()> = Mutex::new(());
157
140
158
#[test]
141
#[test]
159
fn normalizes_bare_host_path_to_https() {
142
fn normalizes_bare_host_path_to_https() {
@@ -169,22 +152,18 @@ mod tests {169
}
152
}
170
153
171
#[test]
154
#[test]
172
fn blocks_localhost() {
155
fn allows_loopback_hosts() {
173
let _g = ENV_LOCK.lock().unwrap();
156
let url = normalize_referrer_url("http://127.0.0.1:8765/verify?code=1").unwrap();
174
std::env::remove_var("POSPRINT_ALLOW_LOCAL_REFERRER");
157
assert_eq!(url, "http://127.0.0.1:8765/verify?code=1");
175
let err = normalize_referrer_url("http://127.0.0.1/verify").unwrap_err();
158
assert!(normalize_referrer_url("http://localhost/verify").is_ok());
176
assert!(matches!(err, ReferrerVerifyError::BlockedHost(_)));
177
let err = normalize_referrer_url("https://localhost/x").unwrap_err();
178
assert!(matches!(err, ReferrerVerifyError::BlockedHost(_)));
179
}
159
}
180
160
181
#[test]
161
#[test]
182
fn allows_localhost_when_env_set() {
162
fn blocks_private_lan_hosts() {
183
let _g = ENV_LOCK.lock().unwrap();
163
let err = normalize_referrer_url("http://192.168.1.10/verify").unwrap_err();
184
std::env::set_var("POSPRINT_ALLOW_LOCAL_REFERRER", "1");
164
assert!(matches!(err, ReferrerVerifyError::BlockedHost(_)));
185
let url = normalize_referrer_url("http://127.0.0.1:8765/verify?code=1").unwrap();
165
let err = normalize_referrer_url("http://10.0.0.5/x").unwrap_err();
186
assert_eq!(url, "http://127.0.0.1:8765/verify?code=1");
166
assert!(matches!(err, ReferrerVerifyError::BlockedHost(_)));
187
std::env::remove_var("POSPRINT_ALLOW_LOCAL_REFERRER");
188
}
167
}
189
168
190
#[test]
169
#[test]