"use strict"; const DEFAULT_SETTINGS = { proxyEnabled: true, proxyHost: "127.0.0.1", proxyPort: 4444, apiHost: "127.0.0.1", apiPort: 4445, downloadDir: "", interceptTorrents: true, }; let cachedSettings = { ...DEFAULT_SETTINGS }; let syncedAppImageEnv = false; async function loadSettings() { const stored = await browser.storage.local.get(DEFAULT_SETTINGS); cachedSettings = { ...DEFAULT_SETTINGS, ...stored }; return cachedSettings; } async function syncFromNativeEnv(force = false) { const st = await nativeCommand("status"); if (st && st.appimage && (!syncedAppImageEnv || force)) { let changed = false; if (st.env_proxy_host && st.env_proxy_host !== cachedSettings.proxyHost) { cachedSettings.proxyHost = st.env_proxy_host; changed = true; } if (st.env_proxy_port > 0 && st.env_proxy_port !== Number(cachedSettings.proxyPort)) { cachedSettings.proxyPort = st.env_proxy_port; changed = true; } if (st.env_api_host && st.env_api_host !== cachedSettings.apiHost) { cachedSettings.apiHost = st.env_api_host; changed = true; } if (st.env_api_port > 0 && st.env_api_port !== Number(cachedSettings.apiPort)) { cachedSettings.apiPort = st.env_api_port; changed = true; } if (st.env_download_dir && !cachedSettings.downloadDir) { cachedSettings.downloadDir = st.env_download_dir; changed = true; } syncedAppImageEnv = true; if (changed) { await browser.storage.local.set(cachedSettings); } } return st; } loadSettings().then(() => syncFromNativeEnv()); browser.storage.onChanged.addListener((changes, area) => { if (area !== "local") return; for (const [key, val] of Object.entries(changes)) { cachedSettings[key] = val.newValue; } }); function isLoopbackHost(hostname) { return ( hostname === "127.0.0.1" || hostname === "localhost" || hostname === "::1" || hostname === "[::1]" ); } // Route *.i2p URLs through moon-i2p HTTP proxy; never proxy loopback API calls. browser.proxy.onRequest.addListener( (requestInfo) => { try { const url = new URL(requestInfo.url); const host = url.hostname.toLowerCase(); if (isLoopbackHost(host)) { return { type: "direct" }; } if (cachedSettings.proxyEnabled && host.endsWith(".i2p")) { return { type: "http", host: cachedSettings.proxyHost || "127.0.0.1", port: Number(cachedSettings.proxyPort) || 4444, }; } } catch (_e) { // Fall through to direct } return { type: "direct" }; }, { urls: [""] } ); function apiBaseUrl() { const host = cachedSettings.apiHost || "127.0.0.1"; const port = Number(cachedSettings.apiPort) || 4445; return `http://${host}:${port}`; } async function apiJson(path, method = "GET", bodyObj = null) { const headers = {}; const opts = { method, headers, cache: "no-store" }; if (method === "POST") { headers["X-Moon-I2P"] = "1"; headers["Content-Type"] = "application/json"; opts.body = JSON.stringify(bodyObj || {}); } const resp = await fetch(`${apiBaseUrl()}${path}`, opts); const text = await resp.text(); let data = null; try { data = JSON.parse(text); } catch (_e) { data = { ok: resp.ok, raw: text }; } if (!resp.ok && data && !data.error) { data.error = `HTTP ${resp.status}`; } return data; } function bytesToBase64(bytes) { let bin = ""; const chunk = 0x8000; for (let i = 0; i < bytes.length; i += chunk) { bin += String.fromCharCode(...bytes.subarray(i, i + chunk)); } return btoa(bin); } async function addTorrentBytes(uint8Bytes) { const b64 = bytesToBase64(uint8Bytes); return apiJson("/api/torrents/add", "POST", { torrent_b64: b64, download_dir: cachedSettings.downloadDir || "", }); } async function addTorrentFromUrl(urlStr) { const resp = await fetch(urlStr, { cache: "no-store" }); if (!resp.ok) { throw new Error(`Failed to fetch .torrent (${resp.status})`); } const buf = await resp.arrayBuffer(); return addTorrentBytes(new Uint8Array(buf)); } async function nativeCommand(cmd, extra = {}) { try { return await browser.runtime.sendNativeMessage("moon_i2p_torrent", { cmd, proxy_host: cachedSettings.proxyHost || "127.0.0.1", proxy_port: Number(cachedSettings.proxyPort) || 4444, api_host: cachedSettings.apiHost || "127.0.0.1", api_port: Number(cachedSettings.apiPort) || 4445, download_dir: cachedSettings.downloadDir || "", ...extra, }); } catch (err) { return { ok: false, available: false, error: String(err) }; } } async function gatherFullState() { await loadSettings(); const nativeStatus = await syncFromNativeEnv(); const [routerStatus, torrents, dht] = await Promise.all([ apiJson("/api/status").catch((e) => ({ ok: false, error: String(e) })), apiJson("/api/torrents").catch(() => ({ ok: false, torrents: [] })), apiJson("/api/dht/nodes").catch(() => ({ ok: false, nodes: [] })), ]); return { settings: cachedSettings, nativeStatus, routerStatus, torrents: torrents.torrents || [], dht, }; } // Intercept completed/started .torrent downloads from .i2p when enabled. browser.downloads.onCreated.addListener(async (item) => { try { if (!cachedSettings.interceptTorrents || !item.url) return; const u = new URL(item.url); if (!u.hostname.toLowerCase().endsWith(".i2p")) return; if ( u.pathname.toLowerCase().endsWith(".torrent") || (item.mime && item.mime.includes("bittorrent")) ) { await browser.downloads.cancel(item.id).catch(() => {}); await browser.downloads.erase({ id: item.id }).catch(() => {}); await addTorrentFromUrl(item.url); } } catch (_e) { // Ignore cancellation failures on fast transfers } }); browser.runtime.onMessage.addListener(async (msg) => { await loadSettings(); switch (msg?.type) { case "getState": return gatherFullState(); case "saveSettings": { const next = { ...cachedSettings, ...(msg.settings || {}) }; await browser.storage.local.set(next); cachedSettings = next; return { ok: true, settings: cachedSettings }; } case "startRouter": return nativeCommand("start_router"); case "stopRouter": return nativeCommand("stop_router"); case "addMagnet": return apiJson("/api/torrents/magnet", "POST", { uri: msg.uri || "", download_dir: cachedSettings.downloadDir || "", }); case "addTorrentUrl": try { return await addTorrentFromUrl(msg.url); } catch (e) { return { ok: false, error: String(e) }; } case "addTorrentB64": return apiJson("/api/torrents/add", "POST", { torrent_b64: msg.torrentB64 || "", download_dir: cachedSettings.downloadDir || "", }); case "pauseTorrent": return apiJson("/api/torrents/pause", "POST", { info_hash: msg.infoHash }); case "resumeTorrent": return apiJson("/api/torrents/resume", "POST", { info_hash: msg.infoHash }); case "removeTorrent": return apiJson("/api/torrents/remove", "POST", { info_hash: msg.infoHash }); case "bootstrapDht": return apiJson("/api/dht/bootstrap", "POST", { b32: msg.b32 || "", port: Number(msg.port) || 6881, }); case "openManager": { const url = browser.runtime.getURL("manager.html"); const existing = await browser.tabs.query({ url }); if (existing.length > 0) { await browser.tabs.update(existing[0].id, { active: true }); } else { await browser.tabs.create({ url }); } return { ok: true }; } default: return { ok: false, error: "unknown message type" }; } });