Publish Vulpes Preview 15 sources for desktop, Android and Tundra

Share Gaia assets and adapters, keep private profiles and development documents local, and update both public READMEs.
This commit is contained in:
OverSu 2026-09-30 23:13:03 +02:00
commit b38dea0597
41 changed files with 9982925 additions and 369 deletions

72
tools/audit-apps.py Normal file
View file

@ -0,0 +1,72 @@
#!/usr/bin/env python3
"""Launch genuine user apps in the explicitly enabled test profile and record diagnostics."""
import json
import time
from pathlib import Path
from marionette_client import Client
ROOT = Path(__file__).resolve().parents[1]
with Client(2857) as c:
assert "/host-" in c.execute("return PathUtils.profileDir;")
c.execute(
"try{ChromeUtils.registerWindowActor('VulpesProbe',{child:{esModuleURI:'resource://vulpes/tests/ProbeChild.sys.mjs'},allFrames:true,safeForUntrustedWebProcess:true});}catch(_){}"
)
def ev(app, code, path="/"):
s = """const done=arguments[arguments.length-1];const root=Services.wm.getMostRecentWindow('vulpes:host').document.getElementById('system').browsingContext;
const bc=(function f(b){if(b.currentWindowGlobal?.documentURI.spec.startsWith(PREFIX))return b;for(const child of b.children){const r=f(child);if(r)return r;}})(root);
if(!bc){done(null);return;}bc.currentWindowGlobal.getActor('VulpesProbe').sendQuery('Evaluate',CODE).then(done,e=>done({error:String(e)}));""".replace(
"PREFIX", json.dumps("http://" + app + ".localhost:8765" + path)
).replace(
"CODE", json.dumps(code)
)
return c.call(
"WebDriver:ExecuteAsyncScript",
{
"script": s,
"args": [],
"newSandbox": True,
"sandbox": "system",
"scriptTimeout": 15000,
},
)["value"]
results = {}
for app, entry in [
("communications", "dialer"),
("communications", "contacts"),
("sms", None),
("email", None),
("gallery", None),
("music", None),
("video", None),
("clock", None),
("costcontrol", None),
("camera", None),
("calendar", None),
("settings", None),
("search", None),
("fm", None),
]:
params = {
"manifestURL": f"http://{app}.localhost:8765/manifest.webapp",
"entryPoint": entry,
}
ev(
"system",
'await VulpesCompat.call("apps.launch",' + json.dumps(params) + ");return true;",
)
path = "/" + entry + "/" if entry else "/"
for _ in range(100):
if ev(app, "return document.readyState==='complete';", path):
break
time.sleep(0.1)
time.sleep(1)
result = ev(
app,
"return {url:location.href,text:document.body?.innerText.slice(0,1800),diagnostics:window.__vulpesDiagnostics};",
path,
)
results[app + ("/" + entry if entry else "")] = result
print(app, json.dumps(result, ensure_ascii=False), flush=True)
(ROOT / "logs/app-audit.json").write_text(json.dumps(results, ensure_ascii=False, indent=2))

97
tools/audit-repository.py Normal file
View file

@ -0,0 +1,97 @@
#!/usr/bin/env python3
"""Review files eligible for publication without changing the Git index."""
import json
from pathlib import Path
import subprocess
import sys
ROOT = Path(__file__).resolve().parents[1]
EXCLUDED = [
"profiles/",
"engines/",
"downloads/",
"logs/",
"node_modules/",
".venv/",
"android/toolchain/",
"android/keys/",
"android/.gradle/",
"android/build/",
"android/app/build/",
"android/app/src/main/assets/",
"android/dist/",
"android/logs/",
]
GENERATED = {
"assets/registry.json",
"assets/build-info.json",
"assets/settings-current-defaults.json",
"assets/webapps/webapps.json",
"android/local.properties",
}
def publication_files():
output = subprocess.check_output(
["git", "ls-files", "--cached", "--others", "--exclude-standard", "-z"],
cwd=ROOT,
)
return sorted(set(output.decode().split("\0")) - {""})
def audit():
files = publication_files()
errors = []
size = 0
for name in files:
path = ROOT / name
if name in GENERATED or any(name.startswith(prefix) for prefix in EXCLUDED):
errors.append("Generated/private file eligible for publication: " + name)
if path.suffix.lower() in {".keystore", ".jks", ".p12", ".pfx"} or path.name in {
".env",
"id_rsa",
"id_ed25519",
}:
errors.append("Possible credential file: " + name)
if path.is_symlink() and not path.resolve().is_relative_to(ROOT):
errors.append("Symlink outside the repository: " + name)
if not path.exists():
errors.append("Tracked file missing: " + name)
continue
if path.is_file():
size += path.stat().st_size
if (
name.startswith(("tools/", "host/", "services/", "adapters/", "android/tools/"))
and path.suffix in {".py", ".js", ".mjs", ".sh"}
and path.name != Path(__file__).name
):
text = path.read_text()
if (
"/mnt/BIGDATATWO/" in text
or "/home/archiviste/" in text
or "versions/2.7-gecko52/" in text
):
errors.append("Private workspace dependency: " + name)
ignored_probes = [
"android/keys/preview.keystore",
"android/local.properties",
"profiles/example/cookies.sqlite",
"android/dist/example.apk",
"logs/example.log",
]
for name in ignored_probes:
result = subprocess.run(["git", "check-ignore", "-q", name], cwd=ROOT)
if result.returncode != 0:
errors.append("Missing ignore rule: " + name)
report = {
"eligibleFiles": len(files),
"sizeMiB": round(size / 1024**2, 1),
"errors": errors,
"scope": "Working tree paths and first-party code; not a full history secret scan.",
}
print(json.dumps(report, indent=2))
return bool(errors)
if __name__ == "__main__":
sys.exit(audit())

173
tools/check-desktop.py Normal file
View file

@ -0,0 +1,173 @@
#!/usr/bin/env python3
"""Run desktop integration and restart checks on a private X11 display."""
import argparse
import importlib.util
import os
from pathlib import Path
import shutil
import socket
import subprocess
import sys
import tempfile
from marionette_client import Client
ROOT = Path(__file__).resolve().parents[1]
parser = argparse.ArgumentParser()
parser.add_argument("--candidate", action="store_true")
parser.add_argument(
"--phase",
action="append",
choices=["first", "feedback", "apps", "platform", "languages", "restart"],
help="Run only the selected phase(s)",
)
args = parser.parse_args()
for command in ["Xvfb", "xdotool", "import"]:
if not shutil.which(command):
sys.exit("Dépendance de test absente : " + command)
extra = ["--candidate"] if args.candidate else []
for port in [2857, 8765]:
with socket.socket() as probe:
probe.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
probe.bind(("127.0.0.1", port))
except OSError:
sys.exit(f"Port {port} occupé : fermer le laboratoire actuel avant les tests.")
(ROOT / "logs").mkdir(exist_ok=True)
with tempfile.TemporaryFile() as display_file, (ROOT / "logs/xvfb.log").open("w") as log:
xserver = subprocess.Popen(
[
"Xvfb",
"-displayfd",
str(display_file.fileno()),
"-screen",
"0",
"800x1000x24",
"-nolisten",
"tcp",
],
pass_fds=(display_file.fileno(),),
stdout=log,
stderr=log,
)
try:
import time
for _ in range(100):
display_file.seek(0)
display = display_file.read().decode().strip()
if display:
break
if xserver.poll() is not None:
sys.exit("Xvfb a échoué : logs/xvfb.log")
time.sleep(0.05)
else:
sys.exit("Xvfb ne répond pas")
env = os.environ.copy()
env.update(DISPLAY=":" + display, GDK_BACKEND="x11", MOZ_ENABLE_WAYLAND="0")
for phase in args.phase or [
"first",
"feedback",
"apps",
"platform",
"languages",
"restart",
]:
with (ROOT / "logs" / ("desktop-" + phase + ".log")).open("w") as output:
host = subprocess.Popen(
[sys.executable, str(ROOT / "tools/run-host.py"), "--test", *extra],
env=env,
stdout=output,
stderr=subprocess.STDOUT,
)
connected = False
try:
# Wait for Marionette initialization before opening the suite.
with Client(2857) as client:
spec = importlib.util.spec_from_file_location("probe", ROOT / "tools/probe-desktop.py")
probe = importlib.util.module_from_spec(spec)
spec.loader.exec_module(probe)
probe.register(client)
for _ in range(200):
ready = probe.evaluate(client, "system", "return document.body?.getAttribute('ready-state')==='fullyLoaded';")
if ready.get("value"):
break
time.sleep(.1)
else:
raise RuntimeError("Gaia did not finish loading")
# Wake before unlocking: waking can activate the lockscreen.
probe.evaluate(client, "system", "ScreenManager.turnScreenOn(true);return true;")
time.sleep(.5)
probe.evaluate(client, "system", "lockScreen.unlock(true);return true;")
time.sleep(.5)
connected = True
# The ownership test deliberately removes Gaia's iframe.
# Start the UI regressions in a fresh process, preserving data.
if phase in ["first", "restart"]:
subprocess.run(
[
sys.executable,
str(ROOT / "tools/test-host.py"),
*extra,
*(["--restart-check"] if phase == "restart" else []),
],
env=env,
check=True,
)
if phase in ["feedback", "restart"]:
subprocess.run(
[
sys.executable,
str(ROOT / "tools/test-feedback.py"),
*(["--restart-check"] if phase == "restart" else []),
],
env=env,
check=True,
)
if phase in ["apps", "restart"]:
subprocess.run(
[
sys.executable,
str(ROOT / "tools/test-apps.py"),
*(["--restart-check"] if phase == "restart" else []),
],
env=env,
check=True,
)
if phase == "platform":
subprocess.run(
[sys.executable, str(ROOT / "tools/test-camera.py")],
env=env,
check=True,
)
subprocess.run(
[sys.executable, str(ROOT / "tools/test-platform.py")],
env=env,
check=True,
)
if phase in ["languages", "restart"]:
subprocess.run(
[
sys.executable,
str(ROOT / "tools/test-languages.py"),
*(["--restart-check"] if phase == "restart" else []),
],
env=env,
check=True,
)
finally:
try:
if connected:
with Client(2857) as client:
client.call("Marionette:Quit", {"flags": ["eAttemptQuit"]})
finally:
try:
host.wait(timeout=15)
except subprocess.TimeoutExpired:
host.terminate()
host.wait(timeout=10)
if host.returncode:
sys.exit("Le lanceur a échoué, consulter logs/desktop-" + phase + ".log")
finally:
xserver.terminate()
xserver.wait(timeout=10)

