mirror of
https://github.com/Such-Software/adaptive-multi-protocol-browser.git
synced 2026-10-17 14:31:46 +02:00
Harden route-aware browser lifecycle
This commit is contained in:
@@ -97,6 +97,7 @@ def main(argv: list[str] | None = None) -> int:
|
||||
helper_parser.add_argument("--token", required=True)
|
||||
helper_parser.add_argument("--root", type=Path, default=Path.cwd())
|
||||
helper_parser.add_argument("--config", type=Path, help="Path to an AMPB config file.")
|
||||
helper_parser.add_argument("--watch-pid", type=int, default=0, help=argparse.SUPPRESS)
|
||||
|
||||
args = parser.parse_args(argv)
|
||||
try:
|
||||
@@ -322,6 +323,7 @@ def _cmd_helper(args) -> int:
|
||||
token=args.token,
|
||||
root=args.root,
|
||||
config_path=args.config,
|
||||
watch_pid=args.watch_pid,
|
||||
)
|
||||
return 0
|
||||
|
||||
|
||||
+87
-8
@@ -6,10 +6,12 @@ import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import secrets
|
||||
import signal
|
||||
import shlex
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from .adapters import adapter_for
|
||||
@@ -37,6 +39,7 @@ class RouteHelperLaunch:
|
||||
endpoint: str = "-"
|
||||
token: str = "-"
|
||||
pid: int = 0
|
||||
watch_pid: int = 0
|
||||
command: tuple[str, ...] = ()
|
||||
message: str = "-"
|
||||
|
||||
@@ -191,15 +194,38 @@ def execute_open(open_plan: OpenPlan, *, root: Path | None = None) -> OpenPlan:
|
||||
message=f"browser runtime not found: {spec.runtime_path}",
|
||||
)
|
||||
|
||||
route_helper = _start_route_helper(root) if spec.route_aware else RouteHelperLaunch("disabled")
|
||||
route_helper = _route_helper_launch_plan(root) if spec.route_aware else RouteHelperLaunch("disabled")
|
||||
_write_profile(root, spec, route_helper=route_helper)
|
||||
process = subprocess.Popen(spec.command, cwd=str(root)) # noqa: S603
|
||||
launch_spec = replace(spec, command=_execution_command(root, spec))
|
||||
process = subprocess.Popen(launch_spec.command, cwd=str(root), start_new_session=True) # noqa: S603
|
||||
if spec.route_aware:
|
||||
route_helper = _start_route_helper(root, planned=route_helper, watch_pid=process.pid)
|
||||
exit_code = _immediate_exit_code(process)
|
||||
if exit_code is not None:
|
||||
helper_status = route_helper.status
|
||||
helper_message = route_helper.message
|
||||
if spec.route_aware:
|
||||
helper_status = _stop_route_helper(route_helper)
|
||||
helper_message = "stopped route helper after browser exited immediately"
|
||||
return replace(
|
||||
open_plan,
|
||||
dry_run=False,
|
||||
launch_spec=launch_spec,
|
||||
status="browser-exited",
|
||||
browser_pid=process.pid,
|
||||
message=f"browser exited immediately with code {exit_code}",
|
||||
route_helper_status=helper_status,
|
||||
route_helper_endpoint=route_helper.endpoint,
|
||||
route_helper_pid=route_helper.pid,
|
||||
route_helper_message=helper_message,
|
||||
)
|
||||
message = "launched bundled browser"
|
||||
if spec.route_aware:
|
||||
message = f"launched bundled browser with route helper {route_helper.status}"
|
||||
return replace(
|
||||
open_plan,
|
||||
dry_run=False,
|
||||
launch_spec=launch_spec,
|
||||
status="launched",
|
||||
browser_pid=process.pid,
|
||||
message=message,
|
||||
@@ -304,7 +330,7 @@ def _launch_spec_for(
|
||||
return None
|
||||
runtime_path = _runtime_path(config)
|
||||
user_js_path = str(Path(profile_path) / "user.js")
|
||||
command = (runtime_path, "-no-remote", "-profile", profile_path, browse_plan.route.normalized)
|
||||
command = (runtime_path, "--new-instance", "--profile", profile_path, browse_plan.route.normalized)
|
||||
prefs = _prefs_for(browse_plan, route_aware=route_aware)
|
||||
pac_path = str(Path(profile_path) / ROUTE_AWARE_PAC_NAME) if route_aware else "-"
|
||||
pac_content = _route_aware_pac() if route_aware else ""
|
||||
@@ -633,10 +659,35 @@ def _format_pref(name: str, value: str | int | bool) -> str:
|
||||
return f"user_pref({json.dumps(name)}, {literal});"
|
||||
|
||||
|
||||
def _start_route_helper(root: Path) -> RouteHelperLaunch:
|
||||
def _route_helper_launch_plan(root: Path) -> RouteHelperLaunch:
|
||||
port = _free_loopback_port()
|
||||
token = secrets.token_urlsafe(24)
|
||||
endpoint = f"http://127.0.0.1:{port}/"
|
||||
return RouteHelperLaunch(
|
||||
"planned",
|
||||
endpoint=endpoint,
|
||||
token=token,
|
||||
command=_route_helper_command(root=root, port=port, token=token),
|
||||
)
|
||||
|
||||
|
||||
def _start_route_helper(
|
||||
root: Path,
|
||||
*,
|
||||
planned: RouteHelperLaunch | None = None,
|
||||
watch_pid: int = 0,
|
||||
) -> RouteHelperLaunch:
|
||||
helper = planned or _route_helper_launch_plan(root)
|
||||
port = _endpoint_host_port(helper.endpoint)[1]
|
||||
command = _route_helper_command(root=root, port=port, token=helper.token, watch_pid=watch_pid)
|
||||
try:
|
||||
process = subprocess.Popen(command, cwd=str(root), start_new_session=True) # noqa: S603
|
||||
except OSError as exc:
|
||||
return replace(helper, status="start-failed", command=command, watch_pid=watch_pid, message=str(exc))
|
||||
return replace(helper, status="started", pid=process.pid, watch_pid=watch_pid, command=command, message="-")
|
||||
|
||||
|
||||
def _route_helper_command(*, root: Path, port: int, token: str, watch_pid: int = 0) -> tuple[str, ...]:
|
||||
command = (
|
||||
sys.executable,
|
||||
"-m",
|
||||
@@ -651,11 +702,39 @@ def _start_route_helper(root: Path) -> RouteHelperLaunch:
|
||||
"--root",
|
||||
str(root),
|
||||
)
|
||||
if watch_pid > 0:
|
||||
command = (*command, "--watch-pid", str(watch_pid))
|
||||
return command
|
||||
|
||||
|
||||
def _execution_command(root: Path, spec: BrowserLaunchSpec) -> tuple[str, ...]:
|
||||
command = list(spec.command)
|
||||
try:
|
||||
process = subprocess.Popen(command, cwd=str(root), start_new_session=True) # noqa: S603
|
||||
except OSError as exc:
|
||||
return RouteHelperLaunch("start-failed", endpoint=endpoint, token=token, command=command, message=str(exc))
|
||||
return RouteHelperLaunch("started", endpoint=endpoint, token=token, pid=process.pid, command=command)
|
||||
profile_index = command.index("--profile") + 1
|
||||
except ValueError:
|
||||
return tuple(command)
|
||||
if profile_index >= len(command):
|
||||
return tuple(command)
|
||||
command[profile_index] = str(_path_from(root, command[profile_index]))
|
||||
return tuple(command)
|
||||
|
||||
|
||||
def _stop_route_helper(route_helper: RouteHelperLaunch) -> str:
|
||||
if route_helper.pid <= 0:
|
||||
return route_helper.status
|
||||
try:
|
||||
os.kill(route_helper.pid, signal.SIGTERM)
|
||||
except OSError:
|
||||
return "stop-failed"
|
||||
return "stopped"
|
||||
|
||||
|
||||
def _immediate_exit_code(process: subprocess.Popen, *, wait_seconds: float = 1.0) -> int | None:
|
||||
time.sleep(wait_seconds)
|
||||
return_code = process.poll()
|
||||
if isinstance(return_code, int):
|
||||
return return_code
|
||||
return None
|
||||
|
||||
|
||||
def _free_loopback_port() -> int:
|
||||
|
||||
@@ -2,7 +2,10 @@ from __future__ import annotations
|
||||
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import threading
|
||||
import time
|
||||
from typing import Any
|
||||
|
||||
from .config import AppConfig, load_config
|
||||
@@ -40,12 +43,16 @@ def serve_route_helper(
|
||||
token: str,
|
||||
root: Path,
|
||||
config_path: Path | None = None,
|
||||
watch_pid: int = 0,
|
||||
) -> None:
|
||||
config = load_config(root, config_path)
|
||||
server = _RouteHelperServer((host, port), _RouteHelperHandler)
|
||||
server.token = token
|
||||
server.root_path = root
|
||||
server.config = config
|
||||
if watch_pid > 0:
|
||||
watcher = threading.Thread(target=_shutdown_when_pid_exits, args=(server, watch_pid), daemon=True)
|
||||
watcher.start()
|
||||
server.serve_forever()
|
||||
|
||||
|
||||
@@ -133,3 +140,19 @@ def _error_response(status: str, message: str) -> dict[str, Any]:
|
||||
|
||||
def _string(value: object) -> str:
|
||||
return value if isinstance(value, str) else ""
|
||||
|
||||
|
||||
def _shutdown_when_pid_exits(server: _RouteHelperServer, pid: int, *, interval_seconds: float = 1.0) -> None:
|
||||
while _pid_exists(pid):
|
||||
time.sleep(interval_seconds)
|
||||
server.shutdown()
|
||||
|
||||
|
||||
def _pid_exists(pid: int) -> bool:
|
||||
if pid <= 0:
|
||||
return False
|
||||
try:
|
||||
os.kill(pid, 0)
|
||||
except OSError:
|
||||
return False
|
||||
return True
|
||||
|
||||
+5
-4
@@ -1,6 +1,6 @@
|
||||
# Open Flow
|
||||
|
||||
> Status: draft | Updated 2026-07-05 | Applies to: AMPB users and implementers
|
||||
> Status: draft | Updated 2026-07-08 | Applies to: AMPB users and implementers
|
||||
|
||||
`ampbrowser open` prepares a safe launch plan for one URL. It routes the URL, checks only
|
||||
the selected transport, and reports whether the browser can open immediately or needs a
|
||||
@@ -36,9 +36,10 @@ launches through the same transport runner after approval.
|
||||
|
||||
`ampbrowser open <url> --route-aware --launch` creates one desktop profile for clearnet,
|
||||
Tor, and I2P. The profile uses a PAC file for `.onion` and `.i2p` routing, installs the
|
||||
AMPB route-helper extension, and starts a loopback AMPB helper. If a user clicks an
|
||||
alternate-network link before its local transport is ready, the extension shows a setup
|
||||
page and asks the helper to start the AMPB-managed transport after approval.
|
||||
AMPB route-helper extension, and starts a token-gated loopback helper tied to the browser
|
||||
process. If a user clicks an alternate-network link before its local transport is ready,
|
||||
the extension shows a setup page and asks the helper to start the AMPB-managed transport
|
||||
after approval.
|
||||
|
||||
## Examples
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Transport Management
|
||||
|
||||
> Status: draft | Updated 2026-07-07 | Applies to: AMPB transport adapters
|
||||
> Status: draft | Updated 2026-07-08 | Applies to: AMPB transport adapters
|
||||
|
||||
Transport management follows one rule: use what is already healthy, and manage missing
|
||||
transports only after the user opens a URL that needs them and approves setup.
|
||||
@@ -20,7 +20,8 @@ user or system daemons.
|
||||
Route-aware desktop launches add a local helper process for in-browser setup prompts. The
|
||||
helper accepts token-gated loopback requests from the AMPB profile extension, reports
|
||||
transport status, and starts only supported AMPB-managed transports. It does not expose a
|
||||
public network listener or manage adopted daemons.
|
||||
public network listener or manage adopted daemons. The helper watches the browser process
|
||||
and exits when that isolated browser exits.
|
||||
|
||||
## Lifecycle
|
||||
|
||||
|
||||
@@ -118,6 +118,14 @@ class CliOpenTest(unittest.TestCase):
|
||||
self.assertIn("profile_path=.ampb/profiles/route-aware", output)
|
||||
self.assertIn("pac_path=.ampb/profiles/route-aware/ampb-proxy.pac", output)
|
||||
|
||||
def test_hidden_helper_command_passes_watch_pid(self) -> None:
|
||||
with patch("ampbrowser.cli.serve_route_helper") as helper:
|
||||
code = main(["helper", "--port", "44001", "--token", "test-token", "--watch-pid", "9876"])
|
||||
|
||||
self.assertEqual(0, code)
|
||||
helper.assert_called_once()
|
||||
self.assertEqual(9876, helper.call_args.kwargs["watch_pid"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
+62
-5
@@ -24,7 +24,7 @@ class PrepareOpenTest(unittest.TestCase):
|
||||
self.assertEqual("/opt/ampb/firefox", plan.launch_spec.runtime_path)
|
||||
self.assertEqual(".ampb/profiles/clearnet/user.js", plan.launch_spec.user_js_path)
|
||||
self.assertEqual(
|
||||
("/opt/ampb/firefox", "-no-remote", "-profile", ".ampb/profiles/clearnet", "https://wownero.org"),
|
||||
("/opt/ampb/firefox", "--new-instance", "--profile", ".ampb/profiles/clearnet", "https://wownero.org"),
|
||||
plan.launch_spec.command,
|
||||
)
|
||||
|
||||
@@ -116,8 +116,15 @@ class PrepareOpenTest(unittest.TestCase):
|
||||
self.assertFalse(launched.dry_run)
|
||||
self.assertEqual(popen.return_value.pid, launched.browser_pid)
|
||||
popen.assert_called_once_with(
|
||||
(str(runtime), "-no-remote", "-profile", ".ampb/profiles/clearnet", "https://wownero.org"),
|
||||
(
|
||||
str(runtime),
|
||||
"--new-instance",
|
||||
"--profile",
|
||||
str(root / ".ampb/profiles/clearnet"),
|
||||
"https://wownero.org",
|
||||
),
|
||||
cwd=str(root),
|
||||
start_new_session=True,
|
||||
)
|
||||
user_js = root / ".ampb/profiles/clearnet/user.js"
|
||||
self.assertTrue(user_js.exists())
|
||||
@@ -148,8 +155,15 @@ class PrepareOpenTest(unittest.TestCase):
|
||||
self.assertEqual("http://127.0.0.1:44001/", launched.route_helper_endpoint)
|
||||
self.assertEqual(4321, launched.route_helper_pid)
|
||||
popen.assert_called_once_with(
|
||||
(str(runtime), "-no-remote", "-profile", ".ampb/profiles/route-aware", "https://ampgateway.site/"),
|
||||
(
|
||||
str(runtime),
|
||||
"--new-instance",
|
||||
"--profile",
|
||||
str(root / ".ampb/profiles/route-aware"),
|
||||
"https://ampgateway.site/",
|
||||
),
|
||||
cwd=str(root),
|
||||
start_new_session=True,
|
||||
)
|
||||
profile = root / ".ampb/profiles/route-aware"
|
||||
user_js = (profile / "user.js").read_text(encoding="utf-8")
|
||||
@@ -166,8 +180,9 @@ class PrepareOpenTest(unittest.TestCase):
|
||||
background = (extension / "background.js").read_text(encoding="utf-8")
|
||||
setup = (extension / "setup.html").read_text(encoding="utf-8")
|
||||
self.assertIn("webNavigation", manifest)
|
||||
self.assertIn("http://127.0.0.1:44001/", background)
|
||||
self.assertIn("test-token", background)
|
||||
self.assertIn("http://127.0.0.1:", background)
|
||||
self.assertNotIn("__AMPB_ROUTE_HELPER_URL__", background)
|
||||
self.assertNotIn("__AMPB_ROUTE_HELPER_TOKEN__", background)
|
||||
self.assertIn("Set Up Transport", setup)
|
||||
|
||||
def test_execute_open_blocks_when_runtime_is_missing(self) -> None:
|
||||
@@ -179,6 +194,48 @@ class PrepareOpenTest(unittest.TestCase):
|
||||
self.assertEqual("runtime-missing", launched.status)
|
||||
self.assertIn("browser runtime not found", launched.message)
|
||||
|
||||
def test_route_aware_launch_stops_helper_when_browser_exits_immediately(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
runtime = root / "firefox"
|
||||
runtime.write_text("#!/bin/sh\n", encoding="utf-8")
|
||||
config = AppConfig(runtime_path=str(runtime), transport_modes={})
|
||||
plan = prepare_open("https://ampgateway.site/", config=config, route_aware=True)
|
||||
helper = RouteHelperLaunch("started", endpoint="http://127.0.0.1:44001/", token="test-token", pid=4321)
|
||||
|
||||
with patch("ampbrowser.launch._start_route_helper", return_value=helper):
|
||||
with patch("ampbrowser.launch._stop_route_helper", return_value="stopped") as stop_helper:
|
||||
with patch("ampbrowser.launch.subprocess.Popen") as popen:
|
||||
popen.return_value.pid = 9876
|
||||
popen.return_value.poll.return_value = 1
|
||||
launched = execute_open(plan, root=root)
|
||||
|
||||
self.assertEqual("browser-exited", launched.status)
|
||||
self.assertEqual(9876, launched.browser_pid)
|
||||
self.assertEqual("stopped", launched.route_helper_status)
|
||||
self.assertIn("browser exited immediately", launched.message)
|
||||
stop_helper.assert_called_once_with(helper)
|
||||
|
||||
def test_route_aware_launch_starts_helper_with_browser_pid(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
runtime = root / "firefox"
|
||||
runtime.write_text("#!/bin/sh\n", encoding="utf-8")
|
||||
config = AppConfig(runtime_path=str(runtime), transport_modes={})
|
||||
plan = prepare_open("https://ampgateway.site/", config=config, route_aware=True)
|
||||
helper = RouteHelperLaunch("started", endpoint="http://127.0.0.1:44001/", token="test-token", pid=4321)
|
||||
|
||||
with patch("ampbrowser.launch._start_route_helper", return_value=helper) as start_helper:
|
||||
with patch("ampbrowser.launch.subprocess.Popen") as popen:
|
||||
popen.return_value.pid = 9876
|
||||
popen.return_value.poll.return_value = None
|
||||
launched = execute_open(plan, root=root)
|
||||
|
||||
self.assertEqual("launched", launched.status)
|
||||
start_helper.assert_called_once()
|
||||
self.assertEqual(9876, start_helper.call_args.kwargs["watch_pid"])
|
||||
self.assertEqual("planned", start_helper.call_args.kwargs["planned"].status)
|
||||
|
||||
def test_custom_state_dir_changes_profile_path(self) -> None:
|
||||
config = AppConfig(state_dir=".local/ampb", transport_modes={})
|
||||
|
||||
|
||||
Reference in New Issue
Block a user