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): give pairing a feedback loop and fix stale-token deadlock

Antonio Leandro7eb3d91caa03
diff --git a/browser-extension/chrome/README.md b/browser-extension/chrome/README.md
index 8a359237..6a9547b0 100644
--- a/browser-extension/chrome/README.md
+++ b/browser-extension/chrome/README.md
@@ -72,14 +72,41 @@ If the user clicks Download before completing the pairing flow, the extension fa
Mirror domains are also recognized: `youtu.be`, `youtube-nocookie.com`, `ddinstagram.com`, `vxtwitter.com`, `fixvx.com`, `v.redd.it`, `redd.it`, `clips.twitch.tv`, `pin.it`, `b23.tv`, `t.me`, `telegram.me`.
-## Install
+## Install & pair
-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. 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.
+### 1. Install the desktop app
-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.
+Install OmniGet from [github.com/tonhowtf/omniget/releases](https://github.com/tonhowtf/omniget/releases/latest) and **launch it once**. On first launch it generates a per-installation pairing token and starts the local bridge on `127.0.0.1:47720` (or the next free port up to `47729`).
+
+### 2. Install the extension
+
+- **Unpacked (development):** open `chrome://extensions`, enable **Developer mode**, click **Load unpacked**, select `browser-extension/chrome/`.
+- **Chrome Web Store:** install from the store listing when available — the pairing flow is identical.
+
+The extension's onboarding tab opens automatically after install (and after updates, if this browser isn't paired yet).
+
+### 3. Pair (pick either path)
+
+**Recommended — one click in the app:**
+
+1. In OmniGet, go to **Settings → Network → Browser extension** and click **Pair extension**. This opens a single-use pairing window for 120 seconds.
+2. Keep the extension's options page open (or click **Pair now** on it). The page polls the app every 5 seconds while visible, so pairing completes within seconds; the app shows "Extension connected" when it succeeds. Even with the options page closed, the extension's background worker retries about once per minute, so pairing can take up to ~60 s in the worst case.
+
+**Manual — paste the token:**
+
+1. In OmniGet, go to **Settings → Network → Browser extension**, reveal/copy the **token**.
+2. Open the extension's options page (right-click the toolbar icon → Options). The endpoint is auto-detected; paste the token into the **Pairing token** field and click **Save**.
+
+### 4. Use it
+
+Click the OmniGet icon on any page. 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.
+
+### Troubleshooting
+
+- **Pairing window expired without connecting** — make sure the extension is installed and the browser is open, then click **Pair extension** in the app again with the extension's options page visible (it polls every 5 s while visible).
+- **Downloads suddenly stopped working / HTTP 401 (stale token)** — if you clicked **Rotate token** (or reset settings) in OmniGet, the token stored in this browser is no longer valid. The extension detects the 401, clears the stale token, and automatically goes back to pairing mode; open **Settings → Network → Browser extension → Pair extension** in the app (or paste the new token manually) to re-pair.
+- **"OmniGet doesn't seem to be running" / all ports busy** — the bridge binds the first free port in `47720–47729` and falls back to an OS-picked port if all ten are taken. Check the endpoint URL shown in **Settings → Network → Browser extension**, then enter it under **Advanced: change endpoint URL** on the options page.
+- **App not running** — launch the desktop app first; the health probe (`GET /v1/health`) must answer before pairing can work.
## Permissions
diff --git a/browser-extension/chrome/pages/options.html b/browser-extension/chrome/pages/options.html
index 78ef8ae6..455303bb 100644
--- a/browser-extension/chrome/pages/options.html
+++ b/browser-extension/chrome/pages/options.html
@@ -23,8 +23,9 @@
<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.
+ extension</strong> and click <strong>Pair extension</strong> —
+ this page picks the token up automatically within a few seconds.
+ Or copy the <em>token</em> shown there into the field below.
</p>
</header>
@@ -67,7 +68,8 @@
</details>
<div class="actions">
- <button id="save" type="submit" class="button primary">Save</button>
+ <button id="pair-now" type="button" class="button primary">Pair now</button>
+ <button id="save" type="submit" class="button">Save</button>
<button id="test" type="button" class="button">Test connection</button>
</div>
diff --git a/browser-extension/chrome/pages/options.js b/browser-extension/chrome/pages/options.js
index 54ecd75b..a2f7714b 100644
--- a/browser-extension/chrome/pages/options.js
+++ b/browser-extension/chrome/pages/options.js
@@ -4,6 +4,7 @@ import {
checkBridgeHealth,
discoverBridgeEndpoint,
trimEndpoint,
+ autoPair,
} from "../src/bridge-client.js";
const endpointInput = document.getElementById("endpoint");
@@ -11,6 +12,7 @@ const tokenInput = document.getElementById("token");
const revealBtn = document.getElementById("reveal");
const form = document.getElementById("pair-form");
const testBtn = document.getElementById("test");
+const pairNowBtn = document.getElementById("pair-now");
const statusEl = document.getElementById("status");
const welcomeHeader = document.getElementById("welcome-header");
const settingsHeader = document.getElementById("settings-header");
@@ -39,10 +41,73 @@ function setDiscovery(state, message) {
discoveryMessage.textContent = message;
}
+// --- Auto-pairing -----------------------------------------------------------
+// The desktop app opens a single-use ~120s pairing window when the user
+// clicks "Pair extension" in Settings. While this page is visible we poll
+// `GET /v1/pair` every 5 seconds so pairing completes within seconds of that
+// click (the background service worker only retries once per minute).
+const AUTOPAIR_POLL_MS = 5000;
+let pairPollTimer = null;
+
+async function onPairedSuccess() {
+ const { endpoint, token } = await loadBridgeConfig();
+ endpointInput.value = endpoint || "";
+ tokenInput.value = token || "";
+ setDiscovery("found", `Paired with OmniGet at ${endpoint}.`);
+ setStatus("Paired automatically — you're all set.", "ok");
+ stopPairPolling();
+}
+
+async function tryAutoPair() {
+ const result = await autoPair().catch(() => ({ ok: false }));
+ if (!result?.ok) return false;
+ if (result.reason === "already-paired") {
+ stopPairPolling();
+ return true;
+ }
+ await onPairedSuccess();
+ return true;
+}
+
+function startPairPolling() {
+ if (pairPollTimer !== null) return;
+ pairPollTimer = setInterval(() => {
+ void tryAutoPair();
+ }, AUTOPAIR_POLL_MS);
+}
+
+function stopPairPolling() {
+ if (pairPollTimer !== null) {
+ clearInterval(pairPollTimer);
+ pairPollTimer = null;
+ }
+}
+
+document.addEventListener("visibilitychange", () => {
+ if (document.hidden) {
+ stopPairPolling();
+ return;
+ }
+ loadBridgeConfig().then(({ token }) => {
+ if (!token) {
+ void tryAutoPair();
+ startPairPolling();
+ }
+ });
+});
+
async function init() {
const { endpoint, token } = await loadBridgeConfig();
const alreadyPaired = Boolean(token);
+ // While unpaired, keep trying to grab the token automatically: once
+ // immediately (the user may already have a pairing window open in the
+ // app) and then every few seconds while this page stays visible.
+ if (!alreadyPaired) {
+ void tryAutoPair();
+ if (!document.hidden) startPairPolling();
+ }
+
// 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) {
@@ -111,6 +176,19 @@ form.addEventListener("submit", async (event) => {
setStatus("Saved. The extension will use this token from now on.", "ok");
});
+if (pairNowBtn) {
+ pairNowBtn.addEventListener("click", async () => {
+ setStatus("Trying to pair automatically…");
+ const paired = await tryAutoPair();
+ if (paired) return;
+ setStatus(
+ "No open pairing window found. In OmniGet, go to Settings → Network → Browser extension and click \"Pair extension\", then try again (or just wait — this page keeps retrying).",
+ "error"
+ );
+ if (!document.hidden) startPairPolling();
+ });
+}
+
testBtn.addEventListener("click", async () => {
const endpoint = resolvedEndpoint();
setStatus("Testing connection…");
diff --git a/browser-extension/chrome/src/background.js b/browser-extension/chrome/src/background.js
index 5aeea7d2..d42e8bd8 100644
--- a/browser-extension/chrome/src/background.js
+++ b/browser-extension/chrome/src/background.js
@@ -6,9 +6,16 @@ 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, autoPair, loadBridgeConfig } from "./bridge-client.js";
+import {
+ sendViaBridge,
+ sendCookiesViaBridge,
+ autoPair,
+ loadBridgeConfig,
+ AUTOPAIR_ALARM_NAME,
+ STORAGE_KEY_TOKEN,
+} from "./bridge-client.js";
-const AUTOPAIR_ALARM = "omniget-autopair";
+const AUTOPAIR_ALARM = AUTOPAIR_ALARM_NAME;
async function isPaired() {
try {
@@ -56,6 +63,19 @@ if (chrome.alarms?.onAlarm) {
});
}
+// If the stored token is ever cleared (401 recovery in bridge-client.js, or
+// the user wiping it from the options page), go back to polling for a fresh
+// pairing window so the browser can re-pair without a reinstall.
+if (chrome.storage?.onChanged) {
+ chrome.storage.onChanged.addListener((changes, areaName) => {
+ if (areaName !== "local") return;
+ const change = changes?.[STORAGE_KEY_TOKEN];
+ if (!change) return;
+ const newToken = typeof change.newValue === "string" ? change.newValue.trim() : "";
+ if (!newToken) void ensureAutoPairAlarm();
+ });
+}
+
const INSTALL_URL = "https://github.com/tonhowtf/omniget/releases/latest";
const PROTOCOL_VERSION = 1;
diff --git a/browser-extension/chrome/src/bridge-client.js b/browser-extension/chrome/src/bridge-client.js
index 8584ff37..b9f21824 100644
--- a/browser-extension/chrome/src/bridge-client.js
+++ b/browser-extension/chrome/src/bridge-client.js
@@ -15,6 +15,9 @@
export const STORAGE_KEY_ENDPOINT = "bridge_endpoint";
export const STORAGE_KEY_TOKEN = "bridge_token";
+// Name of the low-frequency autopair alarm owned by background.js. Exported
+// so the 401 recovery path below can re-arm it without duplicating the name.
+export const AUTOPAIR_ALARM_NAME = "omniget-autopair";
const HEALTH_TIMEOUT_MS = 1500;
const ENQUEUE_TIMEOUT_MS = 8000;
const PROTOCOL_VERSION = 1;
@@ -64,6 +67,35 @@ export async function saveBridgeConfig(
});
}
+// Forget the stored token (keep the endpoint — it's still valid). Used when
+// the desktop app rejects our bearer, e.g. after the user rotated the token
+// in Settings; keeping the stale token around would leave this browser
+// permanently unable to re-pair.
+export async function clearStoredToken({ storage = globalThis.chrome?.storage?.local } = {}) {
+ if (!storage?.set) return false;
+ return new Promise((resolve) => {
+ storage.set({ [STORAGE_KEY_TOKEN]: "" }, () => resolve(true));
+ });
+}
+
+// 401/403 from the bridge means our token is stale (rotated or reset on the
+// desktop side). Clear it and re-arm the autopair alarm so the extension can
+// pick up a fresh token the next time the user opens a pairing window.
+async function handleUnauthorized(storage) {
+ try {
+ await clearStoredToken({ storage });
+ } catch {}
+ try {
+ const alarms = globalThis.chrome?.alarms;
+ if (alarms?.create) {
+ const existing = alarms.get ? await alarms.get(AUTOPAIR_ALARM_NAME) : null;
+ if (!existing) {
+ alarms.create(AUTOPAIR_ALARM_NAME, { periodInMinutes: 1 });
+ }
+ }
+ } catch {}
+}
+
function withTimeout(promise, ms, controller) {
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
@@ -233,6 +265,9 @@ export async function sendViaBridge(
}
if (response.status === 401 || response.status === 403) {
+ // Stale token (rotated/reset in the app) — drop it and re-arm autopair
+ // so this browser can pair again instead of being locked out forever.
+ await handleUnauthorized(storage);
return {
ok: false,
reason: "unauthorized",
@@ -321,6 +356,9 @@ export async function sendCookiesViaBridge(
}
if (response.status === 401 || response.status === 403) {
+ // Stale token (rotated/reset in the app) — drop it and re-arm autopair
+ // so this browser can pair again instead of being locked out forever.
+ await handleUnauthorized(storage);
return {
ok: false,
reason: "unauthorized",
diff --git a/browser-extension/firefox/_locales/ru/messages.json b/browser-extension/firefox/_locales/ru/messages.json
new file mode 100644
index 00000000..d3e9c0df
--- /dev/null
+++ b/browser-extension/firefox/_locales/ru/messages.json
@@ -0,0 +1,98 @@
+{
+ "action_title_supported": {
+ "message": "Отправить эту медиа-страницу в OmniGet"
+ },
+ "action_title_unsupported": {
+ "message": "На этой странице не обнаружено поддерживаемых медиа"
+ },
+ "error_page_document_title": {
+ "message": "Расширение OmniGet"
+ },
+ "error_page_eyebrow": {
+ "message": "Расширение OmniGet"
+ },
+ "error_page_install_cta": {
+ "message": "Установить OmniGet"
+ },
+ "error_page_open_extensions": {
+ "message": "Открыть расширения Chrome"
+ },
+ "error_host_missing_title": {
+ "message": "Запустите OmniGet один раз, чтобы завершить настройку Chrome"
+ },
+ "error_host_missing_body": {
+ "message": "Chrome пока не может найти мост OmniGet на этом компьютере."
+ },
+ "error_host_missing_detail": {
+ "message": "Установите OmniGet при необходимости, затем запустите приложение один раз и нажмите на расширение снова."
+ },
+ "error_invalid_url_title": {
+ "message": "URL этой страницы нельзя отправить в OmniGet"
+ },
+ "error_invalid_url_body": {
+ "message": "Текущая страница не является поддерживаемой медиа-страницей для расширения OmniGet."
+ },
+ "error_invalid_url_detail": {
+ "message": "Попробуйте снова с прямой страницы видео, рилса, поста, плейлиста или курса."
+ },
+ "error_launch_failed_title": {
+ "message": "Не удалось запустить OmniGet из Chrome"
+ },
+ "error_launch_failed_body": {
+ "message": "Расширение связалось с нативным хостом, но приложение не запустилось корректно."
+ },
+ "error_launch_failed_detail": {
+ "message": "Проверьте, установлен ли OmniGet и не блокируется ли он вашей системой, затем повторите попытку."
+ },
+ "popup_send_default": { "message": "Отправить в OmniGet" },
+ "popup_send_audio": { "message": "Отправить аудио" },
+ "popup_video_found_one": { "message": "Найдено видео" },
+ "popup_videos_found": { "message": "$count$ видео найдено", "placeholders": { "count": { "content": "$1" } } },
+ "popup_listening_title": { "message": "Ожидание медиа…" },
+ "popup_listening_hint": { "message": "Видео и аудио будут появляться здесь по мере загрузки страниц." },
+ "popup_paused_title": { "message": "Обнаружение медиа приостановлено" },
+ "popup_paused_hint": { "message": "Включите переключатель выше, чтобы обнаруживать видео на этой странице." },
+ "popup_send_all": { "message": "Отправить все ($count$ видео)", "placeholders": { "count": { "content": "$1" } } },
+ "popup_detected_one": { "message": "Обнаружено 1 видео" },
+ "popup_detected_many": { "message": "Обнаружено $count$ видео", "placeholders": { "count": { "content": "$1" } } },
+ "popup_video_n": { "message": "Видео $n$", "placeholders": { "n": { "content": "$1" } } },
+ "popup_kind_audio": { "message": "Аудио" },
+ "popup_kind_video": { "message": "Видео" },
+ "popup_download_aria": { "message": "Скачать $name$", "placeholders": { "name": { "content": "$1" } } },
+ "popup_sending": { "message": "Отправка…" },
+ "popup_sent": { "message": "Отправлено!" },
+ "popup_sending_n": { "message": "Отправка $count$ видео…", "placeholders": { "count": { "content": "$1" } } },
+ "popup_sent_n": { "message": "$count$ видео отправлено!", "placeholders": { "count": { "content": "$1" } } },
+ "popup_sent_failed": { "message": "Отправлено $sent$, не удалось $failed$", "placeholders": { "sent": { "content": "$1" }, "failed": { "content": "$2" } } },
+ "popup_not_running": { "message": "OmniGet не запущен" },
+ "popup_try_again": { "message": "Повторить" },
+ "popup_get_app": { "message": "Скачать OmniGet" },
+ "popup_lbl_course": { "message": "Отправить курс в OmniGet" },
+ "popup_lbl_playlist": { "message": "Отправить плейлист в OmniGet" },
+ "popup_lbl_video": { "message": "Отправить видео в OmniGet" },
+ "popup_lbl_reel": { "message": "Отправить рилс в OmniGet" },
+ "popup_lbl_post": { "message": "Отправить пост в OmniGet" },
+ "popup_lbl_short": { "message": "Отправить короткое видео в OmniGet" },
+ "popup_lbl_clip": { "message": "Отправить клип в OmniGet" },
+ "popup_lbl_image": { "message": "Отправить изображение в OmniGet" },
+ "popup_lbl_audio": { "message": "Отправить аудио в OmniGet" },
+ "popup_lbl_profile": { "message": "Отправить профиль в OmniGet" },
+ "popup_lbl_page": { "message": "Отправить страницу в OmniGet" },
+ "popup_ck_saving": { "message": "Сохранение cookies…" },
+ "popup_ck_saved": { "message": "Сохранено cookies: $count$", "placeholders": { "count": { "content": "$1" } } },
+ "popup_ck_btn": { "message": "Сохранить cookies сайта" },
+ "popup_ck_meta": { "message": "$domain$ • $kind$", "placeholders": { "domain": { "content": "$1" }, "kind": { "content": "$2" } } },
+ "popup_ck_hint": { "message": "Отправляет cookies этого сайта в менеджер cookies OmniGet." },
+ "popup_ckerr_no_url": { "message": "Нет активной вкладки" },
+ "popup_ckerr_invalid_url": { "message": "Страница недоступна для проверки" },
+ "popup_ckerr_unsupported": { "message": "Только страницы http/https" },
+ "popup_ckerr_no_api": { "message": "API cookies заблокирован" },
+ "popup_ckerr_no_cookies": { "message": "Нет cookies для этого сайта" },
+ "popup_ckerr_missing_token": { "message": "Сначала свяжите OmniGet" },
+ "popup_ckerr_missing_endpoint": { "message": "OmniGet не обнаружен" },
+ "popup_ckerr_fetch_failed": { "message": "OmniGet не запущен" },
+ "popup_ckerr_unauthorized": { "message": "Неверный токен связывания" },
+ "popup_ckerr_default": { "message": "Не удалось сохранить cookies" },
+ "popup_open_app_label": { "message": "Открывать приложение при загрузке" },
+ "popup_sniffer_label": { "message": "Обнаружение медиа" }
+}
\ No newline at end of file
diff --git a/browser-extension/firefox/pages/options.html b/browser-extension/firefox/pages/options.html
index 78ef8ae6..455303bb 100644
--- a/browser-extension/firefox/pages/options.html
+++ b/browser-extension/firefox/pages/options.html
@@ -23,8 +23,9 @@
<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.
+ extension</strong> and click <strong>Pair extension</strong> —
+ this page picks the token up automatically within a few seconds.
+ Or copy the <em>token</em> shown there into the field below.
</p>
</header>
@@ -67,7 +68,8 @@
</details>
<div class="actions">
- <button id="save" type="submit" class="button primary">Save</button>
+ <button id="pair-now" type="button" class="button primary">Pair now</button>
+ <button id="save" type="submit" class="button">Save</button>
<button id="test" type="button" class="button">Test connection</button>
</div>
diff --git a/browser-extension/firefox/pages/options.js b/browser-extension/firefox/pages/options.js
index 54ecd75b..a2f7714b 100644
--- a/browser-extension/firefox/pages/options.js
+++ b/browser-extension/firefox/pages/options.js
@@ -4,6 +4,7 @@ import {
checkBridgeHealth,
discoverBridgeEndpoint,
trimEndpoint,
+ autoPair,
} from "../src/bridge-client.js";
const endpointInput = document.getElementById("endpoint");
@@ -11,6 +12,7 @@ const tokenInput = document.getElementById("token");
const revealBtn = document.getElementById("reveal");
const form = document.getElementById("pair-form");
const testBtn = document.getElementById("test");
+const pairNowBtn = document.getElementById("pair-now");
const statusEl = document.getElementById("status");
const welcomeHeader = document.getElementById("welcome-header");
const settingsHeader = document.getElementById("settings-header");
@@ -39,10 +41,73 @@ function setDiscovery(state, message) {
discoveryMessage.textContent = message;
}
+// --- Auto-pairing -----------------------------------------------------------
+// The desktop app opens a single-use ~120s pairing window when the user
+// clicks "Pair extension" in Settings. While this page is visible we poll
+// `GET /v1/pair` every 5 seconds so pairing completes within seconds of that
+// click (the background service worker only retries once per minute).
+const AUTOPAIR_POLL_MS = 5000;
+let pairPollTimer = null;
+
+async function onPairedSuccess() {
+ const { endpoint, token } = await loadBridgeConfig();
+ endpointInput.value = endpoint || "";
+ tokenInput.value = token || "";
+ setDiscovery("found", `Paired with OmniGet at ${endpoint}.`);
+ setStatus("Paired automatically — you're all set.", "ok");
+ stopPairPolling();
+}
+
+async function tryAutoPair() {
+ const result = await autoPair().catch(() => ({ ok: false }));
+ if (!result?.ok) return false;
+ if (result.reason === "already-paired") {
+ stopPairPolling();
+ return true;
+ }
+ await onPairedSuccess();
+ return true;
+}
+
+function startPairPolling() {
+ if (pairPollTimer !== null) return;
+ pairPollTimer = setInterval(() => {
+ void tryAutoPair();
+ }, AUTOPAIR_POLL_MS);
+}
+
+function stopPairPolling() {
+ if (pairPollTimer !== null) {
+ clearInterval(pairPollTimer);
+ pairPollTimer = null;
+ }
+}
+
+document.addEventListener("visibilitychange", () => {
+ if (document.hidden) {
+ stopPairPolling();
+ return;
+ }
+ loadBridgeConfig().then(({ token }) => {
+ if (!token) {
+ void tryAutoPair();
+ startPairPolling();
+ }
+ });
+});
+
async function init() {
const { endpoint, token } = await loadBridgeConfig();
const alreadyPaired = Boolean(token);
+ // While unpaired, keep trying to grab the token automatically: once
+ // immediately (the user may already have a pairing window open in the
+ // app) and then every few seconds while this page stays visible.
+ if (!alreadyPaired) {
+ void tryAutoPair();
+ if (!document.hidden) startPairPolling();
+ }
+
// 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) {
@@ -111,6 +176,19 @@ form.addEventListener("submit", async (event) => {
setStatus("Saved. The extension will use this token from now on.", "ok");
});
+if (pairNowBtn) {
+ pairNowBtn.addEventListener("click", async () => {
+ setStatus("Trying to pair automatically…");
+ const paired = await tryAutoPair();
+ if (paired) return;
+ setStatus(
+ "No open pairing window found. In OmniGet, go to Settings → Network → Browser extension and click \"Pair extension\", then try again (or just wait — this page keeps retrying).",
+ "error"
+ );
+ if (!document.hidden) startPairPolling();
+ });
+}
+
testBtn.addEventListener("click", async () => {
const endpoint = resolvedEndpoint();
setStatus("Testing connection…");
diff --git a/browser-extension/firefox/src/background.js b/browser-extension/firefox/src/background.js
index 5aeea7d2..d42e8bd8 100644
--- a/browser-extension/firefox/src/background.js
+++ b/browser-extension/firefox/src/background.js
@@ -6,9 +6,16 @@ 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, autoPair, loadBridgeConfig } from "./bridge-client.js";
+import {
+ sendViaBridge,
+ sendCookiesViaBridge,
+ autoPair,
+ loadBridgeConfig,
+ AUTOPAIR_ALARM_NAME,
+ STORAGE_KEY_TOKEN,
+} from "./bridge-client.js";
-const AUTOPAIR_ALARM = "omniget-autopair";
+const AUTOPAIR_ALARM = AUTOPAIR_ALARM_NAME;
async function isPaired() {
try {
@@ -56,6 +63,19 @@ if (chrome.alarms?.onAlarm) {
});
}
+// If the stored token is ever cleared (401 recovery in bridge-client.js, or
+// the user wiping it from the options page), go back to polling for a fresh
+// pairing window so the browser can re-pair without a reinstall.
+if (chrome.storage?.onChanged) {
+ chrome.storage.onChanged.addListener((changes, areaName) => {
+ if (areaName !== "local") return;
+ const change = changes?.[STORAGE_KEY_TOKEN];
+ if (!change) return;
+ const newToken = typeof change.newValue === "string" ? change.newValue.trim() : "";
+ if (!newToken) void ensureAutoPairAlarm();
+ });
+}
+
const INSTALL_URL = "https://github.com/tonhowtf/omniget/releases/latest";
const PROTOCOL_VERSION = 1;
diff --git a/browser-extension/firefox/src/bridge-client.js b/browser-extension/firefox/src/bridge-client.js
index 8584ff37..b9f21824 100644
--- a/browser-extension/firefox/src/bridge-client.js
+++ b/browser-extension/firefox/src/bridge-client.js
@@ -15,6 +15,9 @@
export const STORAGE_KEY_ENDPOINT = "bridge_endpoint";
export const STORAGE_KEY_TOKEN = "bridge_token";
+// Name of the low-frequency autopair alarm owned by background.js. Exported
+// so the 401 recovery path below can re-arm it without duplicating the name.
+export const AUTOPAIR_ALARM_NAME = "omniget-autopair";
const HEALTH_TIMEOUT_MS = 1500;
const ENQUEUE_TIMEOUT_MS = 8000;
const PROTOCOL_VERSION = 1;
@@ -64,6 +67,35 @@ export async function saveBridgeConfig(
});
}
+// Forget the stored token (keep the endpoint — it's still valid). Used when
+// the desktop app rejects our bearer, e.g. after the user rotated the token
+// in Settings; keeping the stale token around would leave this browser
+// permanently unable to re-pair.
+export async function clearStoredToken({ storage = globalThis.chrome?.storage?.local } = {}) {
+ if (!storage?.set) return false;
+ return new Promise((resolve) => {
+ storage.set({ [STORAGE_KEY_TOKEN]: "" }, () => resolve(true));
+ });
+}
+
+// 401/403 from the bridge means our token is stale (rotated or reset on the
+// desktop side). Clear it and re-arm the autopair alarm so the extension can
+// pick up a fresh token the next time the user opens a pairing window.
+async function handleUnauthorized(storage) {
+ try {
+ await clearStoredToken({ storage });
+ } catch {}
+ try {
+ const alarms = globalThis.chrome?.alarms;
+ if (alarms?.create) {
+ const existing = alarms.get ? await alarms.get(AUTOPAIR_ALARM_NAME) : null;
+ if (!existing) {
+ alarms.create(AUTOPAIR_ALARM_NAME, { periodInMinutes: 1 });
+ }
+ }
+ } catch {}
+}
+
function withTimeout(promise, ms, controller) {
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
@@ -233,6 +265,9 @@ export async function sendViaBridge(
}
if (response.status === 401 || response.status === 403) {
+ // Stale token (rotated/reset in the app) — drop it and re-arm autopair
+ // so this browser can pair again instead of being locked out forever.
+ await handleUnauthorized(storage);
return {
ok: false,
reason: "unauthorized",
@@ -321,6 +356,9 @@ export async function sendCookiesViaBridge(
}
if (response.status === 401 || response.status === 403) {
+ // Stale token (rotated/reset in the app) — drop it and re-arm autopair
+ // so this browser can pair again instead of being locked out forever.
+ await handleUnauthorized(storage);
return {
ok: false,
reason: "unauthorized",
diff --git a/src-tauri/src/local_bridge.rs b/src-tauri/src/local_bridge.rs
index d355b50e..f8ac4dbc 100644
--- a/src-tauri/src/local_bridge.rs
+++ b/src-tauri/src/local_bridge.rs
@@ -32,7 +32,7 @@ use axum::{
use base64::Engine;
use serde::{Deserialize, Serialize};
use socket2::{Domain, Protocol, Socket, Type};
-use tauri::AppHandle;
+use tauri::{AppHandle, Emitter};
use tokio::net::TcpListener;
use tower_http::cors::{Any, CorsLayer};
@@ -261,7 +261,7 @@ struct PairResponse {
token: Option<String>,
}
-async fn pair(State(state): State<BridgeState>) -> Response {
+async fn pair(State(state): State<BridgeState>, headers: HeaderMap) -> Response {
if !pairing_open() {
return (
StatusCode::FORBIDDEN,
@@ -274,6 +274,20 @@ async fn pair(State(state): State<BridgeState>) -> Response {
}
PAIR_OPEN_UNTIL_MS.store(0, Ordering::SeqCst);
tracing::info!("[bridge] pairing token handed out (window closed, single-use)");
+
+ // Tell the Settings UI that pairing actually succeeded, so it can flip
+ // from the countdown to a success state instead of silently expiring.
+ let user_agent = headers
+ .get("user-agent")
+ .and_then(|v| v.to_str().ok())
+ .map(str::to_string);
+ if let Err(error) = state.app.emit(
+ "bridge-paired",
+ serde_json::json!({ "userAgent": user_agent }),
+ ) {
+ tracing::warn!("[bridge] failed to emit bridge-paired event: {error}");
+ }
+
(
StatusCode::OK,
Json(PairResponse {
diff --git a/src/components/settings/SettingsBrowserExtension.svelte b/src/components/settings/SettingsBrowserExtension.svelte
index e7110b5f..ecc1ef70 100644
--- a/src/components/settings/SettingsBrowserExtension.svelte
+++ b/src/components/settings/SettingsBrowserExtension.svelte
@@ -1,6 +1,7 @@
<script lang="ts">
import { onMount, onDestroy } from "svelte";
import { invoke } from "@tauri-apps/api/core";
+ import { listen } from "@tauri-apps/api/event";
import { t } from "$lib/i18n";
import { showToast } from "$lib/stores/toast-store.svelte";
@@ -56,7 +57,14 @@
let pairing = $state(false);
let pairSecondsLeft = $state(0);
+ let pairResult = $state<"none" | "success" | "expired">("none");
let pairTimer: ReturnType<typeof setInterval> | null = null;
+ let unlistenPaired: (() => void) | undefined;
+
+ function stopPairTimer() {
+ if (pairTimer) clearInterval(pairTimer);
+ pairTimer = null;
+ }
async function startPairing() {
try {
@@ -68,14 +76,15 @@
return;
}
pairing = true;
+ pairResult = "none";
pairSecondsLeft = res.window_secs;
- if (pairTimer) clearInterval(pairTimer);
+ stopPairTimer();
pairTimer = setInterval(() => {
pairSecondsLeft -= 1;
if (pairSecondsLeft <= 0) {
pairing = false;
- if (pairTimer) clearInterval(pairTimer);
- pairTimer = null;
+ pairResult = "expired";
+ stopPairTimer();
}
}, 1000);
} catch (e: any) {
@@ -83,8 +92,24 @@
}
}
+ onMount(() => {
+ // The backend emits `bridge-paired` the moment the extension fetches the
+ // token from GET /v1/pair, so we can flip the countdown into a success
+ // state instead of letting it silently expire.
+ listen("bridge-paired", () => {
+ if (!pairing) return;
+ pairing = false;
+ pairResult = "success";
+ stopPairTimer();
+ showToast("success", $t("settings.bridge.pair_success") as string);
+ }).then((fn) => {
+ unlistenPaired = fn;
+ });
+ });
+
onDestroy(() => {
- if (pairTimer) clearInterval(pairTimer);
+ stopPairTimer();
+ unlistenPaired?.();
});
function maskedToken(value: string): string {
@@ -113,11 +138,21 @@
<div class="setting-row">
<div class="setting-col">
<span class="setting-label">{$t("settings.bridge.pair_label")}</span>
- <span class="setting-hint">
- {pairing
- ? $t("settings.bridge.pair_active", { secs: pairSecondsLeft })
- : $t("settings.bridge.pair_hint")}
- </span>
+ {#if pairing}
+ <span class="setting-hint">
+ {$t("settings.bridge.pair_active", { secs: pairSecondsLeft })}
+ </span>
+ {:else if pairResult === "success"}
+ <span class="setting-hint pair-success" role="status">
+ {$t("settings.bridge.pair_success")}
+ </span>
+ {:else if pairResult === "expired"}
+ <span class="setting-hint pair-expired" role="status">
+ {$t("settings.bridge.pair_expired")}
+ </span>
+ {:else}
+ <span class="setting-hint">{$t("settings.bridge.pair_hint")}</span>
+ {/if}
</div>
<button
class="bridge-action primary"
@@ -189,6 +224,12 @@
font-size: 13px;
line-height: 1.5;
}
+ .pair-success {
+ color: var(--success, #4caf50);
+ }
+ .pair-expired {
+ color: var(--warning, #e0a030);
+ }
.token-display {
font-family: var(--font-mono, "IBM Plex Mono", monospace);
word-break: break-all;