View file

@ -0,0 +1,85 @@
#!/usr/bin/env python3
"""Run archived app observations and restart in an isolated profile/display."""
import os
import socket
import subprocess
import sys
import tempfile
import time
from pathlib import Path
from marionette_client import Client
ROOT = Path(__file__).resolve().parents[1]
(ROOT / "logs").mkdir(exist_ok=True)
for port in [8765, 2857]:
with socket.socket() as probe:
probe.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
probe.bind(("127.0.0.1", port))
except OSError:
sys.exit("Fermer Vulpes avant ces tests (port " + str(port) + " occupé).")
with tempfile.TemporaryFile() as display_file, (ROOT / "logs/legacy-xvfb.log").open("w") as log:
xserver = subprocess.Popen(
[
"Xvfb",
"-displayfd",
str(display_file.fileno()),
"-screen",
"0",
"800x1000x24",
"-nolisten",
"tcp",
],
pass_fds=(display_file.fileno(),),
stdout=log,
stderr=log,
)
try:
for _ in range(100):
display_file.seek(0)
display = display_file.read().decode().strip()
if display:
break
time.sleep(0.05)
else:
raise RuntimeError("Xvfb failed")
env = os.environ.copy()
env.update(DISPLAY=":" + display, GDK_BACKEND="x11", MOZ_ENABLE_WAYLAND="0")
for phase in ["first", "restart"]:
with (ROOT / "logs" / ("legacy-host-" + phase + ".log")).open("w") as output:
host = subprocess.Popen(
[sys.executable, str(ROOT / "tools/run-host.py"), "--test", "--legacy-apps"],
env=env,
stdout=output,
stderr=subprocess.STDOUT,
)
connected = False
try:
with Client(2857):
pass
connected = True
subprocess.run(
[
sys.executable,
str(ROOT / "tools/test-legacy-apps.py"),
*(["--restart-check"] if phase == "restart" else []),
],
env=env,
check=True,
)
finally:
try:
if connected:
with Client(2857) as client:
client.call("Marionette:Quit", {"flags": ["eAttemptQuit"]})
finally:
try:
host.wait(timeout=15)
except subprocess.TimeoutExpired:
host.terminate()
host.wait(timeout=10)
if host.returncode:
raise RuntimeError("Host failed, see logs/legacy-host-" + phase + ".log")
finally:
xserver.terminate()
xserver.wait(timeout=10)

106
tools/check-parity.py Normal file
View file

@ -0,0 +1,106 @@
#!/usr/bin/env python3
"""Reject stale Android payloads and inconsistent common release metadata."""
import argparse, hashlib, io, json, re, zipfile
from project import ROOT, release_info
p = argparse.ArgumentParser()
p.add_argument("--apk", type=str)
args = p.parse_args()
r = release_info()
apk = ROOT / (args.apk or f'android/dist/vulpes-os-preview-{r["version"]}.apk')
pattern = re.compile(
r"app://([a-zA-Z0-9_-]+)\.gaiamobile\.org|http://([a-zA-Z0-9_-]+)\.localhost:8765"
)
def translate(s):
return pattern.sub(lambda m: f"http://{m[1] or m[2]}.localhost:18765", s)
results = {}
with zipfile.ZipFile(apk) as archive:
metadata = json.loads(archive.read("assets/build-info.json"))
packaged = json.loads(archive.read("assets/bridge/release.json"))
assert metadata["version"] == r["version"], metadata
assert metadata["geckoview"] == r["geckoview"], metadata
assert packaged == r, (packaged, r)
with zipfile.ZipFile(io.BytesIO(archive.read("assets/gaia.zip"))) as gaia:
for name in [
"platform-ui.js",
"gaia-camera.js",
"gaia-compat.js",
"gaia-services.js",
"gaia-styles.js",
"gaia-restoration.js",
"gaia-wifi.js",
"desktop.css",
]:
expected = translate((ROOT / "host" / name).read_text()).encode()
actual = gaia.read("_vulpes/" + name)
assert actual == expected, "Stale Android shared UI: " + name
results[name] = hashlib.sha256(actual).hexdigest()
wifi = translate((ROOT / "overrides/system.gaiamobile.org/js/wifi.js").read_text()).encode()
assert gaia.read("system/js/wifi.js") == wifi, "Stale Android Gaia Wi-Fi timer"
results["system/js/wifi.js"] = hashlib.sha256(wifi).hexdigest()
for app, path in [
("settings", "js/panels/display/panel.js"),
("settings", "js/panels/wifi/panel.js"),
("system", "js/screen_manager.js"),
("system", "js/notification_screen.js"),
("system", "style/system/system.css"),
("communications", "dialer/style/call_log.css"),
]:
expected = translate((ROOT / "overrides" / (app + ".gaiamobile.org") / path).read_text())
for old, new in [("-moz-calc(", "calc("), ("-moz-box-sizing:", "box-sizing:"),
("-moz-plaintext", "plaintext"), (":-moz-dir(", ":dir("),
("offset-inline-start:", "inset-inline-start:"),
("offset-inline-end:", "inset-inline-end:")]:
expected = expected.replace(old, new)
actual = gaia.read(app + "/" + path)
assert actual == expected.encode(), "Stale Android Gaia panel: " + path
results[app + "/" + path] = hashlib.sha256(actual).hexdigest()
for app, path, source in [
("calendar", "gaia_build_defer_index.js", "overrides"),
("calendar", "js/bundle.js", "overrides"),
("gallery", "js/metadata_scripts.js", "assets/webapps"),
("gallery", "js/ImageEditor.js", "assets/webapps"),
]:
expected = translate((ROOT / source / (app + ".gaiamobile.org") / path).read_text())
for old, new in [("-moz-calc(", "calc("), ("-moz-box-sizing:", "box-sizing:"),
("-moz-plaintext", "plaintext"), (":-moz-dir(", ":dir("),
("offset-inline-start:", "inset-inline-start:"),
("offset-inline-end:", "inset-inline-end:")]:
expected = expected.replace(old, new)
expected = expected.encode()
actual = gaia.read(app + "/" + path)
assert actual == expected, "Stale application workflow: " + app + "/" + path
results[app + "/" + path] = hashlib.sha256(actual).hexdigest()
for path in (ROOT / "overrides/search.gaiamobile.org/home").rglob("*"):
if path.is_file():
relative = path.relative_to(ROOT / "overrides/search.gaiamobile.org")
assert gaia.read("search/" + relative.as_posix()) == path.read_bytes(), str(relative)
assert b"vulpes-local-home" in gaia.read("search/newtab.html")
assert archive.read("assets/bridge/Messages.mjs") == (ROOT / "host/Messages.sys.mjs").read_bytes()
for name in ["platform.mjs", "settings.mjs", "datastores.mjs", "screen-power.mjs"]:
assert (
archive.read("assets/bridge/services/" + name)
== (ROOT / "services" / name).read_bytes()
), name
assert (
r["androidEngine"].split(".")[0]
== r["desktopEngine"].split(".")[0]
== r["engineAlignment"]["family"]
)
report = {
"version": r["version"],
"gaia": r["gaia"],
"desktopEngine": r["desktopEngine"],
"androidEngine": r["androidEngine"],
"exactEngineMatch": r["desktopEngine"] == r["androidEngine"],
"sharedFiles": results,
"apk": str(apk),
"scope": "Payload and metadata parity; hardware behavior requires separate integration tests.",
}
(ROOT / "logs/parity-payload.json").write_text(json.dumps(report, indent=2) + "\n")
print(json.dumps(report, indent=2))

135
tools/fetch-engine.py Normal file
View file

