feat: add non-blocking NTCP2 sends and Firefox settings sync
check / check (macos-latest) (push) Failing after 26s
check / check (ubuntu-latest) (push) Failing after 27s
check / check (windows-latest) (push) Failing after 30s

- 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
This commit is contained in:
nandi committed 2026-11-28 18:39:32 -08:00
1 parent 82aaa9f11e
commit 9aa15f9ae8
18 files changed
+1323 -239

No files matched your search

+117 -67
View File
@@ -22,36 +22,38 @@ async function loadSettings() {
async function syncFromNativeEnv(force = false) {
const st = await nativeCommand("status");
if (st && st.appimage && (!syncedAppImageEnv || force)) {
let changed = false;
const patch = {};
if (st.env_proxy_host && st.env_proxy_host !== cachedSettings.proxyHost) {
cachedSettings.proxyHost = st.env_proxy_host;
changed = true;
patch.proxyHost = st.env_proxy_host;
}
if (st.env_proxy_port > 0 && st.env_proxy_port !== Number(cachedSettings.proxyPort)) {
cachedSettings.proxyPort = st.env_proxy_port;
changed = true;
patch.proxyPort = st.env_proxy_port;
}
if (st.env_api_host && st.env_api_host !== cachedSettings.apiHost) {
cachedSettings.apiHost = st.env_api_host;
changed = true;
patch.apiHost = st.env_api_host;
}
if (st.env_api_port > 0 && st.env_api_port !== Number(cachedSettings.apiPort)) {
cachedSettings.apiPort = st.env_api_port;
changed = true;
patch.apiPort = st.env_api_port;
}
if (st.env_download_dir && !cachedSettings.downloadDir) {
cachedSettings.downloadDir = st.env_download_dir;
changed = true;
patch.downloadDir = st.env_download_dir;
}
syncedAppImageEnv = true;
if (changed) {
await browser.storage.local.set(cachedSettings);
if (Object.keys(patch).length > 0) {
cachedSettings = { ...cachedSettings, ...patch };
await browser.storage.local.set(patch);
}
}
return st;
}
loadSettings().then(() => syncFromNativeEnv());
let startupCompleted = false;
const startupReady = loadSettings()
.then(() => syncFromNativeEnv())
.catch(() => null)
.finally(() => {
startupCompleted = true;
});
browser.storage.onChanged.addListener((changes, area) => {
if (area !== "local") return;
@@ -69,26 +71,33 @@ function isLoopbackHost(hostname) {
);
}
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) => {
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
if (!startupCompleted && !syncedAppImageEnv) {
return startupReady.then(() => resolveProxyForRequest(requestInfo));
}
return { type: "direct" };
return resolveProxyForRequest(requestInfo);
},
{ urls: ["<all_urls>"] }
);
@@ -99,26 +108,37 @@ function apiBaseUrl() {
return `http://${host}:${port}`;
}
async function apiJson(path, method = "GET", bodyObj = null) {
async function apiJson(path, method = "GET", bodyObj = null, timeoutMs = 3000) {
const headers = {};
const opts = { method, headers, cache: "no-store" };
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 || {});
}
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 };
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);
}
if (!resp.ok && data && !data.error) {
data.error = `HTTP ${resp.status}`;
}
return data;
}
function bytesToBase64(bytes) {
@@ -132,10 +152,15 @@ function bytesToBase64(bytes) {
async function addTorrentBytes(uint8Bytes) {
const b64 = bytesToBase64(uint8Bytes);
return apiJson("/api/torrents/add", "POST", {
torrent_b64: b64,
download_dir: cachedSettings.downloadDir || "",
});
return apiJson(
"/api/torrents/add",
"POST",
{
torrent_b64: b64,
download_dir: cachedSettings.downloadDir || "",
},
15000
);
}
async function addTorrentFromUrl(urlStr) {
@@ -167,9 +192,9 @@ 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: [] })),
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,
@@ -202,12 +227,22 @@ browser.downloads.onCreated.addListener(async (item) => {
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 next = { ...cachedSettings, ...(msg.settings || {}) };
await browser.storage.local.set(next);
cachedSettings = next;
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":
@@ -215,10 +250,15 @@ browser.runtime.onMessage.addListener(async (msg) => {
case "stopRouter":
return nativeCommand("stop_router");
case "addMagnet":
return apiJson("/api/torrents/magnet", "POST", {
uri: msg.uri || "",
download_dir: cachedSettings.downloadDir || "",
});
return apiJson(
"/api/torrents/magnet",
"POST",
{
uri: msg.uri || "",
download_dir: cachedSettings.downloadDir || "",
},
15000
);
case "addTorrentUrl":
try {
return await addTorrentFromUrl(msg.url);
@@ -226,21 +266,31 @@ browser.runtime.onMessage.addListener(async (msg) => {
return { ok: false, error: String(e) };
}
case "addTorrentB64":
return apiJson("/api/torrents/add", "POST", {
torrent_b64: msg.torrentB64 || "",
download_dir: cachedSettings.downloadDir || "",
});
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 });
return apiJson("/api/torrents/pause", "POST", { info_hash: msg.infoHash }, 10000);
case "resumeTorrent":
return apiJson("/api/torrents/resume", "POST", { info_hash: msg.infoHash });
return apiJson("/api/torrents/resume", "POST", { info_hash: msg.infoHash }, 10000);
case "removeTorrent":
return apiJson("/api/torrents/remove", "POST", { info_hash: msg.infoHash });
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,
});
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 });