Speed up downloads by combining multiple network connections in parallel
TypeScript bandwidth-aggregationcross-platformdesktop-appdownloaderdownloadmanagerlinuxmacosmulticonnectionparallel-downloadswindows
Add a browser extension that hands downloads to Plexo (#98)
Anmol Kapil6cc6df5ad580
diff --git a/e2e/browserContext.spec.ts b/e2e/browserContext.spec.tsnew file mode 100644index 0000000..7e8de0c--- /dev/null+++ b/e2e/browserContext.spec.ts@@ -0,0 +1,53 @@+import { expect, test } from '@playwright/test'+import { browserContextFrom, requestHeaders } from '../src/main/download/browserContext'+import type { BrowserCookie } from '../src/shared/types'++// Pure, so checked without the app.++const cookie = (fields: Partial<BrowserCookie>): BrowserCookie => ({+ name: 'session',+ value: 'secret',+ domain: 'example.com',+ hostOnly: false,+ path: '/',+ secure: true,+ ...fields+})++const sentTo = (url: string, cookies: BrowserCookie[]): string | undefined =>+ requestHeaders(new URL(url), { cookies })['Cookie']++test('a domain cookie follows a hop within its domain', () => {+ // drive.google.com redirects to drive.usercontent.google.com, which needs the .google.com sign-in.+ const google = cookie({ name: 'SID', domain: '.google.com' })+ expect(sentTo('https://drive.usercontent.google.com/download?id=1', [google])).toBe('SID=secret')+})++test("a site's cookies never reach another site", () => {+ const github = cookie({ name: 'user_session', domain: 'github.com', hostOnly: true })+ const githubDomain = cookie({ name: 'logged_in', domain: '.github.com' })+ expect(sentTo('https://objects.githubusercontent.com/x', [github, githubDomain])).toBeUndefined()+ expect(sentTo('https://notgithub.com/x', [github, githubDomain])).toBeUndefined()+ // A host-only cookie stays off subdomains too.+ expect(sentTo('https://api.github.com/x', [github])).toBeUndefined()+})++test('path and secure decide as a browser does, longest path first', () => {+ const root = cookie({ name: 'a', path: '/' })+ const docs = cookie({ name: 'b', path: '/docs' })+ expect(sentTo('https://example.com/docs/file.zip', [root, docs])).toBe('b=secret; a=secret')+ expect(sentTo('https://example.com/docsx/file.zip', [root, docs])).toBe('a=secret')+ expect(sentTo('http://example.com/docs/file.zip', [root, docs])).toBeUndefined()+})++test('browser context from outside is checked, and a header break is refused', () => {+ const valid = { cookies: [cookie({})], referer: 'https://example.com/page', extra: 'dropped' }+ expect(browserContextFrom(valid)).toEqual({+ cookies: [cookie({})],+ referer: 'https://example.com/page'+ })+ expect(browserContextFrom({ cookies: [cookie({ value: 'a\r\nX-Evil: 1' })] })).toBeNull()+ expect(browserContextFrom({ cookies: [], userAgent: 'UA\nHost: evil' })).toBeNull()+ expect(browserContextFrom({ cookies: [], referer: 'javascript:alert(1)' })).toBeNull()+ expect(browserContextFrom('cookies')).toBeNull()+})diff --git a/e2e/download.spec.ts b/e2e/download.spec.tsindex 0a33550..5634d67 100644--- a/e2e/download.spec.ts+++ b/e2e/download.spec.ts@@ -194,6 +194,10 @@ test.describe('edge cases', () => {const other = await serve({ size: 8 * BLOCK, seed: 8 })await expect(plexo.api.relinkDownload(id, other.url())).rejects.toThrow(/different file/)+ // Same size and the same ETag (every test origin's "v1"), other bytes: labels alone would let+ // it through and mix two files.+ const lookalike = await serve({ size: 16 * BLOCK, seed: 9 })+ await expect(plexo.api.relinkDownload(id, lookalike.url())).rejects.toThrow(/different file/)const fresh = await serve({ size: 16 * BLOCK, seed: 7 })await plexo.api.relinkDownload(id, fresh.url())diff --git a/electron-builder.yml b/electron-builder.ymlindex 4471e64..e7f6e0d 100644--- a/electron-builder.yml+++ b/electron-builder.yml@@ -48,9 +48,12 @@ mac:- NSDownloadsFolderUsageDescription: Plexo saves downloaded files to your Downloads folder.# Magnet links and .torrent files can be opened with Plexo, as one choice among others: it's# never made the default over a torrent client the user already has (LSHandlerRank).+ # plexo:// is Plexo's own scheme, so registering it takes nothing from another app.- CFBundleURLTypes:- CFBundleURLName: Magnet linkCFBundleURLSchemes: [magnet]+ - CFBundleURLName: Plexo+ CFBundleURLSchemes: [plexo]CFBundleDocumentTypes:- CFBundleTypeName: TorrentCFBundleTypeRole: Viewer@@ -71,7 +74,7 @@ linux:maintainer: electronjs.orgcategory: Utility# Offered for magnet links and .torrent files ("Open with"), not made their default.- mimeTypes: [x-scheme-handler/magnet, application/x-bittorrent]+ mimeTypes: [x-scheme-handler/magnet, application/x-bittorrent, x-scheme-handler/plexo]appImage:artifactName: ${name}-${version}-${arch}.${ext}npmRebuild: falsediff --git a/eslint.config.mjs b/eslint.config.mjsindex 4806791..83e2979 100644--- a/eslint.config.mjs+++ b/eslint.config.mjs@@ -38,7 +38,7 @@ export default defineConfig(// Plain JavaScript that runs as-is — the download page's script, and the CommonJS and ES module// scripts that Electron and node load directly — so TypeScript's conventions (return types,// import syntax) don't apply.- files: ['docs/**/*.js', 'e2e/page-host/*.cjs', 'scripts/**/*.mjs'],+ files: ['docs/**/*.js', 'e2e/page-host/*.cjs', 'scripts/**/*.mjs', 'extension/build.mjs'],rules: {'@typescript-eslint/explicit-function-return-type': 'off','@typescript-eslint/no-require-imports': 'off'diff --git a/extension/build.mjs b/extension/build.mjsnew file mode 100644index 0000000..99fc19a--- /dev/null+++ b/extension/build.mjs@@ -0,0 +1,63 @@+import { cp, mkdir, readFile, rm, writeFile } from 'node:fs/promises'+import { dirname, join } from 'node:path'+import { fileURLToPath } from 'node:url'+import { build } from 'vite'++const root = dirname(fileURLToPath(import.meta.url))+const out = join(root, 'dist')+const scripts = join(out, 'scripts')++await rm(out, { recursive: true, force: true })++// One self-contained script each: Firefox's background script can't load modules.+for (const name of ['background', 'popup', 'options']) {+ await build({+ configFile: false,+ root,+ logLevel: 'warn',+ build: {+ outDir: scripts,+ emptyOutDir: false,+ minify: false,+ lib: {+ entry: join(root, 'src', `${name}.ts`),+ formats: ['iife'],+ name: 'plexo',+ fileName: () => `${name}.js`+ }+ }+ })+}++const base = JSON.parse(await readFile(join(root, 'manifest.json'), 'utf-8'))+// One manifest per browser: given both background keys, Chrome reports the one it doesn't use as+// an error.+const manifests = {+ chrome: {+ ...base,+ // The first Chrome where every API this calls returns a promise (contextMenus.removeAll).+ minimum_chrome_version: '123',+ background: { service_worker: 'background.js' }+ },+ firefox: {+ ...base,+ background: { scripts: ['background.js'] },+ browser_specific_settings: {+ gecko: { id: '[email protected]', strict_min_version: '121.0' }+ }+ }+}++for (const [browser, manifest] of Object.entries(manifests)) {+ const dir = join(out, browser)+ await mkdir(dir, { recursive: true })+ await cp(scripts, dir, { recursive: true })+ for (const file of ['popup.html', 'options.html', 'ui.css']) {+ await cp(join(root, 'src', file), join(dir, file))+ }+ await cp(join(root, 'icons'), join(dir, 'icons'), { recursive: true })+ await cp(join(root, '../src/renderer/src/assets/fonts'), join(dir, 'fonts'), { recursive: true })+ await writeFile(join(dir, 'manifest.json'), `${JSON.stringify(manifest, null, 2)}\n`)+}+await rm(scripts, { recursive: true })+console.log(`Built ${Object.keys(manifests).join(' and ')} into ${out}`)diff --git a/extension/icons/icon-128.png b/extension/icons/icon-128.pngnew file mode 100644index 0000000..d38025aBinary files /dev/null and b/extension/icons/icon-128.png differdiff --git a/extension/icons/icon-16.png b/extension/icons/icon-16.pngnew file mode 100644index 0000000..37eb55fBinary files /dev/null and b/extension/icons/icon-16.png differdiff --git a/extension/icons/icon-32.png b/extension/icons/icon-32.pngnew file mode 100644index 0000000..9ec9d25Binary files /dev/null and b/extension/icons/icon-32.png differdiff --git a/extension/icons/icon-48.png b/extension/icons/icon-48.pngnew file mode 100644index 0000000..97888d1Binary files /dev/null and b/extension/icons/icon-48.png differdiff --git a/extension/icons/icon-off-16.png b/extension/icons/icon-off-16.pngnew file mode 100644index 0000000..90c3019Binary files /dev/null and b/extension/icons/icon-off-16.png differdiff --git a/extension/icons/icon-off-32.png b/extension/icons/icon-off-32.pngnew file mode 100644index 0000000..4b0e0baBinary files /dev/null and b/extension/icons/icon-off-32.png differdiff --git a/extension/manifest.json b/extension/manifest.jsonnew file mode 100644index 0000000..b4400ab--- /dev/null+++ b/extension/manifest.json@@ -0,0 +1,24 @@+{+ "manifest_version": 3,+ "name": "Plexo",+ "version": "1.0.0",+ "description": "Download files with the Plexo app.",+ "homepage_url": "https://getplexo.app",+ "icons": {+ "16": "icons/icon-16.png",+ "32": "icons/icon-32.png",+ "48": "icons/icon-48.png",+ "128": "icons/icon-128.png"+ },+ "action": {+ "default_title": "Plexo",+ "default_popup": "popup.html",+ "default_icon": {+ "16": "icons/icon-16.png",+ "32": "icons/icon-32.png"+ }+ },+ "options_ui": { "page": "options.html", "open_in_tab": true },+ "permissions": ["alarms", "downloads", "contextMenus", "cookies", "storage", "tabs"],+ "host_permissions": ["<all_urls>"]+}diff --git a/extension/src/api.ts b/extension/src/api.tsnew file mode 100644index 0000000..0b16c9f--- /dev/null+++ b/extension/src/api.ts@@ -0,0 +1,3 @@+// Firefox returns promises only through `browser`: its `chrome` takes callbacks. Chrome has+// `browser` from 148, and promises on `chrome` before that.+export const api: typeof chrome = (globalThis as { browser?: typeof chrome }).browser ?? chromediff --git a/extension/src/background.ts b/extension/src/background.tsnew file mode 100644index 0000000..9bf06b6--- /dev/null+++ b/extension/src/background.ts@@ -0,0 +1,140 @@+import { api } from './api'+import type { BridgeAddRequest } from '../../src/shared/browserBridge'+import { browserContext, confirm, reach, send, storeOf, wake, type Reach } from './plexo'+import { excluded, loadSettings } from './settings'++const MENU_ID = 'download-with-plexo'+// Plexo can't tell the extension it has quit, so the toolbar icon checks on a timer.+const CHECK_ALARM = 'check-plexo'++const openedAt = new Map<number, number>()++const ICON = { 16: 'icons/icon-16.png', 32: 'icons/icon-32.png' }+// A greyed-out icon rather than a badge: the browser draws badges too small to notice.+const ICON_OFF = { 16: 'icons/icon-off-16.png', 32: 'icons/icon-off-32.png' }++async function showState(reached?: Reach): Promise<void> {+ const { capture } = await loadSettings()+ reached ??= await reach()+ const title = !capture+ ? 'Plexo: capture is off'+ : reached === 'closed'+ ? 'Plexo isn’t open: downloads stay in the browser'+ : reached === 'update'+ ? 'Update Plexo to use this extension'+ : 'Plexo'+ await api.action.setIcon({ path: capture && reached === 'ok' ? ICON : ICON_OFF })+ await api.action.setTitle({ title })+}++/** True when Plexo took the download; otherwise the browser keeps it. */+async function capture(item: chrome.downloads.DownloadItem): Promise<boolean> {+ const settings = await loadSettings()+ const url = item.finalUrl || item.url+ // blob: and data: downloads exist only inside the browser.+ if (!settings.capture || !/^https?:/i.test(url)) return false+ if (excluded(settings.sites, [item.url, item.finalUrl, item.referrer])) return false++ const request: BridgeAddRequest = {+ url,+ browser: await browserContext([item.url, item.finalUrl], storeOf(item), item.referrer),+ pageUrl: item.referrer || undefined,+ minBytes: settings.skipSmall ? settings.minMegabytes * 1024 * 1024 : undefined,+ // Chrome and Firefox both give a path here.+ fileName: item.filename.split(/[\\/]/).pop() || undefined+ }+ const handoff = await send(request)+ if (typeof handoff === 'string') {+ if (handoff === 'closed') await showState('closed')+ return false+ }+ // Plexo shows the download only once the browser's copy is gone. Firefox can't hold a download+ // while Plexo checks it, so a small one may have finished meanwhile: cancelling then does+ // nothing, and the browser keeps it rather than both ending up with it.+ await api.downloads.cancel(item.id).catch(() => {})+ const [after] = await api.downloads.search({ id: item.id }).catch(() => [])+ if (after?.state === 'complete') return false+ await api.downloads.erase({ id: item.id }).catch(() => {})+ const shown = await confirm(handoff)+ await closeEmptyTab([item.url, item.finalUrl])+ await showState(shown ? 'ok' : undefined)+ return true+}++/** A link that opens a tab only to download leaves that tab empty once Plexo takes it. */+async function closeEmptyTab(urls: readonly (string | undefined)[]): Promise<void> {+ const recently = Date.now() - 30_000+ for (const tab of await api.tabs.query({})) {+ const shows = tab.pendingUrl ?? tab.url+ if (tab.id === undefined || shows === undefined || !urls.includes(shows)) continue+ if ((openedAt.get(tab.id) ?? 0) < recently) continue+ await api.tabs.remove(tab.id).catch(() => {})+ }+}++// In Chromium, answering later holds back the browser's own Save As dialog until Plexo has+// decided, so the user is never asked twice. Firefox has no such event.+const determining = api.downloads.onDeterminingFilename+if (determining) {+ determining.addListener((item, suggest) => {+ void capture(item).then((taken) => taken || suggest())+ return true+ })+} else {+ api.downloads.onCreated.addListener((item) => void capture(item))+}++/** Sent whatever the settings say, and Plexo is started if needed: the user asked for it. */+async function sendLink(+ info: chrome.contextMenus.OnClickData,+ tab?: chrome.tabs.Tab+): Promise<void> {+ const url = info.linkUrl+ if (!url) return+ const request: BridgeAddRequest = /^magnet:/i.test(url)+ ? { url }+ : {+ url,+ browser: await browserContext([url], tab && storeOf(tab), info.pageUrl),+ pageUrl: info.pageUrl+ }+ let sent = await send(request)+ if (sent === 'closed' && (await wake())) sent = await send(request)+ // No browser copy to cancel first.+ const shown = typeof sent !== 'string' && (await confirm(sent))+ await showState(shown ? 'ok' : undefined)+}++// Run on install and on every browser start: menus and alarms don't always survive a restart.+function setUp(): void {+ createMenu()+ void api.alarms.create(CHECK_ALARM, { periodInMinutes: 0.5 })+ void showState()+}++function createMenu(): void {+ void api.contextMenus+ .removeAll()+ .then(() =>+ api.contextMenus.create({ id: MENU_ID, title: 'Download with Plexo', contexts: ['link'] })+ )+}++api.runtime.onInstalled.addListener(setUp)+api.runtime.onStartup.addListener(setUp)+api.alarms.onAlarm.addListener((alarm) => {+ if (alarm.name === CHECK_ALARM) void showState()+})+api.contextMenus.onClicked.addListener((info, tab) => {+ if (info.menuItemId === MENU_ID) void sendLink(info, tab)+})+api.tabs.onCreated.addListener((tab) => {+ if (tab.id !== undefined) openedAt.set(tab.id, Date.now())+})+api.storage.onChanged.addListener(() => void showState())++api.runtime.onMessage.addListener((message) => {+ const { wakePlexo, checkPlexo } = message as { wakePlexo?: boolean; checkPlexo?: boolean }+ if (checkPlexo) void showState()+ if (wakePlexo) void wake().then((woke) => showState(woke ? 'ok' : 'closed'))+})diff --git a/extension/src/options.html b/extension/src/options.htmlnew file mode 100644index 0000000..dca8103--- /dev/null+++ b/extension/src/options.html@@ -0,0 +1,175 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="utf-8" />+ <title>Plexo extension options</title>+ <link rel="stylesheet" href="ui.css" />+ <style>+ main {+ max-width: 680px;+ margin: 0 auto;+ padding: 48px 20px 64px;+ display: flex;+ flex-direction: column;+ gap: 28px;+ }+ header {+ display: flex;+ align-items: center;+ gap: 14px;+ }+ header img {+ width: 36px;+ height: 36px;+ }+ h1 {+ margin: 0;+ font-size: 20px;+ }+ h2 {+ margin: 0 0 10px;+ font: 500 11px var(--mono);+ letter-spacing: 0.08em;+ text-transform: uppercase;+ color: var(--text3);+ }+ .card {+ border: 0.5px solid var(--border);+ border-radius: 12px;+ background: var(--bg2);+ overflow: hidden;+ }+ .card .row {+ flex-wrap: wrap;+ gap: 16px;+ padding: 16px 18px;+ }+ .card .row:last-child {+ border-bottom: none;+ }+ .card .grow {+ flex: 1 1 260px;+ }+ #sites li {+ display: flex;+ align-items: center;+ gap: 10px;+ padding: 6px 8px 6px 18px;+ border-top: 0.5px solid var(--border);+ font: 12.5px var(--mono);+ }+ #sites li span {+ flex: 1;+ min-width: 0;+ overflow-wrap: anywhere;+ }+ #sites {+ margin: 0;+ padding: 0;+ list-style: none;+ }+ .links {+ display: flex;+ flex-wrap: wrap;+ gap: 6px 16px;+ font-size: 12px;+ color: var(--text3);+ }+ </style>+ </head>+ <body>+ <main>+ <header>+ <img src="icons/icon-128.png" alt="" />+ <div class="grow">+ <h1>Plexo</h1>+ <div class="muted">Extension options</div>+ </div>+ </header>++ <section>+ <h2>Capture</h2>+ <div class="card">+ <label class="row" for="capture">+ <span class="grow">+ <span class="title">Capture downloads</span>+ <span class="muted"+ >Every download this browser starts opens in Plexo. If Plexo isn’t open, the browser+ keeps it.</span+ >+ </span>+ <input type="checkbox" role="switch" class="switch" id="capture" />+ </label>+ <div class="row">+ <label class="grow" for="skip-small">+ <span class="title">Skip small files</span>+ <span class="muted">Files smaller than this stay in the browser.</span>+ </label>+ <input+ type="number"+ id="min-mb"+ min="1"+ step="1"+ style="width: 64px"+ aria-label="Minimum size in megabytes"+ />+ <span class="mono muted">MB</span>+ <input type="checkbox" role="switch" class="switch" id="skip-small" />+ </div>+ </div>+ </section>++ <section>+ <h2>Sites that keep their downloads</h2>+ <div class="card">+ <form class="row" id="add-site" style="flex-direction: column; align-items: stretch">+ <span class="muted"+ >Downloads from these sites and their subdomains stay in the browser. Right-click ›+ Download with Plexo still works on them.</span+ >+ <span style="display: flex; gap: 8px">+ <input+ type="text"+ id="site"+ placeholder="example.com"+ aria-label="Site to add"+ class="mono"+ style="flex: 1; min-width: 0"+ />+ <button type="submit">Add</button>+ </span>+ <span id="site-error" role="alert" style="color: var(--warn)" hidden+ >That isn’t a site name.</span+ >+ </form>+ <ul id="sites"></ul>+ <div class="row muted" id="no-sites" style="border-top: 0.5px solid var(--border)">+ No sites yet. Every site’s downloads go to Plexo.+ </div>+ </div>+ </section>++ <section>+ <h2>Connection</h2>+ <div class="card">+ <div class="row">+ <span class="grow">+ <span class="title" style="display: flex; align-items: center; gap: 8px"+ ><span class="dot" id="dot"></span><span id="connection">…</span></span+ >+ <span class="mono muted" id="port"></span>+ </span>+ <button type="button" id="open-plexo" hidden>Open Plexo</button>+ </div>+ </div>+ </section>++ <div class="links">+ <span class="mono" id="version"></span>+ <a href="https://getplexo.app" target="_blank" rel="noreferrer">Website</a>+ <a href="https://github.com/anmolkapil/plexo" target="_blank" rel="noreferrer">GitHub</a>+ </div>+ </main>+ <script src="options.js"></script>+ </body>+</html>diff --git a/extension/src/options.ts b/extension/src/options.tsnew file mode 100644index 0000000..2a5b19a--- /dev/null+++ b/extension/src/options.ts@@ -0,0 +1,80 @@+import { api } from './api'+import { plexoPort, reach } from './plexo'+import { loadSettings, saveSettings, siteOf } from './settings'++const element = <T extends HTMLElement>(id: string): T => document.getElementById(id) as T++async function render(): Promise<void> {+ const settings = await loadSettings()+ element<HTMLInputElement>('capture').checked = settings.capture+ element<HTMLInputElement>('skip-small').checked = settings.skipSmall+ const minimum = element<HTMLInputElement>('min-mb')+ minimum.value = String(settings.minMegabytes)+ minimum.disabled = !settings.skipSmall++ const list = element('sites')+ list.replaceChildren(+ ...settings.sites.map((site) => {+ const item = document.createElement('li')+ const name = document.createElement('span')+ name.textContent = site+ const remove = document.createElement('button')+ remove.type = 'button'+ remove.className = 'ghost'+ remove.textContent = 'Remove'+ remove.setAttribute('aria-label', `Remove ${site}`)+ remove.addEventListener('click', () => {+ void saveSettings({ sites: settings.sites.filter((other) => other !== site) })+ })+ item.append(name, remove)+ return item+ })+ )+ element('no-sites').hidden = settings.sites.length > 0+}++async function renderConnection(): Promise<void> {+ const reached = await reach()+ element('dot').className = `dot ${reached === 'ok' ? 'ok' : reached === 'update' ? 'warn' : ''}`+ element('connection').textContent =+ reached === 'ok'+ ? 'Connected to Plexo'+ : reached === 'update'+ ? 'Update Plexo to use this extension'+ : 'Plexo isn’t open'+ element('open-plexo').hidden = reached !== 'closed'+ const port = plexoPort()+ element('port').textContent = port === null ? '' : `127.0.0.1:${port}`+}++element<HTMLInputElement>('capture').addEventListener('change', (event) => {+ void saveSettings({ capture: (event.target as HTMLInputElement).checked })+})+element<HTMLInputElement>('skip-small').addEventListener('change', (event) => {+ void saveSettings({ skipSmall: (event.target as HTMLInputElement).checked })+})+element<HTMLInputElement>('min-mb').addEventListener('change', (event) => {+ const megabytes = Math.round(Number((event.target as HTMLInputElement).value))+ if (megabytes >= 1) void saveSettings({ minMegabytes: megabytes })+ else void render()+})++element<HTMLFormElement>('add-site').addEventListener('submit', async (event) => {+ event.preventDefault()+ const input = element<HTMLInputElement>('site')+ const site = siteOf(input.value)+ element('site-error').hidden = site !== null || input.value.trim() === ''+ if (!site) return+ const { sites } = await loadSettings()+ if (!sites.includes(site)) await saveSettings({ sites: [...sites, site] })+ input.value = ''+})++element('open-plexo').addEventListener('click', () => {+ void api.runtime.sendMessage({ wakePlexo: true }).then(() => setTimeout(renderConnection, 4000))+})++element('version').textContent = `Extension ${api.runtime.getManifest().version}`+api.storage.onChanged.addListener(() => void render())+void render()+void renderConnection()diff --git a/extension/src/plexo.ts b/extension/src/plexo.tsnew file mode 100644index 0000000..5b91b03--- /dev/null+++ b/extension/src/plexo.ts@@ -0,0 +1,160 @@+import { api } from './api'+import {+ BRIDGE_API,+ BRIDGE_DEADLINE_MS,+ BRIDGE_PORTS,+ type BridgeAddRequest,+ type BridgeHandoff,+ type BridgePing+} from '../../src/shared/browserBridge'+import type { BrowserContext, BrowserCookie } from '../../src/shared/types'++export type Reach = 'ok' | 'closed' | 'update'++let found: number | null = null++/** Anything other than Plexo holding the port counts as closed. */+async function ask(port: number): Promise<Reach> {+ try {+ const response = await fetch(`http://127.0.0.1:${port}/ping`, {+ signal: AbortSignal.timeout(1500)+ })+ const ping = (await response.json()) as Partial<BridgePing>+ if (!response.ok || ping.app !== 'plexo') return 'closed'+ return ping.api === BRIDGE_API ? 'ok' : 'update'+ } catch {+ return 'closed'+ }+}++export function plexoPort(): number | null {+ return found+}++export async function reach(): Promise<Reach> {+ const answers = await Promise.all(BRIDGE_PORTS.map(ask))+ const at = answers.indexOf('ok')+ found = at >= 0 ? BRIDGE_PORTS[at] : null+ return at >= 0 ? 'ok' : answers.includes('update') ? 'update' : 'closed'+}++/** Plexo will take the download once confirmed (see BridgeHandoff). */+export interface Handoff {+ port: number+ token: string+}++/** kept: Plexo said no, or took too long. */+export async function send(request: BridgeAddRequest): Promise<Handoff | 'kept' | 'closed'> {+ // Asked first every time, so the sign-in only ever goes to a port that has just answered as+ // Plexo, never to another app that has since taken it.+ if ((await reach()) !== 'ok' || found === null) return 'closed'+ const port = found+ try {+ const response = await fetch(`http://127.0.0.1:${port}/add`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(request),+ // Past Plexo's own deadline: Plexo answers nothing once this has given up.+ signal: AbortSignal.timeout(BRIDGE_DEADLINE_MS + 2000)+ })+ if (!response.ok) return 'kept'+ const { token } = (await response.json()) as BridgeHandoff+ return { port, token }+ } catch (error) {+ return error instanceof DOMException && error.name === 'TimeoutError' ? 'kept' : 'closed'+ }+}++export async function confirm({ port, token }: Handoff): Promise<boolean> {+ try {+ const response = await fetch(`http://127.0.0.1:${port}/confirm`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ token }),+ signal: AbortSignal.timeout(3000)+ })+ return response.ok+ } catch {+ return false+ }+}++/** Firefox names its containers and private windows; Chrome's incognito store is "1". */+export function storeOf(source: {+ incognito: boolean+ cookieStoreId?: string+}): string | undefined {+ return source.cookieStoreId ?? (source.incognito ? '1' : undefined)+}++type IsolatedCookie = chrome.cookies.Cookie & { firstPartyDomain?: string }++function hostOf(url: string | undefined): string[] {+ try {+ return url ? [new URL(url).hostname] : []+ } catch {+ return []+ }+}++/** Cookies for where the download starts and where its redirects end; Plexo sends each request+ * only the ones that match it. */+export async function browserContext(+ urls: readonly (string | undefined)[],+ storeId: string | undefined,+ referer: string | undefined+): Promise<BrowserContext> {+ const cookies = new Map<string, BrowserCookie>()+ const hosts = [...urls, referer].flatMap(hostOf)+ for (const url of new Set(urls)) {+ if (!url || !/^https?:/i.test(url)) continue+ const found = await api.cookies+ .getAll({ url, storeId })+ // Firefox with first-party isolation on refuses without firstPartyDomain. null reads every+ // site's copy, so only those kept for the download's own site or its page's are used.+ // Chrome refuses the key, so it's only tried second.+ .catch(async () => {+ const all = (await api.cookies.getAll({+ url,+ storeId,+ firstPartyDomain: null+ } as chrome.cookies.GetAllDetails)) as IsolatedCookie[]+ return all.filter(({ firstPartyDomain: site }) => {+ return !site || hosts.some((host) => host === site || host.endsWith(`.${site}`))+ })+ })+ .catch(() => [])+ for (const { name, value, domain, hostOnly, path, secure } of found) {+ cookies.set(`${domain}\n${path}\n${name}`, { name, value, domain, hostOnly, path, secure })+ }+ }+ return {+ cookies: [...cookies.values()],+ ...(referer && /^https?:/i.test(referer) && { referer }),+ userAgent: navigator.userAgent,+ name: browserName()+ }+}++function browserName(): string {+ const agent = navigator.userAgent+ if (/Firefox\//.test(agent)) return 'Firefox'+ if (/Edg\//.test(agent)) return 'Edge'+ if (/OPR\//.test(agent)) return 'Opera'+ if (/Vivaldi\//.test(agent)) return 'Vivaldi'+ if ('brave' in navigator) return 'Brave'+ return 'Chrome'+}++/** Only ever on a click: the browser asks the user whether to open the app. */+export async function wake(): Promise<boolean> {+ const tab = await api.tabs.create({ url: 'plexo://open' })+ let reached = false+ for (let tries = 0; tries < 20 && !reached; tries++) {+ await new Promise((resolve) => setTimeout(resolve, 500))+ reached = (await reach()) === 'ok'+ }+ if (reached && tab.id !== undefined) await api.tabs.remove(tab.id).catch(() => {})+ return reached+}diff --git a/extension/src/popup.html b/extension/src/popup.htmlnew file mode 100644index 0000000..7f3f397--- /dev/null+++ b/extension/src/popup.html@@ -0,0 +1,105 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="utf-8" />+ <title>Plexo</title>+ <link rel="stylesheet" href="ui.css" />+ <style>+ body {+ width: 340px;+ }+ header {+ display: flex;+ align-items: center;+ gap: 10px;+ padding: 12px 14px;+ border-bottom: 0.5px solid var(--border);+ }+ header img {+ width: 22px;+ height: 22px;+ }+ header strong {+ flex: 1;+ font-size: 14px;+ }+ #status {+ display: flex;+ align-items: center;+ gap: 6px;+ font: 11px var(--mono);+ color: var(--text2);+ }+ #site-host {+ font: 500 12.5px var(--mono);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ #closed {+ padding: 16px 14px;+ display: flex;+ flex-direction: column;+ gap: 10px;+ border-bottom: 0.5px solid var(--border);+ }+ footer {+ display: flex;+ align-items: center;+ gap: 10px;+ padding: 6px 6px 6px 14px;+ background: var(--bg2);+ font-size: 11.5px;+ color: var(--text3);+ }+ footer span {+ flex: 1;+ }+ </style>+ </head>+ <body>+ <header>+ <img src="icons/icon-32.png" alt="" />+ <strong>Plexo</strong>+ <div id="status" role="status">+ <span class="dot" id="status-dot"></span><span id="status-text">…</span>+ </div>+ </header>++ <div class="notice" id="access" hidden>+ Plexo needs access to websites to send your sign-in with each download.+ <button type="button" class="primary" id="grant">Allow access</button>+ </div>++ <div id="closed" hidden>+ <div class="title">Plexo isn’t open</div>+ <div class="muted">Downloads stay in the browser until it is.</div>+ <div style="display: flex; align-items: center; gap: 12px">+ <button type="button" id="open-plexo">Open Plexo</button>+ <a href="https://getplexo.app" target="_blank" rel="noreferrer">Get Plexo</a>+ </div>+ </div>++ <label class="row" for="capture">+ <span class="grow">+ <span class="title">Capture downloads</span>+ <span class="muted" id="capture-hint"></span>+ </span>+ <input type="checkbox" role="switch" class="switch" id="capture" />+ </label>++ <label class="row" for="site" id="site-row" hidden>+ <span class="grow">+ <span id="site-host"></span>+ <span class="muted" id="site-hint"></span>+ </span>+ <input type="checkbox" role="switch" class="switch" id="site" />+ </label>++ <footer>+ <span>Right-click any link › Download with Plexo</span>+ <button type="button" class="ghost" id="options">Options</button>+ </footer>+ <script src="popup.js"></script>+ </body>+</html>diff --git a/extension/src/popup.ts b/extension/src/popup.tsnew file mode 100644index 0000000..66299fa--- /dev/null+++ b/extension/src/popup.ts@@ -0,0 +1,82 @@+import { api } from './api'+import { reach } from './plexo'+import { excluded, loadSettings, saveSettings } from './settings'++const element = <T extends HTMLElement>(id: string): T => document.getElementById(id) as T+const ALL_SITES = { origins: ['<all_urls>'] }++async function activeHost(): Promise<string | null> {+ const [tab] = await api.tabs.query({ active: true, currentWindow: true })+ return tab?.url && /^https?:/i.test(tab.url) ? new URL(tab.url).hostname : null+}++async function render(): Promise<void> {+ const [settings, host, reached, access] = await Promise.all([+ loadSettings(),+ activeHost(),+ reach(),+ // Firefox lets the user withhold site access, which reading a site's cookies needs.+ api.permissions.contains(ALL_SITES)+ ])+ const [tone, text] =+ reached === 'closed'+ ? ['', 'Plexo not open']+ : reached === 'update'+ ? ['warn', 'Update Plexo']+ : settings.capture+ ? ['ok', 'Connected']+ : ['', 'Capture off']+ element('status-dot').className = `dot ${tone}`+ element('status-text').textContent = text+ element('access').hidden = access+ element('closed').hidden = reached !== 'closed'++ element<HTMLInputElement>('capture').checked = settings.capture+ element('capture-hint').textContent = settings.capture+ ? 'Downloads open in Plexo instead of the browser.'+ : 'Downloads stay in the browser.'++ element('site-row').hidden = host === null+ if (host) {+ const on = !excluded(settings.sites, [`https://${host}/`])+ const site = element<HTMLInputElement>('site')+ site.checked = on && settings.capture+ site.disabled = !settings.capture+ element('site-host').textContent = host+ element('site-hint').textContent = !settings.capture+ ? 'Capture is off everywhere.'+ : on+ ? 'Downloads from this site go to Plexo.'+ : 'Downloads from this site stay in the browser.'+ }+}++element<HTMLInputElement>('capture').addEventListener('change', (event) => {+ void saveSettings({ capture: (event.target as HTMLInputElement).checked })+})++element<HTMLInputElement>('site').addEventListener('change', async (event) => {+ const host = await activeHost()+ if (!host) return+ const { sites } = await loadSettings()+ // A parent domain's rule covers this site too, so turning it back on drops that as well.+ const covering = (site: string): boolean => host === site || host.endsWith(`.${site}`)+ await saveSettings({+ sites: (event.target as HTMLInputElement).checked+ ? sites.filter((site) => !covering(site))+ : [...sites, host]+ })+})++element('grant').addEventListener('click', () => {+ void api.permissions.request(ALL_SITES).then(render)+})+element('open-plexo').addEventListener('click', () => {+ void api.runtime.sendMessage({ wakePlexo: true })+})+element('options').addEventListener('click', () => void api.runtime.openOptionsPage())++api.storage.onChanged.addListener(() => void render())+void render()+// So the toolbar icon agrees with the popup now, not at its next check.+void api.runtime.sendMessage({ checkPlexo: true }).catch(() => {})diff --git a/extension/src/settings.ts b/extension/src/settings.tsnew file mode 100644index 0000000..3f950c6--- /dev/null+++ b/extension/src/settings.ts@@ -0,0 +1,46 @@+import { api } from './api'+export interface Settings {+ capture: boolean+ sites: string[]+ skipSmall: boolean+ minMegabytes: number+}++const DEFAULTS: Settings = {+ capture: true,+ sites: [],+ skipSmall: false,+ minMegabytes: 1+}++export async function loadSettings(): Promise<Settings> {+ return { ...DEFAULTS, ...(await api.storage.local.get(DEFAULTS)) } as Settings+}++export function saveSettings(patch: Partial<Settings>): Promise<void> {+ return api.storage.local.set(patch)+}++/** The site rule typed or pasted ("https://Drive.Google.com/x", "*.example.com"), or null. */+export function siteOf(input: string): string | null {+ const text = input.trim().toLowerCase().replace(/^\*\./, '')+ try {+ const host = new URL(/^[a-z]+:\/\//.test(text) ? text : `https://${text}`).hostname+ return host.includes('.') || host === 'localhost' ? host : null+ } catch {+ return null+ }+}++export function excluded(sites: readonly string[], urls: readonly (string | undefined)[]): boolean {+ return urls.some((url) => {+ if (!url) return false+ let host: string+ try {+ host = new URL(url).hostname+ } catch {+ return false+ }+ return sites.some((site) => host === site || host.endsWith(`.${site}`))+ })+}diff --git a/extension/src/ui.css b/extension/src/ui.cssnew file mode 100644index 0000000..2e65ec2--- /dev/null+++ b/extension/src/ui.css@@ -0,0 +1,201 @@+/* The app's tokens (src/renderer/src/assets/main.css), so the extension looks like Plexo. */+@font-face {+ font-family: 'Manrope';+ font-weight: 400 700;+ src: url('fonts/Manrope-Variable.woff2') format('woff2');+}+@font-face {+ font-family: 'Roboto Mono';+ font-weight: 400 600;+ src: url('fonts/RobotoMono-Variable.woff2') format('woff2');+}++:root {+ color-scheme: light dark;+ --bg: #ffffff;+ --bg2: #fafafa;+ --input: #ffffff;+ --text: #1d1d1f;+ --text2: #6e6e73;+ --text3: #737377;+ --border: #e0e0e2;+ --strong: #b9b9bb;+ --on: #1f8a70;+ /* Darker than the app's #d97706, so white text on it reads at WCAG AA. */+ --accent: #b45309;+ --accent-on: #ffffff;+ --warn: #92400e;+ --warn-bg: #fef3c7;+ --warn-border: #fde68a;+ --mono: 'Roboto Mono', ui-monospace, Menlo, monospace;+}+@media (prefers-color-scheme: dark) {+ :root {+ --bg: #1b1e20;+ --bg2: #202325;+ --input: #242729;+ --text: #eae7e2;+ --text2: #a9adb2;+ --text3: #8d9196;+ --border: #2b2f33;+ --strong: #3a3f44;+ --on: #4ea89a;+ --accent: #d8a44c;+ --accent-on: #1b1408;+ --warn: #e8bb6d;+ --warn-bg: #33291a;+ --warn-border: #54421f;+ }+}++* {+ box-sizing: border-box;+}+body {+ margin: 0;+ background: var(--bg);+ color: var(--text);+ font:+ 13px/1.45 Manrope,+ -apple-system,+ 'Helvetica Neue',+ sans-serif;+}+[hidden] {+ display: none !important;+}+a {+ color: var(--accent);+}+.mono {+ font-family: var(--mono);+}+.muted {+ color: var(--text2);+}+.title {+ font-size: 13.5px;+ font-weight: 600;+}++.row {+ display: flex;+ align-items: center;+ gap: 12px;+ padding: 14px;+ border-bottom: 0.5px solid var(--border);+}+.grow {+ flex: 1;+ min-width: 0;+ display: flex;+ flex-direction: column;+ gap: 3px;+}+.dot {+ width: 7px;+ height: 7px;+ border-radius: 999px;+ background: var(--text3);+ flex-shrink: 0;+}+.dot.ok {+ background: var(--on);+}+.dot.warn {+ background: var(--accent);+}++/* A real checkbox under the switch look, so keyboards and screen readers still work. */+.switch {+ appearance: none;+ margin: 0;+ flex-shrink: 0;+ width: 38px;+ height: 22px;+ border-radius: 999px;+ background: var(--strong);+ position: relative;+ cursor: pointer;+ transition: background 0.15s;+}+.switch::after {+ content: '';+ position: absolute;+ top: 3px;+ left: 3px;+ width: 16px;+ height: 16px;+ border-radius: 999px;+ background: #ffffff;+ box-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);+ transition: transform 0.15s;+}+.switch:checked {+ background: var(--on);+}+.switch:checked::after {+ transform: translateX(16px);+}+.switch:disabled {+ opacity: 0.45;+ cursor: default;+}+.switch:focus-visible,+button:focus-visible,+input:focus-visible,+a:focus-visible {+ outline: 2px solid var(--accent);+ outline-offset: 2px;+}++button {+ font: inherit;+ font-weight: 500;+ height: 32px;+ padding: 0 12px;+ border-radius: 8px;+ border: 0.5px solid var(--border);+ background: var(--bg2);+ color: var(--text);+ cursor: pointer;+ text-decoration: none;+ display: inline-flex;+ align-items: center;+ justify-content: center;+}+button.primary {+ border: none;+ background: var(--accent);+ color: var(--accent-on);+ font-weight: 600;+}+button.ghost {+ border: none;+ background: transparent;+ color: var(--text2);+}++input[type='text'],+input[type='number'] {+ font: inherit;+ height: 32px;+ padding: 0 10px;+ border-radius: 8px;+ border: 0.5px solid var(--strong);+ background: var(--input);+ color: var(--text);+}++.notice {+ display: flex;+ flex-direction: column;+ gap: 8px;+ margin: 12px 14px 0;+ padding: 10px 12px;+ border-radius: 8px;+ border: 0.5px solid var(--warn-border);+ background: var(--warn-bg);+ color: var(--warn);+ font-size: 12.5px;+}diff --git a/extension/tsconfig.json b/extension/tsconfig.jsonnew file mode 100644index 0000000..319db3c--- /dev/null+++ b/extension/tsconfig.json@@ -0,0 +1,14 @@+{+ "compilerOptions": {+ "target": "ES2022",+ "module": "ESNext",+ "moduleResolution": "bundler",+ "lib": ["ES2022", "DOM", "DOM.Iterable"],+ "types": ["chrome"],+ "strict": true,+ "noEmit": true,+ "isolatedModules": true,+ "skipLibCheck": true+ },+ "include": ["src/**/*.ts", "../src/shared/browserBridge.ts", "../src/shared/types.ts"]+}diff --git a/package-lock.json b/package-lock.jsonindex a539360..2570363 100644--- a/package-lock.json+++ b/package-lock.json@@ -28,6 +28,7 @@"@electron-toolkit/tsconfig": "^2.0.0","@playwright/test": "^1.63.0","@tailwindcss/vite": "^4.3.3",+ "@types/chrome": "^0.3.4","@types/node": "^22.19.1","@types/react": "^19.2.7","@types/react-dom": "^19.2.3",@@ -2796,6 +2797,17 @@"@types/responselike": "^1.0.0"}},+ "node_modules/@types/chrome": {+ "version": "0.3.4",+ "resolved": "https://registry.npmjs.org/@types/chrome/-/chrome-0.3.4.tgz",+ "integrity": "sha512-dcySM5R3WAUVYFjylu6tvI4D03hPKjgAqk+tKZ/tm/vxL4mLgbnSsOEQ3J7V99qP/U3Oo9IORstJLmX2hPaDlA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/filesystem": "*",+ "@types/har-format": "*"+ }+ },"node_modules/@types/debug": {"version": "4.1.13","resolved": "https://registry.npmjs.org/@types/debug/-/debug-4.1.13.tgz",@@ -2813,6 +2825,23 @@"dev": true,"license": "MIT"},+ "node_modules/@types/filesystem": {+ "version": "0.0.36",+ "resolved": "https://registry.npmjs.org/@types/filesystem/-/filesystem-0.0.36.tgz",+ "integrity": "sha512-vPDXOZuannb9FZdxgHnqSwAG/jvdGM8Wq+6N4D/d80z+D4HWH+bItqsZaVRQykAn6WEVeEkLm2oQigyHtgb0RA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/filewriter": "*"+ }+ },+ "node_modules/@types/filewriter": {+ "version": "0.0.33",+ "resolved": "https://registry.npmjs.org/@types/filewriter/-/filewriter-0.0.33.tgz",+ "integrity": "sha512-xFU8ZXTw4gd358lb2jw25nxY9QAgqn2+bKKjKOYfNCzN4DKCFetK7sPtrlpg66Ywe3vWY9FNxprZawAh9wfJ3g==",+ "dev": true,+ "license": "MIT"+ },"node_modules/@types/fs-extra": {"version": "9.0.13","resolved": "https://registry.npmjs.org/@types/fs-extra/-/fs-extra-9.0.13.tgz",@@ -2823,6 +2852,13 @@"@types/node": "*"}},+ "node_modules/@types/har-format": {+ "version": "1.2.16",+ "resolved": "https://registry.npmjs.org/@types/har-format/-/har-format-1.2.16.tgz",+ "integrity": "sha512-fluxdy7ryD3MV6h8pTfTYpy/xQzCFC7m89nOH9y94cNqJ1mDIDPut7MnRHI3F6qRmh/cT2fUjG1MLdCNb4hE9A==",+ "dev": true,+ "license": "MIT"+ },"node_modules/@types/http-cache-semantics": {"version": "4.2.0","resolved": "https://registry.npmjs.org/@types/http-cache-semantics/-/http-cache-semantics-4.2.0.tgz",diff --git a/package.json b/package.jsonindex 5a9437c..0427257 100644--- a/package.json+++ b/package.json@@ -12,7 +12,8 @@"typecheck:node": "tsc --noEmit -p tsconfig.node.json --composite false","typecheck:web": "tsc --noEmit -p tsconfig.web.json --composite false","typecheck:e2e": "tsc -p tsconfig.e2e.json",- "typecheck": "npm run typecheck:node && npm run typecheck:web && npm run typecheck:e2e",+ "typecheck:extension": "tsc -p extension/tsconfig.json",+ "typecheck": "npm run typecheck:node && npm run typecheck:web && npm run typecheck:e2e && npm run typecheck:extension","prestart": "install-electron","start": "electron-vite preview","predev": "install-electron",@@ -23,6 +24,7 @@"build:win": "npm run build && electron-builder --win","build:mac": "electron-vite build && electron-builder --mac","build:linux": "electron-vite build && electron-builder --linux",+ "build:extension": "node extension/build.mjs","test:e2e": "playwright test","test:e2e:smoke": "playwright test --grep @smoke"},@@ -31,9 +33,9 @@"@electron-toolkit/preload": "^3.0.2","@electron-toolkit/utils": "^4.0.0","bittorrent-peerid": "2.0.2",- "fs-chunk-store": "5.0.1","class-variance-authority": "^0.7.1","cn": "^0.3.0",+ "fs-chunk-store": "5.0.1","koffi": "^2.16.3","lucide-react": "^1.47.0","parse-torrent": "11.0.24",@@ -46,6 +48,7 @@"@electron-toolkit/tsconfig": "^2.0.0","@playwright/test": "^1.63.0","@tailwindcss/vite": "^4.3.3",+ "@types/chrome": "^0.3.4","@types/node": "^22.19.1","@types/react": "^19.2.7","@types/react-dom": "^19.2.3",diff --git a/src/main/browserBridge.ts b/src/main/browserBridge.tsnew file mode 100644index 0000000..8e62847--- /dev/null+++ b/src/main/browserBridge.ts@@ -0,0 +1,257 @@+import { randomUUID } from 'node:crypto'+import { createServer, type IncomingMessage, type ServerResponse } from 'node:http'+import { app } from 'electron'+import {+ BRIDGE_API,+ BRIDGE_DEADLINE_MS,+ BRIDGE_PORTS,+ type BridgeAddRequest,+ type BridgeHandoff,+ type BridgePing+} from '../shared/browserBridge'+import type { BrowserContext, ProbeResult } from '../shared/types'+import { browserContextFrom, requestHeaders } from './download/browserContext'+import type { DownloadManager } from './download/downloadManager'+import { probeUrl } from './download/probe'+import type { Offer } from './openLinks'+import { loadSettings, saveSettings } from './settings'++// HTTP on 127.0.0.1 works in every browser with nothing to register. There's no pairing: nothing+// here starts a download without the user, web pages can't get in (see handle), and a program on+// this computer could already do more.++const MAX_BODY_BYTES = 64 * 1024+// The extension confirms within milliseconds of an answer; an unconfirmed offer is dropped.+const HANDOFF_MS = 15_000+// Any extension's origin: Firefox gives each install its own id, so ours can't be pinned.+const EXTENSION_ORIGIN = /^(chrome|moz)-extension:\/\/[a-z0-9-]+$/i++export interface BridgeHost {+ manager: DownloadManager+ offer: (offer: Offer) => void+}++let host: BridgeHost | null = null+let listeningOn: number | null = null+const handoffs = new Map<string, Offer>()+let extensionUsed = false++/** Once an extension has connected, closing the window keeps Plexo in the tray, where the+ * browser can still reach it. */+export function keepsRunningForBrowser(): boolean {+ return listeningOn !== null && extensionUsed+}++export async function startBridge(bridgeHost: BridgeHost): Promise<void> {+ host = bridgeHost+ extensionUsed = (await loadSettings()).browserExtensionUsed === true+ for (const port of BRIDGE_PORTS) {+ const server = createServer(+ (req, res) => void handle(req, res, port).catch(() => end(res, 500))+ )+ const listened = await new Promise<boolean>((resolve) => {+ server.once('error', () => resolve(false))+ server.listen(port, '127.0.0.1', () => resolve(true))+ })+ if (listened) {+ listeningOn = port+ return+ }+ }+ console.error(`[plexo] browser bridge: ports ${BRIDGE_PORTS.join(', ')} are all taken`)+}++function end(res: ServerResponse, code: number, headers: Record<string, string> = {}): void {+ if (!res.headersSent) res.writeHead(code, headers)+ res.end()+}++function json(+ res: ServerResponse,+ code: number,+ headers: Record<string, string>,+ body: unknown+): void {+ if (res.writableEnded || res.destroyed) return+ res.writeHead(code, { ...headers, 'Content-Type': 'application/json' })+ res.end(JSON.stringify(body))+}++async function handle(req: IncomingMessage, res: ServerResponse, port: number): Promise<void> {+ const origin = req.headers.origin+ // Host blocks DNS rebinding: a page whose domain resolves to 127.0.0.1 still sends its own name.+ // A missing Origin is allowed because a page's POST always sends one, and Firefox may leave it+ // off an extension's.+ const local = req.headers.host === `127.0.0.1:${port}` || req.headers.host === `localhost:${port}`+ if (!local || (origin && !EXTENSION_ORIGIN.test(origin))) {+ return end(res, 403)+ }+ const cors: Record<string, string> = origin+ ? {+ 'Access-Control-Allow-Origin': origin,+ 'Access-Control-Allow-Headers': 'Content-Type',+ 'Access-Control-Allow-Methods': 'GET, POST',+ Vary: 'Origin'+ }+ : {}+ if (req.method === 'OPTIONS') return end(res, 204, cors)+ const path = new URL(req.url ?? '/', 'http://local').pathname++ // JSON only: a page can't send JSON here without a CORS preflight, which only an extension's+ // origin passes.+ if (req.method === 'POST' && !/^application\/json\b/i.test(req.headers['content-type'] ?? '')) {+ return end(res, 415, cors)+ }+ if (req.method === 'GET' && path === '/ping') {+ noteExtension()+ return json(res, 200, cors, {+ app: 'plexo',+ version: app.getVersion(),+ api: BRIDGE_API+ } satisfies BridgePing)+ }+ if (req.method === 'POST' && path === '/add') {+ const request = addRequestFrom(await readJson(req))+ if (!request) return end(res, 400, cors)+ noteExtension()+ return add(request, res, cors)+ }+ if (req.method === 'POST' && path === '/confirm') {+ const body = await readJson(req)+ const token =+ typeof body === 'object' && body !== null ? (body as Record<string, unknown>).token : null+ const offer = typeof token === 'string' ? handoffs.get(token) : undefined+ if (!host || !offer || typeof token !== 'string') return end(res, 410, cors)+ handoffs.delete(token)+ host.offer(offer)+ return json(res, 200, cors, {})+ }+ end(res, 404, cors)+}++function noteExtension(): void {+ if (extensionUsed) return+ extensionUsed = true+ void saveSettings({ browserExtensionUsed: true }).catch(() => {})+}++async function readJson(req: IncomingMessage): Promise<unknown> {+ const chunks: Buffer[] = []+ let size = 0+ for await (const chunk of req as AsyncIterable<Buffer>) {+ size += chunk.length+ if (size > MAX_BODY_BYTES) return null+ chunks.push(chunk)+ }+ try {+ return JSON.parse(Buffer.concat(chunks).toString('utf-8'))+ } catch {+ return null+ }+}++function addRequestFrom(body: unknown): BridgeAddRequest | null {+ if (typeof body !== 'object' || body === null) return null+ const { url, browser, pageUrl, minBytes, fileName } = body as Record<string, unknown>+ if (typeof url !== 'string' || url.length > 8192 || !/^(https?:\/\/|magnet:\?)/i.test(url)) {+ return null+ }+ const context = browser === undefined ? undefined : browserContextFrom(browser)+ if (context === null) return null+ if (pageUrl !== undefined && !(typeof pageUrl === 'string' && /^https?:\/\//i.test(pageUrl))) {+ return null+ }+ if (minBytes !== undefined && !Number.isSafeInteger(minBytes)) return null+ if (+ fileName !== undefined &&+ // eslint-disable-next-line no-control-regex -- a name, never a path or a control character+ !(typeof fileName === 'string' && /^[^\x00-\x1f\x7f/\\]{1,255}$/.test(fileName))+ ) {+ return null+ }+ return {+ url,+ browser: context,+ pageUrl: pageUrl as string | undefined,+ minBytes: minBytes as number | undefined,+ fileName: fileName as string | undefined+ }+}++/** The probe, or why the browser should keep the download. */+async function checked(+ request: BridgeAddRequest,+ gone: Promise<void>+): Promise<ProbeResult | string> {+ let timer: NodeJS.Timeout | undefined+ try {+ // ponytail: the probe isn't cancelled, only no longer waited for; it ends at its own timeout.+ return await Promise.race([+ probeUrl(request.url, request.browser),+ new Promise<string>((resolve) => {+ timer = setTimeout(resolve, BRIDGE_DEADLINE_MS, 'The server took too long to answer.')+ }),+ gone.then(() => 'gone')+ ])+ } catch (error) {+ return error instanceof Error ? error.message : String(error)+ } finally {+ clearTimeout(timer)+ }+}++async function add(+ request: BridgeAddRequest,+ res: ServerResponse,+ cors: Record<string, string>+): Promise<void> {+ if (!host) return end(res, 503, cors)+ const keep = (reason: string): void => json(res, 422, cors, { reason })+ const hold = (offer: Offer): void => {+ const token = randomUUID()+ handoffs.set(token, offer)+ setTimeout(() => handoffs.delete(token), HANDOFF_MS).unref()+ json(res, 200, cors, { token } satisfies BridgeHandoff)+ }++ // A magnet link has nothing to check here: New download looks it up.+ if (/^magnet:/i.test(request.url)) return hold({ url: request.url })++ const gone = new Promise<void>((resolve) =>+ res.once('close', () => !res.writableFinished && resolve())+ )+ const checkedProbe = await checked(request, gone)+ const probe =+ typeof checkedProbe !== 'string' && checkedProbe.kind === 'http' && request.fileName+ ? { ...checkedProbe, suggestedFileName: request.fileName }+ : checkedProbe+ // The extension gave up and the browser kept the download: adding it too would make two. From+ // here on nothing awaits, so the answer can't come after the extension has stopped waiting.+ if (res.writableEnded || res.destroyed) return+ if (typeof probe === 'string') return keep(probe)+ if (+ probe.kind === 'http' &&+ request.minBytes !== undefined &&+ probe.totalBytes !== null &&+ probe.totalBytes < request.minBytes+ ) {+ return keep('smaller than the minimum size')+ }+ hold({+ url: request.url,+ probe,+ browser: request.browser,+ from: request.browser?.name,+ signedInTo: signedInTo(request, probe),+ resumes: probe.kind === 'http' ? host.manager.failedMatch(probe) : undefined+ })+}++/** The page's site rather than the file's, which is often a CDN's: drive.google.com, not+ * drive.usercontent.google.com. */+function signedInTo(request: BridgeAddRequest, probe: ProbeResult): string | undefined {+ const browser: BrowserContext | undefined = request.browser+ const fileUrl = new URL(probe.finalUrl)+ if (!browser || !requestHeaders(fileUrl, browser)['Cookie']) return undefined+ return new URL(request.pageUrl ?? browser.referer ?? fileUrl).hostname+}diff --git a/src/main/download/browserContext.ts b/src/main/download/browserContext.tsnew file mode 100644index 0000000..5577c60--- /dev/null+++ b/src/main/download/browserContext.ts@@ -0,0 +1,71 @@+import type { BrowserContext, BrowserCookie } from '../../shared/types'++const USER_AGENT = 'Plexo/1.0'++/** Called again for every redirect, so a site's session cookie never reaches the next host (its+ * CDN), while a cookie set for a whole domain still follows a hop within it. */+export function requestHeaders(url: URL, browser?: BrowserContext): Record<string, string> {+ const headers: Record<string, string> = { 'User-Agent': browser?.userAgent ?? USER_AGENT }+ if (browser?.referer) headers['Referer'] = browser.referer+ const cookie = browser ? cookieHeader(url, browser.cookies) : ''+ if (cookie) headers['Cookie'] = cookie+ return headers+}++/** RFC 6265 §5.4. */+function cookieHeader(url: URL, cookies: readonly BrowserCookie[]): string {+ const host = url.hostname.toLowerCase()+ const path = url.pathname || '/'+ return cookies+ .filter((cookie) => {+ const domain = cookie.domain.replace(/^\./, '').toLowerCase()+ const domainMatches = cookie.hostOnly+ ? host === domain+ : host === domain || host.endsWith(`.${domain}`)+ const pathMatches =+ path === cookie.path ||+ (path.startsWith(cookie.path) &&+ (cookie.path.endsWith('/') || path[cookie.path.length] === '/'))+ return domainMatches && pathMatches && (!cookie.secure || url.protocol === 'https:')+ })+ .sort((a, b) => b.path.length - a.path.length)+ .map((cookie) => (cookie.name ? `${cookie.name}=${cookie.value}` : cookie.value))+ .join('; ')+}++const MAX_COOKIES = 500+const MAX_TEXT = 8192+// A line break would start a header of its own, and `;` separates cookies.+// eslint-disable-next-line no-control-regex -- control characters are exactly what's refused+const UNSAFE = /[\x00-\x1f\x7f]/+// eslint-disable-next-line no-control-regex -- as above+const UNSAFE_IN_COOKIE = /[\x00-\x1f\x7f;]/++const isText = (value: unknown, unsafe = UNSAFE): value is string =>+ typeof value === 'string' && value.length <= MAX_TEXT && !unsafe.test(value)++/** It comes from outside Plexo (the extension, or a manifest read back from disk), so only known+ * fields are kept. */+export function browserContextFrom(value: unknown): BrowserContext | null {+ if (typeof value !== 'object' || value === null) return null+ const { cookies, referer, userAgent, name } = value as Record<string, unknown>+ if (!Array.isArray(cookies) || cookies.length > MAX_COOKIES) return null+ if (referer !== undefined && !(isText(referer) && /^https?:\/\//i.test(referer))) return null+ if (userAgent !== undefined && !isText(userAgent)) return null+ if (name !== undefined && !(isText(name) && name.length <= 40)) return null+ const checked: BrowserCookie[] = []+ for (const cookie of cookies) {+ if (typeof cookie !== 'object' || cookie === null) return null+ const { name, value, domain, hostOnly, path, secure } = cookie as Record<string, unknown>+ if (!isText(name, UNSAFE_IN_COOKIE) || !isText(value, UNSAFE_IN_COOKIE)) return null+ if (!isText(domain) || !isText(path) || !path.startsWith('/')) return null+ if (typeof hostOnly !== 'boolean' || typeof secure !== 'boolean') return null+ checked.push({ name, value, domain, hostOnly, path, secure })+ }+ return {+ cookies: checked,+ ...(referer !== undefined && { referer }),+ ...(userAgent !== undefined && { userAgent }),+ ...(name !== undefined && { name })+ }+}diff --git a/src/main/download/chunkDownloader.ts b/src/main/download/chunkDownloader.tsindex 23f11cf..fff22fb 100644--- a/src/main/download/chunkDownloader.ts+++ b/src/main/download/chunkDownloader.ts@@ -2,11 +2,14 @@ import type { Writable } from 'node:stream'import type { ClientRequest, IncomingMessage } from 'node:http'import { URL } from 'node:url'import { asConnectionError, type StreamConnection } from '../network/routes'+import type { BrowserContext } from '../../shared/types'import { testKnobs } from '../testKnobs'+import { requestHeaders } from './browserContext'import { compareVersion, type FileVersion, type VersionCheck } from './fileVersion'export interface ChunkDownloadOptions {url: string+ browser?: BrowserContextrangeStart: number/** null = open-ended range, download to end of file. */rangeEnd: number | null@@ -125,6 +128,7 @@ function versionOf(res: IncomingMessage, served: ServedRange | null): FileVersioexport function downloadChunk(options: ChunkDownloadOptions): Promise<void> {const {url,+ browser,rangeStart,rangeEnd,connection,@@ -201,15 +205,14 @@ export function downloadChunk(options: ChunkDownloadOptions): Promise<void> {// The whole file from the start needs no Range at all — and an empty file would answer// `bytes=0-` with 416, since it has no byte 0 to start from.- const headers: Record<string, string> = { 'User-Agent': 'Plexo/1.0' }- if (rangeStart > 0 || rangeEnd !== null) {- headers['Range'] =- rangeEnd === null ? `bytes=${rangeStart}-` : `bytes=${rangeStart}-${rangeEnd}`- }+ const range: Record<string, string> =+ rangeStart > 0 || rangeEnd !== null+ ? { Range: rangeEnd === null ? `bytes=${rangeStart}-` : `bytes=${rangeStart}-${rangeEnd}` }+ : {}const attempt = (targetUrl: URL, redirectsLeft: number): void => {void connection- .request(targetUrl, headers, signal)+ .request(targetUrl, { ...requestHeaders(targetUrl, browser), ...range }, signal).then(({ req, res, sentAt }) => {if (settled) {req.destroy()@@ -387,12 +390,13 @@ export function fetchRange(url: string,start: number,end: number,- connection: StreamConnection+ connection: StreamConnection,+ browser?: BrowserContext): Promise<{ body: Buffer; version: FileVersion }> {return new Promise((resolve, reject) => {const attempt = (target: URL, redirectsLeft: number): void => {void connection- .request(target, { 'User-Agent': 'Plexo/1.0', Range: `bytes=${start}-${end}` })+ .request(target, { ...requestHeaders(target, browser), Range: `bytes=${start}-${end}` }).then(({ req, res }) => {req.on('error', reject)const status = res.statusCode ?? 0diff --git a/src/main/download/downloadManager.ts b/src/main/download/downloadManager.tsindex 96e28a7..7819a6c 100644--- a/src/main/download/downloadManager.ts+++ b/src/main/download/downloadManager.ts@@ -4,12 +4,13 @@ import { randomUUID } from 'node:crypto'import { lstat, readFile, readdir, rename, rm, stat, statfs, writeFile } from 'node:fs/promises'import { basename, dirname, isAbsolute, join, sep } from 'node:path'import type { BrowserWindow } from 'electron'-import { app, Notification, powerSaveBlocker, shell } from 'electron'+import { app, Notification, powerSaveBlocker, safeStorage, shell } from 'electron'import { IpcChannels } from '../../shared/ipc-channels'import {DOWNLOADS_AT_ONCE,SPEED_HISTORY_SECONDS,type AppSettings,+ type BrowserContext,type DownloadNetwork,type DownloadState,type DownloadStatus,@@ -21,6 +22,7 @@ import {type HttpDownloadState,type NetworkInterfaceInfo,type NetworkStatus,+ type HttpProbeResult,type StartDownloadRequest,type StartHttpDownloadRequest,type StartTorrentDownloadRequest,@@ -35,12 +37,14 @@ import { loadSettings } from '../settings'import { addToHistory, findInHistory, removeFromHistory } from './history'import { testKnobs } from '../testKnobs'import { DownloadFile } from './downloadFile'-import { HttpTransfer, splittable } from './httpTransfer'+import { compareSamples, HttpTransfer, splittable } from './httpTransfer'+import { normalizeEtag } from './fileVersion'import { ensureDirectory, pathExists, reserveDestinationPath } from './paths'import { planBlocks, planDownload, planPieces } from './plan'import { restoreBlocks, restorePieces, saveBlocks, type SavedBlocks } from './savedProgress'import { chosenFiles, finishedFiles, wantedPieces } from './torrent/files'import { probeUrl } from './probe'+import { browserContextFrom } from './browserContext'import { describeTorrent, probedTorrentFile } from './torrent/metadata'import { TorrentDestination } from './torrent/torrentDestination'import { TorrentTransfer } from './torrent/torrentTransfer'@@ -61,7 +65,8 @@ import {compatibleInterfaces,NoCompatibleRouteError,resolveTargetWithin,- targetHost+ targetHost,+ StreamConnection} from '../network/routes'interface RuntimeFields {@@ -115,6 +120,8 @@ interface PersistedDownloadBase {publicationPath?: stringpublicationIdentity?: { dev: number; ino: number }requestPayload: StartDownloadRequest+ /** Kept apart from requestPayload, sealed (see sealBrowser). */+ browser?: string}type PersistedState =@@ -125,6 +132,46 @@ type PersistedDownload = PersistedDownloadBase & {state: PersistedState} & SavedBlocks+/** Cookies are never written in the clear. Without a keychain (Linux falls back to a fixed key)+ * they aren't saved at all, and a download resumed after a restart goes without them. */+function sealBrowser(browser: BrowserContext): string | undefined {+ if (!safeStorage.isEncryptionAvailable()) return undefined+ if (process.platform === 'linux' && safeStorage.getSelectedStorageBackend() === 'basic_text') {+ return undefined+ }+ // The keychain can refuse; the download is still saved, it just won't keep the sign-in.+ try {+ return safeStorage.encryptString(JSON.stringify(browser)).toString('base64')+ } catch {+ return undefined+ }+}++function unsealBrowser(sealed: string): BrowserContext | undefined {+ try {+ return (+ browserContextFrom(JSON.parse(safeStorage.decryptString(Buffer.from(sealed, 'base64')))) ??+ undefined+ )+ } catch {+ return undefined+ }+}++/** A finished download drops its cookies: nothing will ask the server for it again. */+function savedRequest(+ runtime: DownloadRuntime+): Pick<PersistedDownloadBase, 'requestPayload' | 'browser'> {+ if (runtime.kind !== 'http' || !runtime.requestPayload.browser) {+ return { requestPayload: runtime.requestPayload }+ }+ const { browser, ...requestPayload } = runtime.requestPayload+ return {+ requestPayload,+ browser: runtime.state.status === 'completed' ? undefined : sealBrowser(browser)+ }+}+const UI_UPDATE_MS = 200/** How often a running download takes stock (see run). */const TICK_MS = 500@@ -301,6 +348,8 @@ async function ensureDiskSpace(destinationDir: string, requiredBytes: number): Pexport class DownloadManager {private runtimes = new Map<string, DownloadRuntime>()+ /** Downloads whose new link is being checked: two at once could both pass and both resume. */+ private relinking = new Set<string>()private readonly initialization: Promise<void>private suspending = false/** Each network's addresses as last seen, by id: what tells a network that has changed. */@@ -601,7 +650,10 @@ export class DownloadManager {id: string,persisted: PersistedDownload): Promise<DownloadRuntime | null> {- const { requestPayload } = persisted+ const requestPayload: StartDownloadRequest =+ persisted.requestPayload.kind === 'http' && typeof persisted.browser === 'string'+ ? { ...persisted.requestPayload, browser: unsealBrowser(persisted.browser) }+ : persisted.requestPayloadconst saved: SavedBlocks = { progress: persisted.progress, complete: persisted.complete }let state: DownloadStatelet runtime: DownloadRuntime@@ -750,6 +802,11 @@ export class DownloadManager {async start(requestPayload: StartDownloadRequest): Promise<string> {await this.initialization+ if (requestPayload.kind === 'http' && requestPayload.browser !== undefined) {+ const browser = browserContextFrom(requestPayload.browser)+ if (!browser) throw new Error('The browser’s details for this download couldn’t be read.')+ requestPayload = { ...requestPayload, browser }+ }const available = await this.networks.refresh()const selected = available.filter((iface) => requestPayload.interfaceIds.includes(iface.id))@@ -846,7 +903,10 @@ export class DownloadManager {blocks,totalBlocks: blocks.length,blockSizeBytes,- startedAt: Date.now()+ startedAt: Date.now(),+ ...(requestPayload.browser && {+ fromBrowser: requestPayload.browser.name ?? 'your browser'+ })}runtime = this.newHttpRuntime(state,@@ -909,18 +969,48 @@ export class DownloadManager {}/** Gives a download whose link stopped working (a signed link ran out, say) a fresh link to the- * same file, and resumes it from where it stopped. The file must be as big as before; whether- * its bytes are the same is checked as on any resume (see HttpTransfer's version check). */- async relink(id: string, url: string): Promise<void> {+ * same file, and resumes it from where it stopped. `given`: a link already checked, with the+ * browser sign-in it came with. */+ async relink(+ id: string,+ url: string,+ given?: { probe?: HttpProbeResult; browser?: BrowserContext }+ ): Promise<void> {const runtime = this.runtimes.get(id)if (runtime?.kind !== 'http') throw new Error('Only web downloads support replacing a link.')- const { status, resumable, totalBytes } = runtime.state- if (status !== 'error' && status !== 'paused') {- throw new Error('Pause the download before replacing its link.')+ const replaceable = (): boolean => {+ const { status, resumable } = runtime.state+ return (+ this.runtimes.get(id) === runtime &&+ resumable !== false &&+ (status === 'error' || status === 'paused')+ )+ }+ if (runtime.state.resumable === false) {+ throw new Error('This download can’t resume. Start it again.')}- if (resumable === false) throw new Error('This download can’t resume. Start it again.')- const probe = await probeUrl(url)+ if (!replaceable()) throw new Error('Pause the download before replacing its link.')+ if (this.relinking.has(id)) throw new Error('A new link for this download is being checked.')+ this.relinking.add(id)+ try {+ await this.replaceLink(runtime, url, replaceable, given)+ } finally {+ this.relinking.delete(id)+ }+ }++ private async replaceLink(+ runtime: HttpDownloadRuntime,+ url: string,+ replaceable: () => boolean,+ given?: { probe?: HttpProbeResult; browser?: BrowserContext }+ ): Promise<void> {+ // A fresh link from the same site usually needs the same sign-in, so the old one carries over+ // unless the browser sent a new one.+ const browser = given?.browser ?? runtime.requestPayload.browser+ const probe = given?.probe ?? (await probeUrl(url, browser))if (probe.kind !== 'http') throw new Error('That isn’t a link to a file')+ const { totalBytes } = runtime.stateif ((probe.totalBytes ?? 0) !== totalBytes) {throw new Error(`That link is to a different file: ${formatGigabytes(probe.totalBytes ?? 0)}, not ${formatGigabytes(totalBytes)}`@@ -931,10 +1021,67 @@ export class DownloadManager {'This server doesn’t support resuming downloads. Try another link to the same file.')}+ // An ETag or date from another link proves nothing about its bytes: two different files can+ // share them. Once resumed, only a label this download hasn't seen would make it compare+ // bytes, so they're compared now, before anything from the new link is written.+ const verdict = await this.compareWithDisk(runtime, probe.finalUrl, browser)+ if (verdict === 'different') {+ throw new Error('That link is to a different file: its bytes don’t match what’s downloaded.')+ }+ if (verdict === 'unknown') {+ throw new Error('Plexo couldn’t check that link against what’s downloaded. Try again.')+ }+ if (!replaceable()) throw new Error('The download changed while its new link was checked.')runtime.requestPayload.url = probe.finalUrl+ runtime.requestPayload.browser = browserruntime.state.url = probe.finalUrlawait this.persistNow(runtime)- this.resume(id)+ this.resume(runtime.state.id)+ }++ private async compareWithDisk(+ runtime: HttpDownloadRuntime,+ url: string,+ browser: BrowserContext | undefined+ ): Promise<'same' | 'different' | 'unknown'> {+ // Nothing downloaded, nothing a different file could spoil.+ if (!runtime.blocks.some((block) => block.bytesDownloaded > 0)) return 'same'+ const available = await this.networks.refresh()+ const enabled = (iface: NetworkInterfaceInfo): boolean =>+ runtime.state.networks.some((network) => network.id === iface.id && network.enabled)+ const network = available.find(enabled) ?? available[0]+ if (!network) return 'unknown'+ const connection = new StreamConnection(() => network, {+ timeoutMs: testKnobs.stallTimeoutMs,+ connectTimeoutMs: testKnobs.connectTimeoutMs+ })+ try {+ return await compareSamples(runtime, url, browser, connection)+ } finally {+ connection.close()+ }+ }++ /** A failed download this link looks like the same file as: same name, size and strong ETag.+ * Only a suggestion for the user, who decides; relink then compares the bytes. */+ failedMatch(probe: HttpProbeResult): { id: string; fileName: string } | undefined {+ const strong = (etag: string | null): etag is string => etag !== null && !/^W\//i.test(etag)+ if (!strong(probe.etag) || !probe.totalBytes) return undefined+ const etag = normalizeEtag(probe.etag)+ for (const runtime of this.runtimes.values()) {+ if (runtime.kind !== 'http' || runtime.state.status !== 'error') continue+ const { requestPayload: request, state } = runtime+ if (+ state.resumable !== false &&+ state.totalBytes === probe.totalBytes &&+ request.suggestedFileName === probe.suggestedFileName &&+ strong(request.etag) &&+ normalizeEtag(request.etag) === etag+ ) {+ return { id: state.id, fileName: state.fileName }+ }+ }+ return undefined}resume(id: string): void {@@ -1688,7 +1835,7 @@ export class DownloadManager {partialPath: runtime.file.path,publicationPath: runtime.publicationPath,publicationIdentity: runtime.publicationIdentity,- requestPayload: runtime.requestPayload+ ...savedRequest(runtime)}if (runtime.state.status === 'downloading' || runtime.state.status === 'paused') {await runtime.file.sync()diff --git a/src/main/download/httpTransfer.ts b/src/main/download/httpTransfer.tsindex c709886..10c5291 100644--- a/src/main/download/httpTransfer.ts+++ b/src/main/download/httpTransfer.ts@@ -1,4 +1,5 @@import type {+ BrowserContext,HttpBlockState,HttpStreamState,DownloadNetwork,@@ -216,6 +217,59 @@ const MAX_SAMPLES = 8* request may land on another one, so take a few tries at reaching it. */const SAMPLE_TRIES = 4+/**+ * Re-fetches a spread of the bytes `target` already has on disk from `url` and compares them.+ * 'unknown' when there's nothing on disk to compare yet, or the samples couldn't be fetched.+ * `label`: only a reply from a server presenting it counts.+ */+export async function compareSamples(+ target: Pick<HttpTransferTarget, 'blocks' | 'file'>,+ url: string,+ browser: BrowserContext | undefined,+ connection: StreamConnection,+ label?: FileVersion+): Promise<'same' | 'different' | 'unknown'> {+ const withData = target.blocks.filter((block) => block.bytesDownloaded > 0)+ const step = Math.max(1, withData.length / MAX_SAMPLES)+ const picks = Array.from(+ { length: Math.min(MAX_SAMPLES, withData.length) },+ (_, i) => withData[Math.floor(i * step)]+ )++ let compared = 0+ for (const block of picks) {+ let local: Buffer+ try {+ local = await target.file.read(+ block.rangeStart,+ Math.min(SAMPLE_BYTES, block.bytesDownloaded)+ )+ } catch {+ continue+ }+ if (local.length === 0) continue++ for (let tries = 0; tries < SAMPLE_TRIES; tries++) {+ try {+ const remote = await fetchRange(+ url,+ block.rangeStart,+ block.rangeStart + local.length - 1,+ connection,+ browser+ )+ if (label && compareVersion([label], remote.version).kind !== 'same') continue+ if (!remote.body.equals(local)) return 'different'+ compared += 1+ break+ } catch {+ return 'unknown'+ }+ }+ }+ return compared > 0 ? 'same' : 'unknown'+}+/*** Fetches a download over HTTP: streams, each one connection to the server through one network,* taking blocks from the scheduler and writing them into the staging file at their own offsets.@@ -655,6 +709,7 @@ export class HttpTransfer implements Transfer {attempt.startedAt = Date.now()await downloadChunk({url: this.runtime.requestPayload.url,+ browser: this.runtime.requestPayload.browser,rangeStart: block.rangeStart + attempt.startOffset,rangeEnd: block.rangeEnd,connection: self.connection,@@ -1140,47 +1195,9 @@ export class HttpTransfer implements Transfer {seen: FileVersion): Promise<'same' | 'different' | 'unknown'> {if (compareVersion(this.acceptedVersions, seen).kind === 'same') return 'same'-// Every byte on disk came from an accepted version: mismatched responses are rejected- // before anything is written.- const withData = this.runtime.blocks.filter((block) => block.bytesDownloaded > 0)- const step = Math.max(1, withData.length / MAX_SAMPLES)- const picks = Array.from(- { length: Math.min(MAX_SAMPLES, withData.length) },- (_, i) => withData[Math.floor(i * step)]- )-- let compared = 0- for (const block of picks) {- let local: Buffer- try {- local = await this.runtime.file.read(- block.rangeStart,- Math.min(SAMPLE_BYTES, block.bytesDownloaded)- )- } catch {- continue- }- if (local.length === 0) continue-- for (let tries = 0; tries < SAMPLE_TRIES; tries++) {- try {- const remote = await fetchRange(- this.runtime.requestPayload.url,- block.rangeStart,- block.rangeStart + local.length - 1,- connection- )- // A reply from a server still presenting an accepted label proves nothing here.- if (compareVersion([seen], remote.version).kind !== 'same') continue- if (!remote.body.equals(local)) return 'different'- compared += 1- break- } catch {- return 'unknown'- }- }- }- return compared > 0 ? 'same' : 'unknown'+ // before anything is written. A reply still presenting an accepted label proves nothing.+ const { url, browser } = this.runtime.requestPayload+ return compareSamples(this.runtime, url, browser, connection, seen)}}diff --git a/src/main/download/probe.ts b/src/main/download/probe.tsindex 90065b5..036d0ac 100644--- a/src/main/download/probe.ts+++ b/src/main/download/probe.ts@@ -2,8 +2,9 @@ import { request as httpRequest } from 'node:http'import { request as httpsRequest } from 'node:https'import { isAbsolute } from 'node:path'import { URL } from 'node:url'-import type { ProbeResult } from '../../shared/types'+import type { BrowserContext, ProbeResult } from '../../shared/types'import { testKnobs } from '../testKnobs'+import { requestHeaders } from './browserContext'import { parseContentDispositionFilename } from './contentDisposition'import {describeTorrent,@@ -13,7 +14,6 @@ import {} from './torrent/metadata'const MAX_REDIRECTS = 5-const USER_AGENT = 'Plexo/1.0'// A server that accepts the connection and never answers would otherwise hang the probe — and// the link field's "Checking…" — forever. Same budget as a stalled chunk, for the whole probe:// redirects included, so a chain of slow hops can't stretch it.@@ -34,7 +34,11 @@ interface ProbeResponse {/** GET with a 1-byte range: cheaper than fetching the body, and unlike HEAD it* also tells us (via the 206 status) whether range requests actually work. */-function requestOneByte(url: URL, deadline: number): Promise<ProbeResponse> {+function requestOneByte(+ url: URL,+ deadline: number,+ browser: BrowserContext | undefined+): Promise<ProbeResponse> {return new Promise((resolve, reject) => {const requester = url.protocol === 'https:' ? httpsRequest : httpRequestconst req = requester(@@ -43,7 +47,7 @@ function requestOneByte(url: URL, deadline: number): Promise<ProbeResponse> {hostname: url.hostname.replace(/^\[|\]$/g, ''),port: url.port || undefined,path: `${url.pathname}${url.search}`,- headers: { 'User-Agent': USER_AGENT, Range: 'bytes=0-0' }+ headers: { ...requestHeaders(url, browser), Range: 'bytes=0-0' }},(res) => {clearTimeout(timer)@@ -80,14 +84,15 @@ function fileNameFromHeaders(headers: Headers, url: URL): string {}async function requestFollowingRedirects(- rawUrl: string+ rawUrl: string,+ browser: BrowserContext | undefined): Promise<{ current: URL; response: ProbeResponse | null }> {let current = new URL(rawUrl)let response: ProbeResponse | null = nullconst deadline = Date.now() + PROBE_TIMEOUT_MSfor (let redirect = 0; redirect <= MAX_REDIRECTS; redirect += 1) {- response = await requestOneByte(current, deadline)+ response = await requestOneByte(current, deadline, browser)if (response.statusCode >= 300 && response.statusCode < 400) {const location = headerValue(response.headers, 'location')if (!location) break@@ -107,14 +112,15 @@ function isTorrentLink(headers: Headers, url: URL): boolean {}/** What a link would download: a file over HTTP(S), or a torrent — a magnet link, a link to a- * .torrent, or the path of a .torrent on this computer (opened or dropped on the window). */-export async function probeUrl(rawUrl: string): Promise<ProbeResult> {+ * .torrent, or the path of a .torrent on this computer (opened or dropped on the window).+ * `browser`: what the browser it came from sends with it (see BrowserContext). */+export async function probeUrl(rawUrl: string, browser?: BrowserContext): Promise<ProbeResult> {if (/^magnet:/i.test(rawUrl)) return describeTorrent(await fetchMagnetMetadata(rawUrl), rawUrl)if (isAbsolute(rawUrl) && /\.torrent$/i.test(rawUrl)) {return describeTorrent(await readTorrentFile(rawUrl), rawUrl)}- const { current, response } = await requestFollowingRedirects(rawUrl)+ const { current, response } = await requestFollowingRedirects(rawUrl, browser)// An empty file can't satisfy a request for its first byte: the server answers 416 and gives// the size as `bytes */0`. That's a valid, empty download, not an error.@@ -141,7 +147,12 @@ export async function probeUrl(rawUrl: string): Promise<ProbeResult> {if (isTorrentLink(response.headers, current)) {const finalUrl = current.toString()- return describeTorrent(await downloadTorrentFile(finalUrl, PROBE_TIMEOUT_MS), finalUrl)+ const torrentFile = await downloadTorrentFile(+ finalUrl,+ PROBE_TIMEOUT_MS,+ requestHeaders(current, browser)+ )+ return describeTorrent(torrentFile, finalUrl)}const contentRange = headerValue(response.headers, 'content-range')diff --git a/src/main/download/torrent/metadata.ts b/src/main/download/torrent/metadata.tsindex 5bf3a0d..d2e8b02 100644--- a/src/main/download/torrent/metadata.ts+++ b/src/main/download/torrent/metadata.ts@@ -63,10 +63,15 @@ export async function readTorrentFile(path: string): Promise<Uint8Array> {}}-/** A .torrent file a link points at. */-export async function downloadTorrentFile(url: string, timeoutMs: number): Promise<Uint8Array> {+/** A .torrent file a link points at. `headers` are for `url`: on a redirect to another origin,+ * fetch drops their Cookie. */+export async function downloadTorrentFile(+ url: string,+ timeoutMs: number,+ headers: Record<string, string>+): Promise<Uint8Array> {const response = await fetch(url, {- headers: { 'User-Agent': 'Plexo/1.0' },+ headers,signal: AbortSignal.timeout(timeoutMs)})if (!response.ok || !response.body) {diff --git a/src/main/index.ts b/src/main/index.tsindex 4ad0f2d..cb693e2 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -1,9 +1,10 @@import { electronApp, is, optimizer } from '@electron-toolkit/utils'-import { app, BrowserWindow, nativeTheme, shell } from 'electron'+import { app, BrowserWindow, Menu, nativeImage, nativeTheme, shell, Tray } from 'electron'import { join } from 'path'import icon from '../../resources/icon-dark.png?asset'import { registerIpcHandlers } from './ipc/handlers'-import { acceptedLink, linkFromArgs, offerLink } from './openLinks'+import { keepsRunningForBrowser, startBridge } from './browserBridge'+import { acceptedLink, bringForward, linkFromArgs, offerLink } from './openLinks'import { loadThemeSource, migrateLegacyNetworkPreferences } from './settings'import { testKnobs } from './testKnobs'import type { DownloadManager } from './download/downloadManager'@@ -23,19 +24,27 @@ if (!app.requestSingleInstanceLock()) app.exit(0)let mainWindow: BrowserWindow | null = nulllet downloadManager: DownloadManager | null = nulllet quitAfterSuspending = false+let tray: Tray | null = null++/** Only once the app is ready. */+function ensureWindow(): BrowserWindow {+ if (!mainWindow || mainWindow.isDestroyed()) createWindow()+ return mainWindow as BrowserWindow+}/** A link the OS handed over goes to the window's link field (see openLinks.ts). */function offer(candidate: string): void {const link = acceptedLink(candidate)if (!link) return- offerLink(link, mainWindow)+ // Before the app is ready the link waits; the window takes it once it opens.+ offerLink({ url: link }, app.isReady() ? ensureWindow() : null)}+// A plexo:// link from the browser extension arrives here too, with no link in it.app.on('second-instance', (_event, argv) => {const link = linkFromArgs(argv)if (link) return offer(link)- if (mainWindow?.isMinimized()) mainWindow.restore()- mainWindow?.focus()+ bringForward(ensureWindow())})// macOS hands links over as events, and may do so before the app is ready.app.on('open-url', (event, url) => {@@ -130,6 +139,13 @@ app.whenReady().then(async () => {})downloadManager = registerIpcHandlers(() => mainWindow)+ void startBridge({+ manager: downloadManager,+ offer: (link) => offerLink(link, ensureWindow())+ }).catch((error) => console.error('[plexo] browser bridge failed to start', error))+ // Unlike magnet:, plexo:// is Plexo's own, so registering it takes nothing from another app. A+ // development build has no fixed path to register.+ if (app.isPackaged) app.setAsDefaultProtocolClient('plexo')nativeTheme.on('updated', () => {mainWindow?.setBackgroundColor(nativeTheme.shouldUseDarkColors ? '#1c1c1e' : '#ffffff')@@ -162,7 +178,18 @@ app.on('before-quit', (event) => {})app.on('window-all-closed', () => {- if (process.platform !== 'darwin') {- app.quit()- }+ if (process.platform === 'darwin') return+ if (!keepsRunningForBrowser()) return app.quit()+ // Kept running in the tray, so the browser extension can still reach it.+ if (tray) return+ tray = new Tray(nativeImage.createFromPath(icon).resize({ width: 16, height: 16 }))+ tray.setToolTip('Plexo')+ tray.on('click', () => bringForward(ensureWindow()))+ tray.setContextMenu(+ Menu.buildFromTemplate([+ { label: 'Open Plexo', click: () => bringForward(ensureWindow()) },+ { type: 'separator' },+ { label: 'Quit Plexo', click: () => app.quit() }+ ])+ )})diff --git a/src/main/ipc/handlers.ts b/src/main/ipc/handlers.tsindex c07b74a..b0c2299 100644--- a/src/main/ipc/handlers.ts+++ b/src/main/ipc/handlers.ts@@ -23,7 +23,7 @@ import { getDefaultDownloadsDir, getHomeDir } from '../download/paths'import { listHistory } from '../download/history'import { probeUrl } from '../download/probe'import { deviceBindingSupported } from '../network/deviceBinding'-import { takePendingLink } from '../openLinks'+import { pendingLink, pendingLinks, releaseLink } from '../openLinks'import { NetworkMonitor } from '../network/interfaces'import { loadSettings, saveSettings } from '../settings'import { testKnobs } from '../testKnobs'@@ -181,13 +181,31 @@ export function registerIpcHandlers(getWindow: () => BrowserWindow | null): Downreturn result.filePaths[0]})- handle('takePendingLink', async () => takePendingLink())+ handle('pendingLinks', async () => pendingLinks())+ handle('resumeFromLink', async (_event, linkId, downloadId) => {+ const link = pendingLink(linkId)+ if (link?.probe?.kind !== 'http') throw new Error('That download is no longer waiting.')+ await manager.relink(downloadId, link.probe.finalUrl, {+ probe: link.probe,+ browser: link.browser+ })+ releaseLink(linkId)+ })+ handle('dismissLink', async (_event, id) => releaseLink(id))handle('readClipboardText', async () => clipboard.readText())handle('revealDownload', async (_event, id) => manager.reveal(id))- handle('startDownload', async (_event, request) => manager.start(request))+ // The browser's sign-in is attached here, so it never passes through the window.+ handle('startDownload', async (_event, request, linkId) => {+ const browser = linkId === undefined ? undefined : pendingLink(linkId)?.browser+ const id = await manager.start(+ browser && request.kind === 'http' ? { ...request, browser } : request+ )+ if (linkId !== undefined) releaseLink(linkId)+ return id+ })handle('listDownloads', async () => manager.listDownloads())diff --git a/src/main/openLinks.ts b/src/main/openLinks.tsindex 960b52b..99424f4 100644--- a/src/main/openLinks.ts+++ b/src/main/openLinks.ts@@ -1,14 +1,22 @@+import { randomUUID } from 'node:crypto'import { statSync } from 'node:fs'import { isAbsolute } from 'node:path'-import type { BrowserWindow } from 'electron'+import { app, type BrowserWindow } from 'electron'import { IpcChannels } from '../shared/ipc-channels'+import type { BrowserContext, PendingLink } from '../shared/types'-// Links the OS hands Plexo — a magnet link clicked in a browser, a .torrent opened from the file-// manager — for the window's link field. They're never started on their own: the user still sees+// Links the OS hands Plexo (a magnet link clicked in a browser, a .torrent opened from the file+// manager) or the browser extension does. They're never started on their own: the user still sees// what the link is and presses Start.-/** The latest link handed over and not yet taken by the window. */-let pending: string | null = null+/** The browser's sign-in stays in main: the window never sees it. */+export interface Offer extends Omit<PendingLink, 'id'> {+ browser?: BrowserContext+}++// Every link is kept here until it's started or let go, not handed over once: the browser has+// already dropped its copy, and the window's own list is lost when the window closes or reloads.+const links = new Map<string, Offer>()/** A magnet link, or the path of a .torrent file that exists; anything else isn't taken. */export function acceptedLink(candidate: string): string | null {@@ -30,22 +38,42 @@ export function linkFromArgs(argv: readonly string[]): string | null {return null}-/**- * Hands `link` to the window: it's kept until the window takes it (takePendingLink), so one that- * arrives before the window is ready isn't lost. The window is brought forward.- */-export function offerLink(link: string, window: BrowserWindow | null): void {- pending = link- if (!window || window.isDestroyed()) return+/** Windows and macOS keep a background app from taking focus: Windows only flashes the taskbar+ * button unless the window is briefly on top, and macOS needs `steal`. */+export function bringForward(window: BrowserWindow): void {if (window.isMinimized()) window.restore()+ if (process.platform === 'win32') {+ window.setAlwaysOnTop(true)+ window.show()+ window.focus()+ window.setAlwaysOnTop(false)+ return+ }+ if (process.platform === 'darwin') app.focus({ steal: true })window.show()window.focus()+}++export function offerLink(offer: Offer, window: BrowserWindow | null): void {+ links.set(randomUUID(), offer)+ if (!window || window.isDestroyed()) return+ bringForward(window)window.webContents.send(IpcChannels.linkReceived)}-/** The link handed over, once: whoever takes it puts it in the link field. */-export function takePendingLink(): string | null {- const link = pending- pending = null- return link+/** Oldest first. */+export function pendingLinks(): PendingLink[] {+ return [...links].map(([id, offer]) => {+ const { browser, ...link } = offer+ void browser+ return { id, ...link }+ })+}++export function pendingLink(id: string): Offer | undefined {+ return links.get(id)+}++export function releaseLink(id: string): void {+ links.delete(id)}diff --git a/src/main/settings.ts b/src/main/settings.tsindex 3a346dd..16e6489 100644--- a/src/main/settings.ts+++ b/src/main/settings.ts@@ -88,6 +88,7 @@ function sanitizeSettings(parsed: unknown): AppSettings {if (parsed.speedUnit === 'bytes' || parsed.speedUnit === 'bits') {settings.speedUnit = parsed.speedUnit}+ if (parsed.browserExtensionUsed === true) settings.browserExtensionUsed = truereturn settings}diff --git a/src/preload/index.ts b/src/preload/index.tsindex cb6308d..a647389 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -34,8 +34,8 @@ const plexoApi = {pathForFile: (file: File) => webUtils.getPathForFile(file),readClipboardText: () => invoke('readClipboardText'),revealDownload: (id: string) => invoke('revealDownload', id),- startDownload: (request: IpcContract['startDownload']['args'][0]) =>- invoke('startDownload', request),+ startDownload: (request: IpcContract['startDownload']['args'][0], linkId?: string) =>+ invoke('startDownload', request, linkId),listDownloads: () => invoke('listDownloads'),listHistory: () => invoke('listHistory'),clearHistory: () => invoke('clearHistory'),@@ -54,9 +54,12 @@ const plexoApi = {removeDownload: (downloadId: string, options?: { trashFile?: boolean }) =>invoke('removeDownload', downloadId, options),checkForUpdate: () => invoke('checkForUpdate'),- takePendingLink: () => invoke('takePendingLink'),+ pendingLinks: () => invoke('pendingLinks'),+ resumeFromLink: (linkId: string, downloadId: string) =>+ invoke('resumeFromLink', linkId, downloadId),+ dismissLink: (id: string) => invoke('dismissLink', id),- /** The OS handed Plexo a link (a magnet link, a .torrent): takePendingLink() has it. */+ /** pendingLinks() has the new link. */onLinkReceived: (callback: () => void): (() => void) => {const listener = (): void => callback()ipcRenderer.on(IpcChannels.linkReceived, listener)diff --git a/src/renderer/src/components/FixLinkDialog.tsx b/src/renderer/src/components/FixLinkDialog.tsxindex 7f8525a..9efca83 100644--- a/src/renderer/src/components/FixLinkDialog.tsx+++ b/src/renderer/src/components/FixLinkDialog.tsx@@ -57,6 +57,9 @@ export function FixLinkDialog({<DialogDescription>{download &&`Paste a new link to the same file: ${download.fileName}${download.totalBytes > 0 ? ` (${formatBytes(download.totalBytes)})` : ''}. Plexo resumes from where the download stopped.`}+ {download?.kind === 'http' &&+ download.fromBrowser &&+ ` Or download it again in ${download.fromBrowser} and choose Resume it.`}</DialogDescription></DialogHeader><formdiff --git a/src/renderer/src/components/NewDownloadDialog.tsx b/src/renderer/src/components/NewDownloadDialog.tsxindex 052c95d..5f5dbec 100644--- a/src/renderer/src/components/NewDownloadDialog.tsx+++ b/src/renderer/src/components/NewDownloadDialog.tsx@@ -1,6 +1,6 @@import type { ProbeResult } from '@shared/types'import { cn } from 'cn'-import { AlertTriangle, FolderOpen, X } from 'lucide-react'+import { AlertTriangle, ChevronLeft, ChevronRight, FolderOpen, Globe, Lock, X } from 'lucide-react'import { useEffect, useRef, useState } from 'react'import { useFormatSpeedLimit } from '../hooks/useFormatSpeed'import { useNetworkUsage } from '../hooks/useNetworks'@@ -40,6 +40,7 @@ const labelClass = 'w-16 shrink-0 text-[12.5px] text-[var(--text-secondary)]'export function NewDownloadDialog(): React.JSX.Element {const open = useAppStore((store) => store.newDownloadOpen)const close = useAppStore((store) => store.closeNewDownload)+ const formKey = useAppStore((store) => store.formKey)return (<Dialog open={open} disablePointerDismissal onOpenChange={(next) => !next && close()}>@@ -47,8 +48,9 @@ export function NewDownloadDialog(): React.JSX.Element {showCloseButton={false}className="flex max-h-[calc(100%-2rem)] flex-col gap-0 p-0 sm:max-w-[560px]">- {/* Mounted only while open, so each opening starts fresh from the link field. */}- {open && <NewDownloadForm onDone={close} />}+ {/* Mounted only while open, and keyed by what it shows, so each opening and each+ download stacked in it starts fresh. */}+ {open && <NewDownloadForm key={formKey} onDone={close} />}</DialogContent></Dialog>)@@ -59,6 +61,13 @@ function NewDownloadForm({ onDone }: { onDone: () => void }): React.JSX.Elementconst homeDir = useAppStore((store) => store.homeDir)const url = useAppStore((store) => store.draftUrl)const setUrl = useAppStore((store) => store.setDraftUrl)+ const links = useAppStore((store) => store.links)+ const shownId = useAppStore((store) => store.shownId)+ const showLink = useAppStore((store) => store.showLink)+ const finishLink = useAppStore((store) => store.finishLink)+ const dropLink = useAppStore((store) => store.dropLink)+ const shownLink = links.find((link) => link.id === shownId)+ const position = shownLink ? links.indexOf(shownLink) : -1const destinationDir = useAppStore((store) => store.destinationDir)const setDestinationDir = useAppStore((store) => store.setDestinationDir)const full = useAppStore(@@ -114,12 +123,21 @@ function NewDownloadForm({ onDone }: { onDone: () => void }): React.JSX.Elementreturn}+ // Checking here would go without the browser's sign-in, and could spend a single-use link.+ const { links: stacked, shownId: shown } = useAppStore.getState()+ const given = stacked.find((link) => link.id === shown)+ if (given && given.url !== trimmed) dropLink(given.id, false)+ setFileNameOverride(null)+ setSkippedFiles([])+ if (given?.url === trimmed && given.probe) {+ setProbe({ status: 'ready', result: given.probe })+ return+ }+// Set once the link changes, cleared included: a magnet can take a while to answer, and its// answer is no longer wanted then.let stale = falsesetProbe({ status: 'probing' })- setFileNameOverride(null)- setSkippedFiles([])const timer = setTimeout(async () => {try {const result = await window.plexo.probeUrl(trimmed)@@ -135,7 +153,7 @@ function NewDownloadForm({ onDone }: { onDone: () => void }): React.JSX.Elementstale = trueclearTimeout(timer)}- }, [url])+ }, [url, dropLink])const ready = probe.status === 'ready' ? probe.result : nullconst torrent = ready?.kind === 'torrent' ? ready.torrent : null@@ -230,8 +248,27 @@ function NewDownloadForm({ onDone }: { onDone: () => void }): React.JSX.Elementif (path) setUrl(path)}+ const handleResume = async (): Promise<void> => {+ const link = shownLink+ const resumes = link?.resumes+ if (!link || !resumes) return+ setStarting(true)+ setStartError(null)+ try {+ await window.plexo.resumeFromLink(link.id, resumes.id)+ useAppStore.setState({ view: { name: 'download', id: resumes.id } })+ finishLink(link.id, true)+ } catch (error) {+ setStartError(describeError(error))+ setStarting(false)+ }+ }+const handleStart = async (): Promise<void> => {if (probe.status !== 'ready' || !canStart) return+ // Captured now: links can arrive and change what's shown while this starts.+ const linkId = shownLink?.id+ const form = useAppStore.getState().formKeysetStarting(true)setStartError(null)try {@@ -257,7 +294,8 @@ function NewDownloadForm({ onDone }: { onDone: () => void }): React.JSX.Element...common,kind: 'http',streamsPerNetwork: streamsChoice === 'auto' ? undefined : streamsChoice- }+ },+ linkId)// Remembered for the next download, like the folder. Not a single-stream pick: that's one// network because the file allows no more, not because the others were unwanted.@@ -273,10 +311,15 @@ function NewDownloadForm({ onDone }: { onDone: () => void }): React.JSX.Element// screen opens, unless it was only added to the queue.useAppStore.setState({startedUrl: url.trim(),- draftUrl: '',...(full ? {} : { view: { name: 'download', id } as const })})- onDone()+ if (linkId) {+ finishLink(linkId, true)+ } else if (useAppStore.getState().formKey === form) {+ // Only while this form is still the one shown: closing would dismiss a link that arrived.+ useAppStore.setState({ draftUrl: '' })+ onDone()+ }} catch (error) {setStartError(describeError(error))setStarting(false)@@ -293,8 +336,35 @@ function NewDownloadForm({ onDone }: { onDone: () => void }): React.JSX.Elementvoid handleStart()}}>- <div className="border-b-[0.5px] border-border px-5 py-4">- <DialogTitle className="text-[16px] font-semibold">New download</DialogTitle>+ <div className="flex items-center gap-2 border-b-[0.5px] border-border py-3 pr-3 pl-5">+ <DialogTitle className="flex-1 py-1 text-[16px] font-semibold">New download</DialogTitle>+ {shownLink && links.length > 1 && (+ <div className="flex items-center gap-1">+ <Button+ type="button"+ variant="ghost"+ size="icon-sm"+ aria-label="Previous download"+ disabled={position === 0}+ onClick={() => showLink(links[position - 1].id)}+ >+ <ChevronLeft />+ </Button>+ <span className="min-w-12 text-center font-mono text-[11.5px] text-muted-foreground tabular-nums">+ {position + 1} of {links.length}+ </span>+ <Button+ type="button"+ variant="ghost"+ size="icon-sm"+ aria-label="Next download"+ disabled={position === links.length - 1}+ onClick={() => showLink(links[position + 1].id)}+ >+ <ChevronRight />+ </Button>+ </div>+ )}</div><div className="flex min-h-0 flex-col gap-3.5 overflow-y-auto px-5 py-4">@@ -343,6 +413,40 @@ function NewDownloadForm({ onDone }: { onDone: () => void }): React.JSX.Element</Button></div>+ {shownLink?.from && (+ <div className="flex h-6 items-center gap-1.5 self-start rounded-full border-[0.5px] border-[var(--color-wifi-border)] bg-[var(--color-wifi-bg)] px-2.5 text-[12px] font-medium text-[var(--color-wifi-text)]">+ {shownLink.signedInTo ? (+ <Lock aria-hidden className="size-3" />+ ) : (+ <Globe aria-hidden className="size-3" />+ )}+ {[+ `From ${shownLink.from}`,+ shownLink.signedInTo && `with your ${shownLink.signedInTo} sign-in`+ ]+ .filter(Boolean)+ .join(' · ')}+ </div>+ )}++ {shownLink?.resumes && (+ <div className="flex items-center gap-3 rounded-lg border-[0.5px] border-border bg-card px-3 py-2 text-[12.5px]">+ <span className="min-w-0 flex-1">+ Same file as <span className="font-medium">{shownLink.resumes.fileName}</span>, which+ failed. Resume that instead?+ </span>+ <Button+ type="button"+ variant="secondary"+ size="sm"+ disabled={starting}+ onClick={() => void handleResume()}+ >+ Resume it+ </Button>+ </div>+ )}+{probe.status === 'probing' && (<div className="font-mono text-[11.5px] text-muted-foreground">Checking the link…</div>)}diff --git a/src/renderer/src/hooks/useOpenedLinks.ts b/src/renderer/src/hooks/useOpenedLinks.tsindex ba42d5f..80e9fee 100644--- a/src/renderer/src/hooks/useOpenedLinks.ts+++ b/src/renderer/src/hooks/useOpenedLinks.ts@@ -2,25 +2,16 @@ import { useEffect } from 'react'import { useAppStore } from '../store/useAppStore'import { acceptedLink } from '../utils/format'-/** Opens New download with a link the OS handed Plexo — a magnet link clicked, a .torrent opened- * — for the user to look at and start (see main/openLinks.ts). */+/** Opens New download with links handed to Plexo, for the user to look at and start. */export function useOpenedLinks(): void {- const openNewDownload = useAppStore((store) => store.openNewDownload)+ const receiveLinks = useAppStore((store) => store.receiveLinks)useEffect(() => {- const take = (): void => {- void window.plexo- .takePendingLink()- .then((link) => {- if (link) openNewDownload(link)- })- .catch(() => {})- }- const unsubscribe = window.plexo.onLinkReceived(take)- // One handed over before the window was ready to hear of it.- take()+ const unsubscribe = window.plexo.onLinkReceived(() => void receiveLinks())+ // Some may have arrived before the window was listening.+ void receiveLinks()return unsubscribe- }, [openNewDownload])+ }, [receiveLinks])}const isMac = window.plexo.platform === 'darwin'diff --git a/src/renderer/src/screens/DownloadsScreen.tsx b/src/renderer/src/screens/DownloadsScreen.tsxindex b507d98..6167457 100644--- a/src/renderer/src/screens/DownloadsScreen.tsx+++ b/src/renderer/src/screens/DownloadsScreen.tsx@@ -1,3 +1,4 @@+import { EXTENSION_PAGE_URL } from '@shared/browserBridge'import type { DownloadState, FinishedDownload } from '@shared/types'import { ChevronRight, Pause, Play, Plus, RotateCw, X, type LucideIcon } from 'lucide-react'import { cn } from 'cn'@@ -546,6 +547,14 @@ function EmptyState(): React.JSX.Element {New download<span className="ml-1 font-mono text-[11px] opacity-70">{NEW_SHORTCUT}</span></Button>+ <a+ href={EXTENSION_PAGE_URL}+ target="_blank"+ rel="noreferrer"+ className="mt-2 text-[12px] text-[var(--text-secondary)] hover:text-foreground hover:underline"+ >+ Downloading in Chrome, Edge or Firefox? Get the browser extension+ </a></>)}</div>diff --git a/src/renderer/src/store/useAppStore.ts b/src/renderer/src/store/useAppStore.tsindex ba25b62..b997593 100644--- a/src/renderer/src/store/useAppStore.ts+++ b/src/renderer/src/store/useAppStore.ts@@ -7,6 +7,7 @@ import type {NetworkInterfaceInfo,NetworkPreference,NetworkPreferences,+ PendingLink,SpeedUnit,ThemeSource,UpdateInfo@@ -57,6 +58,13 @@ interface AppStore {/** Lifted out of the Idle screen so it survives a swap to/from the No-connections screen. */draftUrl: string+ /** Handed-over links stacked in New download, oldest first. */+ links: PendingLink[]+ /** Null while New download shows a link typed or pasted there instead. Links are named by+ * id, never by position: the list changes while a start is under way. */+ shownId: string | null+ /** Bumped to remount New download's form for another link. */+ formKey: number/** The link last started: still on the clipboard afterwards, so not offered again. */startedUrl: string/** Persisted — the last folder picked, falling back to downloadsDir. */@@ -79,6 +87,12 @@ interface AppStore {/** Opens New download, with `link` in its link field when one is given. */openNewDownload: (link?: string) => voidcloseNewDownload: () => void+ receiveLinks: () => Promise<void>+ showLink: (id: string) => void+ /** If it was the one shown, the newest left is shown, or New download closes. */+ finishLink: (id: string, started: boolean) => void+ /** Leaves what New download shows alone, the typed link included. */+ dropLink: (id: string, started: boolean) => voidsetDownloadsAtOnce: (count: number) => void/** Each one applies at once, to every download (see main/network/limits.ts). */setSpeedLimit: (bytesPerSec: number | undefined) => void@@ -99,6 +113,9 @@ function persist(patch: AppSettings): void {window.plexo.updateSettings(patch).catch(() => {})}+/** Links let go here: a listing main sent before it heard so would bring them back. */+const letGo = new Set<string>()+export const useAppStore = create<AppStore>((set, get) => ({interfaces: [],interfacesStatus: 'idle',@@ -123,6 +140,9 @@ export const useAppStore = create<AppStore>((set, get) => ({speedUnit: initial.speedUnit,draftUrl: '',+ links: [],+ shownId: null,+ formKey: 0,startedUrl: '',destinationDir: initial.destinationDir ?? initial.downloadsDir,@@ -203,7 +223,49 @@ export const useAppStore = create<AppStore>((set, get) => ({openNewDownload: (link) =>set(link === undefined ? { newDownloadOpen: true } : { newDownloadOpen: true, draftUrl: link }),- closeNewDownload: () => set({ newDownloadOpen: false }),+ closeNewDownload: () => {+ const { links, shownId } = get()+ if (shownId) return get().finishLink(shownId, false)+ if (links.length > 0) return get().showLink(links[links.length - 1].id)+ set({ newDownloadOpen: false })+ },++ receiveLinks: async () => {+ // main lists every link still waiting, so a window that was closed or reloaded gets them back.+ const pending = await window.plexo.pendingLinks().catch(() => [])+ const known = new Set(get().links.map((link) => link.id))+ const arrived = pending.filter((link) => !known.has(link.id) && !letGo.has(link.id))+ if (arrived.length === 0) return+ set({ links: [...get().links, ...arrived], newDownloadOpen: true })+ get().showLink(arrived[arrived.length - 1].id)+ },++ showLink: (id) => {+ const link = get().links.find((candidate) => candidate.id === id)+ if (link) set({ shownId: id, draftUrl: link.url, formKey: get().formKey + 1 })+ },++ finishLink: (id, started) => {+ const wasShown = get().shownId === id+ get().dropLink(id, started)+ if (!wasShown) return+ const left = get().links+ set({ draftUrl: '' })+ if (left.length > 0) get().showLink(left[left.length - 1].id)+ else set({ newDownloadOpen: false })+ },++ dropLink: (id, started) => {+ const { links, shownId } = get()+ if (!links.some((link) => link.id === id)) return+ letGo.add(id)+ // Started, main has already forgotten its sign-in.+ if (!started) void window.plexo.dismissLink(id).catch(() => {})+ set({+ links: links.filter((link) => link.id !== id),+ ...(shownId === id && { shownId: null })+ })+ },setDownloadsAtOnce: (downloadsAtOnce) => {set({ downloadsAtOnce })diff --git a/src/shared/browserBridge.ts b/src/shared/browserBridge.tsnew file mode 100644index 0000000..213561e--- /dev/null+++ b/src/shared/browserBridge.ts@@ -0,0 +1,38 @@+import type { BrowserContext } from './types'++// The extension imports this file too, so Plexo and the extension can't drift apart.++/** Plexo listens on the first that's free and the extension tries them all, so a port another app+ * holds needs no setting. */+export const BRIDGE_PORTS = [19288, 19289, 19290] as const+/** Raised when an older extension or Plexo couldn't follow a change to /ping or /add. */+export const BRIDGE_API = 1+/** The extension waits a little longer than this, and Plexo adds nothing once it has given up,+ * so a download never ends up in both. */+export const BRIDGE_DEADLINE_MS = 8000+// ponytail: one page linking every store; it must exist before the extension ships.+export const EXTENSION_PAGE_URL = 'https://getplexo.app/extension'++export interface BridgePing {+ app: 'plexo'+ version: string+ api: number+}++/** 200 with a BridgeHandoff: Plexo will take it. 422: the browser keeps it. Never held past the+ * deadline: Chrome stops an extension's service worker when a fetch takes over 30 s. */+export interface BridgeAddRequest {+ url: string+ browser?: BrowserContext+ pageUrl?: string+ minBytes?: number+ /** The name the browser picked: only it saw a link's download attribute. */+ fileName?: string+}++/** Plexo shows the download only once POST /confirm brings this back: the extension confirms+ * after the browser's copy is really gone, since it can finish before it's cancelled. Unconfirmed,+ * it expires and Plexo shows nothing, so a download never ends up in both. */+export interface BridgeHandoff {+ token: string+}diff --git a/src/shared/ipc-channels.ts b/src/shared/ipc-channels.tsindex 52c28e9..7d9ba13 100644--- a/src/shared/ipc-channels.ts+++ b/src/shared/ipc-channels.ts@@ -28,6 +28,8 @@ export const IpcChannels = {downloadUpdated: 'download:updated',networksChanged: 'network:changed',linkReceived: 'app:link-received',- takePendingLink: 'app:take-pending-link',+ pendingLinks: 'app:pending-links',+ resumeFromLink: 'app:resume-from-link',+ dismissLink: 'app:dismiss-link',checkForUpdate: 'update:check'} as constdiff --git a/src/shared/ipc-contract.ts b/src/shared/ipc-contract.tsindex ed77d43..06515f2 100644--- a/src/shared/ipc-contract.ts+++ b/src/shared/ipc-contract.ts@@ -3,6 +3,7 @@ import type {DownloadUpdate,FinishedDownload,NetworkInterfaceInfo,+ PendingLink,ProbeResult,StartDownloadRequest,TorrentFileEntry,@@ -25,7 +26,8 @@ export interface IpcContract {/** Shows a download's file in its folder, by the download's own path. False when nothing is* there any more: history is re-sent, with it marked missing. */revealDownload: { args: [id: string]; result: boolean }- startDownload: { args: [request: StartDownloadRequest]; result: string }+ /** `linkId`: the PendingLink whose browser sign-in it starts with. */+ startDownload: { args: [request: StartDownloadRequest, linkId?: string]; result: string }/** Every download, oldest first, each as a snapshot. */listDownloads: { args: []; result: DownloadUpdate[] }/** Finished downloads, newest first. One is forgotten with removeDownload. */@@ -52,6 +54,10 @@ export interface IpcContract {* `trashFile`: then it goes to the Trash. */removeDownload: { args: [id: string, options?: { trashFile?: boolean }]; result: void }checkForUpdate: { args: []; result: UpdateInfo | null }- /** A link the OS handed over (main/openLinks.ts), once; null when there's none. */- takePendingLink: { args: []; result: string | null }+ /** Oldest first: every link not yet started or dismissed. */+ pendingLinks: { args: []; result: PendingLink[] }+ /** Resumes the failed download a link was matched to, from that link (see relinkDownload). */+ resumeFromLink: { args: [linkId: string, downloadId: string]; result: void }+ /** Forgets the sign-in of a link that won't be started. */+ dismissLink: { args: [id: string]; result: void }}diff --git a/src/shared/types.ts b/src/shared/types.tsindex 15235c6..39b9d59 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -231,6 +231,7 @@ export interface HttpDownloadState extends DownloadStateBase {blockSizeBytes: number/** The disk can't keep up: most streams are waiting for their writes (see concurrency.ts). */diskLimited?: boolean+ fromBrowser?: string}export interface TorrentDownloadState extends DownloadStateBase {@@ -334,6 +335,7 @@ export interface AppSettings {slowModeSpeed?: number/** How speeds are shown everywhere; sizes stay in bytes either way. */speedUnit?: SpeedUnit+ browserExtensionUsed?: boolean}/** bytes: MB/s. bits: Mbps, as internet plans and speed tests count them. */@@ -378,6 +380,38 @@ export interface StartHttpDownloadRequest extends StartDownloadRequestBase {kind: 'http'/** Streams per network the user picked; left out, the count is decided automatically. */streamsPerNetwork?: number+ browser?: BrowserContext+}++/** The fields of chrome.cookies.Cookie that decide where it's sent. */+export interface BrowserCookie {+ name: string+ value: string+ /** With or without a leading dot: `hostOnly` decides whether subdomains get it. */+ domain: string+ hostOnly: boolean+ path: string+ secure: boolean+}++/** So a link that needs a signed-in session, or checks the page it came from, works as it does+ * in the browser. */+export interface BrowserContext {+ cookies: BrowserCookie[]+ referer?: string+ userAgent?: string+ name?: string+}++export interface PendingLink {+ id: string+ url: string+ /** Reused by New download: checking a single-use link again would spend it. */+ probe?: ProbeResult+ from?: string+ signedInTo?: string+ /** A failed download this looks like the same file as, for the user to resume instead. */+ resumes?: { id: string; fileName: string }}export interface StartTorrentDownloadRequest extends StartDownloadRequestBase {