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

+209 -95
View File
@@ -40,88 +40,152 @@ function bytesToBase64(bytes) {
return btoa(bin);
}
let settingsPopulated = false;
const DEFAULT_SETTINGS = {
proxyEnabled: true,
proxyHost: "127.0.0.1",
proxyPort: 4444,
apiHost: "127.0.0.1",
apiPort: 4445,
downloadDir: "",
interceptTorrents: true,
};
async function refresh() {
const st = await browser.runtime.sendMessage({ type: "getState" });
const cfg = st.settings || {};
const rs = st.routerStatus || {};
const ns = st.nativeStatus || {};
const dht = st.dht || {};
let currentSettings = { ...DEFAULT_SETTINGS };
const dirtyFields = new Set();
let refreshInFlight = false;
let refreshPending = false;
let initialSettingsPromise = null;
$("proxy-enabled").checked = !!cfg.proxyEnabled;
$("proxy-addr").textContent = `${cfg.proxyHost || "127.0.0.1"}:${cfg.proxyPort || 4444}`;
if (!settingsPopulated) {
settingsPopulated = true;
$("cfg-proxy-port").value = cfg.proxyPort || 4444;
$("cfg-api-port").value = cfg.apiPort || 4445;
$("cfg-dl-dir").value = cfg.downloadDir || "";
$("cfg-intercept").checked = !!cfg.interceptTorrents;
function parsePort(raw, fallback) {
const s = String(raw ?? "").trim();
if (!s) return fallback;
const n = Number(s);
if (Number.isInteger(n) && n >= 1 && n <= 65535) {
return n;
}
return fallback;
}
const pill = $("router-pill");
const startBtn = $("start-router-btn");
const stopBtn = $("stop-router-btn");
if (rs.ok) {
pill.textContent = rs.public_mode ? "Public Online" : "Online";
pill.className = "pill online";
startBtn.style.display = "none";
stopBtn.style.display = ns.managed_running ? "" : "none";
$("net-summary").textContent = `${rs.netdb_routers || 0} peers · ${rs.inbound_tunnels || 0}in/${rs.outbound_tunnels || 0}out`;
$("torrent-b32").textContent = rs.torrent_b32 || "--";
const d = rs.dht || {};
$("dht-summary").textContent = `${d.routing_table_nodes || 0} nodes (UDP-over-I2CP ${d.query_port || 6881}/${d.reply_port || 6882})`;
$("dht-node-id").textContent = d.node_id_hex || "--";
$("dht-stats").textContent = `${d.queries_sent || 0} / ${d.responses_recv || 0} / ${d.peers_discovered || 0}`;
} else {
pill.textContent = "Offline";
pill.className = "pill offline";
startBtn.style.display = "";
stopBtn.style.display = "none";
$("net-summary").textContent = "Router unreachable";
$("torrent-b32").textContent = "--";
function applySettingsToUi(cfg) {
currentSettings = { ...currentSettings, ...(cfg || {}) };
$("proxy-enabled").checked = !!currentSettings.proxyEnabled;
$("proxy-addr").textContent = `${currentSettings.proxyHost || "127.0.0.1"}:${currentSettings.proxyPort || 4444}`;
if (!dirtyFields.has("proxyPort")) {
$("cfg-proxy-port").value = currentSettings.proxyPort || 4444;
}
const nodesEl = $("dht-nodes-list");
if (nodesEl) {
const nodes = dht.nodes || [];
nodesEl.innerHTML =
nodes.length === 0
? "<span class='stat-label'>No DHT nodes yet. Bootstrap above or connect to a peer.</span>"
: nodes
.map(
(n) =>
`<div class="node-row">${escapeHtml(n.b32)}:${n.port} (${escapeHtml((n.node_id_hex || "").slice(0, 12))}...)</div>`
)
.join("");
if (!dirtyFields.has("apiPort")) {
$("cfg-api-port").value = currentSettings.apiPort || 4445;
}
if (!dirtyFields.has("downloadDir")) {
$("cfg-dl-dir").value = currentSettings.downloadDir || "";
}
if (!dirtyFields.has("interceptTorrents")) {
$("cfg-intercept").checked = !!currentSettings.interceptTorrents;
}
}
const list = st.torrents || [];
$("torrent-count").textContent = String(list.length);
const tEl = $("torrents-list");
if (list.length === 0) {
tEl.innerHTML = "<div class='stat-label'>No active torrents. Paste a magnet link or drop a .torrent file above.</div>";
} else {
tEl.innerHTML = list
.map((t) => {
const pct = Number(t.progress_pct || 0);
const toggleLabel = t.paused ? "Resume" : "Pause";
const toggleType = t.paused ? "resumeTorrent" : "pauseTorrent";
const infTxt = t.inflight_blocks > 0 ? ` (+${t.inflight_blocks} blks)` : "";
const trackerHtml = t.last_tracker_status
? `<div style="color:var(--muted);font-size:11px;">Tracker: ${escapeHtml(t.last_tracker_status)}</div>`
: "";
const peers = Array.isArray(t.peers) ? t.peers : [];
const peersHtml = peers.length
? `<div style="color:var(--muted);font-size:11px;font-family:monospace;line-height:1.4;">${peers
async function loadSettingsFast() {
let cfg = null;
try {
if (browser.storage && browser.storage.local) {
cfg = await browser.storage.local.get(DEFAULT_SETTINGS);
} else {
const res = await browser.runtime.sendMessage({ type: "getSettings" });
cfg = res && res.settings ? res.settings : null;
}
} catch (_e) {
try {
const res = await browser.runtime.sendMessage({ type: "getSettings" });
cfg = res && res.settings ? res.settings : null;
} catch (_e2) {
cfg = null;
}
}
if (cfg) {
applySettingsToUi(cfg);
}
}
async function refresh(force = false) {
if (refreshInFlight) {
if (force) {
refreshPending = true;
}
return;
}
refreshInFlight = true;
try {
const st = await browser.runtime.sendMessage({ type: "getState" });
if (!st) return;
const cfg = st.settings || {};
const rs = st.routerStatus || {};
const ns = st.nativeStatus || {};
const dht = st.dht || {};
applySettingsToUi(cfg);
const pill = $("router-pill");
const startBtn = $("start-router-btn");
const stopBtn = $("stop-router-btn");
if (rs.ok) {
pill.textContent = rs.public_mode ? "Public Online" : "Online";
pill.className = "pill online";
startBtn.style.display = "none";
stopBtn.style.display = ns.managed_running ? "" : "none";
$("net-summary").textContent = `${rs.netdb_routers || 0} peers · ${rs.inbound_tunnels || 0}in/${rs.outbound_tunnels || 0}out`;
$("torrent-b32").textContent = rs.torrent_b32 || "--";
const d = rs.dht || {};
$("dht-summary").textContent = `${d.routing_table_nodes || 0} nodes (UDP-over-I2CP ${d.query_port || 6881}/${d.reply_port || 6882})`;
$("dht-node-id").textContent = d.node_id_hex || "--";
$("dht-stats").textContent = `${d.queries_sent || 0} / ${d.responses_recv || 0} / ${d.peers_discovered || 0}`;
} else {
pill.textContent = "Offline";
pill.className = "pill offline";
startBtn.style.display = "";
stopBtn.style.display = "none";
$("net-summary").textContent = "Router unreachable";
$("torrent-b32").textContent = "--";
}
const nodesEl = $("dht-nodes-list");
if (nodesEl) {
const nodes = dht.nodes || [];
nodesEl.innerHTML =
nodes.length === 0
? "<span class='stat-label'>No DHT nodes yet. Bootstrap above or connect to a peer.</span>"
: nodes
.map(
(p) =>
`<div>peer ${escapeHtml(p.b32)}${p.client ? ` [${escapeHtml(p.client)}]` : ""} · st=${escapeHtml(String(p.state ?? ""))} ${p.choking ? "choked" : "unchoked"} · ${p.pieces || 0} pcs · inf=${p.in_flight || 0} · blks=${p.blocks_recv || 0}</div>`
(n) =>
`<div class="node-row">${escapeHtml(n.b32)}:${n.port} (${escapeHtml((n.node_id_hex || "").slice(0, 12))}...)</div>`
)
.join("")}</div>`
: "";
return `
.join("");
}
const list = st.torrents || [];
$("torrent-count").textContent = String(list.length);
const tEl = $("torrents-list");
if (list.length === 0) {
tEl.innerHTML = "<div class='stat-label'>No active torrents. Paste a magnet link or drop a .torrent file above.</div>";
} else {
tEl.innerHTML = list
.map((t) => {
const pct = Number(t.progress_pct || 0);
const toggleLabel = t.paused ? "Resume" : "Pause";
const toggleType = t.paused ? "resumeTorrent" : "pauseTorrent";
const infTxt = t.inflight_blocks > 0 ? ` (+${t.inflight_blocks} blks)` : "";
const trackerHtml = t.last_tracker_status
? `<div style="color:var(--muted);font-size:11px;">Tracker: ${escapeHtml(t.last_tracker_status)}</div>`
: "";
const peers = Array.isArray(t.peers) ? t.peers : [];
const peersHtml = peers.length
? `<div style="color:var(--muted);font-size:11px;font-family:monospace;line-height:1.4;">${peers
.map(
(p) =>
`<div>peer ${escapeHtml(p.b32)}${p.client ? ` [${escapeHtml(p.client)}]` : ""} · st=${escapeHtml(String(p.state ?? ""))} ${p.choking ? "choked" : "unchoked"} · ${p.pieces || 0} pcs · inf=${p.in_flight || 0} · blks=${p.blocks_recv || 0}</div>`
)
.join("")}</div>`
: "";
return `
<div class="torrent-item" data-ih="${escapeHtml(t.info_hash)}">
<div class="row" style="justify-content:space-between;">
<strong>${escapeHtml(t.name)}</strong>
@@ -140,12 +204,45 @@ async function refresh() {
${t.error ? `<div class="msg err">${escapeHtml(t.error)}</div>` : ""}
</div>
`;
})
.join("");
})
.join("");
}
} catch (_e) {
// Ignore transient runtime errors during refresh
} finally {
refreshInFlight = false;
if (refreshPending) {
refreshPending = false;
refresh(false);
}
}
}
document.addEventListener("DOMContentLoaded", () => {
for (const [id, field] of [
["cfg-proxy-port", "proxyPort"],
["cfg-api-port", "apiPort"],
["cfg-dl-dir", "downloadDir"],
["cfg-intercept", "interceptTorrents"],
]) {
const el = $(id);
if (el) {
el.addEventListener("input", () => dirtyFields.add(field));
el.addEventListener("change", () => dirtyFields.add(field));
}
}
if (browser.storage && browser.storage.onChanged) {
browser.storage.onChanged.addListener((changes, area) => {
if (area !== "local") return;
const patch = {};
for (const [key, val] of Object.entries(changes)) {
patch[key] = val.newValue;
}
applySettingsToUi(patch);
});
}
if ($("open-manager-btn")) {
$("open-manager-btn").addEventListener("click", () =>
browser.runtime.sendMessage({ type: "openManager" })
@@ -157,7 +254,7 @@ document.addEventListener("DOMContentLoaded", () => {
type: "saveSettings",
settings: { proxyEnabled: e.target.checked },
});
refresh();
refresh(true);
});
$("start-router-btn").addEventListener("click", async () => {
@@ -168,13 +265,13 @@ document.addEventListener("DOMContentLoaded", () => {
} else {
setMsg(`Failed to start router: ${(res && res.error) || "run just extension"}`, true);
}
setTimeout(refresh, 700);
setTimeout(() => refresh(true), 700);
});
$("stop-router-btn").addEventListener("click", async () => {
await browser.runtime.sendMessage({ type: "stopRouter" });
setMsg("Stopped router.");
setTimeout(refresh, 400);
setTimeout(() => refresh(true), 400);
});
$("bootstrap-form").addEventListener("submit", async (e) => {
@@ -184,7 +281,7 @@ document.addEventListener("DOMContentLoaded", () => {
if (!b32) return;
const res = await browser.runtime.sendMessage({ type: "bootstrapDht", b32, port });
setMsg(res && res.ok ? `Sent DHT ping to ${res.b32}:${res.port}` : `DHT error: ${res?.error || "failed"}`, !res?.ok);
refresh();
refresh(true);
});
$("magnet-form").addEventListener("submit", async (e) => {
@@ -198,7 +295,7 @@ document.addEventListener("DOMContentLoaded", () => {
} else {
setMsg(`Magnet failed: ${res?.error || "router offline"}`, true);
}
refresh();
refresh(true);
});
const dz = $("dropzone");
@@ -211,7 +308,7 @@ document.addEventListener("DOMContentLoaded", () => {
torrentB64: bytesToBase64(buf),
});
setMsg(res && res.ok ? `Added ${file.name} (${res.info_hash.slice(0, 12)}...)` : `Add failed: ${res?.error}`, !res?.ok);
refresh();
refresh(true);
};
dz.addEventListener("click", () => fileIn.click());
fileIn.addEventListener("change", () => handleFile(fileIn.files[0]));
@@ -233,24 +330,41 @@ document.addEventListener("DOMContentLoaded", () => {
type: btn.dataset.act,
infoHash: btn.dataset.ih,
});
refresh();
refresh(true);
});
$("settings-form").addEventListener("submit", async (e) => {
e.preventDefault();
await browser.runtime.sendMessage({
type: "saveSettings",
settings: {
proxyPort: Number($("cfg-proxy-port").value) || 4444,
apiPort: Number($("cfg-api-port").value) || 4445,
downloadDir: $("cfg-dl-dir").value.trim(),
interceptTorrents: $("cfg-intercept").checked,
},
});
setMsg("Settings saved.");
refresh();
if (initialSettingsPromise) {
await initialSettingsPromise;
}
const nextSettings = {
proxyPort: dirtyFields.has("proxyPort")
? parsePort($("cfg-proxy-port").value, currentSettings.proxyPort || 4444)
: (currentSettings.proxyPort || 4444),
apiPort: dirtyFields.has("apiPort")
? parsePort($("cfg-api-port").value, currentSettings.apiPort || 4445)
: (currentSettings.apiPort || 4445),
downloadDir: dirtyFields.has("downloadDir")
? $("cfg-dl-dir").value.trim()
: (currentSettings.downloadDir || ""),
interceptTorrents: $("cfg-intercept").checked,
};
try {
const res = await browser.runtime.sendMessage({
type: "saveSettings",
settings: nextSettings,
});
dirtyFields.clear();
applySettingsToUi((res && res.settings) || nextSettings);
setMsg("Settings saved.");
refresh(true);
} catch (err) {
setMsg(`Failed to save settings: ${err}`, true);
}
});
refresh();
setInterval(refresh, 2000);
initialSettingsPromise = loadSettingsFast();
refresh(false);
setInterval(() => refresh(false), 2000);
});