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.

24.0 KB
Raw Blame
import { extractCookiesForPlatform } from "./cookies.js";
import { detectSupportedMediaUrl } from "./detect.js";
import { createActionFeedbackController } from "./action-feedback.js";
import { registerSnifferListeners, getMediaCount, getMediaCountForPage, getDetectedMedia, getDetectedMediaForUrl, getPageKeyForTab, recordDetectedMedia, restoreMedia } from "./media-sniffer.js";
import { summarizeCookies } from "./cookie-summary.js";
import { loadSnifferState, isSnifferEnabled, setSnifferEnabled } from "./sniffer-toggle.js";
import {
  loadDeepSearchState,
  isDeepSearchEnabled,
  isDeepSearchSupported,
  setDeepSearchEnabled,
  shouldSkipDeepSearch,
} from "./deep-search-toggle.js";
import { loadH264State, isH264Enabled, isBlock60, setH264 } from "./h264-toggle.js";
import { registerContextMenu, getContextMenuId } from "./context-menu.js";
import { loadOpenAppState, isOpenAppEnabled } from "./open-app-toggle.js";
import { openLibregetScheme } from "./send-via-scheme.js";
import { isSyntheticManifestUrl } from "./synthetic-manifest.js";
import {
  sendViaBridge,
  sendCookiesViaBridge,
  autoPair,
  loadBridgeConfig,
  loadAutoCaptureCookies,
  AUTOPAIR_ALARM_NAME,
  STORAGE_KEY_TOKEN,
} from "./bridge-client.js";

const AUTOPAIR_ALARM = AUTOPAIR_ALARM_NAME;

async function isPaired() {
  try {
    const cfg = await loadBridgeConfig();
    return Boolean(cfg.token);
  } catch {
    return false;
  }
}

// Keep a low-frequency poll alive while unpaired so that, the moment the user
// clicks "Pair extension" in the desktop app (which opens a ~120s single-use
// window), the extension grabs the token on its own — no copy-paste, no
// returning to the extension. The alarm clears itself once paired.
async function runAutoPairTick() {
  if (await isPaired()) {
    try {
      await chrome.alarms.clear(AUTOPAIR_ALARM);
    } catch {}
    return true;
  }
  const result = await autoPair().catch(() => ({ ok: false }));
  if (result?.ok) {
    try {
      await chrome.alarms.clear(AUTOPAIR_ALARM);
    } catch {}
    refreshActiveTab().catch(() => {});
    return true;
  }
  return false;
}

async function ensureAutoPairAlarm() {
  if (await isPaired()) return;
  try {
    if (!(await chrome.alarms.get(AUTOPAIR_ALARM))) {
      chrome.alarms.create(AUTOPAIR_ALARM, { periodInMinutes: 1 });
    }
  } catch {}
}

if (chrome.alarms?.onAlarm) {
  chrome.alarms.onAlarm.addListener((alarm) => {
    if (alarm?.name === AUTOPAIR_ALARM) void runAutoPairTick();
  });
}

// 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/OpenSelena/libreget/releases/latest";
const PROTOCOL_VERSION = 1;

function getIconPath(iconSet) {
  return {
    16: chrome.runtime.getURL(iconSet[16]),
    24: chrome.runtime.getURL(iconSet[24]),
    32: chrome.runtime.getURL(iconSet[32]),
    48: chrome.runtime.getURL(iconSet[48]),
  };
}

const ACTIVE_ICON_PATHS = Object.freeze({
  16: "icons/active-16.png",
  24: "icons/active-24.png",
  32: "icons/active-32.png",
  48: "icons/active-48.png",
});

const INACTIVE_ICON_PATHS = Object.freeze({
  16: "icons/inactive-16.png",
  24: "icons/inactive-24.png",
  32: "icons/inactive-32.png",
  48: "icons/inactive-48.png",
});

const actionFeedback = createActionFeedbackController({
  setBadgeText: (details) => chrome.action.setBadgeText(details),
  setBadgeBackgroundColor: (details) => chrome.action.setBadgeBackgroundColor(details),
});

