Repository Public License
1# DownloadEngine23`Packages/NavigatorKit/Sources/DownloadEngine`. Imports `NavigatorCore`, `Persistence`, `Diagnostics`,4`Foundation`, `UniformTypeIdentifiers`, `CryptoKit` (and `CoreServices` on macOS, for the quarantine keys only).5No WebKit: page downloads are performed by WebKit (`WKDownload`, in WebRuntime), which calls this module through6the `DownloadSink` protocol of NavigatorCore.78| File | What it is |9|---|---|10| `DownloadFilename.swift` | `Content-Disposition` parsing, file-name sanitising, MIME ↔ extension, unique destinations (pure) |11| `DownloadRisk.swift` | Risk classification (pure) |12| `DownloadProgress.swift` | Speed / remaining-time meter and throttle (pure) |13| `DownloadManager.swift` | The download list (actor), `DownloadSink` implementation |14| `ResourceDownloader.swift` | `URLSession` downloader with Range resume, for files the browser itself fetches |1516## How a page download flows1718```19WebKit WebRuntime DownloadManager (actor)20WKDownload created ──▶ DownloadCoordinator.adopt ──▶ downloadWillBegin(candidate, control)21decideDestination ──▶ ──▶ destination(for:response:) → .save(url) | .cancel22progress / finish ──▶ ──▶ download(_:didEmit:)23 pause / cancel ──▶ control.cancel() (resume data comes back)24resume / restart ◀── app glue ◀── DownloadTransferStarter (implemented by the app)25```2627The manager never talks to WebKit. To resume or restart it calls a `DownloadTransferStarter` that the app28implements on top of `WebEngine.resumeDownload(resumeData:id:destination:)` / `startDownload`; the web layer29then reports back through the sink **with the same `DownloadID`**.3031## Destination3233- Default: the user's Downloads folder (macOS; the app sandbox has the `downloads.read-write` entitlement) or34 `Documents/Downloads` in the app container (iOS). A directory chosen by the user is stored as a bookmark35 (`downloads.directory_bookmark`, security-scoped on macOS) — `setDownloadsDirectory(_:)`.36- "Ask where to save each file" (`downloads.ask_every_time`): the manager calls37 `DownloadPrompter.chooseDestination(for:)` with the sanitised name, the risk and a suggested URL; `nil`38 cancels the download and leaves no trace of it. If the user chose to replace an existing file, the manager39 removes it first (WebKit requires a free path). Without a prompter the default directory is used.40- A download the page started without a user gesture (`DownloadCandidate.isUserInitiated == false`) is subject41 to the `downloads` permission of the page's origin when a `PermissionProvider` is injected: `deny` cancels,42 `ask` calls `DownloadPrompter.allowAutomaticDownload`. Without a prompter it proceeds (WebKit only reports43 `isUserInitiated` from macOS 15.2 / iOS 18.2; on older systems everything would otherwise be refused).44- The destination is always a **direct child** of the chosen directory and **never an existing file**: names45 already on disk and names reserved by transfers in progress get ` (2)`, ` (3)`… before the extension46 (`archive (2).tar.gz`).4748## File names4950`DownloadFilename.derive(contentDisposition:suggested:url:mimeType:)`. Every input is untrusted.5152Sources, first usable one wins: `Content-Disposition` (`filename*` decoded per RFC 5987 — UTF-8 and53ISO-8859-1 — before `filename`, RFC 6266), the name suggested by the web layer, the last path component of the54URL (percent-decoded), `"download"`. The `DownloadSink` contract only carries WebKit's suggested name, so page55downloads use the last three; the header parser serves `ResourceDownloader`.5657`sanitize` turns any text into one path component:58591. Unicode NFC.602. Control characters (NUL included), format characters (bidirectional overrides such as U+202E, zero-width61 characters, BOM, soft hyphen, tag characters) and line / paragraph separators are removed.623. Only the last path component is kept; `/` and `\` are both separators (`../../etc/passwd` → `passwd`).634. `: * ? " < > |` → `_`; every white-space character → one space; runs collapse.645. Leading dots and spaces are removed (no hidden file, no `..`); trailing dots and spaces too; no space65 between the stem and the extension (`invoice.pdf .exe` → `invoice.pdf.exe`).666. Windows reserved device names (`CON`, `NUL`, `COM1`…) get a leading `_`.677. At most 200 UTF-8 bytes, cut on whole characters, keeping the extension (compound ones like `.tar.gz`68 included). An "extension" longer than 20 bytes is not treated as one.6970An empty result means "no name" and the next source is tried.7172Extension and MIME type (`UTType`): a missing extension gets the type's preferred one; an extension the system73does not know gets the type's extension appended (`report.final` + PDF → `report.final.pdf`); a name taken from74the URL whose extension is a server-side one (`download.php`, `view.aspx`, `page.html`) is corrected75(`download.pdf`). Otherwise the name stays as stated — the extension is what the system will use to open the76file, so it is never silently changed. Generic types (`application/octet-stream`…) say nothing.7778## Risk7980`DownloadRiskClassifier.classify(filename:mimeType:)` → `DownloadRisk(level:reasons:)`.8182| Level | Reasons | Examples |83|---|---|---|84| `dangerous` — **opening requires an explicit confirmation** | `executable`, `installer`, `script`, `configuration`, `shortcut`, `disguisedExtension` | `.app .exe .jar .dylib`, `.pkg .dmg .msi .apk`, `.sh .command .py .js .ps1 .scpt`, `.mobileconfig .reg .terminal`, `.webloc .lnk .url`, `invoice.pdf.exe` |85| `caution` — flagged, opens normally | `archive`, `macroDocument`, `activeContent`, `typeMismatch` | `.zip .tar.gz`, `.docm .xlsm .doc`, `.html .svg`, `photo.jpg` served as a program type |86| `safe` | — | documents, images, audio, video, text |8788The extension decides (it is what the system opens the file by); explicit lists come first, then `UTType`89conformance (`executable`, `script`, `application`, `diskImage`, alias / internet location, `archive`). A file90without an extension is judged by its MIME type. It is a list, not content inspection: it is not complete.9192`DownloadManager.openDecision(_:confirmed:)` returns `.needsConfirmation(url, risk)` for a dangerous file until93the UI calls again with `confirmed: true` after showing the reasons. The decision is taken on the name of the94file on disk at that moment. The module never opens anything itself (that needs AppKit / UIKit): it returns the95URL (`.open(url)`, `revealURL(_:)`).9697## Progress9899`DownloadSpeedMeter` averages over a sliding 5 s window of `(time, bytes)` samples; no speed before 0.5 s of100samples; 0 when nothing arrived for a whole window (stalled); remaining time = remaining bytes / speed, `nil`101without a total or a speed. A byte count or a clock going backwards starts a new measurement. Time is always102injected.103104Updates reach observers (`updates()`, an `AsyncStream<DownloadUpdate>` per caller) at most every 250 ms and105storage (`database.downloads.updateProgress`) at most every 2 s; state changes are never throttled.106107## States108109```110(willBegin) pending ──destination──▶ running ──finished──▶ finished111 │ ├─ failed(message, resumeData?) ─▶ failed ──resume / restart──▶ pending ─▶ running112 │ └─ pause() ─▶ paused (resume data kept, partial file kept) ──resume──▶ pending ─▶ running113 └─ cancel() / cancelled by the web layer ─▶ cancelled (partial file removed)114```115116- **Pause** is "stop with resume data" (WebKit has no pause). If the server does not allow resuming, the117 result is `.stoppedNotResumable` and the download ends cancelled: it can only be restarted.118- **Resume** needs resume data; **restart** starts over and discards what was received. Both are explicit.119- **At launch**, `recoverInterrupted()` marks downloads that were pending or running when the app stopped as120 failed (`errorDescription == DownloadManager.interruptedErrorKey`, `wasInterrupted`). **Nothing is restarted121 automatically.** Paused downloads stay paused and resumable across launches.122- `remove(_:deletingFile:)` removes from the list, with or without deleting the file (only the regular file at123 the recorded destination); `clearInactive(profile:)` never touches files.124125## Private windows126127Downloads of a ghost profile are **never persisted**: they live in the actor's memory, are listed by128`items(profile:)` for that session only, and leave the list with `endGhostSession(profile:)`, which cancels129transfers still in progress (removing what they wrote) and returns the URLs of the finished files.130131**The downloaded file stays on disk.** The UI must say so where the download is shown132(`PrivacyText.ghostDownloadKept`: "This download will disappear from the list when you close the private133window. The file itself stays where you saved it.") and in the private-window introduction.134135A download whose profile is neither stored nor declared ghost (a private session that already ended) is kept136in memory too: storage refuses it and the manager does not retry under another owner.137138## Quarantine (macOS)139140- **Files written by `ResourceDownloader`** are explicitly marked with the quarantine attribute141 (`URLResourceValues.quarantineProperties`: type web download, data URL, origin URL, agent name). A test142 checks the attribute is present after a download (outside the sandbox).143- **Files written by WebKit (`WKDownload`)**: this module does nothing to them and makes no claim. What is144 generally documented is that macOS quarantines files created by a sandboxed app, and that Gatekeeper checks145 quarantined files when they are opened. **Whether a file saved by `WKDownload` from the sandboxed ORIX146 Navigator carries `com.apple.quarantine` was not checked** — it needs a signed, sandboxed build and a real147 download, which this work did not run. Until it is checked, the confirmation before opening risky files148 (above) is the protection this code base actually provides; `ResourceDownloader.isQuarantined(_:)` is149 available to verify the attribute once the app runs.150- iOS has no quarantine attribute.151152## ResourceDownloader153154For files the browser itself needs (resources of a page archive, a capsule import), and only for actions the155user started: no queue, no background session, no retry loop.156157- `http` / `https` only; a redirect may not leave them nor downgrade https → http.158- Ephemeral session: no cookies sent or stored, no credential storage, no cache; `Accept-Encoding: identity`159 so byte offsets mean the same thing on both sides.160- Bytes go to a partial file (named by the SHA-256 of the URL) in a partials directory. After an interruption161 the next attempt sends `Range: bytes=N-` and `If-Range: <strong ETag or Last-Modified>`; `206` with the162 expected start appends, `200` starts over, `416` restarts once from zero, a `206` with another range is163 refused. **Without a validator from the first response a partial file is never reused.**164- `maximumBytes` (2 GB by default) is enforced on the announced length and while receiving.165- The finished file is moved into the destination under a sanitised, unique name and quarantined (macOS).166167## Not verified168169- No real `WKDownload` was driven through the manager: the tests play the web layer's calls. The integration170 with `DownloadCoordinator` (ordering of `downloadWillBegin` / `destination` / events, resume under the same171 id, whether WebKit leaves a partial file at the destination on cancel) is untested.172- Quarantine of files written by `WKDownload` (see above).173- Security-scoped bookmarks for a custom downloads directory were exercised outside the sandbox only (the174 code falls back to a plain bookmark there).175- `ResourceDownloader` was tested against an in-process `URLProtocol` stub, not a real server or a real176 network interruption.177- iOS: compiled, not run.178