@ -0,0 +1,135 @@
#!/usr/bin/env python3
"""Download a checked engine archive into an isolated installation."""
import argparse
import hashlib
import json
import os
from pathlib import Path
import re
import tarfile
import tempfile
import urllib.request
ROOT = Path(__file__).resolve().parents[1]
def read_url(url):
with urllib.request.urlopen(url, timeout=30) as response:
return response.read()
def install(lock, offline=False):
version = lock["version"]
archive = ROOT / "downloads" / Path(lock["archive"]).name
target = ROOT / "engines" / version
if target.exists():
metadata_path = target / "engine.json"
if not metadata_path.is_file() or not (target / "firefox/firefox").is_file():
raise RuntimeError(f"Incomplete engine installation left untouched: {target}")
existing = json.loads(metadata_path.read_text())
if existing.get("version") != version or existing.get("sha512") != lock["sha512"]:
raise RuntimeError(f"Existing engine metadata differs from the lock: {target}")
return
if not archive.exists():
if offline:
raise RuntimeError(f"Cached archive missing: {archive}")
partial = archive.with_suffix(archive.suffix + ".partial")
with (
urllib.request.urlopen(lock["archive"], timeout=60) as response,
partial.open("wb") as out,
):
while chunk := response.read(1024 * 1024):
out.write(chunk)
partial.replace(archive)
with archive.open("rb") as stream:
digest = hashlib.file_digest(stream, "sha512").hexdigest()
if digest != lock["sha512"]:
raise RuntimeError(f"SHA512 mismatch; archive not extracted: {archive}")
with tempfile.TemporaryDirectory(prefix=".fetch-", dir=ROOT / "engines") as temporary:
stage = Path(temporary)
with tarfile.open(archive) as package:
package.extractall(stage, filter="data")
if not (stage / "firefox/firefox").is_file():
raise RuntimeError("Firefox executable missing from the archive")
distribution = stage / "firefox/distribution"
distribution.mkdir(exist_ok=True)
policies = {"policies": {"DisableAppUpdate": True, "DontCheckDefaultBrowser": True}}
(distribution / "policies.json").write_text(json.dumps(policies, indent=2) + "\n")
(stage / "engine.json").write_text(json.dumps(lock, indent=2) + "\n")
stage.rename(target)
def main():
parser = argparse.ArgumentParser()
choice = parser.add_mutually_exclusive_group()
choice.add_argument(
"--locked",
action="store_true",
help="Install engine-lock.json without changing the candidate",
)
choice.add_argument(
"--version", help="Exact candidate release; otherwise fetch the latest stable release"
)
parser.add_argument(
"--offline", action="store_true", help="With --locked, use the local archive cache only"
)
args = parser.parse_args()
if args.offline and not args.locked:
parser.error("--offline requires --locked")
for name in ["downloads", "engines"]:
(ROOT / name).mkdir(exist_ok=True)
if args.locked:
lock = json.loads((ROOT / "engine-lock.json").read_text())
else:
version = args.version
if not version:
metadata = json.loads(
read_url("https://product-details.mozilla.org/1.0/firefox_versions.json")
)
version = metadata["LATEST_FIREFOX_VERSION"]
(ROOT / "downloads/firefox_versions.json").write_text(
json.dumps(metadata, indent=2) + "\n"
)
if not re.fullmatch(r"\d+\.\d+(?:\.\d+)?(?:esr)?", version):
raise RuntimeError("Unsupported release identifier")
base = "https://archive.mozilla.org/pub/firefox/releases/" + version + "/"
relative = f"linux-x86_64/en-US/firefox-{version}.tar.xz"
sums = read_url(base + "SHA512SUMS").decode()
(ROOT / "downloads" / ("SHA512SUMS-" + version)).write_text(sums)
expected = next(
(
line.split()[0]
for line in sums.splitlines()
if len(line.split()) == 2 and line.split()[1].lstrip("*") == relative
),
None,
)
if not expected:
raise RuntimeError("Archive not listed in official SHA512SUMS")
lock = {
"version": version,
"runtime": f"engines/{version}/firefox",
"archive": base + relative,
"sha512": expected,
"checksumSource": base + "SHA512SUMS",
"channel": "release",
"sourceArchive": base + f"source/firefox-{version}.source.tar.xz",
"localChanges": ["distribution/policies.json: pin engine; no automatic update"],
"gaiaPorted": False,
}
if not re.fullmatch(r"\d+\.\d+(?:\.\d+)?(?:esr)?", lock["version"]):
raise RuntimeError("Unsupported release identifier in lock")
if lock["runtime"] != f'engines/{lock["version"]}/firefox':
raise RuntimeError("Runtime path does not match the locked version")
install(lock, args.offline)
if not args.locked:
with tempfile.NamedTemporaryFile("w", dir=ROOT, delete=False) as output:
json.dump(lock, output, indent=2)
output.write("\n")
temporary = output.name
os.replace(temporary, ROOT / "candidate-engine.json")
print(json.dumps(lock, indent=2), flush=True)
if __name__ == "__main__":
main()

47
tools/inspect-host.py Normal file
View file

@ -0,0 +1,47 @@
#!/usr/bin/env python3
"""Inspect a test host. Requires its explicitly enabled Marionette port."""
import argparse
import json
import sys
from marionette_client import Client
parser = argparse.ArgumentParser()
parser.add_argument("--app", default="system")
args = parser.parse_args()
with Client(2857) as client:
client.execute(
"""
try {ChromeUtils.registerWindowActor('VulpesProbe', {child: {esModuleURI:'resource://vulpes/tests/ProbeChild.sys.mjs'}, allFrames:true,safeForUntrustedWebProcess:true});} catch(e) {}
"""
)
script = (
sys.stdin.read()
or """return {url:location.href, title:document.title, text:document.body?.innerText.slice(0,500),
api:typeof navigator.vulpesRequest, frames:Array.from(document.querySelectorAll('iframe'),f=>({src:f.src,id:f.id})),
booted:!!window.app, appsReady:!!window.applications?.ready};"""
)
result = client.call(
"WebDriver:ExecuteAsyncScript",
{
"script": """
const done=arguments[arguments.length-1];
const browser=Services.wm.getMostRecentWindow('vulpes:host').document.getElementById('system');
const deadline=Date.now()+10000;
(function inspect(){
const context=
(function find(bc){if(bc.currentWindowGlobal?.documentURI.spec.startsWith("http://"""
+ args.app
+ """.localhost:8765/"))return bc;for(const c of bc.children){const found=find(c);if(found)return found;}return null;})(browser.browsingContext);
if(!context){if(Date.now()<deadline){setTimeout(inspect,100);return;}done({error:'Application is not open'});return;}
context.currentWindowGlobal.getActor('VulpesProbe').sendQuery('Evaluate', """
+ json.dumps(script)
+ """).then(v=>done({result:v}),e=>done({error:String(e),stack:e.stack}));
})();
""",
"args": [],
"newSandbox": True,
"sandbox": "system",
"scriptTimeout": 15000,
},
)
print(json.dumps(result, ensure_ascii=False, indent=2))

47
tools/inventory-gaia.py Normal file
View file

@ -0,0 +1,47 @@
#!/usr/bin/env python3
"""Static inventory of the preserved, actually launched Gaia profile."""
from pathlib import Path
import json
import re
root = Path(__file__).resolve().parents[1]
apps = root / "assets/webapps"
report = {
"source": "assets/webapps",
"note": "Static references, including definitions: not a count of mandatory calls.",
"navigatorAPIs": {},
"legacyCustomElementFiles": [],
"apps": {},
}
for f in apps.rglob("*"):
if f.suffix not in (".js", ".html", ".webapp") or not f.is_file():
continue
s = f.read_text(errors="replace")
rel = str(f.relative_to(apps))
for api in set(re.findall(r"navigator\.(moz\w+|getDataStores)", s)):
info = report["navigatorAPIs"].setdefault(api, {"fileCount": 0, "examples": []})
info["fileCount"] += 1
if len(info["examples"]) < 3:
info["examples"].append(rel)
if "registerElement(" in s:
report["legacyCustomElementFiles"].append(rel)
if f.name == "manifest.webapp" and f.parent.parent == apps:
try:
d = json.loads(s)
report["apps"][f.parent.name] = {
"name": d.get("name"),
"permissions": d.get("permissions", {}),
"activities": list(d.get("activities", {})),
}
except ValueError:
pass
out = root / "docs/legacy-dependencies.json"
out.write_text(json.dumps(report, indent=2, ensure_ascii=False) + "\n")
print(
len(report["navigatorAPIs"]),
"APIs referenced;",
len(report["apps"]),
"apps;",
len(report["legacyCustomElementFiles"]),
"files referencing Custom Elements v0",
)

View file

@ -0,0 +1,70 @@
"""Small client for the Marionette protocol shipped with current Firefox."""
import json
import socket
import time
class Client:
def __init__(self, port=2856):
deadline = time.monotonic() + 30
while True:
try:
self.socket = socket.create_connection(("127.0.0.1", port), timeout=20)
break
except ConnectionRefusedError:
if time.monotonic() >= deadline:
raise
time.sleep(0.2)
self.sequence = 0
self.quit_requested = False
self.receive()
self.call("WebDriver:NewSession", {"capabilities": {}})
self.call("Marionette:SetContext", {"value": "chrome"})
def receive(self):
length = bytearray()
while not length.endswith(b":"):
chunk = self.socket.recv(1)
if not chunk:
raise ConnectionError("Marionette disconnected")
length += chunk
remaining = int(length[:-1])
payload = bytearray()
while len(payload) < remaining:
chunk = self.socket.recv(remaining - len(payload))
if not chunk:
raise ConnectionError("Marionette disconnected")
payload += chunk
return json.loads(payload)
def call(self, command, arguments=None):
self.sequence += 1
payload = json.dumps([0, self.sequence, command, arguments or {}]).encode()
self.socket.sendall(str(len(payload)).encode() + b":" + payload)
response = self.receive()
if response[2]:
raise RuntimeError(response[2])
if command == "Marionette:Quit":
self.quit_requested = True
return response[3]
def execute(self, script):
result = self.call(
"WebDriver:ExecuteScript",
{"script": script, "args": [], "newSandbox": True, "sandbox": "system"},
)
return result.get("value", result)
def close(self):
try:
if not self.quit_requested:
self.call("WebDriver:DeleteSession")
finally:
self.socket.close()
def __enter__(self):
return self
def __exit__(self, *args):
self.close()

