feat: add I2P BitTorrent engine, DHT, and Firefox torrent extension
check / check (macos-latest) (push) Failing after 29s
check / check (ubuntu-latest) (push) Failing after 29s
check / check (windows-latest) (push) Failing after 30s

- Add pure-MoonBit bittorrent package: bencode codec, metainfo/magnet parsing with path traversal checks, peer wire protocol (BEP 10/9), and I2P Kademlia DHT with KRPC and 54-byte compact nodes
- Add SHA-1 primitive in crypto for torrent info hashes
- Add router torrent API and engine, enabled with --torrent-api (default 127.0.0.1:4445) and --download-dir
- Add Firefox WebExtension torrent manager with native messaging host and packed .xpi
- Add scripts to build a standalone Firefox + router AppImage and install the native host
- Add just targets (proxy, appimage, extension), README docs, and ignore .cache/ and dist/
This commit is contained in:
nandi committed 2026-11-28 13:19:03 -08:00
1 parent 14eae00f5c
commit fbe6818c4e
37 files changed
+8543 -9

No files matched your search

@@ -0,0 +1,257 @@
"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: ["<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) {
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" };
}
});
+71
View File
@@ -0,0 +1,71 @@
"use strict";
(function () {
function showToast(text, isError) {
let el = document.getElementById("moon-i2p-torrent-toast");
if (!el) {
el = document.createElement("div");
el.id = "moon-i2p-torrent-toast";
el.style.cssText = [
"position:fixed",
"right:18px",
"bottom:18px",
"z-index:2147483647",
"padding:10px 14px",
"border-radius:10px",
"font-family:system-ui,-apple-system,sans-serif",
"font-size:13px",
"color:#f8fafc",
"box-shadow:0 8px 24px rgba(0,0,0,0.35)",
"border:1px solid rgba(255,255,255,0.16)",
"max-width:360px",
].join(";");
document.documentElement.appendChild(el);
}
el.style.background = isError ? "#991b1b" : "#0f172a";
el.textContent = text;
clearTimeout(el._hideTimer);
el._hideTimer = setTimeout(() => {
if (el.parentNode) el.parentNode.removeChild(el);
}, 4500);
}
document.addEventListener(
"click",
async (ev) => {
if (ev.button !== 0 || ev.altKey || ev.ctrlKey || ev.metaKey || ev.shiftKey) {
return;
}
const anchor = ev.target && ev.target.closest ? ev.target.closest("a[href]") : null;
if (!anchor) return;
const href = anchor.getAttribute("href") || "";
let absUrl = "";
try {
absUrl = new URL(href, window.location.href).href;
} catch (_e) {
return;
}
const isMagnet = absUrl.toLowerCase().startsWith("magnet:");
const isTorrent = /\.torrent(\?.*)?$/i.test(absUrl);
if (!isMagnet && !isTorrent) return;
ev.preventDefault();
ev.stopPropagation();
try {
const res = await browser.runtime.sendMessage(
isMagnet
? { type: "addMagnet", uri: absUrl }
: { type: "addTorrentUrl", url: absUrl }
);
if (res && res.ok) {
showToast(`Added to moon-i2p (${(res.info_hash || "").slice(0, 12)}...)`, false);
} else {
showToast(`moon-i2p error: ${(res && res.error) || "router offline?"}`, true);
}
} catch (err) {
showToast(`moon-i2p error: ${err}`, true);
}
},
true
);
})();
+12
View File
@@ -0,0 +1,12 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 96 96">
<defs>
<linearGradient id="g" x1="0" y1="0" x2="1" y2="1">
<stop offset="0%" stop-color="#6d5dfc"/>
<stop offset="100%" stop-color="#14b8a6"/>
</linearGradient>
</defs>
<rect width="96" height="96" rx="22" fill="#0f172a"/>
<circle cx="48" cy="48" r="34" fill="none" stroke="url(#g)" stroke-width="6"/>
<path d="M48 25v29m0 0-12-12m12 12 12-12" fill="none" stroke="#f8fafc" stroke-width="6" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M29 64h38" stroke="#14b8a6" stroke-width="6" stroke-linecap="round"/>
</svg>

After

Width:  |  Height:  |  Size: 618 B

