Skip to content

Open-source download manager & offline media toolbox for YouTube, music, social media, learning platforms & 1,800+ sites. Built with Tauri 2.0, Rust & Svelte.

fix(extension): drop the Chrome extension-ID allowlist (#107)

InstaZDLL66526fc4bc06
diff --git a/browser-extension/chrome/README.md b/browser-extension/chrome/README.md
index bbc9d93c..8a359237 100644
--- a/browser-extension/chrome/README.md
+++ b/browser-extension/chrome/README.md
@@ -17,12 +17,41 @@ Detects video and audio streams on any website and sends them to the OmniGet des
### On known platforms
-When you visit YouTube, Instagram, TikTok, or any of the 13 recognized platforms, the toolbar icon switches from gray to colored. Open the popup and click the download button — the page URL, cookies, and platform info are sent to OmniGet via native messaging.
+When you visit YouTube, Instagram, TikTok, or any of the 13 recognized platforms, the toolbar icon switches from gray to colored. Open the popup and click the download button — the page URL, cookies, and platform info are POSTed to the OmniGet desktop app over an authenticated localhost HTTP bridge (or fall through to the `omniget://` deep link if the bridge isn't paired).
### On any website (media detection)
The extension monitors network requests for video and audio streams as pages load them. Detected media appears in the popup grouped by video session. Click the download button on any entry, or use batch download to send all detected videos at once. Each download includes the page's cookies and referer for authenticated content.
+### Pairing the localhost bridge
+
+The desktop app starts a local HTTP server on `127.0.0.1:<port>` (default `47720`, range `47720..47729`, falls back to an OS-picked port if all are taken). On first launch it generates a per-installation token. The extension's options page opens automatically on install/update, **probes the local port range to auto-detect the endpoint**, and asks you to paste only the token from **OmniGet → Settings → Network → Browser extension**. After pairing, every download reaches the app authenticated with `Authorization: Bearer <token>` — no extension ID involved, so the same app works with any browser, any extension build, and any Chromium fork.
+
+The endpoint URL is hidden behind an "Advanced" disclosure for the rare case where the desktop app runs on a different host. If auto-discovery fails (app not running, port out of range), the disclosure opens automatically so you can set the URL by hand.
+
+## Screenshots
+
+### Where the token comes from
+
+OmniGet → Settings → Network → Browser extension. Copy the masked token; the URL is auto-detected by the extension so you don't have to.
+
+![Settings → Network → Browser extension](docs/app-settings.png)
+
+### Pairing flow on the extension side
+
+| State | Screenshot |
+|---|---|
+| **Discovering** the local bridge — first second on a fresh install. | ![Looking for the desktop app](docs/onboarding-discovery.png) |
+| **Found.** Endpoint pre-filled, only the token field is visible. | ![Found OmniGet on http://127.0.0.1:47721](docs/onboarding-found.png) |
+| **Saved.** Token persisted in `chrome.storage.local`, ready for downloads. | ![Saved](docs/onboarding-saved.png) |
+| **App not running.** Discovery banner turns red and the Advanced URL field opens automatically so you can override. | ![OmniGet doesn't seem to be running](docs/onboarding-not-found.png) |
+
+### `omniget://` fallback when the bridge isn't paired
+
+If the user clicks Download before completing the pairing flow, the extension falls back to the `omniget://` URL scheme. Chrome shows its standard external-protocol prompt the first time; tick "Always allow" to skip it on subsequent clicks.
+
+![Open omniget? — Chrome external protocol prompt](docs/chrome-protocol-prompt.png)
+
## Supported Platforms
| Platform | Content types |
@@ -45,13 +74,12 @@ Mirror domains are also recognized: `youtu.be`, `youtube-nocookie.com`, `ddinsta
## Install
-1. Install OmniGet desktop app and launch it once (registers the native messaging host).
+1. Install the OmniGet desktop app and launch it once (it generates a pairing token and starts the local bridge).
2. Open `chrome://extensions`, enable **Developer mode**, click **Load unpacked**, select `browser-extension/chrome/`.
-3. Click the OmniGet icon on any page.
-
-The unpacked extension keeps a stable ID via the manifest key: `dkjelkhaaakffpghdfalobccaaipajip`
+3. The extension's onboarding tab opens automatically. The endpoint is auto-detected; just copy the token from **OmniGet → Settings → Network → Browser extension** (Copy button), paste it in the **Pairing token** field, and click **Save**.
+4. Click the OmniGet icon on any page.
-On macOS/Linux, the first launch writes the native messaging manifest to your user profile. On Windows, a registry key is created under `HKCU\Software\Google\Chrome\NativeMessagingHosts`.
+If the bridge isn't paired (or the app is closed), clicks fall back to the `omniget://` URL scheme, which still queues the URL but won't carry cookies.
## Permissions
@@ -59,10 +87,10 @@ On macOS/Linux, the first launch writes the native messaging manifest to your us
|------------|-----|
| `webRequest` | Detect video/audio streams in network traffic |
| `cookies` | Forward session cookies for authenticated downloads |
-| `nativeMessaging` | Communicate with the OmniGet desktop app |
-| `storage` | Remember sniffer on/off preference |
+| `storage` | Remember sniffer on/off preference and the bridge pairing token |
| `tabs` | Read page URL and title for context |
-| `host_permissions: *://*/*` | Monitor requests on all sites for media detection |
+| `host_permissions: http://127.0.0.1/*` | POST to the desktop app's local bridge |
+| `host_permissions: *://*/*` (optional) | Monitor requests on all sites for media detection |
## Architecture
@@ -72,7 +100,9 @@ popup/
popup.css Dark theme, animations, state-based styles
popup.js State machine UI: known platform / media detected / listening / paused
src/
- background.js Service worker: icon switching, native messaging, message routing
+ background.js Service worker: icon switching, bridge fetch, message routing
+ bridge-client.js Localhost HTTP client: load/save token, health check, port discovery
+ send-via-scheme.js omniget:// fallback: hidden tab launches the OS handler
media-sniffer.js webRequest listener: detects media streams, filters .ts segments
sniffer-toggle.js Persists sniffer on/off state via chrome.storage.local
detect.js URL-based platform detection (no content scripts)
@@ -81,12 +111,13 @@ src/
action-title.js Tooltip resolution with i18n fallback
action-click.js Click handler with DI for testability
pages/
+ options.html/css/js Pairing onboarding: welcome state, auto-discovery, token paste
error.html/css/js Standalone error page (HOST_MISSING, INVALID_URL, LAUNCH_FAILED)
error-content.js Error message resolution with i18n fallback
scripts/
package.mjs ZIP packaging for CWS (strips manifest key)
tests/
- *.test.mjs 96 tests across 7 files
+ *.test.mjs 196 tests across 9 files
```
## Packaging
@@ -95,7 +126,7 @@ tests/
node browser-extension/chrome/scripts/package.mjs --version 0.2.0 --output omniget-chrome-extension.zip
```
-The packaging script strips the `key` field from `manifest.json` before creating the ZIP. Once the CWS assigns a store ID, add it to `CHROME_EXTENSION_IDS` in [`src-tauri/src/native_host.rs`](../../src-tauri/src/native_host.rs).
+The packaging script strips the `key` field from `manifest.json` before creating the ZIP. The extension ID is no longer load-bearing on the desktop side — auth flows through the bridge token, so any CWS / unpacked / sideloaded build pairs with the same app instance.
## Tests
@@ -103,7 +134,7 @@ The packaging script strips the `key` field from `manifest.json` before creating
node --test browser-extension/chrome/tests/*.test.mjs
```
-96 tests across 7 files covering platform detection, click handling, badge feedback, tooltip titles, error content, cookie extraction, and manifest validation.
+196 tests across 9 files covering platform detection, click handling, badge feedback, tooltip titles, error content, cookie extraction, manifest validation, the omniget:// scheme builder + hidden-tab fallback, and the localhost bridge client (config IO, health probe, port discovery, fetch with timeout / 401 / network failure paths).
## Internationalization
diff --git a/browser-extension/chrome/docs/app-settings.png b/browser-extension/chrome/docs/app-settings.png
new file mode 100644
index 00000000..ce7ba42b
Binary files /dev/null and b/browser-extension/chrome/docs/app-settings.png differ
diff --git a/browser-extension/chrome/docs/chrome-protocol-prompt.png b/browser-extension/chrome/docs/chrome-protocol-prompt.png
new file mode 100644
index 00000000..dc0b8e66
Binary files /dev/null and b/browser-extension/chrome/docs/chrome-protocol-prompt.png differ
diff --git a/browser-extension/chrome/docs/onboarding-discovery.png b/browser-extension/chrome/docs/onboarding-discovery.png
new file mode 100644
index 00000000..5c002421
Binary files /dev/null and b/browser-extension/chrome/docs/onboarding-discovery.png differ
diff --git a/browser-extension/chrome/docs/onboarding-found.png b/browser-extension/chrome/docs/onboarding-found.png
new file mode 100644
index 00000000..061858e3
Binary files /dev/null and b/browser-extension/chrome/docs/onboarding-found.png differ
diff --git a/browser-extension/chrome/docs/onboarding-not-found.png b/browser-extension/chrome/docs/onboarding-not-found.png
new file mode 100644
index 00000000..9271b0ed
Binary files /dev/null and b/browser-extension/chrome/docs/onboarding-not-found.png differ
diff --git a/browser-extension/chrome/docs/onboarding-saved.png b/browser-extension/chrome/docs/onboarding-saved.png
new file mode 100644
index 00000000..2234e02a
Binary files /dev/null and b/browser-extension/chrome/docs/onboarding-saved.png differ
diff --git a/browser-extension/chrome/manifest.json b/browser-extension/chrome/manifest.json
index 832839bb..d54f2b97 100644
--- a/browser-extension/chrome/manifest.json
+++ b/browser-extension/chrome/manifest.json
@@ -6,7 +6,6 @@
"default_locale": "en",
"key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0ribk9X5HR4XBloFk2g/V6kjICK8XWYC/QqrGFTOjKkRhRNDJr8Z14JFLggvWBbrj0D/zYdd5CfHJG01bGWMZC0hxRtm71q5Pbu1jtChEfE4QO/xWvM8WfrXH895nJFcUzxi137eoWq+FtSGxqFnSl6IXg5EZdgYH5LN3t6kL0HTwKnJLB3/8d4JD1uF2tQxHzii+MosIozKyDatqtEaBLprY1gfAfCwfY8Iqr9yehFUm7IDH+TGwjE17GJY1ZhfkpNBRmH/h23hwyk6coocSsWpM9GbCFdBX22iUnZjxZqACO1n+8xw2364Lznqtuot4iawznQGF4ALL7CbIvHPOQIDAQAB",
"permissions": [
- "nativeMessaging",
"tabs",
"cookies",
"webRequest",
@@ -14,6 +13,8 @@
"contextMenus"
],
"host_permissions": [
+ "http://127.0.0.1/*",
+ "http://localhost/*",
"*://*.hotmart.com/*",
"*://*.youtube.com/*",
"*://*.youtube-nocookie.com/*",
@@ -102,5 +103,9 @@
},
"description": "Send current page to OmniGet"
}
+ },
+ "options_ui": {
+ "page": "pages/options.html",
+ "open_in_tab": true
}
}
diff --git a/browser-extension/chrome/pages/options.css b/browser-extension/chrome/pages/options.css
new file mode 100644
index 00000000..3b0e9656
--- /dev/null
+++ b/browser-extension/chrome/pages/options.css
@@ -0,0 +1,225 @@
+:root {
+ color-scheme: dark;
+ font-family: "Segoe UI", system-ui, sans-serif;
+ background:
+ radial-gradient(circle at top, rgba(255, 125, 56, 0.18), transparent 42%),
+ #101114;
+ color: #f5f7fb;
+}
+
+* { box-sizing: border-box; }
+
+body { margin: 0; min-height: 100vh; }
+
+.shell {
+ min-height: 100vh;
+ display: grid;
+ place-items: center;
+ padding: 24px;
+}
+
+.card {
+ width: min(100%, 540px);
+ padding: 28px;
+ border-radius: 20px;
+ background: rgba(18, 20, 26, 0.92);
+ border: 1px solid rgba(255, 255, 255, 0.08);
+ box-shadow: 0 18px 80px rgba(0, 0, 0, 0.4);
+}
+
+.eyebrow {
+ margin: 0 0 10px;
+ font-size: 12px;
+ letter-spacing: 0.12em;
+ text-transform: uppercase;
+ color: #ff9a66;
+}
+
+h1 {
+ margin: 0 0 12px;
+ font-size: clamp(22px, 3vw, 28px);
+ line-height: 1.2;
+}
+
+.body {
+ margin: 0 0 18px;
+ color: #d9deea;
+ font-size: 14px;
+ line-height: 1.55;
+}
+
+form { display: grid; gap: 16px; }
+
+.field {
+ display: grid;
+ gap: 6px;
+ position: relative;
+}
+
+.label {
+ font-size: 13px;
+ color: #95a0b7;
+}
+
+input[type="url"],
+input[type="text"],
+input[type="password"] {
+ width: 100%;
+ min-height: 40px;
+ padding: 0 12px;
+ border-radius: 10px;
+ background: rgba(255, 255, 255, 0.04);
+ color: #f5f7fb;
+ border: 1px solid rgba(255, 255, 255, 0.08);
+ font: inherit;
+}
+
+input:focus {
+ outline: none;
+ border-color: rgba(255, 125, 56, 0.55);
+}
+
+.hint {
+ font-size: 12px;
+ color: #6b7691;
+}
+
+.hint code {
+ background: rgba(255, 255, 255, 0.05);
+ padding: 1px 6px;
+ border-radius: 4px;
+}
+
+.reveal {
+ position: absolute;
+ right: 6px;
+ top: 27px;
+ background: transparent;
+ border: none;
+ color: #95a0b7;
+ cursor: pointer;
+ padding: 4px 8px;
+ border-radius: 6px;
+ font-size: 12px;
+}
+
+.reveal:hover { background: rgba(255, 255, 255, 0.05); color: #f5f7fb; }
+
+.actions {
+ display: flex;
+ gap: 10px;
+ flex-wrap: wrap;
+ margin-top: 4px;
+}
+
+.button {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ min-height: 40px;
+ padding: 0 16px;
+ border: none;
+ border-radius: 999px;
+ appearance: none;
+ cursor: pointer;
+ font: inherit;
+ color: #f5f7fb;
+ background: rgba(255, 255, 255, 0.08);
+}
+
+.button.primary {
+ background: #ff7d38;
+ color: #160d06;
+ font-weight: 700;
+}
+
+.status {
+ margin: 6px 0 0;
+ min-height: 18px;
+ font-size: 13px;
+ color: #95a0b7;
+}
+
+.status.ok { color: #59d8a0; }
+.status.error { color: #ff7d7d; }
+
+.discovery {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding: 10px 12px;
+ border-radius: 10px;
+ background: rgba(255, 255, 255, 0.04);
+ border: 1px solid rgba(255, 255, 255, 0.08);
+ font-size: 13px;
+ color: #d9deea;
+ margin-bottom: 4px;
+}
+.discovery.found {
+ background: rgba(89, 216, 160, 0.08);
+ border-color: rgba(89, 216, 160, 0.35);
+ color: #79e1b3;
+}
+.discovery.missing {
+ background: rgba(255, 125, 125, 0.06);
+ border-color: rgba(255, 125, 125, 0.3);
+ color: #ffb1b1;
+}
+
+.spinner {
+ width: 14px;
+ height: 14px;
+ border-radius: 50%;
+ border: 2px solid rgba(255, 255, 255, 0.18);
+ border-top-color: #ff9a66;
+ animation: spin 0.85s linear infinite;
+}
+.discovery.found .spinner,
+.discovery.missing .spinner { display: none; }
+
+@keyframes spin {
+ to { transform: rotate(360deg); }
+}
+
+.install-help {
+ margin-top: 8px;
+ padding: 10px 12px;
+ border-radius: 10px;
+ border: 1px solid rgba(255, 255, 255, 0.06);
+ background: rgba(255, 255, 255, 0.02);
+ font-size: 13px;
+ color: #95a0b7;
+}
+.install-help summary {
+ cursor: pointer;
+ user-select: none;
+}
+.install-help p {
+ margin: 8px 0 0;
+ line-height: 1.55;
+}
+.install-help a {
+ color: #ff9a66;
+}
+
+.advanced {
+ margin-top: 4px;
+ padding: 10px 12px;
+ border-radius: 10px;
+ border: 1px solid rgba(255, 255, 255, 0.06);
+ background: rgba(255, 255, 255, 0.02);
+ font-size: 13px;
+ color: #95a0b7;
+}
+.advanced summary {
+ cursor: pointer;
+ user-select: none;
+ list-style: none;
+}
+.advanced summary::-webkit-details-marker { display: none; }
+.advanced summary::before {
+ content: "▸ ";
+ color: #6b7691;
+}
+.advanced[open] summary::before { content: "▾ "; }
+.advanced .field { margin-top: 10px; }
diff --git a/browser-extension/chrome/pages/options.html b/browser-extension/chrome/pages/options.html
new file mode 100644
index 00000000..78ef8ae6
--- /dev/null
+++ b/browser-extension/chrome/pages/options.html
@@ -0,0 +1,90 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width,initial-scale=1" />
+ <title>OmniGet Extension — Pair with desktop app</title>
+ <link rel="stylesheet" href="options.css" />
+ </head>
+ <body>
+ <main class="shell">
+ <div class="card" id="card">
+ <p class="eyebrow">OmniGet Extension</p>
+
+ <header id="welcome-header" hidden>
+ <h1>Welcome to OmniGet</h1>
+ <p class="body">
+ Let's connect this browser to the desktop app. We're looking for it
+ now — almost done.
+ </p>
+ </header>
+
+ <header id="settings-header" hidden>
+ <h1>Pair this browser</h1>
+ <p class="body">
+ Open OmniGet, go to <strong>Settings → Network → Browser
+ extension</strong>, then copy the <em>endpoint URL</em> and
+ <em>token</em> shown there into the fields below.
+ </p>
+ </header>
+
+ <div id="discovery-status" class="discovery" role="status" aria-live="polite">
+ <span class="spinner" aria-hidden="true"></span>
+ <span id="discovery-message">Looking for the desktop app on this machine…</span>
+ </div>
+
+ <form id="pair-form" novalidate>
+ <label class="field">
+ <span class="label">Pairing token</span>
+ <input
+ id="token"
+ name="token"
+ type="password"
+ placeholder="Paste the token from OmniGet → Settings → Network → Browser extension"
+ autocomplete="off"
+ spellcheck="false"
+ required
+ />
+ <button id="reveal" type="button" class="reveal" aria-pressed="false">
+ Show
+ </button>
+ </label>
+
+ <details id="advanced" class="advanced">
+ <summary>Advanced: change endpoint URL</summary>
+ <label class="field">
+ <span class="label">Endpoint URL</span>
+ <input
+ id="endpoint"
+ name="endpoint"
+ type="url"
+ placeholder="http://127.0.0.1:47720"
+ autocomplete="off"
+ spellcheck="false"
+ />
+ <span class="hint" id="endpoint-hint">Default: <code>http://127.0.0.1:47720</code></span>
+ </label>
+ </details>
+
+ <div class="actions">
+ <button id="save" type="submit" class="button primary">Save</button>
+ <button id="test" type="button" class="button">Test connection</button>
+ </div>
+
+ <p id="status" class="status" role="status" aria-live="polite"></p>
+ </form>
+
+ <details id="install-help" class="install-help">
+ <summary>Don't have OmniGet installed yet?</summary>
+ <p>
+ Install the desktop app from
+ <a href="https://github.com/tonhowtf/omniget/releases/latest" target="_blank" rel="noreferrer">
+ github.com/tonhowtf/omniget
+ </a>, launch it once, then come back to this page.
+ </p>
+ </details>
+ </div>
+ </main>
+ <script type="module" src="options.js"></script>
+ </body>
+</html>
diff --git a/browser-extension/chrome/pages/options.js b/browser-extension/chrome/pages/options.js
new file mode 100644
index 00000000..54ecd75b
--- /dev/null
+++ b/browser-extension/chrome/pages/options.js
@@ -0,0 +1,129 @@
+import {
+ loadBridgeConfig,
+ saveBridgeConfig,
+ checkBridgeHealth,
+ discoverBridgeEndpoint,
+ trimEndpoint,
+} from "../src/bridge-client.js";
+
+const endpointInput = document.getElementById("endpoint");
+const tokenInput = document.getElementById("token");
+const revealBtn = document.getElementById("reveal");
+const form = document.getElementById("pair-form");
+const testBtn = document.getElementById("test");
+const statusEl = document.getElementById("status");
+const welcomeHeader = document.getElementById("welcome-header");
+const settingsHeader = document.getElementById("settings-header");
+const discoveryEl = document.getElementById("discovery-status");
+const discoveryMessage = document.getElementById("discovery-message");
+const endpointHint = document.getElementById("endpoint-hint");
+const advancedDetails = document.getElementById("advanced");
+
+const FALLBACK_ENDPOINT = "http://127.0.0.1:47720";
+
+function resolvedEndpoint() {
+ return trimEndpoint(endpointInput.value) || FALLBACK_ENDPOINT;
+}
+
+function setStatus(message, kind) {
+ statusEl.textContent = message ?? "";
+ statusEl.classList.remove("ok", "error");
+ if (kind === "ok") statusEl.classList.add("ok");
+ if (kind === "error") statusEl.classList.add("error");
+}
+
+function setDiscovery(state, message) {
+ discoveryEl.classList.remove("found", "missing");
+ if (state === "found") discoveryEl.classList.add("found");
+ if (state === "missing") discoveryEl.classList.add("missing");
+ discoveryMessage.textContent = message;
+}
+
+async function init() {
+ const { endpoint, token } = await loadBridgeConfig();
+ const alreadyPaired = Boolean(token);
+
+ // Show the welcome heading on first run, the regular settings heading
+ // once the user is already paired (they're here to inspect / change).
+ if (alreadyPaired) {
+ settingsHeader.hidden = false;
+ } else {
+ welcomeHeader.hidden = false;
+ }
+
+ endpointInput.value = endpoint || "";
+ tokenInput.value = token || "";
+
+ // Skip auto-discovery if the user is already paired AND we have a stored
+ // endpoint that responds — they're probably here to change the token, no
+ // need to overwrite the URL they trust.
+ if (alreadyPaired) {
+ const result = await checkBridgeHealth(endpoint);
+ if (result.ok) {
+ const versionSuffix = result.version ? ` (v${result.version})` : "";
+ setDiscovery("found", `Connected to OmniGet${versionSuffix} at ${endpoint}.`);
+ return;
+ }
+ setDiscovery(
+ "missing",
+ `Couldn't reach the saved endpoint ${endpoint}. Probing default ports…`
+ );
+ }
+
+ const found = await discoverBridgeEndpoint();
+ if (found) {
+ endpointInput.value = found.endpoint;
+ const versionSuffix = found.version ? ` (v${found.version})` : "";
+ setDiscovery(
+ "found",
+ `Found OmniGet${versionSuffix} on ${found.endpoint}. Paste the token from OmniGet → Settings → Network → Browser extension to finish.`
+ );
+ endpointHint.textContent =
+ "Auto-detected — change only if your OmniGet runs on a different host.";
+ return;
+ }
+
+ // Discovery failed: open the Advanced disclosure so the user can supply
+ // the endpoint manually.
+ if (advancedDetails) advancedDetails.open = true;
+ setDiscovery(
+ "missing",
+ "OmniGet doesn't seem to be running. Launch the desktop app, then refresh this page — or set the endpoint manually below."
+ );
+}
+
+revealBtn.addEventListener("click", () => {
+ const next = tokenInput.type === "password" ? "text" : "password";
+ tokenInput.type = next;
+ revealBtn.textContent = next === "password" ? "Show" : "Hide";
+ revealBtn.setAttribute("aria-pressed", String(next !== "password"));
+});
+
+form.addEventListener("submit", async (event) => {
+ event.preventDefault();
+ const endpoint = resolvedEndpoint();
+ const token = tokenInput.value.trim();
+ if (!token) {
+ setStatus("Paste the pairing token first.", "error");
+ return;
+ }
+ await saveBridgeConfig({ endpoint, token });
+ setStatus("Saved. The extension will use this token from now on.", "ok");
+});
+
+testBtn.addEventListener("click", async () => {
+ const endpoint = resolvedEndpoint();
+ setStatus("Testing connection…");
+ const result = await checkBridgeHealth(endpoint);
+ if (result.ok) {
+ const versionSuffix = result.version ? ` (v${result.version})` : "";
+ setStatus(`Connected to OmniGet${versionSuffix} at ${endpoint}.`, "ok");
+ } else {
+ setStatus(
+ `Could not reach OmniGet at ${endpoint}. Make sure the app is running.`,
+ "error"
+ );
+ }
+});
+
+init();
diff --git a/browser-extension/chrome/src/action-click.js b/browser-extension/chrome/src/action-click.js
index dfa8d8dc..e6aa4855 100644
--- a/browser-extension/chrome/src/action-click.js
+++ b/browser-extension/chrome/src/action-click.js
@@ -1,11 +1,19 @@
const DEFAULT_LAUNCH_FAILED_CODE = "LAUNCH_FAILED";
const PROTOCOL_VERSION = 1;
+// Reusable click handler factored out of background.js so it can be unit-tested
+// in isolation. Transport is injected as `sendToHost` (the localhost bridge in
+// production), with `openSchemeUrl` providing the cookie-less fallback when the
+// app is unreachable. Both callbacks return `{ ok, ... }` results.
+//
+// `sendToHost` is also accepted under the legacy alias `sendNativeMessage` for
+// backwards-compat with tests written before the native-messaging removal.
export async function handleSupportedActionClick({
tabId,
url,
platform,
getCookies,
+ sendToHost,
sendNativeMessage,
clearBadge = async () => {},
showSuccessBadge = async () => {},
@@ -13,6 +21,8 @@ export async function handleSupportedActionClick({
mapChromeErrorCode,
openSchemeUrl = async () => ({ ok: false, reason: "not-wired" }),
}) {
+ const send = sendToHost ?? sendNativeMessage;
+
if (tabId !== undefined && tabId !== null) {
await clearBadge(tabId);
}
@@ -32,7 +42,7 @@ export async function handleSupportedActionClick({
message.cookies = cookies;
}
- const response = await sendNativeMessage(message);
+ const response = await send(message);
if (!response?.ok) {
await openErrorPage({
diff --git a/browser-extension/chrome/src/background.js b/browser-extension/chrome/src/background.js
index 70d2eb4b..ef8036f9 100644
--- a/browser-extension/chrome/src/background.js
+++ b/browser-extension/chrome/src/background.js
@@ -6,8 +6,8 @@ import { summarizeCookies } from "./cookie-summary.js";
import { loadSnifferState, isSnifferEnabled, setSnifferEnabled } from "./sniffer-toggle.js";
import { registerContextMenu, getContextMenuId } from "./context-menu.js";
import { openOmnigetScheme } from "./send-via-scheme.js";
+import { sendViaBridge, sendCookiesViaBridge } from "./bridge-client.js";
-const HOST_NAME = "wtf.tonho.omniget";
const INSTALL_URL = "https://github.com/tonhowtf/omniget/releases/latest";
const PROTOCOL_VERSION = 1;
@@ -49,9 +49,28 @@ loadSnifferState().then(async (enabled) => {
}
});
-chrome.runtime.onInstalled.addListener(() => {
+chrome.runtime.onInstalled.addListener(async (details) => {
registerContextMenu();
refreshActiveTab().catch(() => {});
+ // Surface the pairing page on any install/update *if the user hasn't
+ // already paired this browser*. Reloading an unpacked extension fires
+ // `update`, not `install`, so gating only on `install` would silently
+ // skip the onboarding flow for dev builds and users coming from a
+ // pre-bridge OmniGet version.
+ if (typeof chrome.runtime.openOptionsPage !== "function") return;
+ try {
+ const stored = await chrome.storage.local.get("bridge_token");
+ const token = typeof stored?.bridge_token === "string" ? stored.bridge_token.trim() : "";
+ if (!token) {
+ chrome.runtime.openOptionsPage().catch(() => {});
+ }
+ } catch {
+ // storage unavailable — fall back to the previous behaviour and only
+ // open on a real install.
+ if (details?.reason === "install") {
+ chrome.runtime.openOptionsPage().catch(() => {});
+ }
+ }
});
chrome.contextMenus.onClicked.addListener(async (info, tab) => {
@@ -276,16 +295,27 @@ async function handleSendToApp(msg) {
const cookieSummary = summarizeCookies(cookies);
- try {
- const response = await sendNativeMessage(message);
- return { ok: response?.ok ?? false, cookieSummary };
- } catch (e) {
- const schemeResult = await openOmnigetScheme(url);
- if (schemeResult?.ok) {
- return { ok: true, viaScheme: true, cookieSummary };
- }
- return { ok: false, error: e.message };
+ // Primary path: localhost HTTP bridge (no extension-ID dependency, full
+ // cookie + metadata payload).
+ const bridgeResult = await sendViaBridge(message);
+ if (bridgeResult?.ok) {
+ return { ok: true, viaBridge: true, cookieSummary };
}
+
+ // Fallback: omniget:// scheme handler. The desktop app is launched (or
+ // brought to focus) and the URL is queued, but cookies aren't forwarded
+ // — the user can pair the bridge from the extension's options page to
+ // get the full experience.
+ const schemeResult = await openOmnigetScheme(url);
+ if (schemeResult?.ok) {
+ return { ok: true, viaScheme: true, cookieSummary, bridgeReason: bridgeResult?.reason };
+ }
+ return {
+ ok: false,
+ error: bridgeResult?.message || schemeResult?.message || "OmniGet is not reachable",
+ bridgeReason: bridgeResult?.reason,
+ schemeReason: schemeResult?.reason,
+ };
}
async function refreshActiveTab() {
@@ -327,18 +357,6 @@ function isTabGoneError(error) {
return msg.includes("No tab with id");
}
-function sendNativeMessage(message) {
- return new Promise((resolve, reject) => {
- chrome.runtime.sendNativeMessage(HOST_NAME, message, (response) => {
- if (chrome.runtime.lastError) {
- reject(new Error(chrome.runtime.lastError.message));
- return;
- }
- resolve(response);
- });
- });
-}
-
const COOKIE_AUTO_CAPTURE_DEBOUNCE_MS = 1500;
const COOKIE_AUTO_CAPTURE_MIN_INTERVAL_MS = 60_000;
const cookieDebounceTimers = new Map();
@@ -453,25 +471,13 @@ async function capturePlatformCookies(platform, force = false) {
return { ok: false, reason: "no_cookies" };
}
- try {
- const response = await sendNativeMessage({
- type: "cookies:export",
- protocolVersion: PROTOCOL_VERSION,
- platform,
- cookies,
- timestamp: Date.now(),
- });
- console.info(
- "[OmniGet] cookies exported",
- platform,
- cookies.length,
- response,
- );
+ const response = await sendCookiesViaBridge(cookies);
+ if (response.ok) {
+ console.info("[OmniGet] cookies exported", platform, cookies.length, response);
return { ok: true, count: cookies.length, response };
- } catch (e) {
- console.warn("[OmniGet] cookie export failed", platform, e.message);
- return { ok: false, reason: "host_unreachable", error: e.message };
}
+ console.warn("[OmniGet] cookie export failed", platform, response.reason ?? response.message);
+ return { ok: false, reason: response.reason ?? "bridge_failed", response };
}
async function scanOpenTabsForCookies() {
diff --git a/browser-extension/chrome/src/bridge-client.js b/browser-extension/chrome/src/bridge-client.js
new file mode 100644
index 00000000..2dd2ed31
--- /dev/null
+++ b/browser-extension/chrome/src/bridge-client.js
@@ -0,0 +1,303 @@
+// Localhost HTTP bridge client.
+//
+// Replaces native messaging: instead of relying on Chrome's native-messaging
+// manifest (which requires hard-coded extension IDs in the desktop app), we
+// POST the same payload to the OmniGet desktop app's local HTTP listener,
+// authenticating each request with a bearer token the user pastes once into
+// the extension's options page.
+//
+// Lookup contract:
+// - The user copies `endpoint` (e.g. http://127.0.0.1:47720) and `token`
+// from the OmniGet Settings UI into the extension's Options page.
+// - chrome.storage.local stores them under the keys below.
+// - If either value is missing the bridge is considered "unpaired" and the
+// caller falls through to the omniget:// scheme handler.
+
+export const STORAGE_KEY_ENDPOINT = "bridge_endpoint";
+export const STORAGE_KEY_TOKEN = "bridge_token";
+const HEALTH_TIMEOUT_MS = 1500;
+const ENQUEUE_TIMEOUT_MS = 8000;
+const PROTOCOL_VERSION = 1;
+const DEFAULT_ENDPOINT = "http://127.0.0.1:47720";
+// Mirrors `PORT_RANGE` in src-tauri/src/local_bridge.rs — kept narrow so the
+// auto-discovery probe is fast.
+export const DEFAULT_PORT_RANGE = [
+ 47720, 47721, 47722, 47723, 47724, 47725, 47726, 47727, 47728, 47729,
+];
+
+export function trimEndpoint(value) {
+ if (typeof value !== "string") return "";
+ let trimmed = value.trim();
+ if (!trimmed) return "";
+ while (trimmed.endsWith("/")) {
+ trimmed = trimmed.slice(0, -1);
+ }
+ return trimmed;
+}
+
+export async function loadBridgeConfig({ storage = globalThis.chrome?.storage?.local } = {}) {
+ if (!storage?.get) {
+ return { endpoint: "", token: "" };
+ }
+ return new Promise((resolve) => {
+ storage.get([STORAGE_KEY_ENDPOINT, STORAGE_KEY_TOKEN], (items) => {
+ const endpoint = trimEndpoint(items?.[STORAGE_KEY_ENDPOINT]) || DEFAULT_ENDPOINT;
+ const token = typeof items?.[STORAGE_KEY_TOKEN] === "string" ? items[STORAGE_KEY_TOKEN].trim() : "";
+ resolve({ endpoint, token });
+ });
+ });
+}
+
+export async function saveBridgeConfig(
+ { endpoint = "", token = "" },
+ { storage = globalThis.chrome?.storage?.local } = {}
+) {
+ if (!storage?.set) return false;
+ return new Promise((resolve) => {
+ storage.set(
+ {
+ [STORAGE_KEY_ENDPOINT]: trimEndpoint(endpoint),
+ [STORAGE_KEY_TOKEN]: typeof token === "string" ? token.trim() : "",
+ },
+ () => resolve(true)
+ );
+ });
+}
+
+function withTimeout(promise, ms, controller) {
+ return new Promise((resolve, reject) => {
+ const timer = setTimeout(() => {
+ try {
+ controller?.abort();
+ } catch {}
+ reject(new Error(`bridge timed out after ${ms}ms`));
+ }, ms);
+ promise.then(
+ (value) => {
+ clearTimeout(timer);
+ resolve(value);
+ },
+ (error) => {
+ clearTimeout(timer);
+ reject(error);
+ }
+ );
+ });
+}
+
+// Probes the bridge port range in parallel and returns the first endpoint
+// that answers `/v1/health` with `ok: true`. Used by the options page to
+// pre-fill the URL without making the user discover the port by hand.
+export async function discoverBridgeEndpoint({
+ fetchImpl = typeof fetch !== "undefined" ? fetch : null,
+ ports = DEFAULT_PORT_RANGE,
+ host = "127.0.0.1",
+ timeoutMs = HEALTH_TIMEOUT_MS,
+} = {}) {
+ if (!fetchImpl) return null;
+ const probes = ports.map(async (port) => {
+ const endpoint = `http://${host}:${port}`;
+ const result = await checkBridgeHealth(endpoint, { fetchImpl, timeoutMs });
+ return result.ok ? { endpoint, version: result.version ?? null } : null;
+ });
+
+ const settled = await Promise.allSettled(probes);
+ for (const result of settled) {
+ if (result.status === "fulfilled" && result.value) {
+ return result.value;
+ }
+ }
+ return null;
+}
+
+export async function checkBridgeHealth(
+ endpoint,
+ { fetchImpl = (typeof fetch !== "undefined" ? fetch : null), timeoutMs = HEALTH_TIMEOUT_MS } = {}
+) {
+ if (!fetchImpl) return { ok: false, reason: "no-fetch" };
+ const target = trimEndpoint(endpoint);
+ if (!target) return { ok: false, reason: "no-endpoint" };
+
+ const controller = typeof AbortController !== "undefined" ? new AbortController() : null;
+ try {
+ const response = await withTimeout(
+ fetchImpl(`${target}/v1/health`, {
+ method: "GET",
+ signal: controller?.signal,
+ }),
+ timeoutMs,
+ controller
+ );
+ if (!response.ok) {
+ return { ok: false, reason: "http-error", status: response.status };
+ }
+ const body = await response.json().catch(() => null);
+ return { ok: Boolean(body?.ok), version: body?.version ?? null };
+ } catch (error) {
+ return { ok: false, reason: "fetch-failed", message: error?.message ?? String(error) };
+ }
+}
+
+export async function sendViaBridge(
+ payload,
+ {
+ fetchImpl = (typeof fetch !== "undefined" ? fetch : null),
+ storage = globalThis.chrome?.storage?.local,
+ timeoutMs = ENQUEUE_TIMEOUT_MS,
+ config = null,
+ } = {}
+) {
+ if (!fetchImpl) {
+ return { ok: false, reason: "no-fetch" };
+ }
+
+ const resolved = config ?? (await loadBridgeConfig({ storage }));
+ const endpoint = trimEndpoint(resolved.endpoint);
+ const token = typeof resolved.token === "string" ? resolved.token.trim() : "";
+
+ if (!endpoint) {
+ return { ok: false, reason: "missing-endpoint" };
+ }
+ if (!token) {
+ return { ok: false, reason: "missing-token" };
+ }
+
+ const body = { ...payload, protocolVersion: PROTOCOL_VERSION };
+
+ const controller = typeof AbortController !== "undefined" ? new AbortController() : null;
+ let response;
+ try {
+ response = await withTimeout(
+ fetchImpl(`${endpoint}/v1/enqueue`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: `Bearer ${token}`,
+ },
+ body: JSON.stringify(body),
+ signal: controller?.signal,
+ }),
+ timeoutMs,
+ controller
+ );
+ } catch (error) {
+ return {
+ ok: false,
+ reason: "fetch-failed",
+ message: error?.message ?? String(error),
+ };
+ }
+
+ let parsed = null;
+ try {
+ parsed = await response.json();
+ } catch {
+ parsed = null;
+ }
+
+ if (response.status === 401 || response.status === 403) {
+ return {
+ ok: false,
+ reason: "unauthorized",
+ status: response.status,
+ message: parsed?.message ?? "Bridge rejected the bearer token",
+ };
+ }
+ if (!response.ok) {
+ return {
+ ok: false,
+ reason: "http-error",
+ status: response.status,
+ code: parsed?.code ?? null,
+ message: parsed?.message ?? `HTTP ${response.status}`,
+ };
+ }
+
+ return {
+ ok: Boolean(parsed?.ok ?? false),
+ code: parsed?.code ?? null,
+ message: parsed?.message ?? null,
+ };
+}
+
+export async function sendCookiesViaBridge(
+ cookies,
+ {
+ fetchImpl = (typeof fetch !== "undefined" ? fetch : null),
+ storage = globalThis.chrome?.storage?.local,
+ timeoutMs = ENQUEUE_TIMEOUT_MS,
+ config = null,
+ } = {}
+) {
+ if (!fetchImpl) {
+ return { ok: false, reason: "no-fetch" };
+ }
+
+ const resolved = config ?? (await loadBridgeConfig({ storage }));
+ const endpoint = trimEndpoint(resolved.endpoint);
+ const token = typeof resolved.token === "string" ? resolved.token.trim() : "";
+
+ if (!endpoint) {
+ return { ok: false, reason: "missing-endpoint" };
+ }
+ if (!token) {
+ return { ok: false, reason: "missing-token" };
+ }
+
+ const body = { cookies, protocolVersion: PROTOCOL_VERSION };
+
+ const controller = typeof AbortController !== "undefined" ? new AbortController() : null;
+ let response;
+ try {
+ response = await withTimeout(
+ fetchImpl(`${endpoint}/v1/cookies`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: `Bearer ${token}`,
+ },
+ body: JSON.stringify(body),
+ signal: controller?.signal,
+ }),
+ timeoutMs,
+ controller
+ );
+ } catch (error) {
+ return {
+ ok: false,
+ reason: "fetch-failed",
+ message: error?.message ?? String(error),
+ };
+ }
+
+ let parsed = null;
+ try {
+ parsed = await response.json();
+ } catch {
+ parsed = null;
+ }
+
+ if (response.status === 401 || response.status === 403) {
+ return {
+ ok: false,
+ reason: "unauthorized",
+ status: response.status,
+ message: parsed?.message ?? "Bridge rejected the bearer token",
+ };
+ }
+ if (!response.ok) {
+ return {
+ ok: false,
+ reason: "http-error",
+ status: response.status,
+ code: parsed?.code ?? null,
+ message: parsed?.message ?? `HTTP ${response.status}`,
+ };
+ }
+
+ return {
+ ok: Boolean(parsed?.ok ?? false),
+ code: parsed?.code ?? null,
+ message: parsed?.message ?? null,
+ };
+}
diff --git a/browser-extension/chrome/src/send-via-scheme.js b/browser-extension/chrome/src/send-via-scheme.js
index 8547820c..403f39d5 100644
--- a/browser-extension/chrome/src/send-via-scheme.js
+++ b/browser-extension/chrome/src/send-via-scheme.js
@@ -1,4 +1,5 @@
export const OMNIGET_SCHEME = "omniget://";
+const SCHEME_TAB_LIFETIME_MS = 1500;
export function buildOmnigetSchemeUrl(url) {
if (typeof url !== "string") {
@@ -21,21 +22,45 @@ export function buildOmnigetSchemeUrl(url) {
return `${OMNIGET_SCHEME}${withoutProtocol}`;
}
-export async function openOmnigetScheme(url, { tabs } = { tabs: chrome?.tabs }) {
+// Opens the omniget:// scheme in a hidden background tab so the OS can route
+// it to the desktop app, without disturbing the user's currently focused tab.
+// We close the throwaway tab shortly after creation since the page itself has
+// no meaningful content (the protocol handler runs out-of-process).
+export async function openOmnigetScheme(
+ url,
+ {
+ tabs = chrome?.tabs,
+ schedule = (fn, ms) => setTimeout(fn, ms),
+ tabLifetimeMs = SCHEME_TAB_LIFETIME_MS,
+ } = {}
+) {
const schemeUrl = buildOmnigetSchemeUrl(url);
if (!schemeUrl) {
return { ok: false, reason: "invalid-url" };
}
- if (!tabs?.update) {
+ if (!tabs?.create) {
return { ok: false, reason: "tabs-api-unavailable" };
}
try {
- await tabs.update({ url: schemeUrl });
+ const newTab = await tabs.create({ url: schemeUrl, active: false });
+ const tabId = newTab?.id;
+ if (typeof tabId === "number" && typeof tabs.remove === "function") {
+ schedule(() => {
+ try {
+ const removeResult = tabs.remove(tabId);
+ if (removeResult && typeof removeResult.catch === "function") {
+ removeResult.catch(() => {});
+ }
+ } catch {
+ // Tab may already be gone; ignore.
+ }
+ }, tabLifetimeMs);
+ }
return { ok: true, schemeUrl };
} catch (error) {
return {
ok: false,
- reason: "tabs-update-failed",
+ reason: "tabs-create-failed",
message: error instanceof Error ? error.message : String(error),
};
}
diff --git a/browser-extension/chrome/tests/bridge-client.test.mjs b/browser-extension/chrome/tests/bridge-client.test.mjs
new file mode 100644
index 00000000..50befca3
--- /dev/null
+++ b/browser-extension/chrome/tests/bridge-client.test.mjs
@@ -0,0 +1,233 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+
+import {
+ trimEndpoint,
+ loadBridgeConfig,
+ saveBridgeConfig,
+ checkBridgeHealth,
+ discoverBridgeEndpoint,
+ sendViaBridge,
+ STORAGE_KEY_ENDPOINT,
+ STORAGE_KEY_TOKEN,
+ DEFAULT_PORT_RANGE,
+} from "../src/bridge-client.js";
+
+function fakeStorage(initial = {}) {
+ const data = { ...initial };
+ return {
+ data,
+ get: (keys, cb) => {
+ const result = {};
+ for (const key of keys) result[key] = data[key];
+ cb(result);
+ },
+ set: (patch, cb) => {
+ Object.assign(data, patch);
+ cb();
+ },
+ };
+}
+
+test("trimEndpoint strips whitespace and trailing slashes", () => {
+ assert.equal(trimEndpoint(" http://127.0.0.1:47720/ "), "http://127.0.0.1:47720");
+ assert.equal(trimEndpoint("http://x/"), "http://x");
+ assert.equal(trimEndpoint("http://x///"), "http://x");
+ assert.equal(trimEndpoint(null), "");
+ assert.equal(trimEndpoint(undefined), "");
+});
+
+test("loadBridgeConfig returns defaults when storage is empty", async () => {
+ const storage = fakeStorage();
+ const result = await loadBridgeConfig({ storage });
+ assert.equal(result.endpoint, "http://127.0.0.1:47720");
+ assert.equal(result.token, "");
+});
+
+test("loadBridgeConfig respects stored values", async () => {
+ const storage = fakeStorage({
+ [STORAGE_KEY_ENDPOINT]: "http://127.0.0.1:9999",
+ [STORAGE_KEY_TOKEN]: "abc",
+ });
+ const result = await loadBridgeConfig({ storage });
+ assert.equal(result.endpoint, "http://127.0.0.1:9999");
+ assert.equal(result.token, "abc");
+});
+
+test("saveBridgeConfig writes trimmed values", async () => {
+ const storage = fakeStorage();
+ await saveBridgeConfig({ endpoint: " http://127.0.0.1:1234/ ", token: " tok " }, { storage });
+ assert.equal(storage.data[STORAGE_KEY_ENDPOINT], "http://127.0.0.1:1234");
+ assert.equal(storage.data[STORAGE_KEY_TOKEN], "tok");
+});
+
+test("checkBridgeHealth returns ok when /v1/health responds with ok=true", async () => {
+ const fetchImpl = async (url) => {
+ assert.equal(url, "http://127.0.0.1:47720/v1/health");
+ return { ok: true, json: async () => ({ ok: true, version: "0.5.3" }) };
+ };
+ const result = await checkBridgeHealth("http://127.0.0.1:47720", { fetchImpl });
+ assert.deepEqual(result, { ok: true, version: "0.5.3" });
+});
+
+test("checkBridgeHealth surfaces a clean failure when fetch rejects", async () => {
+ const fetchImpl = async () => { throw new Error("boom"); };
+ const result = await checkBridgeHealth("http://127.0.0.1:47720", { fetchImpl });
+ assert.equal(result.ok, false);
+ assert.equal(result.reason, "fetch-failed");
+ assert.equal(result.message, "boom");
+});
+
+test("checkBridgeHealth refuses an empty endpoint", async () => {
+ const fetchImpl = async () => { throw new Error("should not call"); };
+ const result = await checkBridgeHealth("", { fetchImpl });
+ assert.deepEqual(result, { ok: false, reason: "no-endpoint" });
+});
+
+test("sendViaBridge POSTs the payload with bearer auth and protocolVersion", async () => {
+ const calls = [];
+ const fetchImpl = async (url, init) => {
+ calls.push({ url, init });
+ return {
+ ok: true,
+ status: 200,
+ json: async () => ({ ok: true }),
+ };
+ };
+
+ const result = await sendViaBridge(
+ { type: "enqueue", url: "https://example.com/v" },
+ {
+ fetchImpl,
+ config: { endpoint: "http://127.0.0.1:47720", token: "tok" },
+ }
+ );
+
+ assert.deepEqual(result, { ok: true, code: null, message: null });
+ assert.equal(calls.length, 1);
+ assert.equal(calls[0].url, "http://127.0.0.1:47720/v1/enqueue");
+ assert.equal(calls[0].init.method, "POST");
+ assert.equal(calls[0].init.headers["Content-Type"], "application/json");
+ assert.equal(calls[0].init.headers.Authorization, "Bearer tok");
+ const body = JSON.parse(calls[0].init.body);
+ assert.equal(body.url, "https://example.com/v");
+ assert.equal(body.type, "enqueue");
+ assert.equal(body.protocolVersion, 1);
+});
+
+test("sendViaBridge reports missing-token when no token is set", async () => {
+ const fetchImpl = async () => { throw new Error("should not call"); };
+ const result = await sendViaBridge(
+ { url: "https://example.com" },
+ {
+ fetchImpl,
+ config: { endpoint: "http://127.0.0.1:47720", token: "" },
+ }
+ );
+ assert.deepEqual(result, { ok: false, reason: "missing-token" });
+});
+
+test("sendViaBridge reports unauthorized on HTTP 401", async () => {
+ const fetchImpl = async () => ({
+ ok: false,
+ status: 401,
+ json: async () => ({ ok: false, code: "UNAUTHORIZED", message: "bad token" }),
+ });
+ const result = await sendViaBridge(
+ { url: "https://example.com" },
+ {
+ fetchImpl,
+ config: { endpoint: "http://127.0.0.1:47720", token: "bad" },
+ }
+ );
+ assert.equal(result.ok, false);
+ assert.equal(result.reason, "unauthorized");
+ assert.equal(result.status, 401);
+ assert.equal(result.message, "bad token");
+});
+
+test("sendViaBridge surfaces network error so the caller can fall back", async () => {
+ const fetchImpl = async () => { throw new Error("ECONNREFUSED"); };
+ const result = await sendViaBridge(
+ { url: "https://example.com" },
+ {
+ fetchImpl,
+ config: { endpoint: "http://127.0.0.1:47720", token: "tok" },
+ }
+ );
+ assert.equal(result.ok, false);
+ assert.equal(result.reason, "fetch-failed");
+ assert.equal(result.message, "ECONNREFUSED");
+});
+
+test("DEFAULT_PORT_RANGE matches the Rust bridge's PORT_RANGE", () => {
+ // Sanity: keep the JS probe range narrow and aligned with
+ // src-tauri/src/local_bridge.rs (47720..47730 = 10 ports).
+ assert.equal(DEFAULT_PORT_RANGE[0], 47720);
+ assert.equal(DEFAULT_PORT_RANGE.at(-1), 47729);
+ assert.equal(DEFAULT_PORT_RANGE.length, 10);
+});
+
+test("discoverBridgeEndpoint returns the first port that answers /v1/health", async () => {
+ const seen = [];
+ const fetchImpl = async (url) => {
+ seen.push(url);
+ if (url === "http://127.0.0.1:47722/v1/health") {
+ return { ok: true, json: async () => ({ ok: true, version: "0.5.3" }) };
+ }
+ return { ok: false, json: async () => ({}) };
+ };
+
+ const result = await discoverBridgeEndpoint({
+ fetchImpl,
+ ports: [47720, 47721, 47722, 47723],
+ });
+
+ assert.deepEqual(result, {
+ endpoint: "http://127.0.0.1:47722",
+ version: "0.5.3",
+ });
+ // All four ports were probed in parallel.
+ assert.equal(seen.length, 4);
+});
+
+test("discoverBridgeEndpoint returns null when no port responds", async () => {
+ const fetchImpl = async () => { throw new Error("ECONNREFUSED"); };
+ const result = await discoverBridgeEndpoint({
+ fetchImpl,
+ ports: [47720, 47721],
+ });
+ assert.equal(result, null);
+});
+
+test("discoverBridgeEndpoint ignores 200 responses where ok is false", async () => {
+ const fetchImpl = async () => ({
+ ok: true,
+ json: async () => ({ ok: false }),
+ });
+ const result = await discoverBridgeEndpoint({
+ fetchImpl,
+ ports: [47720],
+ });
+ assert.equal(result, null);
+});
+
+test("sendViaBridge bubbles up app-level error code on a 4xx response", async () => {
+ const fetchImpl = async () => ({
+ ok: false,
+ status: 400,
+ json: async () => ({ ok: false, code: "INVALID_URL", message: "bad URL" }),
+ });
+ const result = await sendViaBridge(
+ { url: "not-a-url" },
+ {
+ fetchImpl,
+ config: { endpoint: "http://127.0.0.1:47720", token: "tok" },
+ }
+ );
+ assert.equal(result.ok, false);
+ assert.equal(result.reason, "http-error");
+ assert.equal(result.status, 400);
+ assert.equal(result.code, "INVALID_URL");
+ assert.equal(result.message, "bad URL");
+});
diff --git a/browser-extension/chrome/tests/send-via-scheme.test.mjs b/browser-extension/chrome/tests/send-via-scheme.test.mjs
new file mode 100644
index 00000000..f5897c86
--- /dev/null
+++ b/browser-extension/chrome/tests/send-via-scheme.test.mjs
@@ -0,0 +1,156 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+
+import { buildOmnigetSchemeUrl, openOmnigetScheme } from "../src/send-via-scheme.js";
+
+test("buildOmnigetSchemeUrl strips http(s) prefix and prepends omniget://", () => {
+ assert.equal(
+ buildOmnigetSchemeUrl("https://www.youtube.com/watch?v=abc"),
+ "omniget://www.youtube.com/watch?v=abc"
+ );
+ assert.equal(
+ buildOmnigetSchemeUrl("http://example.com/v"),
+ "omniget://example.com/v"
+ );
+});
+
+test("buildOmnigetSchemeUrl preserves an already-omniget URL", () => {
+ assert.equal(
+ buildOmnigetSchemeUrl("omniget://example.com/v"),
+ "omniget://example.com/v"
+ );
+});
+
+test("buildOmnigetSchemeUrl wraps magnet/p2p URLs without an extra slash", () => {
+ assert.equal(
+ buildOmnigetSchemeUrl("magnet:?xt=urn:btih:abc"),
+ "omniget:magnet:?xt=urn:btih:abc"
+ );
+ assert.equal(
+ buildOmnigetSchemeUrl("p2p:foo"),
+ "omniget:p2p:foo"
+ );
+});
+
+test("buildOmnigetSchemeUrl returns null for empty / non-string input", () => {
+ assert.equal(buildOmnigetSchemeUrl(""), null);
+ assert.equal(buildOmnigetSchemeUrl(" "), null);
+ assert.equal(buildOmnigetSchemeUrl(null), null);
+ assert.equal(buildOmnigetSchemeUrl(undefined), null);
+ assert.equal(buildOmnigetSchemeUrl(42), null);
+});
+
+test("openOmnigetScheme creates a hidden tab and schedules its removal", async () => {
+ const events = [];
+ const scheduled = [];
+
+ const tabs = {
+ create: async (options) => {
+ events.push(["create", options]);
+ return { id: 1234 };
+ },
+ remove: (id) => {
+ events.push(["remove", id]);
+ return Promise.resolve();
+ },
+ };
+
+ const schedule = (fn, ms) => {
+ scheduled.push({ fn, ms });
+ return null;
+ };
+
+ const result = await openOmnigetScheme("https://example.com/v", {
+ tabs,
+ schedule,
+ tabLifetimeMs: 500,
+ });
+
+ assert.deepEqual(result, { ok: true, schemeUrl: "omniget://example.com/v" });
+ assert.deepEqual(events, [
+ ["create", { url: "omniget://example.com/v", active: false }],
+ ]);
+ assert.equal(scheduled.length, 1);
+ assert.equal(scheduled[0].ms, 500);
+
+ // Run the scheduled cleanup: the throwaway tab should be removed.
+ scheduled[0].fn();
+ assert.deepEqual(events[1], ["remove", 1234]);
+});
+
+test("openOmnigetScheme does not navigate the user's active tab", async () => {
+ let updateCalled = false;
+ const tabs = {
+ create: async () => ({ id: 99 }),
+ update: async () => {
+ updateCalled = true;
+ },
+ remove: () => Promise.resolve(),
+ };
+
+ const result = await openOmnigetScheme("https://example.com/v", {
+ tabs,
+ schedule: () => {},
+ });
+
+ assert.equal(result.ok, true);
+ assert.equal(updateCalled, false);
+});
+
+test("openOmnigetScheme returns invalid-url for empty input", async () => {
+ const result = await openOmnigetScheme("", {
+ tabs: { create: async () => ({ id: 1 }), remove: () => Promise.resolve() },
+ schedule: () => {},
+ });
+ assert.deepEqual(result, { ok: false, reason: "invalid-url" });
+});
+
+test("openOmnigetScheme returns tabs-api-unavailable when tabs.create is missing", async () => {
+ const result = await openOmnigetScheme("https://example.com/v", {
+ tabs: {},
+ schedule: () => {},
+ });
+ assert.deepEqual(result, { ok: false, reason: "tabs-api-unavailable" });
+});
+
+test("openOmnigetScheme reports tabs-create-failed when tabs.create throws", async () => {
+ const tabs = {
+ create: async () => {
+ throw new Error("permission denied");
+ },
+ remove: () => Promise.resolve(),
+ };
+
+ const result = await openOmnigetScheme("https://example.com/v", {
+ tabs,
+ schedule: () => {},
+ });
+
+ assert.deepEqual(result, {
+ ok: false,
+ reason: "tabs-create-failed",
+ message: "permission denied",
+ });
+});
+
+test("openOmnigetScheme tolerates a sync remove() that throws", async () => {
+ const tabs = {
+ create: async () => ({ id: 7 }),
+ remove: () => {
+ throw new Error("tab is gone");
+ },
+ };
+
+ const calls = [];
+ const schedule = (fn) => {
+ calls.push(fn);
+ };
+
+ const result = await openOmnigetScheme("https://example.com/v", {
+ tabs,
+ schedule,
+ });
+
+ assert.equal(result.ok, true);
+ assert.doesNotThrow(() => calls[0]());
+});
diff --git a/browser-extension/firefox/manifest.json b/browser-extension/firefox/manifest.json
index 1568f978..99604237 100644
--- a/browser-extension/firefox/manifest.json
+++ b/browser-extension/firefox/manifest.json
@@ -11,7 +11,6 @@
}
},
"permissions": [
- "nativeMessaging",
"tabs",
"cookies",
"webRequest",
@@ -19,6 +18,8 @@
"menus"
],
"host_permissions": [
+ "http://127.0.0.1/*",
+ "http://localhost/*",
"*://*.hotmart.com/*",
"*://*.youtube.com/*",
"*://*.youtube-nocookie.com/*",
@@ -107,5 +108,9 @@
},
"description": "Send current page to OmniGet"
}
+ },
+ "options_ui": {
+ "page": "pages/options.html",
+ "open_in_tab": true
}
}
diff --git a/browser-extension/firefox/pages/options.css b/browser-extension/firefox/pages/options.css
new file mode 100644
index 00000000..3b0e9656
--- /dev/null
+++ b/browser-extension/firefox/pages/options.css
@@ -0,0 +1,225 @@
+:root {
+ color-scheme: dark;
+ font-family: "Segoe UI", system-ui, sans-serif;
+ background:
+ radial-gradient(circle at top, rgba(255, 125, 56, 0.18), transparent 42%),
+ #101114;
+ color: #f5f7fb;
+}
+
+* { box-sizing: border-box; }
+
+body { margin: 0; min-height: 100vh; }
+
+.shell {
+ min-height: 100vh;
+ display: grid;
+ place-items: center;
+ padding: 24px;
+}
+
+.card {
+ width: min(100%, 540px);
+ padding: 28px;
+ border-radius: 20px;
+ background: rgba(18, 20, 26, 0.92);
+ border: 1px solid rgba(255, 255, 255, 0.08);
+ box-shadow: 0 18px 80px rgba(0, 0, 0, 0.4);
+}
+
+.eyebrow {
+ margin: 0 0 10px;
+ font-size: 12px;
+ letter-spacing: 0.12em;
+ text-transform: uppercase;
+ color: #ff9a66;
+}
+
+h1 {
+ margin: 0 0 12px;
+ font-size: clamp(22px, 3vw, 28px);
+ line-height: 1.2;
+}
+
+.body {
+ margin: 0 0 18px;
+ color: #d9deea;
+ font-size: 14px;
+ line-height: 1.55;
+}
+
+form { display: grid; gap: 16px; }
+
+.field {
+ display: grid;
+ gap: 6px;
+ position: relative;
+}
+
+.label {
+ font-size: 13px;
+ color: #95a0b7;
+}
+
+input[type="url"],
+input[type="text"],
+input[type="password"] {
+ width: 100%;
+ min-height: 40px;
+ padding: 0 12px;
+ border-radius: 10px;
+ background: rgba(255, 255, 255, 0.04);
+ color: #f5f7fb;
+ border: 1px solid rgba(255, 255, 255, 0.08);
+ font: inherit;
+}
+
+input:focus {
+ outline: none;
+ border-color: rgba(255, 125, 56, 0.55);
+}
+
+.hint {
+ font-size: 12px;
+ color: #6b7691;
+}
+
+.hint code {
+ background: rgba(255, 255, 255, 0.05);
+ padding: 1px 6px;
+ border-radius: 4px;
+}
+
+.reveal {
+ position: absolute;
+ right: 6px;
+ top: 27px;
+ background: transparent;
+ border: none;
+ color: #95a0b7;
+ cursor: pointer;
+ padding: 4px 8px;
+ border-radius: 6px;
+ font-size: 12px;
+}
+
+.reveal:hover { background: rgba(255, 255, 255, 0.05); color: #f5f7fb; }
+
+.actions {
+ display: flex;
+ gap: 10px;
+ flex-wrap: wrap;
+ margin-top: 4px;
+}
+
+.button {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ min-height: 40px;
+ padding: 0 16px;
+ border: none;
+ border-radius: 999px;
+ appearance: none;
+ cursor: pointer;
+ font: inherit;
+ color: #f5f7fb;
+ background: rgba(255, 255, 255, 0.08);
+}
+
+.button.primary {
+ background: #ff7d38;
+ color: #160d06;
+ font-weight: 700;
+}
+
+.status {
+ margin: 6px 0 0;
+ min-height: 18px;
+ font-size: 13px;
+ color: #95a0b7;
+}
+
+.status.ok { color: #59d8a0; }
+.status.error { color: #ff7d7d; }
+
+.discovery {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding: 10px 12px;
+ border-radius: 10px;
+ background: rgba(255, 255, 255, 0.04);
+ border: 1px solid rgba(255, 255, 255, 0.08);
+ font-size: 13px;
+ color: #d9deea;
+ margin-bottom: 4px;
+}
+.discovery.found {
+ background: rgba(89, 216, 160, 0.08);
+ border-color: rgba(89, 216, 160, 0.35);
+ color: #79e1b3;
+}
+.discovery.missing {
+ background: rgba(255, 125, 125, 0.06);
+ border-color: rgba(255, 125, 125, 0.3);
+ color: #ffb1b1;
+}
+
+.spinner {
+ width: 14px;
+ height: 14px;
+ border-radius: 50%;
+ border: 2px solid rgba(255, 255, 255, 0.18);
+ border-top-color: #ff9a66;
+ animation: spin 0.85s linear infinite;
+}
+.discovery.found .spinner,
+.discovery.missing .spinner { display: none; }
+
+@keyframes spin {
+ to { transform: rotate(360deg); }
+}
+
+.install-help {
+ margin-top: 8px;
+ padding: 10px 12px;
+ border-radius: 10px;
+ border: 1px solid rgba(255, 255, 255, 0.06);
+ background: rgba(255, 255, 255, 0.02);
+ font-size: 13px;
+ color: #95a0b7;
+}
+.install-help summary {
+ cursor: pointer;
+ user-select: none;
+}
+.install-help p {
+ margin: 8px 0 0;
+ line-height: 1.55;
+}
+.install-help a {
+ color: #ff9a66;
+}
+
+.advanced {
+ margin-top: 4px;
+ padding: 10px 12px;
+ border-radius: 10px;
+ border: 1px solid rgba(255, 255, 255, 0.06);
+ background: rgba(255, 255, 255, 0.02);
+ font-size: 13px;
+ color: #95a0b7;
+}
+.advanced summary {
+ cursor: pointer;
+ user-select: none;
+ list-style: none;
+}
+.advanced summary::-webkit-details-marker { display: none; }
+.advanced summary::before {
+ content: "▸ ";
+ color: #6b7691;
+}
+.advanced[open] summary::before { content: "▾ "; }
+.advanced .field { margin-top: 10px; }
diff --git a/browser-extension/firefox/pages/options.html b/browser-extension/firefox/pages/options.html
new file mode 100644
index 00000000..78ef8ae6
--- /dev/null
+++ b/browser-extension/firefox/pages/options.html
@@ -0,0 +1,90 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width,initial-scale=1" />
+ <title>OmniGet Extension — Pair with desktop app</title>
+ <link rel="stylesheet" href="options.css" />
+ </head>
+ <body>
+ <main class="shell">
+ <div class="card" id="card">
+ <p class="eyebrow">OmniGet Extension</p>
+
+ <header id="welcome-header" hidden>
+ <h1>Welcome to OmniGet</h1>
+ <p class="body">
+ Let's connect this browser to the desktop app. We're looking for it
+ now — almost done.
+ </p>
+ </header>
+
+ <header id="settings-header" hidden>
+ <h1>Pair this browser</h1>
+ <p class="body">
+ Open OmniGet, go to <strong>Settings → Network → Browser
+ extension</strong>, then copy the <em>endpoint URL</em> and
+ <em>token</em> shown there into the fields below.
+ </p>
+ </header>
+
+ <div id="discovery-status" class="discovery" role="status" aria-live="polite">
+ <span class="spinner" aria-hidden="true"></span>
+ <span id="discovery-message">Looking for the desktop app on this machine…</span>
+ </div>
+
+ <form id="pair-form" novalidate>
+ <label class="field">
+ <span class="label">Pairing token</span>
+ <input
+ id="token"
+ name="token"
+ type="password"
+ placeholder="Paste the token from OmniGet → Settings → Network → Browser extension"
+ autocomplete="off"
+ spellcheck="false"
+ required
+ />
+ <button id="reveal" type="button" class="reveal" aria-pressed="false">
+ Show
+ </button>
+ </label>
+
+ <details id="advanced" class="advanced">
+ <summary>Advanced: change endpoint URL</summary>
+ <label class="field">
+ <span class="label">Endpoint URL</span>
+ <input
+ id="endpoint"
+ name="endpoint"
+ type="url"
+ placeholder="http://127.0.0.1:47720"
+ autocomplete="off"
+ spellcheck="false"
+ />
+ <span class="hint" id="endpoint-hint">Default: <code>http://127.0.0.1:47720</code></span>
+ </label>
+ </details>
+
+ <div class="actions">
+ <button id="save" type="submit" class="button primary">Save</button>
+ <button id="test" type="button" class="button">Test connection</button>
+ </div>
+
+ <p id="status" class="status" role="status" aria-live="polite"></p>
+ </form>
+
+ <details id="install-help" class="install-help">
+ <summary>Don't have OmniGet installed yet?</summary>
+ <p>
+ Install the desktop app from
+ <a href="https://github.com/tonhowtf/omniget/releases/latest" target="_blank" rel="noreferrer">
+ github.com/tonhowtf/omniget
+ </a>, launch it once, then come back to this page.
+ </p>
+ </details>
+ </div>
+ </main>
+ <script type="module" src="options.js"></script>
+ </body>
+</html>
diff --git a/browser-extension/firefox/pages/options.js b/browser-extension/firefox/pages/options.js
new file mode 100644
index 00000000..54ecd75b
--- /dev/null
+++ b/browser-extension/firefox/pages/options.js
@@ -0,0 +1,129 @@
+import {
+ loadBridgeConfig,
+ saveBridgeConfig,
+ checkBridgeHealth,
+ discoverBridgeEndpoint,
+ trimEndpoint,
+} from "../src/bridge-client.js";
+
+const endpointInput = document.getElementById("endpoint");
+const tokenInput = document.getElementById("token");
+const revealBtn = document.getElementById("reveal");
+const form = document.getElementById("pair-form");
+const testBtn = document.getElementById("test");
+const statusEl = document.getElementById("status");
+const welcomeHeader = document.getElementById("welcome-header");
+const settingsHeader = document.getElementById("settings-header");
+const discoveryEl = document.getElementById("discovery-status");
+const discoveryMessage = document.getElementById("discovery-message");
+const endpointHint = document.getElementById("endpoint-hint");
+const advancedDetails = document.getElementById("advanced");
+
+const FALLBACK_ENDPOINT = "http://127.0.0.1:47720";
+
+function resolvedEndpoint() {
+ return trimEndpoint(endpointInput.value) || FALLBACK_ENDPOINT;
+}
+
+function setStatus(message, kind) {
+ statusEl.textContent = message ?? "";
+ statusEl.classList.remove("ok", "error");
+ if (kind === "ok") statusEl.classList.add("ok");
+ if (kind === "error") statusEl.classList.add("error");
+}
+
+function setDiscovery(state, message) {
+ discoveryEl.classList.remove("found", "missing");
+ if (state === "found") discoveryEl.classList.add("found");
+ if (state === "missing") discoveryEl.classList.add("missing");
+ discoveryMessage.textContent = message;
+}
+
+async function init() {
+ const { endpoint, token } = await loadBridgeConfig();
+ const alreadyPaired = Boolean(token);
+
+ // Show the welcome heading on first run, the regular settings heading
+ // once the user is already paired (they're here to inspect / change).
+ if (alreadyPaired) {
+ settingsHeader.hidden = false;
+ } else {
+ welcomeHeader.hidden = false;
+ }
+
+ endpointInput.value = endpoint || "";
+ tokenInput.value = token || "";
+
+ // Skip auto-discovery if the user is already paired AND we have a stored
+ // endpoint that responds — they're probably here to change the token, no
+ // need to overwrite the URL they trust.
+ if (alreadyPaired) {
+ const result = await checkBridgeHealth(endpoint);
+ if (result.ok) {
+ const versionSuffix = result.version ? ` (v${result.version})` : "";
+ setDiscovery("found", `Connected to OmniGet${versionSuffix} at ${endpoint}.`);
+ return;
+ }
+ setDiscovery(
+ "missing",
+ `Couldn't reach the saved endpoint ${endpoint}. Probing default ports…`
+ );
+ }
+
+ const found = await discoverBridgeEndpoint();
+ if (found) {
+ endpointInput.value = found.endpoint;
+ const versionSuffix = found.version ? ` (v${found.version})` : "";
+ setDiscovery(
+ "found",
+ `Found OmniGet${versionSuffix} on ${found.endpoint}. Paste the token from OmniGet → Settings → Network → Browser extension to finish.`
+ );
+ endpointHint.textContent =
+ "Auto-detected — change only if your OmniGet runs on a different host.";
+ return;
+ }
+
+ // Discovery failed: open the Advanced disclosure so the user can supply
+ // the endpoint manually.
+ if (advancedDetails) advancedDetails.open = true;
+ setDiscovery(
+ "missing",
+ "OmniGet doesn't seem to be running. Launch the desktop app, then refresh this page — or set the endpoint manually below."
+ );
+}
+
+revealBtn.addEventListener("click", () => {
+ const next = tokenInput.type === "password" ? "text" : "password";
+ tokenInput.type = next;
+ revealBtn.textContent = next === "password" ? "Show" : "Hide";
+ revealBtn.setAttribute("aria-pressed", String(next !== "password"));
+});
+
+form.addEventListener("submit", async (event) => {
+ event.preventDefault();
+ const endpoint = resolvedEndpoint();
+ const token = tokenInput.value.trim();
+ if (!token) {
+ setStatus("Paste the pairing token first.", "error");
+ return;
+ }
+ await saveBridgeConfig({ endpoint, token });
+ setStatus("Saved. The extension will use this token from now on.", "ok");
+});
+
+testBtn.addEventListener("click", async () => {
+ const endpoint = resolvedEndpoint();
+ setStatus("Testing connection…");
+ const result = await checkBridgeHealth(endpoint);
+ if (result.ok) {
+ const versionSuffix = result.version ? ` (v${result.version})` : "";
+ setStatus(`Connected to OmniGet${versionSuffix} at ${endpoint}.`, "ok");
+ } else {
+ setStatus(
+ `Could not reach OmniGet at ${endpoint}. Make sure the app is running.`,
+ "error"
+ );
+ }
+});
+
+init();
diff --git a/browser-extension/firefox/src/action-click.js b/browser-extension/firefox/src/action-click.js
index dfa8d8dc..e6aa4855 100644
--- a/browser-extension/firefox/src/action-click.js
+++ b/browser-extension/firefox/src/action-click.js
@@ -1,11 +1,19 @@
const DEFAULT_LAUNCH_FAILED_CODE = "LAUNCH_FAILED";
const PROTOCOL_VERSION = 1;
+// Reusable click handler factored out of background.js so it can be unit-tested
+// in isolation. Transport is injected as `sendToHost` (the localhost bridge in
+// production), with `openSchemeUrl` providing the cookie-less fallback when the
+// app is unreachable. Both callbacks return `{ ok, ... }` results.
+//
+// `sendToHost` is also accepted under the legacy alias `sendNativeMessage` for
+// backwards-compat with tests written before the native-messaging removal.
export async function handleSupportedActionClick({
tabId,
url,
platform,
getCookies,
+ sendToHost,
sendNativeMessage,
clearBadge = async () => {},
showSuccessBadge = async () => {},
@@ -13,6 +21,8 @@ export async function handleSupportedActionClick({
mapChromeErrorCode,
openSchemeUrl = async () => ({ ok: false, reason: "not-wired" }),
}) {
+ const send = sendToHost ?? sendNativeMessage;
+
if (tabId !== undefined && tabId !== null) {
await clearBadge(tabId);
}
@@ -32,7 +42,7 @@ export async function handleSupportedActionClick({
message.cookies = cookies;
}
- const response = await sendNativeMessage(message);
+ const response = await send(message);
if (!response?.ok) {
await openErrorPage({
diff --git a/browser-extension/firefox/src/background.js b/browser-extension/firefox/src/background.js
index f442debd..d5d76213 100644
--- a/browser-extension/firefox/src/background.js
+++ b/browser-extension/firefox/src/background.js
@@ -6,8 +6,8 @@ import { summarizeCookies } from "./cookie-summary.js";
import { loadSnifferState, isSnifferEnabled, setSnifferEnabled } from "./sniffer-toggle.js";
import { registerContextMenu, getContextMenuId } from "./context-menu.js";
import { openOmnigetScheme } from "./send-via-scheme.js";
+import { sendViaBridge, sendCookiesViaBridge } from "./bridge-client.js";
-const HOST_NAME = "wtf.tonho.omniget";
const INSTALL_URL = "https://github.com/tonhowtf/omniget/releases/latest";
const PROTOCOL_VERSION = 1;
@@ -49,9 +49,28 @@ loadSnifferState().then(async (enabled) => {
}
});
-chrome.runtime.onInstalled.addListener(() => {
+chrome.runtime.onInstalled.addListener(async (details) => {
registerContextMenu();
refreshActiveTab().catch(() => {});
+ // Surface the pairing page on any install/update *if the user hasn't
+ // already paired this browser*. Reloading an unpacked extension fires
+ // `update`, not `install`, so gating only on `install` would silently
+ // skip the onboarding flow for dev builds and users coming from a
+ // pre-bridge OmniGet version.
+ if (typeof chrome.runtime.openOptionsPage !== "function") return;
+ try {
+ const stored = await chrome.storage.local.get("bridge_token");
+ const token = typeof stored?.bridge_token === "string" ? stored.bridge_token.trim() : "";
+ if (!token) {
+ chrome.runtime.openOptionsPage().catch(() => {});
+ }
+ } catch {
+ // storage unavailable — fall back to the previous behaviour and only
+ // open on a real install.
+ if (details?.reason === "install") {
+ chrome.runtime.openOptionsPage().catch(() => {});
+ }
+ }
});
chrome.contextMenus.onClicked.addListener(async (info, tab) => {
@@ -276,16 +295,27 @@ async function handleSendToApp(msg) {
const cookieSummary = summarizeCookies(cookies);
- try {
- const response = await sendNativeMessage(message);
- return { ok: response?.ok ?? false, cookieSummary };
- } catch (e) {
- const schemeResult = await openOmnigetScheme(url);
- if (schemeResult?.ok) {
- return { ok: true, viaScheme: true, cookieSummary };
- }
- return { ok: false, error: e.message };
+ // Primary path: localhost HTTP bridge (no extension-ID dependency, full
+ // cookie + metadata payload).
+ const bridgeResult = await sendViaBridge(message);
+ if (bridgeResult?.ok) {
+ return { ok: true, viaBridge: true, cookieSummary };
}
+
+ // Fallback: omniget:// scheme handler. The desktop app is launched (or
+ // brought to focus) and the URL is queued, but cookies aren't forwarded
+ // — the user can pair the bridge from the extension's options page to
+ // get the full experience.
+ const schemeResult = await openOmnigetScheme(url);
+ if (schemeResult?.ok) {
+ return { ok: true, viaScheme: true, cookieSummary, bridgeReason: bridgeResult?.reason };
+ }
+ return {
+ ok: false,
+ error: bridgeResult?.message || schemeResult?.message || "OmniGet is not reachable",
+ bridgeReason: bridgeResult?.reason,
+ schemeReason: schemeResult?.reason,
+ };
}
async function refreshActiveTab() {
@@ -327,18 +357,6 @@ function isTabGoneError(error) {
return msg.includes("No tab with id");
}
-function sendNativeMessage(message) {
- return new Promise((resolve, reject) => {
- chrome.runtime.sendNativeMessage(HOST_NAME, message, (response) => {
- if (chrome.runtime.lastError) {
- reject(new Error(chrome.runtime.lastError.message));
- return;
- }
- resolve(response);
- });
- });
-}
-
const COOKIE_AUTO_CAPTURE_DEBOUNCE_MS = 1500;
const COOKIE_AUTO_CAPTURE_MIN_INTERVAL_MS = 60_000;
const cookieDebounceTimers = new Map();
@@ -453,25 +471,13 @@ async function capturePlatformCookies(platform, force = false) {
return { ok: false, reason: "no_cookies" };
}
- try {
- const response = await sendNativeMessage({
- type: "cookies:export",
- protocolVersion: PROTOCOL_VERSION,
- platform,
- cookies,
- timestamp: Date.now(),
- });
- console.info(
- "[OmniGet] cookies exported",
- platform,
- cookies.length,
- response,
- );
+ const response = await sendCookiesViaBridge(cookies);
+ if (response.ok) {
+ console.info("[OmniGet] cookies exported", platform, cookies.length, response);
return { ok: true, count: cookies.length, response };
- } catch (e) {
- console.warn("[OmniGet] cookie export failed", platform, e.message);
- return { ok: false, reason: "host_unreachable", error: e.message };
}
+ console.warn("[OmniGet] cookie export failed", platform, response.reason ?? response.message);
+ return { ok: false, reason: response.reason ?? "bridge_failed", response };
}
async function scanOpenTabsForCookies() {
diff --git a/browser-extension/firefox/src/bridge-client.js b/browser-extension/firefox/src/bridge-client.js
new file mode 100644
index 00000000..2dd2ed31
--- /dev/null
+++ b/browser-extension/firefox/src/bridge-client.js
@@ -0,0 +1,303 @@
+// Localhost HTTP bridge client.
+//
+// Replaces native messaging: instead of relying on Chrome's native-messaging
+// manifest (which requires hard-coded extension IDs in the desktop app), we
+// POST the same payload to the OmniGet desktop app's local HTTP listener,
+// authenticating each request with a bearer token the user pastes once into
+// the extension's options page.
+//
+// Lookup contract:
+// - The user copies `endpoint` (e.g. http://127.0.0.1:47720) and `token`
+// from the OmniGet Settings UI into the extension's Options page.
+// - chrome.storage.local stores them under the keys below.
+// - If either value is missing the bridge is considered "unpaired" and the
+// caller falls through to the omniget:// scheme handler.
+
+export const STORAGE_KEY_ENDPOINT = "bridge_endpoint";
+export const STORAGE_KEY_TOKEN = "bridge_token";
+const HEALTH_TIMEOUT_MS = 1500;
+const ENQUEUE_TIMEOUT_MS = 8000;
+const PROTOCOL_VERSION = 1;
+const DEFAULT_ENDPOINT = "http://127.0.0.1:47720";
+// Mirrors `PORT_RANGE` in src-tauri/src/local_bridge.rs — kept narrow so the
+// auto-discovery probe is fast.
+export const DEFAULT_PORT_RANGE = [
+ 47720, 47721, 47722, 47723, 47724, 47725, 47726, 47727, 47728, 47729,
+];
+
+export function trimEndpoint(value) {
+ if (typeof value !== "string") return "";
+ let trimmed = value.trim();
+ if (!trimmed) return "";
+ while (trimmed.endsWith("/")) {
+ trimmed = trimmed.slice(0, -1);
+ }
+ return trimmed;
+}
+
+export async function loadBridgeConfig({ storage = globalThis.chrome?.storage?.local } = {}) {
+ if (!storage?.get) {
+ return { endpoint: "", token: "" };
+ }
+ return new Promise((resolve) => {
+ storage.get([STORAGE_KEY_ENDPOINT, STORAGE_KEY_TOKEN], (items) => {
+ const endpoint = trimEndpoint(items?.[STORAGE_KEY_ENDPOINT]) || DEFAULT_ENDPOINT;
+ const token = typeof items?.[STORAGE_KEY_TOKEN] === "string" ? items[STORAGE_KEY_TOKEN].trim() : "";
+ resolve({ endpoint, token });
+ });
+ });
+}
+
+export async function saveBridgeConfig(
+ { endpoint = "", token = "" },
+ { storage = globalThis.chrome?.storage?.local } = {}
+) {
+ if (!storage?.set) return false;
+ return new Promise((resolve) => {
+ storage.set(
+ {
+ [STORAGE_KEY_ENDPOINT]: trimEndpoint(endpoint),
+ [STORAGE_KEY_TOKEN]: typeof token === "string" ? token.trim() : "",
+ },
+ () => resolve(true)
+ );
+ });
+}
+
+function withTimeout(promise, ms, controller) {
+ return new Promise((resolve, reject) => {
+ const timer = setTimeout(() => {
+ try {
+ controller?.abort();
+ } catch {}
+ reject(new Error(`bridge timed out after ${ms}ms`));
+ }, ms);
+ promise.then(
+ (value) => {
+ clearTimeout(timer);
+ resolve(value);
+ },
+ (error) => {
+ clearTimeout(timer);
+ reject(error);
+ }
+ );
+ });
+}
+
+// Probes the bridge port range in parallel and returns the first endpoint
+// that answers `/v1/health` with `ok: true`. Used by the options page to
+// pre-fill the URL without making the user discover the port by hand.
+export async function discoverBridgeEndpoint({
+ fetchImpl = typeof fetch !== "undefined" ? fetch : null,
+ ports = DEFAULT_PORT_RANGE,
+ host = "127.0.0.1",
+ timeoutMs = HEALTH_TIMEOUT_MS,
+} = {}) {
+ if (!fetchImpl) return null;
+ const probes = ports.map(async (port) => {
+ const endpoint = `http://${host}:${port}`;
+ const result = await checkBridgeHealth(endpoint, { fetchImpl, timeoutMs });
+ return result.ok ? { endpoint, version: result.version ?? null } : null;
+ });
+
+ const settled = await Promise.allSettled(probes);
+ for (const result of settled) {
+ if (result.status === "fulfilled" && result.value) {
+ return result.value;
+ }
+ }
+ return null;
+}
+
+export async function checkBridgeHealth(
+ endpoint,
+ { fetchImpl = (typeof fetch !== "undefined" ? fetch : null), timeoutMs = HEALTH_TIMEOUT_MS } = {}
+) {
+ if (!fetchImpl) return { ok: false, reason: "no-fetch" };
+ const target = trimEndpoint(endpoint);
+ if (!target) return { ok: false, reason: "no-endpoint" };
+
+ const controller = typeof AbortController !== "undefined" ? new AbortController() : null;
+ try {
+ const response = await withTimeout(
+ fetchImpl(`${target}/v1/health`, {
+ method: "GET",
+ signal: controller?.signal,
+ }),
+ timeoutMs,
+ controller
+ );
+ if (!response.ok) {
+ return { ok: false, reason: "http-error", status: response.status };
+ }
+ const body = await response.json().catch(() => null);
+ return { ok: Boolean(body?.ok), version: body?.version ?? null };
+ } catch (error) {
+ return { ok: false, reason: "fetch-failed", message: error?.message ?? String(error) };
+ }
+}
+
+export async function sendViaBridge(
+ payload,
+ {
+ fetchImpl = (typeof fetch !== "undefined" ? fetch : null),
+ storage = globalThis.chrome?.storage?.local,
+ timeoutMs = ENQUEUE_TIMEOUT_MS,
+ config = null,
+ } = {}
+) {
+ if (!fetchImpl) {
+ return { ok: false, reason: "no-fetch" };
+ }
+
+ const resolved = config ?? (await loadBridgeConfig({ storage }));
+ const endpoint = trimEndpoint(resolved.endpoint);
+ const token = typeof resolved.token === "string" ? resolved.token.trim() : "";
+
+ if (!endpoint) {
+ return { ok: false, reason: "missing-endpoint" };
+ }
+ if (!token) {
+ return { ok: false, reason: "missing-token" };
+ }
+
+ const body = { ...payload, protocolVersion: PROTOCOL_VERSION };
+
+ const controller = typeof AbortController !== "undefined" ? new AbortController() : null;
+ let response;
+ try {
+ response = await withTimeout(
+ fetchImpl(`${endpoint}/v1/enqueue`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: `Bearer ${token}`,
+ },
+ body: JSON.stringify(body),
+ signal: controller?.signal,
+ }),
+ timeoutMs,
+ controller
+ );
+ } catch (error) {
+ return {
+ ok: false,
+ reason: "fetch-failed",
+ message: error?.message ?? String(error),
+ };
+ }
+
+ let parsed = null;
+ try {
+ parsed = await response.json();
+ } catch {
+ parsed = null;
+ }
+
+ if (response.status === 401 || response.status === 403) {
+ return {
+ ok: false,
+ reason: "unauthorized",
+ status: response.status,
+ message: parsed?.message ?? "Bridge rejected the bearer token",
+ };
+ }
+ if (!response.ok) {
+ return {
+ ok: false,
+ reason: "http-error",
+ status: response.status,
+ code: parsed?.code ?? null,
+ message: parsed?.message ?? `HTTP ${response.status}`,
+ };
+ }
+
+ return {
+ ok: Boolean(parsed?.ok ?? false),
+ code: parsed?.code ?? null,
+ message: parsed?.message ?? null,
+ };
+}
+
+export async function sendCookiesViaBridge(
+ cookies,
+ {
+ fetchImpl = (typeof fetch !== "undefined" ? fetch : null),
+ storage = globalThis.chrome?.storage?.local,
+ timeoutMs = ENQUEUE_TIMEOUT_MS,
+ config = null,
+ } = {}
+) {
+ if (!fetchImpl) {
+ return { ok: false, reason: "no-fetch" };
+ }
+
+ const resolved = config ?? (await loadBridgeConfig({ storage }));
+ const endpoint = trimEndpoint(resolved.endpoint);
+ const token = typeof resolved.token === "string" ? resolved.token.trim() : "";
+
+ if (!endpoint) {
+ return { ok: false, reason: "missing-endpoint" };
+ }
+ if (!token) {
+ return { ok: false, reason: "missing-token" };
+ }
+
+ const body = { cookies, protocolVersion: PROTOCOL_VERSION };
+
+ const controller = typeof AbortController !== "undefined" ? new AbortController() : null;
+ let response;
+ try {
+ response = await withTimeout(
+ fetchImpl(`${endpoint}/v1/cookies`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: `Bearer ${token}`,
+ },
+ body: JSON.stringify(body),
+ signal: controller?.signal,
+ }),
+ timeoutMs,
+ controller
+ );
+ } catch (error) {
+ return {
+ ok: false,
+ reason: "fetch-failed",
+ message: error?.message ?? String(error),
+ };
+ }
+
+ let parsed = null;
+ try {
+ parsed = await response.json();
+ } catch {
+ parsed = null;
+ }
+
+ if (response.status === 401 || response.status === 403) {
+ return {
+ ok: false,
+ reason: "unauthorized",
+ status: response.status,
+ message: parsed?.message ?? "Bridge rejected the bearer token",
+ };
+ }
+ if (!response.ok) {
+ return {
+ ok: false,
+ reason: "http-error",
+ status: response.status,
+ code: parsed?.code ?? null,
+ message: parsed?.message ?? `HTTP ${response.status}`,
+ };
+ }
+
+ return {
+ ok: Boolean(parsed?.ok ?? false),
+ code: parsed?.code ?? null,
+ message: parsed?.message ?? null,
+ };
+}
diff --git a/browser-extension/firefox/src/send-via-scheme.js b/browser-extension/firefox/src/send-via-scheme.js
index 8547820c..403f39d5 100644
--- a/browser-extension/firefox/src/send-via-scheme.js
+++ b/browser-extension/firefox/src/send-via-scheme.js
@@ -1,4 +1,5 @@
export const OMNIGET_SCHEME = "omniget://";
+const SCHEME_TAB_LIFETIME_MS = 1500;
export function buildOmnigetSchemeUrl(url) {
if (typeof url !== "string") {
@@ -21,21 +22,45 @@ export function buildOmnigetSchemeUrl(url) {
return `${OMNIGET_SCHEME}${withoutProtocol}`;
}
-export async function openOmnigetScheme(url, { tabs } = { tabs: chrome?.tabs }) {
+// Opens the omniget:// scheme in a hidden background tab so the OS can route
+// it to the desktop app, without disturbing the user's currently focused tab.
+// We close the throwaway tab shortly after creation since the page itself has
+// no meaningful content (the protocol handler runs out-of-process).
+export async function openOmnigetScheme(
+ url,
+ {
+ tabs = chrome?.tabs,
+ schedule = (fn, ms) => setTimeout(fn, ms),
+ tabLifetimeMs = SCHEME_TAB_LIFETIME_MS,
+ } = {}
+) {
const schemeUrl = buildOmnigetSchemeUrl(url);
if (!schemeUrl) {
return { ok: false, reason: "invalid-url" };
}
- if (!tabs?.update) {
+ if (!tabs?.create) {
return { ok: false, reason: "tabs-api-unavailable" };
}
try {
- await tabs.update({ url: schemeUrl });
+ const newTab = await tabs.create({ url: schemeUrl, active: false });
+ const tabId = newTab?.id;
+ if (typeof tabId === "number" && typeof tabs.remove === "function") {
+ schedule(() => {
+ try {
+ const removeResult = tabs.remove(tabId);
+ if (removeResult && typeof removeResult.catch === "function") {
+ removeResult.catch(() => {});
+ }
+ } catch {
+ // Tab may already be gone; ignore.
+ }
+ }, tabLifetimeMs);
+ }
return { ok: true, schemeUrl };
} catch (error) {
return {
ok: false,
- reason: "tabs-update-failed",
+ reason: "tabs-create-failed",
message: error instanceof Error ? error.message : String(error),
};
}
diff --git a/browser-extension/sync.mjs b/browser-extension/sync.mjs
index a129bbaa..01bd6597 100644
--- a/browser-extension/sync.mjs
+++ b/browser-extension/sync.mjs
@@ -14,6 +14,7 @@ const SHARED = [
"src/action-title.js",
"src/background.js",
"src/blocked-hosts.js",
+ "src/bridge-client.js",
"src/context-menu.js",
"src/cookie-summary.js",
"src/cookies.js",
@@ -33,6 +34,9 @@ const SHARED = [
"pages/error.css",
"pages/error.js",
"pages/error-content.js",
+ "pages/options.html",
+ "pages/options.css",
+ "pages/options.js",
];
const SHARED_DIRS = ["_locales", "icons"];
diff --git a/flatpak/wtf.tonho.omniget.desktop b/flatpak/wtf.tonho.omniget.desktop
index 44fcb6d6..cc88bdf7 100644
--- a/flatpak/wtf.tonho.omniget.desktop
+++ b/flatpak/wtf.tonho.omniget.desktop
@@ -2,10 +2,11 @@
Name=Omniget
Comment=Download media from multiple platforms
GenericName=Download Manager
-Exec=omniget
+Exec=omniget %u
Icon=wtf.tonho.omniget
Terminal=false
Type=Application
Categories=Network;FileTransfer;Utility;
Keywords=omniget;download;downloader;video;media;udemy;hotmart;youtube;telegram;
StartupWMClass=omniget
+MimeType=x-scheme-handler/omniget;
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock
index 087f3355..6dc2a2a5 100644
--- a/src-tauri/Cargo.lock
+++ b/src-tauri/Cargo.lock
@@ -323,6 +323,54 @@ version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8"
+[[package]]
+name = "axum"
+version = "0.8.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90"
+dependencies = [
+ "axum-core",
+ "bytes",
+ "futures-util",
+ "http",
+ "http-body",
+ "http-body-util",
+ "hyper",
+ "hyper-util",
+ "itoa",
+ "matchit",
+ "memchr",
+ "mime",
+ "percent-encoding",
+ "pin-project-lite",
+ "serde_core",
+ "serde_json",
+ "serde_path_to_error",
+ "sync_wrapper",
+ "tokio",
+ "tower",
+ "tower-layer",
+ "tower-service",
+]
+
+[[package]]
+name = "axum-core"
+version = "0.5.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1"
+dependencies = [
+ "bytes",
+ "futures-core",
+ "http",
+ "http-body",
+ "http-body-util",
+ "mime",
+ "pin-project-lite",
+ "sync_wrapper",
+ "tower-layer",
+ "tower-service",
+]
+
[[package]]
name = "backoff"
version = "0.4.0"
@@ -760,6 +808,12 @@ dependencies = [
"typewit",
]
+[[package]]
+name = "constant_time_eq"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b"
+
[[package]]
name = "convert_case"
version = "0.4.0"
@@ -2136,6 +2190,12 @@ version = "1.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"
+[[package]]
+name = "httpdate"
+version = "1.0.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"
+
[[package]]
name = "hyper"
version = "1.8.1"
@@ -2150,6 +2210,7 @@ dependencies = [
"http",
"http-body",
"httparse",
+ "httpdate",
"itoa",
"pin-project-lite",
"pin-utils",
@@ -2995,6 +3056,12 @@ version = "0.1.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2532096657941c2fea9c289d370a250971c689d4f143798ff67113ec042024a5"
+[[package]]
+name = "matchit"
+version = "0.8.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3"
+
[[package]]
name = "memchr"
version = "2.8.0"
@@ -3540,9 +3607,11 @@ dependencies = [
"aes",
"anyhow",
"async-trait",
+ "axum",
"base64 0.22.1",
"cbc",
"chrono",
+ "constant_time_eq",
"dirs 6.0.0",
"discord-rich-presence",
"filetime",
@@ -3561,6 +3630,7 @@ dependencies = [
"serde",
"serde_json",
"sha2",
+ "socket2",
"tar",
"tauri",
"tauri-build",
@@ -3578,6 +3648,7 @@ dependencies = [
"tauri-plugin-updater",
"tokio",
"tokio-util",
+ "tower-http",
"tracing",
"tracing-subscriber",
"unicode-normalization",
@@ -4985,6 +5056,17 @@ dependencies = [
"zmij",
]
+[[package]]
+name = "serde_path_to_error"
+version = "0.1.20"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457"
+dependencies = [
+ "itoa",
+ "serde",
+ "serde_core",
+]
+
[[package]]
name = "serde_repr"
version = "0.1.20"
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index 6b9100fa..251a080b 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -37,6 +37,10 @@ anyhow = "1"
tracing = "0.1"
tracing-subscriber = "0.3"
uuid = { version = "1", features = ["v4"] }
+axum = { version = "0.8", default-features = false, features = ["http1", "json", "tokio"] }
+tower-http = { version = "0.6", features = ["cors"] }
+constant_time_eq = "0.4"
+socket2 = "0.6"
chrono = { version = "0.4", features = ["serde"] }
dirs = "6"
sanitize-filename = "0.6"
diff --git a/src-tauri/omniget-core/src/models/settings.rs b/src-tauri/omniget-core/src/models/settings.rs
index 8f7ec03b..1bee40dc 100644
--- a/src-tauri/omniget-core/src/models/settings.rs
+++ b/src-tauri/omniget-core/src/models/settings.rs
@@ -27,6 +27,8 @@ pub struct AppSettings {
pub typography: TypographySettings,
#[serde(default)]
pub rpc: RpcSettings,
+ #[serde(default)]
+ pub bridge: BridgeSettings,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -270,6 +272,41 @@ fn default_spacing_scale() -> f32 {
1.0
}
+/// Local HTTP bridge that lets the browser extension talk to the desktop app
+/// without depending on a Chrome native-messaging manifest (which would
+/// otherwise force us to maintain an explicit allowlist of extension IDs).
+///
+/// The token is generated lazily on first launch and shown in the app
+/// Settings; the user pastes it into the extension's options page once,
+/// after which the extension authenticates each request with
+/// `Authorization: Bearer <token>`.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct BridgeSettings {
+ #[serde(default = "default_bridge_enabled")]
+ pub enabled: bool,
+ /// Bound port on `127.0.0.1`. `0` means "pick at startup, then persist".
+ #[serde(default)]
+ pub port: u16,
+ /// Random token used to authenticate extension requests.
+ /// Empty means "regenerate on next launch".
+ #[serde(default)]
+ pub token: String,
+}
+
+impl Default for BridgeSettings {
+ fn default() -> Self {
+ Self {
+ enabled: default_bridge_enabled(),
+ port: 0,
+ token: String::new(),
+ }
+ }
+}
+
+fn default_bridge_enabled() -> bool {
+ true
+}
+
impl Default for TypographySettings {
fn default() -> Self {
Self {
@@ -343,6 +380,7 @@ impl Default for AppSettings {
last_download_options: LastDownloadOptions::default(),
typography: TypographySettings::default(),
rpc: RpcSettings::default(),
+ bridge: BridgeSettings::default(),
}
}
}
diff --git a/src-tauri/src/commands/extension_cookies.rs b/src-tauri/src/commands/extension_cookies.rs
index 67f2df4e..16147eeb 100644
--- a/src-tauri/src/commands/extension_cookies.rs
+++ b/src-tauri/src/commands/extension_cookies.rs
@@ -2,7 +2,7 @@ use std::collections::BTreeMap;
use serde::Serialize;
-use crate::native_host::extension_cookie_file_path;
+use crate::extension_storage::extension_cookie_file_path;
#[derive(Debug, Serialize)]
pub struct ExtensionCookiesStatus {
diff --git a/src-tauri/src/commands/settings.rs b/src-tauri/src/commands/settings.rs
index 6cc15adb..81bc5c8d 100644
--- a/src-tauri/src/commands/settings.rs
+++ b/src-tauri/src/commands/settings.rs
@@ -85,6 +85,44 @@ pub fn mark_legal_acknowledged(app: tauri::AppHandle) -> Result<(), String> {
Ok(())
}
+#[derive(serde::Serialize)]
+pub struct BridgeInfo {
+ pub enabled: bool,
+ pub port: u16,
+ pub token: String,
+ pub url: String,
+}
+
+/// Returns the localhost bridge connection info for the Settings UI.
+///
+/// `port == 0` means the bridge has not finished binding yet (the user can
+/// retry shortly). `token` may be empty until the first run completes.
+#[tauri::command]
+pub fn get_bridge_info(app: tauri::AppHandle) -> Result<BridgeInfo, String> {
+ let settings = config::load_settings(&app);
+ let url = if settings.bridge.port == 0 {
+ String::new()
+ } else {
+ crate::local_bridge::build_pairing_url(settings.bridge.port)
+ };
+ Ok(BridgeInfo {
+ enabled: settings.bridge.enabled,
+ port: settings.bridge.port,
+ token: settings.bridge.token,
+ url,
+ })
+}
+
+/// Forces a fresh token to be generated. Used by the Settings UI when the
+/// user wants to revoke a previously-paired browser.
+#[tauri::command]
+pub fn rotate_bridge_token(app: tauri::AppHandle) -> Result<BridgeInfo, String> {
+ let mut current = config::load_settings(&app);
+ current.bridge.token = crate::local_bridge::generate_token();
+ config::save_settings(&app, &current).map_err(|e| format!("Save: {}", e))?;
+ get_bridge_info(app)
+}
+
fn merge_json(base: &mut serde_json::Value, patch: &serde_json::Value) {
if let (Some(base_obj), Some(patch_obj)) = (base.as_object_mut(), patch.as_object()) {
for (key, value) in patch_obj {
diff --git a/src-tauri/src/extension_storage.rs b/src-tauri/src/extension_storage.rs
new file mode 100644
index 00000000..5841a631
--- /dev/null
+++ b/src-tauri/src/extension_storage.rs
@@ -0,0 +1,512 @@
+//! Disk-backed storage for cookies and per-URL metadata supplied by the browser
+//! extension.
+//!
+//! The extension communicates with the desktop app over the local HTTP bridge
+//! (see `local_bridge.rs`); this module is the only place that knows how to
+//! turn the extension's payloads into the on-disk artefacts that yt-dlp and
+//! `external_url::queue_url_with_defaults` expect:
+//!
+//! * a Netscape-format cookie file consumed by yt-dlp's `--cookies` flag,
+//! * a small JSON map keyed by URL with metadata (referer, headers, title, …)
+//! that survives the very short window between the extension request and the
+//! moment the queue worker picks the URL up.
+//!
+//! There is intentionally no networking code here: the bridge module owns the
+//! HTTP listener and calls into the helpers below.
+
+use std::collections::HashMap;
+use std::fs;
+use std::path::PathBuf;
+
+use serde::{Deserialize, Serialize};
+
+const MAX_COOKIES_PER_REQUEST: usize = 500;
+const METADATA_TTL_SECS: u64 = 60;
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+pub struct ExtensionCookie {
+ pub domain: String,
+ #[serde(rename = "httpOnly")]
+ pub http_only: bool,
+ pub path: String,
+ pub secure: bool,
+ pub expires: i64,
+ pub name: String,
+ pub value: String,
+ #[serde(default, rename = "hostOnly")]
+ pub host_only: Option<bool>,
+ #[serde(default, rename = "sameSite")]
+ pub same_site: Option<String>,
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+pub struct ExtensionPayload {
+ pub url: String,
+ #[serde(default)]
+ pub cookies: Option<Vec<ExtensionCookie>>,
+ #[serde(default)]
+ pub referer: Option<String>,
+ #[serde(default)]
+ pub headers: Option<HashMap<String, String>>,
+ #[serde(default, rename = "mediaType")]
+ pub media_type: Option<String>,
+ #[serde(default, rename = "contentType")]
+ pub content_type: Option<String>,
+ #[serde(default)]
+ pub title: Option<String>,
+ #[serde(default)]
+ pub thumbnail: Option<String>,
+ #[serde(default, rename = "openApp")]
+ pub open_app: Option<bool>,
+ #[serde(default, rename = "pageUrl")]
+ pub page_url: Option<String>,
+ #[serde(default, rename = "userAgent")]
+ pub user_agent: Option<String>,
+}
+
+pub fn cookie_limit() -> usize {
+ MAX_COOKIES_PER_REQUEST
+}
+
+pub fn extension_cookie_file_path() -> PathBuf {
+ crate::core::paths::app_data_dir()
+ .unwrap_or_else(|| PathBuf::from("."))
+ .join("chrome-extension-cookies.txt")
+}
+
+fn sanitize_cookie_field(s: &str) -> String {
+ s.chars()
+ .filter(|c| *c != '\n' && *c != '\r' && *c != '\t')
+ .collect()
+}
+
+fn root_domain_of(host: &str) -> String {
+ let h = host.trim_start_matches('.').to_lowercase();
+ let parts: Vec<&str> = h.split('.').collect();
+ if parts.len() >= 2 {
+ parts[parts.len() - 2..].join(".")
+ } else {
+ h
+ }
+}
+
+fn format_cookie_line(c: &ExtensionCookie, session_ttl: u64) -> String {
+ let raw_domain = sanitize_cookie_field(&c.domain);
+ let path_field = sanitize_cookie_field(&c.path);
+ let name = sanitize_cookie_field(&c.name);
+ let value = sanitize_cookie_field(&c.value);
+ let http_only_prefix = if c.http_only { "#HttpOnly_" } else { "" };
+ let is_host_only = c
+ .host_only
+ .unwrap_or_else(|| !raw_domain.starts_with('.'));
+ let (domain, include_subdomains) = if is_host_only {
+ let stripped = raw_domain
+ .strip_prefix('.')
+ .unwrap_or(&raw_domain)
+ .to_string();
+ (stripped, "FALSE")
+ } else if raw_domain.starts_with('.') {
+ (raw_domain.clone(), "TRUE")
+ } else {
+ (format!(".{}", raw_domain), "TRUE")
+ };
+ let secure = if c.secure { "TRUE" } else { "FALSE" };
+ let expires = if c.expires == 0 {
+ session_ttl
+ } else {
+ c.expires as u64
+ };
+ format!(
+ "{}{}\t{}\t{}\t{}\t{}\t{}\t{}\n",
+ http_only_prefix, domain, include_subdomains, path_field, secure, expires, name, value,
+ )
+}
+
+pub fn write_extension_cookies(cookies: &[ExtensionCookie]) -> anyhow::Result<()> {
+ let path = extension_cookie_file_path();
+ if let Some(parent) = path.parent() {
+ fs::create_dir_all(parent)?;
+ }
+
+ // Session cookies (expires == 0) must be given a future TTL.
+ // Python's MozillaCookieJar treats 0 as "expired at epoch" and discards
+ // the cookie, which strips auth context and breaks yt-dlp downloads.
+ let now = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_secs();
+ let session_ttl = now + 86400; // 24 h, same approach as Cookie-Editor
+
+ // Merge with existing file: keep cookies whose root domain is NOT in the
+ // incoming batch. Each platform capture only ships its own domains, so
+ // overwriting the file would wipe other platforms' auth.
+ let incoming_roots: std::collections::HashSet<String> = cookies
+ .iter()
+ .map(|c| root_domain_of(&c.domain))
+ .collect();
+
+ let mut preserved: Vec<String> = Vec::new();
+ if let Ok(existing) = fs::read_to_string(&path) {
+ for line in existing.lines() {
+ let trimmed = line.trim();
+ if trimmed.is_empty() {
+ continue;
+ }
+ let effective = if let Some(rest) = trimmed.strip_prefix("#HttpOnly_") {
+ rest
+ } else if trimmed.starts_with('#') {
+ continue; // header / comment
+ } else {
+ trimmed
+ };
+ let parts: Vec<&str> = effective.split('\t').collect();
+ if parts.len() < 7 {
+ continue;
+ }
+ let domain = parts[0];
+ let root = root_domain_of(domain);
+ if !incoming_roots.contains(&root) {
+ preserved.push(line.to_string());
+ }
+ }
+ }
+
+ let mut content = String::from("# Netscape HTTP Cookie File\n");
+ for line in &preserved {
+ content.push_str(line);
+ content.push('\n');
+ }
+ for c in cookies {
+ content.push_str(&format_cookie_line(c, session_ttl));
+ }
+
+ fs::write(&path, content)?;
+
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600))?;
+ }
+
+ Ok(())
+}
+
+fn extension_metadata_path() -> PathBuf {
+ crate::core::paths::app_data_dir()
+ .unwrap_or_else(|| PathBuf::from("."))
+ .join("extension-metadata.json")
+}
+
+fn current_unix_timestamp() -> u64 {
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_secs()
+}
+
+fn load_metadata_map(path: &std::path::Path) -> serde_json::Map<String, serde_json::Value> {
+ let content = match fs::read_to_string(path) {
+ Ok(c) => c,
+ Err(_) => return serde_json::Map::new(),
+ };
+ let parsed: serde_json::Value = match serde_json::from_str(&content) {
+ Ok(v) => v,
+ Err(_) => return serde_json::Map::new(),
+ };
+ match parsed {
+ serde_json::Value::Object(map) => map,
+ _ => serde_json::Map::new(),
+ }
+}
+
+fn prune_expired_metadata(
+ map: &mut serde_json::Map<String, serde_json::Value>,
+ now: u64,
+) {
+ map.retain(|_, v| {
+ v.get("timestamp")
+ .and_then(|t| t.as_u64())
+ .map(|ts| now.saturating_sub(ts) <= METADATA_TTL_SECS)
+ .unwrap_or(false)
+ });
+}
+
+fn write_metadata_map(
+ path: &std::path::Path,
+ map: &serde_json::Map<String, serde_json::Value>,
+) -> anyhow::Result<()> {
+ if map.is_empty() {
+ let _ = fs::remove_file(path);
+ return Ok(());
+ }
+ let serialized = serde_json::to_string(&serde_json::Value::Object(map.clone()))?;
+ fs::write(path, serialized)?;
+ Ok(())
+}
+
+pub fn write_extension_metadata(payload: &ExtensionPayload) -> anyhow::Result<()> {
+ let path = extension_metadata_path();
+ if let Some(parent) = path.parent() {
+ fs::create_dir_all(parent)?;
+ }
+
+ let now = current_unix_timestamp();
+ let mut map = load_metadata_map(&path);
+ prune_expired_metadata(&mut map, now);
+
+ let entry = serde_json::json!({
+ "referer": payload.referer,
+ "headers": payload.headers,
+ "mediaType": payload.media_type,
+ "contentType": payload.content_type,
+ "title": payload.title,
+ "thumbnail": payload.thumbnail,
+ "openApp": payload.open_app,
+ "pageUrl": payload.page_url,
+ "userAgent": payload.user_agent,
+ "timestamp": now,
+ });
+
+ map.insert(payload.url.clone(), entry);
+ write_metadata_map(&path, &map)?;
+ Ok(())
+}
+
+pub struct ExtensionMetadata {
+ pub referer: Option<String>,
+ pub headers: Option<HashMap<String, String>>,
+ pub media_type: Option<String>,
+ pub content_type: Option<String>,
+ pub title: Option<String>,
+ pub thumbnail: Option<String>,
+ pub open_app: Option<bool>,
+ pub page_url: Option<String>,
+ pub user_agent: Option<String>,
+}
+
+fn parse_metadata_entry(meta: &serde_json::Value) -> ExtensionMetadata {
+ let headers = meta.get("headers").and_then(|v| v.as_object()).map(|obj| {
+ obj.iter()
+ .filter_map(|(k, v)| Some((k.clone(), v.as_str()?.to_string())))
+ .collect::<HashMap<String, String>>()
+ });
+
+ ExtensionMetadata {
+ referer: meta
+ .get("referer")
+ .and_then(|v| v.as_str())
+ .map(String::from),
+ headers,
+ media_type: meta
+ .get("mediaType")
+ .and_then(|v| v.as_str())
+ .map(String::from),
+ content_type: meta
+ .get("contentType")
+ .and_then(|v| v.as_str())
+ .map(String::from),
+ title: meta
+ .get("title")
+ .and_then(|v| v.as_str())
+ .filter(|s| !s.is_empty())
+ .map(String::from),
+ thumbnail: meta
+ .get("thumbnail")
+ .and_then(|v| v.as_str())
+ .filter(|s| !s.is_empty())
+ .map(String::from),
+ open_app: meta.get("openApp").and_then(|v| v.as_bool()),
+ page_url: meta
+ .get("pageUrl")
+ .and_then(|v| v.as_str())
+ .filter(|s| !s.is_empty())
+ .map(String::from),
+ user_agent: meta
+ .get("userAgent")
+ .and_then(|v| v.as_str())
+ .filter(|s| !s.is_empty())
+ .map(String::from),
+ }
+}
+
+pub fn read_extension_metadata(url: &str) -> Option<ExtensionMetadata> {
+ let path = extension_metadata_path();
+ let now = current_unix_timestamp();
+ let mut map = load_metadata_map(&path);
+ prune_expired_metadata(&mut map, now);
+
+ let entry = map.remove(url)?;
+ let result = parse_metadata_entry(&entry);
+
+ let _ = write_metadata_map(&path, &map);
+
+ Some(result)
+}
+
+/// Best-effort removal of the native-messaging artefacts left behind by the
+/// pre-0.5.3 builds: the Chrome / Firefox host manifests and the copied
+/// `omniget-native-host` binary that lived under `chrome-native-host/`.
+///
+/// We can't unregister the manifest atomically across all browsers — the
+/// best we can do is delete the files and let Chrome / Firefox skip them
+/// silently the next time they look for a host.
+pub fn cleanup_legacy_native_messaging() {
+ let host_name = "wtf.tonho.omniget";
+
+ if let Some(data_dir) = crate::core::paths::app_data_dir() {
+ let dir = data_dir.join("chrome-native-host");
+ if dir.exists() {
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+ }
+
+ #[cfg(target_os = "linux")]
+ {
+ if let Some(config_dir) = dirs::config_dir() {
+ let chrome = config_dir
+ .join("google-chrome")
+ .join("NativeMessagingHosts")
+ .join(format!("{host_name}.json"));
+ let _ = std::fs::remove_file(chrome);
+ }
+ if let Some(home) = dirs::home_dir() {
+ let firefox = home
+ .join(".mozilla")
+ .join("native-messaging-hosts")
+ .join(format!("{host_name}.json"));
+ let _ = std::fs::remove_file(firefox);
+ }
+ }
+
+ #[cfg(target_os = "macos")]
+ {
+ if let Some(data_dir) = dirs::data_dir() {
+ let chrome = data_dir
+ .join("Google")
+ .join("Chrome")
+ .join("NativeMessagingHosts")
+ .join(format!("{host_name}.json"));
+ let _ = std::fs::remove_file(chrome);
+ }
+ if let Some(home) = dirs::home_dir() {
+ let firefox = home
+ .join("Library")
+ .join("Application Support")
+ .join("Mozilla")
+ .join("NativeMessagingHosts")
+ .join(format!("{host_name}.json"));
+ let _ = std::fs::remove_file(firefox);
+ }
+ }
+
+ #[cfg(target_os = "windows")]
+ {
+ // Remove the registry keys created by the legacy `ensure_registered`
+ // path. Failure (key absent, no permissions) is fine — we ignore it.
+ use std::os::windows::process::CommandExt;
+ const CREATE_NO_WINDOW: u32 = 0x08000000;
+
+ for vendor in ["Google\\Chrome", "Mozilla"] {
+ let _ = std::process::Command::new("reg")
+ .args([
+ "delete",
+ &format!("HKCU\\Software\\{vendor}\\NativeMessagingHosts\\{host_name}"),
+ "/f",
+ ])
+ .creation_flags(CREATE_NO_WINDOW)
+ .status();
+ }
+ }
+}
+
+pub fn peek_extension_open_app(url: &str) -> Option<bool> {
+ let path = extension_metadata_path();
+ let now = current_unix_timestamp();
+ let mut map = load_metadata_map(&path);
+ prune_expired_metadata(&mut map, now);
+
+ let entry = map.get(url)?;
+ let timestamp = entry.get("timestamp").and_then(|v| v.as_u64())?;
+ if now.saturating_sub(timestamp) > METADATA_TTL_SECS {
+ return None;
+ }
+ entry.get("openApp").and_then(|v| v.as_bool())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn cookie_limit_is_reasonable() {
+ assert_eq!(cookie_limit(), 500);
+ }
+
+ #[test]
+ fn prune_expired_metadata_drops_entries_past_ttl() {
+ let mut map = serde_json::Map::new();
+ map.insert(
+ "https://a".to_string(),
+ serde_json::json!({"timestamp": 100_u64, "referer": "r1"}),
+ );
+ map.insert(
+ "https://b".to_string(),
+ serde_json::json!({"timestamp": 200_u64, "referer": "r2"}),
+ );
+ let now = 100 + METADATA_TTL_SECS + 1;
+ prune_expired_metadata(&mut map, now);
+ assert!(!map.contains_key("https://a"));
+ assert!(map.contains_key("https://b"));
+ }
+
+ #[test]
+ fn metadata_map_roundtrip_preserves_multiple_urls() {
+ let tmp = std::env::temp_dir().join(format!(
+ "omniget-meta-test-{}.json",
+ current_unix_timestamp()
+ ));
+ let _ = fs::remove_file(&tmp);
+
+ let mut map = serde_json::Map::new();
+ map.insert(
+ "https://a".to_string(),
+ serde_json::json!({"timestamp": 1_u64, "referer": "ra"}),
+ );
+ map.insert(
+ "https://b".to_string(),
+ serde_json::json!({"timestamp": 2_u64, "referer": "rb"}),
+ );
+ write_metadata_map(&tmp, &map).unwrap();
+ let loaded = load_metadata_map(&tmp);
+ assert_eq!(loaded.len(), 2);
+ assert_eq!(
+ loaded
+ .get("https://a")
+ .and_then(|v| v.get("referer"))
+ .and_then(|v| v.as_str()),
+ Some("ra")
+ );
+ assert_eq!(
+ loaded
+ .get("https://b")
+ .and_then(|v| v.get("referer"))
+ .and_then(|v| v.as_str()),
+ Some("rb")
+ );
+
+ let _ = fs::remove_file(&tmp);
+ }
+
+ #[test]
+ fn write_empty_metadata_map_removes_file() {
+ let tmp = std::env::temp_dir().join(format!(
+ "omniget-meta-empty-{}.json",
+ current_unix_timestamp()
+ ));
+ fs::write(&tmp, "{}").unwrap();
+ assert!(tmp.exists());
+ let empty: serde_json::Map<String, serde_json::Value> = serde_json::Map::new();
+ write_metadata_map(&tmp, &empty).unwrap();
+ assert!(!tmp.exists());
+ }
+}
diff --git a/src-tauri/src/external_url.rs b/src-tauri/src/external_url.rs
index 4b2e018b..c120e2ca 100644
--- a/src-tauri/src/external_url.rs
+++ b/src-tauri/src/external_url.rs
@@ -56,6 +56,19 @@ pub fn is_external_url(value: &str) -> bool {
.unwrap_or(false)
}
+/// Returns true when the request originated from the `omniget://` protocol
+/// handler — either via the deep-link event or because the raw URL still
+/// carries the scheme prefix when handed to the second-instance callback.
+///
+/// This is used to decide whether to bring the app window to the front:
+/// the native-messaging path uses metadata written by the host process to
+/// honour the extension's "Open app" toggle, but the scheme path bypasses
+/// the native host entirely, so we treat scheme arrival as the user's
+/// explicit intent.
+pub fn arrived_via_scheme(raw_url: &str, source: &str) -> bool {
+ raw_url.trim_start().starts_with("omniget:") || source == "deep-link"
+}
+
pub fn normalize_external_url(value: &str) -> Option<String> {
let trimmed = value.trim();
let rest = trimmed
@@ -109,7 +122,7 @@ pub async fn queue_url_with_defaults(
let ytdlp_path = crate::core::ytdlp::find_ytdlp_cached().await;
- let ext_meta = crate::native_host::read_extension_metadata(&url);
+ let ext_meta = crate::extension_storage::read_extension_metadata(&url);
let has_ext_media = ext_meta
.as_ref()
@@ -292,6 +305,7 @@ pub async fn handle_external_url(
url: String,
source: &str,
) -> Result<ExternalUrlAction, String> {
+ let scheme_arrival = arrived_via_scheme(&url, source);
let url = normalize_external_url(&url).unwrap_or(url);
if !is_external_url(&url) {
return Err("Invalid external URL".to_string());
@@ -302,11 +316,15 @@ pub async fn handle_external_url(
|| settings.download.auto_download_on_paste)
&& has_valid_output_dir(&settings.download.default_output_dir);
- let open_app_flag = crate::native_host::peek_extension_open_app(&url);
+ let open_app_flag = crate::extension_storage::peek_extension_open_app(&url);
let action = if can_queue_directly {
let outcome = queue_url_with_defaults(app, url.clone(), false).await?;
- if open_app_flag == Some(true) {
+ // The native-messaging path only shows the window when the extension's
+ // "Open app" toggle is on. When the request arrived via the omniget://
+ // scheme, no metadata exists (it bypasses the native host), so we use
+ // the scheme presence itself as the user's intent to bring up the app.
+ if open_app_flag == Some(true) || scheme_arrival {
crate::tray::show_window(app);
}
match outcome {
@@ -350,10 +368,14 @@ where
I: IntoIterator<Item = S>,
S: AsRef<str>,
{
+ // Return the raw argument (preserving any `omniget://` prefix). The caller
+ // forwards this string to `handle_external_url`, which normalises it after
+ // recording whether the request arrived through the scheme — preserving
+ // the prefix is what lets that detection work on Linux's single-instance
+ // path, where the OS hands us the omniget:// URL as a plain CLI argument.
args.into_iter()
.map(|arg| arg.as_ref().trim().to_string())
.find(|arg| is_external_url(arg))
- .map(|arg| normalize_external_url(&arg).unwrap_or(arg))
}
async fn push_or_emit_event(app: &AppHandle, event: ExternalUrlEvent) {
@@ -374,3 +396,93 @@ async fn push_or_emit_event(app: &AppHandle, event: ExternalUrlEvent) {
fn has_valid_output_dir(path: &PathBuf) -> bool {
!path.as_os_str().is_empty() && path.is_dir()
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn normalize_strips_omniget_prefix_and_adds_https() {
+ assert_eq!(
+ normalize_external_url("omniget://www.youtube.com/watch?v=abc"),
+ Some("https://www.youtube.com/watch?v=abc".to_string())
+ );
+ }
+
+ #[test]
+ fn normalize_preserves_explicit_http_inside_scheme_payload() {
+ assert_eq!(
+ normalize_external_url("omniget://https://example.com/v"),
+ Some("https://example.com/v".to_string())
+ );
+ }
+
+ #[test]
+ fn normalize_preserves_magnet_payload() {
+ assert_eq!(
+ normalize_external_url("omniget:magnet:?xt=urn:btih:abc"),
+ Some("magnet:?xt=urn:btih:abc".to_string())
+ );
+ }
+
+ #[test]
+ fn normalize_returns_none_for_non_scheme_input() {
+ assert_eq!(normalize_external_url("https://example.com/v"), None);
+ assert_eq!(normalize_external_url(""), None);
+ }
+
+ #[test]
+ fn arrived_via_scheme_detects_prefix() {
+ assert!(arrived_via_scheme(
+ "omniget://www.youtube.com/watch?v=abc",
+ "command-line"
+ ));
+ assert!(arrived_via_scheme(
+ " omniget://example.com/v",
+ "command-line"
+ ));
+ assert!(arrived_via_scheme("omniget:magnet:?xt=foo", "command-line"));
+ }
+
+ #[test]
+ fn arrived_via_scheme_detects_deep_link_source() {
+ assert!(arrived_via_scheme(
+ "https://www.youtube.com/watch?v=abc",
+ "deep-link"
+ ));
+ }
+
+ #[test]
+ fn arrived_via_scheme_returns_false_for_plain_cli() {
+ assert!(!arrived_via_scheme(
+ "https://www.youtube.com/watch?v=abc",
+ "command-line"
+ ));
+ }
+
+ #[test]
+ fn find_external_url_arg_preserves_omniget_prefix() {
+ // The single-instance / cold-start callbacks rely on this so the
+ // downstream `arrived_via_scheme` check can still detect the scheme.
+ let args = vec!["--flag", "omniget://www.youtube.com/watch?v=abc"];
+ assert_eq!(
+ find_external_url_arg(args.iter().copied()),
+ Some("omniget://www.youtube.com/watch?v=abc".to_string())
+ );
+ }
+
+ #[test]
+ fn find_external_url_arg_returns_https_url_unchanged() {
+ let args = vec!["https://example.com/video"];
+ assert_eq!(
+ find_external_url_arg(args.iter().copied()),
+ Some("https://example.com/video".to_string())
+ );
+ }
+
+ #[test]
+ fn find_external_url_arg_skips_irrelevant_args() {
+ let args = vec!["--start-hidden", "--config=/etc/foo"];
+ assert_eq!(find_external_url_arg(args.iter().copied()), None);
+ }
+}
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index fce5f9c0..762f9f07 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -13,10 +13,11 @@ pub type ActiveP2pSends = Arc<tokio::sync::Mutex<HashMap<String, P2pSendHandle>>
pub mod commands;
pub mod core;
+pub mod extension_storage;
pub mod external_url;
pub mod hotkey;
+pub mod local_bridge;
pub mod models;
-pub mod native_host;
pub mod pets;
pub mod platforms;
pub mod plugin_host;
@@ -130,7 +131,7 @@ pub fn run() {
core::http_fetcher::set_global_max_concurrent_segments(
settings.advanced.max_concurrent_segments as usize,
);
- core::ytdlp::set_ext_cookie_path_fn(|| native_host::extension_cookie_file_path());
+ core::ytdlp::set_ext_cookie_path_fn(|| extension_storage::extension_cookie_file_path());
core::ytdlp::set_global_cookie_file_fn(|| {
let s = storage::config::load_settings_standalone();
let cf = s.download.cookie_file.clone();
@@ -151,7 +152,7 @@ pub fn run() {
.twitter_manual_cookie
});
core::ytdlp::set_ext_referer_fn(|url| {
- native_host::read_extension_metadata(url).and_then(|m| m.referer)
+ extension_storage::read_extension_metadata(url).and_then(|m| m.referer)
});
core::ytdlp::set_include_auto_subs_fn(|| {
storage::config::load_settings_standalone()
@@ -242,10 +243,33 @@ pub fn run() {
}
});
}
+ // Make sure the OS routes `omniget://` to this binary even when the
+ // package didn't ship a desktop file with `MimeType=x-scheme-handler/omniget;`
+ // or when the user is running from an AppImage / unpacked build.
+ // No-op on macOS (which uses Info.plist registered by the bundler).
+ #[cfg(any(target_os = "linux", target_os = "windows"))]
+ {
+ if let Err(error) = app.deep_link().register_all() {
+ tracing::warn!("Failed to register omniget:// scheme: {}", error);
+ }
+ }
tray::setup(app.handle())?;
hotkey::register_from_settings(app.handle());
- if let Err(error) = native_host::ensure_registered() {
- tracing::warn!("Failed to register Chrome native host: {}", error);
+
+ // Migration: drop the manifests / binary copies the previous
+ // native-messaging code left under `~/.config/...` so Chrome and
+ // Firefox stop trying to start the legacy host process.
+ extension_storage::cleanup_legacy_native_messaging();
+
+ // Start the localhost HTTP bridge for the browser extension. This
+ // replaces the previous Chrome native-messaging path, which forced
+ // us to maintain a hard-coded extension-ID allowlist. Bridge auth
+ // is via a per-installation token shown in the Settings UI.
+ {
+ let app_handle = app.handle().clone();
+ tauri::async_runtime::spawn(async move {
+ local_bridge::spawn(app_handle).await;
+ });
}
{
let plugins_dir = core::paths::app_data_dir()
@@ -377,6 +401,8 @@ pub fn run() {
commands::rpc::rpc_set_source,
commands::rpc::rpc_clear_source,
commands::rpc::rpc_set_idle_stats,
+ commands::settings::get_bridge_info,
+ commands::settings::rotate_bridge_token,
commands::autostart::set_autostart,
commands::autostart::get_autostart_status,
commands::dependencies::check_dependencies,
diff --git a/src-tauri/src/local_bridge.rs b/src-tauri/src/local_bridge.rs
new file mode 100644
index 00000000..f84827b8
--- /dev/null
+++ b/src-tauri/src/local_bridge.rs
@@ -0,0 +1,456 @@
+//! Localhost HTTP bridge between the browser extension and the desktop app.
+//!
+//! Replaces the previous Chrome native-messaging path, which required
+//! hard-coding extension IDs in an OS-installed manifest. This bridge listens
+//! on `127.0.0.1:<port>` and authenticates extension requests with a single
+//! random token that the user pairs once via the app's settings UI.
+//!
+//! The token is regenerated by hand from the settings (or by deleting it from
+//! `settings.json`); the port is picked at first launch from a small range
+//! and persisted so the extension always knows where to connect.
+//!
+//! Endpoints:
+//!
+//! * `GET /v1/health` — unauthenticated; returns `{ ok, version }` so the
+//! extension can detect that the app is running.
+//! * `POST /v1/enqueue` — authenticated; same payload as the legacy native
+//! host accepted (`ExtensionPayload`). Validates the
+//! URL, writes cookies + metadata to disk, then queues
+//! the URL through `external_url::handle_external_url`.
+
+use std::net::SocketAddr;
+use std::sync::Arc;
+
+use axum::{
+ extract::State,
+ http::{HeaderMap, Method, StatusCode},
+ response::{IntoResponse, Response},
+ routing::{get, post},
+ Json, Router,
+};
+use base64::Engine;
+use serde::{Deserialize, Serialize};
+use socket2::{Domain, Protocol, Socket, Type};
+use tauri::AppHandle;
+use tokio::net::TcpListener;
+use tower_http::cors::{Any, CorsLayer};
+
+use crate::extension_storage::{
+ cookie_limit, write_extension_cookies, write_extension_metadata, ExtensionCookie,
+ ExtensionPayload,
+};
+use crate::storage::config;
+
+/// Range of ports we'll try when picking a fresh `bridge.port`. Chosen above
+/// the most common dev-server / Vite ranges so collisions are rare.
+const PORT_RANGE: std::ops::Range<u16> = 47720..47730;
+
+#[derive(Clone)]
+pub struct BridgeState {
+ pub app: AppHandle,
+ /// Authoritative copy of the bearer token, kept in `Arc` so cloning the
+ /// state for each handler doesn't allocate, and so reading it is lock-free.
+ pub token: Arc<String>,
+}
+
+#[derive(Debug, Serialize)]
+struct HealthResponse {
+ ok: bool,
+ version: &'static str,
+}
+
+#[derive(Debug, Serialize)]
+struct EnqueueResponse {
+ ok: bool,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ code: Option<&'static str>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ message: Option<String>,
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct EnqueueRequest {
+ #[serde(flatten)]
+ payload: ExtensionPayload,
+ #[serde(default)]
+ protocol_version: Option<u32>,
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct CookiesRequest {
+ #[serde(default)]
+ cookies: Vec<ExtensionCookie>,
+ #[serde(default)]
+ protocol_version: Option<u32>,
+}
+
+const HOST_MAX_PROTOCOL_VERSION: u32 = 1;
+
+/// Generate a random bearer token (32 bytes, URL-safe base64, no padding).
+pub fn generate_token() -> String {
+ let mut buf = [0u8; 32];
+ rand::Rng::fill_bytes(&mut rand::rng(), &mut buf);
+ base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(buf)
+}
+
+/// Bind a TCP listener on `127.0.0.1:port` with `SO_REUSEADDR` enabled so
+/// the port can be re-bound immediately across app restarts (the previous
+/// socket stays in `TIME_WAIT` for ~60 s otherwise, which would otherwise
+/// kick us off our persisted port and force re-pairing).
+fn bind_with_reuse(port: u16) -> std::io::Result<TcpListener> {
+ let addr: SocketAddr = ([127, 0, 0, 1], port).into();
+ let socket = Socket::new(Domain::IPV4, Type::STREAM, Some(Protocol::TCP))?;
+ socket.set_reuse_address(true)?;
+ socket.set_nonblocking(true)?;
+ socket.bind(&addr.into())?;
+ socket.listen(128)?;
+ let std_listener: std::net::TcpListener = socket.into();
+ TcpListener::from_std(std_listener)
+}
+
+/// Try to bind a free TCP listener — first the persisted port, then the
+/// preferred range, finally `0` (OS-picked) as last resort.
+async fn bind_listener(preferred: u16) -> std::io::Result<(u16, TcpListener)> {
+ if preferred != 0 {
+ if let Ok(listener) = bind_with_reuse(preferred) {
+ return Ok((preferred, listener));
+ }
+ }
+
+ for port in PORT_RANGE {
+ if let Ok(listener) = bind_with_reuse(port) {
+ return Ok((port, listener));
+ }
+ }
+
+ let listener = bind_with_reuse(0)?;
+ let port = listener.local_addr()?.port();
+ Ok((port, listener))
+}
+
+/// Ensure `settings.bridge.{token,port}` are populated and persisted.
+/// Returns the resolved (token, port) pair to use for this run.
+fn ensure_bridge_settings(
+ app: &AppHandle,
+ bound_port: u16,
+) -> anyhow::Result<(String, u16)> {
+ let mut settings = config::load_settings(app);
+ let mut dirty = false;
+
+ if settings.bridge.token.trim().is_empty() {
+ settings.bridge.token = generate_token();
+ dirty = true;
+ }
+ if settings.bridge.port != bound_port {
+ settings.bridge.port = bound_port;
+ dirty = true;
+ }
+
+ if dirty {
+ config::save_settings(app, &settings)?;
+ }
+
+ Ok((settings.bridge.token, settings.bridge.port))
+}
+
+/// Spawn the localhost bridge in a background tokio task.
+///
+/// Returns once the listener has been bound (so the port is known and
+/// persisted), then continues serving on the spawned task. Errors during
+/// binding are logged but never propagated up — the deep-link path remains
+/// usable as a fallback.
+pub async fn spawn(app: AppHandle) {
+ let settings = config::load_settings(&app);
+
+ if !settings.bridge.enabled {
+ tracing::info!("local bridge disabled by settings; not starting HTTP server");
+ return;
+ }
+
+ let preferred_port = settings.bridge.port;
+ let (port, listener) = match bind_listener(preferred_port).await {
+ Ok(pair) => pair,
+ Err(error) => {
+ tracing::warn!(
+ "failed to bind local bridge on 127.0.0.1: {} — extension cookie path disabled",
+ error
+ );
+ return;
+ }
+ };
+
+ let (token, _port) = match ensure_bridge_settings(&app, port) {
+ Ok(pair) => pair,
+ Err(error) => {
+ tracing::warn!("failed to persist bridge settings: {}", error);
+ return;
+ }
+ };
+
+ let state = BridgeState {
+ app: app.clone(),
+ token: Arc::new(token),
+ };
+
+ let cors = CorsLayer::new()
+ // The token is the actual auth boundary, so we accept any browser
+ // origin (extension or webpage). Requests without a valid bearer are
+ // still rejected by the handler.
+ .allow_origin(Any)
+ .allow_methods([Method::GET, Method::POST, Method::OPTIONS])
+ .allow_headers(Any);
+
+ let router = Router::new()
+ .route("/v1/health", get(health))
+ .route("/v1/enqueue", post(enqueue))
+ .route("/v1/cookies", post(cookies_export))
+ .with_state(state)
+ .layer(cors);
+
+ tracing::info!("local bridge listening on http://127.0.0.1:{port}");
+
+ tokio::spawn(async move {
+ if let Err(error) = axum::serve(listener, router).await {
+ tracing::warn!("local bridge stopped: {error}");
+ }
+ });
+}
+
+async fn health() -> Json<HealthResponse> {
+ Json(HealthResponse {
+ ok: true,
+ version: env!("CARGO_PKG_VERSION"),
+ })
+}
+
+fn unauthorized() -> Response {
+ let body = Json(EnqueueResponse {
+ ok: false,
+ code: Some("UNAUTHORIZED"),
+ message: Some("Invalid or missing bearer token".to_string()),
+ });
+ (StatusCode::UNAUTHORIZED, body).into_response()
+}
+
+fn check_bearer(headers: &HeaderMap, expected: &str) -> bool {
+ let header = match headers.get("authorization") {
+ Some(v) => v,
+ None => return false,
+ };
+ let raw = match header.to_str() {
+ Ok(s) => s,
+ Err(_) => return false,
+ };
+ let provided = match raw.strip_prefix("Bearer ").or_else(|| raw.strip_prefix("bearer ")) {
+ Some(s) => s.trim(),
+ None => return false,
+ };
+ constant_time_eq::constant_time_eq(provided.as_bytes(), expected.as_bytes())
+}
+
+async fn enqueue(
+ State(state): State<BridgeState>,
+ headers: HeaderMap,
+ Json(request): Json<EnqueueRequest>,
+) -> Response {
+ if !check_bearer(&headers, &state.token) {
+ return unauthorized();
+ }
+
+ if let Some(client_version) = request.protocol_version {
+ if client_version > HOST_MAX_PROTOCOL_VERSION {
+ return error_response(
+ StatusCode::BAD_REQUEST,
+ "UNSUPPORTED_PROTOCOL",
+ format!(
+ "Extension protocol v{client_version} is newer than host v{HOST_MAX_PROTOCOL_VERSION}. Please update OmniGet."
+ ),
+ );
+ }
+ }
+
+ let payload = request.payload;
+
+ if !crate::external_url::is_external_url(&payload.url) {
+ return error_response(
+ StatusCode::BAD_REQUEST,
+ "INVALID_URL",
+ "The requested URL is invalid".to_string(),
+ );
+ }
+
+ if let Some(ref cookies) = payload.cookies {
+ if cookies.len() > cookie_limit() {
+ return error_response(
+ StatusCode::BAD_REQUEST,
+ "TOO_MANY_COOKIES",
+ format!(
+ "Request contains {} cookies; max allowed is {}",
+ cookies.len(),
+ cookie_limit()
+ ),
+ );
+ }
+ if !cookies.is_empty() {
+ if let Err(error) = write_extension_cookies(cookies) {
+ tracing::warn!("failed to write extension cookies: {error}");
+ }
+ }
+ }
+
+ if payload.referer.is_some()
+ || payload.headers.is_some()
+ || payload.media_type.is_some()
+ || payload.title.is_some()
+ || payload.thumbnail.is_some()
+ || payload.open_app.is_some()
+ || payload.page_url.is_some()
+ || payload.user_agent.is_some()
+ {
+ if let Err(error) = write_extension_metadata(&payload) {
+ tracing::warn!("failed to write extension metadata: {error}");
+ }
+ }
+
+ let app = state.app.clone();
+ let url = payload.url.clone();
+ tauri::async_runtime::spawn(async move {
+ if let Err(error) =
+ crate::external_url::handle_external_url(&app, url, "bridge").await
+ {
+ tracing::warn!("failed to handle bridge URL: {error}");
+ }
+ });
+
+ let body = Json(EnqueueResponse {
+ ok: true,
+ code: None,
+ message: None,
+ });
+ (StatusCode::OK, body).into_response()
+}
+
+async fn cookies_export(
+ State(state): State<BridgeState>,
+ headers: HeaderMap,
+ Json(request): Json<CookiesRequest>,
+) -> Response {
+ if !check_bearer(&headers, &state.token) {
+ return unauthorized();
+ }
+
+ if let Some(client_version) = request.protocol_version {
+ if client_version > HOST_MAX_PROTOCOL_VERSION {
+ return error_response(
+ StatusCode::BAD_REQUEST,
+ "UNSUPPORTED_PROTOCOL",
+ format!(
+ "Extension protocol v{client_version} is newer than host v{HOST_MAX_PROTOCOL_VERSION}. Please update OmniGet."
+ ),
+ );
+ }
+ }
+
+ if request.cookies.len() > cookie_limit() {
+ return error_response(
+ StatusCode::BAD_REQUEST,
+ "TOO_MANY_COOKIES",
+ format!(
+ "cookies:export contains {} cookies; max is {}",
+ request.cookies.len(),
+ cookie_limit()
+ ),
+ );
+ }
+
+ if !request.cookies.is_empty() {
+ if let Err(error) = write_extension_cookies(&request.cookies) {
+ return error_response(
+ StatusCode::INTERNAL_SERVER_ERROR,
+ "WRITE_FAILED",
+ format!("write extension cookies: {error}"),
+ );
+ }
+ }
+
+ let body = Json(EnqueueResponse {
+ ok: true,
+ code: None,
+ message: None,
+ });
+ (StatusCode::OK, body).into_response()
+}
+
+fn error_response(status: StatusCode, code: &'static str, message: String) -> Response {
+ let body = Json(EnqueueResponse {
+ ok: false,
+ code: Some(code),
+ message: Some(message),
+ });
+ (status, body).into_response()
+}
+
+pub fn build_pairing_url(port: u16) -> String {
+ format!("http://127.0.0.1:{port}")
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use axum::http::HeaderValue;
+
+ fn header_with_auth(value: &str) -> HeaderMap {
+ let mut headers = HeaderMap::new();
+ headers.insert(
+ "authorization",
+ HeaderValue::from_str(value).expect("valid header"),
+ );
+ headers
+ }
+
+ #[test]
+ fn token_is_url_safe_base64_with_no_padding() {
+ let t = generate_token();
+ assert!(t.len() >= 40);
+ assert!(!t.contains('+'));
+ assert!(!t.contains('/'));
+ assert!(!t.contains('='));
+ }
+
+ #[test]
+ fn check_bearer_accepts_valid_token() {
+ let headers = header_with_auth("Bearer abc.def-ghi");
+ assert!(check_bearer(&headers, "abc.def-ghi"));
+ }
+
+ #[test]
+ fn check_bearer_is_case_insensitive_on_scheme() {
+ let headers = header_with_auth("bearer abc");
+ assert!(check_bearer(&headers, "abc"));
+ }
+
+ #[test]
+ fn check_bearer_rejects_missing_header() {
+ let headers = HeaderMap::new();
+ assert!(!check_bearer(&headers, "abc"));
+ }
+
+ #[test]
+ fn check_bearer_rejects_wrong_token() {
+ let headers = header_with_auth("Bearer different");
+ assert!(!check_bearer(&headers, "abc"));
+ }
+
+ #[test]
+ fn check_bearer_rejects_missing_scheme_prefix() {
+ let headers = header_with_auth("abc");
+ assert!(!check_bearer(&headers, "abc"));
+ }
+
+ #[test]
+ fn build_pairing_url_uses_loopback_address() {
+ assert_eq!(build_pairing_url(47720), "http://127.0.0.1:47720");
+ }
+}
diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs
index 2862bdc1..7823f88f 100644
--- a/src-tauri/src/main.rs
+++ b/src-tauri/src/main.rs
@@ -34,13 +34,6 @@ fn setup_environment() {
}
fn main() {
- if omniget_lib::native_host::should_run_as_native_host() {
- if let Err(error) = omniget_lib::native_host::run_native_host() {
- eprintln!("native host error: {error}");
- }
- return;
- }
-
check_portable_mode();
setup_environment();
omniget_lib::run()
diff --git a/src-tauri/src/native_host.rs b/src-tauri/src/native_host.rs
deleted file mode 100644
index 8293c8ed..00000000
--- a/src-tauri/src/native_host.rs
+++ /dev/null
@@ -1,1251 +0,0 @@
-use std::fs;
-use std::io::{Read, Write};
-use std::path::{Path, PathBuf};
-
-#[cfg(any(target_os = "linux", target_os = "macos"))]
-use anyhow::Context;
-use serde::{Deserialize, Serialize};
-
-pub const CHROME_HOST_NAME: &str = "wtf.tonho.omniget";
-pub const CHROME_EXTENSION_IDS: &[&str] = &["dkjelkhaaakffpghdfalobccaaipajip"];
-const FIREFOX_EXTENSION_ID: &str = "[email protected]";
-const HOST_MAX_PROTOCOL_VERSION: u32 = 1;
-const MAX_MESSAGE_LENGTH: usize = 1_048_576;
-const MAX_COOKIES_PER_REQUEST: usize = 500;
-
-#[cfg(target_os = "windows")]
-const HOST_COPY_NAME: &str = "omniget-native-host.exe";
-#[cfg(not(target_os = "windows"))]
-const HOST_COPY_NAME: &str = "omniget-native-host";
-const HOST_BINARY_STEM: &str = "omniget-native-host";
-const HOST_CONFIG_NAME: &str = "native-host-config.json";
-const HOST_MANIFEST_NAME: &str = "wtf.tonho.omniget.json";
-
-#[derive(Debug, Deserialize)]
-struct NativeHostRequest {
- #[serde(rename = "type")]
- kind: String,
- #[serde(default)]
- url: String,
- #[serde(default, rename = "protocolVersion")]
- protocol_version: Option<u32>,
- #[serde(default)]
- cookies: Option<Vec<NativeCookie>>,
- #[serde(default)]
- referer: Option<String>,
- #[serde(default)]
- headers: Option<std::collections::HashMap<String, String>>,
- #[serde(default, rename = "mediaType")]
- media_type: Option<String>,
- #[serde(default, rename = "contentType")]
- content_type: Option<String>,
- #[serde(default)]
- title: Option<String>,
- #[serde(default)]
- thumbnail: Option<String>,
- #[serde(default, rename = "openApp")]
- open_app: Option<bool>,
- #[serde(default, rename = "pageUrl")]
- page_url: Option<String>,
- #[serde(default, rename = "userAgent")]
- user_agent: Option<String>,
-}
-
-#[derive(Debug, Deserialize)]
-struct NativeCookie {
- domain: String,
- #[serde(rename = "httpOnly")]
- http_only: bool,
- path: String,
- secure: bool,
- expires: i64,
- name: String,
- value: String,
- #[serde(default, rename = "hostOnly")]
- host_only: Option<bool>,
- #[serde(default, rename = "sameSite")]
- #[allow(dead_code)]
- same_site: Option<String>,
-}
-
-#[derive(Debug, Serialize)]
-struct NativeHostResponse {
- ok: bool,
- #[serde(skip_serializing_if = "Option::is_none")]
- code: Option<&'static str>,
- #[serde(skip_serializing_if = "Option::is_none")]
- message: Option<String>,
-}
-
-#[derive(Debug, Deserialize, Serialize)]
-struct NativeHostConfig {
- app_path: String,
-}
-
-pub fn should_run_as_native_host() -> bool {
- std::env::current_exe()
- .ok()
- .and_then(|path| {
- path.file_stem()
- .map(|stem| stem.to_string_lossy().to_string())
- })
- .map(|stem| stem.eq_ignore_ascii_case(HOST_BINARY_STEM))
- .unwrap_or(false)
-}
-
-pub fn run_native_host() -> anyhow::Result<()> {
- detect_portable_mode();
- let response = match read_message()? {
- ReadOutcome::Ok(request) => handle_request(request),
- ReadOutcome::TooLarge(length) => {
- log_host_event(
- "PAYLOAD_TOO_LARGE",
- &format!("payload_len={length} limit={MAX_MESSAGE_LENGTH}"),
- );
- NativeHostResponse {
- ok: false,
- code: Some("PAYLOAD_TOO_LARGE"),
- message: Some(format!(
- "Native message ({length} bytes) exceeds {MAX_MESSAGE_LENGTH} bytes limit"
- )),
- }
- }
- ReadOutcome::MalformedJson(details) => {
- log_host_event("INVALID_PAYLOAD", &details);
- NativeHostResponse {
- ok: false,
- code: Some("INVALID_PAYLOAD"),
- message: Some(format!("Failed to parse native message: {details}")),
- }
- }
- };
- write_message(&response)?;
- Ok(())
-}
-
-enum ReadOutcome {
- Ok(NativeHostRequest),
- TooLarge(usize),
- MalformedJson(String),
-}
-
-fn host_log_path() -> Option<PathBuf> {
- crate::core::paths::app_data_dir().map(|dir| dir.join("native-host.log"))
-}
-
-fn log_host_event(kind: &str, detail: &str) {
- let ts = current_unix_timestamp();
- let line = format!("{ts} [{kind}] {detail}\n");
- eprintln!("[native-host] {kind} {detail}");
- if let Some(path) = host_log_path() {
- if let Some(parent) = path.parent() {
- let _ = fs::create_dir_all(parent);
- }
- let _ = fs::OpenOptions::new()
- .create(true)
- .append(true)
- .open(&path)
- .and_then(|mut f| f.write_all(line.as_bytes()));
- }
-}
-
-pub(crate) fn safe_payload_summary(payload: &[u8]) -> String {
- let payload_len = payload.len();
- let parsed: Result<serde_json::Value, _> = serde_json::from_slice(payload);
- match parsed {
- Ok(serde_json::Value::Object(map)) => {
- let type_ = map
- .get("type")
- .and_then(|v| v.as_str())
- .unwrap_or("<missing>");
- let has_url = map.get("url").is_some();
- let cookie_count = map
- .get("cookies")
- .and_then(|v| v.as_array())
- .map(|a| a.len())
- .unwrap_or(0);
- let protocol_version = map
- .get("protocolVersion")
- .and_then(|v| v.as_u64())
- .map(|v| v.to_string())
- .unwrap_or_else(|| "<none>".to_string());
- let mut keys: Vec<&str> = map.keys().map(|s| s.as_str()).collect();
- keys.sort_unstable();
- format!(
- "payload_len={payload_len} type=\"{type_}\" has_url={has_url} cookie_count={cookie_count} protocolVersion={protocol_version} keys={keys:?}"
- )
- }
- Ok(_) => format!("payload_len={payload_len} not_a_json_object"),
- Err(_) => format!("payload_len={payload_len} unparseable"),
- }
-}
-
-fn build_deserialize_error_detail(payload: &[u8], err: &serde_json::Error) -> String {
- format!(
- "err=\"{}\" line={} column={} category={:?} | {}",
- err,
- err.line(),
- err.column(),
- err.classify(),
- safe_payload_summary(payload)
- )
-}
-
-/// Detect portable mode by reading the native-host config to locate the main
-/// app executable, then checking its parent directory for portable markers.
-/// This mirrors the `check_portable_mode()` logic in `main.rs` so that
-/// `app_data_dir()` resolves to the portable data directory when the native
-/// host process is launched by Chrome.
-fn detect_portable_mode() {
- let exe = match std::env::current_exe() {
- Ok(p) => p,
- Err(_) => return,
- };
- let host_dir = match exe.parent() {
- Some(d) => d,
- None => return,
- };
- let config_bytes = match fs::read(host_dir.join(HOST_CONFIG_NAME)) {
- Ok(b) => b,
- Err(_) => return,
- };
- let config: NativeHostConfig = match serde_json::from_slice(&config_bytes) {
- Ok(c) => c,
- Err(_) => return,
- };
- let app_dir = match Path::new(&config.app_path).parent() {
- Some(d) => d,
- None => return,
- };
- if app_dir.join("portable.txt").exists() || app_dir.join(".portable").exists() {
- let data_dir = app_dir.join("data");
- let _ = fs::create_dir_all(&data_dir);
- std::env::set_var("OMNIGET_PORTABLE", "1");
- std::env::set_var("OMNIGET_DATA_DIR", data_dir.to_string_lossy().to_string());
- }
-}
-
-pub fn ensure_registered() -> anyhow::Result<()> {
- let current_exe = std::env::current_exe()?;
- let integration_dir = chrome_integration_dir();
- fs::create_dir_all(&integration_dir)?;
-
- let host_exe = integration_dir.join(HOST_COPY_NAME);
- copy_host_exe(&current_exe, &host_exe)?;
-
- let config_path = integration_dir.join(HOST_CONFIG_NAME);
- write_host_config(&config_path, &current_exe)?;
-
- let manifest_path = chrome_manifest_path(&integration_dir)?;
- if let Some(parent) = manifest_path.parent() {
- fs::create_dir_all(parent)?;
- }
-
- write_host_manifest(&manifest_path, &host_exe)?;
- register_host_manifest(&manifest_path)?;
-
- if let Ok(ff_path) = firefox_manifest_path(&integration_dir) {
- if let Some(parent) = ff_path.parent() {
- let _ = fs::create_dir_all(parent);
- }
- let _ = write_firefox_manifest(&ff_path, &host_exe);
- let _ = register_firefox_manifest(&ff_path);
- }
-
- Ok(())
-}
-
-fn chrome_integration_dir() -> PathBuf {
- crate::core::paths::app_data_dir()
- .unwrap_or_else(|| PathBuf::from("."))
- .join("chrome-native-host")
-}
-
-fn copy_host_exe(source: &Path, dest: &Path) -> anyhow::Result<()> {
- if source != dest && should_copy_exe(source, dest) {
- fs::copy(source, dest)?;
- sync_host_permissions(source, dest)?;
- }
- Ok(())
-}
-
-fn write_host_config(config_path: &Path, app_path: &Path) -> anyhow::Result<()> {
- let config = NativeHostConfig {
- app_path: app_path.to_string_lossy().to_string(),
- };
- fs::write(config_path, serde_json::to_vec_pretty(&config)?)?;
- Ok(())
-}
-
-fn write_host_manifest(manifest_path: &Path, host_exe: &Path) -> anyhow::Result<()> {
- fs::write(
- manifest_path,
- serde_json::to_vec_pretty(&build_host_manifest(host_exe))?,
- )?;
- Ok(())
-}
-
-fn build_host_manifest(host_exe: &Path) -> serde_json::Value {
- serde_json::json!({
- "name": CHROME_HOST_NAME,
- "description": "OmniGet native host for Chrome",
- "path": host_exe.to_string_lossy().to_string(),
- "type": "stdio",
- "allowed_origins": chrome_allowed_origins()
- })
-}
-
-fn chrome_allowed_origins() -> Vec<String> {
- CHROME_EXTENSION_IDS
- .iter()
- .map(|extension_id| format!("chrome-extension://{extension_id}/"))
- .collect()
-}
-
-#[cfg(target_os = "windows")]
-fn chrome_manifest_path(integration_dir: &Path) -> anyhow::Result<PathBuf> {
- Ok(chrome_manifest_path_from_base(integration_dir))
-}
-
-#[cfg(target_os = "linux")]
-fn chrome_manifest_path(_integration_dir: &Path) -> anyhow::Result<PathBuf> {
- let base_dir = dirs::config_dir().context(
- "Could not resolve the Linux config directory for Chrome native host registration",
- )?;
- Ok(chrome_manifest_path_from_base(&base_dir))
-}
-
-#[cfg(target_os = "macos")]
-fn chrome_manifest_path(_integration_dir: &Path) -> anyhow::Result<PathBuf> {
- let base_dir = dirs::data_dir().context(
- "Could not resolve the macOS Application Support directory for Chrome native host registration",
- )?;
- Ok(chrome_manifest_path_from_base(&base_dir))
-}
-
-#[cfg(not(any(target_os = "windows", target_os = "linux", target_os = "macos")))]
-fn chrome_manifest_path(_integration_dir: &Path) -> anyhow::Result<PathBuf> {
- anyhow::bail!("Chrome native host registration is unsupported on this platform");
-}
-
-#[cfg(target_os = "windows")]
-fn chrome_manifest_path_from_base(base: &Path) -> PathBuf {
- base.join(HOST_MANIFEST_NAME)
-}
-
-#[cfg(target_os = "linux")]
-fn chrome_manifest_path_from_base(base: &Path) -> PathBuf {
- base.join("google-chrome")
- .join("NativeMessagingHosts")
- .join(HOST_MANIFEST_NAME)
-}
-
-#[cfg(target_os = "macos")]
-fn chrome_manifest_path_from_base(base: &Path) -> PathBuf {
- base.join("Google")
- .join("Chrome")
- .join("NativeMessagingHosts")
- .join(HOST_MANIFEST_NAME)
-}
-
-#[cfg(target_os = "windows")]
-fn register_host_manifest(manifest_path: &Path) -> anyhow::Result<()> {
- use std::os::windows::process::CommandExt;
-
- const CREATE_NO_WINDOW: u32 = 0x08000000;
- let status = std::process::Command::new("reg")
- .args([
- "add",
- &format!(
- r"HKCU\Software\Google\Chrome\NativeMessagingHosts\{}",
- CHROME_HOST_NAME
- ),
- "/ve",
- "/t",
- "REG_SZ",
- "/d",
- &manifest_path.to_string_lossy(),
- "/f",
- ])
- .creation_flags(CREATE_NO_WINDOW)
- .status()?;
-
- if !status.success() {
- anyhow::bail!("Failed to register Chrome native host");
- }
-
- Ok(())
-}
-
-// On Linux/macOS, placing the manifest JSON in the well-known directory is
-// sufficient — no registry step is needed (unlike Windows which requires a
-// registry key under HKCU\Software\Google\Chrome\NativeMessagingHosts).
-#[cfg(not(target_os = "windows"))]
-fn register_host_manifest(_manifest_path: &Path) -> anyhow::Result<()> {
- Ok(())
-}
-
-fn build_firefox_manifest(host_exe: &Path) -> serde_json::Value {
- serde_json::json!({
- "name": CHROME_HOST_NAME,
- "description": "OmniGet native host for Firefox",
- "path": host_exe.to_string_lossy().to_string(),
- "type": "stdio",
- "allowed_extensions": [FIREFOX_EXTENSION_ID]
- })
-}
-
-fn write_firefox_manifest(manifest_path: &Path, host_exe: &Path) -> anyhow::Result<()> {
- fs::write(
- manifest_path,
- serde_json::to_vec_pretty(&build_firefox_manifest(host_exe))?,
- )?;
- Ok(())
-}
-
-#[cfg(target_os = "windows")]
-fn firefox_manifest_path(integration_dir: &Path) -> anyhow::Result<PathBuf> {
- Ok(integration_dir.join(format!("{}.firefox.json", CHROME_HOST_NAME)))
-}
-
-#[cfg(target_os = "linux")]
-fn firefox_manifest_path(_integration_dir: &Path) -> anyhow::Result<PathBuf> {
- let home = dirs::home_dir()
- .context("Could not resolve home directory for Firefox native host registration")?;
- Ok(home
- .join(".mozilla")
- .join("native-messaging-hosts")
- .join(format!("{}.json", CHROME_HOST_NAME)))
-}
-
-#[cfg(target_os = "macos")]
-fn firefox_manifest_path(_integration_dir: &Path) -> anyhow::Result<PathBuf> {
- let home = dirs::home_dir()
- .context("Could not resolve home directory for Firefox native host registration")?;
- Ok(home
- .join("Library")
- .join("Application Support")
- .join("Mozilla")
- .join("NativeMessagingHosts")
- .join(format!("{}.json", CHROME_HOST_NAME)))
-}
-
-#[cfg(not(any(target_os = "windows", target_os = "linux", target_os = "macos")))]
-fn firefox_manifest_path(_integration_dir: &Path) -> anyhow::Result<PathBuf> {
- anyhow::bail!("Firefox native host registration is unsupported on this platform");
-}
-
-#[cfg(target_os = "windows")]
-fn register_firefox_manifest(manifest_path: &Path) -> anyhow::Result<()> {
- use std::os::windows::process::CommandExt;
-
- const CREATE_NO_WINDOW: u32 = 0x08000000;
- let _ = std::process::Command::new("reg")
- .args([
- "add",
- &format!(
- r"HKCU\Software\Mozilla\NativeMessagingHosts\{}",
- CHROME_HOST_NAME
- ),
- "/ve",
- "/t",
- "REG_SZ",
- "/d",
- &manifest_path.to_string_lossy(),
- "/f",
- ])
- .creation_flags(CREATE_NO_WINDOW)
- .status();
- Ok(())
-}
-
-#[cfg(not(target_os = "windows"))]
-fn register_firefox_manifest(_manifest_path: &Path) -> anyhow::Result<()> {
- Ok(())
-}
-
-#[cfg(unix)]
-fn sync_host_permissions(source: &Path, dest: &Path) -> anyhow::Result<()> {
- use std::os::unix::fs::PermissionsExt;
-
- let mode = fs::metadata(source)?.permissions().mode();
- fs::set_permissions(dest, std::fs::Permissions::from_mode(mode))?;
- Ok(())
-}
-
-#[cfg(not(unix))]
-fn sync_host_permissions(_source: &Path, _dest: &Path) -> anyhow::Result<()> {
- Ok(())
-}
-
-fn should_copy_exe(source: &Path, dest: &Path) -> bool {
- let Ok(src_meta) = fs::metadata(source) else {
- return true;
- };
- let Ok(dst_meta) = fs::metadata(dest) else {
- return true;
- };
- src_meta.len() != dst_meta.len()
-}
-
-pub fn extension_cookie_file_path() -> PathBuf {
- crate::core::paths::app_data_dir()
- .unwrap_or_else(|| PathBuf::from("."))
- .join("chrome-extension-cookies.txt")
-}
-
-fn sanitize_cookie_field(s: &str) -> String {
- s.chars()
- .filter(|c| *c != '\n' && *c != '\r' && *c != '\t')
- .collect()
-}
-
-fn root_domain_of(host: &str) -> String {
- let h = host.trim_start_matches('.').to_lowercase();
- let parts: Vec<&str> = h.split('.').collect();
- if parts.len() >= 2 {
- parts[parts.len() - 2..].join(".")
- } else {
- h
- }
-}
-
-fn format_cookie_line(c: &NativeCookie, session_ttl: u64) -> String {
- let raw_domain = sanitize_cookie_field(&c.domain);
- let path_field = sanitize_cookie_field(&c.path);
- let name = sanitize_cookie_field(&c.name);
- let value = sanitize_cookie_field(&c.value);
- let http_only_prefix = if c.http_only { "#HttpOnly_" } else { "" };
- let is_host_only = c
- .host_only
- .unwrap_or_else(|| !raw_domain.starts_with('.'));
- let (domain, include_subdomains) = if is_host_only {
- let stripped = raw_domain
- .strip_prefix('.')
- .unwrap_or(&raw_domain)
- .to_string();
- (stripped, "FALSE")
- } else if raw_domain.starts_with('.') {
- (raw_domain.clone(), "TRUE")
- } else {
- (format!(".{}", raw_domain), "TRUE")
- };
- let secure = if c.secure { "TRUE" } else { "FALSE" };
- let expires = if c.expires == 0 {
- session_ttl
- } else {
- c.expires as u64
- };
- format!(
- "{}{}\t{}\t{}\t{}\t{}\t{}\t{}\n",
- http_only_prefix, domain, include_subdomains, path_field, secure, expires, name, value,
- )
-}
-
-fn write_extension_cookies(cookies: &[NativeCookie]) -> anyhow::Result<()> {
- let path = extension_cookie_file_path();
- if let Some(parent) = path.parent() {
- fs::create_dir_all(parent)?;
- }
-
- // Session cookies (expires == 0) must be given a future TTL.
- // Python's MozillaCookieJar treats 0 as "expired at epoch" and discards
- // the cookie, which strips auth context and breaks yt-dlp downloads.
- let now = std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .unwrap_or_default()
- .as_secs();
- let session_ttl = now + 86400; // 24 h, same approach as Cookie-Editor
-
- // Merge with existing file: keep cookies whose root domain is NOT in the
- // incoming batch. Each platform capture only ships its own domains, so
- // overwriting the file would wipe other platforms' auth.
- let incoming_roots: std::collections::HashSet<String> = cookies
- .iter()
- .map(|c| root_domain_of(&c.domain))
- .collect();
-
- let mut preserved: Vec<String> = Vec::new();
- if let Ok(existing) = fs::read_to_string(&path) {
- for line in existing.lines() {
- let trimmed = line.trim();
- if trimmed.is_empty() {
- continue;
- }
- let effective = if let Some(rest) = trimmed.strip_prefix("#HttpOnly_") {
- rest
- } else if trimmed.starts_with('#') {
- continue; // header / comment
- } else {
- trimmed
- };
- let parts: Vec<&str> = effective.split('\t').collect();
- if parts.len() < 7 {
- continue;
- }
- let domain = parts[0];
- let root = root_domain_of(domain);
- if !incoming_roots.contains(&root) {
- preserved.push(line.to_string());
- }
- }
- }
-
- let mut content = String::from("# Netscape HTTP Cookie File\n");
- for line in &preserved {
- content.push_str(line);
- content.push('\n');
- }
- for c in cookies {
- content.push_str(&format_cookie_line(c, session_ttl));
- }
-
- fs::write(&path, content)?;
-
- #[cfg(unix)]
- {
- use std::os::unix::fs::PermissionsExt;
- fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600))?;
- }
-
- Ok(())
-}
-
-fn extension_metadata_path() -> PathBuf {
- crate::core::paths::app_data_dir()
- .unwrap_or_else(|| PathBuf::from("."))
- .join("extension-metadata.json")
-}
-
-const METADATA_TTL_SECS: u64 = 60;
-
-fn current_unix_timestamp() -> u64 {
- std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .unwrap_or_default()
- .as_secs()
-}
-
-fn load_metadata_map(path: &std::path::Path) -> serde_json::Map<String, serde_json::Value> {
- let content = match fs::read_to_string(path) {
- Ok(c) => c,
- Err(_) => return serde_json::Map::new(),
- };
- let parsed: serde_json::Value = match serde_json::from_str(&content) {
- Ok(v) => v,
- Err(_) => return serde_json::Map::new(),
- };
- match parsed {
- serde_json::Value::Object(map) => map,
- _ => serde_json::Map::new(),
- }
-}
-
-fn prune_expired_metadata(
- map: &mut serde_json::Map<String, serde_json::Value>,
- now: u64,
-) {
- map.retain(|_, v| {
- v.get("timestamp")
- .and_then(|t| t.as_u64())
- .map(|ts| now.saturating_sub(ts) <= METADATA_TTL_SECS)
- .unwrap_or(false)
- });
-}
-
-fn write_metadata_map(
- path: &std::path::Path,
- map: &serde_json::Map<String, serde_json::Value>,
-) -> anyhow::Result<()> {
- if map.is_empty() {
- let _ = fs::remove_file(path);
- return Ok(());
- }
- let serialized = serde_json::to_string(&serde_json::Value::Object(map.clone()))?;
- fs::write(path, serialized)?;
- Ok(())
-}
-
-fn write_extension_metadata(request: &NativeHostRequest) -> anyhow::Result<()> {
- let path = extension_metadata_path();
- if let Some(parent) = path.parent() {
- fs::create_dir_all(parent)?;
- }
-
- let now = current_unix_timestamp();
- let mut map = load_metadata_map(&path);
- prune_expired_metadata(&mut map, now);
-
- let entry = serde_json::json!({
- "referer": request.referer,
- "headers": request.headers,
- "mediaType": request.media_type,
- "contentType": request.content_type,
- "title": request.title,
- "thumbnail": request.thumbnail,
- "openApp": request.open_app,
- "pageUrl": request.page_url,
- "userAgent": request.user_agent,
- "timestamp": now,
- });
-
- map.insert(request.url.clone(), entry);
- write_metadata_map(&path, &map)?;
- Ok(())
-}
-
-pub struct ExtensionMetadata {
- pub referer: Option<String>,
- pub headers: Option<std::collections::HashMap<String, String>>,
- pub media_type: Option<String>,
- pub content_type: Option<String>,
- pub title: Option<String>,
- pub thumbnail: Option<String>,
- pub open_app: Option<bool>,
- pub page_url: Option<String>,
- pub user_agent: Option<String>,
-}
-
-fn parse_metadata_entry(meta: &serde_json::Value) -> ExtensionMetadata {
- let headers = meta.get("headers").and_then(|v| v.as_object()).map(|obj| {
- obj.iter()
- .filter_map(|(k, v)| Some((k.clone(), v.as_str()?.to_string())))
- .collect::<std::collections::HashMap<String, String>>()
- });
-
- ExtensionMetadata {
- referer: meta
- .get("referer")
- .and_then(|v| v.as_str())
- .map(String::from),
- headers,
- media_type: meta
- .get("mediaType")
- .and_then(|v| v.as_str())
- .map(String::from),
- content_type: meta
- .get("contentType")
- .and_then(|v| v.as_str())
- .map(String::from),
- title: meta
- .get("title")
- .and_then(|v| v.as_str())
- .filter(|s| !s.is_empty())
- .map(String::from),
- thumbnail: meta
- .get("thumbnail")
- .and_then(|v| v.as_str())
- .filter(|s| !s.is_empty())
- .map(String::from),
- open_app: meta.get("openApp").and_then(|v| v.as_bool()),
- page_url: meta
- .get("pageUrl")
- .and_then(|v| v.as_str())
- .filter(|s| !s.is_empty())
- .map(String::from),
- user_agent: meta
- .get("userAgent")
- .and_then(|v| v.as_str())
- .filter(|s| !s.is_empty())
- .map(String::from),
- }
-}
-
-pub fn read_extension_metadata(url: &str) -> Option<ExtensionMetadata> {
- let path = extension_metadata_path();
- let now = current_unix_timestamp();
- let mut map = load_metadata_map(&path);
- prune_expired_metadata(&mut map, now);
-
- let entry = map.remove(url)?;
- let result = parse_metadata_entry(&entry);
-
- let _ = write_metadata_map(&path, &map);
-
- Some(result)
-}
-
-pub fn peek_extension_open_app(url: &str) -> Option<bool> {
- let path = extension_metadata_path();
- let now = current_unix_timestamp();
- let mut map = load_metadata_map(&path);
- prune_expired_metadata(&mut map, now);
-
- let entry = map.get(url)?;
- let timestamp = entry.get("timestamp").and_then(|v| v.as_u64())?;
- if now.saturating_sub(timestamp) > METADATA_TTL_SECS {
- return None;
- }
- entry.get("openApp").and_then(|v| v.as_bool())
-}
-
-fn handle_request(request: NativeHostRequest) -> NativeHostResponse {
- if let Some(client_version) = request.protocol_version {
- if client_version > HOST_MAX_PROTOCOL_VERSION {
- log_host_event(
- "UNSUPPORTED_PROTOCOL",
- &format!(
- "client_version={client_version} host_max_version={HOST_MAX_PROTOCOL_VERSION}"
- ),
- );
- return NativeHostResponse {
- ok: false,
- code: Some("UNSUPPORTED_PROTOCOL"),
- message: Some(format!(
- "Extension protocol v{} is newer than host v{}. Please update OmniGet.",
- client_version, HOST_MAX_PROTOCOL_VERSION
- )),
- };
- }
- }
-
- if request.kind == "cookies:export" {
- if let Some(ref cookies) = request.cookies {
- if cookies.len() > MAX_COOKIES_PER_REQUEST {
- return NativeHostResponse {
- ok: false,
- code: Some("TOO_MANY_COOKIES"),
- message: Some(format!(
- "cookies:export contains {} cookies; max is {MAX_COOKIES_PER_REQUEST}",
- cookies.len()
- )),
- };
- }
- if !cookies.is_empty() {
- if let Err(e) = write_extension_cookies(cookies) {
- return NativeHostResponse {
- ok: false,
- code: Some("WRITE_FAILED"),
- message: Some(format!("write extension cookies: {}", e)),
- };
- }
- }
- }
- return NativeHostResponse {
- ok: true,
- code: None,
- message: None,
- };
- }
-
- if request.kind != "enqueue" {
- return NativeHostResponse {
- ok: false,
- code: Some("INVALID_URL"),
- message: Some("Unsupported native host message".to_string()),
- };
- }
-
- if !crate::external_url::is_external_url(&request.url) {
- return NativeHostResponse {
- ok: false,
- code: Some("INVALID_URL"),
- message: Some("The requested URL is invalid".to_string()),
- };
- }
-
- if let Some(ref cookies) = request.cookies {
- if cookies.len() > MAX_COOKIES_PER_REQUEST {
- return NativeHostResponse {
- ok: false,
- code: Some("TOO_MANY_COOKIES"),
- message: Some(format!(
- "Request contains {} cookies; max allowed is {MAX_COOKIES_PER_REQUEST}",
- cookies.len()
- )),
- };
- }
- if !cookies.is_empty() {
- if let Err(e) = write_extension_cookies(cookies) {
- eprintln!("[OmniGet] Warning: failed to write extension cookies: {e}");
- }
- }
- }
-
- if request.referer.is_some()
- || request.headers.is_some()
- || request.media_type.is_some()
- || request.title.is_some()
- || request.thumbnail.is_some()
- || request.open_app.is_some()
- || request.page_url.is_some()
- || request.user_agent.is_some()
- {
- if let Err(e) = write_extension_metadata(&request) {
- eprintln!("[OmniGet] Warning: failed to write extension metadata: {e}");
- }
- }
-
- match launch_omniget(&request.url) {
- Ok(()) => NativeHostResponse {
- ok: true,
- code: None,
- message: None,
- },
- Err(error) => NativeHostResponse {
- ok: false,
- code: Some("LAUNCH_FAILED"),
- message: Some(error.to_string()),
- },
- }
-}
-
-fn launch_omniget(url: &str) -> anyhow::Result<()> {
- let current_exe = std::env::current_exe()?;
- let config_path = current_exe
- .parent()
- .unwrap_or_else(|| Path::new("."))
- .join(HOST_CONFIG_NAME);
- let config: NativeHostConfig = serde_json::from_slice(&fs::read(config_path)?)?;
-
- let mut command = std::process::Command::new(config.app_path);
- command.arg(url);
-
- #[cfg(target_os = "windows")]
- {
- use std::os::windows::process::CommandExt;
- const CREATE_NO_WINDOW: u32 = 0x08000000;
- command.creation_flags(CREATE_NO_WINDOW);
- }
-
- command.spawn()?;
- Ok(())
-}
-
-fn read_message() -> anyhow::Result<ReadOutcome> {
- let mut length_bytes = [0u8; 4];
- std::io::stdin().read_exact(&mut length_bytes)?;
- let length = u32::from_le_bytes(length_bytes) as usize;
-
- if length > MAX_MESSAGE_LENGTH {
- return Ok(ReadOutcome::TooLarge(length));
- }
-
- let mut payload = vec![0u8; length];
- std::io::stdin().read_exact(&mut payload)?;
- match serde_json::from_slice(&payload) {
- Ok(request) => Ok(ReadOutcome::Ok(request)),
- Err(err) => Ok(ReadOutcome::MalformedJson(build_deserialize_error_detail(
- &payload, &err,
- ))),
- }
-}
-
-fn write_message(response: &NativeHostResponse) -> anyhow::Result<()> {
- let payload = serde_json::to_vec(response)?;
- let length = (payload.len() as u32).to_le_bytes();
-
- let mut stdout = std::io::stdout();
- stdout.write_all(&length)?;
- stdout.write_all(&payload)?;
- stdout.flush()?;
-
- Ok(())
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn host_copy_name_matches_platform() {
- #[cfg(target_os = "windows")]
- assert_eq!(HOST_COPY_NAME, "omniget-native-host.exe");
-
- #[cfg(not(target_os = "windows"))]
- assert_eq!(HOST_COPY_NAME, "omniget-native-host");
- }
-
- #[test]
- fn manifest_path_from_base_matches_platform_location() {
- #[cfg(target_os = "windows")]
- let base = Path::new(r"C:\Users\test\AppData\Roaming\omniget\chrome-native-host");
-
- #[cfg(not(target_os = "windows"))]
- let base = Path::new("/tmp/chrome-base");
-
- let manifest_path = chrome_manifest_path_from_base(base);
-
- #[cfg(target_os = "windows")]
- assert_eq!(manifest_path, base.join(HOST_MANIFEST_NAME));
-
- #[cfg(target_os = "linux")]
- assert_eq!(
- manifest_path,
- base.join("google-chrome")
- .join("NativeMessagingHosts")
- .join(HOST_MANIFEST_NAME)
- );
-
- #[cfg(target_os = "macos")]
- assert_eq!(
- manifest_path,
- base.join("Google")
- .join("Chrome")
- .join("NativeMessagingHosts")
- .join(HOST_MANIFEST_NAME)
- );
- }
-
- #[test]
- fn rejects_protocol_version_newer_than_host() {
- let payload = serde_json::json!({
- "type": "enqueue",
- "url": "https://example.com/video",
- "protocolVersion": HOST_MAX_PROTOCOL_VERSION + 1,
- });
- let request: NativeHostRequest = serde_json::from_value(payload).unwrap();
- let response = handle_request(request);
- assert!(!response.ok);
- assert_eq!(response.code, Some("UNSUPPORTED_PROTOCOL"));
- }
-
- #[test]
- fn accepts_missing_protocol_version_for_backwards_compat() {
- let payload = serde_json::json!({
- "type": "enqueue",
- "url": "not a url",
- });
- let request: NativeHostRequest = serde_json::from_value(payload).unwrap();
- assert!(request.protocol_version.is_none());
- }
-
- #[test]
- fn accepts_current_protocol_version() {
- let payload = serde_json::json!({
- "type": "enqueue",
- "url": "not a url",
- "protocolVersion": HOST_MAX_PROTOCOL_VERSION,
- });
- let request: NativeHostRequest = serde_json::from_value(payload).unwrap();
- assert_eq!(request.protocol_version, Some(HOST_MAX_PROTOCOL_VERSION));
- }
-
- #[test]
- fn build_host_manifest_contains_expected_fields() {
- #[cfg(target_os = "windows")]
- let host_exe = Path::new(r"C:\tmp\omniget-native-host.exe");
-
- #[cfg(not(target_os = "windows"))]
- let host_exe = Path::new("/tmp/omniget-native-host");
-
- let manifest = build_host_manifest(host_exe);
-
- assert_eq!(manifest["name"].as_str(), Some(CHROME_HOST_NAME));
- assert_eq!(
- manifest["description"].as_str(),
- Some("OmniGet native host for Chrome")
- );
- assert_eq!(
- manifest["path"].as_str(),
- Some(host_exe.to_string_lossy().as_ref())
- );
- assert_eq!(manifest["type"].as_str(), Some("stdio"));
- let allowed_origins = manifest["allowed_origins"]
- .as_array()
- .expect("allowed_origins should be an array");
-
- assert_eq!(allowed_origins.len(), CHROME_EXTENSION_IDS.len());
-
- for (origin, extension_id) in allowed_origins.iter().zip(CHROME_EXTENSION_IDS.iter()) {
- assert_eq!(
- origin.as_str(),
- Some(format!("chrome-extension://{extension_id}/").as_str())
- );
- }
- }
-
- #[test]
- fn prune_expired_metadata_drops_entries_past_ttl() {
- let mut map = serde_json::Map::new();
- map.insert(
- "https://a".to_string(),
- serde_json::json!({"timestamp": 100_u64, "referer": "r1"}),
- );
- map.insert(
- "https://b".to_string(),
- serde_json::json!({"timestamp": 200_u64, "referer": "r2"}),
- );
- let now = 100 + METADATA_TTL_SECS + 1;
- prune_expired_metadata(&mut map, now);
- assert!(!map.contains_key("https://a"));
- assert!(map.contains_key("https://b"));
- }
-
- #[test]
- fn metadata_map_roundtrip_preserves_multiple_urls() {
- let tmp = std::env::temp_dir().join(format!(
- "omniget-meta-test-{}.json",
- current_unix_timestamp()
- ));
- let _ = fs::remove_file(&tmp);
-
- let mut map = serde_json::Map::new();
- map.insert(
- "https://a".to_string(),
- serde_json::json!({"timestamp": 1_u64, "referer": "ra"}),
- );
- map.insert(
- "https://b".to_string(),
- serde_json::json!({"timestamp": 2_u64, "referer": "rb"}),
- );
- write_metadata_map(&tmp, &map).unwrap();
- let loaded = load_metadata_map(&tmp);
- assert_eq!(loaded.len(), 2);
- assert_eq!(
- loaded.get("https://a").and_then(|v| v.get("referer")).and_then(|v| v.as_str()),
- Some("ra")
- );
- assert_eq!(
- loaded.get("https://b").and_then(|v| v.get("referer")).and_then(|v| v.as_str()),
- Some("rb")
- );
-
- let _ = fs::remove_file(&tmp);
- }
-
- fn sample_cookie(name: &str) -> serde_json::Value {
- serde_json::json!({
- "domain": ".example.com",
- "httpOnly": false,
- "path": "/",
- "secure": true,
- "expires": 0,
- "name": name,
- "value": "v",
- })
- }
-
- #[test]
- fn rejects_request_with_too_many_cookies() {
- let cookies: Vec<_> = (0..MAX_COOKIES_PER_REQUEST + 1)
- .map(|i| sample_cookie(&format!("c{i}")))
- .collect();
- let payload = serde_json::json!({
- "type": "enqueue",
- "url": "https://example.com/v",
- "cookies": cookies,
- });
- let request: NativeHostRequest = serde_json::from_value(payload).unwrap();
- let response = handle_request(request);
- assert!(!response.ok);
- assert_eq!(response.code, Some("TOO_MANY_COOKIES"));
- }
-
- #[test]
- fn accepts_request_at_cookie_limit() {
- let cookies: Vec<_> = (0..MAX_COOKIES_PER_REQUEST)
- .map(|i| sample_cookie(&format!("c{i}")))
- .collect();
- let payload = serde_json::json!({
- "type": "enqueue",
- "url": "not a real url",
- "cookies": cookies,
- });
- let request: NativeHostRequest = serde_json::from_value(payload).unwrap();
- let response = handle_request(request);
- assert_ne!(response.code, Some("TOO_MANY_COOKIES"));
- }
-
- #[test]
- fn write_empty_metadata_map_removes_file() {
- let tmp = std::env::temp_dir().join(format!(
- "omniget-meta-empty-{}.json",
- current_unix_timestamp()
- ));
- fs::write(&tmp, "{}").unwrap();
- assert!(tmp.exists());
- let empty: serde_json::Map<String, serde_json::Value> = serde_json::Map::new();
- write_metadata_map(&tmp, &empty).unwrap();
- assert!(!tmp.exists());
- }
-
- #[test]
- fn safe_payload_summary_extracts_non_sensitive_fields() {
- let payload = serde_json::to_vec(&serde_json::json!({
- "type": "enqueue",
- "url": "https://secret.example.com/path?token=SECRET_TOKEN_VALUE",
- "protocolVersion": 1,
- "cookies": [
- {"domain": "a", "httpOnly": false, "path": "/", "secure": true, "expires": 0, "name": "session", "value": "SECRET_VALUE"},
- {"domain": "b", "httpOnly": false, "path": "/", "secure": true, "expires": 0, "name": "csrf", "value": "TOP_SECRET"},
- ],
- })).unwrap();
-
- let summary = safe_payload_summary(&payload);
-
- assert!(summary.contains("type=\"enqueue\""));
- assert!(summary.contains("has_url=true"));
- assert!(summary.contains("cookie_count=2"));
- assert!(summary.contains("protocolVersion=1"));
- }
-
- #[test]
- fn safe_payload_summary_never_leaks_cookie_values() {
- let payload = serde_json::to_vec(&serde_json::json!({
- "type": "enqueue",
- "url": "https://example.com/v",
- "cookies": [
- {"domain": "a", "httpOnly": false, "path": "/", "secure": true, "expires": 0, "name": "session", "value": "SECRET_COOKIE_VALUE_XYZ"},
- ],
- })).unwrap();
-
- let summary = safe_payload_summary(&payload);
-
- assert!(!summary.contains("SECRET_COOKIE_VALUE_XYZ"));
- assert!(!summary.contains("session"));
- }
-
- #[test]
- fn safe_payload_summary_never_leaks_url_query_contents() {
- let payload = serde_json::to_vec(&serde_json::json!({
- "type": "enqueue",
- "url": "https://example.com/?access_token=AAAA_SECRET_TOKEN",
- })).unwrap();
-
- let summary = safe_payload_summary(&payload);
-
- assert!(!summary.contains("AAAA_SECRET_TOKEN"));
- assert!(!summary.contains("example.com"));
- }
-
- #[test]
- fn safe_payload_summary_handles_unparseable_input() {
- let summary = safe_payload_summary(b"{not valid json");
-
- assert!(summary.contains("unparseable"));
- assert!(summary.contains("payload_len=15"));
- }
-
- #[test]
- fn safe_payload_summary_handles_non_object_json() {
- let summary = safe_payload_summary(b"[1,2,3]");
-
- assert!(summary.contains("not_a_json_object"));
- }
-
- #[test]
- fn safe_payload_summary_marks_missing_type_as_placeholder() {
- let payload = serde_json::to_vec(&serde_json::json!({
- "url": "https://example.com/",
- })).unwrap();
-
- let summary = safe_payload_summary(&payload);
-
- assert!(summary.contains("type=\"<missing>\""));
- assert!(summary.contains("has_url=true"));
- }
-
- #[test]
- fn safe_payload_summary_reports_cookie_count_zero_when_absent() {
- let payload = serde_json::to_vec(&serde_json::json!({
- "type": "enqueue",
- "url": "https://example.com/",
- })).unwrap();
-
- let summary = safe_payload_summary(&payload);
-
- assert!(summary.contains("cookie_count=0"));
- assert!(summary.contains("protocolVersion=<none>"));
- }
-}
diff --git a/src/components/settings/SettingsBrowserExtension.svelte b/src/components/settings/SettingsBrowserExtension.svelte
new file mode 100644
index 00000000..7d497781
--- /dev/null
+++ b/src/components/settings/SettingsBrowserExtension.svelte
@@ -0,0 +1,162 @@
+<script lang="ts">
+ import { onMount } from "svelte";
+ import { invoke } from "@tauri-apps/api/core";
+ import { t } from "$lib/i18n";
+ import { showToast } from "$lib/stores/toast-store.svelte";
+
+ type BridgeInfo = {
+ enabled: boolean;
+ port: number;
+ token: string;
+ url: string;
+ };
+
+ let info = $state<BridgeInfo | null>(null);
+ let revealed = $state(false);
+ let rotating = $state(false);
+ let loading = $state(true);
+
+ async function refresh() {
+ try {
+ info = await invoke<BridgeInfo>("get_bridge_info");
+ } catch (e: any) {
+ info = null;
+ showToast("error", typeof e === "string" ? e : (e.message ?? String(e)));
+ } finally {
+ loading = false;
+ }
+ }
+
+ async function copy(value: string, kind: "url" | "token") {
+ if (!value) return;
+ try {
+ await navigator.clipboard.writeText(value);
+ showToast(
+ "success",
+ kind === "url"
+ ? ($t("settings.bridge.copied_url") as string)
+ : ($t("settings.bridge.copied_token") as string)
+ );
+ } catch (e: any) {
+ showToast("error", typeof e === "string" ? e : (e.message ?? String(e)));
+ }
+ }
+
+ async function rotate() {
+ rotating = true;
+ try {
+ info = await invoke<BridgeInfo>("rotate_bridge_token");
+ showToast("success", $t("settings.bridge.rotated") as string);
+ } catch (e: any) {
+ showToast("error", typeof e === "string" ? e : (e.message ?? String(e)));
+ } finally {
+ rotating = false;
+ }
+ }
+
+ function maskedToken(value: string): string {
+ if (!value) return "";
+ if (value.length <= 8) return "•".repeat(value.length);
+ return value.slice(0, 4) + "…" + value.slice(-4);
+ }
+
+ onMount(refresh);
+</script>
+
+<section class="section">
+ <h5 class="section-title">{$t("settings.bridge.title")}</h5>
+ <div class="card">
+ <p class="bridge-intro">{$t("settings.bridge.intro")}</p>
+
+ {#if loading}
+ <div class="setting-row">
+ <span class="setting-label">{$t("common.loading")}</span>
+ </div>
+ {:else if !info || !info.enabled || info.port === 0 || !info.token}
+ <div class="setting-row">
+ <span class="setting-label">{$t("settings.bridge.unavailable")}</span>
+ </div>
+ {:else}
+ <div class="setting-row">
+ <div class="setting-col">
+ <span class="setting-label">{$t("settings.bridge.endpoint_label")}</span>
+ <span class="setting-hint">{info.url}</span>
+ </div>
+ <button class="bridge-action" type="button" onclick={() => copy(info!.url, "url")}>
+ {$t("settings.bridge.copy")}
+ </button>
+ </div>
+ <div class="divider"></div>
+ <div class="setting-row">
+ <div class="setting-col">
+ <span class="setting-label">{$t("settings.bridge.token_label")}</span>
+ <span class="setting-hint token-display">
+ {revealed ? info.token : maskedToken(info.token)}
+ </span>
+ </div>
+ <div class="bridge-actions">
+ <button
+ class="bridge-action"
+ type="button"
+ onclick={() => (revealed = !revealed)}
+ >
+ {revealed ? $t("settings.bridge.hide") : $t("settings.bridge.reveal")}
+ </button>
+ <button
+ class="bridge-action"
+ type="button"
+ onclick={() => copy(info!.token, "token")}
+ >
+ {$t("settings.bridge.copy")}
+ </button>
+ </div>
+ </div>
+ <div class="divider"></div>
+ <div class="setting-row">
+ <div class="setting-col">
+ <span class="setting-label">{$t("settings.bridge.rotate_label")}</span>
+ <span class="setting-hint">{$t("settings.bridge.rotate_hint")}</span>
+ </div>
+ <button
+ class="bridge-action danger"
+ type="button"
+ disabled={rotating}
+ onclick={rotate}
+ >
+ {rotating ? $t("settings.bridge.rotating") : $t("settings.bridge.rotate")}
+ </button>
+ </div>
+ {/if}
+ </div>
+</section>
+
+<style>
+ .bridge-intro {
+ margin: 0 0 12px;
+ color: var(--color-text-muted, #95a0b7);
+ font-size: 13px;
+ line-height: 1.5;
+ }
+ .token-display {
+ font-family: var(--font-mono, "IBM Plex Mono", monospace);
+ word-break: break-all;
+ }
+ .bridge-actions {
+ display: inline-flex;
+ gap: 8px;
+ }
+ .bridge-action {
+ appearance: none;
+ border: 1px solid rgba(255, 255, 255, 0.12);
+ background: rgba(255, 255, 255, 0.04);
+ color: inherit;
+ padding: 6px 12px;
+ border-radius: 8px;
+ font: inherit;
+ cursor: pointer;
+ }
+ .bridge-action:hover { background: rgba(255, 255, 255, 0.08); }
+ .bridge-action:disabled { opacity: 0.5; cursor: not-allowed; }
+ .bridge-action.danger { color: #ff8b6f; border-color: rgba(255, 139, 111, 0.3); }
+ .bridge-action.danger:hover { background: rgba(255, 139, 111, 0.1); }
+</style>
diff --git a/src/lib/i18n/el.json b/src/lib/i18n/el.json
index ccc41886..706a71b4 100644
--- a/src/lib/i18n/el.json
+++ b/src/lib/i18n/el.json
@@ -367,6 +367,23 @@
"app_id_hint": "ID εφαρμογης Discord. Αλλαξτε μονο αν ξερετε τι κανετε.",
"large_image": "Κλειδι μεγαλης εικονας",
"large_image_hint": "Ονομα ενεργειου που μεταφορτωθηκε στην εφαρμογη Discord."
+ },
+ "bridge": {
+ "title": "Browser extension",
+ "intro": "Pair the OmniGet browser extension with this app over a private localhost connection. Open the extension's options page, paste the endpoint URL and token below, and click Save.",
+ "endpoint_label": "Endpoint URL",
+ "token_label": "Pairing token",
+ "rotate_label": "Rotate token",
+ "rotate_hint": "Generates a new token. Any browser already paired will need to update its token.",
+ "rotate": "Rotate",
+ "rotating": "Rotating…",
+ "rotated": "New pairing token generated.",
+ "reveal": "Reveal",
+ "hide": "Hide",
+ "copy": "Copy",
+ "copied_url": "Endpoint URL copied to clipboard.",
+ "copied_token": "Token copied to clipboard.",
+ "unavailable": "Bridge unavailable. Try restarting the app."
}
},
"omnibox": {
diff --git a/src/lib/i18n/en.json b/src/lib/i18n/en.json
index 859ca359..ee9153b6 100644
--- a/src/lib/i18n/en.json
+++ b/src/lib/i18n/en.json
@@ -367,6 +367,23 @@
"app_id_hint": "Discord application ID. Change only if you know what you're doing.",
"large_image": "Large image key",
"large_image_hint": "Asset name uploaded to your Discord application."
+ },
+ "bridge": {
+ "title": "Browser extension",
+ "intro": "Pair the OmniGet browser extension with this app over a private localhost connection. Open the extension's options page, paste the endpoint URL and token below, and click Save.",
+ "endpoint_label": "Endpoint URL",
+ "token_label": "Pairing token",
+ "rotate_label": "Rotate token",
+ "rotate_hint": "Generates a new token. Any browser already paired will need to update its token.",
+ "rotate": "Rotate",
+ "rotating": "Rotating…",
+ "rotated": "New pairing token generated.",
+ "reveal": "Reveal",
+ "hide": "Hide",
+ "copy": "Copy",
+ "copied_url": "Endpoint URL copied to clipboard.",
+ "copied_token": "Token copied to clipboard.",
+ "unavailable": "Bridge unavailable. Try restarting the app."
}
},
"omnibox": {
diff --git a/src/lib/i18n/fr.json b/src/lib/i18n/fr.json
index 0046db57..c4fadabe 100644
--- a/src/lib/i18n/fr.json
+++ b/src/lib/i18n/fr.json
@@ -367,6 +367,23 @@
"app_id_hint": "ID de l'application Discord. Ne changez que si vous savez ce que vous faites.",
"large_image": "Cle de la grande image",
"large_image_hint": "Nom de l'asset televerse vers votre application Discord."
+ },
+ "bridge": {
+ "title": "Extension de navigateur",
+ "intro": "Associez l'extension OmniGet à l'application via une connexion locale privée. Ouvrez la page d'options de l'extension, collez l'URL et le jeton ci-dessous, puis enregistrez.",
+ "endpoint_label": "URL du point d'accès",
+ "token_label": "Jeton d'appairage",
+ "rotate_label": "Régénérer le jeton",
+ "rotate_hint": "Génère un nouveau jeton. Les navigateurs déjà appairés devront le mettre à jour.",
+ "rotate": "Régénérer",
+ "rotating": "Génération…",
+ "rotated": "Nouveau jeton d'appairage généré.",
+ "reveal": "Afficher",
+ "hide": "Masquer",
+ "copy": "Copier",
+ "copied_url": "URL copiée dans le presse-papier.",
+ "copied_token": "Jeton copié dans le presse-papier.",
+ "unavailable": "Pont indisponible. Redémarrez l'application."
}
},
"omnibox": {
diff --git a/src/lib/i18n/it.json b/src/lib/i18n/it.json
index bdc02270..34fb2bd9 100644
--- a/src/lib/i18n/it.json
+++ b/src/lib/i18n/it.json
@@ -367,6 +367,23 @@
"app_id_hint": "ID applicazione Discord. Modifica solo se sai cosa stai facendo.",
"large_image": "Chiave immagine grande",
"large_image_hint": "Nome dell'asset caricato nella tua applicazione Discord."
+ },
+ "bridge": {
+ "title": "Estensione del browser",
+ "intro": "Associa l'estensione OmniGet a questa app tramite una connessione locale privata. Apri la pagina delle opzioni dell'estensione, incolla URL e token qui sotto, poi clicca Salva.",
+ "endpoint_label": "URL dell'endpoint",
+ "token_label": "Token di abbinamento",
+ "rotate_label": "Rigenera token",
+ "rotate_hint": "Genera un nuovo token. I browser già associati dovranno aggiornare il loro token.",
+ "rotate": "Rigenera",
+ "rotating": "Rigenerazione…",
+ "rotated": "Nuovo token di abbinamento generato.",
+ "reveal": "Mostra",
+ "hide": "Nascondi",
+ "copy": "Copia",
+ "copied_url": "URL dell'endpoint copiato negli appunti.",
+ "copied_token": "Token copiato negli appunti.",
+ "unavailable": "Bridge non disponibile. Riavvia l'app."
}
},
"omnibox": {
diff --git a/src/lib/i18n/ja.json b/src/lib/i18n/ja.json
index b23405bb..e699f511 100644
--- a/src/lib/i18n/ja.json
+++ b/src/lib/i18n/ja.json
@@ -367,6 +367,23 @@
"app_id_hint": "Discord アプリケーション ID。意図がない限り変更しないでください。",
"large_image": "ラージイメージキー",
"large_image_hint": "Discord アプリにアップロードされたアセット名。"
+ },
+ "bridge": {
+ "title": "ブラウザー拡張機能",
+ "intro": "プライベートなローカル接続でOmniGetブラウザー拡張機能をこのアプリと連携します。拡張機能のオプションページを開き、下のエンドポイントURLとトークンを貼り付けて保存をクリックしてください。",
+ "endpoint_label": "エンドポイントURL",
+ "token_label": "ペアリングトークン",
+ "rotate_label": "トークンを再発行",
+ "rotate_hint": "新しいトークンを生成します。すでにペアリング済みのブラウザーは更新が必要です。",
+ "rotate": "再発行",
+ "rotating": "発行中…",
+ "rotated": "新しいペアリングトークンを発行しました。",
+ "reveal": "表示",
+ "hide": "非表示",
+ "copy": "コピー",
+ "copied_url": "エンドポイントURLをクリップボードにコピーしました。",
+ "copied_token": "トークンをクリップボードにコピーしました。",
+ "unavailable": "ブリッジが利用できません。アプリを再起動してください。"
}
},
"omnibox": {
diff --git a/src/lib/i18n/keys.ts b/src/lib/i18n/keys.ts
index 521b5eb0..48e0e4df 100644
--- a/src/lib/i18n/keys.ts
+++ b/src/lib/i18n/keys.ts
@@ -480,6 +480,21 @@ export type TranslationKeys =
| 'settings.appearance.theme'
| 'settings.appearance.theme_system'
| 'settings.appearance.title'
+ | 'settings.bridge.copied_token'
+ | 'settings.bridge.copied_url'
+ | 'settings.bridge.copy'
+ | 'settings.bridge.endpoint_label'
+ | 'settings.bridge.hide'
+ | 'settings.bridge.intro'
+ | 'settings.bridge.reveal'
+ | 'settings.bridge.rotate'
+ | 'settings.bridge.rotate_hint'
+ | 'settings.bridge.rotate_label'
+ | 'settings.bridge.rotated'
+ | 'settings.bridge.rotating'
+ | 'settings.bridge.title'
+ | 'settings.bridge.token_label'
+ | 'settings.bridge.unavailable'
| 'settings.cat_advanced'
| 'settings.cat_appearance'
| 'settings.cat_downloads'
diff --git a/src/lib/i18n/pt.json b/src/lib/i18n/pt.json
index 047cfa15..d4e3803b 100644
--- a/src/lib/i18n/pt.json
+++ b/src/lib/i18n/pt.json
@@ -367,6 +367,23 @@
"app_id_hint": "ID da aplicação Discord. Mude apenas se souber o que está fazendo.",
"large_image": "Chave da imagem grande",
"large_image_hint": "Nome do asset enviado para sua aplicação Discord."
+ },
+ "bridge": {
+ "title": "Extensão do navegador",
+ "intro": "Pareie a extensão OmniGet com este app por meio de uma conexão local privada. Abra a página de opções da extensão, cole a URL e o token abaixo e clique em Salvar.",
+ "endpoint_label": "URL do endpoint",
+ "token_label": "Token de pareamento",
+ "rotate_label": "Gerar novo token",
+ "rotate_hint": "Gera um novo token. Navegadores já pareados precisarão atualizar o token.",
+ "rotate": "Gerar novo",
+ "rotating": "Gerando…",
+ "rotated": "Novo token de pareamento gerado.",
+ "reveal": "Mostrar",
+ "hide": "Ocultar",
+ "copy": "Copiar",
+ "copied_url": "URL do endpoint copiada para a área de transferência.",
+ "copied_token": "Token copiado para a área de transferência.",
+ "unavailable": "Bridge indisponível. Reinicie o app."
}
},
"omnibox": {
diff --git a/src/lib/i18n/zh-TW.json b/src/lib/i18n/zh-TW.json
index 61b8424b..ba101fb8 100644
--- a/src/lib/i18n/zh-TW.json
+++ b/src/lib/i18n/zh-TW.json
@@ -367,6 +367,23 @@
"app_id_hint": "Discord 應用程式 ID。除非您知道在做什麼,否則請勿變更。",
"large_image": "大圖鍵",
"large_image_hint": "上傳至 Discord 應用程式的資源名稱。"
+ },
+ "bridge": {
+ "title": "瀏覽器擴充功能",
+ "intro": "透過私有的本機連線將 OmniGet 瀏覽器擴充功能與此應用程式配對。打開擴充功能的選項頁面,貼上下方的端點 URL 與權杖,然後按下儲存。",
+ "endpoint_label": "端點 URL",
+ "token_label": "配對權杖",
+ "rotate_label": "重新產生權杖",
+ "rotate_hint": "產生新的權杖。已配對的瀏覽器需要更新其權杖。",
+ "rotate": "重新產生",
+ "rotating": "產生中…",
+ "rotated": "已產生新的配對權杖。",
+ "reveal": "顯示",
+ "hide": "隱藏",
+ "copy": "複製",
+ "copied_url": "端點 URL 已複製到剪貼簿。",
+ "copied_token": "權杖已複製到剪貼簿。",
+ "unavailable": "橋接不可用。請重新啟動應用程式。"
}
},
"omnibox": {
diff --git a/src/lib/i18n/zh.json b/src/lib/i18n/zh.json
index bf1dae9e..99ffbcdc 100644
--- a/src/lib/i18n/zh.json
+++ b/src/lib/i18n/zh.json
@@ -367,6 +367,23 @@
"app_id_hint": "Discord 应用 ID。如不确定请勿更改。",
"large_image": "大图键",
"large_image_hint": "上传到 Discord 应用的资源名称。"
+ },
+ "bridge": {
+ "title": "浏览器扩展",
+ "intro": "通过私有的本地连接将 OmniGet 浏览器扩展与此应用配对。打开扩展的选项页面,粘贴下方的端点 URL 与令牌,然后点击保存。",
+ "endpoint_label": "端点 URL",
+ "token_label": "配对令牌",
+ "rotate_label": "重新生成令牌",
+ "rotate_hint": "生成新的令牌。已配对的浏览器需要更新其令牌。",
+ "rotate": "重新生成",
+ "rotating": "生成中…",
+ "rotated": "已生成新的配对令牌。",
+ "reveal": "显示",
+ "hide": "隐藏",
+ "copy": "复制",
+ "copied_url": "端点 URL 已复制到剪贴板。",
+ "copied_token": "令牌已复制到剪贴板。",
+ "unavailable": "桥接不可用。请重启应用。"
}
},
"omnibox": {
diff --git a/src/routes/settings/+page.svelte b/src/routes/settings/+page.svelte
index 2445a4f3..9956d6e7 100644
--- a/src/routes/settings/+page.svelte
+++ b/src/routes/settings/+page.svelte
@@ -15,6 +15,7 @@
import SettingsNetwork from "$components/settings/SettingsNetwork.svelte";
import SettingsDownloads from "$components/settings/SettingsDownloads.svelte";
import SettingsTypography from "$components/settings/SettingsTypography.svelte";
+ import SettingsBrowserExtension from "$components/settings/SettingsBrowserExtension.svelte";
type DependencyStatus = {
name: string;
@@ -433,6 +434,7 @@
{/if}
{#if isSearching || activeCategory === "network"}
+ <SettingsBrowserExtension />
<SettingsNetwork />
{/if}