Files
moon-i2p/extensions/firefox-i2p-torrent/background.js
T
nandi 9aa15f9ae8
check / check (macos-latest) (push) Failing after 26s
check / check (ubuntu-latest) (push) Failing after 27s
check / check (windows-latest) (push) Failing after 30s
feat: add non-blocking NTCP2 sends and Firefox settings sync
- NTCP2: queue outbound data frames and flush them without blocking (send_blocks_nb, send_i2np_nb, flush_nonblocking)
- NTCP2: bound write_all with a deadline and set TCP keepalive and user timeout on peer sockets
- Firefox extension 0.1.3: save settings as a patch, keep unsaved form fields from being overwritten on refresh, add timeouts to router API calls, and honor the interceptTorrents toggle in the content script
2026-11-28 18:39:32 -08:00

308 lines
8.8 KiB
JavaScript

"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)) {
const patch = {};
if (st.env_proxy_host && st.env_proxy_host !== cachedSettings.proxyHost) {
patch.proxyHost = st.env_proxy_host;
}
if (st.env_proxy_port > 0 && st.env_proxy_port !== Number(cachedSettings.proxyPort)) {
patch.proxyPort = st.env_proxy_port;
}
if (st.env_api_host && st.env_api_host !== cachedSettings.apiHost) {
patch.apiHost = st.env_api_host;
}
if (st.env_api_port > 0 && st.env_api_port !== Number(cachedSettings.apiPort)) {
patch.apiPort = st.env_api_port;
}
if (st.env_download_dir && !cachedSettings.downloadDir) {
patch.downloadDir = st.env_download_dir;
}
syncedAppImageEnv = true;
if (Object.keys(patch).length > 0) {
cachedSettings = { ...cachedSettings, ...patch };
await browser.storage.local.set(patch);
}
}
return st;
}
let startupCompleted = false;
const startupReady = loadSettings()
.then(() => syncFromNativeEnv())
.catch(() => null)
.finally(() => {
startupCompleted = true;
});
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]"
);
}
function resolveProxyForRequest(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" };
}
// Route *.i2p URLs through moon-i2p HTTP proxy; never proxy loopback API calls.
browser.proxy.onRequest.addListener(
(requestInfo) => {
if (!startupCompleted && !syncedAppImageEnv) {
return startupReady.then(() => resolveProxyForRequest(requestInfo));
}
return resolveProxyForRequest(requestInfo);
},
{ urls: ["<all_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, timeoutMs = 3000) {
const headers = {};
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), timeoutMs);
const opts = { method, headers, cache: "no-store", signal: controller.signal };
if (method === "POST") {
headers["X-Moon-I2P"] = "1";
headers["Content-Type"] = "application/json";
opts.body = JSON.stringify(bodyObj || {});
}
try {
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;
} catch (err) {
if (err && err.name === "AbortError") {
throw new Error(`Router API timeout (${timeoutMs}ms)`);
}
throw err;
} finally {
clearTimeout(timer);
}
}
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 || "",
},
15000
);
}
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", "GET", null, 2500).catch((e) => ({ ok: false, error: String(e) })),
apiJson("/api/torrents", "GET", null, 2500).catch(() => ({ ok: false, torrents: [] })),
apiJson("/api/dht/nodes", "GET", null, 2500).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 "getSettings":
return { ok: true, settings: cachedSettings };
case "getState":
return gatherFullState();
case "saveSettings": {
const incoming = msg.settings || {};
const patch = {};
for (const key of Object.keys(DEFAULT_SETTINGS)) {
if (incoming[key] !== undefined) {
patch[key] = incoming[key];
}
}
if (Object.keys(patch).length > 0) {
await browser.storage.local.set(patch);
cachedSettings = { ...cachedSettings, ...patch };
}
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 || "",
},
15000
);
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 || "",
},
15000
);
case "pauseTorrent":
return apiJson("/api/torrents/pause", "POST", { info_hash: msg.infoHash }, 10000);
case "resumeTorrent":
return apiJson("/api/torrents/resume", "POST", { info_hash: msg.infoHash }, 10000);
case "removeTorrent":
return apiJson("/api/torrents/remove", "POST", { info_hash: msg.infoHash }, 10000);
case "bootstrapDht":
return apiJson(
"/api/dht/bootstrap",
"POST",
{
b32: msg.b32 || "",
port: Number(msg.port) || 6881,
},
10000
);
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" };
}
});