121
tools/modernize-syntax.py Normal file
View file

@ -0,0 +1,121 @@
#!/usr/bin/env python3
"""Explicit, idempotent syntax repairs for sources and prebuilt migration assets."""
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
replacements = {
"timestamp: String(message.timestamp)": "timestamp: String(+message.timestamp)",
"timestamp:String(message.timestamp)": "timestamp:String(+message.timestamp)",
"if (l10nAttrs.raw) {": 'if (typeof l10nAttrs.raw === "string") {',
"if(l10nAttrs.raw){": 'if(typeof l10nAttrs.raw==="string"){',
"this.startupMetadata.splice(entry, 1);\n icon.updateName();": "this.startupMetadata.splice(entry, 1);\n icon.updateName();\n if (window.VulpesCompat && icon.app) icon.refresh(); // Replace legacy rasterized cache with original app assets.",
"this.startupMetadata.splice(entry,1);icon.updateName();": "this.startupMetadata.splice(entry,1);icon.updateName();if(window.VulpesCompat&&icon.app)icon.refresh();",
"menuStatus = document.getElementById('fxa-desc');": "menuStatus = document.getElementById('fxa-desc');\n if(window.VulpesCompat){menuStatus.removeAttribute('data-l10n-id');menuStatus.textContent=(document.documentElement.lang||navigator.language).startsWith('fr')?'Service non disponible sur ce bureau':'Service unavailable on this desktop';return;}",
"menuStatus=document.getElementById('fxa-desc');": "menuStatus=document.getElementById('fxa-desc');if(window.VulpesCompat){menuStatus.removeAttribute('data-l10n-id');menuStatus.textContent=(document.documentElement.lang||navigator.language).startsWith('fr')?'Service non disponible sur ce bureau':'Service unavailable on this desktop';return;}",
"var onImageLoad = (evt) => {\n window.requestAnimationFrame(() => {\n var newActiveImage = evt.target.closest('img:not(.active)');": "var onImageLoad = (evt) => {\n const image = evt.target;\n window.requestAnimationFrame(() => {\n var newActiveImage = image.closest('img:not(.active)');",
"var onImageLoad=(evt)=>{window.requestAnimationFrame(()=>{var newActiveImage=evt.target.closest('img:not(.active)');": "var onImageLoad=(evt)=>{const image=evt.target;window.requestAnimationFrame(()=>{var newActiveImage=image.closest('img:not(.active)');",
"var sdcard = navigator.getDeviceStorage('sdcard');\n var request = sdcard.get(captionsFilename);": "var sdcard = navigator.getDeviceStorage('sdcard');\n if (!sdcard) return; // Captions are optional on desktop.\n var request = sdcard.get(captionsFilename);",
"var sdcard=navigator.getDeviceStorage('sdcard');var request=sdcard.get(captionsFilename);": "var sdcard=navigator.getDeviceStorage('sdcard');if(!sdcard)return;var request=sdcard.get(captionsFilename);",
"this.activeAlarm.snoozeAlarm(alert.id);\n window.close();": "this.activeAlarm.snoozeAlarm(alert.id).then(() => window.close()).catch(console.error);",
"this.activeAlarm.close(alert.type, alert.id);\n window.close();": "this.activeAlarm.close(alert.type, alert.id).then(() => window.close()).catch(console.error);",
"_messageHandler: function(evt) {\n var data = evt.data;": "_messageHandler: function(evt) {\n if (!evt.source || evt.origin !== window.location.origin || !evt.data) return;\n var data = evt.data;",
"offscreenImage.src = '';": "offscreenImage.onload = offscreenImage.onerror = null; offscreenImage.removeAttribute('src');",
"offscreenImage.src='';": "offscreenImage.onload=offscreenImage.onerror=null;offscreenImage.removeAttribute('src');",
"exports.scheduler = exports.scheduler || new Scheduler();": "if (!exports.scheduler || typeof exports.scheduler.mutation !== 'function') Object.defineProperty(exports, 'scheduler', {value:new Scheduler(),configurable:true,writable:true});",
"exports.scheduler=exports.scheduler||new Scheduler();": "if(!exports.scheduler||typeof exports.scheduler.mutation!=='function')Object.defineProperty(exports,'scheduler',{value:new Scheduler(),configurable:true,writable:true});",
"function postMessageSync(win, data, transfer) {": "function postMessageSync(win, data, transfer) { try { void win.document; } catch (_) { win.postMessage(data, location.origin, transfer || []); return; }",
"function postMessageSync(win,data,transfer){": "function postMessageSync(win,data,transfer){try{void win.document;}catch(_){win.postMessage(data,location.origin,transfer||[]);return;}",
"this.childWindow = window.open(this.url, '_blank', 'attention');": "this.childWindow = window.VulpesCompat ? VulpesCompat.openAttention(this.url) : window.open(this.url, '_blank', 'attention');",
"style: function(baseUrl) {": "style: function(baseUrl) { if (window.VulpesCompat) { window.VulpesCompat.componentStyle(this, baseUrl).catch(console.error); return; }",
"style:function(baseUrl){": "style:function(baseUrl){if(window.VulpesCompat){window.VulpesCompat.componentStyle(this,baseUrl).catch(console.error);return;}",
"shimHostIframe.contentDocument.readyState === 'complete' ?": "typeof shimHostIframe.contentWindow.bootstrap === 'function' ?",
"shimHostIframe.contentDocument.readyState==='complete'?": "typeof shimHostIframe.contentWindow.bootstrap==='function'?",
"hardwareHomeButton: '(-moz-physical-home-button)'": "hardwareHomeButton: window.VulpesCompat ? '(min-width: 0px)' : '(-moz-physical-home-button)'",
"hardwareHomeButton:'(-moz-physical-home-button)'": "hardwareHomeButton:window.VulpesCompat?'(min-width: 0px)':'(-moz-physical-home-button)'",
"new AudioContext(this._channel)": "new AudioContext()",
"var doc = (parent.location === window.location) ?\n document : parent.document;": 'var doc = document; try { if (!document.getElementById("confirmation-message")) doc = parent.document; } catch (_) {}',
"var doc=(parent.location===window.location)?document:parent.document;": 'var doc=document;try{if(!document.getElementById("confirmation-message"))doc=parent.document;}catch(_){}',
"window.scheduler || schedulerShim()": '(window.scheduler && typeof window.scheduler.mutation === "function" ? window.scheduler : schedulerShim())',
"window.scheduler||schedulerShim()": '(window.scheduler&&typeof window.scheduler.mutation==="function"?window.scheduler:schedulerShim())',
"div.querySelector(':host'); return true;": "div.querySelector(':host'); div.querySelector('::content'); return true;",
"div.querySelector(':host');return true;": "div.querySelector(':host');div.querySelector('::content');return true;",
"this._screenBrightnessTransition &&\n this._screenBrightnessTransition.transitionTo(this._targetBrightness);": "if (this._screenBrightnessTransition) {\n this._screenBrightnessTransition.transitionTo(this._targetBrightness);\n } else {\n power.screenBrightness = this._targetBrightness;\n }",
"this._screenBrightnessTransition&&this._screenBrightnessTransition.transitionTo(this._targetBrightness);": "this._screenBrightnessTransition?this._screenBrightnessTransition.transitionTo(this._targetBrightness):(power.screenBrightness=this._targetBrightness);",
"window.open(url, '_blank', 'remote=true');": "new MozActivity({name:'view',data:{type:'url',url:url}});",
"window.open(url,'_blank','remote=true');": "new MozActivity({name:'view',data:{type:'url',url:url}});",
"newDate.toLocaleFormat('%p')": "new Intl.DateTimeFormat(navigator.language, {hour:'numeric', hour12:true}).formatToParts(newDate).find(part => part.type === 'dayPeriod').value",
"gaia-container { position: relative; display: block; }": " :host { position: relative; display: block; }",
"[for (v of voices) v.lang.split('-')[0]]": "voices.map(v => v.lang.split('-')[0])",
"[for (p of pat) new SingleMatchPattern(p)]": "Array.from(pat, p => new SingleMatchPattern(p))",
"[for(p of pat)new SingleMatchPattern(p)]": "Array.from(pat, p => new SingleMatchPattern(p))",
"window.scheduler || {": '(window.scheduler && typeof window.scheduler.mutation === "function" ? window.scheduler : null) || {',
"window.scheduler||{": '(window.scheduler&&typeof window.scheduler.mutation==="function"?window.scheduler:null)||{',
"this._pendingIconUrl = 'app-icon';": "this._pendingIconUrl = 'app-icon';\n if (window.VulpesCompat) { this._vulpesSourceIcon = blob; this._hasUserSetIcon = true; } // Keep original app pixels; skip the legacy canvas pass.",
"this._pendingIconUrl='app-icon';": "this._pendingIconUrl='app-icon';if(window.VulpesCompat){this._vulpesSourceIcon=blob;this._hasUserSetIcon=true;}",
"Object.defineProperty(proto, 'icon', {\n get: function() {\n return new Promise((resolve, reject) => {": "Object.defineProperty(proto, 'icon', {\n get: function() {\n if (window.VulpesCompat && this.app && this._vulpesSourceIcon) return Promise.resolve(this._vulpesSourceIcon);\n return new Promise((resolve, reject) => {",
"Object.defineProperty(proto,'icon',{get:function(){return new Promise((resolve,reject)=>{": "Object.defineProperty(proto,'icon',{get:function(){if(window.VulpesCompat&&this.app&&this._vulpesSourceIcon)return Promise.resolve(this._vulpesSourceIcon);return new Promise((resolve,reject)=>{",
"if (window.VulpesCompat && appOrBookmark.manifest?.icons?.['512']?.includes('vulpes-browser.png')) icon.refresh();": "if (window.VulpesCompat && icon.app) icon.refresh(); // Replace legacy rasterized cache with original app assets.",
"if(window.VulpesCompat&&appOrBookmark.manifest?.icons?.['512']?.includes('vulpes-browser.png'))icon.refresh();": "if(window.VulpesCompat&&icon.app)icon.refresh();",
}
for name in ["gaia", "assets/webapps"]:
count = 0
for path in (ROOT / name).rglob("*.js"):
if not path.is_file() or "/test/" in str(path):
continue
try:
original = path.read_text()
except UnicodeDecodeError:
continue
text = original
if path.name == "main.js" and "camera.gaiamobile.org" in str(path):
text = (
text.replace(
"require(['main']);",
"if (!window.VulpesCompat || navigator.mozCameras) require(['main']);",
)
if "if (!window.VulpesCompat || navigator.mozCameras)" not in text
else text
)
if path.name == "fxa_iac_client.js":
text = text.replace(
"callback&&callback();});",
"callback&&callback();}).catch(function(error){callback&&callback(error);});",
)
text = text.replace(
"connect(function(){_sendMessage(message,successCb,errorCb);",
"connect(function(error){if(error){errorCb&&errorCb(error);return;}_sendMessage(message,successCb,errorCb);",
)
for old, new in replacements.items():
if new not in text:
text = text.replace(old, new)
if text != original:
path.write_text(text)
count += 1
print(name, count, "files updated")
# Native boot overlays keep the immutable Gaia system image. Include both SMS
# entry points: the old architecture lazy-loads conversation.js separately.
for relative in ("views/conversation/js/conversation.js", "views/conversation/gaia_build_defer_index.js"):
source = ROOT / "assets/webapps/sms.gaiamobile.org" / relative
target = ROOT / "overrides/sms.gaiamobile.org" / relative
target.parent.mkdir(parents=True, exist_ok=True)
target.write_bytes(source.read_bytes())
# Preserve bundled item definitions, replacing only the root dependency list.
# Unsupported hardware modules must not execute and break unrelated Settings UI.
path = ROOT / "assets/webapps/settings.gaiamobile.org/js/panels/root/low_priority_items.js"
if path.is_file():
text = path.read_text()
marker = "/* VULPES_ROOT_CAPABILITIES */"
old = "define('panels/root/low_priority_items',"
start = text.find(marker) if marker in text else text.find(old)
if start < 0:
raise RuntimeError("Settings root bundle has changed; review capability adapter")
replacement = (
text[:start]
+ marker
+ "\n"
+ (ROOT / "gaia/apps/settings/js/panels/root/low_priority_items.js").read_text()
)
if replacement != text:
path.write_text(replacement)

