The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
OS: open Connections from a minimal browser start page (#1033)
Dee612f700567cd
diff --git a/.github/workflows/os.yml b/.github/workflows/os.ymlindex d2eb542bf..642171c83 100644--- a/.github/workflows/os.yml+++ b/.github/workflows/os.yml@@ -293,7 +293,7 @@ jobs:if: ${{ inputs.checks == 'browser' }}env:OS_MEMORY_MIB: ${{ inputs.memory_mib || '2048' }}- run: python3 os/tests/browser_vm.py --iso os/dist/*.iso --firmware '${{ matrix.firmware }}' --memory-mib "$OS_MEMORY_MIB" --wlrctl /usr/bin/wlrctl --browser-script os/root/usr/bin/hn-browser --compositor-config os/root/usr/share/harness-os/labwc/rc.xml ${{ inputs.browser_memory && '--memory-profile --zram-config os/root/etc/systemd/zram-generator.conf' || '' }}+ run: python3 os/tests/browser_vm.py --iso os/dist/*.iso --firmware '${{ matrix.firmware }}' --memory-mib "$OS_MEMORY_MIB" --wlrctl /usr/bin/wlrctl --browser-script os/root/usr/bin/hn-browser --compositor-config os/root/usr/share/harness-os/labwc/rc.xml --home-source . ${{ inputs.browser_memory && '--memory-profile --zram-config os/root/etc/systemd/zram-generator.conf' || '' }}- name: Exercise browser-active suspend, unlock and input recoveryif: ${{ inputs.checks == 'browser-suspend' }}run: timeout 12m python3 os/tests/browser_vm.py --iso os/dist/*.iso --firmware uefi --memory-mib 2048 --check suspend --wlrctl /usr/bin/wlrctl --browser-script os/root/usr/bin/hn-browser --compositor-config os/root/usr/share/harness-os/labwc/rc.xmldiff --git a/os/README.md b/os/README.mdindex 971c4cc1c..87cd7dabc 100644--- a/os/README.md+++ b/os/README.md@@ -79,8 +79,10 @@ for requirements and remaining work.## Connected accounts-Run `harness connections` to open the local Connectors page and sign in to a-service in the browser. 21 services (Linear, Notion, Canva, Atlassian, GitLab,+Open **Connections** from the browser's New Tab page, or run `harness connections`.+The local start page is removable in Chromium's extension settings and preserves+existing New Tab customizations. Sign in to a service on the local Connectors page.+21 services (Linear, Notion, Canva, Atlassian, GitLab,Figma…) sign in directly from this computer; GitHub, Slack, Google, Microsoft365 and a few others sign in through the Harness account. Claude Code, Codexand OpenCode then get each service as an MCP server on a local bridge, whichdiff --git a/os/browser-home/README.md b/os/browser-home/README.mdnew file mode 100644index 000000000..d173bfa75--- /dev/null+++ b/os/browser-home/README.md@@ -0,0 +1,58 @@+# Browser start page++The PC OS packages a small, removable Chromium Manifest V3 extension. It opens on+New Tab and the browser's default startup, with one action: **Connections**.+The launcher registers it for the local user before opening Chromium, only when+their existing profiles have no custom New Tab extension. Each launch also checks+for later customizations or imported profiles; those restrict the descriptor to+updating existing installations only. Startup preferences, bookmarks and explicit+URLs stay untouched. A user can disable/remove it in `chrome://extensions` or+choose another New Tab extension. Chromium remembers removal across OS updates.++The extension is locally signed rather than published in the Chrome Web Store.+Chromium may flag its source in Extensions' Safety Check; that browser warning+is preserved, along with the controls to disable or remove it.++The extension has only `nativeMessaging` permission. It has no network access,+content scripts, history, tab or bookmark permissions. Clicking+Connections starts a short-lived native host which accepts only the Connections+action or install acknowledgment from the exact extension origin. The host+authenticates or starts the existing per-user Connections helper and opens its+temporary capability URL through the OS browser launcher. The page opens in a+new tab; no capability is sent back to the extension. There is+no fixed local port, unauthenticated credential endpoint or shell-command bridge.++On a never-used default profile only, a temporary headless Chromium process lets+the external extension install before the first visible window. An install-only+worker acknowledges readiness through the native host and a private user runtime+socket. The launcher then closes only that child through private CDP pipes; there+is no debugging port. Existing profiles, explicit URLs and custom-profile options+skip this step. Preparation is bounded and failure falls back to normal browsing.+The worker has no startup listener, timers or persistent connection.++The signed `home.crx` is committed alongside its source. Ordinary OS builds need+no private key or browser build. `os/tools/browser_home_payload.py` verifies the+CRX3 RSA signature, extension identity and every bundled file against the source+before packaging it. This uses OpenSSL only on the build/test host; the installed+bridge uses Python's standard library.++To change the page, increment `extension/manifest.json`'s version, then pack it+with Chromium using the existing **private** extension signing key:++```sh+chromium --user-data-dir=/tmp/harness-home-pack --no-message-box \+ --pack-extension="$PWD/os/browser-home/extension" \+ --pack-extension-key=/secure/path/harness-home.pem+mv os/browser-home/extension.crx os/browser-home/home.crx+chmod 644 os/browser-home/home.crx+python3 os/tools/browser_home_payload.py+```++Keep the private key in secure maintainer storage, backed up before publication;+never commit it or ship it in an image. Reuse the same key: changing it changes+the extension ID and loses the browser's remembered customization. Package+updates take effect on the next browser launch; never terminate a running browser+or rewrite a live browser profile to activate the page.++The experimental Fedora session does not yet include this browser integration.+Validate its native Chromium paths and removable install before adding it there.diff --git a/os/browser-home/extension/home.js b/os/browser-home/extension/home.jsnew file mode 100644index 000000000..4125a5c79--- /dev/null+++ b/os/browser-home/extension/home.js@@ -0,0 +1,24 @@+"use strict";++const connections = document.querySelector("#connections");+const notice = document.querySelector("#notice");+connections.addEventListener("click", async () => {+ if (connections.disabled) return;+ connections.disabled = true;+ notice.textContent = "Opening Connections…";+ try {+ const response = await chrome.runtime.sendNativeMessage("ai.autonomous.harness_home", {action: "connections"});+ if (response.ok !== true) throw new Error("Could not open local page");+ notice.textContent = "Opened in a new tab.";+ } catch {+ notice.textContent = "Couldn’t open Connections. Try again, or ask your agent to open Connections.";+ } finally {+ connections.disabled = false;+ connections.focus();+ }+});+// Restore the action after navigating Back, including a page restored from cache.+window.addEventListener("pageshow", () => {+ connections.disabled = false;+ notice.textContent = "";+});diff --git a/os/browser-home/extension/index.html b/os/browser-home/extension/index.htmlnew file mode 100644index 000000000..ef6f0ff3d--- /dev/null+++ b/os/browser-home/extension/index.html@@ -0,0 +1,20 @@+<!doctype html>+<html lang="en">+<head>+ <meta charset="utf-8">+ <meta name="viewport" content="width=device-width,initial-scale=1">+ <title>New Tab</title>+ <link rel="stylesheet" href="style.css">+ <script src="home.js" defer></script>+</head>+<body>+ <main>+ <h1>Harness<span aria-hidden="true">_</span></h1>+ <button id="connections" type="button">+ <span><strong>Connections</strong><span class="detail">Connect accounts. Work with any agent.</span></span>+ <span class="arrow" aria-hidden="true">↗</span>+ </button>+ <p id="notice" role="status" aria-live="polite"></p>+ </main>+</body>+</html>diff --git a/os/browser-home/extension/installed.js b/os/browser-home/extension/installed.jsnew file mode 100644index 000000000..3933f7384--- /dev/null+++ b/os/browser-home/extension/installed.js@@ -0,0 +1,9 @@+"use strict";++// Acknowledge the very first installation so the OS can open its first window.+// No startup listener, tab access, timers, or persistent native connection.+chrome.runtime.onInstalled.addListener(({reason}) => {+ if (reason === "install") {+ chrome.runtime.sendNativeMessage("ai.autonomous.harness_home", {action: "installed"}).catch(() => {});+ }+});diff --git a/os/browser-home/extension/manifest.json b/os/browser-home/extension/manifest.jsonnew file mode 100644index 000000000..a99e55b3e--- /dev/null+++ b/os/browser-home/extension/manifest.json@@ -0,0 +1,19 @@+{+ "manifest_version": 3,+ "name": "Harness start page",+ "version": "1.0.2",+ "description": "Connections for the agents on this computer.",+ "key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsQQ+0kwD+hEd/GjjkVYhJBiB4wMc5yc/rZTaWRCo9kI8nZ9etPXyRoIXIhH/9NJ/TgKH2edapAwzzX3Z9FIs6bZqf3O+kYveflmOLKyg+UVnRup9SrKejAtMyKKpjcOsxbhy2vNS9/sA/TEOLAiMBHGXJedD4xdGYvH8BcomuduyWLF8z3BIsOUqQK98Y+pswVu8m+D5tJFt8Wswlr3cqM5N+8wEMiIrmDnZSeNgjCX5KkxtxNhMXfcRiY9s3OterHwzJdMUvdIuDEKIJyEdtea1bl0h3tcTWyoNADmELfGv2OUIuE6Wikj/a183R/RwD5avGjU73mFp7lrsahOfQwIDAQAB",+ "permissions": [+ "nativeMessaging"+ ],+ "background": {+ "service_worker": "installed.js"+ },+ "chrome_url_overrides": {+ "newtab": "index.html"+ },+ "content_security_policy": {+ "extension_pages": "default-src 'none'; script-src 'self'; style-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'"+ }+}diff --git a/os/browser-home/extension/style.css b/os/browser-home/extension/style.cssnew file mode 100644index 000000000..0e90bf787--- /dev/null+++ b/os/browser-home/extension/style.css@@ -0,0 +1,11 @@+:root{color-scheme:dark;font:16px/1.6 ui-monospace,SFMono-Regular,Consolas,monospace;color:#e7e8de;background:#11140f}+*{box-sizing:border-box}+body{margin:0;min-height:100vh;min-height:100svh;display:grid;align-items:center}+main{width:min(64ch,100%);margin:0 auto;padding:48px 32px}+h1{font:inherit;font-size:28px;line-height:1.2;font-weight:600;letter-spacing:-.04em;margin:0 0 48px}+h1 span{color:#d9f69c}+button{font:inherit;color:inherit;background:transparent;width:100%;border:0;border-top:1px solid #353c2b;border-bottom:1px solid #353c2b;padding:24px 0;text-align:left;display:flex;align-items:center;justify-content:space-between;gap:24px;cursor:pointer}+strong{font-weight:500}.detail{display:block;margin-top:8px;font-size:14px;color:#a1a593}.arrow{color:#d9f69c;font-size:24px}+button:hover strong{color:#d9f69c}button:focus-visible{outline:2px solid #d9f69c;outline-offset:8px}+button:disabled{cursor:wait;opacity:.65}#notice{min-height:3.2em;font-size:14px;color:#a1a593;margin:24px 0 0}+@media(max-width:480px){main{padding:32px 24px}.detail{max-width:27ch}}diff --git a/os/browser-home/home.crx b/os/browser-home/home.crxnew file mode 100644index 000000000..6dafd75c7Binary files /dev/null and b/os/browser-home/home.crx differdiff --git a/os/browser_home.py b/os/browser_home.pynew file mode 100644index 000000000..ce3ba8716--- /dev/null+++ b/os/browser_home.py@@ -0,0 +1,75 @@+#!/usr/bin/python3+"""One-shot native message bridge for the bundled browser start page.++No HTTP endpoint, background service, arbitrary commands or credential API.+Chromium starts this only for the bundled extension's native message.+"""+import json+from pathlib import Path+import struct+import subprocess+import sys++MAX_MESSAGE = 1024+HOST_MANIFEST = Path('/etc/chromium/native-messaging-hosts/ai.autonomous.harness_home.json')+++def open_connections():+ sys.path.insert(0, '/usr/lib/harness-os/connections')+ import connections+ # Keep the capability inside the native path. Browser-initiated navigation+ # is cross-site; the existing OS launcher opens a trusted local tab without+ # weakening the Connections server's fetch/origin restrictions.+ subprocess.run(['/usr/bin/hn-browser', connections.page_url()], check=True,+ stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,+ stderr=subprocess.DEVNULL, timeout=30)+++def read_message(stream):+ header = stream.read(4)+ if len(header) != 4:+ raise ValueError('Missing message')+ length = struct.unpack('=I', header)[0]+ if not 0 < length <= MAX_MESSAGE:+ raise ValueError('Invalid message length')+ raw = stream.read(length)+ if len(raw) != length:+ raise ValueError('Incomplete message')+ message = json.loads(raw)+ if message not in [{'action': 'connections'}, {'action': 'installed'}]:+ raise ValueError('Unknown action')+ return message+++def reply(stream, data):+ raw = json.dumps(data, separators=(',', ':')).encode()+ stream.write(struct.pack('=I', len(raw)) + raw)+ stream.flush()+++def main(argv, source, destination, *, manifest=HOST_MANIFEST, launch=None, ready=None):+ try:+ allowed = json.loads(manifest.read_text())['allowed_origins']+ if len(argv) != 1 or argv[0] not in allowed:+ return 1+ message = read_message(source)+ if message == {'action': 'installed'}:+ if ready is None:+ import browser_profile+ ready = browser_profile.installed+ ready()+ reply(destination, {'ok': True})+ return 0+ if launch is None:+ launch = open_connections+ launch()+ reply(destination, {'ok': True})+ return 0+ except Exception:+ # Never relay exception text, account names or local paths to the browser.+ reply(destination, {'error': 'Could not open Connections.'})+ return 1+++if __name__ == '__main__':+ sys.exit(main(sys.argv[1:], sys.stdin.buffer, sys.stdout.buffer))diff --git a/os/browser_profile.py b/os/browser_profile.pynew file mode 100644index 000000000..e8c76bc3e--- /dev/null+++ b/os/browser_profile.py@@ -0,0 +1,225 @@+#!/usr/bin/python3+"""Offer the OS start page without replacing an existing New Tab customization.++Only our supported external-extension descriptor is written. Browser preferences,+bookmarks, acknowledgement/disable records and other extensions are read-only.+"""+import json+from contextlib import contextmanager+import fcntl+import os+from pathlib import Path+import re+import signal+import socket+import subprocess+import sys+import tempfile+import time++PACKAGE = Path('/usr/share/harness-os/browser-home/extension.json')+++def startup_socket():+ return Path('/run/user') / str(os.getuid()) / 'harness-browser-start' / 'ready'+++def installed():+ """One install-only acknowledgment; no persistent helper or browser access."""+ with socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) as connection:+ connection.sendto(b'ready', str(startup_socket()))+++def pristine(root):+ return (not (root / 'Local State').exists() and+ not (root / 'SingletonLock').is_symlink() and+ not any(root.glob('*/Preferences')) and+ not any(root.glob('*/Secure Preferences')))+++@contextmanager+def startup_guard(timeout=20):+ """All launcher requests wait until an owned primer has fully closed."""+ directory = startup_socket().parent+ directory.mkdir(mode=0o700, parents=False, exist_ok=True)+ with (directory / 'lock').open('a') as lock:+ limit = time.monotonic() + timeout+ while True:+ try:+ fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)+ break+ except BlockingIOError:+ if time.monotonic() >= limit:+ raise TimeoutError('Browser is still starting. Try again.')+ time.sleep(.02)+ yield directory+++def prime(root, *, deadline_seconds=8):+ """Let a new profile finish installing its page before opening a window.++ Only a browser we start in an unused profile is controlled here. CDP stays+ on private child pipes, never a listening port. Ordinary launches and every+ existing profile skip this one-time step entirely. Caller holds startup_guard+ until this child is closed and the normal launch has been handed off.+ """+ endpoint = startup_socket()+ browser = None+ bound = False+ try:+ endpoint.parent.mkdir(mode=0o700, parents=False, exist_ok=True)+ if not pristine(root):+ return False+ endpoint.unlink(missing_ok=True)+ with socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) as ready:+ ready.bind(str(endpoint))+ bound = True+ endpoint.chmod(0o600)+ # The shell only maps Chromium's documented pipe descriptors.+ # All command text is constant; no URL/user input is interpolated.+ browser = subprocess.Popen([+ '/bin/sh', '-c',+ 'exec /usr/bin/chromium --headless --no-first-run '+ '--no-default-browser-check --remote-debugging-pipe '+ '--user-data-dir="$1" about:blank 3<&0 4>&1',+ 'harness-browser-start', str(root),+ ], stdin=subprocess.PIPE, stdout=subprocess.PIPE,+ stderr=subprocess.DEVNULL, start_new_session=True)+ ready.settimeout(deadline_seconds)+ return ready.recv(64) == b'ready'+ except (OSError, ValueError, subprocess.SubprocessError):+ return False # Optional preparation must never prevent normal browsing.+ finally:+ if browser is not None:+ try:+ if browser.poll() is None:+ browser.stdin.write(b'{"id":1,"method":"Browser.close"}\0')+ browser.stdin.flush()+ browser.wait(timeout=3)+ except (OSError, subprocess.TimeoutExpired):+ # This group belongs only to the child created above. Never+ # kill Chromium by name or touch an existing browser process.+ try:+ if browser.poll() is None:+ os.killpg(browser.pid, signal.SIGTERM)+ browser.wait(timeout=2)+ except subprocess.TimeoutExpired:+ try:+ os.killpg(browser.pid, signal.SIGKILL)+ browser.wait(timeout=2)+ except (OSError, subprocess.TimeoutExpired):+ pass+ except OSError:+ pass+ finally:+ for pipe in [browser.stdin, browser.stdout]:+ try:+ pipe.close()+ except OSError:+ pass+ if bound:+ try:+ endpoint.unlink(missing_ok=True)+ except OSError:+ pass+++def read_json(path):+ if path.stat().st_size > 16 * 1024 * 1024:+ raise ValueError('Oversized browser preferences')+ data = json.loads(path.read_text())+ if not isinstance(data, dict):+ raise ValueError('Invalid browser preferences')+ return data+++def customized(root, extension_id):+ for pattern in ['*/Preferences', '*/Secure Preferences']:+ for path in root.glob(pattern):+ extensions = read_json(path).get('extensions', {})+ for entry in extensions.get('chrome_url_overrides', {}).get('newtab', []):+ url = entry.get('entry', '') if isinstance(entry, dict) else entry+ if not isinstance(url, str) or not url.startswith('chrome-extension://' + extension_id + '/'):+ return True+ for other_id, entry in extensions.get('settings', {}).items():+ if (other_id != extension_id and+ 'newtab' in entry.get('manifest', {}).get('chrome_url_overrides', {})):+ return True+ return False+++def prepare(root, package=PACKAGE):+ try:+ record = read_json(package)+ extension_id = record['extension_id']+ if not re.fullmatch('[a-p]{32}', extension_id):+ return False+ descriptor = dict(record['descriptor'])+ target = root / 'External Extensions' / (extension_id + '.json')+ if target.is_symlink():+ return False+ previous = None+ if target.exists():+ previous = read_json(target)+ if previous.get('external_crx') != descriptor['external_crx']:+ return False # This file is no longer ours to update.+ try:+ custom = customized(root, extension_id)+ except (OSError, ValueError, TypeError, AttributeError):+ custom = True # An unreadable profile is never permission to replace it.+ if custom and previous is None:+ return False+ if custom or (previous and previous.get('keep_if_present')):+ # Descriptors are shared across profiles. An imported profile or a+ # choice made after registration must not acquire a new override.+ # Chromium still updates copies already installed in other profiles.+ descriptor['keep_if_present'] = True+ if previous == descriptor:+ return True+ target.parent.mkdir(parents=True, exist_ok=True)+ temporary = None+ try:+ with tempfile.NamedTemporaryFile(dir=target.parent, mode='w', delete=False) as out:+ temporary = Path(out.name)+ json.dump(descriptor, out)+ out.write('\n')+ temporary.replace(target)+ finally:+ if temporary is not None:+ temporary.unlink(missing_ok=True)+ return True+ except (OSError, ValueError, KeyError, TypeError, AttributeError):+ return False # An optional start page must never prevent browsing.+++def launch(args, *, execute=None, lock_timeout=20):+ command = ['systemd-run', '--user', '--quiet', '--collect', '/usr/bin/chromium',+ '--ozone-platform=wayland', '--start-maximized', '--no-first-run',+ '--no-default-browser-check', *args]+ if execute is None:+ execute = lambda command: subprocess.run(command, check=False).returncode+ try:+ with startup_guard(lock_timeout) as directory:+ started = directory / 'launched'+ # Custom profile launches belong to their caller. They still wait+ # behind preparation, including explicit paths to the default profile.+ if not os.environ.get('CHROME_USER_DATA_DIR') and not any(+ arg == '--user-data-dir' or arg.startswith('--user-data-dir=') for arg in args):+ config = Path(os.environ.get('CHROME_CONFIG_HOME') or os.environ.get('XDG_CONFIG_HOME') or Path.home() / '.config')+ root = config / 'chromium'+ if (prepare(root) and not args and not started.exists() and+ not (config / 'chromium-flags.conf').exists() and not any(+ os.environ.get(key) for key in ['CHROME_CONFIG_HOME', 'XDG_CONFIG_HOME'])):+ prime(root)+ # Prevent another primer while the normal browser is still creating+ # its profile. The marker is private to this user's current login.+ started.touch(mode=0o600, exist_ok=True)+ return execute(command)+ except OSError as error:+ # In particular, never forward a URL into a primer after a lock timeout.+ print(str(error), file=sys.stderr)+ return 1+++if __name__ == '__main__':+ sys.exit(launch(sys.argv[1:]))diff --git a/os/connectors/connections.py b/os/connectors/connections.pyindex 5bef99419..5cf7e3697 100644--- a/os/connectors/connections.py+++ b/os/connectors/connections.py@@ -325,9 +325,8 @@ def browse(url):return True-def open_page():- if not shutil.which("hn-browser"):- raise store.StoreError("Open this page on a Harness computer, or run 'connections.py serve' for local review.")+def page_url():+ """Start or authenticate this user's on-demand page without opening a tab."""vault = store.Store()with store.locked(vault.root):url = running_page(vault)@@ -343,6 +342,13 @@ def open_page():time.sleep(0.1)if not url:raise store.StoreError("Could not open Connections.")+ return url+++def open_page():+ if not shutil.which("hn-browser"):+ raise store.StoreError("Open this page on a Harness computer, or run 'connections.py serve' for local review.")+ url = page_url()browse(url)print("Connections opened in the browser.")diff --git a/os/root/usr/bin/hn-browser b/os/root/usr/bin/hn-browserindex e3b51f338..c23030dbd 100644--- a/os/root/usr/bin/hn-browser+++ b/os/root/usr/bin/hn-browser@@ -1,4 +1,7 @@#!/bin/sh# Use the current display environment even from a long-lived agent or SSH pane.# Chromium remains sandboxed and is started only by an explicit browser request.+if [ -f /usr/lib/harness-os/browser_profile.py ]; then+ exec /usr/bin/python3 /usr/lib/harness-os/browser_profile.py "$@"+fiexec systemd-run --user --quiet --collect /usr/bin/chromium --ozone-platform=wayland --start-maximized --no-first-run --no-default-browser-check "$@"diff --git a/os/root/usr/share/harness-os/connections.md b/os/root/usr/share/harness-os/connections.mdindex 198382ca1..42116575b 100644--- a/os/root/usr/share/harness-os/connections.md+++ b/os/root/usr/share/harness-os/connections.md@@ -6,7 +6,8 @@ grant access here. Never copy tokens between machines, into chat or intoproject files, and never read the files under`~/.local/share/harness-os/connections`.-`harness connections list --json` lists this computer's connections. Open+`harness connections list --json` lists this computer's connections. On the PC+OS, choose **Connections** from the browser's New Tab page, or open`harness connections` when the user needs to connect or disconnect an account;`harness connections connect CODE` does the same sign-in from a terminal.diff --git a/os/tests/browser_home_preferences_guest.py b/os/tests/browser_home_preferences_guest.pynew file mode 100644index 000000000..30b7d6bfc--- /dev/null+++ b/os/tests/browser_home_preferences_guest.py@@ -0,0 +1,151 @@+#!/usr/bin/python3+"""Change disposable Chromium choices through Chromium, never preference edits.++Only used in the HN_OS_TEST guest. A private CDP pipe drives Chromium's actual+extension-management API; ordinary visible hn-browser launches verify the result.+No observer or debugging switch is installed in the production OS.+"""+import argparse+from contextlib import contextmanager+import hashlib+import json+import os+from pathlib import Path+import select+import signal+import subprocess+import time+++class Browser:+ def __init__(self, child):+ self.child, self.buffer, self.sequence = child, b'', 0++ def call(self, method, params=None, session=None):+ self.sequence += 1+ request = {'id': self.sequence, 'method': method, 'params': params or {}}+ if session:+ request['sessionId'] = session+ self.child.stdin.write(json.dumps(request).encode() + b'\0')+ self.child.stdin.flush()+ deadline = time.monotonic() + 15+ while True:+ if b'\0' not in self.buffer:+ remaining = deadline - time.monotonic()+ assert remaining > 0 and select.select([self.child.stdout], [], [], remaining)[0], method+ chunk = os.read(self.child.stdout.fileno(), 65536)+ assert chunk, 'Browser closed during ' + method+ self.buffer += chunk+ continue+ raw, self.buffer = self.buffer.split(b'\0', 1)+ response = json.loads(raw)+ if response.get('id') == self.sequence:+ assert 'error' not in response, response+ return response.get('result', {})++ def evaluate(self, expression, session):+ result = self.call('Runtime.evaluate', {'expression': expression,+ 'awaitPromise': True, 'returnByValue': True, 'userGesture': True}, session)+ assert 'exceptionDetails' not in result, result+ return result.get('result', {}).get('value')+++@contextmanager+def browser(root, log):+ with log.open('wb') as error:+ child = subprocess.Popen(['/bin/sh', '-c',+ 'exec /usr/bin/chromium --headless --no-first-run --no-default-browser-check '+ '--remote-debugging-pipe '+ '--allow-chrome-scheme-url --user-data-dir="$1" about:blank 3<&0 4>&1',+ 'harness-test-browser-choices', str(root)], stdin=subprocess.PIPE,+ stdout=subprocess.PIPE, stderr=error, start_new_session=True)+ instance = Browser(child)+ try:+ yield instance+ finally:+ try:+ child.stdin.write(b'{"id":99999,"method":"Browser.close"}\0')+ child.stdin.flush()+ child.wait(timeout=5)+ except (OSError, subprocess.TimeoutExpired):+ if child.poll() is None:+ os.killpg(child.pid, signal.SIGKILL)+ child.wait(timeout=5)+ child.stdin.close()+ child.stdout.close()+++def management(chrome, expression, session):+ return chrome.evaluate('new Promise((resolve, reject) => { ' + expression ++ '(value) => chrome.runtime.lastError ? reject(new Error(chrome.runtime.lastError.message)) : resolve(value)); })', session)+++def custom_page(root):+ """Install a signed test extension through Chromium's supported Linux path.++ CDP loadUnpacked is intentionally transient across browser restarts. A real+ external installation lets the test observe an existing persistent choice.+ The generated key and extension stay only inside this disposable VM.+ """+ fixture = Path('/tmp/harness-custom-newtab')+ fixture.mkdir(mode=0o700)+ (fixture / 'manifest.json').write_text(json.dumps({'manifest_version': 3,+ 'name': 'Custom tab fixture', 'version': '1.0',+ 'chrome_url_overrides': {'newtab': 'index.html'}}))+ (fixture / 'index.html').write_text('<!doctype html><title>New Tab</title><h1>CUSTOM TAB</h1>')+ subprocess.run(['/usr/bin/chromium', '--headless', '--no-message-box',+ '--user-data-dir=/tmp/harness-custom-pack-profile', '--pack-extension=' + str(fixture)],+ stdin=subprocess.DEVNULL, capture_output=True, check=True, timeout=30)+ key = fixture.with_suffix('.pem')+ key.chmod(0o600)+ public = subprocess.check_output(['/usr/bin/openssl', 'pkey', '-in', str(key),+ '-pubout', '-outform', 'DER'], timeout=10)+ identity = hashlib.sha256(public).hexdigest()[:32].translate(+ str.maketrans('0123456789abcdef', 'abcdefghijklmnop'))+ descriptor = root / 'External Extensions' / (identity + '.json')+ descriptor.parent.mkdir(parents=True)+ descriptor.write_text(json.dumps({'external_crx': str(fixture.with_suffix('.crx')),+ 'external_version': '1.0'}))+ return identity+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument('action', choices=['disabled', 'enabled', 'inspect', 'custom'])+ parser.add_argument('--output', type=Path, required=True)+ args = parser.parse_args()+ assert subprocess.check_output(['lsblk', '-dn', '-o', 'SERIAL', '/dev/vda'], text=True).strip() == 'HN_OS_TEST'+ assert not Path('/etc/harness-live').exists()+ assert subprocess.run(['pgrep', '-u', str(os.getuid()), '-x', 'chromium'], capture_output=True).returncode == 1+ root = Path.home() / '.config/chromium'+ identity = json.loads(Path('/usr/share/harness-os/browser-home/extension.json').read_text())['extension_id']+ result = {'action': args.action, 'identity': identity, 'mechanism': 'Chromium management API, private test-only CDP pipe'}+ if args.action == 'custom':+ result['custom_id'] = custom_page(root)+ with browser(root, args.output.with_suffix('.log')) as chrome:+ target = chrome.call('Target.createTarget', {'url': 'chrome://extensions/'})['targetId']+ session = chrome.call('Target.attachToTarget', {'targetId': target, 'flatten': True})['sessionId']+ deadline = time.monotonic() + 15+ while not chrome.evaluate('typeof chrome !== "undefined" && !!chrome.management', session):+ assert time.monotonic() < deadline, 'Extensions management page did not load'+ time.sleep(.1)+ if args.action == 'custom':+ deadline = time.monotonic() + 15+ while not any(item['id'] == result['custom_id'] and item['enabled']+ for item in management(chrome, 'chrome.management.getAll(', session)):+ assert time.monotonic() < deadline, 'Custom extension did not install'+ time.sleep(.1)+ elif args.action in ('disabled', 'enabled'):+ management(chrome, 'chrome.management.setEnabled(' + json.dumps(identity) + ', ' ++ ('true' if args.action == 'enabled' else 'false') + ', ', session)+ result['extensions'] = management(chrome, 'chrome.management.getAll(', session)+ installed = {item['id']: item for item in result['extensions']}+ if args.action == 'custom':+ assert installed[result['custom_id']]['enabled']+ elif args.action in ('disabled', 'enabled'):+ assert installed[identity]['enabled'] == (args.action == 'enabled')+ args.output.write_text(json.dumps(result, indent=2) + '\n')+++if __name__ == '__main__':+ main()diff --git a/os/tests/browser_home_vm.py b/os/tests/browser_home_vm.pynew file mode 100644index 000000000..3bc34824e--- /dev/null+++ b/os/tests/browser_home_vm.py@@ -0,0 +1,192 @@+"""Real Chromium start-page/Connections checks on the disposable OS test disk."""+import hashlib+import importlib.util+import json+from pathlib import Path+import re+import shlex+import shutil+import tarfile+import tempfile++from footprint_vm import copy_file+from install_first import wait_installer_screen++HELPER = r'^/usr/bin/python3 /usr/lib/harness-os/connections/connections[.]py serve --background$'+++def overlay(vm, source, result):+ assert source.is_dir()+ vm.command('test "$(lsblk -dn -o SERIAL /dev/vda)" = HN_OS_TEST && test ! -f /etc/harness-live')+ spec = importlib.util.spec_from_file_location('home_payload', source / 'os/tools/browser_home_payload.py')+ payload = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(payload)+ with tempfile.TemporaryDirectory(prefix='home-candidate-') as temporary:+ base = Path(temporary)+ root = base / 'root'+ result['browser_home'] = payload.stage(source, root)+ # The page's imports, catalog and bundled assets must match its entry+ # point, including when the reusable ISO contains an older connector.+ shutil.copytree(source / 'os/connectors', root / 'usr/lib/harness-os/connections',+ ignore=shutil.ignore_patterns('__pycache__', '*.pyc'))+ archive = base / 'home.tar'+ with tarfile.open(archive, 'w') as tar:+ for path in sorted(root.rglob('*')):+ if path.is_file():+ target = '/' + str(path.relative_to(root))+ result['candidates'][target] = {'sha256': hashlib.sha256(path.read_bytes()).hexdigest()}+ info = tar.gettarinfo(str(path), target.lstrip('/'))+ info.uid = info.gid = 0+ info.uname = info.gname = 'root'+ with path.open('rb') as handle:+ tar.addfile(info, handle)+ copy_file(vm, archive.read_bytes(), '/tmp/home-candidate.tar')+ vm.command('sudo -n tar -xf /tmp/home-candidate.tar -C /')+++def helper_stopped(vm):+ vm.command('pkill -INT -u "$(id -u)" -f ' + shlex.quote(HELPER) + ' || true')+ vm.command('timeout 10 sh -c ' + shlex.quote(+ 'while pgrep -u "$(id -u)" -f ' + shlex.quote(HELPER) + ' >/dev/null; do sleep .1; done'))+++def close_browser(vm):+ vm.keys('ctrl', 'shift', 'w')+ vm.command('timeout 10 sh -c \'while pgrep -u "$(id -u)" -x chromium >/dev/null; do sleep .1; done\'')+++def connected_page(vm, name):+ # Catalog cards are rendered only after the authenticated API succeeds;+ # the static page title alone would miss a broken capability handoff.+ text = wait_installer_screen(vm, r'Ahrefs', name, timeout=30)+ assert re.search(r'Available', text, re.I), text+++def preferences(vm, result):+ """Exercise real browser choices, then observe ordinary visible launches."""+ guest = Path(__file__).with_name('browser_home_preferences_guest.py')+ copy_file(vm, guest.read_bytes(), '/tmp/harness-browser-choices.py')+ result['browser_choice_observer_sha256'] = hashlib.sha256(guest.read_bytes()).hexdigest()+ vm.command('test ! -e /tmp/harness-browser-original && cp -a ~/.config/chromium /tmp/harness-browser-original')++ def choose(action):+ path = '/tmp/browser-choice-' + action + '.json'+ try:+ vm.command('timeout 75 python3 /tmp/harness-browser-choices.py ' + action + ' --output ' + path)+ finally:+ for suffix in ['.json', '.log']:+ try:+ (vm.folder / ('browser-choice-' + action + suffix)).write_bytes(vm.read_file(path.removesuffix('.json') + suffix))+ except Exception:+ pass+ return json.loads(vm.read_file(path))++ def ordinary_page(name):+ vm.command('hn-browser')+ text = wait_installer_screen(vm, r'Google', name, timeout=30)+ assert not re.search(r'Harness_', text, re.I), text+ close_browser(vm)++ choose('disabled')+ ordinary_page('browser-home-disabled')+ choose('enabled')+ vm.command('hn-browser')+ wait_installer_screen(vm, r'Harness_', 'browser-home-enabled')+ close_browser(vm)+ # Chromium requires its visible native confirmation when removing another+ # extension, even if management.uninstall requests showConfirmDialog:false.+ # Remove is the dialog's default OK action; send real keyboard confirmation.+ vm.command('hn-browser')+ wait_installer_screen(vm, r'Harness_', 'browser-home-before-removal')+ # Chromium ignores this internal URL as a normal startup argument. Navigate+ # through the visible address bar as a user would.+ vm.keys('ctrl', 'l')+ vm.type_probe('chrome://extensions/')+ vm.keys('ret')+ wait_installer_screen(vm, r'start\s+page', 'browser-home-extension-card')+ vm.click_word('browser-home-remove-action', 'Remove')+ confirmation = wait_installer_screen(vm, r'Cancel', 'browser-home-remove-confirm')+ assert re.search(r'Remove', confirmation, re.I), confirmation+ vm.keys('ret')+ wait_installer_screen(vm, r'(?s)\A(?!.*(?:start\s+page|Cancel)).*Extensions',+ 'browser-home-extension-removed')+ close_browser(vm)+ identity = result['browser_home']['extension_id']+ assert identity not in {item['id'] for item in choose('inspect')['extensions']}+ ordinary_page('browser-home-removed')+ ordinary_page('browser-home-removed-again')+ vm.command('test -f ' + shlex.quote('/home/me/.config/chromium/External Extensions/' + identity + '.json'))+ result['checks'].append('Disabling, re-enabling and removing through Chromium management persist across ordinary browser launches, even with the OS descriptor present')++ # A real, independently installed custom extension—not fabricated preferences.+ vm.command('mv ~/.config/chromium /tmp/harness-browser-removed')+ choose('custom')+ vm.command('hn-browser')+ wait_installer_screen(vm, r'CUSTOM\s+TAB', 'browser-existing-custom-page')+ close_browser(vm)+ vm.command('test ! -e ' + shlex.quote('/home/me/.config/chromium/External Extensions/' + identity + '.json'))+ result['checks'].append('An existing custom New Tab extension survives ordinary hn-browser startup; Harness does not register its override')+ vm.command('mv ~/.config/chromium /tmp/harness-browser-custom && mv /tmp/harness-browser-original ~/.config/chromium')+++def exercise(vm, result):+ vm.command('! pgrep -u "$(id -u)" -x chromium')+ vm.command('sudo -n nmcli networking off')+ failed = False+ try:+ vm.command('hn-browser')+ # The small subtitle can be split into separate OCR regions at the VM's+ # resolution. The Harness wordmark is distinct and read consistently; Connections can+ # also appear as a recently visited shortcut on Chromium's default page.+ wait_installer_screen(vm, r'Harness_', 'browser-home-offline', timeout=45)+ vm.command('! pgrep -u "$(id -u)" -f ' + shlex.quote(r'^/usr/lib/chromium/chromium .*--headless'))+ vm.command('test ! -S "/run/user/$(id -u)/harness-browser-start/ready"')+ vm.command('! pgrep -u "$(id -u)" -f ' + shlex.quote(HELPER))+ result['checks'].append('First browser start is the local Harness page offline; temporary preparation and Connections helper are both stopped')+ vm.click_word('browser-home-mouse', 'Connections')+ connected_page(vm, 'browser-home-connections')+ vm.keys('ctrl', 'w')+ wait_installer_screen(vm, r'Harness_', 'browser-home-back')+ helper_stopped(vm)+ # Closing the Connections tab returns to its action. Enter must work too.+ vm.keys('ret')+ connected_page(vm, 'browser-home-keyboard-reopen')+ result['checks'].append('Mouse click and keyboard Enter open authenticated Connections in a new tab; closing it and helper expiry recover without a stale bookmark')+ vm.keys('ctrl', 't')+ wait_installer_screen(vm, r'Harness_', 'browser-home-new-tab')+ close_browser(vm)+ helper_stopped(vm)+ vm.command('hn-browser')+ wait_installer_screen(vm, r'Harness_', 'browser-home-restart')+ close_browser(vm)+ result['checks'].append('New Tab and the next browser launch keep the start page without an install or permission prompt')+ preferences(vm, result)+ except BaseException:+ failed = True+ # Inspect only disposable profile extension state, never saved accounts.+ code = '''import json,pathlib+out={}+root=pathlib.Path.home()/'.config/chromium'+for path in root.glob('*/Preferences'):+ d=json.loads(path.read_text()).get('extensions',{})+ out[str(path.relative_to(root))]={'overrides':d.get('chrome_url_overrides'), 'extensions':{k:{field:v.get(field) for field in ['state','disable_reasons','location','manifest']} for k,v in d.get('settings',{}).items()}}+print(json.dumps(out))'''+ try:+ output, _ = vm.command('python3 -c ' + shlex.quote(code), check=False)+ (vm.folder / 'home-profile-diagnostic.txt').write_text(output)+ except Exception as error:+ result.setdefault('diagnostic_errors', []).append(str(error))+ try:+ # Capture the actual failure without typing into a potentially closed+ # browser or replacing the original error with an OCR timeout.+ vm.screenshot('home-failure')+ except Exception as error:+ result.setdefault('diagnostic_errors', []).append(str(error))+ raise+ finally:+ try:+ vm.command('sudo -n nmcli networking on')+ except Exception as error:+ if not failed:+ raise+ result.setdefault('diagnostic_errors', []).append(str(error))diff --git a/os/tests/browser_vm.py b/os/tests/browser_vm.pyindex e0eb8dd7c..6f468d3b5 100644--- a/os/tests/browser_vm.py+++ b/os/tests/browser_vm.py@@ -438,6 +438,8 @@ def main():help='Explicitly overlay a candidate browser launcher; omit to test the packaged image')parser.add_argument('--compositor-config', type=Path,help='Explicitly overlay a candidate compositor configuration; omit to test the packaged image')+ parser.add_argument('--home-source', type=Path,+ help='Stage and exercise this source checkout\'s signed browser start page on the disposable disk')parser.add_argument('--memory-profile', action='store_true',help='Capture finite read-only memory snapshots; separate from ordinary focus acceptance')parser.add_argument('--zram-config', type=Path,@@ -554,6 +556,10 @@ def main():# Signal the actual running compositor, including the private# OS-owned executable. Exact-image acceptance needs no reload.vm.command('pkill -HUP -u "$(id -u)" -x labwc')+ if args.home_source:+ import browser_home_vm+ browser_home_vm.overlay(vm, args.home_source.resolve(), result)+ browser_home_vm.exercise(vm, result)if args.memory_profile:data = Path(__file__).with_name('browser_memory.py').read_bytes()result['memory_observer_sha256'] = hashlib.sha256(data).hexdigest()diff --git a/os/tests/test_browser_home.py b/os/tests/test_browser_home.pynew file mode 100644index 000000000..9e369a675--- /dev/null+++ b/os/tests/test_browser_home.py@@ -0,0 +1,313 @@+"""Security boundary and package identity for the OS browser start page."""+import importlib.util+import io+import json+from pathlib import Path+import shutil+import struct+import subprocess+import tempfile+import threading+from types import SimpleNamespace+import unittest+from unittest.mock import Mock, patch++ROOT = Path(__file__).resolve().parents[2]+++def module(name, path):+ spec = importlib.util.spec_from_file_location(name, ROOT / path)+ result = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(result)+ return result+++host = module('browser_home_host', 'os/browser_home.py')+payload = module('home_payload', 'os/tools/browser_home_payload.py')+profile = module('home_profile', 'os/browser_profile.py')+++def message(data):+ raw = json.dumps(data).encode()+ return io.BytesIO(struct.pack('=I', len(raw)) + raw)+++class BrowserHome(unittest.TestCase):+ def setUp(self):+ temporary = tempfile.TemporaryDirectory()+ self.addCleanup(temporary.cleanup)+ self.folder = Path(temporary.name)+ self.manifest = self.folder / 'native.json'+ self.origin = 'chrome-extension://' + 'a' * 32 + '/'+ self.manifest.write_text(json.dumps({'allowed_origins': [self.origin]}))+ self.launch = Mock(return_value='http://127.0.0.1:12345/#' + 'K' * 43)+ self.ready = Mock()++ def invoke(self, request, origin=None):+ output = io.BytesIO()+ result = host.main([origin or self.origin], request, output,+ manifest=self.manifest, launch=self.launch, ready=self.ready)+ raw = output.getvalue()+ if raw:+ self.assertEqual(struct.unpack('=I', raw[:4])[0], len(raw[4:]))+ return result, json.loads(raw[4:])+ return result, None++ def test_only_explicit_connections_action_can_start_helper(self):+ status, result = self.invoke(message({'action': 'connections'}))+ self.assertEqual(status, 0)+ self.assertEqual(result, {'ok': True})+ self.launch.assert_called_once_with()++ def test_native_open_uses_os_launcher_without_exposing_capability(self):+ local = SimpleNamespace(page_url=self.launch)+ with patch.dict(host.sys.modules, {'connections': local}), patch.object(host.sys, 'path', list(host.sys.path)), patch.object(host.subprocess, 'run') as run:+ host.open_connections()+ run.assert_called_once_with(['/usr/bin/hn-browser', self.launch.return_value],+ check=True, stdin=subprocess.DEVNULL,+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,+ timeout=30)++ def test_other_origins_cannot_invoke_helper(self):+ for origin in ['https://example.com/', 'chrome-extension://' + 'b' * 32 + '/', self.origin + '?x']:+ self.assertEqual(self.invoke(message({'action': 'connections'}), origin), (1, None))+ self.launch.assert_not_called()+ self.ready.assert_not_called()++ def test_install_handshake_never_starts_connections(self):+ self.assertEqual(self.invoke(message({'action': 'installed'})), (0, {'ok': True}))+ self.ready.assert_called_once_with()+ self.launch.assert_not_called()+ self.assertEqual(self.invoke(message({'action': 'installed', 'path': '/unexpected'}))[0], 1)+ self.ready.assert_called_once_with()++ def test_arbitrary_actions_parameters_and_malformed_messages_do_not_launch(self):+ for request in [message({'action': 'connections', 'url': 'https://evil.invalid'}),+ message({'action': 'shell', 'command': 'id'}), message([]), message(None),+ message({'action': 'connections', 'token': 'secret'}),+ io.BytesIO(b''), io.BytesIO(b'\xff' * 4),+ io.BytesIO(struct.pack('=I', 10) + b'{}'),+ io.BytesIO(struct.pack('=I', 2) + b'\xff\xff')]:+ status, response = self.invoke(request)+ self.assertEqual(status, 1)+ self.assertEqual(response, {'error': 'Could not open Connections.'})+ self.launch.assert_not_called()++ def test_failure_does_not_relay_sensitive_exception(self):+ self.launch.side_effect = OSError('sensitive account or key')+ self.assertEqual(self.invoke(message({'action': 'connections'})),+ (1, {'error': 'Could not open Connections.'}))++ def test_signed_extension_matches_reviewed_source_and_narrow_manifest(self):+ extension_id, version = payload.verify(ROOT / 'os/browser-home')+ manifest = json.loads((ROOT / 'os/browser-home/extension/manifest.json').read_text())+ self.assertEqual(manifest['permissions'], ['nativeMessaging'])+ self.assertEqual(manifest['chrome_url_overrides'], {'newtab': 'index.html'})+ self.assertEqual(manifest['background'], {'service_worker': 'installed.js'})+ self.assertFalse(set(manifest) & {'host_permissions', 'content_scripts',+ 'externally_connectable', 'web_accessible_resources', 'update_url'})+ result = payload.stage(ROOT, self.folder / 'stage')+ self.assertEqual(result, {'extension_id': extension_id, 'version': version})+ native = json.loads((self.folder / 'stage/etc/chromium/native-messaging-hosts' /+ (payload.HOST + '.json')).read_text())+ self.assertEqual(native['allowed_origins'], ['chrome-extension://' + extension_id + '/'])+ external = json.loads((self.folder / 'stage/usr/share/harness-os/browser-home/extension.json').read_text())+ self.assertEqual(external['descriptor']['external_version'], version)+ self.assertFalse((self.folder / 'stage/etc/chromium/policies').exists())++ def test_source_changes_or_crx_signature_changes_require_repacking(self):+ folder = self.folder / 'home'+ shutil.copytree(ROOT / 'os/browser-home', folder)+ source = folder / 'extension/home.js'+ original = source.read_bytes()+ source.write_bytes(original + b'\n// unreviewed\n')+ with self.assertRaisesRegex(ValueError, 'Repack'):+ payload.verify(folder)+ source.write_bytes(original)+ crx = folder / 'home.crx'+ raw = bytearray(crx.read_bytes())+ raw[-1] ^= 1+ crx.write_bytes(raw)+ with self.assertRaises(subprocess.CalledProcessError):+ payload.verify(folder)++ def test_first_launch_preserves_custom_newtab_in_any_existing_profile(self):+ package = self.folder / 'extension.json'+ identity = 'b' * 32+ package.write_text(json.dumps({'extension_id': identity, 'descriptor': {'external_crx': '/packaged.crx', 'external_version': '1.0'}}))+ root = self.folder / 'chromium'+ prefs = root / 'Profile 2/Preferences'+ prefs.parent.mkdir(parents=True)+ variants = [+ {'extensions': {'chrome_url_overrides': {'newtab': [{'entry': 'chrome-extension://' + 'c' * 32 + '/home.html', 'active': True}]}}},+ {'extensions': {'settings': {'c' * 32: {'manifest': {'chrome_url_overrides': {'newtab': 'index.html'}}}}}},+ ]+ for data in variants:+ raw = json.dumps(data)+ prefs.write_text(raw)+ self.assertFalse(profile.prepare(root, package))+ self.assertFalse((root / 'External Extensions').exists())+ self.assertEqual(prefs.read_text(), raw)+ prefs.write_text('{invalid')+ self.assertFalse(profile.prepare(root, package))+ self.assertEqual(prefs.read_text(), '{invalid')++ def test_prepare_writes_only_owned_descriptor_and_updates_without_profile_edits(self):+ package = self.folder / 'extension.json'+ identity = 'b' * 32+ descriptor = {'external_crx': '/packaged.crx', 'external_version': '1.0'}+ package.write_text(json.dumps({'extension_id': identity, 'descriptor': descriptor}))+ root = self.folder / 'chromium'+ prefs = root / 'Default/Preferences'+ prefs.parent.mkdir(parents=True)+ original = '{"session":{"restore_on_startup":1},"bookmark_bar":{"show_on_all_tabs":true}}'+ prefs.write_text(original)+ self.assertTrue(profile.prepare(root, package))+ target = root / 'External Extensions' / (identity + '.json')+ self.assertEqual(json.loads(target.read_text()), descriptor)+ self.assertEqual(prefs.read_text(), original)+ self.assertTrue(profile.prepare(root, package))+ descriptor['external_version'] = '1.1'+ package.write_text(json.dumps({'extension_id': identity, 'descriptor': descriptor}))+ self.assertTrue(profile.prepare(root, package))+ self.assertEqual(json.loads(target.read_text()), descriptor)+ self.assertEqual(prefs.read_text(), original)+ target.write_text('{"external_crx":"/user-choice.crx"}')+ self.assertFalse(profile.prepare(root, package))+ self.assertEqual(target.read_text(), '{"external_crx":"/user-choice.crx"}')++ def test_imported_or_later_customization_prevents_new_install_after_registration(self):+ package = self.folder / 'extension.json'+ identity = 'b' * 32+ descriptor = {'external_crx': '/packaged.crx', 'external_version': '1.0'}+ package.write_text(json.dumps({'extension_id': identity, 'descriptor': descriptor}))+ root = self.folder / 'chromium'+ self.assertTrue(profile.prepare(root, package))+ target = root / 'External Extensions' / (identity + '.json')+ prefs = root / 'Imported/Preferences'+ prefs.parent.mkdir(parents=True)+ original = json.dumps({'extensions': {'settings': {+ 'c' * 32: {'manifest': {'chrome_url_overrides': {'newtab': 'home.html'}}}}}})+ prefs.write_text(original)+ self.assertTrue(profile.prepare(root, package))+ self.assertEqual(json.loads(target.read_text()), dict(descriptor, keep_if_present=True))+ self.assertEqual(prefs.read_text(), original)+ # Once a customization is observed, don't silently install into that+ # profile on a later launch or OS package update.+ prefs.write_text('{}')+ descriptor['external_version'] = '1.1'+ package.write_text(json.dumps({'extension_id': identity, 'descriptor': descriptor}))+ self.assertTrue(profile.prepare(root, package))+ self.assertEqual(json.loads(target.read_text()), dict(descriptor, keep_if_present=True))++ def test_unreadable_profile_restricts_an_existing_registration(self):+ package = self.folder / 'extension.json'+ identity = 'b' * 32+ descriptor = {'external_crx': '/packaged.crx', 'external_version': '1.0'}+ package.write_text(json.dumps({'extension_id': identity, 'descriptor': descriptor}))+ root = self.folder / 'chromium'+ self.assertTrue(profile.prepare(root, package))+ prefs = root / 'Default/Preferences'+ prefs.parent.mkdir(parents=True)+ prefs.write_text('{broken')+ self.assertTrue(profile.prepare(root, package))+ target = root / 'External Extensions' / (identity + '.json')+ self.assertTrue(json.loads(target.read_text())['keep_if_present'])+ self.assertEqual(prefs.read_text(), '{broken')++ def test_existing_browser_profiles_never_start_priming_process(self):+ for relative in ['Local State', 'Default/Preferences', 'Profile 2/Secure Preferences']:+ root = self.folder / relative.replace('/', '-')+ state = root / relative+ state.parent.mkdir(parents=True)+ state.write_text('{}')+ endpoint = root / 'runtime/ready'+ with patch.object(profile, 'startup_socket', return_value=endpoint), patch.object(profile.subprocess, 'Popen') as child:+ self.assertFalse(profile.prime(root))+ child.assert_not_called()+ self.assertEqual(state.read_text(), '{}')++ def test_priming_timeout_closes_only_its_own_child_and_removes_socket(self):+ root = self.folder / 'pristine'+ root.mkdir()+ # Unix socket paths are limited to about 100 bytes, including macOS's+ # long default temporary-directory prefix.+ runtime = tempfile.TemporaryDirectory(prefix='hn-home-', dir='/tmp')+ self.addCleanup(runtime.cleanup)+ endpoint = Path(runtime.name) / 'ready'+ child = Mock(stdin=io.BytesIO(), stdout=io.BytesIO())+ child.poll.return_value = None+ with patch.object(profile, 'startup_socket', return_value=endpoint), patch.object(profile.subprocess, 'Popen', return_value=child) as start:+ self.assertFalse(profile.prime(root, deadline_seconds=.01))+ start.assert_called_once()+ self.assertTrue(start.call_args.kwargs['start_new_session'])+ child.wait.assert_called_once_with(timeout=3)+ self.assertFalse(endpoint.exists())+ self.assertTrue(child.stdin.closed)++ def test_priming_waits_for_real_install_acknowledgment_then_closes_child(self):+ root = self.folder / 'pristine'+ root.mkdir()+ runtime = tempfile.TemporaryDirectory(prefix='hn-home-', dir='/tmp')+ self.addCleanup(runtime.cleanup)+ endpoint = Path(runtime.name) / 'ready'+ child = Mock(stdin=io.BytesIO(), stdout=io.BytesIO())+ child.poll.return_value = None+ def start(*args, **kwargs):+ self.assertEqual(args[0][-1], str(root))+ profile.installed()+ return child+ with patch.object(profile, 'startup_socket', return_value=endpoint), patch.object(profile.subprocess, 'Popen', side_effect=start):+ self.assertTrue(profile.prime(root))+ child.wait.assert_called_once_with(timeout=3)+ self.assertFalse(endpoint.exists())++ def test_url_arriving_during_preparation_waits_and_is_not_lost(self):+ runtime = tempfile.TemporaryDirectory(prefix='hn-home-', dir='/tmp')+ self.addCleanup(runtime.cleanup)+ endpoint = Path(runtime.name) / 'ready'+ preparing, finish, requested = threading.Event(), threading.Event(), threading.Event()+ calls, outcomes = [], []+ def prime(root):+ preparing.set()+ return finish.wait(2)+ def execute(args):+ self.assertTrue(finish.is_set())+ calls.append(args)+ return 0+ def second():+ requested.set()+ outcomes.append(profile.launch(['https://example.test/'], execute=execute))+ with patch.object(profile, 'startup_socket', return_value=endpoint), patch.object(profile, 'prepare', return_value=True), patch.object(profile, 'prime', side_effect=prime), patch.dict(profile.os.environ, {}, clear=True):+ first = threading.Thread(target=lambda: outcomes.append(profile.launch([], execute=execute)))+ later = threading.Thread(target=second)+ first.start()+ try:+ self.assertTrue(preparing.wait(1))+ later.start()+ self.assertTrue(requested.wait(1))+ self.assertEqual(calls, [])+ finally:+ finish.set()+ first.join(3)+ if later.ident is not None:+ later.join(3)+ self.assertFalse(first.is_alive())+ self.assertFalse(later.is_alive())+ self.assertEqual(outcomes, [0, 0])+ self.assertEqual(len(calls), 2)+ self.assertEqual(calls[1][-1], 'https://example.test/')++ def test_lock_timeout_never_forwards_a_url_to_temporary_browser(self):+ runtime = tempfile.TemporaryDirectory(prefix='hn-home-', dir='/tmp')+ self.addCleanup(runtime.cleanup)+ endpoint = Path(runtime.name) / 'ready'+ execute = Mock()+ with patch.object(profile, 'startup_socket', return_value=endpoint), patch.object(profile.sys, 'stderr', io.StringIO()):+ with profile.startup_guard():+ self.assertEqual(profile.launch(['https://example.test/'], execute=execute, lock_timeout=.01), 1)+ execute.assert_not_called()+++if __name__ == '__main__':+ unittest.main()diff --git a/os/tests/test_package.py b/os/tests/test_package.pyindex be61e40d8..97d7f17a8 100644--- a/os/tests/test_package.py+++ b/os/tests/test_package.py@@ -25,6 +25,9 @@ class PackageIdentity(unittest.TestCase):identity = package.stage(Path(__file__).resolve().parents[2], runtime, destination, 'a' * 40)config = destination / 'etc/skel/.config/opencode'self.assertTrue((destination / 'usr/lib/harness-os/connections/connections.py').is_file())+ self.assertTrue((destination / 'usr/share/harness-os/browser-home/home.crx').is_file())+ self.assertEqual((destination / 'usr/lib/harness-os/browser_home.py').stat().st_mode & 0o777, 0o755)+ self.assertTrue((destination / 'etc/chromium/native-messaging-hosts/ai.autonomous.harness_home.json').is_file())self.assertTrue((destination / 'usr/lib/harness-os/connections/web/index.html').is_file())for name in ('bridge.py', 'catalog.json', 'oauth.py', 'gateway.py', 'agents.py', 'renew.py'):self.assertTrue((destination / 'usr/lib/harness-os/connections' / name).is_file(), name)diff --git a/os/tools/browser_home_payload.py b/os/tools/browser_home_payload.pynew file mode 100644index 000000000..58ce1775e--- /dev/null+++ b/os/tools/browser_home_payload.py@@ -0,0 +1,123 @@+"""Verify and stage the small browser extension shipped by the OS package."""+import base64+import hashlib+import io+import json+from pathlib import Path+import shutil+import struct+import subprocess+import tempfile+import zipfile++HOST = 'ai.autonomous.harness_home'+CRX_TARGET = 'usr/share/harness-os/browser-home/home.crx'+++def fields(raw):+ """Read only the length-delimited fields used by the CRX3 protobuf header."""+ position = 0++ def varint():+ nonlocal position+ value = 0+ for shift in range(0, 64, 7):+ if position >= len(raw):+ break+ byte = raw[position]+ position += 1+ value |= (byte & 127) << shift+ if byte < 128:+ return value+ raise ValueError('Invalid CRX header')++ result = {}+ while position < len(raw):+ tag = varint()+ if tag & 7 != 2 or tag >> 3 in result:+ raise ValueError('Unexpected CRX header field')+ length = varint()+ if position + length > len(raw):+ raise ValueError('Truncated CRX header')+ result[tag >> 3] = raw[position:position + length]+ position += length+ return result+++def verify(folder):+ source = folder / 'extension'+ manifest = json.loads((source / 'manifest.json').read_text())+ public = base64.b64decode(manifest['key'], validate=True)+ identity = hashlib.sha256(public).digest()[:16]+ extension_id = ''.join(chr(97 + int(char, 16)) for char in identity.hex())+ raw = (folder / 'home.crx').read_bytes()+ if len(raw) > 128 * 1024 or raw[:8] != b'Cr24\x03\0\0\0':+ raise ValueError('Expected the small packaged CRX3 start page')+ size = struct.unpack('<I', raw[8:12])[0]+ header, archive = raw[12:12 + size], raw[12 + size:]+ data = fields(header)+ proof = fields(data[2])+ if (set(data) != {2, 10000} or set(proof) != {1, 2} or proof[1] != public or+ fields(data[10000]) != {1: identity}):+ raise ValueError('Browser extension identity changed')+ with tempfile.TemporaryDirectory(prefix='harness-home-verify-') as temporary:+ base = Path(temporary)+ (base / 'public.der').write_bytes(public)+ (base / 'signature').write_bytes(proof[2])+ (base / 'message').write_bytes(b'CRX3 SignedData\0' + struct.pack('<I', len(data[10000])) + data[10000] + archive)+ subprocess.run(['openssl', 'pkey', '-pubin', '-inform', 'DER', '-in', str(base / 'public.der'),+ '-out', str(base / 'public.pem')], check=True, capture_output=True, timeout=10)+ subprocess.run(['openssl', 'dgst', '-sha256', '-verify', str(base / 'public.pem'),+ '-signature', str(base / 'signature'), str(base / 'message')],+ check=True, capture_output=True, timeout=10)+ expected = {str(p.relative_to(source)): p.read_bytes() for p in source.rglob('*') if p.is_file()}+ with zipfile.ZipFile(io.BytesIO(archive)) as packaged:+ if (len(packaged.namelist()) != len(expected) or set(packaged.namelist()) != set(expected) or+ any(packaged.read(name) != contents for name, contents in expected.items())):+ raise ValueError('Repack the start page: CRX differs from reviewed source')+ return extension_id, manifest['version']+++def stage(source, destination):+ folder = source / 'os/browser-home'+ extension_id, version = verify(folder)+ target = destination / CRX_TARGET+ target.parent.mkdir(parents=True, exist_ok=True)+ shutil.copyfile(folder / 'home.crx', target)+ target.chmod(0o644)+ # The distro's supported external-extension mechanism is removable and+ # remembers removal. Do not force-install it or edit profile preferences.+ records = {+ 'usr/share/harness-os/browser-home/extension.json': {+ 'extension_id': extension_id,+ 'descriptor': {'external_crx': '/' + CRX_TARGET, 'external_version': version},+ },+ 'etc/chromium/native-messaging-hosts/' + HOST + '.json': {+ 'name': HOST, 'description': 'Open Harness Connections',+ 'path': '/usr/lib/harness-os/browser_home.py', 'type': 'stdio',+ 'allowed_origins': ['chrome-extension://' + extension_id + '/'],+ },+ }+ for name, data in records.items():+ path = destination / name+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(json.dumps(data, indent=2) + '\n')+ path.chmod(0o644)+ host = destination / 'usr/lib/harness-os/browser_home.py'+ host.parent.mkdir(parents=True, exist_ok=True)+ shutil.copyfile(source / 'os/browser_home.py', host)+ host.chmod(0o755)+ prepare = destination / 'usr/lib/harness-os/browser_profile.py'+ shutil.copyfile(source / 'os/browser_profile.py', prepare)+ prepare.chmod(0o755)+ return {'extension_id': extension_id, 'version': version}+++if __name__ == '__main__':+ import argparse+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument('--stage', type=Path)+ args = parser.parse_args()+ source = Path(__file__).resolve().parents[2]+ result = stage(source, args.stage) if args.stage else verify(source / 'os/browser-home')+ print(json.dumps(result))diff --git a/os/tools/build-package.py b/os/tools/build-package.pyindex 0380acedd..6b8a17d5c 100644--- a/os/tools/build-package.py+++ b/os/tools/build-package.py@@ -54,6 +54,10 @@ def stage(source, runtime, destination, commit):info = validate_runtime(runtime, commit)os_source = source / 'os'shutil.copytree(os_source / 'root', destination, symlinks=True)+ browser_spec = importlib.util.spec_from_file_location('browser_home_payload', Path(__file__).with_name('browser_home_payload.py'))+ browser_home = importlib.util.module_from_spec(browser_spec)+ browser_spec.loader.exec_module(browser_home)+ browser_home.stage(source, destination)shutil.copytree(os_source / 'connectors', destination / 'usr/lib/harness-os/connections',ignore=shutil.ignore_patterns('__pycache__', '*.pyc'))license_dir = destination / 'usr/share/licenses/harness-os-connections'