+108
View File
@@ -0,0 +1,108 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Moon I2P Torrent &amp; DHT Manager</title>
<link rel="stylesheet" href="ui.css" />
</head>
<body class="manager">
<header>
<div class="brand">
<img src="icon.svg" alt="" />
<span>moon-i2p BitTorrent &amp; I2P DHT Manager</span>
</div>
<div class="row">
<span id="router-pill" class="pill offline">Offline</span>
<button id="start-router-btn">Start Router</button>
<button id="stop-router-btn" class="secondary" style="display:none;">Stop Router</button>
</div>
</header>
<div class="grid-2">
<section class="card">
<h2><span>I2P Router &amp; HTTP Proxy</span></h2>
<div class="grid-2">
<div class="stat">
<div class="stat-label">NetDB / Tunnels</div>
<div id="net-summary" class="stat-val">--</div>
</div>
<div class="stat">
<div class="stat-label">I2P Proxy (.i2p)</div>
<label class="row" style="gap:4px;">
<input id="proxy-enabled" type="checkbox" />
<span id="proxy-addr" class="mono">127.0.0.1:4444</span>
</label>
</div>
</div>
<div class="stat" style="margin-top:8px;">
<div class="stat-label">Torrent Session .b32.i2p (share with DHT peers)</div>
<div id="torrent-b32" class="stat-val mono">--</div>
</div>
</section>
<section class="card">
<h2>
<span>I2P Kademlia DHT (Proto 17 / 18)</span>
<span id="dht-summary" class="mono">0 nodes</span>
</h2>
<div class="grid-2">
<div class="stat">
<div class="stat-label">Secure Node ID (20B)</div>
<div id="dht-node-id" class="stat-val mono">--</div>
</div>
<div class="stat">
<div class="stat-label">Sent / Recv / Peers</div>
<div id="dht-stats" class="stat-val">0 / 0 / 0</div>
</div>
</div>
<form id="bootstrap-form" class="row" style="margin-top:8px;">
<input id="bootstrap-b32" type="text" placeholder="Bootstrap node .b32.i2p" />
<input id="bootstrap-port" type="number" value="6881" style="width:84px;" />
<button type="submit" class="secondary">Bootstrap</button>
</form>
<div id="dht-nodes-list" class="node-list mono"></div>
</section>
</div>
<section class="card">
<h2><span>Add Torrent or Magnet URI</span></h2>
<form id="magnet-form" class="row">
<input id="magnet-uri" type="text" placeholder="magnet:?xt=urn:btih:...&amp;dn=..." />
<button type="submit">Add Magnet</button>
</form>
<div id="dropzone" class="dropzone">
Drop a .torrent file here or click to select one from disk
<input id="torrent-file" type="file" accept=".torrent" style="display:none;" />
</div>
<div id="status-msg" class="msg"></div>
</section>
<section class="card">
<h2>
<span>Active &amp; Completed Torrents</span>
<span id="torrent-count" class="mono">0</span>
</h2>
<div id="torrents-list">No torrents added yet.</div>
</section>
<section class="card">
<h2><span>Extension &amp; Router Settings</span></h2>
<form id="settings-form">
<div class="grid-2">
<div><div class="stat-label">HTTP Proxy Port</div><input id="cfg-proxy-port" type="number" /></div>
<div><div class="stat-label">Torrent API Port</div><input id="cfg-api-port" type="number" /></div>
</div>
<div style="margin-top:8px;">
<div class="stat-label">Default Download Directory</div>
<input id="cfg-dl-dir" type="text" placeholder="~/Downloads/moon-i2p" />
</div>
<div class="row" style="margin-top:8px;justify-content:space-between;">
<label class="row"><input id="cfg-intercept" type="checkbox" /> <span>Intercept magnet: and .torrent links on .i2p pages</span></label>
<button type="submit">Save Settings</button>
</div>
</form>
</section>
<script src="ui.js"></script>
</body>
</html>
@@ -0,0 +1,41 @@
{
"manifest_version": 2,
"name": "Moon I2P Torrent & Proxy",
"version": "0.1.0",
"description": "Route .i2p browsing through moon-i2p and manage I2P BitTorrent + I2P DHT torrents from Firefox.",
"icons": {
"48": "icon.svg",
"96": "icon.svg"
},
"browser_specific_settings": {
"gecko": {
"id": "moon-i2p-torrent@local",
"strict_min_version": "109.0"
}
},
"permissions": [
"proxy",
"storage",
"tabs",
"downloads",
"nativeMessaging",
"http://127.0.0.1/*",
"http://localhost/*",
"*://*.i2p/*"
],
"background": {
"scripts": ["background.js"]
},
"browser_action": {
"default_icon": "icon.svg",
"default_title": "Moon I2P Torrent & DHT",
"default_popup": "popup.html"
},
"content_scripts": [
{
"matches": ["*://*.i2p/*"],
"js": ["content.js"],
"run_at": "document_idle"
}
]
}
+112
View File
@@ -0,0 +1,112 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Moon I2P Torrent</title>
<link rel="stylesheet" href="ui.css" />
</head>
<body class="popup">
<header>
<div class="brand">
<img src="icon.svg" alt="" />
<span>moon-i2p Torrent</span>
</div>
<div class="row">
<span id="router-pill" class="pill offline">Offline</span>
<button id="open-manager-btn" class="secondary">Full View</button>
</div>
</header>
<section class="card">
<h2>
<span>I2P Router &amp; Proxy</span>
<span class="row">
<button id="start-router-btn">Start Router</button>
<button id="stop-router-btn" class="secondary" style="display:none;">Stop</button>
</span>
</h2>
<div class="grid-2">
<div class="stat">
<div class="stat-label">NetDB / Tunnels</div>
<div id="net-summary" class="stat-val">--</div>
</div>
<div class="stat">
<div class="stat-label">I2P Proxy (.i2p)</div>
<div class="row">
<label class="row" style="gap:4px;">
<input id="proxy-enabled" type="checkbox" />
<span id="proxy-addr" class="mono">127.0.0.1:4444</span>
</label>
</div>
</div>
</div>
<div class="stat" style="margin-top:6px;">
<div class="stat-label">Torrent Session .b32.i2p</div>
<div id="torrent-b32" class="stat-val mono">--</div>
</div>
</section>
<section class="card">
<h2>
<span>I2P DHT</span>
<span id="dht-summary" class="mono">0 nodes</span>
</h2>
<div class="grid-2">
<div class="stat">
<div class="stat-label">DHT Node ID (20B)</div>
<div id="dht-node-id" class="stat-val mono">--</div>
</div>
<div class="stat">
<div class="stat-label">Sent / Recv / Peers</div>
<div id="dht-stats" class="stat-val">0 / 0 / 0</div>
</div>
</div>
<form id="bootstrap-form" class="row" style="margin-top:8px;">
<input id="bootstrap-b32" type="text" placeholder="Bootstrap node .b32.i2p" />
<input id="bootstrap-port" type="number" value="6881" style="width:74px;" />
<button type="submit" class="secondary">Ping</button>
</form>
</section>
<section class="card">
<h2><span>Add I2P Torrent</span></h2>
<form id="magnet-form" class="row">
<input id="magnet-uri" type="text" placeholder="magnet:?xt=urn:btih:..." />
<button type="submit">Add</button>
</form>
<div id="dropzone" class="dropzone">
Drop a .torrent file here or click to browse
<input id="torrent-file" type="file" accept=".torrent" style="display:none;" />
</div>
<div id="status-msg" class="msg"></div>
</section>
<section class="card">
<h2>
<span>Torrents</span>
<span id="torrent-count" class="mono">0</span>
</h2>
<div id="torrents-list" class="muted">No torrents added yet.</div>
</section>
<details class="card">
<summary>Settings (API, Proxy &amp; Download Folder)</summary>
<form id="settings-form" style="margin-top:8px;">
<div class="grid-2">
<div><div class="stat-label">Proxy Port</div><input id="cfg-proxy-port" type="number" /></div>
<div><div class="stat-label">Torrent API Port</div><input id="cfg-api-port" type="number" /></div>
</div>
<div style="margin-top:6px;">
<div class="stat-label">Download Directory</div>
<input id="cfg-dl-dir" type="text" placeholder="~/Downloads/moon-i2p" />
</div>
<div class="row" style="margin-top:8px;justify-content:space-between;">
<label class="row"><input id="cfg-intercept" type="checkbox" /> <span>Intercept .i2p magnets &amp; .torrent links</span></label>
<button type="submit" class="secondary">Save</button>
</div>
</form>
</details>
<script src="ui.js"></script>
</body>
</html>
+240
View File
@@ -0,0 +1,240 @@
:root {
color-scheme: dark;
--bg: #0b1120;
--card: #131c31;
--border: #23304d;
--text: #e2e8f0;
--muted: #94a3b8;
--accent: #6d5dfc;
--teal: #14b8a6;
--danger: #ef4444;
--warn: #f59e0b;
}
* {
box-sizing: border-box;
}
body {
margin: 0;
background: var(--bg);
color: var(--text);
font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
font-size: 13px;
line-height: 1.45;
}
body.popup {
width: 450px;
min-height: 540px;
padding: 12px;
}
body.manager {
max-width: 980px;
margin: 0 auto;
padding: 20px;
}
header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
margin-bottom: 12px;
}
.brand {
display: flex;
align-items: center;
gap: 8px;
font-weight: 700;
font-size: 15px;
}
.brand img {
width: 24px;
height: 24px;
}
.pill {
display: inline-block;
padding: 2px 8px;
border-radius: 999px;
font-size: 11px;
font-weight: 600;
background: #1e293b;
color: var(--muted);
}
.pill.online {
background: rgba(20, 184, 166, 0.18);
color: #5eead4;
}
.pill.offline {
background: rgba(239, 68, 68, 0.18);
color: #fca5a5;
}
.card {
background: var(--card);
border: 1px solid var(--border);
border-radius: 10px;
padding: 10px 12px;
margin-bottom: 10px;
}
.card h2 {
margin: 0 0 8px 0;
font-size: 12px;
text-transform: uppercase;
letter-spacing: 0.05em;
color: var(--muted);
display: flex;
justify-content: space-between;
align-items: center;
}
.grid-2 {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 8px;
}
.stat {
background: rgba(15, 23, 42, 0.55);
border: 1px solid rgba(255, 255, 255, 0.06);
border-radius: 7px;
padding: 6px 8px;
}
.stat-label {
font-size: 11px;
color: var(--muted);
}
.stat-val {
font-size: 13px;
font-weight: 600;
word-break: break-all;
}
.mono {
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
font-size: 11px;
}
.row {
display: flex;
gap: 6px;
align-items: center;
}
input[type="text"],
input[type="number"] {
width: 100%;
background: #0b1222;
color: var(--text);
border: 1px solid var(--border);
border-radius: 6px;
padding: 6px 8px;
font-size: 12px;
}
button {
background: var(--accent);
color: #fff;
border: 0;
border-radius: 6px;
padding: 6px 10px;
font-size: 12px;
font-weight: 600;
cursor: pointer;
white-space: nowrap;
}
button.secondary {
background: #1e293b;
color: var(--text);
border: 1px solid var(--border);
}
button.danger {
background: rgba(239, 68, 68, 0.2);
color: #fca5a5;
border: 1px solid rgba(239, 68, 68, 0.35);
}
button:disabled {
opacity: 0.5;
cursor: default;
}
.dropzone {
margin-top: 8px;
border: 1px dashed var(--border);
border-radius: 8px;
padding: 8px;
text-align: center;
color: var(--muted);
cursor: pointer;
}
.dropzone.drag {
border-color: var(--teal);
color: var(--text);
}
.torrent-item {
padding: 8px 0;
border-top: 1px solid rgba(255, 255, 255, 0.06);
}
.torrent-item:first-child {
border-top: 0;
padding-top: 0;
}
.progress-track {
width: 100%;
height: 6px;
background: #0b1222;
border-radius: 999px;
overflow: hidden;
margin: 5px 0;
}
.progress-fill {
height: 100%;
background: linear-gradient(90deg, var(--accent), var(--teal));
}
.msg {
font-size: 12px;
margin-top: 6px;
min-height: 16px;
color: #5eead4;
}
.msg.err {
color: #fca5a5;
}
details summary {
cursor: pointer;
color: var(--muted);
font-size: 12px;
}
.node-list {
max-height: 130px;
overflow-y: auto;
margin-top: 6px;
font-size: 11px;
}
.node-row {
padding: 3px 0;
border-bottom: 1px solid rgba(255, 255, 255, 0.05);
}
+241
View File
@@ -0,0 +1,241 @@
"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);
}
let settingsPopulated = false;
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 || {};
$("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;
}
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";
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 · ${t.connected_peers}/${t.known_peers} peers</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>
${t.error ? `<div class="msg err">${escapeHtml(t.error)}</div>` : ""}
</div>
`;
})
.join("");
}
}
document.addEventListener("DOMContentLoaded", () => {
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();
});
$("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, 700);
});
$("stop-router-btn").addEventListener("click", async () => {
await browser.runtime.sendMessage({ type: "stopRouter" });
setMsg("Stopped router.");
setTimeout(refresh, 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();
});
$("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();
});
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();
};
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();
});
$("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();
});
refresh();
setInterval(refresh, 2000);
});