From 6a8b1932dd3f1abb11b620c774841d9463e9b60f Mon Sep 17 00:00:00 2001 From: debeski Date: Sat, 14 Nov 2026 15:06:41 +0200 Subject: [PATCH 01/12] fix(server): refuse requests whose Host is not loopback A page on a DNS name rebound to 127.0.0.1 is same-origin with the helper, so CORS never applies: it could start scans, read PDFs and post /shutdown. before_request now answers 403 invalid_host unless the Host header names localhost, 127.0.0.1 or [::1]. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 +++ docs/api.md | 2 ++ server.py | 21 ++++++++++- tests/test_browser_security.py | 65 ++++++++++++++++++++++++++++++++++ 4 files changed, 91 insertions(+), 1 deletion(-) create mode 100644 tests/test_browser_security.py diff --git a/CHANGELOG.md b/CHANGELOG.md index cf96abc..87652ff 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ This file owns the release history for `ScanLink`. +## Unreleased + +- **Loopback Host Check**: `server.create_app()` refuses every request whose `Host` header is not `localhost`, `127.0.0.1` or `[::1]` with `403 invalid_host`, so a DNS-rebound page cannot reach the API as a same-origin client. + ## v0.8.0b2 - **Scan Deadline Grace**: `ScanWorker` adds `SCAN_TIMEOUT_GRACE_SECONDS` (15s) to the parent's `scan_timeout_seconds` kill limit so the child's own deadline closes TWAIN and reports its error before forced termination; `gui_task_timeout_seconds` is unchanged. diff --git a/docs/api.md b/docs/api.md index bf9cbe8..405d56a 100644 --- a/docs/api.md +++ b/docs/api.md @@ -11,6 +11,8 @@ ScanLink exposes a browser-friendly local API for starting scans, polling status The JavaScript helper also defaults to `http://localhost:5000` and `https://localhost:5443`. The server binds to `127.0.0.1`. +Every request must address the helper as `localhost`, `127.0.0.1` or `[::1]` in its `Host` header (any port). Other host names, such as a DNS name rebound to `127.0.0.1`, receive `403 invalid_host`. + ## Error Shape Errors use this shape: diff --git a/server.py b/server.py index 1f2a6fc..c71620f 100644 --- a/server.py +++ b/server.py @@ -3,7 +3,7 @@ import ssl import threading import time -from urllib.parse import urlparse +from urllib.parse import urlparse, urlsplit from flask import Flask, Response, jsonify, request, send_file from werkzeug.serving import make_server @@ -23,6 +23,17 @@ logger = get_logger() +# DNS rebinding makes a foreign page same-origin with the helper, bypassing CORS, +# so the Host header must name the loopback interface itself. +LOOPBACK_HOSTNAMES = {"localhost", "127.0.0.1", "::1"} + + +def is_loopback_host(host): + try: + return urlsplit(f"//{host}").hostname in LOOPBACK_HOSTNAMES + except ValueError: + return False + def create_app(worker, shutdown_event, transport_state): app = Flask(__name__) @@ -93,6 +104,14 @@ def scan_payload(): ) return data, None + @app.before_request + def reject_foreign_host(): + if not is_loopback_host(request.host): + return error_response( + 403, "invalid_host", "ScanLink only answers requests addressed to localhost." + ) + return None + @app.after_request def add_cors_headers(response): if is_browser_endpoint(request.path): diff --git a/tests/test_browser_security.py b/tests/test_browser_security.py new file mode 100644 index 0000000..fffebeb --- /dev/null +++ b/tests/test_browser_security.py @@ -0,0 +1,65 @@ +import threading +import unittest +from unittest.mock import patch + +from tests.test_server import FakeWorker + +try: + import server +except ImportError: + server = None + + +@unittest.skipIf(server is None, "Flask is not installed in this environment") +class BrowserSecurityTests(unittest.TestCase): + cors_origins = ["*"] + + def setUp(self): + self.worker = FakeWorker() + self.shutdown_event = threading.Event() + config = patch( + "server.load_config", return_value={"cors_origins": self.cors_origins} + ) + config.start() + self.addCleanup(config.stop) + self.app = server.create_app( + self.worker, self.shutdown_event, {"http_enabled": True} + ) + self.client = self.app.test_client() + + def test_rebound_host_names_are_refused(self): + for host in ( + "evil.example:5000", + "127.0.0.1.nip.io:5000", + "localhost.evil.example", + "evil.localhost:5443", + "a b", + ): + with self.subTest(host=host): + health = self.client.get("/health", headers={"Host": host}) + scan = self.client.post("/scan", json={}, headers={"Host": host}) + shutdown = self.client.post("/shutdown", headers={"Host": host}) + for response in (health, scan, shutdown): + self.assertEqual(response.status_code, 403) + self.assertEqual( + response.get_json()["error"]["code"], "invalid_host" + ) + self.assertEqual(self.worker.jobs, {}) + self.assertFalse(self.shutdown_event.is_set()) + + def test_loopback_host_names_are_served(self): + for host in ( + "localhost:5000", + "localhost:5443", + "127.0.0.1:5000", + "[::1]:5443", + "LOCALHOST:5443", + "127.0.0.1", + ): + with self.subTest(host=host): + response = self.client.get("/health", headers={"Host": host}) + self.assertEqual(response.status_code, 200) + + +if __name__ == "__main__": + unittest.main() From da7f1cdfc7f19b60cf1926b3744db7dd57c4a780 Mon Sep 17 00:00:00 2001 From: debeski Date: Sat, 14 Nov 2026 15:07:13 +0200 Subject: [PATCH 02/12] fix(server): keep /shutdown and the protocol endpoint local-only Any website could shut ScanLink down with a plain cross-site form post, which needs no CORS preflight. Requests to non-browser endpoints that carry Origin or Sec-Fetch-Site now get 403 local_only; the protocol forwarder, PowerShell smoke test and curl send neither header. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + docs/api.md | 2 ++ server.py | 7 +++++++ tests/test_browser_security.py | 32 ++++++++++++++++++++++++++++++++ 4 files changed, 42 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 87652ff..ef57285 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ This file owns the release history for `ScanLink`. ## Unreleased - **Loopback Host Check**: `server.create_app()` refuses every request whose `Host` header is not `localhost`, `127.0.0.1` or `[::1]` with `403 invalid_host`, so a DNS-rebound page cannot reach the API as a same-origin client. +- **Local-Only Control Endpoints**: `POST /shutdown` and `POST /internal/protocol/scan` refuse any request carrying `Origin` or `Sec-Fetch-Site` with `403 local_only`, so a cross-site form post can no longer shut ScanLink down; the protocol forwarder and local scripts send neither header. ## v0.8.0b2 diff --git a/docs/api.md b/docs/api.md index 405d56a..2204359 100644 --- a/docs/api.md +++ b/docs/api.md @@ -174,6 +174,8 @@ Internal endpoint used by `scanlink://` launches to forward commands into an alr Requests ScanLink shutdown. This is intended for local control, not browser integrations. +`/shutdown` and `/internal/protocol/scan` refuse browser requests: any request carrying an `Origin` or `Sec-Fetch-Site` header receives `403 local_only`. Local tools such as the protocol forwarder, PowerShell or `curl` send neither header. + ## Scan Error Codes Errors from the scanner/runtime layer can appear inside the job `error` object: diff --git a/server.py b/server.py index c71620f..eb6b69a 100644 --- a/server.py +++ b/server.py @@ -110,6 +110,13 @@ def reject_foreign_host(): return error_response( 403, "invalid_host", "ScanLink only answers requests addressed to localhost." ) + # Browsers send Origin or Sec-Fetch-Site; form posts need no CORS preflight. + if not is_browser_endpoint(request.path) and ( + "Origin" in request.headers or "Sec-Fetch-Site" in request.headers + ): + return error_response( + 403, "local_only", "This endpoint only accepts requests from this computer's ScanLink tools." + ) return None @app.after_request diff --git a/tests/test_browser_security.py b/tests/test_browser_security.py index fffebeb..70daa74 100644 --- a/tests/test_browser_security.py +++ b/tests/test_browser_security.py @@ -60,6 +60,38 @@ def test_loopback_host_names_are_served(self): response = self.client.get("/health", headers={"Host": host}) self.assertEqual(response.status_code, 200) + def test_browser_requests_cannot_use_local_control_endpoints(self): + browser_headers = ( + {"Origin": "https://evil.example", "Sec-Fetch-Site": "cross-site"}, + {"Origin": "null"}, + {"Sec-Fetch-Site": "cross-site", "Sec-Fetch-Mode": "navigate"}, + ) + for headers in browser_headers: + with self.subTest(headers=headers): + shutdown = self.client.post( + "/shutdown", + data="x=1", + content_type="application/x-www-form-urlencoded", + headers=headers, + ) + protocol = self.client.post( + "/internal/protocol/scan", json={"action": "scan"}, headers=headers + ) + for response in (shutdown, protocol): + self.assertEqual(response.status_code, 403) + self.assertEqual( + response.get_json()["error"]["code"], "local_only" + ) + self.assertFalse(self.shutdown_event.is_set()) + self.assertEqual(self.worker.jobs, {}) + + def test_local_tools_keep_local_control_endpoints(self): + protocol = self.client.post("/internal/protocol/scan", json={"action": "scan"}) + shutdown = self.client.post("/shutdown") + self.assertEqual(protocol.status_code, 202) + self.assertEqual(shutdown.status_code, 200) + self.assertTrue(self.shutdown_event.is_set()) + if __name__ == "__main__": unittest.main() From a91f49099b000db70bf021eeacb0eb28ed1545dd Mon Sep 17 00:00:00 2001 From: debeski Date: Sat, 14 Nov 2026 15:08:34 +0200 Subject: [PATCH 03/12] fix(server): bind scans to the origin that started them With the default cors_origins ["*"], any website could poll /health, read active_job_id from a 409 during an operator's scan, then download the PDF before the DjangoLux page (which then got 410). Jobs now record the request Origin; status/result answer 404 to other origins and busy responses only reveal active_job_id to the owner. Requests from an Origin outside a configured allow-list are refused with 403 before any work. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 + docs/api.md | 8 ++- server.py | 21 ++++--- tests/test_browser_security.py | 102 +++++++++++++++++++++++++++++++++ tests/test_server.py | 8 ++- worker.py | 26 +++++++-- 6 files changed, 150 insertions(+), 17 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ef57285..3f511a3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ This file owns the release history for `ScanLink`. - **Loopback Host Check**: `server.create_app()` refuses every request whose `Host` header is not `localhost`, `127.0.0.1` or `[::1]` with `403 invalid_host`, so a DNS-rebound page cannot reach the API as a same-origin client. - **Local-Only Control Endpoints**: `POST /shutdown` and `POST /internal/protocol/scan` refuse any request carrying `Origin` or `Sec-Fetch-Site` with `403 local_only`, so a cross-site form post can no longer shut ScanLink down; the protocol forwarder and local scripts send neither header. +- **Scan Ownership By Origin**: `ScanWorker.submit_job()` records the requesting `Origin`; `GET /scan/` and `/result` answer `404 job_not_found` to any other origin, and `409 busy` includes `active_job_id` only for the job's own origin, so a website can no longer learn, follow and download another website's scan. +- **Server-Side Origin Allow-List**: Browser-endpoint requests, including preflights, from an `Origin` outside a configured `cors_origins` list are refused with `403 origin_not_allowed` before any work, instead of only omitting CORS headers. ## v0.8.0b2 diff --git a/docs/api.md b/docs/api.md index 2204359..00a4ae6 100644 --- a/docs/api.md +++ b/docs/api.md @@ -104,10 +104,14 @@ Busy response: } ``` +`active_job_id` is included only when the request comes from the same `Origin` that started the active job (or, for jobs started without an `Origin`, from a local tool that sends none). + ## GET /scan/ Returns job status. +A job belongs to the `Origin` that started it. Status and result requests from any other `Origin`, or without an `Origin` for a browser-started job, receive `404 job_not_found`, so one website cannot follow or download another website's scan. + Response: ```json @@ -214,7 +218,9 @@ Allowed origins come from `%LOCALAPPDATA%\ScanLink\config.json`: } ``` -When `cors_origins` is not `["*"]`, the request `Origin` must exactly match an entry in the list. +When `cors_origins` is not `["*"]`, the request `Origin` must exactly match an entry in the list. Browser-endpoint requests from any other `Origin`, including preflights, receive `403 origin_not_allowed` before any work is done. + +With the default `["*"]`, every website the operator opens can call `/health` and `/scan` and download the scans it starts itself. Job ownership keeps each website away from scans started by others. List the DjangoLux origins in `cors_origins` to restrict which websites can scan. ## Automatic HTTPS setup status (0.7.5b1) diff --git a/server.py b/server.py index eb6b69a..35a1827 100644 --- a/server.py +++ b/server.py @@ -110,10 +110,14 @@ def reject_foreign_host(): return error_response( 403, "invalid_host", "ScanLink only answers requests addressed to localhost." ) + origin = request.headers.get("Origin") + if is_browser_endpoint(request.path): + if origin is not None and not is_origin_allowed(origin): + return error_response( + 403, "origin_not_allowed", "This website is not allowed to use ScanLink." + ) # Browsers send Origin or Sec-Fetch-Site; form posts need no CORS preflight. - if not is_browser_endpoint(request.path) and ( - "Origin" in request.headers or "Sec-Fetch-Site" in request.headers - ): + elif origin is not None or "Sec-Fetch-Site" in request.headers: return error_response( 403, "local_only", "This endpoint only accepts requests from this computer's ScanLink tools." ) @@ -164,13 +168,15 @@ def start_scan(): callback_url=callback_url, metadata=data.get("metadata"), source="api", + origin=request.headers.get("Origin"), ) except BusyError as exc: + extra = {"active_job_id": exc.active_job_id} if exc.active_job_id else {} return error_response( 409, "busy", "Another scan job is already queued or running.", - active_job_id=exc.active_job_id, + **extra, ) return jsonify({"job_id": job["job_id"], "status": "queued"}), 202 @@ -180,7 +186,7 @@ def get_scan_status(job_id): if request.method == "OPTIONS": return empty_options_response() - job = worker.get_job(job_id) + job = worker.get_job(job_id, origin=request.headers.get("Origin")) if not job: return error_response( 404, "job_not_found", "The requested scan job was not found." @@ -192,7 +198,8 @@ def get_scan_result(job_id): if request.method == "OPTIONS": return empty_options_response() - job = worker.get_job(job_id) + origin = request.headers.get("Origin") + job = worker.get_job(job_id, origin=origin) if not job: return error_response( 404, "job_not_found", "The requested scan job was not found." @@ -205,7 +212,7 @@ def get_scan_result(job_id): current_status=job["status"], ) - updated_job, result_bytes = worker.consume_result(job_id) + updated_job, result_bytes = worker.consume_result(job_id, origin=origin) if not updated_job: return error_response( 404, "job_not_found", "The requested scan job was not found." diff --git a/tests/test_browser_security.py b/tests/test_browser_security.py index 70daa74..daa5fe1 100644 --- a/tests/test_browser_security.py +++ b/tests/test_browser_security.py @@ -1,8 +1,11 @@ +import queue import threading +import time import unittest from unittest.mock import patch from tests.test_server import FakeWorker +from worker import ScanWorker try: import server @@ -93,5 +96,104 @@ def test_local_tools_keep_local_control_endpoints(self): self.assertTrue(self.shutdown_event.is_set()) +LEGIT = {"Origin": "https://archive.example"} +OTHER = {"Origin": "https://crm.example"} +EVIL = {"Origin": "https://evil.example"} + + +@unittest.skipIf(server is None, "Flask is not installed in this environment") +class JobOwnershipTests(unittest.TestCase): + cors_origins = ["*"] + + def setUp(self): + config = patch( + "server.load_config", return_value={"cors_origins": self.cors_origins} + ) + config.start() + self.addCleanup(config.stop) + # Not started: submitted jobs stay queued until a test completes them. + self.worker = ScanWorker(queue.Queue()) + self.app = server.create_app( + self.worker, threading.Event(), {"http_enabled": True} + ) + self.client = self.app.test_client() + + def complete(self, job_id): + self.worker._update_job( + job_id, + status="completed", + completed_at=time.time(), + result_bytes=b"%PDF-1.4\nsecret\n", + ) + + def test_another_origin_cannot_find_or_take_a_scan(self): + job_id = self.client.post("/scan", json={}, headers=LEGIT).get_json()["job_id"] + + other_busy = self.client.post("/scan", json={}, headers=OTHER) + self.assertEqual(other_busy.status_code, 409) + self.assertNotIn("active_job_id", other_busy.get_json()["error"]) + owner_busy = self.client.post("/scan", json={}, headers=LEGIT) + self.assertEqual(owner_busy.get_json()["error"]["active_job_id"], job_id) + + self.complete(job_id) + for headers in (OTHER, {}, {"Sec-Fetch-Site": "cross-site"}): + with self.subTest(headers=headers): + for path in (f"/scan/{job_id}", f"/scan/{job_id}/result"): + response = self.client.get(path, headers=headers) + self.assertEqual(response.status_code, 404) + self.assertEqual( + response.get_json()["error"]["code"], "job_not_found" + ) + + self.assertEqual( + self.client.get(f"/scan/{job_id}", headers=LEGIT).get_json()["status"], + "completed", + ) + result = self.client.get(f"/scan/{job_id}/result", headers=LEGIT) + self.assertEqual(result.status_code, 200) + self.assertEqual(result.data, b"%PDF-1.4\nsecret\n") + + def test_jobs_started_without_an_origin_stay_with_local_tools(self): + job_id = self.client.post("/scan", json={}).get_json()["job_id"] + self.assertEqual(self.client.post("/scan", json={}).get_json()["error"]["active_job_id"], job_id) + self.assertNotIn( + "active_job_id", + self.client.post("/scan", json={}, headers=LEGIT).get_json()["error"], + ) + self.assertEqual( + self.client.get(f"/scan/{job_id}", headers=LEGIT).status_code, 404 + ) + self.complete(job_id) + self.assertEqual(self.client.get(f"/scan/{job_id}/result").status_code, 200) + + +class AllowListTests(JobOwnershipTests): + cors_origins = ["https://archive.example", "https://crm.example"] + + def test_unlisted_origin_is_refused_before_any_work(self): + preflight = self.client.options( + "/scan", + headers={**EVIL, "Access-Control-Request-Method": "POST"}, + ) + for response in ( + preflight, + self.client.get("/health", headers=EVIL), + self.client.post("/scan", json={}, headers=EVIL), + self.client.get("/scan/anything", headers=EVIL), + ): + self.assertEqual(response.status_code, 403) + self.assertEqual( + response.get_json()["error"]["code"], "origin_not_allowed" + ) + self.assertNotIn("Access-Control-Allow-Origin", response.headers) + self.assertEqual(self.worker.jobs, {}) + + accepted = self.client.post("/scan", json={}, headers=LEGIT) + self.assertEqual(accepted.status_code, 202) + self.assertEqual( + accepted.headers["Access-Control-Allow-Origin"], LEGIT["Origin"] + ) + + if __name__ == "__main__": unittest.main() diff --git a/tests/test_server.py b/tests/test_server.py index 6586b18..42c36af 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -24,7 +24,9 @@ def is_busy(self): def is_twain_available(self): return self.twain_available - def submit_job(self, doc_id=None, callback_url=None, metadata=None, source="api"): + def submit_job( + self, doc_id=None, callback_url=None, metadata=None, source="api", origin=None + ): if self.busy: raise BusyError(active_job_id="busy-job") @@ -47,14 +49,14 @@ def submit_job(self, doc_id=None, callback_url=None, metadata=None, source="api" } return job - def get_job(self, job_id): + def get_job(self, job_id, origin=None): job = self.jobs.get(job_id) if not job: return None return {key: value for key, value in job.items() if key != "result_bytes"} - def consume_result(self, job_id): + def consume_result(self, job_id, origin=None): job = self.jobs.get(job_id) if not job: return None, None diff --git a/worker.py b/worker.py index 455597e..2ed6bec 100644 --- a/worker.py +++ b/worker.py @@ -22,6 +22,9 @@ logger = get_logger() TERMINAL_STATUSES = {"completed", "failed", "cancelled", "timed_out"} +# get_job()/consume_result() default for in-process callers; the server always +# passes the requesting browser Origin (None for local tools). +ANY_ORIGIN = object() # Covers child startup and a graceful TWAIN close after the child's own deadline. SCAN_TIMEOUT_GRACE_SECONDS = 15 @@ -80,12 +83,16 @@ def __init__(self, gui_task_queue): self.scan_idle_timeout_seconds = int(config.get("scan_idle_timeout_seconds", 45)) self.scan_timeout_grace_seconds = SCAN_TIMEOUT_GRACE_SECONDS - def submit_job(self, doc_id=None, callback_url=None, metadata=None, source="api"): + def submit_job( + self, doc_id=None, callback_url=None, metadata=None, source="api", origin=None + ): with self.jobs_lock: self._cleanup_expired_jobs_locked() active_job_id = self._find_active_job_id_locked() if active_job_id: - raise BusyError(active_job_id=active_job_id) + active_job = self.jobs.get(active_job_id) or {} + owned = active_job.get("origin") == origin + raise BusyError(active_job_id=active_job_id if owned else None) job_id = str(uuid.uuid4()) now = time.time() @@ -103,6 +110,7 @@ def submit_job(self, doc_id=None, callback_url=None, metadata=None, source="api" "result_bytes": None, "result_retrieved_at": None, "source": source, + "origin": origin, "error": None, } @@ -111,16 +119,16 @@ def submit_job(self, doc_id=None, callback_url=None, metadata=None, source="api" emit_status(job_id, "queued", doc_id=doc_id) return self.get_job(job_id) - def get_job(self, job_id): + def get_job(self, job_id, origin=ANY_ORIGIN): with self.jobs_lock: self._cleanup_expired_jobs_locked() - job = self.jobs.get(job_id) + job = self._visible_job_locked(job_id, origin) return self._serialize_job(job) if job else None - def consume_result(self, job_id): + def consume_result(self, job_id, origin=ANY_ORIGIN): with self.jobs_lock: self._cleanup_expired_jobs_locked() - job = self.jobs.get(job_id) + job = self._visible_job_locked(job_id, origin) if not job: return None, None @@ -436,6 +444,12 @@ def _send_callback(self, job, pdf_bytes): except Exception as exc: logger.error(f"Callback error for job {job['job_id']}: {exc}") + def _visible_job_locked(self, job_id, origin): + job = self.jobs.get(job_id) + if job and origin is not ANY_ORIGIN and job.get("origin") != origin: + return None + return job + def _find_active_job_id_locked(self): if self.current_job_id: return self.current_job_id From b08906848b71fb8c42841ee3eb80330c50e7a843 Mon Sep 17 00:00:00 2001 From: debeski Date: Sat, 14 Nov 2026 15:09:23 +0200 Subject: [PATCH 04/12] fix(server): cap request bodies at 64 KB and answer HTTP errors in JSON A 64 MB metadata body was accepted, retained with the job for its TTL and echoed by each 1 Hz status poll (+270 MB RSS per request). MAX_CONTENT_LENGTH now rejects it with 413 payload_too_large before any job is created, and werkzeug HTTP errors use the documented JSON error shape with CORS headers so the page can show them. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + docs/api.md | 5 +++- server.py | 14 +++++++++++ tests/test_browser_security.py | 46 +++++++++++++++++++++++++++++++++- 4 files changed, 64 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3f511a3..b51efc7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ This file owns the release history for `ScanLink`. - **Local-Only Control Endpoints**: `POST /shutdown` and `POST /internal/protocol/scan` refuse any request carrying `Origin` or `Sec-Fetch-Site` with `403 local_only`, so a cross-site form post can no longer shut ScanLink down; the protocol forwarder and local scripts send neither header. - **Scan Ownership By Origin**: `ScanWorker.submit_job()` records the requesting `Origin`; `GET /scan/` and `/result` answer `404 job_not_found` to any other origin, and `409 busy` includes `active_job_id` only for the job's own origin, so a website can no longer learn, follow and download another website's scan. - **Server-Side Origin Allow-List**: Browser-endpoint requests, including preflights, from an `Origin` outside a configured `cors_origins` list are refused with `403 origin_not_allowed` before any work, instead of only omitting CORS headers. +- **Request Body Limit**: `MAX_CONTENT_LENGTH` is 64 KB, answered as `413 payload_too_large`; a 64 MB `metadata` body was previously accepted, kept with the job for its 15-minute TTL and returned by every status poll. HTTP errors (`404`, `405`, `413`, `500`) now use the JSON error shape with CORS headers. ## v0.8.0b2 diff --git a/docs/api.md b/docs/api.md index 00a4ae6..21a5eb6 100644 --- a/docs/api.md +++ b/docs/api.md @@ -26,7 +26,9 @@ Errors use this shape: } ``` -Some errors include extra fields such as `active_job_id` or `current_status`. +Some errors include extra fields such as `active_job_id` or `current_status`. Protocol-level errors (unknown route `404`, wrong method `405`, oversized body `413`, internal error `500`) use the same shape, with CORS headers on browser endpoints. + +Request bodies are limited to 64 KB. ## GET /health @@ -90,6 +92,7 @@ Errors: | 400 | `invalid_callback` | Callback URL was not a string or could not be parsed. | | 400 | `invalid_metadata` | `metadata` was provided but is not an object. | | 409 | `busy` | Another scan job is queued or running. | +| 413 | `payload_too_large` | Request body exceeded 64 KB. | | 415 | `json_required` | Request did not use JSON. | Busy response: diff --git a/server.py b/server.py index 35a1827..d25b8dd 100644 --- a/server.py +++ b/server.py @@ -6,6 +6,7 @@ from urllib.parse import urlparse, urlsplit from flask import Flask, Response, jsonify, request, send_file +from werkzeug.exceptions import HTTPException from werkzeug.serving import make_server from utils import ( @@ -26,6 +27,8 @@ # DNS rebinding makes a foreign page same-origin with the helper, bypassing CORS, # so the Host header must name the loopback interface itself. LOOPBACK_HOSTNAMES = {"localhost", "127.0.0.1", "::1"} +# Scan requests carry a few identifiers; larger bodies would be kept with the job. +MAX_REQUEST_BYTES = 64 * 1024 def is_loopback_host(host): @@ -37,6 +40,7 @@ def is_loopback_host(host): def create_app(worker, shutdown_event, transport_state): app = Flask(__name__) + app.config["MAX_CONTENT_LENGTH"] = MAX_REQUEST_BYTES config = load_config() allowed_origins = config.get("cors_origins", ["*"]) @@ -123,6 +127,16 @@ def reject_foreign_host(): ) return None + @app.errorhandler(HTTPException) + def http_error(exc): + if exc.code == 413: + return error_response( + 413, "payload_too_large", "Scan requests must be smaller than 64 KB." + ) + return error_response( + exc.code, exc.name.lower().replace(" ", "_"), exc.description + ) + @app.after_request def add_cors_headers(response): if is_browser_endpoint(request.path): diff --git a/tests/test_browser_security.py b/tests/test_browser_security.py index daa5fe1..da8331b 100644 --- a/tests/test_browser_security.py +++ b/tests/test_browser_security.py @@ -7,6 +7,8 @@ from tests.test_server import FakeWorker from worker import ScanWorker +LEGIT = {"Origin": "https://archive.example"} + try: import server except ImportError: @@ -88,6 +90,49 @@ def test_browser_requests_cannot_use_local_control_endpoints(self): self.assertFalse(self.shutdown_event.is_set()) self.assertEqual(self.worker.jobs, {}) + def test_oversized_scan_bodies_are_refused_without_a_job(self): + body = '{"metadata": {"blob": "%s"}}' % ("x" * (1024 * 1024)) + for endpoint in ("/scan", "/internal/protocol/scan"): + with self.subTest(endpoint=endpoint): + headers = LEGIT if endpoint == "/scan" else {} + response = self.client.post( + endpoint, + data=body, + content_type="application/json", + headers=headers, + ) + self.assertEqual(response.status_code, 413) + self.assertEqual( + response.get_json()["error"]["code"], "payload_too_large" + ) + self.assertEqual( + response.headers.get("Access-Control-Allow-Origin"), None + ) + self.assertEqual(self.worker.jobs, {}) + small = self.client.post( + "/scan", json={"metadata": {"path": "/x" * 1000}}, headers=LEGIT + ) + self.assertEqual(small.status_code, 202) + + def test_http_errors_keep_the_json_error_shape(self): + refused = self.client.post( + "/scan", + data="x" * (1024 * 1024), + content_type="application/json", + headers=LEGIT, + ) + self.assertEqual( + refused.headers["Access-Control-Allow-Origin"], LEGIT["Origin"] + ) + for response, status in ( + (refused, 413), + (self.client.delete("/scan", headers=LEGIT), 405), + (self.client.get("/scan/a/b/c", headers=LEGIT), 404), + ): + self.assertEqual(response.status_code, status) + self.assertEqual(response.mimetype, "application/json") + self.assertTrue(response.get_json()["error"]["message"]) + def test_local_tools_keep_local_control_endpoints(self): protocol = self.client.post("/internal/protocol/scan", json={"action": "scan"}) shutdown = self.client.post("/shutdown") @@ -96,7 +141,6 @@ def test_local_tools_keep_local_control_endpoints(self): self.assertTrue(self.shutdown_event.is_set()) -LEGIT = {"Origin": "https://archive.example"} OTHER = {"Origin": "https://crm.example"} EVIL = {"Origin": "https://evil.example"} From 46b09cecc8b867e4500fcfa87af7011310afc81e Mon Sep 17 00:00:00 2001 From: debeski Date: Sat, 14 Nov 2026 15:09:48 +0200 Subject: [PATCH 05/12] fix(server): answer Private Network Access preflights Chromium sends Access-Control-Request-Private-Network: true when a public page calls a loopback address and, where PNA is enforced, blocks the request unless the preflight allows it. Allowed origins now get Access-Control-Allow-Private-Network: true. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + docs/api.md | 2 ++ server.py | 2 ++ tests/test_browser_security.py | 24 ++++++++++++++++++++++++ 4 files changed, 29 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index b51efc7..c66059e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ This file owns the release history for `ScanLink`. - **Scan Ownership By Origin**: `ScanWorker.submit_job()` records the requesting `Origin`; `GET /scan/` and `/result` answer `404 job_not_found` to any other origin, and `409 busy` includes `active_job_id` only for the job's own origin, so a website can no longer learn, follow and download another website's scan. - **Server-Side Origin Allow-List**: Browser-endpoint requests, including preflights, from an `Origin` outside a configured `cors_origins` list are refused with `403 origin_not_allowed` before any work, instead of only omitting CORS headers. - **Request Body Limit**: `MAX_CONTENT_LENGTH` is 64 KB, answered as `413 payload_too_large`; a 64 MB `metadata` body was previously accepted, kept with the job for its 15-minute TTL and returned by every status poll. HTTP errors (`404`, `405`, `413`, `500`) now use the JSON error shape with CORS headers. +- **Private Network Access Preflight**: Allowed-origin preflights carrying `Access-Control-Request-Private-Network: true` receive `Access-Control-Allow-Private-Network: true`. ## v0.8.0b2 diff --git a/docs/api.md b/docs/api.md index 21a5eb6..d8c25ab 100644 --- a/docs/api.md +++ b/docs/api.md @@ -221,6 +221,8 @@ Allowed origins come from `%LOCALAPPDATA%\ScanLink\config.json`: } ``` +Preflights that carry `Access-Control-Request-Private-Network: true` from an allowed origin are answered with `Access-Control-Allow-Private-Network: true`, as Chromium's Private Network Access requires for a public website calling the loopback helper. + When `cors_origins` is not `["*"]`, the request `Origin` must exactly match an entry in the list. Browser-endpoint requests from any other `Origin`, including preflights, receive `403 origin_not_allowed` before any work is done. With the default `["*"]`, every website the operator opens can call `/health` and `/scan` and download the scans it starts itself. Job ownership keeps each website away from scans started by others. List the DjangoLux origins in `cors_origins` to restrict which websites can scan. diff --git a/server.py b/server.py index d25b8dd..48774ec 100644 --- a/server.py +++ b/server.py @@ -60,6 +60,8 @@ def apply_cors(response): response.headers["Access-Control-Allow-Headers"] = "Content-Type" response.headers["Access-Control-Expose-Headers"] = "Content-Disposition" response.headers["Vary"] = "Origin" + if request.headers.get("Access-Control-Request-Private-Network") == "true": + response.headers["Access-Control-Allow-Private-Network"] = "true" return response def empty_options_response(): diff --git a/tests/test_browser_security.py b/tests/test_browser_security.py index da8331b..999e2e4 100644 --- a/tests/test_browser_security.py +++ b/tests/test_browser_security.py @@ -133,6 +133,30 @@ def test_http_errors_keep_the_json_error_shape(self): self.assertEqual(response.mimetype, "application/json") self.assertTrue(response.get_json()["error"]["message"]) + def test_private_network_preflight_is_answered_for_allowed_origins(self): + for path in ("/health", "/scan", "/scan/job-1", "/scan/job-1/result"): + with self.subTest(path=path): + response = self.client.options( + path, + headers={ + **LEGIT, + "Access-Control-Request-Method": "POST", + "Access-Control-Request-Headers": "content-type", + "Access-Control-Request-Private-Network": "true", + }, + ) + self.assertEqual(response.status_code, 204) + self.assertEqual( + response.headers["Access-Control-Allow-Private-Network"], "true" + ) + self.assertEqual( + response.headers["Access-Control-Allow-Origin"], LEGIT["Origin"] + ) + plain = self.client.options( + "/scan", headers={**LEGIT, "Access-Control-Request-Method": "POST"} + ) + self.assertNotIn("Access-Control-Allow-Private-Network", plain.headers) + def test_local_tools_keep_local_control_endpoints(self): protocol = self.client.post("/internal/protocol/scan", json={"action": "scan"}) shutdown = self.client.post("/shutdown") From ee7080a356a37d4db2480a544b398e78b8319aac Mon Sep 17 00:00:00 2001 From: debeski Date: Sat, 14 Nov 2026 15:12:06 +0200 Subject: [PATCH 06/12] fix(server): complete TLS handshakes off the accept loop, time out idle sockets werkzeug wraps the listening socket, so SSLSocket.accept() ran each TLS handshake in the single serve_forever thread: one TCP connection to :5443 that never sent a ClientHello blocked every HTTPS client indefinitely. The HTTPS listener now accepts with do_handshake_on_connect=False and LoopbackRequestHandler handshakes in the connection thread under a 30-second socket timeout, which also closes half-sent HTTP requests that previously held a thread forever. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 + docs/architecture.md | 7 ++ server.py | 24 +++++- tests/test_loopback_listener.py | 141 ++++++++++++++++++++++++++++++++ 4 files changed, 173 insertions(+), 1 deletion(-) create mode 100644 tests/test_loopback_listener.py diff --git a/CHANGELOG.md b/CHANGELOG.md index c66059e..9560b36 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,8 @@ This file owns the release history for `ScanLink`. - **Server-Side Origin Allow-List**: Browser-endpoint requests, including preflights, from an `Origin` outside a configured `cors_origins` list are refused with `403 origin_not_allowed` before any work, instead of only omitting CORS headers. - **Request Body Limit**: `MAX_CONTENT_LENGTH` is 64 KB, answered as `413 payload_too_large`; a 64 MB `metadata` body was previously accepted, kept with the job for its 15-minute TTL and returned by every status poll. HTTP errors (`404`, `405`, `413`, `500`) now use the JSON error shape with CORS headers. - **Private Network Access Preflight**: Allowed-origin preflights carrying `Access-Control-Request-Private-Network: true` receive `Access-Control-Allow-Private-Network: true`. +- **Non-Blocking TLS Accept**: `LoopbackServer` accepts HTTPS connections without handshaking and `LoopbackRequestHandler` completes the handshake in the connection's own thread; one TCP client that never sent a TLS hello previously stalled every HTTPS request indefinitely. +- **Connection Timeout**: `LoopbackRequestHandler` sets a 30-second socket timeout (`REQUEST_TIMEOUT_SECONDS`), so half-sent or idle connections no longer hold a server thread forever. ## v0.8.0b2 diff --git a/docs/architecture.md b/docs/architecture.md index 115c3e3..523ec11 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -158,6 +158,13 @@ HTTPS: 127.0.0.1:5443 ``` +Each listener is a threaded werkzeug server that serves one connection per +thread. Its `LoopbackRequestHandler` applies a 30-second socket timeout +(`REQUEST_TIMEOUT_SECONDS` in `server.py`) to every connection, and the HTTPS +listener performs the TLS handshake in that connection's thread rather than in +the accept loop, so an idle or slow client only holds its own thread until the +timeout and never blocks other clients. + On normal startup the server thread starts HTTP first, then prepares a trusted HTTPS identity automatically. A one-year self-signed **server** certificate (`BasicConstraints CA=False`, serverAuth EKU, no certificate-signing usage) diff --git a/server.py b/server.py index 48774ec..f354354 100644 --- a/server.py +++ b/server.py @@ -7,7 +7,7 @@ from flask import Flask, Response, jsonify, request, send_file from werkzeug.exceptions import HTTPException -from werkzeug.serving import make_server +from werkzeug.serving import WSGIRequestHandler, make_server from utils import ( APP_ARCH, @@ -29,6 +29,8 @@ LOOPBACK_HOSTNAMES = {"localhost", "127.0.0.1", "::1"} # Scan requests carry a few identifiers; larger bodies would be kept with the job. MAX_REQUEST_BYTES = 64 * 1024 +# Per-connection socket timeout, including the TLS handshake. +REQUEST_TIMEOUT_SECONDS = 30 def is_loopback_host(host): @@ -303,6 +305,23 @@ def emit_scan_status(job_id, status, **kwargs): return None +class LoopbackRequestHandler(WSGIRequestHandler): + def setup(self): + self.timeout = REQUEST_TIMEOUT_SECONDS + super().setup() + + def handle(self): + # The listener accepts without handshaking, so a client that never sends + # a TLS hello only holds its own thread, and only until the timeout. + if isinstance(self.connection, ssl.SSLSocket): + try: + self.connection.do_handshake() + except OSError as exc: + logger.debug("TLS handshake from %s failed: %s", self.client_address, exc) + return + super().handle() + + class LoopbackServer(threading.Thread): def __init__(self, app, host, port, ssl_context=None, label="HTTP"): super().__init__(daemon=True) @@ -327,8 +346,11 @@ def run(self): self.port, self.app, threaded=True, + request_handler=LoopbackRequestHandler, ssl_context=self.ssl_context, ) + if self.ssl_context is not None: + self.httpd.socket.do_handshake_on_connect = False logger.info("%s listener ready on %s:%s", self.label, self.host, self.port) except Exception as exc: self.error = exc diff --git a/tests/test_loopback_listener.py b/tests/test_loopback_listener.py new file mode 100644 index 0000000..99469d9 --- /dev/null +++ b/tests/test_loopback_listener.py @@ -0,0 +1,141 @@ +import datetime +import http.client +import ipaddress +import json +from pathlib import Path +import socket +import ssl +import threading +import time +import unittest +from unittest.mock import patch +import uuid + +from cryptography import x509 +from cryptography.hazmat.primitives import hashes, serialization +from cryptography.hazmat.primitives.asymmetric import ec +from cryptography.x509.oid import NameOID + +from tests.test_server import FakeWorker + +try: + import server +except ImportError: + server = None + + +def localhost_tls(): + key = ec.generate_private_key(ec.SECP256R1()) + name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "localhost")]) + now = datetime.datetime.now(datetime.timezone.utc) + certificate = ( + x509.CertificateBuilder() + .subject_name(name) + .issuer_name(name) + .public_key(key.public_key()) + .serial_number(x509.random_serial_number()) + .not_valid_before(now - datetime.timedelta(minutes=5)) + .not_valid_after(now + datetime.timedelta(days=1)) + .add_extension( + x509.SubjectAlternativeName( + [ + x509.DNSName("localhost"), + x509.IPAddress(ipaddress.ip_address("127.0.0.1")), + ] + ), + critical=False, + ) + .sign(key, hashes.SHA256()) + ) + directory = Path(".xclude/test-output/listener") / uuid.uuid4().hex + directory.mkdir(parents=True) + bundle = directory / "localhost.pem" + bundle.write_bytes( + certificate.public_bytes(serialization.Encoding.PEM) + + key.private_bytes( + serialization.Encoding.PEM, + serialization.PrivateFormat.PKCS8, + serialization.NoEncryption(), + ) + ) + server_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + server_context.load_cert_chain(str(bundle)) + return server_context, ssl.create_default_context(cafile=str(bundle)) + + +@unittest.skipIf(server is None, "Flask is not installed in this environment") +class LoopbackListenerTests(unittest.TestCase): + def setUp(self): + timeout = patch("server.REQUEST_TIMEOUT_SECONDS", 1) + timeout.start() + self.addCleanup(timeout.stop) + config = patch("server.load_config", return_value={"cors_origins": ["*"]}) + config.start() + self.addCleanup(config.stop) + app = server.create_app(FakeWorker(), threading.Event(), {"http_enabled": True}) + self.server_context, self.client_context = localhost_tls() + self.http = server.LoopbackServer(app, "127.0.0.1", 0, label="HTTP") + self.https = server.LoopbackServer( + app, "127.0.0.1", 0, ssl_context=self.server_context, label="HTTPS" + ) + for listener in (self.http, self.https): + listener.start() + self.assertTrue(listener.started.wait(5)) + self.assertIsNone(listener.error) + self.addCleanup(listener.join, 5) + self.addCleanup(listener.shutdown) + + def health(self, secure, timeout=3): + if secure: + raw = socket.create_connection( + ("127.0.0.1", self.https.httpd.server_port), timeout=timeout + ) + connection = http.client.HTTPConnection("localhost", timeout=timeout) + connection.sock = self.client_context.wrap_socket( + raw, server_hostname="localhost" + ) + else: + connection = http.client.HTTPConnection( + "127.0.0.1", self.http.httpd.server_port, timeout=timeout + ) + try: + connection.request("GET", "/health") + response = connection.getresponse() + return response.status, json.loads(response.read()) + finally: + connection.close() + + def test_a_client_that_never_starts_tls_does_not_block_https(self): + idle = [ + socket.create_connection(("127.0.0.1", self.https.httpd.server_port)) + for _ in range(3) + ] + self.addCleanup(lambda: [sock.close() for sock in idle]) + time.sleep(0.2) + started = time.monotonic() + status, payload = self.health(secure=True) + self.assertEqual(status, 200) + self.assertEqual(payload["status"], "ok") + self.assertLess(time.monotonic() - started, 1) + + def test_idle_connections_are_closed_after_the_request_timeout(self): + for port in (self.http.httpd.server_port, self.https.httpd.server_port): + with self.subTest(port=port): + sock = socket.create_connection(("127.0.0.1", port)) + self.addCleanup(sock.close) + if port == self.http.httpd.server_port: + sock.sendall(b"GET /health HTTP/1.1\r\nHost: 127.0.0.1\r\n") + sock.settimeout(10) + started = time.monotonic() + try: + data = sock.recv(1024) + except ConnectionResetError: + data = b"" + self.assertLess(time.monotonic() - started, 5) + self.assertFalse(data.startswith(b"HTTP/1.1 200")) + self.assertEqual(self.health(secure=False)[0], 200) + self.assertEqual(self.health(secure=True)[0], 200) + + +if __name__ == "__main__": + unittest.main() From db776217cef766e3f285e36f16dd39f1fd787fa9 Mon Sep 17 00:00:00 2001 From: debeski Date: Sat, 14 Nov 2026 15:15:10 +0200 Subject: [PATCH 07/12] fix(scanner): keep captured pages as JPEG and embed them without decoding The scan child kept every page as a decoded RGB image (~26 MB per A4 page at 300 DPI) and _create_pdf decoded each JPEG again through ImageReader, whose getRGBData() digest copy reportlab keeps until save(). 20 pages at 300 DPI or 60 pages at 200 DPI peaked near 2 GB, beyond a 32-bit (x86) build's address space, which the target 32-bit TWAIN driver requires. Pages are now JPEG-encoded on arrival with the same quality settings and drawn from temporary JPEG files, which reportlab embeds as-is: peak RSS 175-200 MB, identical image streams in the PDF. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + docs/architecture.md | 5 +++ scanner.py | 77 +++++++++++++++++++--------------- tests/test_scan_pages.py | 90 ++++++++++++++++++++++++++++++++++++++++ 4 files changed, 140 insertions(+), 33 deletions(-) create mode 100644 tests/test_scan_pages.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 9560b36..19d23a5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ This file owns the release history for `ScanLink`. - **Private Network Access Preflight**: Allowed-origin preflights carrying `Access-Control-Request-Private-Network: true` receive `Access-Control-Allow-Private-Network: true`. - **Non-Blocking TLS Accept**: `LoopbackServer` accepts HTTPS connections without handshaking and `LoopbackRequestHandler` completes the handshake in the connection's own thread; one TCP client that never sent a TLS hello previously stalled every HTTPS request indefinitely. - **Connection Timeout**: `LoopbackRequestHandler` sets a 30-second socket timeout (`REQUEST_TIMEOUT_SECONDS`), so half-sent or idle connections no longer hold a server thread forever. +- **Compressed Page Capture**: `ScannerManager` encodes each captured page to JPEG on arrival (`_encode_page`) and `_create_pdf` embeds the JPEG files through `drawImage(path)` instead of decoding them again through `ImageReader`; the scan child's peak memory for 20 pages at 300 DPI drops from about 2 GB to 0.2 GB, which previously exhausted x86 builds. Image streams in the PDF are unchanged. ## v0.8.0b2 diff --git a/docs/architecture.md b/docs/architecture.md index 523ec11..92fef83 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -67,6 +67,11 @@ worker.py This subprocess boundary protects the tray/API process from scanner driver crashes, stuck TWAIN calls, and long-running acquisition operations. +The child compresses each page to JPEG (quality 85) as soon as it is captured and +embeds those JPEG files in the PDF unchanged, so its memory grows with the +compressed page size rather than with decoded images (about 26 MB per A4 page at +300 DPI color). Long ADF batches therefore fit in a 32-bit (x86) build. + ## Thread Model Main process: diff --git a/scanner.py b/scanner.py index 248dc52..f224f6b 100644 --- a/scanner.py +++ b/scanner.py @@ -34,6 +34,8 @@ logger = get_logger() +PAGE_JPEG_QUALITY = 85 + class ScanError(Exception): def __init__(self, code, message, status="failed"): @@ -256,12 +258,6 @@ def scan_to_pdf(self, request_id, progress_callback=None, deadline=None): return self._create_pdf(images) except Exception as exc: raise ScanError("pdf_generation_failed", f"Failed to generate PDF: {exc}") from exc - finally: - for image in images: - try: - image.close() - except Exception: - pass def _open_source(self, sm, config, progress_callback=None, deadline=None): default_scanner = config.get("default_scanner") @@ -451,10 +447,7 @@ def after_transfer(twain_image, _more): code="acquire_timeout", message="Timed out while processing the scanned page.", ) - image = self._twain_image_to_pil(twain_image) - if image.mode != "RGB": - image = image.convert("RGB") - images.append(image) + images.append(self._encode_page(self._twain_image_to_pil(twain_image))) logger.info("Captured page %s via native transfer", len(images)) if progress_callback: progress_callback("page_scanned", page_count=len(images)) @@ -498,8 +491,7 @@ def after_transfer(_more): try: with PilImage.open(temp_path) as pil_image: pil_image.load() - image = pil_image.convert("RGB") if pil_image.mode != "RGB" else pil_image.copy() - images.append(image) + images.append(self._encode_page(pil_image)) logger.info("Captured page %s via file transfer", len(images)) if progress_callback: progress_callback("page_scanned", page_count=len(images)) @@ -642,33 +634,52 @@ def _check_deadline(self, deadline, code, message): if deadline and time.monotonic() > deadline: raise ScanError(code, message, status="timed_out") - def _create_pdf(self, images): + def _encode_page(self, image): + """Compress a captured page at once; decoded A4 pages cost ~26 MB each at 300 DPI.""" + rgb = image if image.mode == "RGB" else image.convert("RGB") + try: + buffer = io.BytesIO() + rgb.save(buffer, format="JPEG", quality=PAGE_JPEG_QUALITY, optimize=True) + return buffer.getvalue() + finally: + rgb.close() + if rgb is not image: + image.close() + + def _create_pdf(self, pages): buffer = io.BytesIO() document = canvas.Canvas(buffer, pagesize=A4) a4_width, a4_height = A4 + # drawImage(filename) embeds a JPEG file as-is; an ImageReader would be + # decoded to raw RGB and kept until save() for image de-duplication. + with tempfile.TemporaryDirectory(prefix="scanlink-pages-") as directory: + for index, page in enumerate(pages): + path = os.path.join(directory, f"page-{index:04d}.jpg") + with open(path, "wb") as page_file: + page_file.write(page) + try: + self._draw_page(document, path, page, a4_width, a4_height) + finally: + os.remove(path) + document.showPage() - for image in images: - image_buffer = io.BytesIO() - image.save(image_buffer, format="JPEG", quality=85, optimize=True) - image_buffer.seek(0) - - rl_image = reportlab_utils.ImageReader(image_buffer) - image_width, image_height = rl_image.getSize() - aspect = image_height / float(image_width) + document.save() + buffer.seek(0) + return buffer - draw_width = a4_width - draw_height = a4_width * aspect + def _draw_page(self, document, path, page, a4_width, a4_height): + with PilImage.open(io.BytesIO(page)) as header: + image_width, image_height = header.size + aspect = image_height / float(image_width) - if draw_height > a4_height: - draw_height = a4_height - draw_width = a4_height / aspect + draw_width = a4_width + draw_height = a4_width * aspect - x = (a4_width - draw_width) / 2.0 - y = (a4_height - draw_height) / 2.0 + if draw_height > a4_height: + draw_height = a4_height + draw_width = a4_height / aspect - document.drawImage(rl_image, x, y, width=draw_width, height=draw_height) - document.showPage() + x = (a4_width - draw_width) / 2.0 + y = (a4_height - draw_height) / 2.0 - document.save() - buffer.seek(0) - return buffer + document.drawImage(path, x, y, width=draw_width, height=draw_height) diff --git a/tests/test_scan_pages.py b/tests/test_scan_pages.py new file mode 100644 index 0000000..a90900a --- /dev/null +++ b/tests/test_scan_pages.py @@ -0,0 +1,90 @@ +import tracemalloc +import unittest + +try: + from PIL import Image, ImageDraw +except ImportError: + Image = None + +import scanner + +DPI = 150 +SIZE = (int(8.27 * DPI), int(11.69 * DPI)) +DECODED_PAGE_BYTES = SIZE[0] * SIZE[1] * 3 + + +def printed_page(): + page = Image.new("L", SIZE, 255) + draw = ImageDraw.Draw(page) + for y in range(0, SIZE[1], DPI // 6): + draw.line((DPI // 2, y, SIZE[0] - DPI // 2, y), fill=0, width=2) + return page + + +class FakeTwainImage: + def save(self, path): + printed_page().save(path, format="BMP") + + def close(self): + pass + + +class FakeSource: + def __init__(self, pages): + self.pages = pages + + def acquire_natively(self, after, before, show_ui, modal): + for index in range(self.pages): + before(None) + after(FakeTwainImage(), index < self.pages - 1) + + def acquire_file(self, before, after, show_ui, modal): + for index in range(self.pages): + path = before(None) + printed_page().save(path, format="BMP") + after(index < self.pages - 1) + + +@unittest.skipIf(Image is None or scanner.canvas is None, "Pillow/ReportLab missing") +class ScanPageMemoryTests(unittest.TestCase): + def acquire(self, mode, pages=3): + manager = scanner.ScannerManager() + captured = [] + progress = [] + acquire = getattr(manager, f"_acquire_via_{mode}_transfer") + acquire( + FakeSource(pages), + captured, + lambda status, **data: progress.append((status, data["page_count"])), + None, + False, + ) + self.assertEqual(progress[-1], ("page_scanned", pages)) + return manager, captured + + def test_captured_pages_are_kept_compressed(self): + for mode in ("native", "file"): + with self.subTest(mode=mode): + _, captured = self.acquire(mode) + self.assertEqual(len(captured), 3) + for page in captured: + self.assertIsInstance(page, bytes) + self.assertTrue(page.startswith(b"\xff\xd8")) + self.assertLess(len(page), DECODED_PAGE_BYTES // 10) + + def test_pdf_embeds_page_jpegs_without_decoding_them(self): + manager, captured = self.acquire("native", pages=4) + tracemalloc.start() + try: + pdf = manager._create_pdf(captured).getvalue() + peak = tracemalloc.get_traced_memory()[1] + finally: + tracemalloc.stop() + self.assertLess(peak, DECODED_PAGE_BYTES) + self.assertTrue(pdf.startswith(b"%PDF")) + self.assertEqual(pdf.count(b"/DCTDecode"), 4) + self.assertEqual(pdf.count(b"/Type /Page\n"), 4) + + +if __name__ == "__main__": + unittest.main() From b9cfa80aec4aa4bbfd7fba8979c681fed330b87b Mon Sep 17 00:00:00 2001 From: debeski Date: Sat, 14 Nov 2026 15:16:53 +0200 Subject: [PATCH 08/12] fix(scan_runtime): run scans only in ScanLink's own temp job directories The scanlink:// handler is registered as "ScanLink.exe" "%1". A launcher that does not escape quotes could inject --scan-worker-dir pointing at any folder or a \\host\share path: the child would read request.json there (sending NTLM credentials to the share), scan whatever is in the feeder and write result.pdf to it. run_scan_job() now exits with 1 unless the directory is a scanlink-job-* folder directly inside tempfile.gettempdir(), the only kind ScanWorker creates. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + docs/architecture.md | 6 ++++ scan_runtime.py | 19 ++++++++++- tests/test_scan_runtime.py | 68 ++++++++++++++++++++++++++++++++++++++ utils.py | 1 + worker.py | 4 +-- 6 files changed, 96 insertions(+), 3 deletions(-) create mode 100644 tests/test_scan_runtime.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 19d23a5..82c91a7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,7 @@ This file owns the release history for `ScanLink`. - **Non-Blocking TLS Accept**: `LoopbackServer` accepts HTTPS connections without handshaking and `LoopbackRequestHandler` completes the handshake in the connection's own thread; one TCP client that never sent a TLS hello previously stalled every HTTPS request indefinitely. - **Connection Timeout**: `LoopbackRequestHandler` sets a 30-second socket timeout (`REQUEST_TIMEOUT_SECONDS`), so half-sent or idle connections no longer hold a server thread forever. - **Compressed Page Capture**: `ScannerManager` encodes each captured page to JPEG on arrival (`_encode_page`) and `_create_pdf` embeds the JPEG files through `drawImage(path)` instead of decoding them again through `ImageReader`; the scan child's peak memory for 20 pages at 300 DPI drops from about 2 GB to 0.2 GB, which previously exhausted x86 builds. Image streams in the PDF are unchanged. +- **Scan Worker Directory Check**: `scan_runtime.run_scan_job()` refuses any `--scan-worker-dir` that is not a `scanlink-job-*` directory directly inside the temp directory, so an argument injected through an unescaped `scanlink://` launch cannot read a request from, or write a scanned PDF to, another folder or a network share. ## v0.8.0b2 diff --git a/docs/architecture.md b/docs/architecture.md index 92fef83..8d77458 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -67,6 +67,12 @@ worker.py This subprocess boundary protects the tray/API process from scanner driver crashes, stuck TWAIN calls, and long-running acquisition operations. +`scan_runtime.run_scan_job()` only runs in a `scanlink-job-*` directory directly +inside the user's temp directory, the only kind `ScanWorker` creates. Any other +`--scan-worker-dir` value, such as one injected through an unescaped +`scanlink://` launch or a network share path, exits with code 1 before reading +or writing anything. + The child compresses each page to JPEG (quality 85) as soon as it is captured and embeds those JPEG files in the PDF unchanged, so its memory grows with the compressed page size rather than with decoded images (about 26 MB per A4 page at diff --git a/scan_runtime.py b/scan_runtime.py index 9a785a8..fd090ae 100644 --- a/scan_runtime.py +++ b/scan_runtime.py @@ -1,12 +1,13 @@ import json import os import sys +import tempfile import time import tkinter as tk from gui.dialogs import init_gui from scanner import ScanError, ScannerManager -from utils import get_logger +from utils import SCAN_JOB_DIRECTORY_PREFIX, get_logger REQUEST_FILE = "request.json" STATE_FILE = "state.json" @@ -43,7 +44,23 @@ def _write_result(work_dir, pdf_buffer): result_file.write(pdf_buffer.getvalue()) +def is_job_directory(work_dir): + """True only for a directory ScanWorker created with tempfile.mkdtemp().""" + path = os.path.abspath(work_dir) + return ( + os.path.basename(path).startswith(SCAN_JOB_DIRECTORY_PREFIX) + and os.path.normcase(os.path.dirname(path)) + == os.path.normcase(os.path.abspath(tempfile.gettempdir())) + and os.path.isdir(path) + ) + + def run_scan_job(work_dir): + # A launcher that passes an unescaped scanlink:// URL could inject + # --scan-worker-dir pointing at another folder or a remote share. + if not is_job_directory(work_dir): + logger.error("Refusing scan worker directory outside ScanLink's temp jobs: %r", work_dir) + return 1 root = None try: request = _read_request(work_dir) diff --git a/tests/test_scan_runtime.py b/tests/test_scan_runtime.py new file mode 100644 index 0000000..d6fb856 --- /dev/null +++ b/tests/test_scan_runtime.py @@ -0,0 +1,68 @@ +import io +import json +import os +from pathlib import Path +import shutil +import tempfile +import unittest +from unittest.mock import MagicMock, patch +import uuid + +import scan_runtime + + +class ScanRuntimeDirectoryTests(unittest.TestCase): + def setUp(self): + self.scanner = MagicMock() + self.scanner.return_value.scan_to_pdf.side_effect = ( + lambda *args, **kwargs: io.BytesIO(b"%PDF-1.4\n") + ) + for target, replacement in ( + ("scan_runtime.ScannerManager", self.scanner), + ("scan_runtime.tk.Tk", MagicMock()), + ("scan_runtime.init_gui", MagicMock()), + ): + patcher = patch(target, replacement) + patcher.start() + self.addCleanup(patcher.stop) + + def prepared(self, directory): + directory = Path(directory) + directory.mkdir(parents=True, exist_ok=True) + (directory / "request.json").write_text( + json.dumps({"job_id": "job", "scan_timeout_seconds": 5}) + ) + return directory + + def test_injected_worker_directories_are_refused(self): + outside = Path(".xclude/test-output/runtime") / uuid.uuid4().hex + job_named_outside = outside / "scanlink-job-injected" + temp_job = Path(tempfile.mkdtemp(prefix="scanlink-job-")) + self.addCleanup(shutil.rmtree, temp_job, ignore_errors=True) + other_temp = Path(tempfile.mkdtemp(prefix="not-scanlink-")) + self.addCleanup(shutil.rmtree, other_temp, ignore_errors=True) + for directory in ( + self.prepared(outside), + self.prepared(job_named_outside), + self.prepared(other_temp), + os.path.join(temp_job, "..", other_temp.name), + r"\\attacker.example\share\scanlink-job-x", + ): + with self.subTest(directory=str(directory)): + self.assertNotEqual(scan_runtime.run_scan_job(str(directory)), 0) + for name in ("state.json", "result.pdf"): + self.assertFalse(Path(directory, name).exists()) + self.scanner.return_value.scan_to_pdf.assert_not_called() + + def test_parent_created_job_directory_runs(self): + directory = self.prepared(tempfile.mkdtemp(prefix="scanlink-job-")) + self.addCleanup(shutil.rmtree, directory, ignore_errors=True) + self.assertEqual(scan_runtime.run_scan_job(str(directory)), 0) + self.assertEqual((directory / "result.pdf").read_bytes(), b"%PDF-1.4\n") + self.assertEqual( + json.loads((directory / "state.json").read_text())["status"], "completed" + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/utils.py b/utils.py index 23ffd3a..6c20f73 100644 --- a/utils.py +++ b/utils.py @@ -49,6 +49,7 @@ def load_app_version(): DEFAULT_SCAN_TIMEOUT_SECONDS = 600 DEFAULT_GUI_TASK_TIMEOUT_SECONDS = 900 DEFAULT_SCAN_IDLE_TIMEOUT_SECONDS = 45 +SCAN_JOB_DIRECTORY_PREFIX = "scanlink-job-" DEFAULT_RESOLUTION = 200 DEFAULT_SCAN_SOURCE = "adf" DEFAULT_SCAN_SIDE = "front" diff --git a/worker.py b/worker.py index 2ed6bec..e19932b 100644 --- a/worker.py +++ b/worker.py @@ -17,7 +17,7 @@ requests = None from scanner import ScanError, ScannerManager -from utils import get_logger, load_config +from utils import SCAN_JOB_DIRECTORY_PREFIX, get_logger, load_config logger = get_logger() @@ -263,7 +263,7 @@ def run_gui_task(self, func, timeout=30): return self._execute_gui(func, timeout=timeout) def _run_scan_subprocess(self, job_id, on_progress): - work_dir = tempfile.mkdtemp(prefix="scanlink-job-") + work_dir = tempfile.mkdtemp(prefix=SCAN_JOB_DIRECTORY_PREFIX) state_path = os.path.join(work_dir, "state.json") result_path = os.path.join(work_dir, "result.pdf") request_path = os.path.join(work_dir, "request.json") From cc5716f9848e9b65a92211ea832ca8abd0fe59a7 Mon Sep 17 00:00:00 2001 From: debeski Date: Sat, 14 Nov 2026 15:18:19 +0200 Subject: [PATCH 09/12] fix(protocol): verify the helper's identity and keep log entries on one line is_existing_instance_running() treated any 200 from 127.0.0.1:5000/health as a running ScanLink and forward_protocol_command() any 2xx/409 as a hand-off, so another program on port 5000 made ScanLink exit at startup and silently dropped protocol scans. Both now require ScanLink's JSON answers. parse_protocol_url() logged the raw URL on failure, letting a crafted scanlink:// link forge scanner.log lines; values are now logged with %r. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 ++ docs/architecture.md | 4 +-- protocol_handler.py | 29 ++++++++++++++++--- tests/test_protocol_handler.py | 52 ++++++++++++++++++++++++++++++++-- 4 files changed, 79 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 82c91a7..ae5f01c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,8 @@ This file owns the release history for `ScanLink`. - **Connection Timeout**: `LoopbackRequestHandler` sets a 30-second socket timeout (`REQUEST_TIMEOUT_SECONDS`), so half-sent or idle connections no longer hold a server thread forever. - **Compressed Page Capture**: `ScannerManager` encodes each captured page to JPEG on arrival (`_encode_page`) and `_create_pdf` embeds the JPEG files through `drawImage(path)` instead of decoding them again through `ImageReader`; the scan child's peak memory for 20 pages at 300 DPI drops from about 2 GB to 0.2 GB, which previously exhausted x86 builds. Image streams in the PDF are unchanged. - **Scan Worker Directory Check**: `scan_runtime.run_scan_job()` refuses any `--scan-worker-dir` that is not a `scanlink-job-*` directory directly inside the temp directory, so an argument injected through an unescaped `scanlink://` launch cannot read a request from, or write a scanned PDF to, another folder or a network share. +- **Helper Identity Check**: `protocol_handler.is_existing_instance_running()` and `forward_protocol_command()` accept only ScanLink-shaped answers, so another program returning `200` on port 5000 no longer makes a new ScanLink exit as a duplicate or swallow a protocol scan. +- **Protocol Log Lines**: `parse_protocol_url()` logs URLs and parsed values with `%r`, so a `scanlink://` URL with encoded line breaks cannot forge `scanner.log` entries. ## v0.8.0b2 diff --git a/docs/architecture.md b/docs/architecture.md index 8d77458..ad51550 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -218,8 +218,8 @@ When launched with a `scanlink://` URL: 1. `main.py` parses the URL with `protocol_handler.parse_protocol_url()`. 2. It tries to forward the command to `http://127.0.0.1:5000/internal/protocol/scan`. -3. If forwarding succeeds, the new process exits. -4. If no instance is running, the new process becomes the tray instance and queues the protocol scan after startup. +3. If forwarding succeeds, the new process exits. Forwarding succeeds only on a ScanLink answer: `202` with a `job_id`, or `409` with error code `busy`. +4. If no instance is running, the new process becomes the tray instance and queues the protocol scan after startup. An instance counts as running only when `/health` returns ScanLink's JSON (`status: ok` with `version` and `twain_available`), so another program answering on port 5000 does not make ScanLink exit. This prevents duplicate tray apps and competing scanner sessions. diff --git a/protocol_handler.py b/protocol_handler.py index 07df043..48c91c8 100644 --- a/protocol_handler.py +++ b/protocol_handler.py @@ -42,10 +42,10 @@ def parse_protocol_url(url): "doc_id": doc_id, "callback_url": callback_url, } - logger.info(f"Parsed protocol URL: {result}") + logger.info("Parsed protocol URL: %r", result) return result except Exception as exc: - logger.error(f"Failed to parse protocol URL '{url}': {exc}") + logger.error("Failed to parse protocol URL %r: %s", url, exc) return None @@ -64,6 +64,14 @@ def extract_protocol_url_from_args(args): return None +def _json_object(response): + try: + payload = response.json() + except ValueError: + return {} + return payload if isinstance(payload, dict) else {} + + def is_existing_instance_running(timeout=1.0): """Probe the loopback HTTP health endpoint for an already-running helper.""" if requests is None: @@ -72,9 +80,16 @@ def is_existing_instance_running(timeout=1.0): try: response = requests.get(HEALTH_ENDPOINT, timeout=timeout) - return response.ok except requests.RequestException: return False + # Another program on port 5000 must not make ScanLink exit as a duplicate. + health = _json_object(response) + return ( + response.ok + and health.get("status") == "ok" + and "version" in health + and "twain_available" in health + ) def forward_protocol_command(command, timeout=3.0): @@ -90,7 +105,13 @@ def forward_protocol_command(command, timeout=3.0): try: response = requests.post(INTERNAL_PROTOCOL_ENDPOINT, json=command, timeout=timeout) - if response.ok or response.status_code == 409: + payload = _json_object(response) + error = payload.get("error") + if (response.status_code == 202 and payload.get("job_id")) or ( + response.status_code == 409 + and isinstance(error, dict) + and error.get("code") == "busy" + ): logger.info( "Forwarded protocol command to existing instance with response %s", response.status_code, diff --git a/tests/test_protocol_handler.py b/tests/test_protocol_handler.py index 9adf151..607f672 100644 --- a/tests/test_protocol_handler.py +++ b/tests/test_protocol_handler.py @@ -16,7 +16,11 @@ def test_parse_protocol_url_extracts_known_fields(self): @patch.object(protocol_handler, "requests") def test_forward_protocol_command_accepts_busy_response(self, mock_requests): - mock_requests.post.return_value = Mock(ok=False, status_code=409) + mock_requests.post.return_value = Mock( + ok=False, + status_code=409, + json=Mock(return_value={"error": {"code": "busy", "message": "Busy"}}), + ) forwarded = protocol_handler.forward_protocol_command( {"action": "scan", "doc_id": "42", "callback_url": None} @@ -26,10 +30,54 @@ def test_forward_protocol_command_accepts_busy_response(self, mock_requests): @patch.object(protocol_handler, "requests") def test_is_existing_instance_running_checks_health(self, mock_requests): - mock_requests.get.return_value = Mock(ok=True) + mock_requests.get.return_value = Mock( + ok=True, + json=Mock( + return_value={"status": "ok", "version": "0.8.0", "twain_available": True} + ), + ) self.assertTrue(protocol_handler.is_existing_instance_running()) + @patch.object(protocol_handler, "requests") + def test_another_program_on_the_port_is_not_scanlink(self, mock_requests): + mock_requests.RequestException = Exception + for payload in (ValueError("not json"), {"status": "ok"}, ["ok"]): + with self.subTest(payload=payload): + foreign = Mock(ok=True, status_code=200) + if isinstance(payload, Exception): + foreign.json.side_effect = payload + else: + foreign.json.return_value = payload + mock_requests.get.return_value = foreign + mock_requests.post.return_value = foreign + self.assertFalse(protocol_handler.is_existing_instance_running()) + self.assertFalse( + protocol_handler.forward_protocol_command({"action": "scan"}) + ) + + @patch.object(protocol_handler, "requests") + def test_forward_protocol_command_accepts_a_queued_job(self, mock_requests): + mock_requests.post.return_value = Mock( + ok=True, + status_code=202, + json=Mock(return_value={"job_id": "job-1", "status": "queued"}), + ) + + self.assertTrue(protocol_handler.forward_protocol_command({"action": "scan"})) + + def test_parse_failures_are_logged_on_one_line(self): + with self.assertLogs("ScanLink", level="DEBUG") as captured: + self.assertIsNone( + protocol_handler.parse_protocol_url( + "scanlink://[\n2026-11-14 09:00:00,000 - INFO - forged" + ) + ) + protocol_handler.parse_protocol_url("scanlink://scan?docId=a%0D%0Aforged") + for line in captured.output: + self.assertNotIn("\n", line) + self.assertNotIn("\r", line) + if __name__ == "__main__": unittest.main() From d2db27971820b7f83adaeb6a7c1a26e4033501e9 Mon Sep 17 00:00:00 2001 From: debeski Date: Sat, 14 Nov 2026 15:28:11 +0200 Subject: [PATCH 10/12] docs: record stress hardening state and open browser-origin decisions Developer guide states the Host check, what the default ["*"] allows and that jobs belong to their Origin. Tracker records the branch, the open wildcard-origin decision, the DjangoLux timeout/error-code gaps and the validation run. Co-Authored-By: Claude Opus 5.5 --- docs/developer-guide.md | 5 +++-- tracker.md | 7 ++++++- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/docs/developer-guide.md b/docs/developer-guide.md index 9d39c6e..c6fe537 100644 --- a/docs/developer-guide.md +++ b/docs/developer-guide.md @@ -191,8 +191,9 @@ Downloading `/scan//result` consumes the stored PDF. A second download f ## Operational Notes -- The API is bound to `127.0.0.1`, not a public network interface. -- CORS defaults to `["*"]` in `%LOCALAPPDATA%\ScanLink\config.json`. +- The API is bound to `127.0.0.1`, not a public network interface, and answers only requests whose `Host` is `localhost`, `127.0.0.1` or `[::1]`. +- CORS defaults to `["*"]` in `%LOCALAPPDATA%\ScanLink\config.json`: any website can start a scan and download the scans it started. List your application origins in `cors_origins` to restrict it; see [API Reference](api.md#cors). +- A scan job belongs to the `Origin` that started it; poll status and download the result from the same page origin. - The first scan may show a scanner selection dialog. - If the user selects "Set as default scanner", later scans skip scanner selection. - Tray settings control source, side, color mode, resolution, scanner UI visibility, paper protection, startup, and diagnostics. diff --git a/tracker.md b/tracker.md index f994a7e..11ad11b 100644 --- a/tracker.md +++ b/tracker.md @@ -3,6 +3,7 @@ ## Part 1: Project-specific ### Current Snapshot - Published 0.8.0b1 on `0.8/stress_fixes` (2026-10-25): real worker completion/deadline, public/internal input validation, single POST transport behavior and result-race fixes. Published0.7.5b1 (tagd74bf90) and stable Latest0.7.4 unchanged; owner authorized publication2026-10-25; PR2 merged as a82aab7; v0.8.0b1 published, release40233617433 PASS, x64/x86 asset digests verified; stable Latest stays0.7.4. +- Branch `0.8/stress_fixes` (2026-11-14, local only, unpushed, VERSION still 0.8.0b2): browser-security and transport hardening under `## Unreleased` — loopback Host check, local-only `/shutdown` and protocol endpoint, scans bound to their Origin, server-side allow-list refusal, 64 KB bodies + JSON HTTP errors, PNA preflight, TLS handshake off the accept loop + 30 s socket timeout, JPEG page capture (x86 memory), scan worker directory check, helper identity check. - Windows tray app uses TWAIN/pytwain; scan jobs run through child `main.py --scan-worker-dir` / `scan_runtime.py`. - Normal startup serves HTTP :5000 while automatically provisioning trusted localhost HTTPS :5443; failed setup offers native Retry and a tray repair action. - `certificates.py`: per-user localhost-only self-signed server identity, Windows CurrentUser Root trust, encrypted PKCS#8 key with DPAPI-protected password; hourly checks/30-day renewal and live TLS context selection. @@ -21,10 +22,13 @@ - Windows x64/x86 unit/build/install gates passed, including real certificate consent, DPAPI/trust, 120 verified HTTPS requests per architecture and restart identity reuse. Real Windows browser/scanner and enterprise-policy acceptance remain manual. - Target PaperStream fi-6230Z may expose only 32-bit TWAIN; live driver compliance/output quality remain unverified. Back-only and blank-page discard remain unsupported. - Organization/browser policies may refuse user-installed trust. A denied setup is reported as failure and retried with the same identity, without repeated automatic dialogs. -- Callbacks are never delivered (since 36249b6, 2026-04-28): `_process_job` passes the serialized job, which omits `callback_url`, to `_send_callback`. Docs promise delivery; enabling it changes production behavior and needs an owner decision. +- Default `cors_origins: ["*"]` (persisted in existing config.json files) lets any website the operator opens start a scan and download it; silent once a default scanner is saved. Ownership now blocks cross-site theft; closing the rest (first-use origin approval or provisioned DjangoLux origins) needs an owner decision. +- Contract gaps on the DjangoLux side: `scan_button.js` gives up after 5 min while ScanLink's deadline is 600+15 s (no cancel endpoint; retry reports busy, PDF orphaned 300 s); `no_pages_scanned`, `scan_idle_timeout`, `acquire_failed`, `scan_worker_crashed`, `origin_not_allowed`, `payload_too_large` show ScanLink's English message. +- Callbacks are never delivered (since 36249b6, 2026-04-28): `_process_job` passes the serialized job, which omits `callback_url`, to `_send_callback`. Docs promise delivery; enabling it changes production behavior and needs an owner decision. Any re-enable must restrict callback hosts: any page or `scanlink://` link can set `callback_url`. ### Active & Pending Tasks - [x] 0.8.0b2 merged to main via PR3 (063269b, 2026-10-30; CI 3/3 PASS): 15s parent scan-deadline grace, callback parse guard, per-scan `/health` in `scanlink.js`. Untagged; tagging/publishing needs owner OK. +- [ ] Review/merge `0.8/stress_fixes` (11 fix commits, 63 tests); then decide the `["*"]` default and the DjangoLux timeout/error-code mapping. - [ ] Mirror the per-scan health check in DjangoLux `scan_button.js` if it shares the stale-transport logic. - [x] 2026-10-30: retired `0.7/automatic_https`, `0.8/stress_fixes`, `0.8/stress_followups` (checkouts removed, branches deleted locally/GitHub; leftovers in `.xclude/retired-worktrees/2026-10-30/`). Only `main` remains. - [x] Paired deeper stress and real-worker regressions pass; candidate0.8.0b1 prepared locally. Owner authorized next beta; PR2 merged after x86/x64 native CI PASS, release gates PASS, both installers published. @@ -38,6 +42,7 @@ - [x] Verified real TLS handshakes, hostname rejection and live identity renewal; setup failure preserves HTTP and Retry recovers HTTPS. ### Validation & Docs Log +- 2026-11-14 `0.8/stress_fixes`, macOS scratch venv (py3.13, Flask 3.1.3): 63 tests OK/1 Windows skip; live stack 20×50 concurrent POSTs (1 accepted each), 50k mixed requests flat RSS, 150 scan cycles, 200 idle HTTP + 200 idle TLS sockets, 7k connect/close, 126 MB result over HTTP/HTTPS, 50k fuzzed `scanlink://` URLs; DjangoLux `main.js`+`scan_button.js` end-to-end against the live stack; dlux `scenarios.mjs` 34/34. Docs: api/architecture, CHANGELOG Unreleased. Evidence `.xclude/validation/stress-2026-11-14/`. No Windows/TWAIN run. - 2026-10-30: 0.8.0b2 changes, macOS: 42 unit tests OK/1 Windows skip (scratch venv). New grace/callback tests fail on 0.8.0b1 code; Node harness for `scanlink.js` 4/4 (old: 2/4). Docs: api/architecture/developer guide, CHANGELOG v0.8.0b2, VERSION 0.8.0b2. Windows/native gates not run. - 2026-10-25: 40 local unit tests OK/1 Windows skip; Windows CI/release PASS x64+x86 including consent/120 HTTPS/restart; pairedJS24 PASS; real worker1000 health (500 verified TLS)/100 hashed PDFs/50 busy/40 result races PASS; timeouts/crash/cancel/callback/shutdown recovery PASS.8097 UI300 health/30 scans/20 simultaneous, PDF save/Arabic lost-response guidance/one POST PASS. Dlux3064 OK/6skips +79 focused; doctor0error. Native candidate gates now PASS; physical hardware/Windows browser policies unverified. - 2026-10-25: API/architecture/developer guide, VERSION0.8.0b1 and CHANGELOG document parent-owned completion, hard deadline, strict payloads, retained metadata and scan_request_uncertain. Local report `.xclude/retired-worktrees/2026-10-30/stress_fixes/.xclude/validation/paired-stress-2026-10-25.md`. From 05ec086b77c956530472692bb14e8bb424fb14c2 Mon Sep 17 00:00:00 2001 From: debeski Date: Sat, 14 Nov 2026 15:32:34 +0200 Subject: [PATCH 11/12] docs(tracker): correct the branch fix-commit count Co-Authored-By: Claude Opus 5.5 --- tracker.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tracker.md b/tracker.md index 11ad11b..15f7ab1 100644 --- a/tracker.md +++ b/tracker.md @@ -28,7 +28,7 @@ ### Active & Pending Tasks - [x] 0.8.0b2 merged to main via PR3 (063269b, 2026-10-30; CI 3/3 PASS): 15s parent scan-deadline grace, callback parse guard, per-scan `/health` in `scanlink.js`. Untagged; tagging/publishing needs owner OK. -- [ ] Review/merge `0.8/stress_fixes` (11 fix commits, 63 tests); then decide the `["*"]` default and the DjangoLux timeout/error-code mapping. +- [ ] Review/merge `0.8/stress_fixes` (10 fix commits, 63 tests); then decide the `["*"]` default and the DjangoLux timeout/error-code mapping. - [ ] Mirror the per-scan health check in DjangoLux `scan_button.js` if it shares the stale-transport logic. - [x] 2026-10-30: retired `0.7/automatic_https`, `0.8/stress_fixes`, `0.8/stress_followups` (checkouts removed, branches deleted locally/GitHub; leftovers in `.xclude/retired-worktrees/2026-10-30/`). Only `main` remains. - [x] Paired deeper stress and real-worker regressions pass; candidate0.8.0b1 prepared locally. Owner authorized next beta; PR2 merged after x86/x64 native CI PASS, release gates PASS, both installers published. From 2998cd1ca29192a7837f49b7d798d23e52b35656 Mon Sep 17 00:00:00 2001 From: debeski Date: Sat, 14 Nov 2026 20:01:59 +0200 Subject: [PATCH 12/12] feat(security): no website scans until the operator links it The default cors_origins ["*"] (saved in existing config.json files) let every website the operator opened start a scan and download it, silently once a default scanner was saved. Owner decision: DjangoLux supplies its own sites, so the admin chooses which websites may scan. - cors_origins defaults to [] and wildcards are ignored on load. - POST /link (sites.SiteRegistry): a website asks to link, naming the sites its administrator allows. An unlinked website opens an approval window (gui.dialogs.confirm_site_link) that names the requesting origin as the browser sent it; one window at a time, 120 s, and a declined website cannot ask again for 10 minutes. A linked website replaces its list without asking. Links persist in config.json linked_sites. - Browser endpoints answer CORS for any well-formed origin, so an unlinked website reads 403 origin_not_allowed and can offer to link; the work itself stays gated. GET /health reports the site's link. - Tray menu: Linked Websites lists links and unlinks them. - scanlink.js: link(sites), and checkHealth() reports origin_not_allowed instead of helper_unavailable. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 5 +- build_exe.py | 1 + docs/api.md | 80 +++++++++++-- docs/architecture.md | 3 +- docs/developer-guide.md | 2 +- gui/dialogs.py | 63 ++++++++++ main.py | 18 ++- server.py | 85 ++++++++----- sites.py | 153 ++++++++++++++++++++++++ static/scanlink.js | 34 ++++++ tests/test_browser_security.py | 21 ++-- tests/test_server.py | 2 +- tests/test_site_links.py | 211 +++++++++++++++++++++++++++++++++ tracker.md | 4 +- tray.py | 23 +++- utils.py | 50 +++++++- 16 files changed, 697 insertions(+), 58 deletions(-) create mode 100644 sites.py create mode 100644 tests/test_site_links.py diff --git a/CHANGELOG.md b/CHANGELOG.md index ae5f01c..f6b9c5d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,12 +4,13 @@ This file owns the release history for `ScanLink`. ## Unreleased +- **No Website Can Scan Until Allowed (security)**: `cors_origins` defaults to `[]` and wildcards are ignored, so a saved `["*"]` no longer lets every website the operator opens start a scan and download it (silently once a default scanner is saved). New `POST /link` (`sites.SiteRegistry`): a website asks to link, naming the sites its administrator allows; an unlinked one opens an approval window in ScanLink (`gui.dialogs.confirm_site_link`) naming the requesting origin as the browser sent it, waits up to 120 s, one window at a time, and a declined site cannot ask again for 10 minutes. A linked site replaces its list without asking. Links persist in `config.json` `linked_sites`; the tray menu's **Linked Websites** lists and unlinks them. `GET /health` reports `link` for the requesting site. The bundled `scanlink.js` adds `link(sites)` and reports `origin_not_allowed` from `checkHealth()`. Upgrading operators approve each website once. - **Loopback Host Check**: `server.create_app()` refuses every request whose `Host` header is not `localhost`, `127.0.0.1` or `[::1]` with `403 invalid_host`, so a DNS-rebound page cannot reach the API as a same-origin client. - **Local-Only Control Endpoints**: `POST /shutdown` and `POST /internal/protocol/scan` refuse any request carrying `Origin` or `Sec-Fetch-Site` with `403 local_only`, so a cross-site form post can no longer shut ScanLink down; the protocol forwarder and local scripts send neither header. - **Scan Ownership By Origin**: `ScanWorker.submit_job()` records the requesting `Origin`; `GET /scan/` and `/result` answer `404 job_not_found` to any other origin, and `409 busy` includes `active_job_id` only for the job's own origin, so a website can no longer learn, follow and download another website's scan. -- **Server-Side Origin Allow-List**: Browser-endpoint requests, including preflights, from an `Origin` outside a configured `cors_origins` list are refused with `403 origin_not_allowed` before any work, instead of only omitting CORS headers. +- **Server-Side Origin Allow-List**: Browser-endpoint requests from a website that is not allowed are refused with `403 origin_not_allowed` before any work, instead of only omitting CORS headers; the refusal carries CORS headers so the page can read it and offer to link. - **Request Body Limit**: `MAX_CONTENT_LENGTH` is 64 KB, answered as `413 payload_too_large`; a 64 MB `metadata` body was previously accepted, kept with the job for its 15-minute TTL and returned by every status poll. HTTP errors (`404`, `405`, `413`, `500`) now use the JSON error shape with CORS headers. -- **Private Network Access Preflight**: Allowed-origin preflights carrying `Access-Control-Request-Private-Network: true` receive `Access-Control-Allow-Private-Network: true`. +- **Private Network Access Preflight**: Preflights carrying `Access-Control-Request-Private-Network: true` receive `Access-Control-Allow-Private-Network: true`. - **Non-Blocking TLS Accept**: `LoopbackServer` accepts HTTPS connections without handshaking and `LoopbackRequestHandler` completes the handshake in the connection's own thread; one TCP client that never sent a TLS hello previously stalled every HTTPS request indefinitely. - **Connection Timeout**: `LoopbackRequestHandler` sets a 30-second socket timeout (`REQUEST_TIMEOUT_SECONDS`), so half-sent or idle connections no longer hold a server thread forever. - **Compressed Page Capture**: `ScannerManager` encodes each captured page to JPEG on arrival (`_encode_page`) and `_create_pdf` embeds the JPEG files through `drawImage(path)` instead of decoding them again through `ImageReader`; the scan child's peak memory for 20 pages at 300 DPI drops from about 2 GB to 0.2 GB, which previously exhausted x86 builds. Image streams in the PDF are unchanged. diff --git a/build_exe.py b/build_exe.py index a859a32..887fae2 100644 --- a/build_exe.py +++ b/build_exe.py @@ -172,6 +172,7 @@ def build_pyinstaller_args(build_name): "--hidden-import=PIL.Image", "--hidden-import=PIL.ImageDraw", "--hidden-import=protocol_handler", + "--hidden-import=sites", "--hidden-import=flask", "--hidden-import=werkzeug", "--hidden-import=jinja2", diff --git a/docs/api.md b/docs/api.md index d8c25ab..cf27cbf 100644 --- a/docs/api.md +++ b/docs/api.md @@ -43,10 +43,16 @@ Response: "busy": false, "http_enabled": true, "https_enabled": false, - "twain_available": true + "twain_available": true, + "link": {"linked": true, "sites": ["https://archive.example", "https://crm.example"]} } ``` +`link` describes the requesting website: whether it is linked itself and, if so, +the sites its link allows. A website allowed only through `cors_origins` or +another site's list reports `{"linked": false, "sites": []}`. Requests without +`Origin` receive no `link`. + ## POST /scan Starts a scan job. @@ -204,28 +210,78 @@ Errors from the scanner/runtime layer can appear inside the job `error` object: | `scan_worker_crashed` | Child scan process exited unexpectedly. | | `unexpected_error` | Unhandled worker exception. | -## CORS +## Allowed websites + +A website may use the browser endpoints when it is listed in +`%LOCALAPPDATA%\ScanLink\config.json` or linked: + +```json +{ + "cors_origins": ["https://archive.example"], + "linked_sites": { + "https://archive.example": { + "sites": ["https://archive.example", "https://crm.example"], + "linked_at": "2026-11-14T12:00:00Z" + } + } +} +``` + +- `cors_origins` is set by hand or by IT and needs a restart. It is empty by + default. Entries must be website origins (`scheme://host[:port]`); `"*"` and + other wildcards are ignored, so no setting lets every website scan. +- `linked_sites` is written by [`POST /link`](#post-link) after the operator + approves a website, and by the tray menu's **Linked Websites → Unlink**. Each + linked website allows itself and the sites in its `sites` list. + +Every browser endpoint answers CORS for any well-formed `Origin`, including +preflights, so an unlinked website can read why it was refused. Requests from a +website that is neither listed nor linked receive `403 origin_not_allowed` before +any work is done; only `POST /link` is open to every website. Preflights carrying +`Access-Control-Request-Private-Network: true` are answered with +`Access-Control-Allow-Private-Network: true`, as Chromium's Private Network +Access requires for a public website calling the loopback helper. -Browser endpoints support CORS for: +Job ownership keeps each allowed website away from scans started by others. -- `/health` -- `/scan` -- `/scan/` -- `/scan//result` +## POST /link -Allowed origins come from `%LOCALAPPDATA%\ScanLink\config.json`: +Asks to link the requesting website, named by the browser's `Origin` header. + +Request: ```json { - "cors_origins": ["*"] + "sites": ["https://crm.example"] } ``` -Preflights that carry `Access-Control-Request-Private-Network: true` from an allowed origin are answered with `Access-Control-Allow-Private-Network: true`, as Chromium's Private Network Access requires for a public website calling the loopback helper. +`sites` lists the other websites the requesting site's administrator allows, at +most 19; the requesting site is always included. An unlinked website opens an +approval window in ScanLink naming it and its list, and the request waits up to +two minutes for the operator's answer. A website that is already linked replaces +its list without asking again. -When `cors_origins` is not `["*"]`, the request `Origin` must exactly match an entry in the list. Browser-endpoint requests from any other `Origin`, including preflights, receive `403 origin_not_allowed` before any work is done. +Success: -With the default `["*"]`, every website the operator opens can call `/health` and `/scan` and download the scans it starts itself. Job ownership keeps each website away from scans started by others. List the DjangoLux origins in `cors_origins` to restrict which websites can scan. +```json +{ + "linked": true, + "prompted": true, + "sites": ["https://archive.example", "https://crm.example"] +} +``` + +Errors: + +| Status | Code | Meaning | +| --- | --- | --- | +| `400` | `origin_required` | No well-formed `Origin` (local tools and `Origin: null` cannot link). | +| `400` | `invalid_payload`, `invalid_sites`, `invalid_site`, `too_many_sites` | The body is not `{"sites": [origins]}` with at most 19 website origins. | +| `403` | `link_declined` | The operator chose **Don't allow**; the website cannot ask again for 10 minutes. | +| `408` | `link_timeout` | Nobody answered the window within two minutes. | +| `409` | `link_pending` | Another website's approval window is open. | +| `409` | `too_many_links` | 50 websites are linked; unlink one first. | ## Automatic HTTPS setup status (0.7.5b1) diff --git a/docs/architecture.md b/docs/architecture.md index ad51550..e6869a9 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -136,7 +136,8 @@ Defaults are provided in `utils.load_config()`: "default_scanner": null, "show_scanner_ui": false, "paper_protection": false, - "cors_origins": ["*"], + "cors_origins": [], + "linked_sites": {}, "job_ttl_seconds": 900, "result_ttl_seconds": 300, "scan_timeout_seconds": 600, diff --git a/docs/developer-guide.md b/docs/developer-guide.md index c6fe537..c42a016 100644 --- a/docs/developer-guide.md +++ b/docs/developer-guide.md @@ -192,7 +192,7 @@ Downloading `/scan//result` consumes the stored PDF. A second download f ## Operational Notes - The API is bound to `127.0.0.1`, not a public network interface, and answers only requests whose `Host` is `localhost`, `127.0.0.1` or `[::1]`. -- CORS defaults to `["*"]` in `%LOCALAPPDATA%\ScanLink\config.json`: any website can start a scan and download the scans it started. List your application origins in `cors_origins` to restrict it; see [API Reference](api.md#cors). +- No website can scan until it is allowed: the operator approves a website once through [`POST /link`](api.md#post-link), or IT lists it in `cors_origins` in `%LOCALAPPDATA%\ScanLink\config.json`; see [Allowed websites](api.md#allowed-websites). The bundled client's `link(sites)` sends the request, and its `checkHealth()` reports `origin_not_allowed` for a website that is not allowed yet. - A scan job belongs to the `Origin` that started it; poll status and download the result from the same page origin. - The first scan may show a scanner selection dialog. - If the user selects "Set as default scanner", later scans skip scanner selection. diff --git a/gui/dialogs.py b/gui/dialogs.py index c4007e8..a7cb12e 100644 --- a/gui/dialogs.py +++ b/gui/dialogs.py @@ -124,3 +124,66 @@ def show_text_dialog(title, body, width=760, height=520): dlg.focus_force() dlg.grab_set() dlg.wait_window() + + +def confirm_site_link(origin, other_sites, timeout_seconds): + """Ask whether ``origin`` may use the scanner: True, False, or None if unanswered.""" + if not _root: + logging.error("GUI not initialized with root window") + return None + + answer = {"value": None} + dlg = tk.Toplevel() + dlg.title("Allow a website to use ScanLink?") + dlg.resizable(False, False) + + frame = tk.Frame(dlg, padx=16, pady=14) + frame.pack(fill=tk.BOTH, expand=True) + tk.Label(frame, text=origin, font=("TkDefaultFont", 11, "bold"), wraplength=440, justify=tk.LEFT).pack(anchor=tk.W) + tk.Label(frame, text="wants to use the scanner on this computer.", wraplength=440, justify=tk.LEFT).pack(anchor=tk.W) + if other_sites: + tk.Label( + frame, + text="Its administrator also allows these websites:", + wraplength=440, + justify=tk.LEFT, + ).pack(anchor=tk.W, pady=(10, 0)) + listing = tk.Listbox(frame, height=min(len(other_sites), 6), width=56) + for site in other_sites: + listing.insert(tk.END, site) + listing.pack(anchor=tk.W, fill=tk.X) + tk.Label( + frame, + text="Only allow a website you use for your work. You can unlink it later from the ScanLink tray menu.", + wraplength=440, + justify=tk.LEFT, + ).pack(anchor=tk.W, pady=(10, 0)) + + def finish(value): + answer["value"] = value + if dlg.winfo_exists(): + dlg.destroy() + + buttons = tk.Frame(frame) + buttons.pack(pady=(14, 0)) + tk.Button(buttons, text="Allow", command=lambda: finish(True), width=12).pack(side=tk.LEFT, padx=8) + deny = tk.Button(buttons, text="Don't allow", command=lambda: finish(False), width=12) + deny.pack(side=tk.LEFT, padx=8) + dlg.protocol("WM_DELETE_WINDOW", lambda: finish(False)) + dlg.bind("", lambda event: finish(False)) + dlg.after(int(timeout_seconds * 1000), lambda: finish(None)) + + dlg.update_idletasks() + width, height = dlg.winfo_reqwidth(), dlg.winfo_reqheight() + x = max((dlg.winfo_screenwidth() // 2) - (width // 2), 0) + y = max((dlg.winfo_screenheight() // 2) - (height // 2), 0) + dlg.geometry(f"+{x}+{y}") + dlg.deiconify() + dlg.wait_visibility() + dlg.attributes("-topmost", True) + dlg.lift() + dlg.focus_force() + deny.focus_set() + dlg.grab_set() + dlg.wait_window() + return answer["value"] diff --git a/main.py b/main.py index cd30170..d3a7fee 100644 --- a/main.py +++ b/main.py @@ -15,8 +15,9 @@ ) from scan_runtime import run_scan_job from server import run_server +from sites import LINK_PROMPT_SECONDS, SiteRegistry from tray import TrayApp -from utils import APP_VERSION, ensure_ssl_certificates, get_logger, setup_logging +from utils import APP_VERSION, ensure_ssl_certificates, get_logger, load_config, setup_logging from worker import ScanWorker, set_status_callback @@ -87,13 +88,24 @@ def show_setup_message(): set_status_callback(None) - tray = TrayApp(worker, shutdown_event, https_retry_event) + def confirm_link(origin, other_sites): + from gui.dialogs import confirm_site_link + + return worker.run_gui_task( + lambda: confirm_site_link(origin, other_sites, LINK_PROMPT_SECONDS), + timeout=LINK_PROMPT_SECONDS + 15, + ) + + config = load_config() + sites = SiteRegistry(config["cors_origins"], config["linked_sites"], confirm=confirm_link) + + tray = TrayApp(worker, shutdown_event, https_retry_event, sites=sites) worker.start() server_thread = threading.Thread( target=run_server, - args=(worker, shutdown_event, https_retry_event, offer_https_retry), + args=(worker, shutdown_event, https_retry_event, offer_https_retry, sites), daemon=True, name="LoopbackServerManager", ) diff --git a/server.py b/server.py index f354354..f4d5e97 100644 --- a/server.py +++ b/server.py @@ -19,7 +19,9 @@ get_ssl_context, ensure_ssl_certificates, load_config, + normalize_origin, ) +from sites import LinkError, SiteRegistry from worker import BusyError logger = get_logger() @@ -40,21 +42,26 @@ def is_loopback_host(host): return False -def create_app(worker, shutdown_event, transport_state): +def create_app(worker, shutdown_event, transport_state, sites=None): app = Flask(__name__) app.config["MAX_CONTENT_LENGTH"] = MAX_REQUEST_BYTES - config = load_config() - allowed_origins = config.get("cors_origins", ["*"]) + if sites is None: + config = load_config() + sites = SiteRegistry(config.get("cors_origins"), config.get("linked_sites")) def is_browser_endpoint(path): - return path == "/health" or path == "/scan" or path.startswith("/scan/") + return path in ("/health", "/scan", "/link") or path.startswith("/scan/") - def is_origin_allowed(origin): - return "*" in allowed_origins or origin in allowed_origins + def web_origin(): + """The request's Origin when it is a well-formed website origin.""" + origin = request.headers.get("Origin") + return origin if origin and normalize_origin(origin) == origin else None def apply_cors(response): - origin = request.headers.get("Origin") - if not origin or not is_origin_allowed(origin): + # Every website may read answers, so an unlinked one can see + # origin_not_allowed and offer to link; the work itself is gated. + origin = web_origin() + if origin is None: return response response.headers["Access-Control-Allow-Origin"] = origin @@ -120,9 +127,10 @@ def reject_foreign_host(): ) origin = request.headers.get("Origin") if is_browser_endpoint(request.path): - if origin is not None and not is_origin_allowed(origin): + gated = request.method != "OPTIONS" and request.path != "/link" + if gated and origin is not None and not sites.is_allowed(origin): return error_response( - 403, "origin_not_allowed", "This website is not allowed to use ScanLink." + 403, "origin_not_allowed", "This website is not linked to ScanLink." ) # Browsers send Origin or Sec-Fetch-Site; form posts need no CORS preflight. elif origin is not None or "Sec-Fetch-Site" in request.headers: @@ -152,21 +160,44 @@ def health(): if request.method == "OPTIONS": return empty_options_response() - return jsonify( - { - "status": "ok", - "version": APP_VERSION, - "arch": APP_ARCH, - "busy": worker.is_busy(), - "http_enabled": transport_state.get("http_enabled", False), - "https_enabled": transport_state.get("https_enabled", False), - "twain_available": worker.is_twain_available(), - "https_setup": transport_state.get( - "https_setup", - "ready" if transport_state.get("https_enabled") else "unavailable", - ), - } - ) + payload = { + "status": "ok", + "version": APP_VERSION, + "arch": APP_ARCH, + "busy": worker.is_busy(), + "http_enabled": transport_state.get("http_enabled", False), + "https_enabled": transport_state.get("https_enabled", False), + "twain_available": worker.is_twain_available(), + "https_setup": transport_state.get( + "https_setup", + "ready" if transport_state.get("https_enabled") else "unavailable", + ), + } + origin = web_origin() + if origin is not None: + link = sites.link_for(origin) + payload["link"] = {"linked": link is not None, "sites": link["sites"] if link else []} + return jsonify(payload) + + @app.route("/link", methods=["POST", "OPTIONS"]) + def link_site(): + if request.method == "OPTIONS": + return empty_options_response() + origin = web_origin() + if origin is None: + return error_response( + 400, "origin_required", "Only a website can link itself, and its origin must be sent." + ) + data = request.get_json(silent=True) if request.is_json else None + if not isinstance(data, dict): + return error_response( + 400, "invalid_payload", "Link requests must contain a JSON object with a sites list." + ) + try: + result = sites.link(origin, data.get("sites")) + except LinkError as exc: + return error_response(exc.status, exc.code, exc.message) + return jsonify(result) @app.route("/scan", methods=["POST", "OPTIONS"]) def start_scan(): @@ -377,14 +408,14 @@ def shutdown(self): self.httpd.shutdown() -def run_server(worker, shutdown_event, https_retry_event=None, on_https_error=None): +def run_server(worker, shutdown_event, https_retry_event=None, on_https_error=None, sites=None): retry = https_retry_event or threading.Event() transport_state = { "http_enabled": False, "https_enabled": False, "https_setup": "preparing", } - app = create_app(worker, shutdown_event, transport_state) + app = create_app(worker, shutdown_event, transport_state, sites) listeners = [] http_listener = LoopbackServer(app, HTTP_HOST, HTTP_PORT, label="HTTP") http_listener.start() diff --git a/sites.py b/sites.py new file mode 100644 index 0000000..b81b6d8 --- /dev/null +++ b/sites.py @@ -0,0 +1,153 @@ +"""Websites allowed to use ScanLink's browser API. + +A website may scan when it is listed in ``cors_origins`` (set by hand or by IT) +or linked. A DjangoLux site links itself with ``POST /link``, naming the sites +its administrator allows; the operator approves the link once, in ScanLink's +own window, which names the requesting site as the browser reported it. A +linked site may later change its list without asking again, and the operator +unlinks it from the tray menu. +""" + +import threading +import time +from datetime import datetime, timezone + +from utils import get_logger, load_config, normalize_origin, save_config + +logger = get_logger() + +MAX_SITES_PER_LINK = 20 +MAX_LINKS = 50 +# A declined website cannot open the approval window again for this long. +DECLINE_COOLDOWN_SECONDS = 600 +LINK_PROMPT_SECONDS = 120 + + +class LinkError(Exception): + def __init__(self, status, code, message): + super().__init__(message) + self.status = status + self.code = code + self.message = message + + +def save_links(links): + config = load_config() + config["linked_sites"] = links + save_config(config) + + +class SiteRegistry: + def __init__(self, listed=(), links=None, *, confirm=None, persist=save_links, clock=time.monotonic): + """``confirm(origin, other_sites)`` returns True, False, or None when unanswered.""" + self._listed = frozenset(origin for origin in map(normalize_origin, listed or ()) if origin) + self._links = {} + for origin, link in (links or {}).items(): + origin = normalize_origin(origin) + if origin and isinstance(link, dict): + sites = [site for site in map(normalize_origin, link.get("sites") or ()) if site] + self._links[origin] = { + "sites": list(dict.fromkeys([origin, *sites])), + "linked_at": str(link.get("linked_at") or ""), + } + self._confirm = confirm + self._persist = persist + self._clock = clock + self._lock = threading.Lock() + self._prompting = threading.Lock() + self._declined = {} + + def is_allowed(self, origin): + with self._lock: + return ( + origin in self._listed + or origin in self._links + or any(origin in link["sites"] for link in self._links.values()) + ) + + def link_for(self, origin): + with self._lock: + link = self._links.get(origin) + return {"sites": list(link["sites"]), "linked_at": link["linked_at"]} if link else None + + def links(self): + with self._lock: + return {origin: list(link["sites"]) for origin, link in self._links.items()} + + def link(self, origin, sites): + sites = self._clean_sites(origin, sites) + with self._lock: + link = self._links.get(origin) + if link is not None: + if link["sites"] != sites: + self._links[origin] = {**link, "sites": sites} + self._save() + logger.info("Linked website %r changed its allowed sites to %r", origin, sites) + return {"linked": True, "prompted": False, "sites": sites} + if len(self._links) >= MAX_LINKS: + raise LinkError(409, "too_many_links", "ScanLink is linked to too many websites. Unlink one from the tray menu first.") + declined_at = self._declined.get(origin) + if declined_at is not None and self._clock() - declined_at < DECLINE_COOLDOWN_SECONDS: + raise LinkError(403, "link_declined", "Linking this website was declined on this computer.") + if not self._prompting.acquire(blocking=False): + raise LinkError(409, "link_pending", "Another website is waiting for approval in ScanLink.") + try: + answer = self._ask(origin, sites[1:]) + finally: + self._prompting.release() + if answer is None: + raise LinkError(408, "link_timeout", "Nobody answered ScanLink's approval window.") + with self._lock: + if not answer: + self._declined[origin] = self._clock() + logger.info("The operator declined linking %r", origin) + raise LinkError(403, "link_declined", "Linking this website was declined on this computer.") + self._declined.pop(origin, None) + self._links[origin] = { + "sites": sites, + "linked_at": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), + } + self._save() + logger.info("The operator linked %r; allowed sites %r", origin, sites) + return {"linked": True, "prompted": True, "sites": sites} + + def unlink(self, origin): + with self._lock: + removed = self._links.pop(origin, None) is not None + if removed: + self._save() + if removed: + logger.info("The operator unlinked %r", origin) + return removed + + def _ask(self, origin, other_sites): + if self._confirm is None: + return None + try: + return self._confirm(origin, other_sites) + except Exception: + logger.exception("Could not show the link approval window") + return None + + def _save(self): + try: + self._persist({origin: dict(link) for origin, link in self._links.items()}) + except Exception: + logger.exception("Could not save the linked websites") + + @staticmethod + def _clean_sites(origin, sites): + if sites is None: + sites = [] + if not isinstance(sites, list): + raise LinkError(400, "invalid_sites", "sites must be a list of website origins.") + cleaned = [origin] + for value in sites: + site = normalize_origin(value) + if site is None: + raise LinkError(400, "invalid_site", f"{str(value)[:80]!r} is not a website origin such as https://example.org.") + if site not in cleaned: + cleaned.append(site) + if len(cleaned) > MAX_SITES_PER_LINK: + raise LinkError(400, "too_many_sites", f"A website can allow at most {MAX_SITES_PER_LINK} sites.") + return cleaned diff --git a/static/scanlink.js b/static/scanlink.js index 425e5e8..3201101 100644 --- a/static/scanlink.js +++ b/static/scanlink.js @@ -49,6 +49,13 @@ class ScanLink { this.connectionError = null; return health; } catch (error) { + if (error instanceof ScanLinkError && error.code === "origin_not_allowed") { + // ScanLink answered, but this website is not linked: link() can fix that. + this._setPreferredUrl(baseUrl); + this.onConnectionChange(false); + this.connectionError = error; + return null; + } continue; } } @@ -66,6 +73,11 @@ class ScanLink { method: "GET", mode: "cors", signal: controller.signal, }); // Read the body before clearing the timeout, including stalled responses. + if (response.status === 403) { + const refusal = await this._responseToError(response, "ScanLink refused this website."); + if (refusal.code === "origin_not_allowed") throw refusal; + return null; + } return response.ok ? await response.json() : null; } finally { clearTimeout(timer); @@ -225,6 +237,28 @@ class ScanLink { window.location.href = url; } + async link(sites = []) { + // Resolves once the operator approves in ScanLink's own window (or at once + // for a website that is already linked); rejects with link_declined, + // link_pending or link_timeout otherwise. + if (!this.preferredUrl) await this.checkHealth(true); + let response; + try { + response = await this._fetchResponse("/link", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ sites }), + mode: "cors", + }); + } catch (error) { + throw this._connectionFailure(error); + } + if (!response.ok) { + throw await this._responseToError(response, "ScanLink did not link this website."); + } + return response.json(); + } + _uncertainRequest(cause) { return new ScanLinkError("The scan request lost its connection. Check ScanLink before starting another scan.", "scan_request_uncertain", { cause }); } diff --git a/tests/test_browser_security.py b/tests/test_browser_security.py index 999e2e4..e94e9b7 100644 --- a/tests/test_browser_security.py +++ b/tests/test_browser_security.py @@ -17,7 +17,7 @@ @unittest.skipIf(server is None, "Flask is not installed in this environment") class BrowserSecurityTests(unittest.TestCase): - cors_origins = ["*"] + cors_origins = ["https://archive.example"] def setUp(self): self.worker = FakeWorker() @@ -171,7 +171,7 @@ def test_local_tools_keep_local_control_endpoints(self): @unittest.skipIf(server is None, "Flask is not installed in this environment") class JobOwnershipTests(unittest.TestCase): - cors_origins = ["*"] + cors_origins = ["https://archive.example", "https://crm.example"] def setUp(self): config = patch( @@ -236,15 +236,14 @@ def test_jobs_started_without_an_origin_stay_with_local_tools(self): class AllowListTests(JobOwnershipTests): - cors_origins = ["https://archive.example", "https://crm.example"] - def test_unlisted_origin_is_refused_before_any_work(self): preflight = self.client.options( "/scan", - headers={**EVIL, "Access-Control-Request-Method": "POST"}, + headers={**EVIL, "Access-Control-Request-Method": "POST", "Access-Control-Request-Private-Network": "true"}, ) + self.assertEqual(preflight.status_code, 204) + self.assertEqual(preflight.headers["Access-Control-Allow-Private-Network"], "true") for response in ( - preflight, self.client.get("/health", headers=EVIL), self.client.post("/scan", json={}, headers=EVIL), self.client.get("/scan/anything", headers=EVIL), @@ -253,7 +252,8 @@ def test_unlisted_origin_is_refused_before_any_work(self): self.assertEqual( response.get_json()["error"]["code"], "origin_not_allowed" ) - self.assertNotIn("Access-Control-Allow-Origin", response.headers) + # Readable, so the page can offer to link instead of seeing a network error. + self.assertEqual(response.headers["Access-Control-Allow-Origin"], EVIL["Origin"]) self.assertEqual(self.worker.jobs, {}) accepted = self.client.post("/scan", json={}, headers=LEGIT) @@ -262,6 +262,13 @@ def test_unlisted_origin_is_refused_before_any_work(self): accepted.headers["Access-Control-Allow-Origin"], LEGIT["Origin"] ) + def test_the_wildcard_no_longer_allows_every_website(self): + with patch("server.load_config", return_value={"cors_origins": ["*"]}): + app = server.create_app(self.worker, threading.Event(), {"http_enabled": True}) + refused = app.test_client().post("/scan", json={}, headers=LEGIT) + self.assertEqual(refused.status_code, 403) + self.assertEqual(refused.get_json()["error"]["code"], "origin_not_allowed") + if __name__ == "__main__": unittest.main() diff --git a/tests/test_server.py b/tests/test_server.py index 42c36af..78f38a5 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -73,7 +73,7 @@ def setUp(self): self.transport_state = {"http_enabled": True, "https_enabled": False} self.shutdown_event = threading.Event() self.config_patch = patch( - "server.load_config", return_value={"cors_origins": ["*"]} + "server.load_config", return_value={"cors_origins": ["http://localhost:82"]} ) self.config_patch.start() self.app = server.create_app( diff --git a/tests/test_site_links.py b/tests/test_site_links.py new file mode 100644 index 0000000..f32ee22 --- /dev/null +++ b/tests/test_site_links.py @@ -0,0 +1,211 @@ +import threading +import unittest +from unittest.mock import patch + +from tests.test_server import FakeWorker +from utils import _normalize_config, normalize_origin + +try: + import server + from sites import DECLINE_COOLDOWN_SECONDS, MAX_SITES_PER_LINK, SiteRegistry +except ImportError: + server = None + +ARCHIVE = {"Origin": "https://archive.example"} +CRM = {"Origin": "https://crm.example"} +EVIL = {"Origin": "https://evil.example"} + + +class OriginTests(unittest.TestCase): + def test_only_plain_website_origins_are_accepted(self): + for value, expected in ( + ("https://archive.example", "https://archive.example"), + ("https://Archive.Example:443/", "https://archive.example"), + ("http://intranet:8080", "http://intranet:8080"), + ("http://[::1]:8000", "http://[::1]:8000"), + ): + with self.subTest(value=value): + self.assertEqual(normalize_origin(value), expected) + for value in ("*", "null", "", None, 5, "file:///c:/x", "https://*.example", "https://a.example/path", + "https://user:pw@a.example", "https://a.example?x=1", "javascript:alert(1)", "https://"): + with self.subTest(value=value): + self.assertIsNone(normalize_origin(value)) + + def test_saved_wildcard_and_bad_links_are_dropped_on_load(self): + config = _normalize_config({ + "cors_origins": ["*", "https://archive.example", "https://archive.example/"], + "linked_sites": { + "https://crm.example": {"sites": ["https://sales.example", "*"], "linked_at": "2026-11-14T00:00:00Z"}, + "*": {"sites": []}, + "https://bad.example": "not a link", + }, + }) + self.assertEqual(config["cors_origins"], ["https://archive.example"]) + self.assertEqual(config["linked_sites"], { + "https://crm.example": {"sites": ["https://crm.example", "https://sales.example"], + "linked_at": "2026-11-14T00:00:00Z"}, + }) + + +@unittest.skipIf(server is None, "Flask is not installed in this environment") +class LinkTests(unittest.TestCase): + def setUp(self): + self.answers = [] + self.asked = [] + self.saved = [] + self.now = [1000.0] + self.sites = SiteRegistry( + ["https://listed.example"], + confirm=self.confirm, + persist=self.saved.append, + clock=lambda: self.now[0], + ) + self.worker = FakeWorker() + self.client = server.create_app( + self.worker, threading.Event(), {"http_enabled": True}, self.sites + ).test_client() + + def confirm(self, origin, other_sites): + self.asked.append((origin, other_sites)) + return self.answers.pop(0) if self.answers else None + + def link(self, headers, sites=()): + return self.client.post("/link", json={"sites": list(sites)}, headers=headers) + + def test_an_unlinked_site_can_read_why_it_is_refused(self): + health = self.client.get("/health", headers=EVIL) + self.assertEqual(health.status_code, 403) + self.assertEqual(health.get_json()["error"]["code"], "origin_not_allowed") + self.assertEqual(health.headers["Access-Control-Allow-Origin"], EVIL["Origin"]) + preflight = self.client.options("/link", headers={**EVIL, "Access-Control-Request-Method": "POST"}) + self.assertEqual(preflight.status_code, 204) + self.assertEqual(preflight.headers["Access-Control-Allow-Origin"], EVIL["Origin"]) + + def test_an_approved_link_allows_the_site_and_the_sites_its_admin_lists(self): + self.answers.append(True) + response = self.link(ARCHIVE, ["https://crm.example", "https://archive.example", "https://CRM.example/"]) + self.assertEqual(response.status_code, 200) + self.assertEqual(response.get_json(), { + "linked": True, "prompted": True, "sites": ["https://archive.example", "https://crm.example"], + }) + self.assertEqual(self.asked, [("https://archive.example", ["https://crm.example"])]) + self.assertEqual(list(self.saved[-1]), ["https://archive.example"]) + + health = self.client.get("/health", headers=ARCHIVE).get_json() + self.assertEqual(health["link"], {"linked": True, "sites": ["https://archive.example", "https://crm.example"]}) + self.assertEqual(self.client.get("/health", headers=CRM).get_json()["link"], {"linked": False, "sites": []}) + self.assertEqual(self.client.post("/scan", json={}, headers=CRM).status_code, 202) + self.assertEqual(self.client.post("/scan", json={}, headers=EVIL).status_code, 403) + + def test_a_linked_site_changes_its_list_without_asking_again(self): + self.answers.append(True) + self.link(ARCHIVE, ["https://crm.example"]) + response = self.link(ARCHIVE, ["https://sales.example"]) + self.assertEqual(response.get_json()["prompted"], False) + self.assertEqual(len(self.asked), 1) + self.assertEqual(self.client.get("/health", headers=CRM).status_code, 403) + self.assertEqual(self.client.get("/health", headers={"Origin": "https://sales.example"}).status_code, 200) + + def test_a_listed_site_cannot_change_another_sites_link(self): + self.answers.append(True) + self.link(ARCHIVE, ["https://crm.example"]) + self.answers.append(False) + response = self.link(CRM, ["https://evil.example"]) + self.assertEqual(response.status_code, 403) + self.assertEqual(len(self.asked), 2) + self.assertEqual(self.client.get("/health", headers=EVIL).status_code, 403) + + def test_a_declined_site_cannot_ask_again_until_the_cooldown_ends(self): + self.answers.append(False) + first = self.link(EVIL) + self.assertEqual((first.status_code, first.get_json()["error"]["code"]), (403, "link_declined")) + self.assertEqual(first.headers["Access-Control-Allow-Origin"], EVIL["Origin"]) + again = self.link(EVIL) + self.assertEqual(again.get_json()["error"]["code"], "link_declined") + self.assertEqual(len(self.asked), 1) + self.now[0] += DECLINE_COOLDOWN_SECONDS + 1 + self.answers.append(True) + self.assertEqual(self.link(EVIL).status_code, 200) + self.assertEqual(len(self.asked), 2) + + def test_an_unanswered_window_links_nothing(self): + response = self.link(EVIL) + self.assertEqual((response.status_code, response.get_json()["error"]["code"]), (408, "link_timeout")) + self.assertEqual(self.client.get("/health", headers=EVIL).status_code, 403) + self.assertEqual(self.saved, []) + + def test_one_approval_window_at_a_time(self): + opened, release = threading.Event(), threading.Event() + + def slow_confirm(origin, other_sites): + opened.set() + release.wait(5) + return True + + self.sites._confirm = slow_confirm + results = {} + thread = threading.Thread(target=lambda: results.setdefault("first", self.link(ARCHIVE))) + thread.start() + self.assertTrue(opened.wait(5)) + try: + second = self.link(EVIL) + finally: + release.set() + thread.join(5) + self.assertEqual((second.status_code, second.get_json()["error"]["code"]), (409, "link_pending")) + self.assertEqual(results["first"].status_code, 200) + self.assertEqual(self.client.get("/health", headers=EVIL).status_code, 403) + + def test_bad_link_requests_are_refused_without_a_window(self): + too_many = [f"https://s{n}.example" for n in range(MAX_SITES_PER_LINK)] + for headers, body, code in ( + ({}, {"sites": []}, "origin_required"), + ({"Origin": "null"}, {"sites": []}, "origin_required"), + (ARCHIVE, ["https://a.example"], "invalid_payload"), + (ARCHIVE, {"sites": "https://a.example"}, "invalid_sites"), + (ARCHIVE, {"sites": ["https://*.example"]}, "invalid_site"), + (ARCHIVE, {"sites": ["*"]}, "invalid_site"), + (ARCHIVE, {"sites": too_many}, "too_many_sites"), + ): + with self.subTest(code=code, headers=headers): + response = self.client.post("/link", json=body, headers=headers) + self.assertEqual(response.status_code, 400) + self.assertEqual(response.get_json()["error"]["code"], code) + self.assertEqual(self.asked, []) + + def test_link_keeps_the_loopback_host_check(self): + response = self.client.post("/link", json={"sites": []}, headers={**EVIL, "Host": "evil.example:5000"}) + self.assertEqual(response.get_json()["error"]["code"], "invalid_host") + self.assertEqual(self.asked, []) + + def test_unlinking_removes_the_site_and_its_list(self): + self.answers.append(True) + self.link(ARCHIVE, ["https://crm.example"]) + self.assertTrue(self.sites.unlink("https://archive.example")) + self.assertEqual(self.saved[-1], {}) + for headers in (ARCHIVE, CRM): + self.assertEqual(self.client.get("/health", headers=headers).status_code, 403) + self.assertEqual(self.client.get("/health", headers={"Origin": "https://listed.example"}).status_code, 200) + + def test_saved_links_are_restored(self): + self.answers.append(True) + self.link(ARCHIVE, ["https://crm.example"]) + restored = SiteRegistry([], self.saved[-1]) + self.assertTrue(restored.is_allowed("https://crm.example")) + self.assertEqual(restored.link_for("https://archive.example")["sites"], + ["https://archive.example", "https://crm.example"]) + + def test_config_wiring_links_from_the_saved_file(self): + with patch("server.load_config", return_value=_normalize_config({ + "cors_origins": ["*"], + "linked_sites": {"https://archive.example": {"sites": ["https://crm.example"]}}, + })): + client = server.create_app(FakeWorker(), threading.Event(), {"http_enabled": True}).test_client() + self.assertEqual(client.post("/scan", json={}, headers=CRM).status_code, 202) + self.assertEqual(client.post("/scan", json={}, headers=EVIL).status_code, 403) + self.assertEqual(client.post("/link", json={"sites": []}, headers=EVIL).get_json()["error"]["code"], + "link_timeout") + + +if __name__ == "__main__": + unittest.main() diff --git a/tracker.md b/tracker.md index 15f7ab1..7a9235e 100644 --- a/tracker.md +++ b/tracker.md @@ -22,13 +22,13 @@ - Windows x64/x86 unit/build/install gates passed, including real certificate consent, DPAPI/trust, 120 verified HTTPS requests per architecture and restart identity reuse. Real Windows browser/scanner and enterprise-policy acceptance remain manual. - Target PaperStream fi-6230Z may expose only 32-bit TWAIN; live driver compliance/output quality remain unverified. Back-only and blank-page discard remain unsupported. - Organization/browser policies may refuse user-installed trust. A denied setup is reported as failure and retried with the same identity, without repeated automatic dialogs. -- Default `cors_origins: ["*"]` (persisted in existing config.json files) lets any website the operator opens start a scan and download it; silent once a default scanner is saved. Ownership now blocks cross-site theft; closing the rest (first-use origin approval or provisioned DjangoLux origins) needs an owner decision. +- Owner decision 2026-11-14: DjangoLux supplies its sites (admin's choice). Done on `0.8/stress_fixes`: no wildcard, `POST /link` with a one-time approval window naming the browser's origin, tray **Linked Websites** to unlink; paired DjangoLux `1.16/scanlink_sites` sends the admin's list. Every upgrading operator approves each site once. The window is English-only, like the rest of ScanLink's UI. - Contract gaps on the DjangoLux side: `scan_button.js` gives up after 5 min while ScanLink's deadline is 600+15 s (no cancel endpoint; retry reports busy, PDF orphaned 300 s); `no_pages_scanned`, `scan_idle_timeout`, `acquire_failed`, `scan_worker_crashed`, `origin_not_allowed`, `payload_too_large` show ScanLink's English message. - Callbacks are never delivered (since 36249b6, 2026-04-28): `_process_job` passes the serialized job, which omits `callback_url`, to `_send_callback`. Docs promise delivery; enabling it changes production behavior and needs an owner decision. Any re-enable must restrict callback hosts: any page or `scanlink://` link can set `callback_url`. ### Active & Pending Tasks - [x] 0.8.0b2 merged to main via PR3 (063269b, 2026-10-30; CI 3/3 PASS): 15s parent scan-deadline grace, callback parse guard, per-scan `/health` in `scanlink.js`. Untagged; tagging/publishing needs owner OK. -- [ ] Review/merge `0.8/stress_fixes` (10 fix commits, 63 tests); then decide the `["*"]` default and the DjangoLux timeout/error-code mapping. +- [ ] Review/merge `0.8/stress_fixes` (PR #5: 10 fix commits + site linking, 78 tests) with DjangoLux #71 and `1.16/scanlink_sites`; then ScanLink 0.8.0b3 (owner OK to tag). - [ ] Mirror the per-scan health check in DjangoLux `scan_button.js` if it shares the stale-transport logic. - [x] 2026-10-30: retired `0.7/automatic_https`, `0.8/stress_fixes`, `0.8/stress_followups` (checkouts removed, branches deleted locally/GitHub; leftovers in `.xclude/retired-worktrees/2026-10-30/`). Only `main` remains. - [x] Paired deeper stress and real-worker regressions pass; candidate0.8.0b1 prepared locally. Owner authorized next beta; PR2 merged after x86/x64 native CI PASS, release gates PASS, both installers published. diff --git a/tray.py b/tray.py index df1b31d..f7a0f9d 100644 --- a/tray.py +++ b/tray.py @@ -96,8 +96,9 @@ def format_color_mode(value): class TrayApp: - def __init__(self, worker, shutdown_event, https_retry_event=None): + def __init__(self, worker, shutdown_event, https_retry_event=None, sites=None): self.worker = worker + self.sites = sites self.shutdown_event = shutdown_event self.icon = None self.https_retry_event = https_retry_event or threading.Event() @@ -246,6 +247,25 @@ def on_startup_toggle(icon, item): if self.icon: self.icon.update_menu() + def unlink_site(origin): + def handler(icon, item): + if self.sites: + self.sites.unlink(origin) + if self.icon: + self.icon.update_menu() + + return handler + + def linked_site_items(): + links = self.sites.links() if self.sites else {} + if not links: + yield MenuItem("No linked websites", None, enabled=False) + return + for origin, allowed in sorted(links.items()): + others = len(allowed) - 1 + label = origin if not others else f"{origin} (+{others} site{'s' if others != 1 else ''})" + yield MenuItem(label, Menu(MenuItem("Unlink", unlink_site(origin)))) + resolution_menu = Menu( MenuItem("160 DPI", set_resolution(160), checked=resolution_checked(160), radio=True, enabled=resolution_enabled), MenuItem("200 DPI", set_resolution(200), checked=resolution_checked(200), radio=True, enabled=resolution_enabled), @@ -317,6 +337,7 @@ def on_startup_toggle(icon, item): ), MenuItem("Clear Default Scanner", clear_default_scanner, enabled=lambda item: not self.worker.is_busy()), MenuItem("Diagnostics", diagnostics_menu), + MenuItem("Linked Websites", Menu(linked_site_items)), Menu.SEPARATOR, MenuItem("Run on Startup", on_startup_toggle, checked=lambda item: is_startup_enabled()), MenuItem("Quit", on_quit), diff --git a/utils.py b/utils.py index 6c20f73..4203397 100644 --- a/utils.py +++ b/utils.py @@ -7,6 +7,7 @@ import io import tempfile from logging.handlers import RotatingFileHandler +from urllib.parse import urlsplit try: from PIL import Image as PilImage @@ -136,7 +137,53 @@ def _apply_scan_profile_migration(config): config["color_mode"] = DEFAULT_COLOR_MODE config["paper_protection"] = False +def normalize_origin(value): + """``scheme://host[:port]`` for an http(s) website origin, as browsers send it; else None. + + Wildcards, paths, credentials and the opaque ``null`` origin are refused. + """ + if not isinstance(value, str) or not value or len(value) > 255: + return None + try: + parts = urlsplit(value.strip()) + port = parts.port + except ValueError: + return None + if parts.scheme not in ("http", "https") or not parts.hostname: + return None + if parts.username or parts.password or parts.query or parts.fragment or parts.path not in ("", "/"): + return None + host = parts.hostname.lower() + if "*" in host or any(ch.isspace() for ch in host): + return None + if ":" in host: + host = f"[{host}]" + default_port = 443 if parts.scheme == "https" else 80 + return f"{parts.scheme}://{host}" + (f":{port}" if port and port != default_port else "") + +def _origin_list(values): + origins = [] + for value in values if isinstance(values, list) else []: + origin = normalize_origin(value) + if origin and origin not in origins: + origins.append(origin) + return origins + +def _linked_sites(value): + links = {} + for origin, link in (value.items() if isinstance(value, dict) else ()): + origin = normalize_origin(origin) + if not origin or not isinstance(link, dict): + continue + sites = _origin_list(link.get("sites")) + if origin not in sites: + sites.insert(0, origin) + links[origin] = {"sites": sites, "linked_at": str(link.get("linked_at") or "")} + return links + def _normalize_config(config): + config["cors_origins"] = _origin_list(config.get("cors_origins")) + config["linked_sites"] = _linked_sites(config.get("linked_sites")) config["scan_profile_version"] = int(config.get("scan_profile_version") or SCAN_PROFILE_VERSION) config["scan_source"] = _coerce_choice(config.get("scan_source"), SCAN_SOURCE_OPTIONS, DEFAULT_SCAN_SOURCE) config["scan_side"] = _coerce_choice(config.get("scan_side"), SCAN_SIDE_OPTIONS, DEFAULT_SCAN_SIDE) @@ -160,7 +207,8 @@ def load_config(): "default_scanner": None, "show_scanner_ui": False, "paper_protection": False, - "cors_origins": ["*"], + "cors_origins": [], + "linked_sites": {}, "job_ttl_seconds": DEFAULT_JOB_TTL_SECONDS, "result_ttl_seconds": DEFAULT_RESULT_TTL_SECONDS, "scan_timeout_seconds": DEFAULT_SCAN_TIMEOUT_SECONDS,