DownloadEngine
Packages/NavigatorKit/Sources/DownloadEngine. Imports NavigatorCore, Persistence, Diagnostics,
Foundation, UniformTypeIdentifiers, CryptoKit (and CoreServices on macOS, for the quarantine keys only).
No WebKit: page downloads are performed by WebKit (WKDownload, in WebRuntime), which calls this module through
the DownloadSink protocol of NavigatorCore.
| File | What it is |
|---|---|
DownloadFilename.swift |
Content-Disposition parsing, file-name sanitising, MIME ↔ extension, unique destinations (pure) |
DownloadRisk.swift |
Risk classification (pure) |
DownloadProgress.swift |
Speed / remaining-time meter and throttle (pure) |
DownloadManager.swift |
The download list (actor), DownloadSink implementation |
ResourceDownloader.swift |
URLSession downloader with Range resume, for files the browser itself fetches |
How a page download flows
WebKit WebRuntime DownloadManager (actor)
WKDownload created ──▶ DownloadCoordinator.adopt ──▶ downloadWillBegin(candidate, control)
decideDestination ──▶ ──▶ destination(for:response:) → .save(url) | .cancel
progress / finish ──▶ ──▶ download(_:didEmit:)
pause / cancel ──▶ control.cancel() (resume data comes back)
resume / restart ◀── app glue ◀── DownloadTransferStarter (implemented by the app)The manager never talks to WebKit. To resume or restart it calls a DownloadTransferStarter that the app
implements on top of WebEngine.resumeDownload(resumeData:id:destination:) / startDownload; the web layer
then reports back through the sink with the same DownloadID.
Destination
- Default: the user's Downloads folder (macOS; the app sandbox has the
downloads.read-writeentitlement) orDocuments/Downloadsin the app container (iOS). A directory chosen by the user is stored as a bookmark (downloads.directory_bookmark, security-scoped on macOS) —setDownloadsDirectory(_:). - "Ask where to save each file" (
downloads.ask_every_time): the manager callsDownloadPrompter.chooseDestination(for:)with the sanitised name, the risk and a suggested URL;nilcancels the download and leaves no trace of it. If the user chose to replace an existing file, the manager removes it first (WebKit requires a free path). Without a prompter the default directory is used. - A download the page started without a user gesture (
DownloadCandidate.isUserInitiated == false) is subject to thedownloadspermission of the page's origin when aPermissionProvideris injected:denycancels,askcallsDownloadPrompter.allowAutomaticDownload. Without a prompter it proceeds (WebKit only reportsisUserInitiatedfrom macOS 15.2 / iOS 18.2; on older systems everything would otherwise be refused). - The destination is always a direct child of the chosen directory and never an existing file: names
already on disk and names reserved by transfers in progress get
(2),(3)… before the extension (archive (2).tar.gz).
File names
DownloadFilename.derive(contentDisposition:suggested:url:mimeType:). Every input is untrusted.
Sources, first usable one wins: Content-Disposition (filename* decoded per RFC 5987 — UTF-8 and
ISO-8859-1 — before filename, RFC 6266), the name suggested by the web layer, the last path component of the
URL (percent-decoded), "download". The DownloadSink contract only carries WebKit's suggested name, so page
downloads use the last three; the header parser serves ResourceDownloader.
sanitize turns any text into one path component:
- Unicode NFC.
- Control characters (NUL included), format characters (bidirectional overrides such as U+202E, zero-width characters, BOM, soft hyphen, tag characters) and line / paragraph separators are removed.
- Only the last path component is kept;
/and\are both separators (../../etc/passwd→passwd). : * ? " < > |→_; every white-space character → one space; runs collapse.- Leading dots and spaces are removed (no hidden file, no
..); trailing dots and spaces too; no space between the stem and the extension (invoice.pdf .exe→invoice.pdf.exe). - Windows reserved device names (
CON,NUL,COM1…) get a leading_. - At most 200 UTF-8 bytes, cut on whole characters, keeping the extension (compound ones like
.tar.gzincluded). An "extension" longer than 20 bytes is not treated as one.
An empty result means "no name" and the next source is tried.
Extension and MIME type (UTType): a missing extension gets the type's preferred one; an extension the system
does not know gets the type's extension appended (report.final + PDF → report.final.pdf); a name taken from
the URL whose extension is a server-side one (download.php, view.aspx, page.html) is corrected
(download.pdf). Otherwise the name stays as stated — the extension is what the system will use to open the
file, so it is never silently changed. Generic types (application/octet-stream…) say nothing.
Risk
DownloadRiskClassifier.classify(filename:mimeType:) → DownloadRisk(level:reasons:).
| Level | Reasons | Examples |
|---|---|---|
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 |
caution — flagged, opens normally |
archive, macroDocument, activeContent, typeMismatch |
.zip .tar.gz, .docm .xlsm .doc, .html .svg, photo.jpg served as a program type |
safe |
— | documents, images, audio, video, text |
The extension decides (it is what the system opens the file by); explicit lists come first, then UTType
conformance (executable, script, application, diskImage, alias / internet location, archive). A file
without an extension is judged by its MIME type. It is a list, not content inspection: it is not complete.
DownloadManager.openDecision(_:confirmed:) returns .needsConfirmation(url, risk) for a dangerous file until
the UI calls again with confirmed: true after showing the reasons. The decision is taken on the name of the
file on disk at that moment. The module never opens anything itself (that needs AppKit / UIKit): it returns the
URL (.open(url), revealURL(_:)).
Progress
DownloadSpeedMeter averages over a sliding 5 s window of (time, bytes) samples; no speed before 0.5 s of
samples; 0 when nothing arrived for a whole window (stalled); remaining time = remaining bytes / speed, nil
without a total or a speed. A byte count or a clock going backwards starts a new measurement. Time is always
injected.
Updates reach observers (updates(), an AsyncStream<DownloadUpdate> per caller) at most every 250 ms and
storage (database.downloads.updateProgress) at most every 2 s; state changes are never throttled.
States
(willBegin) pending ──destination──▶ running ──finished──▶ finished
│ ├─ failed(message, resumeData?) ─▶ failed ──resume / restart──▶ pending ─▶ running
│ └─ pause() ─▶ paused (resume data kept, partial file kept) ──resume──▶ pending ─▶ running
└─ cancel() / cancelled by the web layer ─▶ cancelled (partial file removed)- Pause is "stop with resume data" (WebKit has no pause). If the server does not allow resuming, the
result is
.stoppedNotResumableand the download ends cancelled: it can only be restarted. - Resume needs resume data; restart starts over and discards what was received. Both are explicit.
- At launch,
recoverInterrupted()marks downloads that were pending or running when the app stopped as failed (errorDescription == DownloadManager.interruptedErrorKey,wasInterrupted). Nothing is restarted automatically. Paused downloads stay paused and resumable across launches. remove(_:deletingFile:)removes from the list, with or without deleting the file (only the regular file at the recorded destination);clearInactive(profile:)never touches files.
Private windows
Downloads of a ghost profile are never persisted: they live in the actor's memory, are listed by
items(profile:) for that session only, and leave the list with endGhostSession(profile:), which cancels
transfers still in progress (removing what they wrote) and returns the URLs of the finished files.
The downloaded file stays on disk. The UI must say so where the download is shown
(PrivacyText.ghostDownloadKept: "This download will disappear from the list when you close the private
window. The file itself stays where you saved it.") and in the private-window introduction.
A download whose profile is neither stored nor declared ghost (a private session that already ended) is kept in memory too: storage refuses it and the manager does not retry under another owner.
Quarantine (macOS)
- Files written by
ResourceDownloaderare explicitly marked with the quarantine attribute (URLResourceValues.quarantineProperties: type web download, data URL, origin URL, agent name). A test checks the attribute is present after a download (outside the sandbox). - Files written by WebKit (
WKDownload): this module does nothing to them and makes no claim. What is generally documented is that macOS quarantines files created by a sandboxed app, and that Gatekeeper checks quarantined files when they are opened. Whether a file saved byWKDownloadfrom the sandboxed ORIX Navigator carriescom.apple.quarantinewas not checked — it needs a signed, sandboxed build and a real download, which this work did not run. Until it is checked, the confirmation before opening risky files (above) is the protection this code base actually provides;ResourceDownloader.isQuarantined(_:)is available to verify the attribute once the app runs. - iOS has no quarantine attribute.
ResourceDownloader
For files the browser itself needs (resources of a page archive, a capsule import), and only for actions the user started: no queue, no background session, no retry loop.
http/httpsonly; a redirect may not leave them nor downgrade https → http.- Ephemeral session: no cookies sent or stored, no credential storage, no cache;
Accept-Encoding: identityso byte offsets mean the same thing on both sides. - Bytes go to a partial file (named by the SHA-256 of the URL) in a partials directory. After an interruption
the next attempt sends
Range: bytes=N-andIf-Range: <strong ETag or Last-Modified>;206with the expected start appends,200starts over,416restarts once from zero, a206with another range is refused. Without a validator from the first response a partial file is never reused. maximumBytes(2 GB by default) is enforced on the announced length and while receiving.- The finished file is moved into the destination under a sanitised, unique name and quarantined (macOS).
Not verified
- No real
WKDownloadwas driven through the manager: the tests play the web layer's calls. The integration withDownloadCoordinator(ordering ofdownloadWillBegin/destination/ events, resume under the same id, whether WebKit leaves a partial file at the destination on cancel) is untested. - Quarantine of files written by
WKDownload(see above). - Security-scoped bookmarks for a custom downloads directory were exercised outside the sandbox only (the code falls back to a plain bookmark there).
ResourceDownloaderwas tested against an in-processURLProtocolstub, not a real server or a real network interruption.- iOS: compiled, not run.