6
tools/prepare-assets.py Normal file
View file

@ -0,0 +1,6 @@
#!/usr/bin/env python3
"""Check that the installed Gaia payload is present in this checkout."""
from project import validate_assets
if __name__ == "__main__":
print(f"Gaia: {validate_assets()} applications available in assets/webapps")

View file

@ -0,0 +1,55 @@
#!/usr/bin/env python3
"""Fetch three pinned historical packages and extract byte-identical test copies."""
import hashlib
import json
from pathlib import Path
import stat
import tempfile
import urllib.request
import zipfile
ROOT = Path(__file__).resolve().parents[1]
CATALOG = json.loads((ROOT / "tests/legacy-apps.json").read_text())
BASE = ROOT / "downloads/legacy-apps"
BASE.mkdir(parents=True, exist_ok=True)
(BASE / "apps").mkdir(exist_ok=True)
for app in CATALOG:
archive = BASE / app["archive"]
if not archive.exists():
with urllib.request.urlopen(app["url"], timeout=30) as response:
data = response.read(10 * 1024 * 1024 + 1)
if len(data) > 10 * 1024 * 1024:
raise RuntimeError("Archive too large")
if hashlib.sha256(data).hexdigest() != app["sha256"]:
raise RuntimeError("Archive checksum mismatch: " + app["id"])
archive.write_bytes(data)
if hashlib.sha256(archive.read_bytes()).hexdigest() != app["sha256"]:
raise RuntimeError("Archive checksum mismatch: " + app["id"])
destination = BASE / "apps" / app["id"]
with zipfile.ZipFile(archive) as package:
if sum(info.file_size for info in package.infolist()) > 50 * 1024 * 1024:
raise RuntimeError("Extracted package too large")
manifest = json.loads(package.read("manifest.webapp"))
if manifest.get("type", "web") not in ("web", "privileged"):
raise RuntimeError("Only web and reviewed privileged packages are allowed")
for info in package.infolist():
name = Path(info.filename)
if (
name.is_absolute()
or ".." in name.parts
or "\\" in info.filename
or stat.S_ISLNK(info.external_attr >> 16)
):
raise RuntimeError("Unsafe archive entry: " + info.filename)
if not destination.exists():
with tempfile.TemporaryDirectory(dir=BASE / "apps") as temporary:
stage = Path(temporary) / "package"
stage.mkdir()
package.extractall(stage)
stage.rename(destination)
for info in package.infolist():
if not info.is_dir() and (destination / info.filename).read_bytes() != package.read(
info
):
raise RuntimeError("Extracted app was modified: " + app["id"] + "/" + info.filename)
print(app["id"] + ": archive SHA256 and extracted files verified", flush=True)

View file

@ -0,0 +1,82 @@
#!/usr/bin/env python3
"""Build a separate publication index; never change the working index or push."""
import argparse
import hashlib
import json
import os
from pathlib import Path
import re
import subprocess
ROOT = Path(__file__).resolve().parents[1]
SOURCE_DIRS = {'adapters','android','assets','contracts','gaia','host','overrides','services','tests','tools','tundra'}
ROOT_FILES = {'.gitignore','.nvmrc','.prettierignore','.prettierrc.json','LICENSE','NOTICE',
'README.md','README.fr.md','engine-lock.json','package.json','package-lock.json',
'pyproject.toml','requirements-dev.txt','release.json','run.sh','setup.sh'}
INTERNAL = {'changelog.json','VALIDATION.json','candidate-engine.json',
'tools/export-changelog.py','tools/sync-forgejo-changelog.py','tests/test_changelog.py',
'tools/check-checkout.py'}
MEDIA = {'docs/media/vulpes-logo.png','docs/media/vulpes-desktop.png','docs/media/vulpes-gecko.png'}
PRIVATE_PARTS = {'.git','.ssh','profiles','logs','out','downloads','engines','toolchain','keys','.gradle','node_modules','__pycache__'}
def target_name(name):
p=Path(name)
if name in INTERNAL or any(x in PRIVATE_PARTS for x in p.parts):return None
if name in MEDIA:return name
if p.parts[0] not in SOURCE_DIRS and name not in ROOT_FILES:return None
if 'docs' in p.parts or p.name=='VALIDATION.json':return None
if p.suffix.lower()=='.md' and name not in {'README.md','README.fr.md'}:
# License notices are retained verbatim, without publishing internal Markdown.
if p.name.lower() in {'license.md','copying.md','notice.md'}:return str(p.with_suffix(''))
return None
if p.name.lower() in {'roadmap','todo','roadmap.txt','todo.txt'}:return None
if name.startswith(('android/app/build/','android/build/','android/dist/','android/app/src/main/assets/','tundra/sources/')):return None
if p.suffix.lower() in {'.apk','.img','.ext4','.keystore','.jks','.p12','.pfx','.pyc'}:return None
if p.name in {'local.properties','client-key','known_hosts','authorized_keys','id_rsa','id_ed25519'}:return None
return name
def select():
paths=subprocess.check_output(['git','ls-files','--cached','--others','--exclude-standard','-z'],cwd=ROOT).decode().split('\0')
selected={}
for name in sorted(set(paths)-{''}):
dest=target_name(name)
if dest is None:continue
p=ROOT/name
if p.is_symlink() and not p.resolve().is_relative_to(ROOT):raise ValueError('External symlink: '+name)
if not p.is_file():raise ValueError('Missing publication file: '+name)
if dest in selected:raise ValueError('Duplicate destination: '+dest)
selected[dest]=name
if not {'LICENSE','NOTICE','README.md','README.fr.md'}<=selected.keys():raise ValueError('Missing publication metadata')
return selected
def main():
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('--index',type=Path,required=True)
parser.add_argument('--report',type=Path,required=True)
args=parser.parse_args()
index=args.index.resolve();normal=Path(subprocess.check_output(['git','rev-parse','--git-path','index'],cwd=ROOT,text=True).strip()).resolve()
if index==normal:raise ValueError('Refusing to replace working index')
selected=select();env=dict(os.environ,GIT_INDEX_FILE=str(index))
index.parent.mkdir(parents=True,exist_ok=True)
subprocess.run(['git','read-tree','--empty'],cwd=ROOT,env=env,check=True)
ordinary=[name for name in selected.values() if not (ROOT/name).is_symlink()]
encoded=''.join(json.dumps(name,ensure_ascii=False)+'\n' for name in ordinary).encode()
hashes=subprocess.check_output(['git','hash-object','-w','--no-filters','--stdin-paths'],input=encoded,cwd=ROOT).decode().splitlines()
if len(hashes)!=len(ordinary):raise ValueError('Blob count mismatch')
blobs=dict(zip(ordinary,hashes))
entries=[];manifest={};warnings=[]
for dest,source in selected.items():
p=ROOT/source;data=os.readlink(p).encode() if p.is_symlink() else p.read_bytes()
if re.search(rb'-----BEGIN (?:OPENSSH|RSA|EC|DSA)? ?PRIVATE KEY-----',data):warnings.append(source)
blob=blobs.get(source) or subprocess.check_output(['git','hash-object','-w','--stdin'],input=data,cwd=ROOT).decode().strip()
mode='120000' if p.is_symlink() else ('100755' if p.stat().st_mode&0o111 else '100644')
entries.append((mode+' '+blob+'\t'+dest+'\0').encode())
manifest[dest]={'source':source,'sha256':hashlib.sha256(data).hexdigest(),'bytes':len(data)}
if warnings:raise ValueError('Private-key material requires review: '+', '.join(warnings))
subprocess.run(['git','update-index','-z','--index-info'],input=b''.join(entries),cwd=ROOT,env=env,check=True)
tree=subprocess.check_output(['git','write-tree'],cwd=ROOT,env=env,text=True).strip()
report={'tree':tree,'files':len(manifest),'bytes':sum(v['bytes'] for v in manifest.values()),'markdown':[x for x in manifest if x.lower().endswith('.md')],'manifest':manifest}
args.report.parent.mkdir(parents=True,exist_ok=True);args.report.write_text(json.dumps(report,indent=2)+'\n')
print(json.dumps({k:v for k,v in report.items() if k!='manifest'},indent=2))
if __name__=='__main__':main()

