Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,22 @@

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/<job_id>` 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 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**: 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.
- **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

- **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.
Expand Down
1 change: 1 addition & 0 deletions build_exe.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
93 changes: 82 additions & 11 deletions docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -24,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

Expand All @@ -39,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.
Expand Down Expand Up @@ -88,6 +98,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:
Expand All @@ -102,10 +113,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/<job_id>

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
Expand Down Expand Up @@ -172,6 +187,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:
Expand All @@ -193,24 +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/<job_id>`
- `/scan/<job_id>/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"]
}
```

When `cors_origins` is not `["*"]`, the request `Origin` must exactly match an entry in the list.
`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.

Success:

```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)

Expand Down
25 changes: 22 additions & 3 deletions docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,17 @@ 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
300 DPI color). Long ADF batches therefore fit in a 32-bit (x86) build.

## Thread Model

Main process:
Expand Down Expand Up @@ -125,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,
Expand Down Expand Up @@ -158,6 +170,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)
Expand Down Expand Up @@ -200,8 +219,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.

Expand Down
5 changes: 3 additions & 2 deletions docs/developer-guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -191,8 +191,9 @@ Downloading `/scan/<job_id>/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]`.
- 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.
- Tray settings control source, side, color mode, resolution, scanner UI visibility, paper protection, startup, and diagnostics.
Expand Down
63 changes: 63 additions & 0 deletions gui/dialogs.py
Original file line number Diff line number Diff line change
Expand Up @@ -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("<Escape>", 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"]
18 changes: 15 additions & 3 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down Expand Up @@ -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",
)
Expand Down
Loading
Loading