- Firefox extension: add start.html/css/js as homepage and new-tab page (manifest bumped to 0.1.5, .xpi rebuilt). Shows router readiness, tunnel/NetDB/DHT tiles, torrents, and a .i2p/magnet address bar. - openManager message now accepts an optional hash and reuses any open manager tab. - Android: default page is file:///android_asset/start.html, backed by a MoonI2pStart JS bridge (status, torrents, open URL, diagnostics, copy .b32). Blocks file: navigation from the WebView. - RouterService: add fetchLocalApiJsonOrNull for bounded local API reads. - Built-in .i2p destinations reordered (NotBob, Postman first); README updated to match.
434 lines
14 KiB
JavaScript
434 lines
14 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,
|
|
};
|
|
}
|
|
|
|
function safePrettyJson(obj, compact = false) {
|
|
try {
|
|
return compact ? JSON.stringify(obj) : JSON.stringify(obj, null, 2);
|
|
} catch (err) {
|
|
return `{"ok":false,"error":${JSON.stringify(String(err))}}`;
|
|
}
|
|
}
|
|
|
|
function formatDiagnosticsReport(cfg, nativeDiag, routerStatus, dht, torrents) {
|
|
const manifest = browser.runtime.getManifest ? browser.runtime.getManifest() : {};
|
|
const nd = nativeDiag || {};
|
|
const lines = [];
|
|
lines.push("=== Moon I2P Firefox Diagnostics ===");
|
|
lines.push(`Timestamp: ${new Date().toISOString()}`);
|
|
lines.push(`Extension Version: ${manifest.version || "?"}`);
|
|
lines.push(`User Agent: ${typeof navigator !== "undefined" ? navigator.userAgent : "?"}`);
|
|
const modeStr = nd.appimage ? "AppImage" : "Standalone";
|
|
lines.push(`Mode: ${modeStr}${nd.platform ? ` · ${nd.platform}` : ""}`);
|
|
|
|
if (nd.available) {
|
|
lines.push(
|
|
`Native Host: available=true · router_pid=${nd.router_pid ?? "none"} · managed_running=${!!nd.managed_running} · api_reachable=${!!nd.api_reachable} · proxy_reachable=${!!nd.proxy_reachable}`
|
|
);
|
|
if (nd.router_bin) {
|
|
lines.push(`Router Binary: ${nd.router_bin}`);
|
|
}
|
|
if (nd.active_ports) {
|
|
lines.push(`Active Ports: ${safePrettyJson(nd.active_ports, true)}`);
|
|
}
|
|
} else {
|
|
lines.push(
|
|
`Native Host: available=false · error=${nd.error || "unavailable (run `just extension` to install native host)"}`
|
|
);
|
|
}
|
|
|
|
lines.push(
|
|
`Settings: proxyEnabled=${!!cfg.proxyEnabled} · proxy=${cfg.proxyHost || "127.0.0.1"}:${cfg.proxyPort || 4444} · api=${cfg.apiHost || "127.0.0.1"}:${cfg.apiPort || 4445} · interceptTorrents=${!!cfg.interceptTorrents}`
|
|
);
|
|
lines.push(`Download Dir: ${cfg.downloadDir || "(router default)"}`);
|
|
|
|
if (nd.log_path) {
|
|
if (nd.log_exists) {
|
|
lines.push(
|
|
`Log File: ${nd.log_path} (${nd.log_size_bytes || 0} bytes, mtime=${nd.log_mtime_iso || "?"})${nd.log_error ? ` · err=${nd.log_error}` : ""}`
|
|
);
|
|
} else {
|
|
lines.push(`Log File: MISSING (${nd.log_path})`);
|
|
}
|
|
}
|
|
|
|
if (nd.log_summary) {
|
|
const s = nd.log_summary;
|
|
lines.push(
|
|
`Log Tail Summary (${s.lines || 0} lines): unhandled_garlic=${s.unhandled_garlic || 0} · garlic_decrypted=${s.garlic_decrypted || 0} · stream_connect_timeouts=${s.stream_connect_timeouts || 0} · bt_handshake_timeouts=${s.bt_handshake_timeouts || 0} · ls2_lookup_timeouts=${s.ls2_lookup_timeouts || 0} · pieces_verified=${s.pieces_verified || 0}`
|
|
);
|
|
if (s.last_public_line) {
|
|
lines.push(`Last Router Status: ${s.last_public_line}`);
|
|
}
|
|
}
|
|
|
|
lines.push("");
|
|
lines.push("=== Router API /api/status ===");
|
|
lines.push(safePrettyJson(routerStatus));
|
|
|
|
lines.push("");
|
|
lines.push("=== Router API /api/torrents ===");
|
|
lines.push(safePrettyJson(torrents));
|
|
|
|
lines.push("");
|
|
lines.push("=== Router API /api/dht/nodes ===");
|
|
lines.push(safePrettyJson(dht, true));
|
|
|
|
lines.push("");
|
|
lines.push("=== Native moon-i2p Router Log (tail 32 KiB) ===");
|
|
if (!nd.available) {
|
|
lines.push(
|
|
`(native host unavailable: ${nd.error || "run `just extension` to inspect desktop router logs"})`
|
|
);
|
|
} else if (nd.log_error) {
|
|
lines.push(`(error reading ${nd.log_path || "router.log"}: ${nd.log_error})`);
|
|
} else if (!nd.log_exists) {
|
|
lines.push(`(log file not found at ${nd.log_path || "router.log"})`);
|
|
} else if (!nd.log_tail) {
|
|
lines.push("(empty)");
|
|
} else {
|
|
lines.push(nd.log_tail.replace(/\n+$/, ""));
|
|
}
|
|
|
|
return lines.join("\n") + "\n";
|
|
}
|
|
|
|
async function gatherDiagnostics(maxBytes = 32768) {
|
|
await loadSettings();
|
|
if (!syncedAppImageEnv) {
|
|
await syncFromNativeEnv();
|
|
}
|
|
const [nativeDiag, routerStatus, dht, torrents] = await Promise.all([
|
|
nativeCommand("diagnostics", { max_bytes: maxBytes }),
|
|
apiJson("/api/status", "GET", null, 3000).catch((e) => ({ ok: false, error: String(e) })),
|
|
apiJson("/api/dht/nodes", "GET", null, 3000).catch((e) => ({ ok: false, error: String(e) })),
|
|
apiJson("/api/torrents", "GET", null, 3000).catch((e) => ({ ok: false, error: String(e) })),
|
|
]);
|
|
const report = formatDiagnosticsReport(
|
|
cachedSettings,
|
|
nativeDiag,
|
|
routerStatus,
|
|
dht,
|
|
torrents
|
|
);
|
|
return {
|
|
ok: true,
|
|
report,
|
|
meta: {
|
|
logPath: nativeDiag?.log_path || "",
|
|
logExists: !!nativeDiag?.log_exists,
|
|
logSizeBytes: Number(nativeDiag?.log_size_bytes || 0),
|
|
nativeAvailable: !!nativeDiag?.available,
|
|
nativeError: nativeDiag?.error || "",
|
|
},
|
|
};
|
|
}
|
|
|
|
// 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 "getDiagnostics":
|
|
return gatherDiagnostics(msg.maxBytes || 32768);
|
|
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 baseUrl = browser.runtime.getURL("manager.html");
|
|
const hash = typeof msg.hash === "string" && msg.hash ? msg.hash : "";
|
|
const targetUrl = hash ? `${baseUrl}${hash}` : baseUrl;
|
|
const existing = await browser.tabs.query({ url: `${baseUrl}*` });
|
|
if (existing.length > 0) {
|
|
await browser.tabs.update(existing[0].id, { active: true, url: targetUrl });
|
|
} else {
|
|
await browser.tabs.create({ url: targetUrl });
|
|
}
|
|
return { ok: true };
|
|
}
|
|
default:
|
|
return { ok: false, error: "unknown message type" };
|
|
}
|
|
});
|