// Registered unconditionally, synchronously, before anything awaits: see the
// note on registerSnifferListeners. The stored enable flag is consulted inside
// the handlers, so a disabled sniffer costs one boolean check per request.
registerSnifferListeners(onMediaDetected);

loadSnifferState().catch(() => {});
loadDeepSearchState().catch(() => {});
loadH264State().catch(() => {});
restoreMedia().catch(() => {});
registerContextMenu();

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 LibreGet 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) {
      const paired = await runAutoPairTick();
      if (!paired) {
        await ensureAutoPairAlarm();
        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(() => {});
    }
  }
});

const menusApi =
  globalThis.browser?.menus ||
  globalThis.browser?.contextMenus ||
  globalThis.chrome?.contextMenus;

if (menusApi?.onClicked) {
  menusApi.onClicked.addListener(async (info, tab) => {
    if (info.menuItemId !== getContextMenuId()) return;

    let url = info.linkUrl || info.srcUrl;
    if (!url && info.selectionText) {
      const trimmed = info.selectionText.trim();
      if (/^https?:\/\//i.test(trimmed)) {
        url = trimmed;
      }
    }
    if (!url) {
      url = info.pageUrl || tab?.url;
    }
    if (!url) return;

    const result = await handleSendToApp({
      type: "sendToLibreGet",
      url,
      platform: "generic",
      referer: tab?.url || "",
      openApp: isOpenAppEnabled(),
    });

    if (result.ok) {
      actionFeedback.showSuccessBadge(tab?.id);
    }
  });
}

chrome.runtime.onStartup.addListener(() => {
  registerContextMenu();
  loadOpenAppState().catch(() => {});
  refreshActiveTab().catch(() => {});
  void runAutoPairTick();
  void ensureAutoPairAlarm();
});

if (chrome.commands && chrome.commands.onCommand) {
  chrome.commands.onCommand.addListener(async (command) => {
    if (command !== "send-to-libreget") return;
    try {
      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
      if (!tab?.url) return;
      const detected = detectSupportedMediaUrl(tab.url);
      if (detected?.supported) {
        const result = await handleSendToApp({
          type: "sendToLibreGet",
          url: tab.url,
          platform: detected.platform,
          referer: tab.url,
          openApp: isOpenAppEnabled(),
        });
        if (result?.ok && tab.id !== undefined) {
          actionFeedback.showSuccessBadge(tab.id);
        }
        return;
      }
      if (chrome.action && typeof chrome.action.openPopup === "function") {
        try { await chrome.action.openPopup(); } catch {}
      }
    } catch (error) {
      console.error("[LibreGet] command handler failed:", error);
    }
  });
}

chrome.tabs.onActivated.addListener(() => {
  refreshActiveTab().catch(() => {});
});

chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
  if (!changeInfo.url && !changeInfo.status) {
    return;
  }
  if (!tab?.url) {
    return;
  }
  refreshTabAction(tabId, tab).catch((error) => {
    console.error("[LibreGet] Failed to refresh tab action:", error);
  });
});

chrome.windows.onFocusChanged.addListener((windowId) => {
  if (windowId !== chrome.windows.WINDOW_ID_NONE) {
    refreshActiveTab().catch(() => {});
  }
});

chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
  if (msg.type === "getDetectedMedia") {
    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
      const tabId = tabs[0]?.id;
      const pageUrl = tabs[0]?.url;
      if (!tabId) { sendResponse({ media: [], snifferEnabled: isSnifferEnabled() }); return; }

      const media = pageUrl
        ? getDetectedMediaForUrl(pageUrl)
        : getDetectedMedia(tabId);
      const list = Array.from(media.values()).sort((a, b) => b.detectedAt - a.detectedAt);

      const pageDetected = detectSupportedMediaUrl(pageUrl);

      sendResponse({
        media: list,
        pageDetected,
        snifferEnabled: isSnifferEnabled(),
        tabUrl: pageUrl,
      });
    });
    return true;
  }

  if (msg.type === "getH264") {
    sendResponse({ enabled: isH264Enabled(), block60: isBlock60() });
    return false;
  }

  if (msg.type === "toggleH264") {
    setH264(msg.enabled, msg.block60).then((r) => sendResponse(r)).catch(() => sendResponse({ enabled: isH264Enabled(), block60: isBlock60() }));
    return true;
  }

  if (msg.type === "toggleSniffer") {
    setSnifferEnabled(msg.enabled).then((result) => {
      const effective = isSnifferEnabled();
      sendResponse({
        ok: result?.ok !== false,
        enabled: effective,
        reason: result?.reason,
      });
    });
    return true;
  }

  if (msg.type === "sendToLibreGet") {
    handleSendToApp(msg).then(sendResponse);
    return true;
  }

  // Deep search runs in the page and finds playlists the network layer never
  // sees as media. The manifest text itself stays in the content script (it can
  // be hundreds of KB); we only fetch it at send time, from the tab that has it.
  if (msg.type === "deep-search-media") {
    const tabId = sender?.tab?.id;
    if (typeof tabId !== "number") return false;
    if (shouldSkipDeepSearch(msg.pageUrl)) return false;
    const entry = {
      url: msg.url,
      contentType: msg.format === "dash" ? "application/dash+xml" : "application/x-mpegurl",
      contentLength: 0,
      mediaType: msg.format === "dash" ? "dash" : "hls",
      sizeText: "",
      detectedAt: Date.now(),
      tabId,
      requestHeaders: [],
      responseHeaders: [],
      source: "deep-search",
      hasManifest: Boolean(msg.hasManifest),
      // Which frame holds the text: an iframe player keeps its own copy, and
      // asking the whole tab would take whichever frame answered first.
      frameId: typeof sender?.frameId === "number" ? sender.frameId : 0,
    };
    recordDetectedMedia(tabId, entry).then((recorded) => {
      if (recorded) onMediaDetected(tabId, entry);
    });
    return false;
  }

  if (msg.type === "getDeepSearch") {
    isDeepSearchSupported()
      .then((supported) => sendResponse({ enabled: isDeepSearchEnabled(), supported }))
      .catch(() => sendResponse({ enabled: false, supported: false }));
    return true;
  }

  if (msg.type === "toggleDeepSearch") {
    setDeepSearchEnabled(msg.enabled)
      .then((result) => sendResponse({
        ok: result?.ok !== false,
        enabled: isDeepSearchEnabled(),
        reason: result?.reason,
      }))
      .catch(() => sendResponse({ ok: false, enabled: isDeepSearchEnabled() }));
    return true;
  }
});

// The text lives in the deep-search bridge of the tab that captured it. A tab
// that has since navigated away answers nothing, which is fine: the app falls
// back to fetching the URL, and only a blob-backed playlist is truly lost.
async function fetchManifestText(tabId, frameId, url) {
  if (typeof tabId !== "number") return null;
  try {
    const options = typeof frameId === "number" ? { frameId } : undefined;
    const response = await chrome.tabs.sendMessage(tabId, { type: "getManifestText", url }, options);
    const text = response?.text;
    return typeof text === "string" && text !== "" ? text : null;
  } catch {
    return null;
  }
}

function onMediaDetected(tabId, _entry) {
  if (!isSnifferEnabled()) return;
  updateBadge(tabId);
  const pageKey = getPageKeyForTab(tabId);
  if (!pageKey) return;
  const count = getMediaCountForPage(pageKey);
  chrome.runtime.sendMessage({
    type: "media-detected",
    pageKey,
    count,
  }).catch(() => {});
}

function updateBadge(tabId) {
  const count = getMediaCount(tabId);
  chrome.action.setBadgeText({
    tabId,
    text: count > 0 ? String(count) : "",
  }).catch(() => {});
  chrome.action.setBadgeBackgroundColor({
    tabId,
    color: "#FF9F0A",
  }).catch(() => {});
}