46
tools/probe-desktop.py Normal file
View file

@ -0,0 +1,46 @@
#!/usr/bin/env python3
"""Evaluate diagnostics in Gaia on the test desktop, never a normal profile."""
import json, sys, time
from marionette_client import Client
def evaluate(client, app, code, path="/"):
prefix = f"http://{app}.localhost:8765{path}"
script = """const done=arguments[arguments.length-1];const w=Services.wm.getMostRecentWindow('vulpes:host');
const bc=w?.document.getElementById('system')?.browsingContext;
function find(b){if(b.currentWindowGlobal?.documentURI.spec.startsWith(PREFIX))return b;for(const c of b.children){const f=find(c);if(f)return f;}return null;}
const target=bc&&find(bc);if(!target){done({missing:true});return;}
target.currentWindowGlobal.getActor('VulpesProbe').sendQuery('Evaluate',CODE).then(value=>done({value}),error=>done({error:String(error)}));""".replace(
"PREFIX", json.dumps(prefix)
).replace(
"CODE", json.dumps(code)
)
return client.call(
"WebDriver:ExecuteAsyncScript",
{
"script": script,
"args": [],
"newSandbox": True,
"sandbox": "system",
"scriptTimeout": 25000,
},
)["value"]
def register(client):
assert client.execute("return PathUtils.profileDir;").split("/")[-1].startswith("host-")
client.execute(
"try{ChromeUtils.registerWindowActor('VulpesProbe',{child:{esModuleURI:'resource://vulpes/tests/ProbeChild.sys.mjs'},allFrames:true,safeForUntrustedWebProcess:true});}catch(_){}"
)
if __name__ == "__main__":
with Client(2857) as c:
register(c)
for _ in range(50):
result = evaluate(c, sys.argv[1], sys.argv[2])
if not result.get("missing"):
break
time.sleep(0.2)
print(json.dumps(result, indent=2, ensure_ascii=False))

88
tools/probe-engine.py Normal file
View file

@ -0,0 +1,88 @@
#!/usr/bin/env python3
"""Audit the official engine in isolation. This does not launch Gaia."""
import argparse
import json
import os
import subprocess
from pathlib import Path
from marionette_client import Client
ROOT = Path(__file__).resolve().parents[1]
(ROOT / "logs").mkdir(exist_ok=True)
(ROOT / "profiles").mkdir(exist_ok=True)
parser = argparse.ArgumentParser()
parser.add_argument("--candidate", action="store_true")
args = parser.parse_args()
lock = json.loads(
(ROOT / ("candidate-engine.json" if args.candidate else "engine-lock.json")).read_text()
)
runtime = ROOT / lock["runtime"]
profile = ROOT / "profiles" / ("probe-" + lock["version"])
profile.mkdir(parents=True, exist_ok=True)
prefs = {
"marionette.port": 2856,
"browser.shell.checkDefaultBrowser": False,
"browser.startup.homepage_override.mstone": "ignore",
"datareporting.policy.dataSubmissionEnabled": False,
"toolkit.telemetry.reportingpolicy.firstRun": False,
"browser.aboutwelcome.enabled": False,
}
(profile / "user.js").write_text(
"".join("user_pref(" + json.dumps(k) + "," + json.dumps(v) + ");\n" for k, v in prefs.items())
)
env = os.environ.copy()
for name in list(env):
if name.startswith("MOZ_DISABLE_") or name == "B2G_HOMESCREEN":
env.pop(name)
with (ROOT / "logs/engine-probe.log").open("w") as log:
proc = subprocess.Popen(
[
str(runtime / "firefox"),
"-no-remote",
"-headless",
"-marionette",
"--remote-allow-system-access",
"-profile",
str(profile),
"about:blank",
],
env=env,
stdout=log,
stderr=subprocess.STDOUT,
start_new_session=True,
)
try:
with Client() as client:
result = client.execute(
"""
const w=Services.wm.getMostRecentWindow('navigator:browser');
const f=w.document.createElementNS('http://www.w3.org/1999/xhtml','iframe');
const b=w.document.createXULElement('browser');
const contracts={};
for(const name of ['@mozilla.org/AppsService;1','@mozilla.org/settingsService;1','@mozilla.org/network/protocol;1?name=app'])contracts[name]=name in Components.classes;
const methods={};
for(const name of ['setVisible','getScreenshot','sendTouchEvent','setInputMethodActive','getCanGoBack'])methods[name]=typeof f[name];
const modules={};
for(const name of ['Downloads','Services','AppConstants']){try{ChromeUtils.importESModule('resource://gre/modules/'+name+'.sys.mjs');modules[name]=true;}catch(e){modules[name]=false;}}
return {version:Services.appinfo.platformVersion,build:Services.appinfo.platformBuildID,
updatesDisabled:!Services.policies.isAllowed('appUpdate'),contracts,modules,iframeMethods:methods,
registerElement:typeof w.document.registerElement,customElements:typeof w.customElements,
xulBrowser:{loadURI:typeof b.loadURI,tag:b.localName},fission:Services.appinfo.fissionAutostart,
contentSandboxLevel:Services.prefs.getIntPref('security.sandbox.content.level'),gaiaPorted:false};
"""
)
assert result["version"] == lock["version"], result
assert result["updatesDisabled"] is True, result
assert result["contentSandboxLevel"] > 0, result
(ROOT / "logs/engine-capabilities.json").write_text(json.dumps(result, indent=2) + "\n")
(ROOT / "logs" / ("engine-capabilities-" + lock["version"] + ".json")).write_text(
json.dumps(result, indent=2) + "\n"
)
print(json.dumps(result, indent=2), flush=True)
client.call("Marionette:Quit", {"flags": ["eAttemptQuit"]})
finally:
try:
proc.wait(timeout=15)
except subprocess.TimeoutExpired:
proc.terminate()
proc.wait(timeout=10)

67
tools/project.py Normal file
View file

@ -0,0 +1,67 @@
"""Paths and metadata shared by the desktop and Android build tools."""
import json
from pathlib import Path
import subprocess
ROOT = Path(__file__).resolve().parents[1]
def validate_assets():
"""Require the checked-in Gaia payload instead of a private profile copy."""
apps = ROOT / "assets/webapps"
required = [
ROOT / "assets/settings-defaults.json",
apps / "system.gaiamobile.org/index.html",
apps / "homescreen.gaiamobile.org/index.html",
apps / "default_theme.gaiamobile.org/manifest.webapp",
]
missing = [str(path.relative_to(ROOT)) for path in required if not path.is_file()]
if missing:
raise RuntimeError("Incomplete checkout; missing Gaia files: " + ", ".join(missing))
manifests = sorted(apps.glob("*/manifest.webapp"))
if not manifests:
raise RuntimeError("No installed Gaia manifests in assets/webapps")
for manifest in manifests:
json.loads(manifest.read_text())
json.loads((ROOT / "assets/settings-defaults.json").read_text())
return len(manifests)
def build_info():
"""Read this checkout's revision; archives without .git report it as unknown."""
unknown = {"revision": "unknown", "timestamp": 0, "dirty": None}
if not (ROOT / ".git").exists():
return unknown
try:
revision, timestamp = (
subprocess.check_output(
["git", "show", "-s", "--format=%H%n%ct", "HEAD"],
cwd=ROOT,
text=True,
stderr=subprocess.DEVNULL,
)
.strip()
.splitlines()
)
changes = subprocess.check_output(
["git", "status", "--porcelain", "--untracked-files=normal"],
cwd=ROOT,
text=True,
)
except (OSError, subprocess.CalledProcessError, ValueError):
return unknown
return {"revision": revision, "timestamp": int(timestamp), "dirty": bool(changes)}
def release_info():
"""One product revision, with independently verified platform engine packages."""
release = json.loads((ROOT / "release.json").read_text())
release.setdefault("version", f'{release["gaia"]}-{release["channel"]}.{release["revision"]}')
release["desktopEngine"] = json.loads((ROOT / "engine-lock.json").read_text())["version"]
engine, build_id = release["geckoview"].rsplit(".", 1)
release["androidEngine"] = engine
release["androidEngineBuildID"] = build_id
if not release["androidVersionCode"] > 4:
raise ValueError("Android versionCode must preserve upgrades from Preview 4")
return release

