#!/usr/bin/env python3 """Build a self-contained MoonI2P-Browser x86_64 AppImage. Bundles: - Official Mozilla Firefox ESR (x86_64) - Native moon-i2p router (--public, HTTP proxy, BitTorrent + I2P DHT API) - Pre-installed moon-i2p-torrent@local Firefox WebExtension & Native Messaging host - Pre-configured Moon I2P Start Page, I2P PAC routing, and HTTPS-First disabled for .i2p """ import json import os import shutil import stat import subprocess import sys import tarfile import urllib.request import zipfile from pathlib import Path REPO_ROOT = Path(__file__).resolve().parent.parent CACHE_DIR = REPO_ROOT / ".cache" / "appimage" APP_DIR = CACHE_DIR / "AppDir" DIST_DIR = REPO_ROOT / "dist" OUTPUT_APPIMAGE = DIST_DIR / "MoonI2P-Browser-x86_64.AppImage" EXT_SRC = REPO_ROOT / "extensions" / "firefox-i2p-torrent" EXT_XPI = REPO_ROOT / "extensions" / "firefox-i2p-torrent.xpi" NATIVE_HOST_SRC = REPO_ROOT / "scripts" / "moon_i2p_native_host.py" FIREFOX_ESR_URL = ( "https://download.mozilla.org/?product=firefox-esr-latest-ssl&os=linux64&lang=en-US" ) APPIMAGE_RUNTIME_URL = ( "https://github.com/AppImage/type2-runtime/releases/download/continuous/runtime-x86_64" ) def run(cmd, cwd=None, check=True): print(f"[build_appimage] $ {' '.join(map(str, cmd))}") return subprocess.run(cmd, cwd=str(cwd or REPO_ROOT), check=check) def download_cached(url: str, dest: Path, min_bytes: int = 100_000) -> Path: dest.parent.mkdir(parents=True, exist_ok=True) if dest.is_file() and dest.stat().st_size >= min_bytes: print(f"[build_appimage] Using cached {dest} ({dest.stat().st_size} bytes)") return dest tmp = dest.with_suffix(dest.suffix + ".part") print(f"[build_appimage] Downloading {url} -> {dest}") req = urllib.request.Request(url, headers={"User-Agent": "moon-i2p-appimage-builder/1.0"}) with urllib.request.urlopen(req, timeout=180) as resp, open(tmp, "wb") as fp: shutil.copyfileobj(resp, fp, length=1024 * 256) if tmp.stat().st_size < min_bytes: raise RuntimeError(f"Downloaded file too small: {tmp} ({tmp.stat().st_size} bytes)") tmp.replace(dest) return dest def build_router_binary() -> Path: rel_bin = REPO_ROOT / "_build" / "native" / "release" / "build" / "cmd" / "router" / "router.exe" dbg_bin = REPO_ROOT / "_build" / "native" / "debug" / "build" / "cmd" / "router" / "router.exe" res = subprocess.run( ["moon", "build", "--target", "native", "--release", "cmd/router"], cwd=str(REPO_ROOT), ) if res.returncode == 0 and rel_bin.is_file(): return rel_bin run(["moon", "build", "--target", "native", "cmd/router"]) if not dbg_bin.is_file(): raise FileNotFoundError(f"router binary not built at {dbg_bin}") return dbg_bin def build_extension_xpi() -> Path: EXT_XPI.parent.mkdir(parents=True, exist_ok=True) with zipfile.ZipFile(EXT_XPI, "w", compression=zipfile.ZIP_DEFLATED) as zf: for path in sorted(EXT_SRC.rglob("*")): if path.is_file(): zf.write(path, path.relative_to(EXT_SRC).as_posix()) return EXT_XPI def make_executable(path: Path): mode = os.stat(path).st_mode os.chmod(path, mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH) def write_firefox_configs(firefox_dir: Path): pref_dir = firefox_dir / "defaults" / "pref" pref_dir.mkdir(parents=True, exist_ok=True) (pref_dir / "autoconfig.js").write_text( 'pref("general.config.filename", "mozilla.cfg");\n' 'pref("general.config.obscure_value", 0);\n', encoding="utf-8", ) # First line MUST be a comment (`//`). (firefox_dir / "mozilla.cfg").write_text( "// Moon I2P Browser defaults (Firefox ESR AppImage)\n" 'pref("xpinstall.signatures.required", false);\n' 'pref("extensions.autoDisableScopes", 0);\n' 'pref("extensions.enabledScopes", 15);\n' 'pref("extensions.sideloadScopes", 15);\n' 'pref("extensions.startupScanScopes", 15);\n' 'pref("extensions.installDistroAddons", true);\n' 'defaultPref("browser.startup.page", 1);\n' 'defaultPref("dom.security.https_only_mode", false);\n' 'defaultPref("dom.security.https_only_mode_pbm", false);\n' 'defaultPref("dom.security.https_first", false);\n' 'defaultPref("dom.security.https_first_pbm", false);\n' 'pref("browser.fixup.domainsuffixwhitelist.i2p", true);\n' 'pref("network.trr.mode", 5);\n' 'pref("network.proxy.socks_remote_dns", true);\n' 'pref("network.captive-portal-service.enabled", false);\n' 'pref("network.connectivity-service.enabled", false);\n' 'pref("browser.shell.checkDefaultBrowser", false);\n' 'pref("app.update.auto", false);\n' 'pref("app.update.enabled", false);\n', encoding="utf-8", ) dist_dir = firefox_dir / "distribution" dist_dir.mkdir(parents=True, exist_ok=True) policies = { "policies": { "OverrideFirstRunPage": "", "OverridePostUpdatePage": "", "DontCheckDefaultBrowser": True, "DisableAppUpdate": True, "DisableTelemetry": True, "DisablePocket": True, "DisableFirefoxStudies": True, "DNSOverHTTPS": {"Enabled": False}, "Bookmarks": [ { "Title": "NotBob Directory", "URL": "http://notbob.i2p/", "Placement": "toolbar", }, { "Title": "Postman Tracker", "URL": "http://tracker2.postman.i2p/", "Placement": "toolbar", }, { "Title": "Insula Occulta", "URL": "http://insulaocculta.i2p/", "Placement": "toolbar", }, { "Title": "I2P Stats", "URL": "http://stats.i2p/", "Placement": "toolbar", }, { "Title": "zzz.i2p", "URL": "http://zzz.i2p/", "Placement": "toolbar", }, ], "ExtensionSettings": { "moon-i2p-torrent@local": { "default_area": "navbar", "private_browsing": True, "updates_disabled": True, } }, } } (dist_dir / "policies.json").write_text( json.dumps(policies, indent=2) + "\n", encoding="utf-8" ) APP_RUN_SH = r'''#!/usr/bin/env bash set -euo pipefail APPDIR="$(dirname "$(readlink -f "$0")")" DATA_DIR="${MOON_I2P_DATA_DIR:-${XDG_DATA_HOME:-$HOME/.local/share}/moon-i2p-browser}" PROFILE_DIR="${MOON_I2P_PROFILE_DIR:-$DATA_DIR/profile}" DOWNLOAD_DIR="${MOON_I2P_DOWNLOAD_DIR:-$HOME/Downloads/moon-i2p}" LOG_FILE="$DATA_DIR/router.log" LOCK_FILE="$DATA_DIR/instance.lock" mkdir -p "$DATA_DIR" PYTHON_BIN="$(command -v python3 || true)" abort_already_running() { local detail="$1" local msg="Moon I2P Browser is already running ($detail). Close the existing window before relaunching." echo "$msg" >&2 if [[ "${MOON_I2P_NO_NOTIFY:-0}" != "1" ]] && [[ -n "${DISPLAY:-}${WAYLAND_DISPLAY:-}" ]] && command -v notify-send >/dev/null 2>&1; then notify-send -a "Moon I2P Browser" \ "Moon I2P Browser is already running" \ "Close the existing Moon I2P Browser window before relaunching ($detail)." \ >/dev/null 2>&1 || true fi exit 1 } # Guard 1: Exclusive AppRun instance lock (append mode so held lockfiles are never truncated). exec 9>>"$LOCK_FILE" if command -v flock >/dev/null 2>&1; then if ! flock -n 9; then EXISTING_PID="$(tr -dc '0-9' < "$LOCK_FILE" 2>/dev/null || true)" if [[ -n "$EXISTING_PID" ]]; then abort_already_running "PID $EXISTING_PID" fi abort_already_running "instance lock held" fi fi # Guard 2: Detect an already-running Firefox on this profile (e.g. legacy AppImage without instance.lock). if [[ -n "$PYTHON_BIN" && -f "$PROFILE_DIR/.parentlock" ]]; then EXISTING_FF_PID="$("$PYTHON_BIN" -c ' import fcntl, os, struct, sys p = sys.argv[1] try: fd = os.open(p, os.O_RDONLY) except OSError: sys.exit(0) try: fl = struct.pack("hhqqi4x", fcntl.F_WRLCK, os.SEEK_SET, 0, 0, 0) res = fcntl.fcntl(fd, fcntl.F_GETLK, fl) l_type, _, _, _, l_pid = struct.unpack("hhqqi4x", res) if l_type != fcntl.F_UNLCK and l_pid > 0: print(l_pid) except OSError: pass finally: os.close(fd) ' "$PROFILE_DIR/.parentlock" 2>/dev/null || true)" if [[ -n "$EXISTING_FF_PID" ]]; then abort_already_running "Firefox PID $EXISTING_FF_PID" fi fi if [[ -L "$PROFILE_DIR/lock" ]]; then LOCK_TARGET="$(readlink "$PROFILE_DIR/lock" 2>/dev/null || true)" if [[ "$LOCK_TARGET" == *":+"* ]]; then LOCK_PID="${LOCK_TARGET##*:+}" if [[ "$LOCK_PID" =~ ^[0-9]+$ ]] && kill -0 "$LOCK_PID" 2>/dev/null; then if ! LOCK_CMDLINE="$(tr '\0' ' ' < "/proc/$LOCK_PID/cmdline" 2>/dev/null)" || printf '%s' "$LOCK_CMDLINE" | grep -qi "firefox"; then abort_already_running "Firefox PID $LOCK_PID" fi fi fi fi printf '%s\n' "$$" > "$LOCK_FILE" mkdir -p "$PROFILE_DIR/extensions" "$DOWNLOAD_DIR" # Ensure the bundled extension XPI is installed in the browser profile. cp -f "$APPDIR/usr/share/moon-i2p/moon-i2p-torrent@local.xpi" \ "$PROFILE_DIR/extensions/moon-i2p-torrent@local.xpi" # Install a stable Native Messaging host wrapper outside the ephemeral /tmp mount. if [[ "${MOON_I2P_NO_HOST_INSTALL:-0}" != "1" ]]; then HOST_COPY="$DATA_DIR/moon_i2p_native_host.py" cp -f "$APPDIR/usr/bin/moon_i2p_native_host.py" "$HOST_COPY" chmod 755 "$HOST_COPY" for NM_DIR in "$HOME/.mozilla/native-messaging-hosts" "$HOME/.config/mozilla/native-messaging-hosts"; do mkdir -p "$NM_DIR" cat > "$NM_DIR/moon_i2p_torrent.json" < "$PROFILE_DIR/i2p.pac" < "$PROFILE_DIR/user.js" < "$PREFS_TMP" || true mv -f "$PREFS_TMP" "$PROFILE_DIR/prefs.js" fi ROUTER_BIN="$APPDIR/usr/bin/moon-i2p-router" ROUTER_PID="" FF_PID="" ACTIVE_PORTS_WRITTEN=0 cleanup() { local rc=$? if [[ "$ACTIVE_PORTS_WRITTEN" == "1" ]]; then rm -f "$DATA_DIR/active_ports.json" fi if [[ -n "$FF_PID" ]] && kill -0 "$FF_PID" 2>/dev/null; then kill -TERM "$FF_PID" 2>/dev/null || true wait "$FF_PID" 2>/dev/null || true fi if [[ -n "$ROUTER_PID" ]] && kill -0 "$ROUTER_PID" 2>/dev/null; then kill -TERM "$ROUTER_PID" 2>/dev/null || true for _ in $(seq 1 20); do kill -0 "$ROUTER_PID" 2>/dev/null || break sleep 0.1 done if kill -0 "$ROUTER_PID" 2>/dev/null; then kill -KILL "$ROUTER_PID" 2>/dev/null || true fi wait "$ROUTER_PID" 2>/dev/null || true fi exit "$rc" } trap cleanup EXIT INT TERM LOG_MAX_BYTES="${MOON_I2P_LOG_MAX_BYTES:-5242880}" [[ "$LOG_MAX_BYTES" =~ ^[0-9]+$ ]] || LOG_MAX_BYTES=5242880 if [[ -f "$LOG_FILE" ]]; then LOG_SIZE="$(stat -c%s "$LOG_FILE" 2>/dev/null || wc -c < "$LOG_FILE")" LOG_SIZE="${LOG_SIZE//[[:space:]]/}" if [[ "$LOG_SIZE" =~ ^[0-9]+$ ]] && (( LOG_SIZE >= LOG_MAX_BYTES )); then mv -f "$LOG_FILE" "$LOG_FILE.1" fi fi printf '\n=== Moon I2P Browser start %s appdir=%s proxy=%s api=%s sam=%s ===\n' \ "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$APPDIR" "$PROXY_PORT" "$API_PORT" "$SAM_PORT" >> "$LOG_FILE" "$ROUTER_BIN" \ --public \ --debug \ --sam "127.0.0.1:$SAM_PORT" \ --http-proxy "127.0.0.1:$PROXY_PORT" \ --torrent-api "127.0.0.1:$API_PORT" \ --download-dir "$DOWNLOAD_DIR" \ 9>&- >> "$LOG_FILE" 2>&1 & ROUTER_PID=$! ACTIVE_PORTS_TMP="$DATA_DIR/active_ports.json.tmp.$$" cat > "$ACTIVE_PORTS_TMP" <&- & FF_PID=$! wait "$FF_PID" ''' def main(): DIST_DIR.mkdir(parents=True, exist_ok=True) CACHE_DIR.mkdir(parents=True, exist_ok=True) router_bin = build_router_binary() xpi_path = build_extension_xpi() firefox_tar = download_cached( FIREFOX_ESR_URL, CACHE_DIR / "firefox-esr-linux64.tar.xz", min_bytes=20_000_000 ) runtime_bin = download_cached( APPIMAGE_RUNTIME_URL, CACHE_DIR / "runtime-x86_64", min_bytes=100_000 ) if runtime_bin.read_bytes()[:4] != b"\x7fELF": raise RuntimeError(f"Invalid ELF AppImage runtime at {runtime_bin}") if APP_DIR.exists(): shutil.rmtree(APP_DIR) (APP_DIR / "usr" / "bin").mkdir(parents=True) (APP_DIR / "usr" / "lib").mkdir(parents=True) (APP_DIR / "usr" / "share" / "moon-i2p").mkdir(parents=True) print(f"[build_appimage] Extracting {firefox_tar.name}...") with tarfile.open(firefox_tar, "r:*") as tf: tf.extractall(APP_DIR / "usr" / "lib") firefox_dir = APP_DIR / "usr" / "lib" / "firefox" if not (firefox_dir / "firefox").is_file(): raise RuntimeError(f"Expected Firefox binary at {firefox_dir / 'firefox'}") dist_ext_dir = firefox_dir / "distribution" / "extensions" dist_ext_dir.mkdir(parents=True, exist_ok=True) shutil.copy2(xpi_path, dist_ext_dir / "moon-i2p-torrent@local.xpi") shutil.copy2(xpi_path, APP_DIR / "usr" / "share" / "moon-i2p" / "moon-i2p-torrent@local.xpi") write_firefox_configs(firefox_dir) router_dest = APP_DIR / "usr" / "bin" / "moon-i2p-router" shutil.copy2(router_bin, router_dest) make_executable(router_dest) host_dest = APP_DIR / "usr" / "bin" / "moon_i2p_native_host.py" shutil.copy2(NATIVE_HOST_SRC, host_dest) make_executable(host_dest) # Render desktop PNG icon via rsvg-convert (fallback magick). icon_png = APP_DIR / "moon-i2p-browser.png" svg_src = EXT_SRC / "icon.svg" if shutil.which("rsvg-convert"): run(["rsvg-convert", "-w", "256", "-h", "256", str(svg_src), "-o", str(icon_png)]) elif shutil.which("magick"): run(["magick", "-background", "none", str(svg_src), "-resize", "256x256", str(icon_png)]) else: raise RuntimeError("Need rsvg-convert or magick to render AppImage icon") dir_icon = APP_DIR / ".DirIcon" if dir_icon.exists() or dir_icon.is_symlink(): dir_icon.unlink() dir_icon.symlink_to("moon-i2p-browser.png") (APP_DIR / "MoonI2P-Browser.desktop").write_text( "[Desktop Entry]\n" "Version=1.0\n" "Type=Application\n" "Name=Moon I2P Browser\n" "Comment=Zero-setup I2P browser and BitTorrent/DHT client powered by moon-i2p\n" "Exec=AppRun %u\n" "Icon=moon-i2p-browser\n" "Categories=Network;WebBrowser;P2P;\n" "MimeType=text/html;x-scheme-handler/magnet;application/x-bittorrent;\n" "StartupWMClass=MoonI2PBrowser\n", encoding="utf-8", ) app_run = APP_DIR / "AppRun" app_run.write_text(APP_RUN_SH, encoding="utf-8") make_executable(app_run) squashfs_img = CACHE_DIR / "moon-i2p-browser.squashfs" if squashfs_img.exists(): squashfs_img.unlink() mk_res = subprocess.run( [ "mksquashfs", str(APP_DIR), str(squashfs_img), "-root-owned", "-noappend", "-comp", "zstd", "-b", "1M", ] ) if mk_res.returncode != 0: run( [ "mksquashfs", str(APP_DIR), str(squashfs_img), "-root-owned", "-noappend", "-comp", "gzip", "-b", "1M", ] ) tmp_out = OUTPUT_APPIMAGE.with_suffix(".AppImage.part") with open(tmp_out, "wb") as out_fp: with open(runtime_bin, "rb") as rt_fp: shutil.copyfileobj(rt_fp, out_fp, length=1024 * 256) with open(squashfs_img, "rb") as sq_fp: shutil.copyfileobj(sq_fp, out_fp, length=1024 * 1024) make_executable(tmp_out) tmp_out.replace(OUTPUT_APPIMAGE) size_mb = OUTPUT_APPIMAGE.stat().st_size / (1024 * 1024) print(f"[build_appimage] Built {OUTPUT_APPIMAGE} ({size_mb:.1f} MiB)") if __name__ == "__main__": main()