async function handleSendToApp(msg) {
  const url = msg.url;
  const platform = msg.platform || "generic";

  let pageTitle = "";
  let pageThumbnail = "";
  try {
    const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
    pageTitle = tab?.title || "";
    pageThumbnail = tab?.favIconUrl || "";
  } catch {}

  let cookies = null;
  try {
    const platformCookies = await extractCookiesForPlatform(platform);
    if (platformCookies && platformCookies.length > 0) {
      cookies = platformCookies;
    } else {
      const cookieMap = new Map();

      const cdnCookies = await chrome.cookies.getAll({ url });
      for (const c of cdnCookies) {
        cookieMap.set(`${c.domain}:${c.name}`, c);
      }

      if (msg.referer) {
        try {
          const pageCookies = await chrome.cookies.getAll({ url: msg.referer });
          for (const c of pageCookies) {
            cookieMap.set(`${c.domain}:${c.name}`, c);
          }
        } catch {}
      }

      if (cookieMap.size > 0) {
        cookies = [...cookieMap.values()].map(c => ({
          domain: c.domain,
          httpOnly: c.httpOnly,
          path: c.path,
          secure: c.secure,
          expires: c.expirationDate ? Math.floor(c.expirationDate) : 0,
          name: c.name,
          value: c.value,
          hostOnly: c.hostOnly,
          sameSite: c.sameSite,
        }));
      }
    }
  } catch {}

  const message = { type: "enqueue", url, protocolVersion: PROTOCOL_VERSION };
  if (cookies) message.cookies = cookies;
  if (msg.referer) message.referer = msg.referer;
  if (msg.title) message.title = msg.title;
  else if (pageTitle) message.title = pageTitle;
  if (msg.thumbnail) message.thumbnail = msg.thumbnail;
  else if (pageThumbnail) message.thumbnail = pageThumbnail;
  if (msg.mediaType) message.mediaType = msg.mediaType;
  if (msg.hasManifest) {
    let tabId = msg.tabId;
    if (typeof tabId !== "number") {
      try {
        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
        tabId = tab?.id;
      } catch {}
    }
    const manifestText = await fetchManifestText(tabId, msg.frameId, url);
    if (manifestText) {
      message.manifestText = manifestText;
    } else if (isSyntheticManifestUrl(url)) {
      // The text lived in the page and the page is gone — a reload, a closed
      // tab, an evicted entry. A synthetic URL is an identity, not an address,
      // so there is nothing left to download and no fallback to try. Say so
      // instead of queueing a URL that can only fail at DNS.
      return { ok: false, reason: "manifest_gone" };
    }
  }
  if (msg.contentType) message.contentType = msg.contentType;
  if (msg.headers) message.headers = msg.headers;
  if (typeof msg.openApp === "boolean") message.openApp = msg.openApp;
  message.pageUrl = msg.referer || "";
  message.userAgent = navigator.userAgent;

  try {
    await chrome.storage.local.set({
      last_download_metadata: {
        url,
        referer: msg.referer || "",
        headers: msg.headers || {},
        cookies: cookies || [],
        userAgent: navigator.userAgent,
        timestamp: Date.now(),
      },
    }).catch(() => {});
  } catch {}

  const cookieSummary = summarizeCookies(cookies);

  // 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: libreget:// 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 openLibregetScheme(url);
  if (schemeResult?.ok) {
    return { ok: true, viaScheme: true, cookieSummary, bridgeReason: bridgeResult?.reason };
  }
  return {
    ok: false,
    error: bridgeResult?.message || schemeResult?.message || "LibreGet is not reachable",
    bridgeReason: bridgeResult?.reason,
    schemeReason: schemeResult?.reason,
  };
}

async function refreshActiveTab() {
  const [tab] = await chrome.tabs.query({
    active: true,
    lastFocusedWindow: true,
  });

  if (tab?.id !== undefined) {
    await refreshTabAction(tab.id, tab);
  }
}

async function refreshTabAction(tabId, tab) {
  if (!tab?.url) {
    return;
  }

  const detected = detectSupportedMediaUrl(tab.url);
  const supported = Boolean(detected?.supported);
  const mediaCount = getMediaCount(tabId);

  try {
    const iconSet = supported ? ACTIVE_ICON_PATHS : INACTIVE_ICON_PATHS;
    await chrome.action.setIcon({ tabId, path: getIconPath(iconSet) });
  } catch (error) {
    if (isTabGoneError(error)) return;
  }

  if (mediaCount > 0) {
    updateBadge(tabId);
  } else {
    try { await actionFeedback.clearBadge(tabId); } catch {}
  }
}