View file

@ -0,0 +1,21 @@
#!/usr/bin/env python3
"""Refresh selected AMD modules inside Gaia's existing Settings panel bundles."""
from pathlib import Path
import re
ROOT=Path(__file__).resolve().parents[1]
for panel, module in [('display','slider_handler'),('wifi','wifi_network_list')]:
name=f'panels/{panel}/{module}'
relative=f'js/panels/{panel}/panel.js'
original=ROOT/'assets/webapps/settings.gaiamobile.org'/relative
source=ROOT/'overrides/settings.gaiamobile.org'/f'js/{name}.js'
text=source.read_text()
dependencies=list(dict.fromkeys(re.findall(r"require\(['\"]([^'\"]+)['\"]\)",text)))
import json
text=text.replace('define(function(require)', 'define('+repr(name)+','+json.dumps(['require',*dependencies])+',function(require)',1)
bundle=original.read_text()
start=bundle.index("define('"+name+"'")
end=bundle.find("define('",start+8)
if end<0:end=len(bundle)
target=ROOT/'overrides/settings.gaiamobile.org'/relative
target.write_text(bundle[:start]+text+'\n'+bundle[end:])
print(target.relative_to(ROOT))

View file

@ -0,0 +1,59 @@
#!/usr/bin/env python3
"""Restore original Gaia density variants discarded by the 1x packaged build."""
import json
from pathlib import Path
import re
import shutil
ROOT = Path(__file__).resolve().parents[1]
URL = re.compile(r'url\([\'\"]?([^\s)\'\"]+)[\'\"]?\)')
PROPERTY = re.compile(r'background(?:-image)?\s*:[^;{}]+;')
def main():
report = []
for packaged in sorted((ROOT/'assets/webapps').glob('**/*.css')):
rel = packaged.relative_to(ROOT/'assets/webapps')
app, *parts = rel.parts
override = ROOT/'overrides'/rel
text = (override if override.exists() else packaged).read_text()
def declaration(match):
value = match[0]
if 'image-set(' in value:
return value
def image(found):
name = found[1]
if name.startswith(('data:', 'http:', 'https:')) or '@' in name:
return found[0]
target = (packaged.parent/name).resolve() if not name.startswith('/') else ROOT/'assets/webapps'/app/name.lstrip('/')
try:
asset = target.relative_to(ROOT/'assets/webapps'/app)
except ValueError:
return found[0]
source = ROOT/'gaia/apps'/app.removesuffix('.gaiamobile.org')/asset
if asset.parts[0] == 'shared':
source = ROOT/'gaia'/asset
variants = []
for density in ('1.5', '2', '2.25'):
candidate = source.with_name(source.stem+'@'+density+'x'+source.suffix)
if candidate.is_file() and candidate.suffix == '.png':
dest = ROOT/'overrides'/app/asset.parent/candidate.name
dest.parent.mkdir(parents=True,exist_ok=True)
shutil.copyfile(candidate,dest)
url = str(Path(name).with_name(candidate.name))
variants.append(f'url("{url}") {density}x')
if not variants:
return found[0]
report.append({'stylesheet':str(rel),'image':name,'densities':len(variants)})
return 'image-set('+f'url("{name}") 1x, '+', '.join(variants)+')'
return URL.sub(image,value)
updated = PROPERTY.sub(declaration,text)
if updated != text:
override.parent.mkdir(parents=True,exist_ok=True)
override.write_text(updated)
(ROOT/'logs/density-restoration.json').write_text(json.dumps(report,indent=2)+'\n')
print(f'{len(report)} CSS image references restored from original Gaia variants')
if __name__ == '__main__':
main()

164
tools/run-host.py Normal file
View file

