Files
nandi 4bb81f1b80
check / check (macos-latest) (push) Failing after 26s
check / check (windows-latest) (push) Failing after 26s
check / check (ubuntu-latest) (push) Failing after 29s
feat: add diagnostics report to Firefox torrent extension
- Add a Diagnostics panel to the extension popup and manager page with copy and refresh actions
- Collect extension settings, router API status, torrents, DHT nodes, and a tail of the router log into one report
- Add a native host `diagnostics` command that reports router PID, active ports, log path, and log summary counters
- Export data dir, log file, router PID, and SAM port from the AppImage launcher
- Start the router with `--debug` so the log tail has detailed output
- Bump extension version to 0.1.4 and request clipboardWrite permission
2026-11-28 19:28:39 -08:00

516 lines
17 KiB
JavaScript

"use strict";
const $ = (id) => document.getElementById(id);
function fmtBytes(n) {
if (!n || n <= 0) return "0 B";
const units = ["B", "KiB", "MiB", "GiB"];
let u = 0;
let v = n;
while (v >= 1024 && u < units.length - 1) {
v /= 1024;
u++;
}
return `${v.toFixed(u === 0 ? 0 : 1)} ${units[u]}`;
}
function setMsg(text, isErr = false) {
const el = $("status-msg");
if (!el) return;
el.textContent = text;
el.className = isErr ? "msg err" : "msg";
}
function escapeHtml(s) {
return String(s || "").replace(/[&<>"']/g, (c) => ({
"&": "&amp;",
"<": "&lt;",
">": "&gt;",
'"': "&quot;",
"'": "&#39;",
})[c]);
}
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);
}
const DEFAULT_SETTINGS = {
proxyEnabled: true,
proxyHost: "127.0.0.1",
proxyPort: 4444,
apiHost: "127.0.0.1",
apiPort: 4445,
downloadDir: "",
interceptTorrents: true,
};
let currentSettings = { ...DEFAULT_SETTINGS };
const dirtyFields = new Set();
let refreshInFlight = false;
let refreshPending = false;
let initialSettingsPromise = null;
let latestDiagnosticsReport = "";
let diagInFlight = false;
let diagPromise = null;
let copyBtnTimer = null;
function setDiagMsg(text, isErr = false) {
const el = $("diag-status");
if (!el) return;
el.textContent = text;
el.className = isErr ? "msg err" : "msg";
}
async function copyTextToClipboard(text) {
if (navigator.clipboard && navigator.clipboard.writeText) {
try {
await navigator.clipboard.writeText(text);
return true;
} catch (_e) {
// Fall through to textarea + execCommand fallback
}
}
const ta = document.createElement("textarea");
ta.value = text;
ta.setAttribute("readonly", "");
ta.style.position = "fixed";
ta.style.top = "-9999px";
ta.style.left = "-9999px";
document.body.appendChild(ta);
ta.select();
let ok = false;
try {
ok = document.execCommand("copy");
} finally {
document.body.removeChild(ta);
}
return ok;
}
async function loadDiagnostics(showStatus = false) {
const logEl = $("diagnostics-log");
if (!logEl) return latestDiagnosticsReport;
if (diagInFlight && diagPromise) {
return diagPromise;
}
diagInFlight = true;
if (showStatus) {
setDiagMsg("Collecting diagnostics...");
}
diagPromise = (async () => {
try {
const res = await browser.runtime.sendMessage({ type: "getDiagnostics" });
if (res && res.ok && res.report) {
latestDiagnosticsReport = res.report;
logEl.textContent = res.report;
if (showStatus) {
const meta = res.meta || {};
if (!meta.nativeAvailable) {
setDiagMsg(
`Diagnostics refreshed (native host unavailable: ${meta.nativeError || "log tail skipped"}).`,
true
);
} else if (meta.logPath) {
setDiagMsg(`Diagnostics refreshed (${meta.logPath}).`);
} else {
setDiagMsg("Diagnostics refreshed.");
}
} else {
setDiagMsg("");
}
return res.report;
}
const errMsg = (res && res.error) || "failed to collect diagnostics";
if (!latestDiagnosticsReport) {
logEl.textContent = `Error loading diagnostics: ${errMsg}`;
}
setDiagMsg(`Diagnostics failed: ${errMsg}`, true);
return latestDiagnosticsReport;
} catch (err) {
if (!latestDiagnosticsReport) {
logEl.textContent = `Error loading diagnostics: ${err}`;
}
setDiagMsg(`Diagnostics failed: ${err}`, true);
return latestDiagnosticsReport;
} finally {
diagInFlight = false;
diagPromise = null;
}
})();
return diagPromise;
}
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;
}
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;
}
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;
}
}
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(
(n) =>
`<div class="node-row">${escapeHtml(n.b32)}:${n.port} (${escapeHtml((n.node_id_hex || "").slice(0, 12))}...)</div>`
)
.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>
<span class="pill ${t.completed ? "online" : ""}">${escapeHtml(t.state)} · ${pct}%</span>
</div>
<div class="progress-track"><div class="progress-fill" style="width:${pct}%"></div></div>
<div class="row" style="justify-content:space-between;color:var(--muted);font-size:11px;">
<span>${fmtBytes(t.downloaded_bytes)} / ${fmtBytes(t.total_length)} · ${t.have_pieces}/${t.num_pieces} pcs${infTxt} · ${t.connected_peers}/${t.known_peers} peers (${t.unchoked_peers || 0} unchoked)</span>
<span class="row">
<button class="secondary act-btn" data-act="${toggleType}" data-ih="${escapeHtml(t.info_hash)}">${toggleLabel}</button>
<button class="danger act-btn" data-act="removeTorrent" data-ih="${escapeHtml(t.info_hash)}">Remove</button>
</span>
</div>
${trackerHtml}
${peersHtml}
${t.error ? `<div class="msg err">${escapeHtml(t.error)}</div>` : ""}
</div>
`;
})
.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" })
);
}
$("proxy-enabled").addEventListener("change", async (e) => {
await browser.runtime.sendMessage({
type: "saveSettings",
settings: { proxyEnabled: e.target.checked },
});
refresh(true);
});
$("start-router-btn").addEventListener("click", async () => {
setMsg("Starting moon-i2p router via native host...");
const res = await browser.runtime.sendMessage({ type: "startRouter" });
if (res && res.ok) {
setMsg("Router starting (waiting for API & tunnels)...");
} else {
setMsg(`Failed to start router: ${(res && res.error) || "run just extension"}`, true);
}
setTimeout(() => refresh(true), 700);
});
$("stop-router-btn").addEventListener("click", async () => {
await browser.runtime.sendMessage({ type: "stopRouter" });
setMsg("Stopped router.");
setTimeout(() => refresh(true), 400);
});
$("bootstrap-form").addEventListener("submit", async (e) => {
e.preventDefault();
const b32 = $("bootstrap-b32").value.trim();
const port = Number($("bootstrap-port").value) || 6881;
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(true);
});
$("magnet-form").addEventListener("submit", async (e) => {
e.preventDefault();
const uri = $("magnet-uri").value.trim();
if (!uri) return;
const res = await browser.runtime.sendMessage({ type: "addMagnet", uri });
if (res && res.ok) {
$("magnet-uri").value = "";
setMsg(`Added magnet ${res.info_hash.slice(0, 12)}...`);
} else {
setMsg(`Magnet failed: ${res?.error || "router offline"}`, true);
}
refresh(true);
});
const dz = $("dropzone");
const fileIn = $("torrent-file");
const handleFile = async (file) => {
if (!file) return;
const buf = new Uint8Array(await file.arrayBuffer());
const res = await browser.runtime.sendMessage({
type: "addTorrentB64",
torrentB64: bytesToBase64(buf),
});
setMsg(res && res.ok ? `Added ${file.name} (${res.info_hash.slice(0, 12)}...)` : `Add failed: ${res?.error}`, !res?.ok);
refresh(true);
};
dz.addEventListener("click", () => fileIn.click());
fileIn.addEventListener("change", () => handleFile(fileIn.files[0]));
dz.addEventListener("dragover", (e) => {
e.preventDefault();
dz.classList.add("drag");
});
dz.addEventListener("dragleave", () => dz.classList.remove("drag"));
dz.addEventListener("drop", (e) => {
e.preventDefault();
dz.classList.remove("drag");
handleFile(e.dataTransfer.files[0]);
});
$("torrents-list").addEventListener("click", async (e) => {
const btn = e.target.closest(".act-btn");
if (!btn) return;
await browser.runtime.sendMessage({
type: btn.dataset.act,
infoHash: btn.dataset.ih,
});
refresh(true);
});
$("settings-form").addEventListener("submit", async (e) => {
e.preventDefault();
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);
}
});
const headerDiagBtn = $("header-diag-btn");
if (headerDiagBtn) {
headerDiagBtn.addEventListener("click", () => {
const card = $("diagnostics-card");
if (card) {
card.scrollIntoView({ behavior: "smooth", block: "start" });
}
loadDiagnostics(true);
});
}
const refreshDiagBtn = $("refresh-diag-btn");
if (refreshDiagBtn) {
refreshDiagBtn.addEventListener("click", () => loadDiagnostics(true));
}
const copyDiagBtn = $("copy-diag-btn");
if (copyDiagBtn) {
copyDiagBtn.addEventListener("click", async () => {
const report = (await loadDiagnostics(false)) || latestDiagnosticsReport;
if (!report) {
setDiagMsg("No diagnostics available to copy.", true);
return;
}
try {
const copied = await copyTextToClipboard(report);
if (copied) {
setDiagMsg("Copied diagnostics report to clipboard.");
copyDiagBtn.textContent = "Copied!";
if (copyBtnTimer) clearTimeout(copyBtnTimer);
copyBtnTimer = setTimeout(() => {
copyDiagBtn.textContent = "Copy Diagnostics";
copyBtnTimer = null;
}, 1500);
} else {
setDiagMsg("Clipboard copy blocked by browser; select text below to copy.", true);
}
} catch (err) {
setDiagMsg(`Clipboard copy failed: ${err}`, true);
}
});
}
const diagDetails = $("diagnostics-details");
if (diagDetails) {
diagDetails.addEventListener("toggle", () => {
if (diagDetails.open) {
loadDiagnostics(false);
}
});
}
initialSettingsPromise = loadSettingsFast();
refresh(false);
if (document.body && document.body.classList.contains("manager")) {
loadDiagnostics(false);
}
setInterval(() => refresh(false), 2000);
});