function isTabGoneError(error) {
  const msg = error instanceof Error ? error.message : String(error);
  return msg.includes("No tab with id");
}

const COOKIE_AUTO_CAPTURE_DEBOUNCE_MS = 1500;
const COOKIE_AUTO_CAPTURE_MIN_INTERVAL_MS = 60_000;
const cookieDebounceTimers = new Map();
const cookieLastSentAt = new Map();

const TRACKED_COOKIE_NAMES = new Set([
  "__Secure-3PAPISID",
  "__Secure-1PAPISID",
  "__Secure-3PSID",
  "__Secure-1PSID",
  "SAPISID",
  "SID",
  "HSID",
  "SSID",
  "APISID",
  "LOGIN_INFO",
  "VISITOR_INFO1_LIVE",
  "PREF",
  "sessionid",
  "ds_user_id",
  "ig_did",
  "auth_token",
  "ct0",
  "kp",
  "tt_webid",
  "twid",
  "loid",
  "edgebucket",
  "oauth_token",
  "sc_anonymous_id",
  "moe_uuid",
  "datadome",
  "skylab_next_access_token_v4",
  "skylab_next_refresh_token_v4",
]);

const TRACKED_DOMAIN_SUFFIXES = [
  ".youtube.com",
  ".google.com",
  ".instagram.com",
  ".tiktok.com",
  ".x.com",
  ".twitter.com",
  ".reddit.com",
  ".twitch.tv",
  ".vimeo.com",
  ".bilibili.com",
  ".pinterest.com",
  ".hotmart.com",
  ".udemy.com",
  ".rocketseat.com.br",
  ".bsky.app",
  ".bsky.social",
  ".telegram.org",
  ".soundcloud.com",
];

function platformForDomain(domain) {
  const d = (domain || "").toLowerCase();
  if (d.endsWith(".youtube.com") || d.endsWith(".google.com") || d === "youtube.com")
    return "youtube";
  if (d.endsWith(".instagram.com") || d.endsWith(".cdninstagram.com")) return "instagram";
  if (d.endsWith(".tiktok.com")) return "tiktok";
  if (d.endsWith(".x.com") || d.endsWith(".twitter.com")) return "twitter";
  if (d.endsWith(".reddit.com")) return "reddit";
  if (d.endsWith(".twitch.tv")) return "twitch";
  if (d.endsWith(".vimeo.com")) return "vimeo";
  if (d.endsWith(".bilibili.com")) return "bilibili";
  if (d.endsWith(".pinterest.com")) return "pinterest";
  if (d.endsWith(".hotmart.com")) return "hotmart";
  if (d.endsWith(".udemy.com")) return "udemy";
  if (d.endsWith(".rocketseat.com.br") || d === "rocketseat.com.br") return "rocketseat";
  if (d.endsWith(".bsky.app") || d.endsWith(".bsky.social")) return "bluesky";
  if (d.endsWith(".telegram.org")) return "telegram";
  if (d.endsWith(".soundcloud.com") || d === "soundcloud.com") return "soundcloud";
  return null;
}

function shouldTrackCookieDomain(domain) {
  if (!domain) return false;
  const d = domain.toLowerCase();
  for (const suffix of TRACKED_DOMAIN_SUFFIXES) {
    if (d === suffix.slice(1) || d.endsWith(suffix)) return true;
  }
  return false;
}

function debounceCookieCapture(platform) {
  if (cookieDebounceTimers.has(platform)) {
    clearTimeout(cookieDebounceTimers.get(platform));
  }
  const timer = setTimeout(() => {
    cookieDebounceTimers.delete(platform);
    void capturePlatformCookies(platform);
  }, COOKIE_AUTO_CAPTURE_DEBOUNCE_MS);
  cookieDebounceTimers.set(platform, timer);
}