@ -0,0 +1,164 @@
#!/usr/bin/env python3
"""Prepare and run the independent Gaia desktop on a pinned Mozilla runtime."""
import argparse
import fcntl
import json
import os
from pathlib import Path
import shutil
import socket
import subprocess
import sys
import time
ROOT = Path(__file__).resolve().parents[1]
from project import validate_assets
def prepare(lock, test=False):
runtime = ROOT / lock["runtime"]
if not (runtime / "firefox").is_file():
raise RuntimeError(
"Moteur absent. Exécuter ./setup.sh pour installer le moteur verrouillé."
)
validate_assets()
for name in ["host", "services", "adapters"] + (["tests"] if test else []):
shutil.copytree(ROOT / name, runtime / "vulpes" / name, dirs_exist_ok=True)
(runtime / "defaults/pref").mkdir(parents=True, exist_ok=True)
shutil.copy2(ROOT / "host/bootstrap/vulpes.cfg", runtime / "vulpes.cfg")
shutil.copy2(
ROOT / "host/bootstrap/vulpes-autoconfig.js", runtime / "defaults/pref/vulpes-autoconfig.js"
)
return runtime
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--candidate", action="store_true")
parser.add_argument(
"--legacy-apps", action="store_true", help="Trois paquets archivés, profil séparé"
)
parser.add_argument(
"--test", action="store_true", help="Marionette 2857, profil de test et fenêtre auxiliaire"
)
parser.add_argument("--prepare-only", action="store_true")
args = parser.parse_args()
lock = json.loads(
(ROOT / ("candidate-engine.json" if args.candidate else "engine-lock.json")).read_text()
)
(ROOT / "logs").mkdir(exist_ok=True)
# One host owns the loopback origins/registry. Never attach silently to an
# unknown HTTP listener or to another application's profile.
with (ROOT / "logs/host.lock").open("w") as guard:
try:
fcntl.flock(guard, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
raise RuntimeError(
"Un hôte Gecko actuel est déjà ouvert. Fermer sa fenêtre avant de relancer."
)
if args.legacy_apps:
subprocess.run([sys.executable, str(ROOT / "tools/prepare-legacy-apps.py")], check=True)
runtime = prepare(lock, args.test)
if args.prepare_only:
print("Adaptateur synchronisé :", runtime)
return
probe = socket.socket()
probe.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
probe.bind(("127.0.0.1", 8765))
except OSError:
raise RuntimeError("Port Gaia 8765 déjà occupé. Fermer le précédent hôte/serveur Gaia.")
finally:
probe.close()
profile = (
ROOT
/ "profiles"
/ (
("host-" if args.test else "desktop-")
+ ("legacy-" if args.legacy_apps else "")
+ lock["version"]
)
)
profile.mkdir(parents=True, exist_ok=True)
prefs = {
"browser.shell.checkDefaultBrowser": False,
"browser.dom.window.dump.enabled": True,
"browser.startup.homepage_override.mstone": "ignore",
"browser.aboutwelcome.enabled": False,
"font.default.x-western": "sans-serif",
"font.name.sans-serif.x-western": "Fira Sans",
"marionette.enabled": args.test,
"datareporting.policy.dataSubmissionEnabled": False,
}
if args.test:
prefs["marionette.port"] = 2857
(profile / "user.js").write_text(
"\n".join(f"user_pref({json.dumps(k)}, {json.dumps(v)});" for k, v in prefs.items())
+ "\n"
)
env = os.environ.copy()
for name in list(env):
if name.startswith("MOZ_DISABLE_") or name in (
"B2G_HOMESCREEN",
"MOZ_MARIONETTE",
"MOZ_HEADLESS",
):
env.pop(name)
env.update(VULPES_HOST_ROOT=str(runtime / "vulpes/host"), VULPES_WORKSPACE_ROOT=str(ROOT))
command = [
str(runtime / "firefox"),
"-no-remote",
"-purgecaches",
"-profile",
str(profile),
"-chrome",
"chrome://vulpes/content/shell.xhtml",
]
if args.test:
command += ["-marionette", "--remote-allow-system-access", "-new-window", "about:blank"]
proc = None
with (ROOT / "logs/gaia-server.log").open("w") as output:
server = subprocess.Popen(
[
sys.executable,
str(ROOT / "tools/serve-gaia.py"),
*(["--legacy-apps"] if args.legacy_apps else []),
],
stdout=output,
stderr=subprocess.STDOUT,
)
try:
for _ in range(900):
if server.poll() is not None:
raise RuntimeError("Échec du serveur Gaia : logs/gaia-server.log")
try:
with socket.create_connection(("127.0.0.1", 8765), timeout=0.2):
break
except OSError:
time.sleep(0.05)
else:
raise RuntimeError("Le serveur Gaia ne répond pas.")
print(f'Vulpes / Gecko {lock["version"]} — profil {profile}', flush=True)
proc = subprocess.Popen(command, env=env)
result = proc.wait()
if result:
raise RuntimeError(f"Gecko a quitté avec le code {result}")
finally:
if proc and proc.poll() is None:
proc.terminate()
try:
proc.wait(timeout=10)
except subprocess.TimeoutExpired:
proc.kill()
proc.wait()
server.terminate()
server.wait(timeout=10)
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
pass
except (RuntimeError, OSError) as error:
sys.exit(str(error))

206
tools/serve-gaia.py Normal file
View file

@ -0,0 +1,206 @@
#!/usr/bin/env python3
"""Serve packaged Gaia with a distinct loopback origin for every installed app."""
import argparse
import json
import mimetypes
import os
import re
import subprocess
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from urllib.parse import unquote, urlsplit
ROOT = Path(__file__).resolve().parents[1]
parser = argparse.ArgumentParser()
parser.add_argument("--port", type=int, default=8765)
parser.add_argument("--legacy-apps", action="store_true")
args = parser.parse_args()
from project import build_info, validate_assets, release_info
validate_assets()
info = build_info()
info["release"] = release_info()
revision, commit_time = info["revision"], str(info["timestamp"])
(ROOT / "assets/build-info.json").write_text(json.dumps(info))
APPS = ROOT / "assets/webapps"
ORIGINS = {}
REGISTRY = []
pattern = re.compile(r"app://([a-zA-Z0-9_-]+)\.gaiamobile\.org")
def translate(text):
return pattern.sub(lambda m: f"http://{m[1]}.localhost:{args.port}", text)
manifests = sorted(APPS.glob("*/manifest.webapp"))
LEGACY_ROOTS = set()
if args.legacy_apps:
for entry in json.loads((ROOT / "tests/legacy-apps.json").read_text()):
directory = ROOT / "downloads/legacy-apps/apps" / entry["id"]
manifests.append(directory / "manifest.webapp")
LEGACY_ROOTS.add(directory.resolve())
for manifest_path in manifests:
name = manifest_path.parent.name.removesuffix(".gaiamobile.org")
if not re.fullmatch("[a-z0-9_-]+", name):
continue
origin = f"http://{name}.localhost:{args.port}"
manifest = json.loads(translate(manifest_path.read_text()))
ORIGINS[urlsplit(origin).netloc] = manifest_path.parent.resolve()
REGISTRY.append(
{
"id": name,
"origin": origin,
"manifestURL": origin + "/manifest.webapp",
"manifest": manifest,
}
)
ORIGINS[f"theme.localhost:{args.port}"] = ORIGINS[f"default_theme.localhost:{args.port}"]
(ROOT / "assets/registry.json").write_text(
json.dumps(REGISTRY, ensure_ascii=False, indent=2) + "\n"
)
(ROOT / "assets/settings-current-defaults.json").write_text(
translate((ROOT / "assets/settings-defaults.json").read_text())
)
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
root = ORIGINS.get(self.headers.get("Host", "").lower())
if root is None:
self.send_error(421, "Unregistered application host")
return
path = unquote(urlsplit(self.path).path)
if "\x00" in path or "\\" in path or ".." in Path(path).parts:
self.send_error(400)
return
if path == "/_vulpes/platform-config.js":
data = (('window.VulpesPlatform='+json.dumps('tundra' if os.environ.get('VULPES_TUNDRA')=='1' else 'desktop')+';window.VulpesNativeInput='+('true' if os.environ.get('VULPES_TUNDRA')=='1' or os.environ.get('VULPES_TEST_INPUT')=='1' else 'false')+';window.VulpesNativeTelephony=') + ('true' if os.environ.get('VULPES_TUNDRA_RADIO') == '1' or os.environ.get('VULPES_TEST_TELEPHONY') == '1' else 'false') + ';window.VulpesNativeWifi=' + ('true' if os.environ.get('VULPES_TUNDRA_WIFI') == '1' else 'false') + ';').encode()
self.send_response(200)
self.send_header("Content-Type", "text/javascript")
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
return
if path == "/resources/gaia_commit.txt":
data = (revision + "\n" + commit_time + "\n").encode()
self.send_response(200)
self.send_header("Content-Type", "text/plain")
self.send_header("Content-Length", str(len(data)))
self.send_header("Cache-Control", "no-store")
self.end_headers()
self.wfile.write(data)
return
# Only this non-privileged compatibility layer is exposed, never host modules.
if path in [
"/_vulpes/" + name
for name in ["gaia-compat.js", "gaia-input.js", "gaia-services.js", "gaia-styles.js", "gaia-restoration.js", "gaia-wifi.js", "desktop.css", "platform-ui.js", "gaia-camera.js"]
]:
file = ROOT / "host" / path.rsplit("/", 1)[1]
else:
file = (root / path.lstrip("/")).resolve()
if file.is_dir():
file = file / "index.html"
if not file.is_relative_to(root):
self.send_error(403)
return
overrides = {
"system.gaiamobile.org": [
"js/launcher.js",
"js/gaia_scheduler.js",
"js/keyboard_manager.js",
"js/core.js",
"js/rocketbar.js",
]
}
if path.lstrip("/") in overrides.get(root.name, []):
file = (
ROOT
/ "gaia/apps"
/ root.name.removesuffix(".gaiamobile.org")
/ path.lstrip("/")
)
overlay_root = (ROOT / "overrides" / root.name).resolve()
overlay = (overlay_root / path.lstrip("/")).resolve()
if (
path != "/manifest.webapp"
and overlay.is_relative_to(overlay_root)
and overlay.is_file()
):
file = overlay
if path.startswith("/shared/"):
common = (ROOT / "overrides" / path.lstrip("/")).resolve()
if common.is_relative_to((ROOT / "overrides/shared").resolve()) and common.is_file():
file = common
if not file.is_file() and path.startswith("/shared/"):
shared = (ROOT / "gaia" / path.lstrip("/")).resolve()
if shared.is_relative_to((ROOT / "gaia/shared").resolve()):
file = shared
if not file.is_file():
self.send_error(404)
return
data = file.read_bytes()
mime = mimetypes.guess_type(file.name)[0] or "application/octet-stream"
if file.suffix in (".html", ".js", ".css", ".json", ".webapp", ".properties", ".svg"):
text = translate(data.decode("utf-8"))
if file.suffix in (".css", ".js", ".html"):
text = (
text.replace("-moz-calc(", "calc(")
.replace("-moz-box-sizing:", "box-sizing:")
.replace("-moz-plaintext", "plaintext")
.replace(":-moz-dir(", ":dir(")
.replace("offset-inline-start:", "inset-inline-start:")
.replace("offset-inline-end:", "inset-inline-end:")
)
data = text.encode("utf-8")
if root.name == "music.gaiamobile.org" and file.suffix == ".js":
data = data.replace(b"audio.src=null;", b"audio.removeAttribute('src');")
if file.suffix == ".html" and root in LEGACY_ROOTS:
data = data.replace(
b"<head>",
b'<head><script src="/_vulpes/gaia-compat.js"></script><script src="/_vulpes/gaia-wifi.js"></script><script src="/_vulpes/gaia-input.js"></script><script src="/_vulpes/gaia-services.js"></script>',
1,
)
elif file.suffix == ".html" and not (root.name == "search.gaiamobile.org" and path.startswith("/home/")):
data = data.replace(
b"<head>",
b'<head><script src="/_vulpes/platform-config.js"></script><link rel="stylesheet" href="/_vulpes/desktop.css"><script src="/_vulpes/gaia-compat.js"></script><script src="/_vulpes/gaia-wifi.js"></script><script src="/_vulpes/gaia-input.js"></script><script src="/_vulpes/gaia-services.js"></script><script src="/_vulpes/gaia-styles.js"></script><script src="/_vulpes/gaia-restoration.js"></script><script src="/_vulpes/platform-ui.js"></script><script src="/_vulpes/gaia-camera.js"></script>',
1,
)
if (
file.suffix == ".html"
and root.name == "communications.gaiamobile.org"
and "/dialer/" in path
):
data = data.replace(
b"<head>", b'<head><script src="/shared/js/accessibility_helper.js"></script>', 1
)
self.send_response(200)
self.send_header(
"Content-Type", mime + ("; charset=utf-8" if mime.startswith("text/") else "")
)
self.send_header("Content-Length", str(len(data)))
self.send_header("Cache-Control", "no-store")
self.send_header("X-Content-Type-Options", "nosniff")
# Installed Gaia code may use its legacy module compiler, but must not
# gain privileged host rights through inline or remote script injection.
self.send_header(
"Content-Security-Policy",
"script-src 'self' 'unsafe-eval'; object-src 'none'; "
"base-uri 'self'; worker-src 'self' blob:; "
f"frame-ancestors http://*.localhost:{args.port}",
)
origin = self.headers.get("Origin", "")
if urlsplit(origin).netloc in ORIGINS and origin.startswith("http://"):
self.send_header("Access-Control-Allow-Origin", origin)
self.send_header("Vary", "Origin")
self.end_headers()
self.wfile.write(data)
def log_message(self, fmt, *values):
if values and str(values[1]) not in ("200", "304"):
super().log_message(fmt, *values)
server = ThreadingHTTPServer(("127.0.0.1", args.port), Handler)
print(f"Gaia: {len(REGISTRY)} applications; 127.0.0.1:{args.port}", flush=True)
server.serve_forever()

Some files were not shown because too many files have changed in this diff Show more