async function capturePlatformCookies(platform, force = false) {
  if (!(await loadAutoCaptureCookies())) {
    console.debug("[LibreGet] cookie auto-capture disabled", platform);
    return { ok: false, reason: "disabled" };
  }
  const lastSent = cookieLastSentAt.get(platform) || 0;
  if (!force && Date.now() - lastSent < COOKIE_AUTO_CAPTURE_MIN_INTERVAL_MS) {
    console.debug("[LibreGet] cookie capture throttled", platform);
    return { ok: false, reason: "throttled" };
  }
  cookieLastSentAt.set(platform, Date.now());

  let cookies = null;
  try {
    cookies = await extractCookiesForPlatform(platform);
  } catch (e) {
    console.warn("[LibreGet] cookie extract failed", platform, e);
    return { ok: false, reason: "extract_failed", error: e.message };
  }
  if (!cookies || cookies.length === 0) {
    console.debug("[LibreGet] no cookies for platform", platform);
    return { ok: false, reason: "no_cookies" };
  }

  const response = await sendCookiesViaBridge(cookies);
  if (response.ok) {
    console.info("[LibreGet] cookies exported", platform, cookies.length, response);
    return { ok: true, count: cookies.length, response };
  }
  console.warn("[LibreGet] cookie export failed", platform, response.reason ?? response.message);
  return { ok: false, reason: response.reason ?? "bridge_failed", response };
}

async function scanOpenTabsForCookies() {
  if (!chrome.tabs?.query) return;
  try {
    const tabs = await chrome.tabs.query({});
    const seen = new Set();
    for (const tab of tabs) {
      if (!tab.url) continue;
      let host;
      try {
        host = new URL(tab.url).hostname;
      } catch {
        continue;
      }
      const platform = platformForDomain(host);
      if (!platform || seen.has(platform)) continue;
      seen.add(platform);
      void capturePlatformCookies(platform, true);
    }
    if (seen.size === 0) {
      console.info("[LibreGet] no tracked tabs open at extension load");
    }
  } catch (e) {
    console.warn("[LibreGet] scan tabs failed", e);
  }
}

// Scan every tracked platform — useful when the user logged into a service
// before installing the extension (no cookies.onChanged event was ever fired
// for that login, and they may not have a tab open right now).
async function scanAllPlatformsForCookies() {
  if (!chrome.cookies?.getAll) return;
  const allPlatforms = [
    "youtube",
    "instagram",
    "tiktok",
    "twitter",
    "reddit",
    "twitch",
    "vimeo",
    "bilibili",
    "soundcloud",
    "pinterest",
    "hotmart",
    "udemy",
    "rocketseat",
    "bluesky",
    "telegram",
  ];
  for (const platform of allPlatforms) {
    try {
      void capturePlatformCookies(platform, true);
    } catch (e) {
      console.warn(`[LibreGet] proactive capture ${platform} failed`, e);
    }
  }
}

scanOpenTabsForCookies();
// Also do a proactive sweep for users who logged in BEFORE installing the
// extension (cookies.onChanged never fired, no tab open) — covers SoundCloud,
// YouTube etc. when the user already had a session in their browser.
scanAllPlatformsForCookies();

if (chrome.runtime?.onStartup) {
  chrome.runtime.onStartup.addListener(() => {
    void scanOpenTabsForCookies();
    void scanAllPlatformsForCookies();
  });
}
if (chrome.runtime?.onInstalled) {
  chrome.runtime.onInstalled.addListener(() => {
    void scanAllPlatformsForCookies();
  });
}

if (chrome.cookies?.onChanged) {
  chrome.cookies.onChanged.addListener((change) => {
    const cookie = change.cookie;
    if (!cookie) return;
    if (!TRACKED_COOKIE_NAMES.has(cookie.name)) return;
    if (!shouldTrackCookieDomain(cookie.domain)) return;
    const platform = platformForDomain(cookie.domain);
    if (!platform) return;
    debounceCookieCapture(platform);
  });
}

if (chrome.tabs?.onUpdated) {
  chrome.tabs.onUpdated.addListener((_tabId, changeInfo, tab) => {
    if (changeInfo.status !== "complete") return;
    if (!tab?.url) return;
    let host;
    try {
      host = new URL(tab.url).hostname;
    } catch {
      return;
    }
    if (!shouldTrackCookieDomain(host)) return;
    const platform = platformForDomain(host);
    if (!platform) return;
    debounceCookieCapture(platform);
  });
}