diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index f9ed1fa..e9ef535 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -36,6 +36,18 @@ jobs: run: node --import tsx tools/package-release.ts --public - run: npm run package:check if: runner.os == 'Linux' + - name: Build headless Linux browser distribution + if: runner.os == 'Linux' + shell: bash + run: | + set -euo pipefail + node --import tsx tools/package-browser-client.ts + version="${GITHUB_REF_NAME#v}" + archive="abridge-client-browser-$version-linux.tar.gz" + cp -- ".local/release/browser-client/$archive" dist/releases/ + cd dist/releases + test "$(tar -xOf "$archive" abridge-client-browser/version)" = "$version" + sha256sum -- "$archive" > "$archive.sha256" - name: Build portable unsigned macOS candidate if: runner.os == 'macOS' run: npm run package:macos -- --reuse-build @@ -81,6 +93,7 @@ jobs: path: | dist/releases/*.tgz dist/releases/abridge-browser-*.zip + dist/releases/abridge-client-browser-*.tar.gz* dist/releases/aBridge-*-android.apk if-no-files-found: error retention-days: 14 @@ -170,6 +183,10 @@ jobs: archives+=("$archive") checksums+=("$archive.sha256") done + browser_archive="abridge-client-browser-$version-linux.tar.gz" + mv -- "$GITHUB_WORKSPACE/release/$browser_archive" "$GITHUB_WORKSPACE/release/$browser_archive.sha256" . + archives+=("$browser_archive") + checksums+=("$browser_archive.sha256") sha256sum --check --strict -- "${checksums[@]}" cp -- "${archives[@]}" "$GITHUB_WORKSPACE/release/" sha256sum -- "${archives[@]}" > "$GITHUB_WORKSPACE/release/SHA256SUMS" diff --git a/apps/browser-client/abridge-client-browser b/apps/browser-client/abridge-client-browser new file mode 100755 index 0000000..d23b3aa --- /dev/null +++ b/apps/browser-client/abridge-client-browser @@ -0,0 +1,500 @@ +#!/usr/bin/env python3 +"""在 Linux 上运行使用原版 aBridge 扩展的独立浏览器设备。""" + +import argparse +import base64 +import fcntl +import getpass +import hashlib +import json +import os +import pwd +import shutil +import signal +import socket +import subprocess +import sys +import time +import urllib.request +from contextlib import contextmanager, suppress +from pathlib import Path +from urllib.parse import urlsplit + +from playwright.sync_api import Error, sync_playwright + +INSTALLATION = Path(__file__).resolve().parent +MAX_MESSAGE = 8192 +FAILED = {"status": "failed"} + + +class BindingMissing(ValueError): + """扩展已明确缺少预期绑定。""" + + +def valid_origin(origin: str, allow_http: bool = False) -> str: + """凭据仅发送至规范化的 HTTPS 或显式信任的 HTTP 来源。""" + url = urlsplit(origin) + host = url.hostname or "" + address = f"[{host}]" if ":" in host else host + port = url.port + authority = address if port is None else f"{address}:{port}" + if ( + not host + or origin != f"{url.scheme}://{authority}" + or any(c.isspace() or c in "%\\@*" for c in host) + or url.scheme not in {"https", "http"} + or (url.scheme == "http" and not allow_http and host not in {"localhost", "127.0.0.1", "::1"}) + ): + raise ValueError("invalid server origin") + if port == (443 if url.scheme == "https" else 80): + return f"{url.scheme}://{address}" + return origin + + +class NoRedirect(urllib.request.HTTPRedirectHandler): + """禁止跟随携带凭据的请求重定向。""" + + def redirect_request(self, req, fp, code, msg, headers, newurl): + """让携带凭据的重定向请求失败。""" + return + + +def device_request(origin: str, path: str, *, body=None, key=None) -> dict: + """读取设备身份,禁止继承代理或跟随重定向。""" + headers = {"Content-Type": "application/json"} if body is not None else {"Authorization": f"Bearer {key}"} + request = urllib.request.Request(origin + path, data=json.dumps(body).encode() if body is not None else None, headers=headers) + opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), NoRedirect()) + with opener.open(request, timeout=6) as response: + device = json.loads(response.read(16384)) + if device["kind"] != "browser" or device["capabilities"] != ["browser"]: + raise ValueError("a Browser Device Key is required") + return device + + +def binding_for(home: Path) -> dict | None: + """回读扩展已经确认的绑定。""" + try: + return json.loads((home / "binding.json").read_text()) + except FileNotFoundError: + return None + + +def save_binding(home: Path, binding: dict) -> None: + """在扩展完成绑定后原子发布设备与版本。""" + pending = home / "binding.tmp" + pending.write_text(json.dumps(binding)) + pending.replace(home / "binding.json") + + +@contextmanager +def connection_page(context): + """仅向扩展自己的连接页面交付浏览器凭据。""" + manifest = json.loads((INSTALLATION / "extension/manifest.json").read_text()) + # 发行物的公开密钥固定扩展 ID,重启及升级沿用同一 Profile。 + digest = hashlib.sha256(base64.b64decode(manifest["key"], validate=True)).hexdigest()[:32] + extension_id = digest.translate(str.maketrans("0123456789abcdef", "abcdefghijklmnop")) + page = context.new_page() + try: + page.goto(f"chrome-extension://{extension_id}/connection.html", timeout=4000) + yield page + finally: + page.close() + + +def open_browser(playwright, home: Path, origin: str): + """复制扩展并仅授予配置主机的权限,Chromium 使用私有持久 profile。""" + url = urlsplit(origin) + extension = home / "extension" + shutil.copytree(INSTALLATION / "extension", extension, dirs_exist_ok=True) + manifest_path = extension / "manifest.json" + manifest = json.loads(manifest_path.read_text()) + host = url.hostname if ":" not in url.hostname else f"[{url.hostname}]" + # Chrome 的 match pattern 按主机授权,具体端口仍由登记和兑换的 origin 限定。 + manifest["host_permissions"] = [f"{url.scheme}://{host}/*"] + manifest_path.chmod(0o600) + manifest_path.write_text(json.dumps(manifest)) + return playwright.chromium.launch_persistent_context( + home / "profile", + channel="chromium", + headless=True, + chromium_sandbox=True, + timeout=9000, + args=[ + f"--disable-extensions-except={extension}", + f"--load-extension={extension}", + ], + ) + + +def extension_request(page, message: dict, timeout: float = 1): + """只从扩展的内部连接页发送请求。""" + return page.evaluate( + """([message, timeout]) => Promise.race([ + chrome.runtime.sendMessage(message), + new Promise(resolve => setTimeout(resolve, timeout, null)) + ])""", + [message, int(timeout * 1000)], + ) + + +def bind(page, binding: dict, device_key: str) -> None: + """通过原版扩展的内部页面发起绑定。""" + origin = binding["browser_origin"] + message = {"type": "bind_token", "server": origin, "device_key": device_key} + if origin.startswith("http://"): + message["http_confirmed_origin"] = origin + if binding["revision"]: + message["platform_revision"] = binding["revision"] + accepted = extension_request(page, message, timeout=5) + if not accepted or not accepted.get("ok"): + raise ValueError("binding rejected") + + +def profile_status(page, timeout: float = 5) -> dict: + """等待扩展完成本地存储和标签页恢复。""" + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + status = extension_request(page, {"type": "status"}, timeout=0.5) + if status and status.get("ok"): + return status + time.sleep(0.1) + raise TimeoutError("browser status could not be read") + + +def matches_binding(status: dict, binding: dict, *, legacy: bool = False) -> bool: + revision = status.get("platform_revision") + return ( + status.get("configured") + and status.get("device_id") == binding["device_id"] + and status.get("server") == binding["browser_origin"] + and (revision == binding["revision"] or revision is None and (legacy or not binding["revision"])) + ) + + +def verify_binding(page, binding: dict, *, timeout: float = 7, connected: bool = False) -> None: + """等待指定版本落盘。平台代理交接还须确认 WebSocket 与 Server 提交成功。""" + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + status = extension_request(page, {"type": "status"}, timeout=0.5) + if status and status.get("authorization_error"): + raise ValueError("binding failed") + if status and status.get("ok") and not status.get("authorizing"): + if not matches_binding(status, binding) or status.get("revoked"): + raise BindingMissing("expected browser binding is missing") + if not connected: + return + if status.get("connected"): + if not status.get("replacement_pending"): + return + state = resolve_binding(page, "confirm", binding["revision"]) + if state == "active": + return + if state == "invalid": + raise BindingMissing("candidate binding is no longer valid") + time.sleep(0.1) + raise TimeoutError("browser binding did not complete") + + +def resolve_binding(page, action: str, revision: int) -> str: + reply = extension_request( + page, + {"type": "platform_binding", "action": action, "revision": revision}, + timeout=12, + ) + if not reply or not reply.get("ok"): + raise ValueError("binding resolution failed") + return reply["state"] + + +def published_binding(status: dict) -> dict: + """读取扩展保存的已提交版本。""" + return { + "browser_origin": status["server"], + "device_id": status["device_id"], + "revision": status["platform_revision"], + } + + +@contextmanager +def profile_lock(home: Path): + """CLI 首绑与运行进程互斥,进程退出时释放锁。""" + with (home / "profile.lock").open("a") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + yield + + +def describe(home: Path, context=None) -> dict: + """运行中从扩展回读绑定,只有明确丢失才清理已确认的记录。""" + binding = binding_for(home) + if context is None: + return {**binding, "status": "bound"} if binding else {"status": "unbound"} + try: + with connection_page(context) as page: + status = profile_status(page, timeout=1) + except Error as exc: + raise TimeoutError("browser binding could not be read") from exc + if status.get("replacement_pending"): + return {**binding, "status": "running", "connected": False} if binding else {"status": "unbound"} + if status.get("configured") and not status.get("revoked"): + if status.get("platform_revision") is not None and status.get("connected"): + current = published_binding(status) + if binding != current: + save_binding(home, current) + binding = current + if binding and matches_binding(status, binding, legacy=True): + return {**binding, "status": "running", "connected": status.get("connected") is True} + if binding and not status.get("authorizing"): + (home / "binding.json").unlink(missing_ok=True) + return {"status": "unbound"} + + +def platform_binding(data: dict) -> dict: + """校验私有平台交接,后续只使用已确认的单一来源。""" + origin = valid_origin(data["browser_origin"], data.get("http_confirmed_origin") == data["browser_origin"]) + device_id, revision = data["device_id"], data["revision"] + if not isinstance(device_id, str) or not device_id or type(revision) is not int or revision < 1: + raise ValueError("invalid browser registration") + return {"browser_origin": origin, "device_id": device_id, "revision": revision} + + +def redeem_binding(binding: dict, token) -> dict: + """为候选版本兑换设备凭据。""" + if not isinstance(token, str) or not token: + raise ValueError("browser ticket required") + device = device_request( + binding["browser_origin"], "/api/managed-browsers/redeem", + body={"device_id": binding["device_id"], "bootstrap_token": token}, + ) + if device["device_id"] != binding["device_id"] or device.get("revision") != binding["revision"]: + raise ValueError("unexpected browser identity") + return device + + +def settle_interrupted_binding(page, home: Path, binding: dict, status: dict, token) -> dict: + """恢复上一轮交接。即使上一次提交回执丢失,也以 Server 生效版本为准。""" + candidate_revision = status.get("platform_revision") + if status.get("replacement_pending"): + if matches_binding(status, binding) and not status.get("revoked"): + if resolve_binding(page, "resume", candidate_revision) != "invalid": + return profile_status(page) + if not token: + raise ValueError("candidate could not be verified; a fresh ticket is required") + if resolve_binding(page, "abort", candidate_revision) == "active": + save_binding(home, published_binding(status)) + if candidate_revision > binding["revision"]: + raise ValueError("a newer browser binding is already active") + return profile_status(page) + if type(candidate_revision) is int and candidate_revision > binding["revision"]: + if status.get("connected"): + save_binding(home, published_binding(status)) + raise ValueError("a newer browser binding already exists") + return status + + +def platform_start(page, home: Path, binding: dict, token) -> None: + """只在候选登记已经生效后更新本机发布版本。""" + status = settle_interrupted_binding(page, home, binding, profile_status(page), token) + prior = binding_for(home) + matches = matches_binding(status, binding, legacy=prior == binding) and not status.get("revoked") + if matches and not status.get("replacement_pending") and prior == binding: + if status.get("platform_revision") is None: + resolve_binding(page, "resume", binding["revision"]) + return + key = None if matches else redeem_binding(binding, token)["key"] + try: + if key is not None: + bind(page, binding, key) + verify_binding(page, binding, timeout=12, connected=True) + except (Error, OSError, ValueError, KeyError): + status = profile_status(page) + if status.get("authorizing"): + extension_request(page, {"type": "authorize_cancel"}, timeout=3) + if ( + status.get("replacement_pending") + and matches_binding(status, binding) + and resolve_binding(page, "abort", binding["revision"]) == "active" + ): + save_binding(home, binding) + return + raise + save_binding(home, binding) + + +def activate(playwright, home: Path, binding: dict, *, context=None, token=None, key=None): + """沿用原 Profile。只有新启动的 Chromium 由本次失败关闭。""" + current = context or open_browser(playwright, home, binding["browser_origin"]) + try: + with connection_page(current) as page: + if key is not None: + bind(page, binding, key) + verify_binding(page, binding) + save_binding(home, binding) + elif binding["revision"]: + platform_start(page, home, binding, token) + else: + status = profile_status(page) + if not matches_binding(status, binding) or status.get("revoked"): + (home / "binding.json").unlink(missing_ok=True) + raise BindingMissing("expected browser binding is missing") + return current + except (Error, OSError, ValueError, KeyError, TypeError): + if context is None: + current.close() + raise + + +def serve(home: Path, foreground: bool) -> None: + """监督单个 Chromium,Cube 可通过私有 socket 调用固定动作。""" + with profile_lock(home), sync_playwright() as playwright: + endpoint = home / "control.sock" + endpoint.unlink(missing_ok=True) + context = None + try: + if foreground: + binding = binding_for(home) + if binding is None: + raise ValueError("browser is unbound") + context = activate(playwright, home, binding) + with socket.socket(socket.AF_UNIX) as listener: + listener.bind(str(endpoint)) + listener.listen(2) + listener.settimeout(2) + while True: + try: + client, _ = listener.accept() + except TimeoutError: + if context is not None: + context.cookies("https://example.invalid/") + continue + with client, client.makefile("rb") as stream: + client.settimeout(2) + stop = False + try: + message = json.loads(stream.readline(MAX_MESSAGE + 1)) + match message["action"]: + case "start" if not foreground: + handoff = message["handoff"] + binding = platform_binding(handoff) + prior = binding_for(home) + if prior and ( + prior["browser_origin"] != binding["browser_origin"] + or prior["device_id"] != binding["device_id"] + or prior["revision"] > binding["revision"] + ): + raise ValueError("binding version or origin changed") + context = activate( + playwright, home, binding, context=context, + token=handoff.get("bootstrap_token"), + ) + case "stop": + if context is not None: + context.close() + context = None + stop = True + case "status": + pass + case _: + raise ValueError("invalid action") + result = describe(home, context) + except Error: + with suppress(OSError): + client.sendall(json.dumps(FAILED).encode() + b"\n") + raise + except (OSError, ValueError, KeyError, TypeError): + result = FAILED + with suppress(OSError): + client.sendall(json.dumps(result).encode() + b"\n") + if stop: + return + finally: + endpoint.unlink(missing_ok=True) + if context is not None: + with suppress(Error): + context.close() + + +def request_service(home: Path, action: str) -> dict: + """读取有界交接数据,只有 start 可创建监督进程。""" + message = {"action": action} + if action == "start": + message["handoff"] = json.loads(sys.stdin.buffer.readline(MAX_MESSAGE + 1)) + payload = json.dumps(message).encode() + b"\n" + if len(payload) > MAX_MESSAGE: + raise ValueError("control request too large") + with socket.socket(socket.AF_UNIX) as client: + client.settimeout(65 if action == "start" else 7) + endpoint = str(home / "control.sock") + try: + client.connect(endpoint) + except (FileNotFoundError, ConnectionRefusedError): + if action != "start": + # 正在启动的进程持锁;此时不能把缺失的 socket 判成未绑定。 + with profile_lock(home): + return describe(home) + subprocess.Popen( + [sys.executable, "-I", __file__, "_serve"], + stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + start_new_session=True, + ) + for _ in range(50): + try: + client.connect(endpoint) + break + except (FileNotFoundError, ConnectionRefusedError): + time.sleep(0.1) + else: + raise ValueError("browser supervisor did not start") + client.sendall(payload) + with client.makefile("rb") as stream: + return json.loads(stream.readline(MAX_MESSAGE + 1)) + + +def main() -> None: + """安装配置由系统账户拥有。长期凭据仅由扩展持久化。""" + parser = argparse.ArgumentParser(prog="abridge-client-browser") + commands = parser.add_subparsers(dest="action", required=True) + pair = commands.add_parser("bind", help="bind a Browser Device Key") + pair.add_argument("--server", required=True, help="public aBridge origin") + pair.add_argument("--stdin", action="store_true", help="read the key from private stdin") + pair.add_argument("--allow-http", action="store_true", help="confirm a specific HTTP origin") + for command in ("run", "status", "start", "stop", "_serve"): + commands.add_parser(command) + args = parser.parse_args() + + os.umask(0o077) + account_home = Path(pwd.getpwuid(os.getuid()).pw_dir) + home = Path(os.environ.get("ABRIDGE_BROWSER_HOME") or (account_home / ".local/state/abridge-client-browser")) + home.mkdir(mode=0o700, parents=True, exist_ok=True) + if home.stat().st_mode & 0o077 or home.stat().st_uid != os.getuid() or os.getuid() == 0: + raise ValueError("run as a non-root account with a private state directory") + bundled_browser = INSTALLATION / "chromium" + if bundled_browser.exists(): + os.environ["PLAYWRIGHT_BROWSERS_PATH"] = str(bundled_browser) + if args.action == "bind": + origin = valid_origin(args.server, args.allow_http) + if not args.stdin and not sys.stdin.isatty(): + raise ValueError("binding requires a terminal or private stdin") + key = sys.stdin.readline(MAX_MESSAGE).strip() if args.stdin else getpass.getpass("Browser Device Key: ") + with profile_lock(home), sync_playwright() as playwright: + prior = binding_for(home) + if prior and (prior["revision"] != 0 or prior["browser_origin"] != origin): + raise ValueError("existing binding belongs to another origin or platform") + device = device_request(origin, "/api/device", key=key) + result = {"device_id": device["id"], "browser_origin": origin, "revision": 0} + activate(playwright, home, result, key=key).close() + print(json.dumps(describe(home))) + elif args.action in {"run", "_serve"}: + signal.signal(signal.SIGTERM, lambda *_: sys.exit(0)) + serve(home, args.action == "run") + else: + result = request_service(home, args.action) + print(json.dumps(result)) + if result == FAILED: + sys.exit(1) + + +if __name__ == "__main__": + try: + main() + except (Error, OSError, ValueError, KeyError, TypeError): + sys.exit("Browser operation failed. Check the origin, credential and Chromium sandbox prerequisites.") diff --git a/apps/browser-client/requirements.txt b/apps/browser-client/requirements.txt new file mode 100644 index 0000000..718f8e9 --- /dev/null +++ b/apps/browser-client/requirements.txt @@ -0,0 +1 @@ +playwright==1.64.0 diff --git a/apps/browser/src/client.ts b/apps/browser/src/client.ts index 2a84b57..5615785 100644 --- a/apps/browser/src/client.ts +++ b/apps/browser/src/client.ts @@ -44,22 +44,27 @@ const incomingSchema = z device_name: deviceRenameSchema.shape.name.optional(), }) .passthrough(); +const profileSchema = z.object({ + key: z.string().optional(), + http_confirmed_origin: z.string().optional(), + revoked: z.boolean().optional(), + paused: z.boolean().optional(), + instance_id: z.string().optional(), + server: z.string().optional(), + device_id: z.string().optional(), + label: z.string().optional(), + platform_revision: z.number().int().positive().optional(), +}); +const journalSchema = z.record(z.string(), z.object({ status: z.string(), request_hash: z.string() })); +const replacementSchema = z.object({ device: profileSchema, operation_journal: journalSchema }); +const bindingIdentitySchema = deviceIdentitySchema.extend({ + pending: z.literal(true).optional(), + revision: z.number().int().positive().optional(), +}); const storedLocalSchema = z.object({ - device: z - .object({ - key: z.string().optional(), - http_confirmed_origin: z.string().optional(), - revoked: z.boolean().optional(), - paused: z.boolean().optional(), - instance_id: z.string().optional(), - server: z.string().optional(), - device_id: z.string().optional(), - label: z.string().optional(), - }) - .optional(), - operation_journal: z - .record(z.string(), z.object({ status: z.string(), request_hash: z.string() })) - .optional(), + device: profileSchema.optional(), + operation_journal: journalSchema.optional(), + binding_replacement: replacementSchema.nullish(), connection_history: z .object({ worker_started_at: z.number().optional(), @@ -201,6 +206,8 @@ export class BrowserDeviceClient { private bridge!: BrowserBridge; private socket: WebSocket | undefined; private profile: BrowserProfile = {}; + private replacement: z.infer | undefined; + private replacementConnecting = false; private connecting: Promise | undefined; private timer: ReturnType | undefined; private heartbeat: ReturnType | undefined; @@ -320,7 +327,7 @@ export class BrowserDeviceClient { } private async syncRecoveryAlarm() { if (this.disposed) return; - if (!this.profile?.key || this.profile.revoked) { + if (!this.canConnect()) { await this.chrome.alarms.clear(RECOVERY_ALARM); return; } @@ -350,11 +357,14 @@ export class BrowserDeviceClient { } private scheduleReconnect() { this.timers.clearTimeout(this.timer); - if (!this.disposed && this.profile?.key && !this.profile.revoked && !this.cleanupError) + if (!this.disposed && this.canConnect() && !this.cleanupError) this.timer = this.timers.setTimeout(() => { void this.connect().catch(() => {}); }, 2000); } + private canConnect(): boolean { + return !!this.profile.key && !this.profile.revoked && (!this.replacement || this.replacementConnecting); + } private result( connection: WebSocket, operationId: string, @@ -405,7 +415,8 @@ export class BrowserDeviceClient { } private async dispatch(connection: WebSocket, message: DeviceDispatchEnvelope) { const id = message.operation_id, - startedGeneration = this.generation; + startedGeneration = this.generation, + journal = this.journal; let tracked = false, intentWritten = false; try { @@ -468,22 +479,24 @@ export class BrowserDeviceClient { const requestHash = [...new Uint8Array(digest)] .map((value) => value.toString(16).padStart(2, "0")) .join(""); - if (this.journal[id]) { - if (this.journal[id].request_hash !== requestHash) + if (journal !== this.journal || startedGeneration !== this.generation || connection !== this.socket) + throw fail("session_closed", "任务已停止"); + if (journal[id]) { + if (journal[id].request_hash !== requestHash) throw fail("operation_conflict", "相同操作标识的参数不能改变"); this.result( connection, id, - this.journal[id].status === "executing" ? "outcome_unknown" : this.journal[id].status, + journal[id].status === "executing" ? "outcome_unknown" : journal[id].status, { deduplicated: true, }, ); return; } - if (Object.keys(this.journal).length >= OPERATION_JOURNAL_LIMIT) + if (Object.keys(journal).length >= OPERATION_JOURNAL_LIMIT) throw fail("journal_full", "操作记录已满,请重新绑定浏览器设备"); - this.journal[id] = { status: "executing", request_hash: requestHash }; + journal[id] = { status: "executing", request_hash: requestHash }; intentWritten = true; await this.saveJournal(); // Persist intent before any page side effect. if ( @@ -511,16 +524,21 @@ export class BrowserDeviceClient { }); if (this.cancelledOperations.has(id) && !response.error && response.result?.executed !== true) throw fail("operation_cancelled", "操作已取消,结果未知;不会重放"); + if (journal !== this.journal) return; const status = response.status; - this.journal[id].status = status; + journal[id].status = status; const receiptError = await this.saveTerminalJournal(response.error); if (this.cancelledOperations.has(id) && !response.error && response.result?.executed !== true) throw fail("operation_cancelled", "操作已取消,结果未知;不会重放"); this.result(connection, id, status, response.result || {}, receiptError); } catch (caught) { const error = errorDetails(caught); - if (intentWritten && (this.journal[id]?.status === "executing" || this.cancelledOperations.has(id))) { - this.journal[id].status = "outcome_unknown"; + if ( + intentWritten && + journal === this.journal && + (journal[id]?.status === "executing" || this.cancelledOperations.has(id)) + ) { + journal[id].status = "outcome_unknown"; const cause = operationErrorSchema.shape.cause.safeParse(error.cause); const receiptError = await this.saveTerminalJournal({ ...error, @@ -547,7 +565,7 @@ export class BrowserDeviceClient { await this.cleanup; if (this.disposed) return; if (this.cleanupError) throw this.cleanupError; - if (!this.profile.key || this.profile.revoked || this.authorization) return; + if (!this.canConnect() || this.authorization) return; if (this.connecting) return this.connecting; this.connecting = (async () => { if (this.socket) { @@ -583,7 +601,7 @@ export class BrowserDeviceClient { await this.cleanup; } // Binding may have started while retiring the previous connection. - if (this.disposed || this.authorization || !this.profile.key || this.profile.revoked) return; + if (this.disposed || this.authorization || !this.canConnect()) return; const server = serverURL(this.profile.server!, this.profile.http_confirmed_origin); const url = new URL(server + "/ws/browser"); url.protocol = url.protocol === "https:" ? "wss:" : "ws:"; @@ -731,6 +749,11 @@ export class BrowserDeviceClient { this.authenticated = false; this.timers.clearInterval(this.heartbeat); this.recordConnection({ last_disconnected_at: this.now(), last_close_code: event.code || 0 }); + if (this.replacement) { + // A staged credential is retried deliberately by the launcher. + this.replacementConnecting = false; + void this.track(this.syncRecoveryAlarm()); + } if ([4401, 4403].includes(event.code)) { this.profile.revoked = true; void this.track(this.chrome.storage.local.set({ device: this.profile })); @@ -767,10 +790,16 @@ export class BrowserDeviceClient { } private async initialize(): Promise { const saved = storedLocalSchema.parse( - await this.chrome.storage.local.get(["device", "operation_journal", "connection_history"]), + await this.chrome.storage.local.get([ + "device", + "operation_journal", + "binding_replacement", + "connection_history", + ]), ); this.assertRunning(); this.profile = saved.device || {}; + this.replacement = saved.binding_replacement ?? undefined; this.journal = saved.operation_journal || {}; this.connectionHistory = saved.connection_history || {}; for (const id in this.journal) @@ -788,6 +817,117 @@ export class BrowserDeviceClient { this.assertRunning(); await this.syncRecoveryAlarm(); } + + private verifyDevice(server: string, key: string, signal: AbortSignal) { + return requestBinding( + this.fetch, + server + "/api/device", + { + headers: { Authorization: `Bearer ${key}` }, + signal, + }, + bindingIdentitySchema, + true, + ); + } + + private async retireBindingConnection() { + // Retire callbacks first so asynchronous close/revoke cannot alter the restored binding. + const retired = this.socket; + this.socket = undefined; + this.authenticated = false; + this.timers.clearInterval(this.heartbeat); + this.timers.clearTimeout(this.timer); + retired?.close(); + await this.connecting?.catch(() => {}); + await this.stop(); + this.bridge.resetRequests(); + } + + private async resolvePlatformBinding(action: "resume" | "confirm" | "abort", revision: number) { + const { key, server, device_id, http_confirmed_origin, platform_revision } = this.profile; + if (this.authorization || !key || !server) throw fail("binding_changed", "当前登记版本与请求不符"); + const origin = serverURL(server, http_confirmed_origin); + const original = this.replacement; + if (!original && action === "resume" && platform_revision === undefined) { + const device = await this.verifyDevice(origin, key, this.lifetime.signal); + if ( + device.pending || + device.kind !== "browser" || + device.id !== device_id || + device.revision !== revision + ) + throw fail("binding_changed", "当前登记版本与请求不符"); + const next = { ...this.profile, platform_revision: revision }; + await this.chrome.storage.local.set({ device: next }); + this.profile = next; + return { ok: true, state: "active" }; + } + if (platform_revision !== revision) throw fail("binding_changed", "当前登记版本与请求不符"); + if (!original) return { ok: true, state: "active" }; + if (action !== "abort") { + let device: z.infer; + if (this.profile.revoked) return { ok: true, state: "invalid" }; + try { + device = await this.verifyDevice(origin, key, this.lifetime.signal); + } catch (error) { + if (errorDetails(error).code === "invalid_token") return { ok: true, state: "invalid" }; + throw error; + } + if (device.kind !== "browser" || device.id !== device_id || device.revision !== revision) + throw fail("device_mismatch", "Server 返回的设备不匹配"); + if (device.pending) { + if (action === "resume") { + this.replacementConnecting = true; + void this.connect().catch(() => {}); + } + return { ok: true, state: "pending" }; + } + } else { + this.replacementConnecting = false; + let status: "abandoned" | "invalid" | "active"; + try { + ({ status } = await requestBinding( + this.fetch, + origin + "/api/managed-browsers/abandon", + { + method: "POST", + headers: { Authorization: `Bearer ${key}` }, + signal: this.lifetime.signal, + }, + z.object({ status: z.enum(["abandoned", "invalid", "active"]) }), + )); + } catch (error) { + await this.retireBindingConnection(); + throw error; + } + if (status !== "active") { + await this.retireBindingConnection(); + // Only the device WS can distinguish explicit revocation from a proxy's HTTP denial. + const previous = { ...original.device, paused: !!(this.profile.paused || original.device.paused) }; + await this.chrome.storage.local.set({ + device: previous, + operation_journal: original.operation_journal, + binding_replacement: null, + }); + this.profile = previous; + this.journal = original.operation_journal; + this.replacement = undefined; + await this.syncRecoveryAlarm(); + void this.connect().catch(() => {}); + this.notify(); + return { ok: true, state: "restored" }; + } + } + // A response lost after cutover can be reconciled without republishing the prior key. + await this.chrome.storage.local.set({ binding_replacement: null }); + this.replacement = undefined; + this.replacementConnecting = false; + await this.syncRecoveryAlarm(); + void this.connect().catch(() => {}); + this.notify(); + return { ok: true, state: "active" }; + } private onMessage: Parameters[0] = ( raw: unknown, sender, @@ -812,9 +952,23 @@ export class BrowserDeviceClient { return false; } const message = parsed.data; + if ( + (message.type === "platform_binding" || + (message.type === "bind_token" && message.platform_revision !== undefined)) && + !connectionPage + ) + return false; if ( connectionPage && - !["status", "authorize", "bind_token", "authorize_cancel", "rename", "unbind"].includes(message.type) + ![ + "status", + "authorize", + "bind_token", + "platform_binding", + "authorize_cancel", + "rename", + "unbind", + ].includes(message.type) ) return false; if (message.type === "rename") { @@ -851,7 +1005,11 @@ export class BrowserDeviceClient { binding_method: this.authorization?.method, authorization_expires_at: this.authorization?.expiresAt, authorization_error: this.authorizationError, + platform_revision: this.profile.platform_revision, + replacement_pending: !!this.replacement, }; + if (message.type === "platform_binding") + return this.resolvePlatformBinding(message.action, message.revision); if (message.type === "authorize_cancel") { this.authorization?.controller.abort(); this.authorization = undefined; @@ -860,7 +1018,8 @@ export class BrowserDeviceClient { return { ok: true }; } if (message.type === "bind_token") { - if (this.authorization) throw fail("authorization_pending", "请先完成或取消当前授权"); + if (this.authorization || this.replacement) + throw fail("authorization_pending", "请先完成或取消当前授权"); const server = serverURL(message.server, message.http_confirmed_origin); const pending = { method: "token" as const, @@ -871,20 +1030,21 @@ export class BrowserDeviceClient { }; this.authorization = pending; this.authorizationError = undefined; + let reconnectPrevious: BrowserProfile | undefined; void (async () => { - const device = await requestBinding( - this.fetch, - server + "/api/device", - { - headers: { Authorization: `Bearer ${message.device_key}` }, - signal: pending.controller.signal, - }, - deviceIdentitySchema, - true, - ); + const device = await this.verifyDevice(server, message.device_key, pending.controller.signal); if (this.disposed || this.authorization !== pending || pending.controller.signal.aborted) return; if (device.kind !== "browser") throw fail("wrong_device_kind", "请使用浏览器设备的 Token,不能使用电脑、Agent 或管理员 Token"); + if ( + device.pending && + (message.platform_revision === undefined || + (this.profile.key && + (this.profile.server !== server || this.profile.device_id !== device.id))) + ) + throw fail("device_mismatch", "候选凭据只能用于同一设备的平台代理换绑"); + if (message.platform_revision !== undefined && device.revision !== message.platform_revision) + throw fail("binding_changed", "当前登记版本与请求不符"); this.configuration = this.configuration .catch(() => {}) .then(async () => { @@ -898,21 +1058,34 @@ export class BrowserDeviceClient { label: device.name, paused: !!this.profile.paused, http_confirmed_origin: message.http_confirmed_origin, + ...(message.platform_revision !== undefined && { + platform_revision: message.platform_revision, + }), }; - // Retire callbacks before awaiting cleanup: old close/revoke messages cannot alter the new binding. - const retired = this.socket; - this.socket = undefined; - this.authenticated = false; - this.timers.clearInterval(this.heartbeat); - retired?.close(); - await this.connecting?.catch(() => {}); - await this.stop(); + await this.retireBindingConnection(); + reconnectPrevious = this.profile; if (this.disposed || this.authorization !== pending || pending.controller.signal.aborted) return; - this.bridge.resetRequests(); - await this.chrome.storage.local.set({ device: next, operation_journal: {} }); + const original = device.pending + ? { + device: { ...this.profile }, + operation_journal: Object.fromEntries( + Object.entries(this.journal).map(([id, entry]) => [ + id, + entry.status === "executing" ? { ...entry, status: "outcome_unknown" } : entry, + ]), + ), + } + : undefined; + await this.chrome.storage.local.set({ + device: next, + operation_journal: {}, + binding_replacement: original ?? null, + }); this.profile = next; this.journal = {}; + this.replacement = original; + this.replacementConnecting = !!original; this.authorization = undefined; this.authorizationError = undefined; await this.syncRecoveryAlarm(); @@ -920,16 +1093,22 @@ export class BrowserDeviceClient { this.notify(); }); await this.configuration; - })().catch((caught: unknown) => { - if (this.authorization !== pending) return; - this.authorization = undefined; - this.authorizationError = errorDetails(caught).message; - this.notify(); - }); + })() + .catch((caught: unknown) => { + if (this.authorization !== pending) return; + this.authorization = undefined; + this.authorizationError = errorDetails(caught).message; + this.notify(); + }) + .finally(() => { + if (reconnectPrevious && this.profile === reconnectPrevious) + void this.connect().catch(() => {}); + }); this.notify(); return { ok: true }; } if (message.type === "authorize") { + if (this.replacement) throw fail("authorization_pending", "请先完成或取消当前授权"); if (this.profile.key && !this.profile.revoked) throw fail("already_registered", "当前浏览器已绑定,请先解除绑定"); if (this.authorization) throw fail("authorization_pending", "请先完成或取消当前授权"); diff --git a/apps/browser/src/types.ts b/apps/browser/src/types.ts index dc9febf..111d744 100644 --- a/apps/browser/src/types.ts +++ b/apps/browser/src/types.ts @@ -40,6 +40,7 @@ export interface BrowserProfile { server?: string; device_id?: string; label?: string; + platform_revision?: number; } export interface BrowserStatus { http_confirmed_origin?: string; @@ -58,6 +59,8 @@ export interface BrowserStatus { binding_method?: "browser" | "token"; authorization_expires_at?: number; authorization_error?: string; + platform_revision?: number; + replacement_pending?: boolean; } export type ControlType = "pause" | "resume" | "stop" | "unbind"; export type UiMessage = @@ -87,6 +90,11 @@ export const uiMessageSchema = z.discriminatedUnion("type", [ z.object({ type: z.literal("authorize_cancel") }), deviceRenameSchema.extend({ type: z.literal("rename") }).strict(), z.object({ type: z.enum(["pause", "resume", "stop", "unbind"]) }), + z.strictObject({ + type: z.literal("platform_binding"), + action: z.enum(["resume", "confirm", "abort"]), + revision: z.number().int().positive(), + }), z.object({ type: z.literal("authorize"), server: z.string(), @@ -99,6 +107,7 @@ export const uiMessageSchema = z.discriminatedUnion("type", [ server: z.string(), device_key: z.string().startsWith("abr_device_").max(4096), http_confirmed_origin: z.string().optional(), + platform_revision: z.number().int().positive().optional(), }) .strict(), ]); diff --git a/apps/browser/tests/worker.test.js b/apps/browser/tests/worker.test.js index bd59642..737b686 100644 --- a/apps/browser/tests/worker.test.js +++ b/apps/browser/tests/worker.test.js @@ -1250,6 +1250,139 @@ test("cancelling in-flight Token verification cannot commit a late reply", async assert.equal(local.device?.key, undefined); }); +for (const outcome of ["abandoned", "active", "invalid"]) { + test(`worker restart reconciles a candidate reported as ${outcome}`, async (t) => { + const server = "https://abridge.example"; + const candidateKey = "abr_device_candidate"; + const originalKey = "abr_device_original"; + const originalJournal = { write: { status: "executed", request_hash: "fixture" } }; + const identity = { id: "browser-device", name: "Browser", kind: "browser", capabilities: ["browser"] }; + const local = { + device: { server, key: originalKey, device_id: identity.id, paused: true, platform_revision: 1 }, + operation_journal: structuredClone(originalJournal), + }; + const bind = { + type: "bind_token", + server, + device_key: candidateKey, + platform_revision: 2, + }; + const fromConnection = (h, message) => h.fromPage(message, "connection.html"); + const resolve = (h, action) => fromConnection(h, { type: "platform_binding", action, revision: 2 }); + const waitConnected = async (h) => { + for (let i = 0; i < 50; i++) { + const status = await fromConnection(h, { type: "status" }); + if (status.connected) return status; + await delay(5); + } + assert.fail("worker did not connect"); + }; + + const first = harness(t, local); + first.environment.fetch = async (url, init) => { + assert.equal(url, `${server}/api/device`); + assert.equal(init.headers.Authorization, `Bearer ${candidateKey}`); + assert.equal(init.redirect, "error"); + return Response.json({ ...identity, pending: true, revision: 2 }); + }; + await first.start(); + await waitConnected(first); + assert.equal((await fromConnection(first, bind)).ok, true); + for (let i = 0; i < 50; i++) { + const status = await fromConnection(first, { type: "status" }); + if (status.connected && status.platform_revision === 2) break; + await delay(5); + } + assert.equal(local.device.key, candidateKey); + assert.equal(local.binding_replacement.device.key, originalKey); + assert.deepEqual(await resolve(first, "confirm"), { ok: true, state: "pending" }); + await first.client.close(); + + const resumed = harness(t, local); + resumed.environment.fetch = async (url, init) => { + if (url.endsWith("/abandon")) { + assert.equal(init.method, "POST"); + assert.equal(init.headers.Authorization, `Bearer ${candidateKey}`); + assert.equal(init.redirect, "error"); + return Response.json({ status: outcome }); + } + assert.equal(url, `${server}/api/device`); + if (init.headers.Authorization === `Bearer ${originalKey}`) + assert.fail("an HTTP error on the previous key must not block restoration or mark it revoked"); + if (outcome === "invalid" && init.headers.Authorization === `Bearer ${candidateKey}`) + return new Response(null, { status: 401 }); + assert.equal(init.headers.Authorization, "Bearer abr_device_fresh"); + return Response.json({ ...identity, pending: true, revision: 2 }); + }; + await resumed.start(); + resumed.chrome.runtime.onStartup.emit(); + await delay(10); + assert.equal(resumed.sockets.length, 0, "restart must not activate an unresolved candidate"); + if (outcome === "invalid") { + assert.deepEqual(await resolve(resumed, "resume"), { ok: true, state: "invalid" }); + assert.equal(resumed.sockets.length, 0, "a superseded candidate must not reconnect"); + } + const activated = outcome === "active"; + const state = activated ? "active" : "restored"; + assert.deepEqual(await resolve(resumed, "abort"), { ok: true, state }); + const connected = await waitConnected(resumed); + assert.equal(connected.platform_revision, activated ? 2 : 1); + assert.equal(connected.paused, true); + assert.equal(local.device.key, activated ? candidateKey : originalKey); + assert.deepEqual(local.operation_journal, activated ? {} : originalJournal); + assert.equal(local.binding_replacement, null); + if (outcome === "invalid") { + assert.equal((await fromConnection(resumed, { ...bind, device_key: "abr_device_fresh" })).ok, true); + for (let i = 0; i < 50 && local.device.key !== "abr_device_fresh"; i++) await delay(5); + assert.equal(local.device.key, "abr_device_fresh"); + assert.equal(local.binding_replacement.device.key, originalKey); + } + }); +} + +test("a failed candidate storage write reconnects the still-valid prior profile", async (t) => { + const server = "https://abridge.example"; + const local = { + device: { server, key: "abr_device_original", device_id: "browser-device", platform_revision: 1 }, + }; + const h = harness(t, local); + h.environment.fetch = async () => + Response.json({ + id: local.device.device_id, + name: "Candidate", + kind: "browser", + capabilities: ["browser"], + pending: true, + revision: 2, + }); + const save = h.chrome.storage.local.set; + h.chrome.storage.local.set = async (values) => { + if (values.binding_replacement) throw new Error("fixture storage failure"); + await save(values); + }; + await h.start(); + for (let i = 0; i < 50 && !(await h.popup({ type: "status" })).connected; i++) await delay(5); + assert.equal(h.sockets.length, 1); + assert.equal( + ( + await h.fromPage( + { type: "bind_token", server, device_key: "abr_device_candidate", platform_revision: 2 }, + "connection.html", + ) + ).ok, + true, + ); + for (let i = 0; i < 50 && h.sockets.length < 2; i++) await delay(5); + const status = await h.popup({ type: "status" }); + assert.equal(status.connected, true); + assert.equal(status.platform_revision, 1); + assert.equal(local.binding_replacement, undefined); + assert.deepEqual( + h.messages.filter(({ type }) => type === "hello").map(({ device_key }) => device_key), + ["abr_device_original", "abr_device_original"], + ); +}); + test("late close and revoke from a replaced browser binding cannot revoke the new Token", async (t) => { const local = { device: { diff --git a/apps/server/src/browser-execution.ts b/apps/server/src/browser-execution.ts index 80ee120..21dc6a0 100644 --- a/apps/server/src/browser-execution.ts +++ b/apps/server/src/browser-execution.ts @@ -27,7 +27,7 @@ type StepTool = (typeof STEP_TOOLS)[StepMethod]; /** All child steps enter ControlService's normal authorization and operation admission. */ interface ExecutionOperations { identifyStep(key: string): string; - executeStep(tool: StepTool, args: JsonObject, key: string): Promise; + executeStep(tool: StepTool, args: JsonObject, key: string, signal: AbortSignal): Promise; exists(id: string): boolean; receipt(id: string): OperationResponse | undefined; complete(status: OperationState, result?: unknown, error?: OperationError): void; @@ -67,8 +67,26 @@ export class BrowserExecutions { execution.controller.abort(new Error("Browser execution ended")); return progress; } - private progress(execution: Execution): JsonObject { + private pendingStep(execution: Execution): BrowserStepFailure | undefined { const step = execution.inFlightStep; + if (!step) return undefined; + if (!execution.operations.exists(step.operation_id)) + return { + ...step, + status: "refused", + error: { code: "step_not_dispatched", message: "The step ended before device dispatch" }, + }; + return { + ...step, + status: "outcome_unknown", + error: { + code: "step_receipt_unconfirmed", + message: "Execution ended before this step had a confirmed terminal receipt", + }, + }; + } + private progress(execution: Execution): JsonObject { + const step = this.pendingStep(execution); const receipt = step ? execution.operations.receipt(step.operation_id) : undefined; // A receipt may arrive before the awaiting runtime resumes. Count it once, // and never describe an already confirmed step as an unknown side effect. @@ -81,11 +99,8 @@ export class BrowserExecutions { status: receipt && ["refused", "failed", "cancelled"].includes(receipt.status) ? receipt.status - : "outcome_unknown", - error: receipt?.error ?? { - code: "step_receipt_unconfirmed", - message: "Execution ended before this step had a confirmed terminal receipt", - }, + : step.status, + error: receipt?.error ?? step.error, }, } : {}), @@ -116,18 +131,7 @@ export class BrowserExecutions { args.code, (method, callArgs) => this.step(execution, method, callArgs), execution.controller.signal, - (): BrowserStepFailure | undefined => - execution.inFlightStep - ? { - ...execution.inFlightStep, - status: "outcome_unknown", - error: { - code: "step_receipt_unconfirmed", - message: - "Parent execution ended before this step had a confirmed terminal receipt; query its operation_id before continuing", - }, - } - : undefined, + () => this.pendingStep(execution), ) .then( (result) => operations.complete("executed", result), @@ -161,7 +165,12 @@ export class BrowserExecutions { execution.inFlightStep = { operation_id: id, method }; let response: OperationResponse; try { - response = await execution.operations.executeStep(STEP_TOOLS[method as StepMethod], args, key); + response = await execution.operations.executeStep( + STEP_TOOLS[method as StepMethod], + args, + key, + execution.controller.signal, + ); } catch (caught) { // Admission only creates a record after validation and authorization. An // existing record means delivery or a receipt may already be in flight. diff --git a/apps/server/src/command.ts b/apps/server/src/command.ts index f900b4c..9ad3956 100644 --- a/apps/server/src/command.ts +++ b/apps/server/src/command.ts @@ -69,6 +69,11 @@ export async function serverMain(args = process.argv.slice(2)): Promise { !["true", "false"].includes(process.env.ABRIDGE_ALLOW_INSECURE_HTTP) ) throw new Error("ABRIDGE_ALLOW_INSECURE_HTTP must be true or false"); + if ( + process.env.ABRIDGE_MANAGED_BROWSER_ENABLED && + !["true", "false"].includes(process.env.ABRIDGE_MANAGED_BROWSER_ENABLED) + ) + throw new Error("ABRIDGE_MANAGED_BROWSER_ENABLED must be true or false"); const server = await createServer({ dbPath, identity: { @@ -79,6 +84,7 @@ export async function serverMain(args = process.argv.slice(2)): Promise { clientName: process.env.ABRIDGE_OIDC_CLIENT_NAME, clientSecret: process.env.ABRIDGE_OIDC_CLIENT_SECRET, delegationEnabled: process.env.ABRIDGE_DELEGATION_ENABLED === "true", + managedBrowserEnabled: process.env.ABRIDGE_MANAGED_BROWSER_ENABLED === "true", }, adminToken: process.env.ABRIDGE_ADMIN_TOKEN, resetAdminToken: values["reset-admin-token"], diff --git a/apps/server/src/control.ts b/apps/server/src/control.ts index fb88dde..5926beb 100644 --- a/apps/server/src/control.ts +++ b/apps/server/src/control.ts @@ -1,4 +1,6 @@ import { createHash, randomBytes } from "node:crypto"; +import { addAbortListener } from "node:events"; +import { setTimeout as delay } from "node:timers/promises"; import { CAPABILITIES, PROTOCOL_VERSION, @@ -22,6 +24,7 @@ import { type ConnectionLoss, type Capability, type DeviceKind, + type DeviceMetadata, type DeviceInteractionState, type DeviceTool, } from "@abridge/protocol"; @@ -53,6 +56,7 @@ const FINAL_STATES = new Set([ "cancelled", ]); const safeId = /^[A-Za-z0-9_-]{1,100}$/; +const BROWSER_RECONNECT_SECONDS = 15; function reportedCapabilities(kind: DeviceKind, values: JsonObject, interaction?: DeviceInteractionState) { const available = deviceCapabilities(kind); const screenBlocked = interaction !== undefined && interaction !== "ready"; @@ -65,7 +69,11 @@ function reportedCapabilities(kind: DeviceKind, values: JsonObject, interaction? ]), ); } -function requireLocalCapabilities(connection: DeviceConnection, capabilities: Capability[]) { +function requireLocalAccess( + connection: Pick, + capabilities: Capability[], +) { + if (connection.paused) throw new BridgeError("device_paused", "Resume access locally before continuing"); if (capabilities.some((cap) => cap === "screen" || cap === "input")) { if (connection.interactionState === "locked") throw new BridgeError("device_locked", "Unlock the Android device before continuing", 409, { @@ -172,7 +180,10 @@ export class ControlService { const connection = this.deviceConnections.get(device.id), now = this.mono(); const current = agentConnection ? this.currentAgentConnection(agentConnection) : undefined; - const online = !!connection && now - connection.heartbeatAt <= 30; + const online = + !!connection && + connection.credentialVersion === device.credential_version && + now - connection.heartbeatAt <= 30; const capabilities = current ? deviceAccess(current, device).capabilities : device.capabilities.filter((cap) => deviceCapabilities(device.kind).includes(cap)).sort(); @@ -210,41 +221,82 @@ export class ControlService { .map((p) => p.operation.id), }; } - private readyConnection(deviceId: string): DeviceConnection { + isLocalCapabilityBlocked(deviceId: string, capability: Capability): boolean { + const observed = this.observedLocalAccess(deviceId); + return !!observed && (observed.paused || !observed.capabilities[capability]); + } + private observedLocalAccess( + deviceId: string, + ): Pick | undefined { + return this.localAccess.get(deviceId) ?? this.store.browserLocalAccess(deviceId); + } + private recordLocalAccess(ticket: DeviceConnection): void { + if (ticket.kind === "browser") { + const observed = this.localAccess.get(ticket.deviceId); + if (observed?.paused !== ticket.paused || observed.capabilities.browser !== ticket.capabilities.browser) + this.store.recordBrowserLocalAccess( + ticket.deviceId, + ticket.paused, + ticket.capabilities.browser === true, + ); + } + this.localAccess.set(ticket.deviceId, { capabilities: ticket.capabilities, paused: ticket.paused }); + } + private requireDeviceAvailable(deviceId: string): void { if (this.shuttingDown) throw new BridgeError("server_stopping", "Server is stopping", 503); if (this.stopping.has(deviceId)) throw new BridgeError("device_busy", "Device is stopping existing operations", 409); - const connection = this.deviceConnections.get(deviceId), - device = this.store.device(deviceId); + } + private currentDeviceSocket(device: Device): DeviceConnection | undefined { + const connection = this.deviceConnections.get(device.id); if ( - !connection || - this.mono() - connection.heartbeatAt > 30 || - !device || - device.revoked_at !== null || - device.credential_version !== connection.credentialVersion || - device.epoch !== connection.epoch + connection && + this.mono() - connection.heartbeatAt <= 30 && + device.revoked_at === null && + device.credential_version === connection.credentialVersion && + device.epoch === connection.epoch ) + return connection; + } + private readyConnection(deviceId: string, required: Capability[]): DeviceConnection { + this.requireDeviceAvailable(deviceId); + const device = this.store.device(deviceId); + const connection = device && this.currentDeviceSocket(device); + if (!connection) throw new BridgeError("device_offline", "Device is offline; no other device will be selected"); - if (connection.paused) throw new BridgeError("device_paused", "Resume access locally before continuing"); + requireLocalAccess(connection, required); return connection; } - openSession( + async openSession( agentConnection: AgentConnection, deviceId: string, capabilities: Capability[], - ): ControlSession { - const current = this.currentAgentConnection(agentConnection), - device = this.authorizedDevice(current, deviceId); + signal?: AbortSignal, + ): Promise { if ( !capabilities.length || new Set(capabilities).size !== capabilities.length || capabilities.some((cap) => !CAPABILITIES.includes(cap)) ) throw new BridgeError("invalid_capabilities", "Select valid, unique capabilities", 422); - if (capabilities.some((cap) => !deviceAccess(current, device).capabilities.includes(cap))) - throw new BridgeError("forbidden", "Requested capability is not granted", 403); - const connection = this.readyConnection(deviceId); - requireLocalCapabilities(connection, capabilities); + const access = this.sessionOpenAccess(agentConnection, deviceId, capabilities); + let { current } = access; + const { device } = access; + if (device.kind === "browser") { + const live = await this.waitForLiveBrowser( + agentConnection, + deviceId, + capabilities, + device.credential_version, + signal, + ); + ({ current } = this.sessionOpenAccess(agentConnection, deviceId, capabilities)); + if (this.readyConnection(deviceId, capabilities) !== live) + throw new BridgeError("device_offline", "Browser connection changed while opening the session"); + } else { + this.readyConnection(deviceId, capabilities); + } + signal?.throwIfAborted(); const occupied = this.store .sessions(deviceId) .filter((session) => session.lease_until > this.now() && session.capabilities.includes("input")); @@ -266,6 +318,68 @@ export class ControlService { sessionDeadline(current, this.now() + SESSION_IDLE_SECONDS), ); } + private sessionOpenAccess(agentConnection: AgentConnection, deviceId: string, capabilities: Capability[]) { + const current = this.currentAgentConnection(agentConnection), + device = this.authorizedDevice(current, deviceId); + const granted = deviceAccess(current, device).capabilities; + if (capabilities.some((cap) => !granted.includes(cap))) + throw new BridgeError("forbidden", "Requested capability is not granted", 403); + return { current, device }; + } + private async waitForLiveBrowser( + agentConnection: AgentConnection, + deviceId: string, + capabilities: Capability[], + credentialVersion: number, + signal?: AbortSignal, + ): Promise { + const deadline = this.mono() + BROWSER_RECONNECT_SECONDS; + const timeout = AbortSignal.timeout(BROWSER_RECONNECT_SECONDS * 1000); + const waitSignal = signal ? AbortSignal.any([signal, timeout]) : timeout; + try { + while (this.mono() < deadline) { + waitSignal.throwIfAborted(); + this.requireDeviceAvailable(deviceId); + const { device } = this.sessionOpenAccess(agentConnection, deviceId, capabilities); + if (device.credential_version !== credentialVersion) + throw new BridgeError("device_offline", "Browser credentials changed while opening the session"); + const observed = this.observedLocalAccess(deviceId); + if (observed) requireLocalAccess(observed, capabilities); + const connection = this.currentDeviceSocket(device); + if (connection && (await this.waitForBrowserProbe(connection, waitSignal)) && this.mono() < deadline) + return connection; + const remaining = deadline - this.mono(); + if (remaining > 0) await delay(Math.min(200, remaining * 1000), undefined, { signal: waitSignal }); + } + } catch (error) { + signal?.throwIfAborted(); + if (!timeout.aborted) throw error; + } + throw new BridgeError("device_offline", "Browser did not reconnect; retry after it is online"); + } + private async waitForBrowserProbe(connection: DeviceConnection, signal?: AbortSignal): Promise { + signal?.throwIfAborted(); + const probe = this.confirmBrowserConnection(connection); + if (!signal) return probe; + // A cancelled request releases its wait. The shared probe can still serve other callers. + const cancelled = Promise.withResolvers(); + const listener = addAbortListener(signal, () => cancelled.reject(signal.reason)); + try { + return await Promise.race([probe, cancelled.promise]); + } finally { + listener[Symbol.dispose](); + } + } + private async confirmBrowserConnection(connection: DeviceConnection): Promise { + if (!connection.transport.probe) + throw new BridgeError("device_offline", "Browser transport cannot verify the connection"); + const alive = await connection.transport.probe(); + if (this.deviceConnections.get(connection.deviceId) !== connection) return false; + if (alive) return true; + this.dropConnection(connection, "connection_lost", 4408); + void connection.transport.close(4408, "Browser liveness check failed").catch(() => {}); + return false; + } sessionInfo(session: ControlSession): SessionInfo { return { id: session.id, @@ -430,7 +544,7 @@ export class ControlService { const device = this.authorizedDevice(current, operation.device_id); if (required.some((cap) => !deviceAccess(current, device).capabilities.includes(cap))) throw new BridgeError("forbidden", "Result is outside the current capability intersection", 403); - const local = this.localAccess.get(device.id); + const local = this.observedLocalAccess(device.id); if (local?.paused) throw new BridgeError("device_paused", "Resume access locally before reading results"); if (local && required.some((cap) => !local.capabilities[cap])) throw new BridgeError("capability_unavailable", "Local capability is disabled or unavailable"); @@ -502,7 +616,9 @@ export class ControlService { operationId?: string, wait = true, parentId?: string, + signal?: AbortSignal, ): Promise { + signal?.throwIfAborted(); const { tool, arguments: args } = parseDeviceToolRequest({ tool: requestedTool, arguments: input }); // Input preparation, transport and the bounded follow-up observation share the usual 30s. // A native hold and an explicit verification run sequentially before that observation. @@ -510,32 +626,15 @@ export class ControlService { tool === "browser_act" || tool === "browser_locate_act" ? (args.action.type === "click" ? (args.action.hold_ms ?? 0) : 0) + (args.verify?.timeout_ms ?? 0) : 0; - const deadline = this.mono() + 30 + extraMilliseconds / 1000, - current = this.currentAgentConnection(agentConnection), - session = this.authorizedSession(current, sessionId), - device = this.authorizedDevice(current, session.device_id); + const deadline = this.mono() + 30 + extraMilliseconds / 1000; const required = [...requiredCapabilities(tool, args)]; - if ( - required.some( - (cap) => - !session.capabilities.includes(cap) || !deviceAccess(current, device).capabilities.includes(cap), - ) - ) - throw new BridgeError("forbidden", "Operation is outside the current capability intersection", 403); + let { current, session, device } = this.operationTarget(agentConnection, sessionId, required); const requestHash = createHash("sha256") - .update(sortedJson({ tool, arguments: args, session_id: sessionId })) - .digest("hex"), - id = this.executionId(current, sessionId, operationId); - const previous = this.store.operation(id); - if (previous) { - this.authorizedOperation(current, id); - if (previous.request_hash !== requestHash) - throw new BridgeError( - "operation_conflict", - "An operation identifier cannot be reused with different arguments", - ); - return this.operationStatus(current, id); - } + .update(sortedJson({ tool, arguments: args, session_id: sessionId })) + .digest("hex"); + let id = this.executionId(current, sessionId, operationId); + const previous = this.replayedOperation(current, id, requestHash); + if (previous) return previous; if (!supportedDeviceTools(device.kind, device.platform).includes(tool)) throw new BridgeError( "unsupported_tool", @@ -545,6 +644,20 @@ export class ControlService { recovery: { action: "select_supported_tool" }, }, ); + const connection = this.readyConnection(device.id, required); + if (connection.kind === "browser") { + const live = await this.waitForBrowserProbe(connection, signal); + signal?.throwIfAborted(); + ({ current, session, device } = this.operationTarget(agentConnection, sessionId, required)); + if (!live || this.readyConnection(device.id, required) !== connection) + throw new BridgeError("device_offline", "Browser connection changed before dispatch"); + if (this.mono() >= deadline) + throw new BridgeError("operation_expired", "Operation start deadline elapsed"); + // Other callers can have admitted the same scoped request while the browser answered. + id = this.executionId(current, sessionId, operationId); + const replay = this.replayedOperation(current, id, requestHash); + if (replay) return replay; + } if ( tool === "browser_exec" && [...this.pending.values()].some((pending) => pending.operation.session_id === sessionId) @@ -555,13 +668,12 @@ export class ControlService { throw new BridgeError("session_busy", "Browser code owns this session until it finishes", 409); if (parentId && (!this.pending.has(parentId) || activeCode !== parentId)) throw new BridgeError("operation_cancelled", "Parent browser execution ended", 409); - const connection = this.readyConnection(device.id); - requireLocalCapabilities(connection, required); if ( this.pending.size >= 64 || [...this.pending.values()].filter((p) => p.operation.device_id === device.id).length >= 8 ) throw new BridgeError("busy", "Device execution queue is full", 429); + signal?.throwIfAborted(); this.store.createOperation({ id, owner_id: current.owner_id, @@ -593,8 +705,8 @@ export class ControlService { if (tool === "browser_exec") { this.browserExecutions.start(id, sessionId, args, { identifyStep: (key) => this.executionId(current, sessionId, key), - executeStep: (stepTool, stepArgs, key) => - this.execute(current, sessionId, stepTool, stepArgs, key, true, id), + executeStep: (stepTool, stepArgs, key, stepSignal) => + this.execute(current, sessionId, stepTool, stepArgs, key, true, id, stepSignal), exists: (stepId) => this.store.operation(stepId) !== undefined, receipt: (stepId) => this.cache.get(stepId)?.response, complete: (status, result, error) => this.finish(id, status, result, error), @@ -641,6 +753,30 @@ export class ControlService { } return response; } + private operationTarget(agentConnection: AgentConnection, sessionId: string, required: Capability[]) { + const current = this.currentAgentConnection(agentConnection), + session = this.authorizedSession(current, sessionId), + device = this.authorizedDevice(current, session.device_id); + const granted = deviceAccess(current, device).capabilities; + if (required.some((cap) => !session.capabilities.includes(cap) || !granted.includes(cap))) + throw new BridgeError("forbidden", "Operation is outside the current capability intersection", 403); + return { current, session, device }; + } + private replayedOperation( + agentConnection: AgentConnection, + id: string, + requestHash: string, + ): OperationResponse | undefined { + const previous = this.store.operation(id); + if (!previous) return undefined; + this.authorizedOperation(agentConnection, id); + if (previous.request_hash !== requestHash) + throw new BridgeError( + "operation_conflict", + "An operation identifier cannot be reused with different arguments", + ); + return this.operationStatus(agentConnection, id); + } async cancelOperation(agentConnection: AgentConnection, id: string): Promise { const operation = this.authorizedOperation(agentConnection, id); const active = this.store.session(operation.session_id)?.status === "active"; @@ -835,8 +971,12 @@ export class ControlService { kind: DeviceKind, hello: JsonObject, transport: DeviceTransport, + allowBrowserReplacement = false, + transportCanActivate?: () => boolean, ): Promise { - const initial = this.store.authenticateDevice(key); + const replacementDevice = () => + allowBrowserReplacement && kind === "browser" ? this.store.browserReplacementDevice(key) : undefined; + const initial = this.store.authenticateDevice(key) ?? replacementDevice(); if (!initial || initial.kind !== kind) throw new BridgeError("unauthorized", "Device key is invalid or has the wrong kind", 401); const metadata = deviceMetadataSchema.parse(hello); @@ -849,6 +989,18 @@ export class ControlService { .catch(() => {}) .then(async () => { let device = this.store.authenticateDevice(key); + if (!device) { + const replacement = replacementDevice(); + if (replacement) + return this.attachBrowserReplacement( + key, + replacement, + hello, + transport, + metadata, + transportCanActivate, + ); + } if (!device || device.kind !== kind) throw new BridgeError("unauthorized", "Device key was revoked", 401); const old = this.deviceConnections.get(device.id); @@ -860,34 +1012,16 @@ export class ControlService { if (!device || device.kind !== kind) throw new BridgeError("unauthorized", "Device key was revoked", 401); } - const capabilities = object(hello.capabilities) ? hello.capabilities : {}; - const ticket: DeviceConnection = { - deviceId: device.id, - epoch: this.store.nextEpoch(device.id), - credentialVersion: device.credential_version, - kind, - capabilities: reportedCapabilities(kind, capabilities, interactionState), - interactionState, - paused: hello.paused === true, - heartbeatAt: this.mono(), - sequence: 0, + const ticket = this.connectionTicket( + device, + this.store.nextEpoch(device.id), + hello, transport, - }; - this.deviceConnections.set(device.id, ticket); - this.localAccess.set(device.id, { capabilities: ticket.capabilities, paused: ticket.paused }); + interactionState, + ); + this.publishConnection(ticket); try { - await transport.send({ - type: "welcome", - protocol: PROTOCOL_VERSION, - device_id: device.id, - device_name: device.name, - owner_name: this.store.user(device.owner_id)?.username ?? "", - connection_epoch: ticket.epoch, - capabilities: device.capabilities, - heartbeat_interval: 10, - lease_seconds: 30, - server_time: this.now(), - }); + await transport.send(this.deviceWelcome(device, ticket.epoch)); if (this.deviceConnections.get(device.id) === ticket) this.store.updateDeviceMetadata(device.id, ticket.credentialVersion, ticket.epoch, metadata); } catch (error) { @@ -903,6 +1037,89 @@ export class ControlService { if (this.attachQueues.get(initial.id) === attaching) this.attachQueues.delete(initial.id); } } + private async attachBrowserReplacement( + key: string, + device: Device, + hello: JsonObject, + transport: DeviceTransport, + metadata: DeviceMetadata, + transportCanActivate?: () => boolean, + ): Promise { + this.requireDeviceAvailable(device.id); + const epoch = device.epoch + 1; // The per-device attach queue owns epoch advancement. + if (!transport.probe) + throw new BridgeError("device_offline", "Browser transport cannot verify the connection"); + await transport.send(this.deviceWelcome(device, epoch)); + // The challenge follows welcome on the wire. A failed welcome or round trip preserves the old binding. + if (!(await transport.probe())) + throw new BridgeError("device_offline", "Browser replacement did not confirm its connection"); + this.requireDeviceAvailable(device.id); + const observed = this.observedLocalAccess(device.id); + if (observed) requireLocalAccess(observed, ["browser"]); + if (transportCanActivate && !transportCanActivate()) + throw new BridgeError("device_offline", "Browser replacement connection is closing"); + const active = this.store.activateBrowserReplacement(key, epoch); + if (!active) throw new BridgeError("unauthorized", "Browser replacement is no longer valid", 401); + + const old = this.deviceConnections.get(device.id); + if (old) this.dropConnection(old, "revoked", 4403); + const ticket = this.connectionTicket(active, active.epoch, hello, transport); + this.publishConnection(ticket); + if (old) { + const reason = "Device credentials revoked"; + void old.transport + .send({ type: "revoke", connection_epoch: old.epoch, reason }) + .catch(() => {}) + .then(() => old.transport.close(4403, reason)) + .catch(() => {}); + } + try { + this.store.updateDeviceMetadata(active.id, ticket.credentialVersion, ticket.epoch, metadata); + } catch (error) { + this.dropConnection(ticket); + throw error; + } + return ticket; + } + private connectionTicket( + device: Device, + epoch: number, + hello: JsonObject, + transport: DeviceTransport, + interactionState?: DeviceInteractionState, + ): DeviceConnection { + const capabilities = object(hello.capabilities) ? hello.capabilities : {}; + return { + deviceId: device.id, + epoch, + credentialVersion: device.credential_version, + kind: device.kind, + capabilities: reportedCapabilities(device.kind, capabilities, interactionState), + interactionState, + paused: hello.paused === true, + heartbeatAt: this.mono(), + sequence: 0, + transport, + }; + } + private publishConnection(ticket: DeviceConnection): void { + this.recordLocalAccess(ticket); + this.deviceConnections.set(ticket.deviceId, ticket); + } + private deviceWelcome(device: Device, epoch: number): JsonObject { + return { + type: "welcome", + protocol: PROTOCOL_VERSION, + device_id: device.id, + device_name: device.name, + owner_name: this.store.user(device.owner_id)?.username ?? "", + connection_epoch: epoch, + capabilities: device.capabilities, + heartbeat_interval: 10, + lease_seconds: 30, + server_time: this.now(), + }; + } dropConnection( ticket: DeviceConnection, reason: ConnectionLoss["reason"] = "connection_lost", @@ -972,7 +1189,7 @@ export class ControlService { const values = object(message.capabilities) ? message.capabilities : ticket.capabilities; ticket.capabilities = reportedCapabilities(device.kind, values, ticket.interactionState); ticket.paused = message.paused === undefined ? ticket.paused : message.paused === true; - this.localAccess.set(device.id, { capabilities: ticket.capabilities, paused: ticket.paused }); + this.recordLocalAccess(ticket); ticket.heartbeatAt = this.mono(); this.store.touchDevice(device.id); if (ticket.paused && !wasPaused) await this.stopDevice(device.id, "Access paused locally"); diff --git a/apps/server/src/identity.ts b/apps/server/src/identity.ts index d12b6f3..43a562a 100644 --- a/apps/server/src/identity.ts +++ b/apps/server/src/identity.ts @@ -1,5 +1,16 @@ import * as oidc from "openid-client"; -import { createRemoteJWKSet, jwtVerify, customFetch as jwksFetch, errors as joseErrors } from "jose"; +import { + createRemoteJWKSet, + jwtVerify, + customFetch as jwksFetch, + errors as joseErrors, + type JWTPayload, +} from "jose"; +import { + managedBrowserBindingSchema, + managedBrowserClaimsSchema, + type BrowserEnrollmentScope, +} from "@abridge/protocol"; import { digest, Store } from "./store.js"; import { BridgeError, type AgentConnection } from "./types.js"; @@ -9,6 +20,7 @@ export interface IdentityConfig { clientName?: string; clientSecret?: string; delegationEnabled?: boolean; + managedBrowserEnabled?: boolean; backchannelOrigin?: string; allowInsecureHttp?: boolean; } @@ -83,9 +95,12 @@ export function validateIdentityConfig(config: IdentityConfig, origin: string | config.clientName || config.clientSecret || config.delegationEnabled || + config.managedBrowserEnabled || config.backchannelOrigin) ) throw new Error("OIDC issuer is required"); + if (config.managedBrowserEnabled && !config.delegationEnabled) + throw new Error("Managed browsers require OIDC platform delegation"); if (config.backchannelOrigin) { const backchannel = new URL(config.backchannelOrigin); if (!/^https?:$/.test(backchannel.protocol) || backchannel.origin !== config.backchannelOrigin) @@ -213,8 +228,12 @@ export class Identity { ); return { token: this.store.createLogin(user.id), returnTo: pending.returnTo }; } - /** 委托只接受特定受众、用途和客户端的短期签名令牌。 */ - async authenticate(token: string): Promise { + get managedBrowserEnabled(): boolean { + return this.config.managedBrowserEnabled === true; + } + + /** 委托只接受特定受众和客户端的短期签名令牌。调用方另行约束用途。 */ + private async verifyPlatformToken(token: string, path: string) { if (!this.config.delegationEnabled || !token || token.length > 16384) return undefined; const config = await this.getConfiguration(); if (!this.keys) @@ -226,7 +245,7 @@ export class Identity { try { ({ payload } = await jwtVerify(token, this.keys, { issuer: this.config.issuer!, - audience: this.origin + "/mcp", + audience: this.origin + path, algorithms: ["RS256"], requiredClaims: ["sub", "iat", "exp"], maxTokenAge: 60, @@ -246,7 +265,6 @@ export class Identity { } const now = Date.now() / 1000; if ( - payload.purpose !== "abridge-delegation" || payload.client_id !== this.config.clientId || typeof payload.iat !== "number" || typeof payload.exp !== "number" || @@ -255,7 +273,46 @@ export class Identity { !payload.sub ) return undefined; - return this.store.delegatedAgentConnection(this.config.issuer!, payload.sub, this.config.clientId!); + return payload; + } + + private browserIdentity(payload: JWTPayload | undefined) { + if (!payload || typeof payload.aud !== "string") return undefined; + const result = managedBrowserClaimsSchema.safeParse(payload); + if (!result.success) return undefined; + return { + ...result.data, + issuer: this.config.issuer!, + client_id: this.config.clientId!, + }; + } + + /** 个人登记与工作负载登记各自使用专用受众与用途。 */ + async authenticateBrowserEnrollment( + token: string, + scope: BrowserEnrollmentScope, + action: "status" | "provision" | "stop", + ) { + if (action === "provision" && !this.managedBrowserEnabled) + throw new BridgeError("managed_browser_disabled", "Managed browsers are not enabled", 404); + const payload = await this.verifyPlatformToken(token, `/api/${scope}-browsers/${action}`); + const grant = this.browserIdentity(payload); + if (!grant || payload?.purpose !== `abridge-${scope}-browser-${action}`) + throw new BridgeError("unauthorized", "A browser enrollment grant is required", 401); + return { grant, payload }; + } + + async authenticate(token: string): Promise { + const payload = await this.verifyPlatformToken(token, "/mcp"); + if (payload?.purpose !== "abridge-delegation") return undefined; + if (payload.installation_id !== undefined || payload.revision !== undefined) { + const grant = this.browserIdentity(payload); + const binding = managedBrowserBindingSchema.safeParse(payload); + if (this.managedBrowserEnabled && grant && binding.success) + return this.store.managedBrowserConnection(grant, binding.data); + return undefined; + } + return this.store.delegatedAgentConnection(this.config.issuer!, payload.sub!, this.config.clientId!); } private getConfiguration(): Promise { if (!this.enabled) throw new BridgeError("oidc_disabled", "External login is not configured", 404); diff --git a/apps/server/src/mcp.ts b/apps/server/src/mcp.ts index 4b273a4..154291e 100644 --- a/apps/server/src/mcp.ts +++ b/apps/server/src/mcp.ts @@ -122,20 +122,20 @@ export function createMcpServer(control: ControlService, agentConnection: AgentC name: string, description: string, schema: z.ZodObject, - run: (args: z.infer>) => Promise | unknown, + run: (args: z.infer>, signal: AbortSignal) => Promise | unknown, ): void { const desktop = name.startsWith("computer_"); server.registerTool( name, { description: "aBridge: " + description, inputSchema: z.object(schema.shape).strict() }, - async (args) => { + async (args, context) => { try { // Cross-field contract errors use the same structured result as domain refusals. // MCP still exposes the shared fields, defaults and scalar bounds. const parsed = schema.safeParse(args); if (!parsed.success) throw new BridgeError("invalid_arguments", parsed.error.issues[0]!.message, 422); - const value = await run(parsed.data), + const value = await run(parsed.data, context.mcpReq.signal), response = contentResponse(value, desktop); if ( object(value) && @@ -160,9 +160,19 @@ export function createMcpServer(control: ControlService, agentConnection: AgentC const exec = ( tool: DeviceTool, args: { session_id: string; operation_id?: string } & JsonObject, + signal: AbortSignal, ): Promise => { const { session_id, operation_id, ...arguments_ } = args; - return control.execute(agentConnection, session_id, tool, arguments_, operation_id); + return control.execute( + agentConnection, + session_id, + tool, + arguments_, + operation_id, + true, + undefined, + signal, + ); }; register( "devices_list", @@ -181,10 +191,10 @@ export function createMcpServer(control: ControlService, agentConnection: AgentC ); register( "session_open", - "Open a capability-scoped session on an explicit online device. Use available_tools for this session and obtain a new observation after opening it. Idle lease is 300 seconds, renewed by authorized operations and result queries. Read current session metadata in responses, not the initial deadline. On desktop_busy inspect device_get.sessions. Close it when finished.", + "Open a capability-scoped session on an explicit device. A browser may reconnect within 15 seconds. Use available_tools for this session and obtain a new observation after opening it. Idle lease is 300 seconds, renewed by authorized operations and result queries. Read current session metadata in responses, not the initial deadline. On desktop_busy inspect device_get.sessions. Close it when finished.", z.object({ device_id: id, capabilities: z.array(capabilitySchema).min(1).max(5) }).strict(), - (a) => { - const session = control.openSession(agentConnection, a.device_id, a.capabilities); + async (a, signal) => { + const session = await control.openSession(agentConnection, a.device_id, a.capabilities, signal); const device = control.deviceView( control.authorizedDevice(agentConnection, session.device_id), agentConnection, @@ -211,67 +221,67 @@ export function createMcpServer(control: ControlService, agentConnection: AgentC "computer_apps", "Find running apps; query also finds installed apps. Pass a returned bundle_id to computer_open.", computerAppsSchema.safeExtend(base), - (a) => exec("computer_apps", a), + (a, signal) => exec("computer_apps", a, signal), ); register( "computer_windows", "List windows for an explicit PID. Observe the returned window before acting.", computerWindowsSchema.safeExtend(base), - (a) => exec("computer_windows", a), + (a, signal) => exec("computer_windows", a, signal), ); register( "computer_open", "Launch or activate an app by exact bundle_id. Continue from result.observation, or choose a window from result.window_candidates with computer_observe. Never relaunch to refresh.", computerOpenSchema.safeExtend(base), - (a) => exec("computer_open", a), + (a, signal) => exec("computer_open", a, signal), ); register( "computer_observe", "On macOS, omit pid and window_id or pass the selected window's pid alone to refresh it. For a new target, pass pid for an app with one window or choose pid and window_id from computer_windows. Read available_actions and keyboard_focus. Use desktop=true for an explicit whole-desktop task. On Android use desktop=true and read supported_actions, supported_keys, and focus_status. An unconfirmed screen is read-only. References expire after 120 seconds or an action.", computerObserveSchema.safeExtend(base), - (a) => exec("computer_observe", a), + (a, signal) => exec("computer_observe", a, signal), ); register( "computer_act", "Act once with an observation_id from this session. Check available_actions on macOS or supported_actions and supported_keys on Android. Prefer a supported element_ref action. On a refused action with recovery.action=observe_again, observe once, verify the intended target and retry using the new reference. On user_handoff, stop sending input and ask the user to switch away from the protected screen. If execution is unknown, verify the effect before continuing. On macOS, middle and double clicks require screenshot coordinates. Window screenshot clicks default to background and need an unchanged window image. Use explicit action.delivery_mode=foreground for a screenshot click only when the intended target has verified focus; whole-desktop and modified clicks require it. A covering window can be reported in error.desktop. Use result.observation directly, including any new window target. Set screenshot=true for visual follow-up. wait_after_ms defaults to 2000.", computerActSchema.safeExtend(base), - (a) => exec("computer_act", a), + (a, signal) => exec("computer_act", a, signal), ); register( "browser_open", "Navigate the current task tab using the existing Profile/login and return its observation. To visit a link whose URL was observed, navigate to that URL here. Do not reopen to wait for loading.", browserOpenSchema.safeExtend(base), - (a) => exec("browser_open", a), + (a, signal) => exec("browser_open", a, signal), ); register( "browser_observe", "Refresh the current task tab. query is one case-insensitive substring or an array matching any substring in scanned loaded text/controls; zero matches do not establish that the page has no content. Use next_element_offset with the same query to page through controls in a fresh scan. Link target is the declared attribute. opened_tabs reports observed child tabs; use browser_open with the returned URL to navigate the task tab. References expire after 60s and actions/navigation.", browserObserveSchema.safeExtend(base), - (a) => exec("browser_observe", a), + (a, signal) => exec("browser_observe", a, signal), ); register( "browser_act", "Click, fill, press, select, hover or scroll a reference from the current task page observation. Native pointer actions already scroll and check the target. Scroll changes DOM offsets and reports actual delta; it does not dispatch wheel events. A successful click is not navigation confirmation; links may open another tab, which is not automatically adopted. For a native long press use click with hold_ms (0-10000); omitted means a normal click. Waits 2000ms by default before the follow-up observation; configure wait_after_ms for the expected UI response time. Optionally pass verify with a browser_wait condition scoped to the expected row/variant. A verification timeout preserves the input receipt; read that container before another write. Continue from the returned observation. Observation errors never justify repeating an executed action.", browserActSchema.safeExtend(base), - (a) => exec("browser_act", a), + (a, signal) => exec("browser_act", a, signal), ); register( "browser_read", "Read current page text or loaded table rows, or page a saved snapshot without capturing again. Offsets count text characters or table rows. Read coverage and truncation before drawing conclusions.", browserReadSchema.safeExtend(base), - (a) => exec("browser_read", a), + (a, signal) => exec("browser_read", a, signal), ); register( "browser_wait", "Wait for a selector or page text condition in the existing task tab. This is read-only; a timeout never justifies repeating an executed action.", browserWaitSchema.safeExtend(base), - (a) => exec("browser_wait", a), + (a, signal) => exec("browser_wait", a, signal), ); register( "browser_exec", 'Run an async JavaScript function body for batch actions or custom extraction; use await and return a JSON value. page always addresses the current task tab; a clicked link\'s new tab is not automatically adopted. Native locator actions already scroll and check their target. For native actions use page.locator({within: css,role: role,name: exactAccessibleName}) to target a control within one container (within is optional). Locator actions accept a final options object with a browser_wait condition in verify, e.g. fill(text,{verify:{selector,state:"value",value}}). Inspect executed and verification.matched before another write. CSS locators also support read and waitFor. Available: page.goto(url), page.observe(options), page.locator(css).click({hold_ms:1500})/fill(text)/press(key)/select(values)/hover()/scroll(deltaY,deltaX), page.read({selector,mode: text or tables,snapshot_id,offset,limit}), page.wait({selector,text,state,timeout_ms}), page.evaluate(functionOrExpression,arg), and page.frameLocator(css) for a single same-origin iframe. IMPORTANT: window/document exist ONLY inside page.evaluate, e.g. return await page.evaluate(() => document.title). This code runs in isolated QuickJS, not in the page or Node. No setTimeout/setInterval in this outer runtime: prefer page.wait or locator.waitFor for conditions; use await page.sleep(ms) for a cancellable 0-10000 ms delay. click() is a normal native click; click({hold_ms:1500}) holds the native mouse button before release. DOM dispatchEvent is synthetic input, not a native gesture. An unsupported tool gesture does not prove the website lacks that gesture. Only JSON state persists across calls; local variables/functions do not. Await every browser call. Stable operation_id recovers without replay. After yielding use operation_status for that same operation; operation_cancel stops it. Failed code may have completed steps: inspect the page and steps_completed before continuing, never replay the whole batch blindly. Session close clears state.', browserExecSchema.safeExtend({ ...base, wait_seconds: wait }), - async (a) => { + async (a, signal) => { const { session_id, operation_id, wait_seconds, ...args } = a; const started = await control.execute( agentConnection, @@ -280,6 +290,8 @@ export function createMcpServer(control: ControlService, agentConnection: AgentC args, operation_id, false, + undefined, + signal, ); return control.waitOperation(agentConnection, started.operation_id, wait_seconds); }, @@ -288,7 +300,7 @@ export function createMcpServer(control: ControlService, agentConnection: AgentC "command_execute", "Run a user shell command. Short commands return output and exit code directly; wait_seconds defaults to 15s. Yielding does not cancel. Page retained output using next_output_offsets and operation_status, never rerun.", commandExecuteSchema.safeExtend({ ...base, wait_seconds: wait, output_limit_chars: outputLimit }), - async (a) => { + async (a, signal) => { const { wait_seconds, output_limit_chars, session_id, operation_id, ...args } = a; const started = await control.execute( agentConnection, @@ -297,6 +309,8 @@ export function createMcpServer(control: ControlService, agentConnection: AgentC args, operation_id, false, + undefined, + signal, ); return commandOutputPage( await control.waitOperation(agentConnection, started.operation_id, wait_seconds), @@ -334,16 +348,19 @@ export function createMcpServer(control: ControlService, agentConnection: AgentC "files_list", "List directory entries on the device. macOS and Linux expand ~/ to the device user's home (e.g. ~/Downloads). Android uses /workspace for its granted directory.", filesListSchema.safeExtend(base), - (a) => exec("files_list", a), + (a, signal) => exec("files_list", a, signal), ); - register("file_read", "Read a UTF-8 file, bounded to one MiB.", fileReadSchema.safeExtend(base), (a) => - exec("file_read", a), + register( + "file_read", + "Read a UTF-8 file, bounded to one MiB.", + fileReadSchema.safeExtend(base), + (a, signal) => exec("file_read", a, signal), ); register( "file_write", "Write a UTF-8 file. Content is bounded to one MiB.", fileWriteSchema.safeExtend(base), - (a) => exec("file_write", a), + (a, signal) => exec("file_write", a, signal), ); return server; } diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index d6adfe5..b659919 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -20,12 +20,16 @@ import { deviceAuthorizationDecisionSchema, deviceAuthorizationTokenRequestSchema, deviceAuthorizationCancelSchema, + managedBrowserBindingSchema, + managedBrowserProvisionSchema, + personalBrowserProvisionSchema, + managedBrowserRedeemSchema, adminCreateUserSchema, type AdminOverview, } from "@abridge/protocol"; import { Identity, validateIdentityConfig, type IdentityConfig } from "./identity.js"; import { AdminAuth, ADMIN_SESSION_SECONDS, loadAdminToken } from "./admin.js"; -import { Store, acquireInstanceLock } from "./store.js"; +import { Store, acquireInstanceLock, type BrowserEnrollmentIdentity } from "./store.js"; import { DeviceAuthorizations } from "./device-authorization.js"; import { ControlService } from "./control.js"; import { createMcpServer } from "./mcp.js"; @@ -144,6 +148,7 @@ export async function createServer(config: ServerConfig) { const extensionAuthorization = (pathname === "/api/device-authorizations" && request.method === "POST") || (pathname === "/api/device-authorizations/token" && request.method === "POST") || + (pathname === "/api/managed-browsers/abandon" && request.method === "POST") || (pathname === "/api/device" && ["GET", "PATCH"].includes(request.method)) || (/^\/api\/device-authorizations\/[^/]+$/.test(pathname) && request.method === "DELETE"); if (pathname === "/ws/browser" || (extensionAuthorization && browserOrigin.test(origin))) { @@ -365,9 +370,25 @@ export async function createServer(config: ServerConfig) { return control.deviceView(store.device(device.id)!); }); app.get("/api/device", async (request) => { - const device = store.authenticateDevice(bearer(request)); + const key = bearer(request); + const active = store.authenticateDevice(key); + const device = + active ?? (identity.managedBrowserEnabled ? store.browserReplacementDevice(key) : undefined); if (!device) throw new BridgeError("unauthorized", "设备 Token 无效或已撤销", 401); - return { id: device.id, name: device.name, kind: device.kind, capabilities: device.capabilities }; + const revision = + device.kind === "browser" + ? active + ? store.browserEnrollmentRevision(device.id) + : store.browserReplacement(device.id)?.revision + : undefined; + return { + id: device.id, + name: device.name, + kind: device.kind, + capabilities: device.capabilities, + ...(revision !== undefined && { revision }), + ...(!active && { pending: true }), + }; }); app.patch("/api/device", async (request) => { const device = store.authenticateDevice(bearer(request)); @@ -392,7 +413,7 @@ export async function createServer(config: ServerConfig) { app.post("/api/devices/:id/credentials", async (request) => { const device = owned(request); if (device.revoked_at !== null) throw new BridgeError("revoked", "Device was revoked", 409); - const key = store.rotateDevice(device.id); + const key = store.rotateDeviceCredentials(device.id); await control.invalidateDevice(device.id); store.audit(device.owner_id, device.id, null, null, "device_credentials", "rotated"); return { id: device.id, key }; @@ -497,6 +518,131 @@ export async function createServer(config: ServerConfig) { request.headers.origin, ); }); + function browserBindingView( + row: NonNullable | ReturnType>, + ) { + const device = store.device(row.device_id)!; + const view = control.deviceView(device); + const revoked = + view.status === "revoked" || + ("agent_connection_id" in row && store.agentConnection(row.agent_connection_id)?.revoked_at !== null); + return { + installation_id: row.installation_id, + revision: row.revision, + device_id: row.device_id, + key_issued: !!row.key_issued, + status: revoked + ? "revoked" + : control.isLocalCapabilityBlocked(row.device_id, "browser") + ? "paused" + : view.status, + }; + } + + function browserReplacementView(row: NonNullable>) { + return { + installation_id: row.installation_id, + revision: row.revision, + device_id: row.device_id, + key_issued: row.key_digest !== null, + status: "offline", + pending: true, + expires_at: row.expires_at, + }; + } + + for (const scope of ["managed", "personal"] as const) { + const path = `/api/${scope}-browsers`; + const registration = (grant: BrowserEnrollmentIdentity) => + scope === "managed" ? store.managedBrowser(grant) : store.personalBrowser(grant); + app.get(path + "/status", async (request, reply) => { + const { grant } = await identity.authenticateBrowserEnrollment(bearer(request), scope, "status"); + const row = registration(grant); + const replacement = row && store.browserReplacement(row.device_id); + reply.header("Cache-Control", "no-store"); + return { + version: 2, + enabled: identity.managedBrowserEnabled, + browser_origin: publicOrigin!.origin, + binding: row ? browserBindingView(row) : null, + ...(replacement && { replacement: browserReplacementView(replacement) }), + }; + }); + app.post(path + "/provision", async (request, reply) => { + const { grant, payload } = await identity.authenticateBrowserEnrollment( + bearer(request), + scope, + "provision", + ); + const existing = registration(grant); + if (existing && browserBindingView(existing).status === "paused") + throw new BridgeError("device_paused", "Resume the browser's local access before provisioning", 409); + const { row, replacement } = + scope === "managed" + ? store.provisionManagedBrowser(grant, managedBrowserProvisionSchema.parse(payload)) + : store.provisionPersonalBrowser( + grant, + personalBrowserProvisionSchema.parse(payload), + config.identity?.clientName?.trim(), + ); + const view = browserBindingView(row); + if (view.status === "revoked") + throw new BridgeError("managed_browser_revoked", "Browser access was revoked", 403); + reply.header("Cache-Control", "no-store"); + if (replacement) + return { + ...browserReplacementView(replacement), + key_issued: false, + bootstrap_token: store.issueReplacementBootstrap(replacement), + }; + return { + ...view, + bootstrap_token: store.issueBrowserBootstrap(row, scope), + }; + }); + } + app.post("/api/managed-browsers/redeem", async (request, reply) => { + if (!identity.managedBrowserEnabled) + throw new BridgeError("managed_browser_disabled", "Managed browsers are not enabled", 404); + rateLimit(request, "managed-browser-redeem", 120); + const body = managedBrowserRedeemSchema.parse(request.body); + const { device, key, pending, revision } = store.redeemManagedBrowser( + body.device_id, + body.bootstrap_token, + control.isLocalCapabilityBlocked(body.device_id, "browser"), + ); + if (!pending) { + await control.invalidateDevice(device.id); + if (!store.authenticateDevice(key)) + throw new BridgeError("stale_binding", "The browser binding changed", 409); + } + reply.header("Cache-Control", "no-store"); + return { + device_id: device.id, + key, + pending, + revision, + kind: device.kind, + name: device.name, + capabilities: device.capabilities, + }; + }); + app.post("/api/managed-browsers/abandon", async (request) => { + rateLimit(request, "browser-replacement-abandon", 120); + return { status: store.abandonBrowserReplacement(bearer(request)) }; + }); + app.post("/api/managed-browsers/stop", async (request, reply) => { + const { grant, payload } = await identity.authenticateBrowserEnrollment( + bearer(request), + "managed", + "stop", + ); + const row = store.stopManagedBrowser(grant, managedBrowserBindingSchema.parse(payload)); + await control.invalidateDevice(row.device_id); + reply.header("Cache-Control", "no-store"); + return browserBindingView(row); + }); + app.all("/mcp", async (request, reply) => { const token = bearer(request); const agentConnection = store.authenticateAgent(token) ?? (await identity.authenticate(token)); @@ -517,6 +663,10 @@ export async function createServer(config: ServerConfig) { void mcp.close().catch(() => {}); }; reply.raw.once("close", cleanup); + if (reply.raw.destroyed) { + cleanup(); + return; + } try { await transport.handleRequest(request.raw, reply.raw, request.body); } catch { @@ -582,7 +732,14 @@ export async function createServer(config: ServerConfig) { const key = kind === "browser" ? hello.device_key : bearer(request); if (typeof key !== "string") throw new BridgeError("unauthorized", "Device key is required", 401); - ticket = await control.attachConnection(key, kind, hello, transport); + ticket = await control.attachConnection( + key, + kind, + hello, + transport, + identity.managedBrowserEnabled, + () => !closed && socket.readyState === socket.OPEN, + ); clearTimeout(timer); if (closed) { control.dropConnection(ticket); @@ -592,9 +749,13 @@ export async function createServer(config: ServerConfig) { } await control.receive(ticket, message); }) - .catch(async () => { + .catch(async (error: unknown) => { closed = true; clearTimeout(timer); + if (!ticket && error instanceof BridgeError && error.status === 401) { + await transport.close(4401, "Device key is invalid or revoked"); + return; + } if (ticket) control.dropConnection(ticket, "invalid_message", 4400); await transport.close(4400, "Invalid or stale device message"); }) diff --git a/apps/server/src/store.ts b/apps/server/src/store.ts index 02e71c1..b6afc57 100644 --- a/apps/server/src/store.ts +++ b/apps/server/src/store.ts @@ -1,4 +1,4 @@ -import { createHash, pbkdf2, randomBytes, timingSafeEqual } from "node:crypto"; +import { createHash, createHmac, pbkdf2, randomBytes, timingSafeEqual } from "node:crypto"; import { chmodSync, mkdirSync } from "node:fs"; import { dirname, resolve } from "node:path"; import { DatabaseSync, type SQLInputValue } from "node:sqlite"; @@ -10,6 +10,11 @@ import { type DeviceKind, type DeviceMetadata, type ConnectionPolicy, + type BrowserEnrollmentScope, + type ManagedBrowserBinding, + type ManagedBrowserClaims, + type ManagedBrowserProvision, + type PersonalBrowserProvision, } from "@abridge/protocol"; import { validatePolicy } from "./policy.js"; import { @@ -43,26 +48,100 @@ const SCHEMA = [ "CREATE INDEX operation_owner ON operations(owner_id,created_at); CREATE INDEX audit_owner ON audit(owner_id,created_at); PRAGMA user_version=6;", ].join("\n"); +const MANAGED_BROWSER_SCHEMA = `CREATE TABLE IF NOT EXISTS managed_browsers( + issuer TEXT NOT NULL, subject TEXT NOT NULL, client_id TEXT NOT NULL, + installation_id TEXT NOT NULL, revision INTEGER NOT NULL, + device_id TEXT UNIQUE NOT NULL REFERENCES devices(id), + agent_connection_id TEXT UNIQUE NOT NULL REFERENCES agent_connections(id), + bootstrap_nonce TEXT, bootstrap_expires_at REAL, key_issued INTEGER NOT NULL DEFAULT 0, + PRIMARY KEY(issuer,subject,client_id), + FOREIGN KEY(issuer,subject) REFERENCES external_identities(issuer,subject) +);`; + +const PERSONAL_BROWSER_SCHEMA = `CREATE TABLE IF NOT EXISTS personal_browsers( + issuer TEXT NOT NULL, subject TEXT NOT NULL, client_id TEXT NOT NULL, + installation_id TEXT NOT NULL, revision INTEGER NOT NULL, + device_id TEXT UNIQUE NOT NULL REFERENCES devices(id), + bootstrap_nonce TEXT, bootstrap_expires_at REAL, key_issued INTEGER NOT NULL DEFAULT 0, + PRIMARY KEY(issuer,subject,client_id), + FOREIGN KEY(issuer,subject) REFERENCES external_identities(issuer,subject) +);`; + +const BROWSER_REPLACEMENT_SCHEMA = `CREATE TABLE IF NOT EXISTS browser_replacements( + device_id TEXT PRIMARY KEY REFERENCES devices(id), + scope TEXT NOT NULL CHECK(scope IN ('managed','personal')), + installation_id TEXT NOT NULL, revision INTEGER NOT NULL, credential_version INTEGER NOT NULL, + expires_at REAL NOT NULL, bootstrap_nonce TEXT, bootstrap_expires_at REAL, key_digest TEXT UNIQUE +);`; +const BROWSER_REPLACEMENT_SECONDS = 300; +const BROWSER_LOCAL_ACCESS_SCHEMA = `CREATE TABLE IF NOT EXISTS browser_local_access( + device_id TEXT PRIMARY KEY REFERENCES devices(id), paused INTEGER NOT NULL, enabled INTEGER NOT NULL +);`; + +export type BrowserEnrollmentIdentity = ManagedBrowserClaims & { + issuer: string; + client_id: string; +}; + +interface BrowserEnrollment extends ManagedBrowserBinding { + device_id: string; + bootstrap_nonce: string | null; + bootstrap_expires_at: number | null; + key_issued: number; +} + +interface ManagedBrowser extends BrowserEnrollment { + agent_connection_id: string; +} + +interface BrowserReplacement extends ManagedBrowserBinding { + device_id: string; + scope: BrowserEnrollmentScope; + credential_version: number; + expires_at: number; + bootstrap_nonce: string | null; + bootstrap_expires_at: number | null; + key_digest: string | null; +} + /** One SQL implementation. Compound state and audit mutations share a transaction. */ export class Store { private readonly db: DatabaseSync; + private readonly bootstrapKey = randomBytes(32); readonly path: string; constructor(path: string) { this.path = resolve(path); mkdirSync(dirname(this.path), { recursive: true, mode: 0o700 }); this.db = new DatabaseSync(this.path); chmodSync(this.path, 0o600); - this.db.exec("PRAGMA foreign_keys=ON; PRAGMA journal_mode=WAL; PRAGMA busy_timeout=5000;"); - const version = Number(this.one<{ user_version: number }>("PRAGMA user_version")?.user_version ?? 0); - if (version === 0) this.transaction(() => this.db.exec(SCHEMA)); - else if (version !== 6) { + try { + this.db.exec("PRAGMA foreign_keys=ON; PRAGMA journal_mode=WAL; PRAGMA busy_timeout=5000;"); + const version = this.one<{ user_version: number }>("PRAGMA user_version")!.user_version; + if (version === 0) this.transaction(() => this.db.exec(SCHEMA)); + else if (version !== 6) + throw new BridgeError("schema_mismatch", "Use a development database matching this version", 500); + + this.db.exec(MANAGED_BROWSER_SCHEMA); + const columns = new Set( + this.all<{ name: string }>("PRAGMA table_info(managed_browsers)").map(({ name }) => name), + ); + if (!["installation_id", "revision", "key_issued"].every((column) => columns.has(column))) + throw new BridgeError( + "managed_browser_schema_mismatch", + "Convert legacy managed browser bindings offline before starting the server", + 500, + ); + this.db.exec(PERSONAL_BROWSER_SCHEMA); + this.db.exec(BROWSER_REPLACEMENT_SCHEMA); + this.db.exec(BROWSER_LOCAL_ACCESS_SCHEMA); + this.db.exec( + "CREATE INDEX IF NOT EXISTS active_session_device ON control_sessions(device_id) WHERE status='active'; " + + "CREATE INDEX IF NOT EXISTS active_session_agent_connection ON control_sessions(agent_connection_id) WHERE status='active';", + ); + } catch (error) { this.db.close(); - throw new BridgeError("schema_mismatch", "Use a development database matching this version", 500); + throw error; } - this.db.exec( - "CREATE INDEX IF NOT EXISTS active_session_device ON control_sessions(device_id) WHERE status='active'; " + - "CREATE INDEX IF NOT EXISTS active_session_agent_connection ON control_sessions(agent_connection_id) WHERE status='active';", - ); } close(): void { this.db.close(); @@ -161,46 +240,423 @@ export class Store { } /** 以签发方和稳定主体首次开户,绝不按显示名称合并。 */ externalUser(issuer: string, subject: string, label: string, clientId?: string, clientName?: string): User { + return this.transaction(() => this.ensureLoginUser(issuer, subject, label, clientId, clientName)); + } + private ensureLoginUser( + issuer: string, + subject: string, + label: string, + clientId?: string, + clientName?: string, + ): User { + if (this.one("SELECT 1 FROM managed_browsers WHERE issuer=? AND subject=?", issuer, subject)) + throw new BridgeError("managed_identity", "Workload identities cannot log in", 403); + const user = this.ensureExternalUser(issuer, subject, label); + if (clientId) + this.ensurePlatformConnection(user.id, issuer, subject, clientId, clientName, { + mode: "all", + capabilities: [...CAPABILITIES], + overrides: [], + }); + return user; + } + private ensurePlatformConnection( + owner: string, + issuer: string, + subject: string, + clientId: string, + clientName: string | undefined, + policy: ConnectionPolicy, + ): void { + const linked = this.one( + "SELECT 1 FROM platform_connections WHERE issuer=? AND subject=? AND client_id=?", + issuer, + subject, + clientId, + ); + if (linked) return; + const connection = this.insertPlatformConnection(owner, (clientName ?? clientId) + " 平台连接", policy); + this.run("INSERT INTO platform_connections VALUES(?,?,?,?)", issuer, subject, clientId, connection); + } + private insertPlatformConnection(owner: string, name: string, policy: ConnectionPolicy): string { + const id = identifier("agt"); + this.run( + "INSERT INTO agent_connections VALUES(?,?,?,?,NULL,NULL,NULL,?,NULL)", + id, + owner, + name, + JSON.stringify(policy), + nowSeconds(), + ); + return id; + } + private ensureExternalUser(issuer: string, subject: string, label: string): User { + const existing = this.one<{ user_id: string }>( + "SELECT user_id FROM external_identities WHERE issuer=? AND subject=?", + issuer, + subject, + ); + if (existing) return this.user(existing.user_id)!; + const id = identifier("usr"); + const username = label.slice(0, 50) + " · " + id.slice(4); + this.run("INSERT INTO users VALUES(?,?,NULL,NULL,?)", id, username, nowSeconds()); + this.run("INSERT INTO external_identities VALUES(?,?,?)", issuer, subject, id); + return { id, username }; + } + + managedBrowser(grant: BrowserEnrollmentIdentity): ManagedBrowser | undefined { + return this.one( + "SELECT * FROM managed_browsers WHERE issuer=? AND subject=? AND client_id=?", + grant.issuer, + grant.sub, + grant.client_id, + ); + } + + provisionManagedBrowser(grant: BrowserEnrollmentIdentity, binding: ManagedBrowserProvision) { return this.transaction(() => { - const existing = this.one<{ user_id: string }>( - "SELECT user_id FROM external_identities WHERE issuer=? AND subject=?", - issuer, - subject, + const existing = this.managedBrowser(grant); + if (binding.revision !== (existing?.revision ?? 0)) + throw new BridgeError("stale_binding", "The browser binding changed", 409); + if (existing) { + const device = this.device(existing.device_id)!; + const connection = this.agentConnection(existing.agent_connection_id)!; + if (device.revoked_at !== null || connection.revoked_at !== null) + throw new BridgeError("managed_browser_revoked", "Managed browser access was revoked", 403); + if (!binding.replace) { + if (existing.installation_id !== binding.installation_id) + throw new BridgeError("stale_binding", "Browser reinstall requires replacement", 409); + return { row: existing, replacement: undefined }; + } + return { row: existing, replacement: this.stageBrowserReplacement("managed", existing, binding) }; + } + + if (this.one("SELECT 1 FROM external_identities WHERE issuer=? AND subject=?", grant.issuer, grant.sub)) + throw new BridgeError("managed_identity", "An existing login cannot be enrolled as a workload", 403); + const user = this.ensureExternalUser(grant.issuer, grant.sub, grant.sub); + const name = "托管浏览器"; + const device = this.insertDevice(user.id, name, ["browser"], "browser", secretKey("device")); + const connectionId = this.insertPlatformConnection(user.id, name, { + mode: "selected", + devices: [{ device_id: device.id, capabilities: ["browser"] }], + }); + this.run( + "INSERT INTO managed_browsers(issuer,subject,client_id,installation_id,revision,device_id,agent_connection_id) VALUES(?,?,?,?,1,?,?)", + grant.issuer, + grant.sub, + grant.client_id, + binding.installation_id, + device.id, + connectionId, ); - const user = existing ? this.user(existing.user_id)! : { id: identifier("usr"), username: "" }; - if (!existing) { - user.username = label.slice(0, 50) + " · " + user.id.slice(4); - this.run("INSERT INTO users VALUES(?,?,NULL,NULL,?)", user.id, user.username, nowSeconds()); - this.run("INSERT INTO external_identities VALUES(?,?,?)", issuer, subject, user.id); + return { row: this.managedBrowser(grant)!, replacement: undefined }; + }); + } + + /** 查询本人浏览器登记,不开户或更改授权。 */ + personalBrowser(grant: BrowserEnrollmentIdentity): BrowserEnrollment | undefined { + return this.one( + "SELECT * FROM personal_browsers WHERE issuer=? AND subject=? AND client_id=?", + grant.issuer, + grant.sub, + grant.client_id, + ); + } + + /** 本人浏览器属于正常登录账户,重新绑定只轮换设备凭据。 */ + provisionPersonalBrowser( + grant: BrowserEnrollmentIdentity, + binding: PersonalBrowserProvision, + clientName?: string, + ) { + return this.transaction(() => { + const existing = this.personalBrowser(grant); + if (binding.revision !== (existing?.revision ?? 0)) + throw new BridgeError("stale_binding", "The browser binding changed", 409); + if (existing) { + if (this.device(existing.device_id)?.revoked_at !== null) + throw new BridgeError("managed_browser_revoked", "Browser access was revoked", 403); + if (!binding.replace) { + if (existing.installation_id !== binding.installation_id) + throw new BridgeError("stale_binding", "Browser reinstall requires replacement", 409); + return { row: existing, replacement: undefined }; + } + return { row: existing, replacement: this.stageBrowserReplacement("personal", existing, binding) }; } - if (!clientId) return user; - const linked = this.one<{ agent_connection_id: string }>( - "SELECT agent_connection_id FROM platform_connections WHERE issuer=? AND subject=? AND client_id=?", - issuer, - subject, - clientId, + const user = this.ensureLoginUser( + grant.issuer, + grant.sub, + binding.name ?? "外部用户", + grant.client_id, + clientName, ); - if (!linked) { - const agentConnectionId = identifier("agt"); - this.run( - "INSERT INTO agent_connections VALUES(?,?,?,?,NULL,NULL,NULL,?,NULL)", - agentConnectionId, - user.id, - (clientName ?? clientId) + " 平台连接", - JSON.stringify({ mode: "all", capabilities: [...CAPABILITIES], overrides: [] }), - nowSeconds(), - ); + const device = this.insertDevice(user.id, "沙盒浏览器", ["browser"], "browser", secretKey("device")); + this.run( + "INSERT INTO personal_browsers(issuer,subject,client_id,installation_id,revision,device_id) VALUES(?,?,?,?,1,?)", + grant.issuer, + grant.sub, + grant.client_id, + binding.installation_id, + device.id, + ); + return { row: this.personalBrowser(grant)!, replacement: undefined }; + }); + } + + /** 保留同一设备,推进安装版本并作废该设备未兑换的票据。 */ + private advancePersonalBrowserBinding(deviceId: string): void { + this.run( + "UPDATE personal_browsers SET revision=revision+1,bootstrap_nonce=NULL,bootstrap_expires_at=NULL,key_issued=0 WHERE device_id=?", + deviceId, + ); + } + + private stageBrowserReplacement( + scope: BrowserEnrollmentScope, + active: BrowserEnrollment, + binding: ManagedBrowserBinding, + ): BrowserReplacement { + const current = this.browserReplacement(active.device_id); + if (current) { + if (current.installation_id !== binding.installation_id) + throw new BridgeError("replacement_pending", "Another browser installation is being prepared", 409); + return current; + } + this.run("DELETE FROM browser_replacements WHERE device_id=?", active.device_id); + this.run( + "INSERT INTO browser_replacements(device_id,scope,installation_id,revision,credential_version,expires_at) VALUES(?,?,?,?,?,?)", + active.device_id, + scope, + binding.installation_id, + active.revision + 1, + this.device(active.device_id)!.credential_version, + nowSeconds() + BROWSER_REPLACEMENT_SECONDS, + ); + return this.browserReplacement(active.device_id)!; + } + + browserReplacement(deviceId: string): BrowserReplacement | undefined { + const row = this.one( + "SELECT * FROM browser_replacements WHERE device_id=?", + deviceId, + ); + return this.validBrowserReplacement(row) ? row : undefined; + } + + browserEnrollmentRevision(deviceId: string): number | undefined { + return this.one<{ revision: number }>( + "SELECT revision FROM managed_browsers WHERE device_id=? UNION ALL SELECT revision FROM personal_browsers WHERE device_id=?", + deviceId, + deviceId, + )?.revision; + } + + browserLocalAccess(deviceId: string): { paused: boolean; capabilities: { browser: boolean } } | undefined { + const row = this.one<{ paused: number; enabled: number }>( + "SELECT paused,enabled FROM browser_local_access WHERE device_id=?", + deviceId, + ); + return row && { paused: !!row.paused, capabilities: { browser: !!row.enabled } }; + } + + recordBrowserLocalAccess(deviceId: string, paused: boolean, enabled: boolean): void { + if (paused || !enabled) + this.run( + "INSERT INTO browser_local_access VALUES(?,?,?) ON CONFLICT(device_id) DO UPDATE SET paused=excluded.paused,enabled=excluded.enabled", + deviceId, + Number(paused), + Number(enabled), + ); + else this.run("DELETE FROM browser_local_access WHERE device_id=?", deviceId); + } + + private validBrowserReplacement(row: BrowserReplacement | undefined): Device | undefined { + if (!row || row.expires_at <= nowSeconds()) return undefined; + const device = this.device(row.device_id); + if (!device || device.revoked_at !== null || device.credential_version !== row.credential_version) + return undefined; + if (row.scope === "managed") { + const active = this.one("SELECT * FROM managed_browsers WHERE device_id=?", device.id); + if (!active || this.agentConnection(active.agent_connection_id)?.revoked_at !== null) return undefined; + } + return device; + } + + private browserReplacementByKey(key: string): BrowserReplacement | undefined { + return key.startsWith("abr_device_") + ? this.one("SELECT * FROM browser_replacements WHERE key_digest=?", digest(key)) + : undefined; + } + + /** Staged keys may verify device identity and attempt a cutover, but cannot operate as active keys. */ + browserReplacementDevice(key: string): Device | undefined { + return this.validBrowserReplacement(this.browserReplacementByKey(key)); + } + + abandonBrowserReplacement(key: string): "abandoned" | "active" | "invalid" { + return this.transaction(() => { + const row = this.browserReplacementByKey(key); + if (row) { + this.run("DELETE FROM browser_replacements WHERE device_id=?", row.device_id); + return "abandoned"; + } + return this.authenticateDevice(key)?.kind === "browser" ? "active" : "invalid"; + }); + } + + activateBrowserReplacement(key: string, expectedEpoch: number): Device | undefined { + return this.transaction(() => { + const row = this.browserReplacementByKey(key); + const device = this.validBrowserReplacement(row); + if (!row || !device || device.epoch + 1 !== expectedEpoch) return undefined; + if (row.scope === "managed") { + const active = this.one( + "SELECT * FROM managed_browsers WHERE device_id=?", + device.id, + )!; + const connection = this.agentConnection(active.agent_connection_id)!; + this.revokeAgentConnection(connection.id); + const next = this.insertPlatformConnection(device.owner_id, connection.name, connection.policy); + this.run("UPDATE managed_browsers SET agent_connection_id=? WHERE device_id=?", next, device.id); + } + this.run( + `UPDATE ${row.scope}_browsers SET installation_id=?,revision=?,bootstrap_nonce=NULL,bootstrap_expires_at=NULL,key_issued=1 WHERE device_id=?`, + row.installation_id, + row.revision, + device.id, + ); + this.run( + "UPDATE devices SET token_digest=?,credential_version=credential_version+1,epoch=?,last_seen=? WHERE id=?", + digest(key), + expectedEpoch, + nowSeconds(), + device.id, + ); + this.run("DELETE FROM browser_replacements WHERE device_id=?", device.id); + return this.device(device.id)!; + }); + } + + private bootstrapToken(deviceId: string, nonce: string): string { + return createHmac("sha256", this.bootstrapKey) + .update(deviceId + ":" + nonce) + .digest("base64url"); + } + + /** 两种登记均使用设备绑定的一次性票据。 */ + issueBrowserBootstrap(row: BrowserEnrollment, scope: BrowserEnrollmentScope): string | undefined { + if (row.key_issued) return undefined; + if (row.bootstrap_nonce && row.bootstrap_expires_at! > nowSeconds()) + return this.bootstrapToken(row.device_id, row.bootstrap_nonce); + const nonce = randomBytes(24).toString("base64url"); + this.run( + `UPDATE ${scope}_browsers SET bootstrap_nonce=?,bootstrap_expires_at=? WHERE device_id=?`, + nonce, + nowSeconds() + 60, + row.device_id, + ); + return this.bootstrapToken(row.device_id, nonce); + } + + issueReplacementBootstrap(row: BrowserReplacement): string { + if (row.bootstrap_nonce && row.bootstrap_expires_at! > nowSeconds()) + return this.bootstrapToken(row.device_id, row.bootstrap_nonce); + const nonce = randomBytes(24).toString("base64url"); + this.run( + "UPDATE browser_replacements SET bootstrap_nonce=?,bootstrap_expires_at=?,key_digest=NULL WHERE device_id=?", + nonce, + Math.min(row.expires_at, nowSeconds() + 60), + row.device_id, + ); + return this.bootstrapToken(row.device_id, nonce); + } + + private matchesBrowserBootstrap( + row: Pick, + token: string, + ): boolean { + return ( + !!row.bootstrap_nonce && + row.bootstrap_expires_at! > nowSeconds() && + timingSafeEqual( + Buffer.from(digest(token)), + Buffer.from(digest(this.bootstrapToken(row.device_id, row.bootstrap_nonce))), + ) + ); + } + + redeemManagedBrowser( + deviceId: string, + token: string, + localAccessBlocked: boolean, + ): { device: Device; key: string; pending: boolean; revision: number } { + return this.transaction(() => { + const replacement = this.browserReplacement(deviceId); + if (replacement && !localAccessBlocked && this.matchesBrowserBootstrap(replacement, token)) { + const device = this.device(deviceId)!; + const key = secretKey("device"); this.run( - "INSERT INTO platform_connections VALUES(?,?,?,?)", - issuer, - subject, - clientId, - agentConnectionId, + "UPDATE browser_replacements SET bootstrap_nonce=NULL,bootstrap_expires_at=NULL,key_digest=? WHERE device_id=?", + digest(key), + deviceId, ); + return { device, key, pending: true, revision: replacement.revision }; } - return user; + const managed = this.one("SELECT * FROM managed_browsers WHERE device_id=?", deviceId); + const row = + managed ?? this.one("SELECT * FROM personal_browsers WHERE device_id=?", deviceId); + const device = row && this.device(deviceId); + const connection = managed && this.agentConnection(managed.agent_connection_id); + if ( + !row || + row.key_issued || + !device || + device.revoked_at !== null || + (managed && connection?.revoked_at !== null) || + localAccessBlocked || + !this.matchesBrowserBootstrap(row, token) + ) + throw new BridgeError("invalid_grant", "Browser bootstrap credential is invalid or expired", 400); + const scope = managed ? "managed" : "personal"; + this.run( + `UPDATE ${scope}_browsers SET bootstrap_nonce=NULL,bootstrap_expires_at=NULL,key_issued=1 WHERE device_id=?`, + deviceId, + ); + return { device, key: this.rotateDevice(deviceId), pending: false, revision: row.revision }; + }); + } + + managedBrowserConnection( + grant: BrowserEnrollmentIdentity, + binding: ManagedBrowserBinding, + ): AgentConnection | undefined { + const row = this.managedBrowser(grant); + if (!row || row.revision !== binding.revision || row.installation_id !== binding.installation_id) + return undefined; + const connection = this.agentConnection(row.agent_connection_id); + if (!connection || connection.revoked_at !== null || this.device(row.device_id)?.revoked_at !== null) + return undefined; + return connection; + } + + stopManagedBrowser(grant: BrowserEnrollmentIdentity, binding: ManagedBrowserBinding): ManagedBrowser { + return this.transaction(() => { + const row = this.managedBrowser(grant); + if (!row || row.revision !== binding.revision || row.installation_id !== binding.installation_id) + throw new BridgeError("stale_binding", "The browser binding changed", 409); + if (this.device(row.device_id)!.revoked_at === null) this.revokeDevice(row.device_id); + this.revokeAgentConnection(row.agent_connection_id); + this.run( + "UPDATE managed_browsers SET bootstrap_nonce=NULL,bootstrap_expires_at=NULL WHERE device_id=?", + row.device_id, + ); + return row; }); } + + isManagedBrowserConnection(id: string): boolean { + return !!this.one("SELECT 1 FROM managed_browsers WHERE agent_connection_id=?", id); + } /** 仅解析已登录建立且尚有效的外部平台授权。 */ delegatedAgentConnection(issuer: string, subject: string, clientId: string): AgentConnection | undefined { const row = this.one<{ agent_connection_id: string }>( @@ -280,27 +736,34 @@ export class Store { capabilities: Capability[], kind: DeviceKind = "computer", ): { device: Device; key: string } { + const key = secretKey("device"); + return { device: this.transaction(() => this.insertDevice(owner, name, capabilities, kind, key)), key }; + } + private insertDevice( + owner: string, + name: string, + capabilities: Capability[], + kind: DeviceKind, + key: string, + ): Device { if (!capabilities.length || capabilities.some((cap) => !deviceCapabilities(kind).includes(cap))) throw new BridgeError("invalid_capabilities", "Capabilities do not match device kind", 422); let id: string; do { id = randomBytes(9).toString("base64url"); } while (this.device(id)); - const key = secretKey("device"); - this.transaction(() => { - this.run( - "INSERT INTO devices(id,owner_id,name,capabilities,token_digest,credential_version,epoch,created_at,kind) VALUES(?,?,?,?,?,1,0,?,?)", - id, - owner, - name, - JSON.stringify(capabilities), - digest(key), - nowSeconds(), - kind, - ); - this.audit(owner, id, null, null, "device_create", "changed"); - }); - return { device: this.device(id)!, key }; + this.run( + "INSERT INTO devices(id,owner_id,name,capabilities,token_digest,credential_version,epoch,created_at,kind) VALUES(?,?,?,?,?,1,0,?,?)", + id, + owner, + name, + JSON.stringify(capabilities), + digest(key), + nowSeconds(), + kind, + ); + this.audit(owner, id, null, null, "device_create", "changed"); + return this.device(id)!; } renameDevice(id: string, name: string): void { this.transaction(() => { @@ -308,6 +771,14 @@ export class Store { this.audit(this.device(id)!.owner_id, id, null, null, "device_rename", "changed"); }); } + /** 管理台签发新凭据时,当前个人浏览器安装也需要重新领票。 */ + rotateDeviceCredentials(id: string): string { + return this.transaction(() => { + const key = this.rotateDevice(id); + this.advancePersonalBrowserBinding(id); + return key; + }); + } rotateDevice(id: string): string { const key = secretKey("device"); this.run( @@ -315,6 +786,7 @@ export class Store { digest(key), id, ); + this.run("DELETE FROM browser_replacements WHERE device_id=?", id); return key; } revokeDevice(id: string): void { @@ -323,6 +795,8 @@ export class Store { nowSeconds(), id, ); + this.run("DELETE FROM browser_replacements WHERE device_id=?", id); + this.run("DELETE FROM browser_local_access WHERE device_id=?", id); } authenticateDevice(key: string): Device | undefined { return key.startsWith("abr_device_") @@ -386,6 +860,12 @@ export class Store { const agentConnection = this.agentConnection(id); if (!agentConnection || agentConnection.revoked_at !== null) throw new BridgeError("not_found", "Connection not found", 404); + if (this.isManagedBrowserConnection(id)) + throw new BridgeError( + "managed_connection", + "Managed browser connections have a fixed device policy", + 409, + ); const validated = validatePolicy(agentConnection.owner_id, policy, (deviceId) => this.device(deviceId)); this.transaction(() => { this.run( diff --git a/apps/server/src/transport.ts b/apps/server/src/transport.ts index 04e9507..bd705ff 100644 --- a/apps/server/src/transport.ts +++ b/apps/server/src/transport.ts @@ -1,13 +1,49 @@ +import { randomBytes } from "node:crypto"; import { WebSocket } from "ws"; import type { DeviceTransport, JsonObject } from "./types.js"; /** Every send and close has an absolute budget, including a peer that never drains. */ export class WebSocketTransport implements DeviceTransport { + private pendingProbe: Promise | undefined; + constructor( private readonly socket: WebSocket, private readonly sendTimeoutMs = 5000, private readonly closeTimeoutMs = 1000, ) {} + probe(): Promise { + if (this.pendingProbe) return this.pendingProbe; + this.pendingProbe = this.probeOnce().finally(() => { + this.pendingProbe = undefined; + }); + return this.pendingProbe; + } + private probeOnce(): Promise { + if (this.socket.readyState !== WebSocket.OPEN) return Promise.resolve(false); + const nonce = randomBytes(16); + return new Promise((resolve) => { + const finish = (alive: boolean) => { + clearTimeout(timer); + this.socket.off("pong", pong); + this.socket.off("close", closed); + resolve(alive); + }; + const pong = (data: Buffer) => { + if (nonce.equals(data)) finish(true); + }; + const closed = () => finish(false); + const timer = setTimeout(closed, 2000); + this.socket.on("pong", pong); + this.socket.once("close", closed); + try { + this.socket.ping(nonce, false, (error) => { + if (error) finish(false); + }); + } catch { + finish(false); + } + }); + } send(frame: JsonObject): Promise { return new Promise((resolve, reject) => { if (this.socket.readyState !== WebSocket.OPEN || this.socket.bufferedAmount > 16 * 1024 * 1024) { diff --git a/apps/server/src/types.ts b/apps/server/src/types.ts index 053764f..9de4f4b 100644 --- a/apps/server/src/types.ts +++ b/apps/server/src/types.ts @@ -75,6 +75,8 @@ export interface OperationResponse extends JsonObject { export interface DeviceTransport { send(frame: JsonObject): Promise; close(code: number, reason: string): Promise; + /** A browser transport must support a bounded round trip before admitting work. */ + probe?(): Promise; } export interface DeviceConnection { deviceId: string; diff --git a/apps/server/tests/browser-code.test.ts b/apps/server/tests/browser-code.test.ts index 2149b3e..b8063b5 100644 --- a/apps/server/tests/browser-code.test.ts +++ b/apps/server/tests/browser-code.test.ts @@ -74,7 +74,7 @@ test("browser code shares session state, forwards steps, deduplicates and yields }), ); await welcome; - const session = server.control.openSession(agentConnection.agentConnection, device.device.id, [ + const session = await server.control.openSession(agentConnection.agentConnection, device.device.id, [ "browser", ]); async function run(code: string, id: string, timeout = 20000): Promise { @@ -239,7 +239,9 @@ test("browser code shares session state, forwards steps, deduplicates and yields ); assert.ok(["outcome_unknown", "cancelled"].includes(stopped.status), JSON.stringify(stopped)); await server.control.closeSession(agentConnection.agentConnection, session.id); - const next = server.control.openSession(agentConnection.agentConnection, device.device.id, ["browser"]); + const next = await server.control.openSession(agentConnection.agentConnection, device.device.id, [ + "browser", + ]); const clean = await server.control.execute( agentConnection.agentConnection, next.id, @@ -258,7 +260,13 @@ test("browser code shares session state, forwards steps, deduplicates and yields } }); -for (const ending of ["disconnect", "disconnect-zero", "rotate", "confirmed-receipt"] as const) +for (const ending of [ + "disconnect", + "disconnect-zero", + "before-dispatch", + "rotate", + "confirmed-receipt", +] as const) test(`browser execution preserves step diagnostics on ${ending}`, async () => { const directory = await mkdtemp(join(tmpdir(), "abridge-browser-progress-")); const store = new Store(join(directory, "server.db")); @@ -282,6 +290,13 @@ for (const ending of ["disconnect", "disconnect-zero", "rotate", "confirmed-rece "browser", { capabilities: { browser: true } }, { + async probe() { + if (ending === "before-dispatch" && frames.length === 1) { + reached(); + return false; + } + return true; + }, async send(frame) { if (frame.type !== "dispatch") return; frames.push(frame); @@ -307,7 +322,7 @@ for (const ending of ["disconnect", "disconnect-zero", "rotate", "confirmed-rece async close() {}, }, ); - const session = control.openSession(agentConnection, device.device.id, ["browser"]); + const session = await control.openSession(agentConnection, device.device.id, ["browser"]); const started = await control.execute( agentConnection, session.id, @@ -320,14 +335,20 @@ for (const ending of ["disconnect", "disconnect-zero", "rotate", "confirmed-rece false, ); await dispatched; - if (ending === "disconnect" || ending === "disconnect-zero") control.dropConnection(ticket); + if (ending === "disconnect" || ending === "disconnect-zero" || ending === "before-dispatch") + control.dropConnection(ticket); if (ending === "rotate") ({ agentConnection } = await control.rotateAgentConnection(agentConnection)); const result = control.operationStatus(agentConnection, started.operation_id); assert.equal(result.status, "outcome_unknown"); const progress = result.result as JsonObject; assert.equal(progress.steps_completed, ending === "disconnect-zero" ? 0 : 1, JSON.stringify(result)); if (ending === "confirmed-receipt") assert.equal(progress.failed_step, undefined); - else { + else if (ending === "before-dispatch") { + const failed = progress.failed_step as JsonObject; + assert.equal(store.operation(String(failed.operation_id)), undefined); + assert.equal(failed.method, "locate_act"); + assert.equal(failed.status, "refused"); + } else { const failed = progress.failed_step as JsonObject; assert.equal(failed.operation_id, frames[ending === "disconnect-zero" ? 0 : 1]!.operation_id); assert.equal(failed.method, ending === "disconnect-zero" ? "read" : "locate_act"); @@ -336,7 +357,7 @@ for (const ending of ["disconnect", "disconnect-zero", "rotate", "confirmed-rece await new Promise((resolve) => setTimeout(resolve, 30)); assert.equal( frames.length, - ending === "confirmed-receipt" || ending === "disconnect-zero" ? 1 : 2, + ending === "disconnect" || ending === "rotate" ? 2 : 1, "No queued step may run", ); assert.deepEqual( @@ -390,13 +411,16 @@ test("native input receipt deadline includes the hold and verification budgets", "browser", { capabilities: { browser: true } }, { + async probe() { + return true; + }, async send(frame) { frames.push(frame); }, async close() {}, }, ); - const session = control.openSession(agentConnection, device.device.id, ["browser"]); + const session = await control.openSession(agentConnection, device.device.id, ["browser"]); t.mock.timers.enable({ apis: ["setTimeout"] }); const nextTurn = () => new Promise((resolve) => setImmediate(resolve)); for (const tool of ["browser_act", "browser_locate_act"] as const) { diff --git a/apps/server/tests/connection-independent.test.ts b/apps/server/tests/connection-independent.test.ts index 2c3064c..0380d1d 100644 --- a/apps/server/tests/connection-independent.test.ts +++ b/apps/server/tests/connection-independent.test.ts @@ -104,8 +104,8 @@ test("rotating one connection preserves another connection's session, operation async close() {}, }, ); - const firstSession = control.openSession(first.agentConnection, device.device.id, ["files"]); - const secondSession = control.openSession(second.agentConnection, device.device.id, ["files"]); + const firstSession = await control.openSession(first.agentConnection, device.device.id, ["files"]); + const secondSession = await control.openSession(second.agentConnection, device.device.id, ["files"]); const firstOperation = await control.execute( first.agentConnection, firstSession.id, @@ -180,7 +180,7 @@ for (const reason of ["expiry", "revocation"] as const) { { capabilities: { files: true } }, { async send() {}, async close() {} }, ); - const session = control.openSession(agentConnection, device.device.id, ["files"]); + const session = await control.openSession(agentConnection, device.device.id, ["files"]); const cached = await control.execute( agentConnection, session.id, diff --git a/apps/server/tests/connections.test.ts b/apps/server/tests/connections.test.ts index 6c555b3..ecabf93 100644 --- a/apps/server/tests/connections.test.ts +++ b/apps/server/tests/connections.test.ts @@ -93,7 +93,7 @@ test("device details use the current policy when another request changes an auth assert.equal(changed.status, 200); const listed = f.control.devices(authenticated)[0]!; const detail = f.control.deviceView(f.control.authorizedDevice(authenticated, device.id), authenticated); - const session = f.control.openSession(authenticated, device.id, ["shell"]); + const session = await f.control.openSession(authenticated, device.id, ["shell"]); const sessionDevice = f.control.deviceView( f.control.authorizedDevice(authenticated, session.device_id), authenticated, @@ -102,7 +102,9 @@ test("device details use the current policy when another request changes an auth assert.deepEqual(view.capabilities, ["shell"]); assert.deepEqual(view.available, { shell: true }); } - assert.throws(() => f.control.openSession(authenticated, device.id, ["files"]), { code: "forbidden" }); + await assert.rejects(() => f.control.openSession(authenticated, device.id, ["files"]), { + code: "forbidden", + }); } finally { await f.dispose(); } @@ -297,7 +299,7 @@ test("scope reductions cancel affected in-flight sessions and deny cached and wa { capabilities: { files: true, shell: true }, paused: false }, transport, ); - const session = control.openSession(agentConnection, device.device.id, ["files"]); + const session = await control.openSession(agentConnection, device.device.id, ["files"]); const completed = await control.execute( agentConnection, session.id, @@ -346,7 +348,7 @@ test("scope reductions cancel affected in-flight sessions and deny cached and wa }); assert.ok(store.authenticateAgent(key)); const current = store.agentConnection(agentConnection.id)!; - const shellSession = control.openSession(current, device.device.id, ["shell"]); + const shellSession = await control.openSession(current, device.device.id, ["shell"]); const command = await control.execute( current, shellSession.id, @@ -389,7 +391,7 @@ test("indefinite connections retain bounded sessions; shorter expiry applies imm ); const transport: DeviceTransport = { async send() {}, async close() {} }; await control.attachConnection(device.key, "computer", { capabilities: { files: true } }, transport); - const session = control.openSession(agentConnection, device.device.id, ["files"]); + const session = await control.openSession(agentConnection, device.device.id, ["files"]); assert.equal(session.lease_until, now + 300); const updated = await control.updateAgentConnection( agentConnection, diff --git a/apps/server/tests/device-metadata.test.ts b/apps/server/tests/device-metadata.test.ts index 214f3dc..8aea382 100644 --- a/apps/server/tests/device-metadata.test.ts +++ b/apps/server/tests/device-metadata.test.ts @@ -280,8 +280,8 @@ test("Android interaction state gates UI capabilities independently of connectiv const f = await fixture("computer", ["screen", "input", "files"]); try { const ticket = await f.attach({ platform: "android", interaction_state: "ready" }); - const ui = f.control.openSession(f.agentConnection, f.device.id, ["screen", "input"]); - const files = f.control.openSession(f.agentConnection, f.device.id, ["files"]); + const ui = await f.control.openSession(f.agentConnection, f.device.id, ["screen", "input"]); + const files = await f.control.openSession(f.agentConnection, f.device.id, ["files"]); const report = (interaction_state: "locked" | "screen_off" | "ready") => f.control.receive(ticket, { type: "heartbeat", @@ -298,13 +298,14 @@ test("Android interaction state gates UI capabilities independently of connectiv assert.equal(view.status, "online"); assert.equal(view.interaction_state, state); assert.deepEqual(view.available, { screen: false, input: false, files: true }); - assert.throws(() => f.control.openSession(f.agentConnection, f.device.id, ["screen"]), { code }); + await assert.rejects(f.control.openSession(f.agentConnection, f.device.id, ["screen"]), { code }); assert.equal(f.store.session(ui.id)?.status, "stopped"); assert.equal(f.store.session(files.id)?.status, "active"); } await report("ready"); assert.equal(f.view().interaction_state, "ready"); - assert.notEqual(f.control.openSession(f.agentConnection, f.device.id, ["screen", "input"]).id, ui.id); + const resumed = await f.control.openSession(f.agentConnection, f.device.id, ["screen", "input"]); + assert.notEqual(resumed.id, ui.id); f.control.dropConnection(ticket); assert.equal(f.view().status, "offline"); assert.equal(f.view().interaction_state, undefined); diff --git a/apps/server/tests/identity.test.ts b/apps/server/tests/identity.test.ts index dabed37..b23471a 100644 --- a/apps/server/tests/identity.test.ts +++ b/apps/server/tests/identity.test.ts @@ -5,9 +5,17 @@ import { generateKeyPair, exportJWK, SignJWT } from "jose"; import { mkdtemp, rm } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; +import { DatabaseSync } from "node:sqlite"; import { createHash } from "node:crypto"; +import { execFile } from "node:child_process"; +import { on, once } from "node:events"; +import { setTimeout as delay } from "node:timers/promises"; +import { promisify } from "node:util"; +import { WebSocket } from "ws"; import { createServer } from "../src/server.js"; import { Identity, validateIdentityConfig } from "../src/identity.js"; +import { Store } from "../src/store.js"; +import { BridgeError } from "../src/types.js"; /** 使用真实 HTTP OIDC 替身,保留真实签名与本地数据库。 */ async function fixture( @@ -16,6 +24,7 @@ async function fixture( foreignToken?: boolean; redirectToken?: boolean; delegationEnabled?: boolean; + managedBrowserEnabled?: boolean; allowInsecureHttp?: boolean; publicOrigin?: string; httpIssuer?: boolean; @@ -103,17 +112,19 @@ async function fixture( clientName: "Yuxi", clientSecret: "fixture-secret", delegationEnabled: options.delegationEnabled ?? true, + managedBrowserEnabled: options.managedBrowserEnabled, allowInsecureHttp: options.allowInsecureHttp, ...(options.backchannel ? { backchannelOrigin } : {}), }; - const server = await createServer({ + const serverConfig = { dbPath: join(dir, "server.db"), publicOrigin: origin, identity: config, port: 0, - }); - const serverUrl = await server.start(); - const identity = new Identity(config, origin, server.store); + }; + let server = await createServer(serverConfig); + let serverUrl = await server.start(); + let identity = new Identity(config, origin, server.store); async function login(subject = "user-a", returnTo = "/#authorize=fixture") { sub = subject; const start = await server.app.inject({ @@ -147,12 +158,41 @@ async function fixture( .setProtectedHeader({ alg: "RS256", kid: "fixture" }) .sign(pair.privateKey); } + async function personalBrowserRequest(action: "status" | "provision", claims = {}, subject = "user-a") { + const path = "/api/personal-browsers/" + action; + const signed = await token(subject, { + aud: origin + path, + purpose: "abridge-personal-browser-" + action, + installation_id: "cube-install", + revision: 0, + ...claims, + }); + return fetch(serverUrl + path, { + method: action === "status" ? "GET" : "POST", + headers: { authorization: "Bearer " + signed }, + }); + } + async function redeemBrowser(device_id: string, bootstrap_token: string) { + return fetch(serverUrl + "/api/managed-browsers/redeem", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ device_id, bootstrap_token }), + }); + } return { - server, - serverUrl, - identity, + get server() { + return server; + }, + get serverUrl() { + return serverUrl; + }, + get identity() { + return identity; + }, login, token, + personalBrowserRequest, + redeemBrowser, setWrongNonce: () => { wrongNonce = true; }, @@ -161,6 +201,12 @@ async function fixture( unavailable = true; }, calls: () => ({ tokenCalls, stolenCalls }), + async restart() { + await server.close(); + server = await createServer(serverConfig); + serverUrl = await server.start(); + identity = new Identity(config, origin, server.store); + }, async close() { await server.close(); await provider.close(); @@ -219,6 +265,751 @@ test("OIDC login isolates stable identities, persists mapping and defaults platf } }); +test("current main schema keeps device credentials when the managed table is added", async (t) => { + const dir = await mkdtemp(join(tmpdir(), "abridge-managed-schema-")); + t.after(() => rm(dir, { recursive: true, force: true })); + const path = join(dir, "server.db"); + const original = new Store(path); + const owner = await original.createUser("standard-owner", "fixture-password"); + const { device, key } = original.createDevice(owner.id, "Standard Linux", ["shell"]); + original.close(); + + const db = new DatabaseSync(path); + assert.equal(db.prepare("PRAGMA user_version").get()!.user_version, 6); + db.exec("DROP TABLE managed_browsers"); + db.close(); + const compatible = new Store(path); + assert.equal(compatible.authenticateDevice(key)?.id, device.id); + compatible.close(); + + const readback = new DatabaseSync(path); + assert.equal(readback.prepare("PRAGMA user_version").get()!.user_version, 6); + assert.equal(readback.prepare("SELECT COUNT(*) AS count FROM managed_browsers").get()!.count, 0); + readback.exec( + "DROP TABLE managed_browsers; CREATE TABLE managed_browsers(sandbox_id TEXT, generation INT, stopped_at REAL);", + ); + readback.prepare("INSERT INTO managed_browsers VALUES ('old-sandbox',1,-1)").run(); + readback.close(); + + assert.throws(() => new Store(path), { code: "managed_browser_schema_mismatch" }); + const legacy = new DatabaseSync(path, { readOnly: true }); + try { + assert.equal(legacy.prepare("SELECT sandbox_id FROM managed_browsers").get()!.sandbox_id, "old-sandbox"); + assert.equal(legacy.prepare("PRAGMA user_version").get()!.user_version, 6); + } finally { + legacy.close(); + } +}); + +test("managed browser enrollment fences tickets, device keys and MCP access by binding revision", async (t) => { + const f = await fixture({ managedBrowserEnabled: true }); + const origin = "http://127.0.0.1:43219"; + const root = "/api/managed-browsers/"; + const uid = "workload"; + const binding = (revision: number, installation_id = "install-a") => ({ revision, installation_id }); + async function request(action: "status" | "provision" | "stop", claims = {}, subject = uid) { + const token = await f.token(subject, { + aud: origin + root + action, + purpose: "abridge-managed-browser-" + action, + ...claims, + }); + return f.server.app.inject({ + method: action === "status" ? "GET" : "POST", + url: root + action, + headers: { authorization: "Bearer " + token }, + }); + } + async function redeem(device_id: string, bootstrap_token: string) { + return f.server.app.inject({ + method: "POST", + url: root + "redeem", + payload: { device_id, bootstrap_token }, + }); + } + const sockets: WebSocket[] = []; + async function connect(device_key: string, autoPong = true) { + const socket = new WebSocket(f.serverUrl.replace("http:", "ws:") + "/ws/browser", { + origin: "chrome-extension://" + "a".repeat(32), + autoPong, + }); + sockets.push(socket); + await once(socket, "open", { signal: AbortSignal.timeout(3000) }); + const welcome = once(socket, "message", { signal: AbortSignal.timeout(3000) }); + const ping = autoPong ? undefined : once(socket, "ping", { signal: AbortSignal.timeout(3000) }); + socket.send( + JSON.stringify({ + type: "hello", + protocol: "abridge/1", + platform: "Browser extension", + version: "0.4.23", + paused: false, + instance_id: "managed-test", + device_key, + capabilities: { browser: true }, + }), + ); + const [frame] = await welcome; + const connected = JSON.parse(frame.toString()); + assert.equal(connected.type, "welcome"); + return { socket, epoch: connected.connection_epoch, ping }; + } + function deviceAPI(key: string, method: "GET" | "PATCH" = "GET") { + return f.server.app.inject({ + method, + url: "/api/device", + headers: { authorization: "Bearer " + key }, + ...(method === "PATCH" && { payload: { name: "Candidate" } }), + }); + } + function abandon(key: string) { + return f.server.app.inject({ + method: "POST", + url: root + "abandon", + headers: { authorization: "Bearer " + key, origin: "chrome-extension://" + "a".repeat(32) }, + }); + } + async function waitForActivation(key: string) { + for (let attempt = 0; attempt < 100; attempt++) { + if (f.server.store.authenticateDevice(key)) return; + await delay(20); + } + assert.fail("The browser never became active"); + } + try { + assert.deepEqual((await request("status")).json(), { + version: 2, + enabled: true, + browser_origin: origin, + binding: null, + }); + assert.deepEqual(f.server.store.users(), []); + assert.deepEqual(f.server.store.activeDevices(), []); + assert.equal( + (await request("provision", { ...binding(0), purpose: "abridge-managed-browser-status" })).statusCode, + 401, + ); + assert.equal( + (await request("provision", { ...binding(0), aud: origin + root + "status" })).statusCode, + 401, + ); + + const opened = await request("provision", binding(0)); + assert.equal(opened.statusCode, 200, opened.body); + const first = opened.json(); + assert.equal(first.revision, 1); + assert.equal(first.key_issued, false); + assert.ok(first.bootstrap_token); + assert.equal((await request("provision", binding(1))).json().bootstrap_token, first.bootstrap_token); + assert.equal((await request("status", {}, "another-workload")).json().binding, null); + t.mock.timers.enable({ apis: ["Date"], now: Date.now() + 61_000 }); + let renewed: string; + try { + assert.equal((await redeem(first.device_id, first.bootstrap_token)).statusCode, 400); + const current = (await request("provision", binding(1))).json(); + assert.equal(current.revision, 1); + assert.equal(current.device_id, first.device_id); + assert.ok(current.bootstrap_token); + assert.notEqual(current.bootstrap_token, first.bootstrap_token); + renewed = current.bootstrap_token; + } finally { + t.mock.timers.reset(); + } + assert.equal((await redeem(first.device_id, first.bootstrap_token)).statusCode, 400); + assert.equal((await redeem(first.device_id, renewed)).statusCode, 200); + assert.equal((await redeem(first.device_id, renewed)).statusCode, 400); + // Lost response: same binding cannot silently re-issue a key. + const issued = (await request("provision", binding(1))).json(); + assert.equal(issued.key_issued, true); + assert.equal(issued.status, "offline"); + assert.equal(issued.bootstrap_token, undefined); + + const recovered = await request("provision", { ...binding(1), replace: true }); + assert.equal(recovered.statusCode, 200, recovered.body); + const second = recovered.json(); + assert.equal(second.revision, 2); + assert.equal(second.device_id, first.device_id); + const redeemed = await redeem(first.device_id, second.bootstrap_token); + assert.equal(redeemed.statusCode, 200, redeemed.body); + const key = redeemed.json().key; + const { socket, epoch } = await connect(key); + await waitForActivation(key); + assert.equal((await request("status")).json().binding.status, "online"); + assert.equal((await request("provision", binding(2, "install-b"))).statusCode, 409); + for (const local of [ + { paused: true, capabilities: { browser: true } }, + { paused: false, capabilities: { browser: false } }, + ]) { + const updates = on(socket, "message", { signal: AbortSignal.timeout(3000) }); + socket.send(JSON.stringify({ type: "capabilities", connection_epoch: epoch, ...local })); + for await (const [frame] of updates) { + const type = JSON.parse(frame.toString()).type; + if (type === "heartbeat_ack") break; + assert.equal(type, "stop"); + } + const blocked = await request("provision", { ...binding(2, "install-b"), replace: true }); + assert.equal(blocked.statusCode, 409); + assert.equal(blocked.json().error.code, "device_paused"); + assert.equal((await request("status")).json().binding.revision, 2); + assert.equal(f.server.store.authenticateDevice(key)?.id, first.device_id); + } + const resumed = once(socket, "message"); + socket.send( + JSON.stringify({ + type: "capabilities", + connection_epoch: epoch, + paused: false, + capabilities: { browser: true }, + }), + ); + assert.equal(JSON.parse((await resumed)[0].toString()).type, "heartbeat_ack"); + + const token = await f.token(uid, binding(2)); + const connection = await f.identity.authenticate(token); + assert.ok(connection); + assert.equal(await f.identity.authenticate(await f.token(uid)), undefined); + assert.equal(await f.identity.authenticate(await f.token("other-workload", binding(2))), undefined); + f.server.store.createDevice(connection.owner_id, "Other browser", ["browser"], "browser"); + assert.deepEqual( + f.server.control.devices(connection).map((device) => device.id), + [first.device_id], + ); + assert.throws(() => + f.server.store.updateAgentConnection( + connection.id, + connection.name, + { + mode: "all", + capabilities: ["browser"], + overrides: [], + }, + null, + ), + ); + const session = await f.server.control.openSession(connection, first.device_id, ["browser"]); + + const replaced = await request("provision", { ...binding(2, "install-b"), replace: true }); + assert.equal(replaced.statusCode, 200, replaced.body); + const third = replaced.json(); + assert.equal(third.device_id, first.device_id); + assert.equal(third.revision, 3); + assert.equal(third.pending, true); + const during = (await request("status")).json(); + assert.equal(during.binding.revision, 2); + assert.equal(during.binding.status, "online"); + assert.equal(during.replacement.revision, 3); + assert.equal(f.server.store.session(session.id)?.status, "active"); + assert.equal((await deviceAPI(key)).statusCode, 200); + assert.equal((await f.identity.authenticate(token))?.id, connection.id); + const current = binding(3, "install-b"); + assert.equal(await f.identity.authenticate(await f.token(uid, current)), undefined); + assert.equal((await request("provision", { ...binding(2, "install-c"), replace: true })).statusCode, 409); + assert.equal((await request("stop", current)).statusCode, 409); + + const candidate = await redeem(first.device_id, third.bootstrap_token); + assert.equal(candidate.statusCode, 200, candidate.body); + assert.equal(candidate.json().pending, true); + const candidateKey = candidate.json().key; + assert.equal((await deviceAPI(candidateKey)).json().pending, true); + assert.equal((await deviceAPI(candidateKey, "PATCH")).statusCode, 401); + assert.equal((await redeem(first.device_id, third.bootstrap_token)).statusCode, 400); + const failed = await connect(candidateKey, false); + await failed.ping; + await once(failed.socket, "close", { signal: AbortSignal.timeout(4000) }); + assert.equal((await deviceAPI(key)).statusCode, 200); + assert.equal((await f.identity.authenticate(token))?.id, connection.id); + assert.equal(f.server.store.session(session.id)?.status, "active"); + assert.equal((await request("status")).json().binding.status, "online"); + assert.equal((await abandon(candidateKey)).json().status, "abandoned"); + assert.equal((await deviceAPI(candidateKey)).statusCode, 401); + assert.equal((await request("status")).json().replacement, undefined); + + const retried = await request("provision", { ...binding(2, "install-b"), replace: true }); + assert.equal(retried.statusCode, 200, retried.body); + const previousAttemptKey = (await redeem(first.device_id, retried.json().bootstrap_token)).json().key; + const previousAttempt = await connect(previousAttemptKey, false); + const [challenge] = (await previousAttempt.ping)!; + const superseded = await request("provision", { ...binding(2, "install-b"), replace: true }); + assert.equal(superseded.statusCode, 200, superseded.body); + assert.equal(superseded.json().key_issued, false); + assert.equal((await deviceAPI(previousAttemptKey)).statusCode, 401); + assert.equal((await abandon(previousAttemptKey)).json().status, "invalid"); + const previousAttemptClosed = once(previousAttempt.socket, "close", { + signal: AbortSignal.timeout(3000), + }); + previousAttempt.socket.pong(challenge); + assert.equal((await previousAttemptClosed)[0], 4401); + assert.equal((await f.identity.authenticate(token))?.id, connection.id); + assert.equal(f.server.store.session(session.id)?.status, "active"); + const newKey = (await redeem(first.device_id, superseded.json().bootstrap_token)).json().key; + const oldClose = once(socket, "close", { signal: AbortSignal.timeout(3000) }); + const { socket: currentSocket } = await connect(newKey); + assert.deepEqual((await oldClose).slice(0, 1), [4403]); + assert.equal((await deviceAPI(newKey)).json().pending, undefined); + assert.equal((await abandon(newKey)).json().status, "active"); + assert.equal((await request("status")).json().replacement, undefined); + assert.equal(f.server.store.authenticateDevice(key), undefined); + assert.notEqual(f.server.store.session(session.id)?.status, "active"); + assert.equal(await f.identity.authenticate(token), undefined); + assert.throws(() => f.server.control.devices(connection), /revoked/); + assert.equal((await request("provision", { ...binding(2), replace: true })).statusCode, 409); + assert.equal((await request("stop", binding(2))).statusCode, 409); + + const currentClose = once(currentSocket, "close"); + const beforeStop = await request("provision", { ...binding(3, "install-c"), replace: true }); + assert.equal(beforeStop.json().pending, true); + const stopped = await request("stop", current); + assert.equal(stopped.json().status, "revoked"); + assert.deepEqual((await currentClose).slice(0, 1), [4403]); + assert.equal(f.server.store.authenticateDevice(newKey), undefined); + assert.equal(await f.identity.authenticate(await f.token(uid, current)), undefined); + assert.equal((await request("status")).json().binding.status, "revoked"); + assert.equal((await redeem(first.device_id, beforeStop.json().bootstrap_token)).statusCode, 400); + assert.equal((await request("provision", { ...current, replace: true })).statusCode, 403); + assert.equal((await request("stop", current)).json().status, "revoked"); + } finally { + sockets.forEach((socket) => socket.terminate()); + await f.close(); + } +}); + +const liveBrowserLauncher = process.env.ABRIDGE_BROWSER_TEST_LAUNCHER; +const liveBrowserPython = process.env.ABRIDGE_BROWSER_TEST_PYTHON || "python3"; +test( + "packaged browser restores an online binding after a failed cutover against a real Server", + { skip: !liveBrowserLauncher, timeout: 100_000 }, + async (t) => { + const f = await fixture({ managedBrowserEnabled: true }); + const state = await mkdtemp(join(tmpdir(), "abridge-cutover-")); + const run = promisify(execFile); + type Handoff = { device_id: string; revision: number; bootstrap_token?: string }; + async function cli(action: "start" | "stop" | "status", handoff?: Handoff) { + const command = run(liveBrowserPython, ["-I", liveBrowserLauncher!, action], { + env: { ...process.env, ABRIDGE_BROWSER_HOME: state }, + timeout: 48_000, + }); + command.child.stdin?.end(handoff && JSON.stringify({ ...handoff, browser_origin: f.serverUrl })); + return JSON.parse((await command).stdout) as { connected?: boolean; revision?: number }; + } + async function provision(revision: number, replace = false): Promise { + const reply = await f.personalBrowserRequest("provision", { revision, replace }); + assert.equal(reply.status, 200); + return reply.json(); + } + async function expectOnline(revision: number) { + for (let attempt = 0; attempt < 12; attempt++) { + const local = await cli("status"); + if (local.connected) { + assert.equal(local.revision, revision); + const response = await f.personalBrowserRequest("status"); + const { binding } = await response.json(); + assert.equal(binding.revision, revision); + assert.equal(binding.status, "online"); + return; + } + await delay(250); + } + assert.fail("The browser never reached the requested online revision"); + } + let blocked = true; + let failedAttempts = 0; + const attach = f.server.control.attachConnection.bind(f.server.control); + t.mock.method(f.server.control, "attachConnection", async (...args: Parameters) => { + if (blocked && f.server.store.browserReplacementDevice(args[0])) { + failedAttempts++; + throw new BridgeError("device_offline", "Fixture rejects candidate connection", 503); + } + return attach(...args); + }); + try { + const original = await provision(0); + await cli("start", original); + await expectOnline(original.revision); + + const rejected = await provision(original.revision, true); + await assert.rejects(cli("start", rejected), { code: 1 }); + assert.ok(failedAttempts > 0); + await cli("start", { device_id: original.device_id, revision: original.revision }); + await expectOnline(original.revision); + + blocked = false; + const retry = await provision(original.revision, true); + await cli("start", retry); + await expectOnline(retry.revision); + await cli("stop"); + await cli("start", { device_id: retry.device_id, revision: retry.revision }); + await expectOnline(retry.revision); + } finally { + await cli("stop").catch(() => {}); + await f.close(); + await rm(state, { recursive: true, force: true }); + } + }, +); + +test("a locally paused enrollment survives Server restart and blocks prepared candidates", async () => { + const f = await fixture({ managedBrowserEnabled: true }); + const { personalBrowserRequest: request, redeemBrowser: redeem } = f; + const sockets: WebSocket[] = []; + async function begin(device_key: string) { + const socket = new WebSocket(f.serverUrl.replace("http:", "ws:") + "/ws/browser", { + origin: "chrome-extension://" + "a".repeat(32), + }); + sockets.push(socket); + await once(socket, "open", { signal: AbortSignal.timeout(3000) }); + socket.send( + JSON.stringify({ + type: "hello", + protocol: "abridge/1", + platform: "Browser extension", + version: "0.5.1", + paused: false, + instance_id: "pause-restart", + device_key, + capabilities: { browser: true }, + }), + ); + return socket; + } + try { + const first = await (await request("provision")).json(); + const priorKey = (await (await redeem(first.device_id, first.bootstrap_token)).json()).key; + const original = await begin(priorKey); + const [frame] = await once(original, "message", { signal: AbortSignal.timeout(3000) }); + const { connection_epoch } = JSON.parse(frame.toString()); + const staged = await (await request("provision", { revision: first.revision, replace: true })).json(); + const stagedKey = (await (await redeem(first.device_id, staged.bootstrap_token)).json()).key; + const updates = on(original, "message", { signal: AbortSignal.timeout(3000) }); + original.send(JSON.stringify({ type: "capabilities", connection_epoch, paused: true })); + for await (const [update] of updates) if (JSON.parse(update.toString()).type === "heartbeat_ack") break; + assert.equal((await (await request("status")).json()).binding.status, "paused"); + await f.restart(); + assert.equal((await (await request("status")).json()).binding.status, "paused"); + assert.equal((await request("provision", { revision: first.revision, replace: true })).status, 409); + const candidate = await begin(stagedKey); + await once(candidate, "close", { signal: AbortSignal.timeout(4000) }); + assert.equal(f.server.store.authenticateDevice(stagedKey), undefined); + assert.equal(f.server.store.authenticateDevice(priorKey)?.id, first.device_id); + assert.equal((await (await request("status")).json()).binding.status, "paused"); + await begin(priorKey); + for (let attempt = 0; attempt < 40; attempt++) { + if ((await (await request("status")).json()).binding.status === "online") return; + await delay(25); + } + assert.fail("The enrolled browser did not clear the persisted block on explicit local resume"); + } finally { + sockets.forEach((socket) => socket.terminate()); + await f.close(); + } +}); + +test("managed registration requires opt-in and isolates workload subjects from personal login", async () => { + const disabled = await fixture(); + const origin = "http://127.0.0.1:43219"; + async function request( + f: typeof disabled, + subject: string, + action: "status" | "provision", + scope = "managed", + ) { + const url = `/api/${scope}-browsers/${action}`; + const token = await f.token(subject, { + aud: origin + url, + purpose: `abridge-${scope}-browser-${action}`, + installation_id: "install", + revision: 0, + }); + return f.server.app.inject({ + method: action === "status" ? "GET" : "POST", + url, + headers: { authorization: "Bearer " + token }, + }); + } + try { + assert.equal((await request(disabled, "workload", "status")).json().enabled, false); + assert.equal((await request(disabled, "workload", "provision")).statusCode, 404); + assert.equal((await request(disabled, "personal", "status", "personal")).json().enabled, false); + assert.equal((await request(disabled, "personal", "provision", "personal")).statusCode, 404); + } finally { + await disabled.close(); + } + const active = await fixture({ managedBrowserEnabled: true }); + try { + assert.equal((await active.login("personal")).result.statusCode, 302); + assert.equal((await request(active, "personal", "provision")).statusCode, 403); + assert.equal((await request(active, "workload", "provision")).statusCode, 200); + assert.equal((await active.login("workload")).result.statusCode, 403); + assert.equal((await request(active, "workload", "provision", "personal")).statusCode, 403); + assert.ok(await active.identity.authenticate(await active.token("personal"))); + } finally { + await active.close(); + } +}); + +test("personal enrollment gives the normal OIDC account an ordinary browser", async () => { + const f = await fixture({ managedBrowserEnabled: true }); + const origin = "http://127.0.0.1:43219"; + const { personalBrowserRequest: request, redeemBrowser: redeem } = f; + let socket: WebSocket | undefined; + async function mcp(name: string, args = {}, subject = "user-a") { + return fetch(f.serverUrl + "/mcp", { + method: "POST", + headers: { + authorization: "Bearer " + (await f.token(subject)), + "content-type": "application/json", + accept: "application/json, text/event-stream", + }, + body: JSON.stringify({ + jsonrpc: "2.0", + id: 1, + method: "tools/call", + params: { name, arguments: args }, + }), + }); + } + async function toolResult(response: Response): Promise { + assert.equal(response.status, 200); + const body = (await response.json()) as { result: { content: { text: string }[] } }; + return JSON.parse(body.result.content[0]!.text) as T; + } + try { + assert.equal((await (await request("status")).json()).binding, null); + assert.deepEqual(f.server.store.users(), []); + assert.equal((await request("provision", { purpose: "abridge-managed-browser-provision" })).status, 401); + assert.equal((await request("provision", { aud: origin + "/mcp" })).status, 401); + assert.equal((await request("provision", { client_id: "other-client" })).status, 401); + assert.deepEqual(f.server.store.activeDevices(), []); + + const enrolled = await request("provision", { name: "Same Display Name" }); + assert.equal(enrolled.status, 200); + const { device_id, revision, bootstrap_token } = await enrolled.json(); + assert.equal(revision, 1); + assert.equal(enrolled.headers.get("cache-control"), "no-store"); + const redeemed = await redeem(device_id, bootstrap_token); + assert.equal(redeemed.status, 200); + const { key } = await redeemed.json(); + assert.equal((await redeem(device_id, bootstrap_token)).status, 400); + const connection = (await f.identity.authenticate(await f.token()))!; + assert.equal(connection.name, "Yuxi 平台连接"); + assert.equal(connection.policy.mode, "all"); + assert.ok(connection.policy.capabilities.includes("shell")); + assert.equal(f.server.store.authenticateDevice(key)?.owner_id, connection.owner_id); + assert.equal((await (await request("status", {}, "user-b")).json()).binding, null); + assert.equal( + await f.identity.authenticate(await f.token("user-a", { revision, installation_id: "cube-install" })), + undefined, + ); + + socket = new WebSocket(f.serverUrl.replace("http:", "ws:") + "/ws/browser", { + origin: "chrome-extension://" + "a".repeat(32), + }); + await once(socket, "open"); + const welcome = once(socket, "message"); + socket.send( + JSON.stringify({ + type: "hello", + protocol: "abridge/1", + version: "0.5.0", + platform: "Browser extension", + instance_id: "personal-test", + device_key: key, + capabilities: { browser: true }, + paused: true, + }), + ); + const connected = JSON.parse((await welcome)[0].toString()); + assert.equal(connected.type, "welcome"); + const readMcpDevices = async (subject = "user-a") => + ( + await toolResult<{ devices: { id: string; status: string; available: { browser: boolean } }[] }>( + await mcp("devices_list", {}, subject), + ) + ).devices; + const args = { device_id, capabilities: ["browser"] }; + assert.deepEqual( + (await readMcpDevices()).map((d) => [d.id, d.status, d.available.browser]), + [[device_id, "online", false]], + ); + assert.equal( + (await toolResult<{ error: { code: string } }>(await mcp("session_open", args))).error.code, + "device_paused", + ); + const blocked = await request("provision", { revision, replace: true }); + assert.equal(blocked.status, 409); + assert.equal((await blocked.json()).error.code, "device_paused"); + const resumed = once(socket, "message"); + socket.send( + JSON.stringify({ type: "capabilities", connection_epoch: connected.connection_epoch, paused: false }), + ); + assert.equal(JSON.parse((await resumed)[0].toString()).type, "heartbeat_ack"); + assert.equal( + (await toolResult<{ device: { id: string } }>(await mcp("session_open", args))).device.id, + device_id, + ); + + const loggedIn = await f.login(); + const cookie = String(loggedIn.result.headers["set-cookie"]).split(";")[0]!; + const consoleDevices = await fetch(f.serverUrl + "/api/devices", { headers: { cookie } }); + assert.deepEqual( + (await consoleDevices.json()).devices.map((d: { id: string }) => d.id), + [device_id], + ); + const loginB = await f.login("user-b"); + const other = (await f.identity.authenticate(await f.token("user-b")))!; + assert.equal(loginB.result.statusCode, 302); + assert.deepEqual(await readMcpDevices("user-b"), []); + f.server.store.updateAgentConnection(other.id, other.name, { mode: "selected", devices: [] }, null); + assert.equal((await request("provision", {}, "user-b")).status, 200); + assert.equal((await f.identity.authenticate(await f.token("user-b")))?.id, other.id); + assert.deepEqual(await readMcpDevices("user-b"), []); + + await f.server.control.revokeAgentConnection(connection); + const replaced = await request("provision", { revision, replace: true }); + assert.equal(replaced.status, 200); + const current = await replaced.json(); + assert.equal(current.device_id, device_id); + assert.equal(current.revision, revision + 1); + assert.equal(current.pending, true); + assert.equal(f.server.store.authenticateDevice(key)?.id, device_id); + assert.equal((await mcp("devices_list")).status, 401); + const revoke = await fetch(f.serverUrl + "/api/devices/" + device_id + "/revoke", { + method: "POST", + headers: { cookie }, + }); + assert.equal(revoke.status, 200); + assert.equal((await redeem(device_id, current.bootstrap_token)).status, 400); + assert.equal((await request("provision", { revision, replace: true })).status, 403); + assert.equal((await (await request("status")).json()).binding.status, "revoked"); + } finally { + socket?.terminate(); + await f.close(); + } +}); + +test("console credential rotation invalidates pending personal tickets and allows one explicit rebind", async (t) => { + const f = await fixture({ managedBrowserEnabled: true }); + const { personalBrowserRequest: request, redeemBrowser: redeem } = f; + let socket: WebSocket | undefined; + try { + const created = await request("provision"); + assert.equal(created.status, 200); + const first = await created.json(); + const initial = await redeem(first.device_id, first.bootstrap_token); + assert.equal(initial.status, 200); + const guestKey = (await initial.json()).key as string; + const { result: login } = await f.login(); + assert.equal(login.statusCode, 302); + const cookie = String(login.headers["set-cookie"]).split(";")[0]!; + const read = async () => (await (await request("status")).json()).binding; + const identify = async (key: string) => + fetch(f.serverUrl + "/api/device", { headers: { authorization: "Bearer " + key } }); + async function rotate(): Promise { + const response = await fetch(f.serverUrl + "/api/devices/" + first.device_id + "/credentials", { + method: "POST", + headers: { cookie }, + }); + assert.equal(response.status, 200); + const body = await response.json(); + assert.equal(body.id, first.device_id); + return body.key as string; + } + + assert.equal((await read()).key_issued, true); + const manual = await rotate(); + const next = await read(); + assert.deepEqual(next, { + installation_id: first.installation_id, + revision: first.revision + 1, + device_id: first.device_id, + status: "offline", + key_issued: false, + }); + assert.equal((await identify(guestKey)).status, 401); + const prepared = await request("provision", { revision: next.revision }); + assert.equal(prepared.status, 200); + const pending = await prepared.json(); + assert.equal(pending.revision, next.revision); + assert.equal((await identify(manual)).status, 200); + + const replacement = await rotate(); + const latest = await read(); + assert.equal(latest.revision, next.revision + 1); + assert.equal(latest.key_issued, false); + assert.equal((await redeem(first.device_id, pending.bootstrap_token)).status, 400); + assert.equal((await request("provision", { revision: next.revision })).status, 409); + const provisioned = await request("provision", { revision: latest.revision }); + assert.equal(provisioned.status, 200); + const current = await provisioned.json(); + assert.equal(current.revision, latest.revision); + const identity = await identify(replacement); + assert.equal(identity.status, 200); + const originalDevice = await identity.json(); + + socket = new WebSocket(f.serverUrl.replace("http:", "ws:") + "/ws/browser", { + origin: "chrome-extension://" + "a".repeat(32), + }); + await once(socket, "open", { signal: AbortSignal.timeout(3000) }); + const welcome = once(socket, "message", { signal: AbortSignal.timeout(3000) }); + socket.send( + JSON.stringify({ + type: "hello", + protocol: "abridge/1", + version: "0.5.0", + platform: "Browser extension", + instance_id: "rotation-test", + device_key: replacement, + capabilities: { browser: true }, + paused: true, + }), + ); + const online = JSON.parse((await welcome)[0].toString()); + assert.equal(online.device_id, first.device_id); + assert.equal((await redeem(first.device_id, current.bootstrap_token)).status, 400); + assert.equal((await identify(replacement)).status, 200); + assert.equal((await read()).key_issued, false); + const resumed = once(socket, "message", { signal: AbortSignal.timeout(3000) }); + socket.send( + JSON.stringify({ type: "capabilities", connection_epoch: online.connection_epoch, paused: false }), + ); + assert.equal(JSON.parse((await resumed)[0].toString()).type, "heartbeat_ack"); + + const closed = once(socket, "close", { signal: AbortSignal.timeout(3000) }); + const rebound = await redeem(first.device_id, current.bootstrap_token); + assert.equal(rebound.status, 200); + assert.equal((await closed)[0], 4403); + assert.equal((await identify(replacement)).status, 401); + const restored = await identify((await rebound.json()).key); + assert.deepEqual(await restored.json(), originalDevice); + assert.equal((await read()).revision, latest.revision); + assert.equal((await read()).key_issued, true); + + // Rotate once more while redemption is closing the previous connection. + await rotate(); + const ready = await read(); + const ticket = await (await request("provision", { revision: ready.revision })).json(); + const invalidate = f.server.control.invalidateDevice.bind(f.server.control); + let activeKey = ""; + t.mock.method( + f.server.control, + "invalidateDevice", + async (id: string) => { + await invalidate(id); + activeKey = await rotate(); + }, + { times: 1 }, + ); + const stale = await redeem(first.device_id, ticket.bootstrap_token); + assert.equal(stale.status, 409); + const conflict = await stale.json(); + assert.equal(conflict.error.code, "stale_binding"); + assert.equal(conflict.key, undefined); + assert.equal((await identify(activeKey)).status, 200); + assert.equal((await read()).revision, ready.revision + 1); + } finally { + socket?.terminate(); + await f.close(); + } +}); + test("OIDC rejects browser mismatch, nonce mismatch and external return paths", async () => { const f = await fixture(); try { @@ -311,7 +1102,7 @@ test("delegation enforces claims and current persisted Agent connection policy, { capabilities: { files: true } }, { async send() {}, async close() {} }, ); - const session = f.server.control.openSession(agentConnection, device.id, ["files"]); + const session = await f.server.control.openSession(agentConnection, device.id, ["files"]); await f.server.control.updateAgentConnection( agentConnection, agentConnection.name, @@ -522,7 +1313,7 @@ test("explicit platform reauthorization creates all-device Agent connection with { capabilities: { files: true } }, { async send() {}, async close() {} }, ); - const session = f.server.control.openSession(updated, device.id, ["files"]); + const session = await f.server.control.openSession(updated, device.id, ["files"]); const route = "/api/agent-connections/" + agentConnection.id + "/reconnect"; assert.equal( (await f.server.app.inject({ method: "POST", url: route, headers: { cookie }, payload: {} })) diff --git a/apps/server/tests/independent-authorization.test.ts b/apps/server/tests/independent-authorization.test.ts index 6575b75..ec8f79b 100644 --- a/apps/server/tests/independent-authorization.test.ts +++ b/apps/server/tests/independent-authorization.test.ts @@ -28,7 +28,7 @@ for (const change of ["revoke", "pause", "disable"] as const) { capabilities: { files: true } }, transport, ); - const session = control.openSession(agentConnection, device.id, ["files"]); + const session = await control.openSession(agentConnection, device.id, ["files"]); const started = await control.execute( agentConnection, session.id, @@ -151,7 +151,7 @@ test("sensitive result that finishes after a local pause cannot escape an existi { capabilities: { files: true } }, { async send() {}, async close() {} }, ); - const session = control.openSession(agentConnection, device.id, ["files"]); + const session = await control.openSession(agentConnection, device.id, ["files"]); const started = await control.execute( agentConnection, session.id, @@ -202,7 +202,7 @@ test("terminal results survive a normal disconnect but retain the last local pau { capabilities: { files: true } }, transport, ); - const session = control.openSession(agentConnection, device.id, ["files"]); + const session = await control.openSession(agentConnection, device.id, ["files"]); const started = await control.execute( agentConnection, session.id, diff --git a/apps/server/tests/server.test.ts b/apps/server/tests/server.test.ts index ac5c644..841c22e 100644 --- a/apps/server/tests/server.test.ts +++ b/apps/server/tests/server.test.ts @@ -4,6 +4,7 @@ import { mkdtemp, rm } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { once } from "node:events"; +import { createHash } from "node:crypto"; import { setTimeout as delay } from "node:timers/promises"; import { WebSocket } from "ws"; import { createServer } from "../src/server.js"; @@ -26,9 +27,10 @@ async function fixture() { }, }; } -async function rpc(url: string, key: string, name: string, args: JsonObject = {}) { +async function rpc(url: string, key: string, name: string, args: JsonObject = {}, signal?: AbortSignal) { const response = await fetch(url + "/mcp", { method: "POST", + signal, headers: { authorization: "Bearer " + key, "content-type": "application/json", @@ -53,11 +55,12 @@ async function connect( kind = "computer", onDispatch?: (frame: JsonObject, socket: WebSocket) => void, platform = kind === "browser" ? "Browser extension" : "darwin", + autoPong = true, ) { const socket = new WebSocket( f.url.replace("http:", "ws:") + "/ws/" + (kind === "browser" ? "browser" : "device"), kind === "browser" - ? { origin: "chrome-extension://" + "a".repeat(32) } + ? { origin: "chrome-extension://" + "a".repeat(32), autoPong } : { headers: { authorization: "Bearer " + key } }, ); socket.on("message", (data) => { @@ -499,6 +502,322 @@ test("session_open returns the same device summary as devices_list across platfo } }); +test("a new browser session waits for the same device to reconnect after a stale socket", async () => { + const f = await fixture(); + try { + const user = await f.store.createUser("resume-browser", "synthetic-fixture-password"); + const device = f.store.createDevice(user.id, "Browser", ["browser"], "browser"); + const agent = f.store.createAgentConnection(user.id, "Fixture", { + mode: "all", + capabilities: ["browser"], + overrides: [], + }); + const open = () => + rpc(f.url, agent.key, "session_open", { device_id: device.device.id, capabilities: ["browser"] }); + const oldDispatches: JsonObject[] = []; + const stale = await connect( + f, + device.key, + "browser", + (frame) => oldDispatches.push(frame), + undefined, + false, + ); + const echo = (nonce: Buffer) => stale.socket.pong(nonce); + stale.socket.on("ping", echo); + const oldSession = (await open()).value; + const inFlight = await f.control.execute( + agent.agentConnection, + oldSession.id, + "browser_open", + { url: "https://fixture.invalid/" }, + "old-navigation", + false, + ); + stale.socket.off("ping", echo); + + const challenged = once(stale.socket, "ping"); + const retired = once(stale.socket, "close"); + const opening = open(); + assert.equal( + await Promise.race([challenged.then(() => "challenged"), opening.then(() => "opened")]), + "challenged", + ); + const [nonce] = await challenged; + const wrongNonce = Buffer.from(nonce); + wrongNonce[0] ^= 1; + stale.socket.pong(wrongNonce); + await retired; + assert.equal(f.store.session(oldSession.id)?.status, "connection_lost"); + assert.equal(f.store.operation(inFlight.operation_id)?.status, "outcome_unknown"); + assert.equal(oldDispatches.length, 1); + assert.equal(oldDispatches[0]!.operation_id, inFlight.operation_id); + assert.deepEqual(f.store.sessions(device.device.id), []); + const offlineOpening = f.control.openSession(agent.agentConnection, device.device.id, ["browser"]); + assert.equal(await Promise.race([offlineOpening.then(() => "opened"), delay(50, "waiting")]), "waiting"); + + const dispatches: JsonObject[] = []; + const fresh = await connect(f, device.key, "browser", (frame, socket) => { + dispatches.push(frame); + socket.send( + JSON.stringify({ + type: "result", + operation_id: frame.operation_id, + connection_epoch: frame.connection_epoch, + status: "executed", + result: { text: "fresh browser" }, + }), + ); + }); + const opened = await opening; + assert.equal(opened.isError, undefined); + assert.notEqual(opened.value.id, oldSession.id); + const offlineOpened = await offlineOpening; + assert.notEqual(offlineOpened.id, oldSession.id); + assert.notEqual(offlineOpened.id, opened.value.id); + assert.equal(offlineOpened.device_id, device.device.id); + assert.ok(fresh.welcome.connection_epoch > stale.welcome.connection_epoch); + await assert.rejects(f.control.execute(agent.agentConnection, oldSession.id, "browser_read", {}), { + code: "session_connection_lost", + }); + const read = () => + rpc(f.url, agent.key, "browser_read", { session_id: opened.value.id, operation_id: "fresh-read" }); + const receipts = await Promise.all([read(), read()]); + const receipt = receipts.find(({ value }) => value.status === "executed"); + assert.ok(receipt); + assert.equal(receipt.value.status, "executed"); + assert.equal(receipt.value.result.text, "fresh browser"); + assert.equal(receipts[0]!.value.operation_id, receipts[1]!.value.operation_id); + assert.equal(dispatches.length, 1); + assert.equal(dispatches[0]!.connection_epoch, fresh.welcome.connection_epoch); + } finally { + await f.dispose(); + } +}); + +test("browser session waiting offline rechecks the device key and Agent connection", async () => { + const f = await fixture(); + try { + const owner = await f.store.createUser("offline-browser", "synthetic-fixture-password"); + const { device } = f.store.createDevice(owner.id, "Browser", ["browser"], "browser"); + const policy = { mode: "all" as const, capabilities: ["browser" as const], overrides: [] }; + const revoked = f.store.createAgentConnection(owner.id, "Revoked", policy); + const active = f.store.createAgentConnection(owner.id, "Active", policy); + const mustReject = async (opening: Promise, code: string) => { + await assert.rejects(opening, { code }); + assert.deepEqual(f.store.sessions(device.id), []); + }; + const revokedWait = mustReject( + f.control.openSession(revoked.agentConnection, device.id, ["browser"]), + "unauthorized", + ); + f.store.revokeAgentConnection(revoked.agentConnection.id); + await revokedWait; + const rotatedWait = mustReject( + f.control.openSession(active.agentConnection, device.id, ["browser"]), + "device_offline", + ); + f.store.rotateDevice(device.id); + await rotatedWait; + } finally { + await f.dispose(); + } +}); + +test("browser session opening respects a local pause after its socket closes", async () => { + const f = await fixture(); + try { + const owner = await f.store.createUser("paused-offline-browser", "synthetic-fixture-password"); + const { device, key } = f.store.createDevice(owner.id, "Browser", ["browser"], "browser"); + const agent = f.store.createAgentConnection(owner.id, "Fixture", { + mode: "all", + capabilities: ["browser"], + overrides: [], + }); + const { socket, welcome } = await connect(f, key, "browser"); + const message = once(socket, "message"); + socket.send( + JSON.stringify({ type: "heartbeat", paused: true, connection_epoch: welcome.connection_epoch }), + ); + assert.equal(JSON.parse((await message)[0].toString()).type, "stop"); + const closed = once(socket, "close"); + socket.close(); + await closed; + const deadline = Date.now() + 5000; + while (f.control.deviceView(device).status !== "offline" && Date.now() < deadline) await delay(10); + assert.equal(f.control.deviceView(device).status, "offline"); + await assert.rejects(f.control.openSession(agent.agentConnection, device.id, ["browser"]), { + code: "device_paused", + }); + } finally { + await f.dispose(); + } +}); + +test("a browser transport without liveness confirmation cannot create a session", async () => { + const f = await fixture(); + try { + const owner = await f.store.createUser("unverified-browser", "synthetic-fixture-password"); + const device = f.store.createDevice(owner.id, "Browser", ["browser"], "browser"); + const agent = f.store.createAgentConnection(owner.id, "Fixture", { + mode: "all", + capabilities: ["browser"], + overrides: [], + }); + await f.control.attachConnection( + device.key, + "browser", + { capabilities: { browser: true } }, + { + async send() {}, + async close() {}, + }, + ); + const refused = await rpc(f.url, agent.key, "session_open", { + device_id: device.device.id, + capabilities: ["browser"], + }); + assert.equal(refused.value.error.code, "device_offline"); + assert.deepEqual(f.store.sessions(device.device.id), []); + } finally { + await f.dispose(); + } +}); + +test("browser dispatch rechecks authorization after its WebSocket challenge", async () => { + const f = await fixture(); + try { + const user = await f.store.createUser("revoked-browser", "synthetic-fixture-password"); + const device = f.store.createDevice(user.id, "Browser", ["browser"], "browser"); + const agent = f.store.createAgentConnection(user.id, "Fixture", { + mode: "all", + capabilities: ["browser"], + overrides: [], + }); + const dispatches: JsonObject[] = []; + const { socket } = await connect( + f, + device.key, + "browser", + (frame) => dispatches.push(frame), + undefined, + false, + ); + const echo = (nonce: Buffer) => socket.pong(nonce); + socket.on("ping", echo); + const session = await f.control.openSession(agent.agentConnection, device.device.id, ["browser"]); + socket.off("ping", echo); + + const challenged = once(socket, "ping"); + const execution = f.control.execute( + agent.agentConnection, + session.id, + "browser_read", + {}, + undefined, + false, + ); + assert.equal( + await Promise.race([challenged.then(() => "challenged"), execution.then(() => "dispatched")]), + "challenged", + ); + f.store.revokeAgentConnection(agent.agentConnection.id); + socket.pong((await challenged)[0]); + await assert.rejects(execution, { code: "unauthorized" }); + assert.deepEqual(dispatches, []); + } finally { + await f.dispose(); + } +}); + +for (const tool of ["session_open", "browser_read", "browser_exec"] as const) { + test(`closing the MCP HTTP request prevents ${tool} admission during a browser challenge`, async (t) => { + const f = await fixture(); + try { + const user = await f.store.createUser("cancelled-browser", "synthetic-fixture-password"); + const device = f.store.createDevice(user.id, "Browser", ["browser"], "browser"); + const agent = f.store.createAgentConnection(user.id, "Fixture", { + mode: "all", + capabilities: ["browser"], + overrides: [], + }); + const dispatches: JsonObject[] = []; + const collect = (frame: JsonObject) => dispatches.push(frame); + const { socket, welcome } = await connect(f, device.key, "browser", collect, undefined, false); + const openSession = t.mock.method(f.control, "openSession"); + const execute = t.mock.method(f.control, "execute"); + const echo = (nonce: Buffer) => socket.pong(nonce); + const operationId = "fixture-cancel"; + let sessionId: string | undefined; + let args: JsonObject = { device_id: device.device.id, capabilities: ["browser"] }; + if (tool !== "session_open") { + socket.on("ping", echo); + const session = await f.control.openSession(agent.agentConnection, device.device.id, ["browser"]); + socket.off("ping", echo); + sessionId = session.id; + args = { + session_id: sessionId, + operation_id: operationId, + ...(tool === "browser_exec" ? { code: "return await page.read();" } : {}), + }; + } + + const caller = new AbortController(); + const disconnected = new Promise((resolve) => { + f.app.server.once("request", (_request, response) => response.once("close", () => resolve())); + }); + const challenge = once(socket, "ping"); + const requested = rpc(f.url, agent.key, tool, args, caller.signal); + assert.equal( + await Promise.race([challenge.then(() => "challenged"), requested.then(() => "accepted")]), + "challenged", + ); + const surviving = + tool === "session_open" + ? f.control.openSession(agent.agentConnection, device.device.id, ["browser"]) + : undefined; + caller.abort(); + await assert.rejects(requested, { name: "AbortError" }); + await disconnected; + const admission = (tool === "session_open" ? openSession : execute).mock.calls[0]?.result; + assert.ok(admission); + assert.equal( + await Promise.race([ + assert.rejects(admission, /aborted|connection closed/i).then(() => "cancelled"), + delay(1000, "waiting"), + ]), + "cancelled", + "the request should be released before the shared probe times out", + ); + + if (sessionId) { + const [nonce] = await challenge; + const acknowledgement = once(socket, "message"); + socket.pong(nonce); + socket.send(JSON.stringify({ type: "heartbeat", connection_epoch: welcome.connection_epoch })); + assert.equal(JSON.parse((await acknowledgement)[0].toString()).type, "heartbeat_ack"); + const keyHash = createHash("sha256") + .update(JSON.stringify([agent.agentConnection.id, sessionId, operationId])) + .digest("base64url"); + assert.equal(f.store.operationForKey(keyHash), undefined); + } else { + assert.deepEqual(f.store.sessions(device.device.id), []); + const [nonce] = await challenge; + socket.pong(nonce); + const session = await surviving; + assert.ok(session); + assert.deepEqual( + f.store.sessions(device.device.id).map(({ id }) => id), + [session.id], + ); + } + assert.deepEqual(dispatches, []); + } finally { + await f.dispose(); + } + }); +} + test("MCP input occupancy exposes only this connection's recoverable sessions", async () => { const f = await fixture(); try { @@ -553,7 +872,7 @@ test("browser is an independent device; revocation during wait blocks result acc const { socket } = await connect(f, device.key, "browser", (frame) => { dispatch = frame; }); - const session = f.control.openSession(g.agentConnection, device.device.id, ["browser"]); + const session = await f.control.openSession(g.agentConnection, device.device.id, ["browser"]); const pending = f.control.execute(g.agentConnection, session.id, "browser_open", { url: "https://example.com", }); @@ -569,7 +888,10 @@ test("browser is an independent device; revocation during wait blocks result acc }), ); await assert.rejects(pending, (error) => error instanceof BridgeError && error.code === "unauthorized"); - assert.throws(() => f.control.openSession(g.agentConnection, device.device.id, ["shell"]), BridgeError); + await assert.rejects( + () => f.control.openSession(g.agentConnection, device.device.id, ["shell"]), + BridgeError, + ); socket.close(); } finally { await f.dispose(); @@ -703,6 +1025,62 @@ test("Device Token verification returns only its identity, rejects other credent } }); +test("browser socket distinguishes invalidated Device Keys from protocol errors", async () => { + const f = await fixture(); + let online: WebSocket | undefined; + async function rejectedHello(deviceKey: string, code: number, protocol = "abridge/1") { + const socket = new WebSocket(f.url.replace("http:", "ws:") + "/ws/browser", { + origin: "chrome-extension://" + "a".repeat(32), + }); + let received = 0; + socket.on("message", () => received++); + try { + await once(socket, "open", { signal: AbortSignal.timeout(3000) }); + const closed = once(socket, "close", { signal: AbortSignal.timeout(3000) }); + socket.send( + JSON.stringify({ + type: "hello", + protocol, + platform: "Browser extension", + version: "0.5.0", + paused: false, + instance_id: "server-test-instance", + device_key: deviceKey, + capabilities: { browser: true }, + }), + ); + assert.equal((await closed)[0], code); + assert.equal(received, 0); + } finally { + socket.terminate(); + } + } + try { + const owner = await f.store.createUser("browser-owner", "fixture-password-123"); + const { device, key } = f.store.createDevice(owner.id, "Fixture Browser", ["browser"], "browser"); + const session = await f.store.login(owner.username, "fixture-password-123"); + const headers = { cookie: "abridge_session=" + session!.token }; + const path = f.url + "/api/devices/" + device.id; + const rotation = await fetch(path + "/credentials", { method: "POST", headers }); + assert.equal(rotation.status, 200); + const freshKey = (await rotation.json()).key as string; + await rejectedHello(key, 4401); + await rejectedHello(freshKey, 4400, "abridge/unknown"); + const connected = await connect(f, freshKey, "browser"); + online = connected.socket; + assert.equal(connected.welcome.device_id, device.id); + + const closed = once(online, "close", { signal: AbortSignal.timeout(3000) }); + assert.equal((await fetch(path + "/revoke", { method: "POST", headers })).status, 200); + assert.equal((await closed)[0], 4403); + await rejectedHello(freshKey, 4401); + assert.ok(f.store.device(device.id)?.revoked_at); + } finally { + online?.terminate(); + await f.dispose(); + } +}); + test("computer_observe accepts pid alone and rejects invalid window targets before dispatch", async () => { const f = await fixture(); let socket: WebSocket | undefined; diff --git a/apps/server/tests/session-recovery.test.ts b/apps/server/tests/session-recovery.test.ts index 625f383..d4eb7d3 100644 --- a/apps/server/tests/session-recovery.test.ts +++ b/apps/server/tests/session-recovery.test.ts @@ -100,7 +100,7 @@ test("Android tool discovery, dispatch and recovery agree with the device profil "computer_observe", "computer_act", ]); - const session = f.control.openSession(f.agentConnection, device.id, ["screen", "input"]); + const session = await f.control.openSession(f.agentConnection, device.id, ["screen", "input"]); const before = f.frames.length; await assert.rejects(f.control.execute(f.agentConnection, session.id, "computer_apps", {}), { code: "unsupported_tool", @@ -141,7 +141,7 @@ test("Android tool discovery, dispatch and recovery agree with the device profil test("activity returns fresh leases for dispatch, completion, status and duplicate requests", async () => { const f = await fixture(); try { - const session = f.control.openSession(f.agentConnection, f.device.id, ["screen"]); + const session = await f.control.openSession(f.agentConnection, f.device.id, ["screen"]); f.advance(100); const accepted = await f.control.execute( f.agentConnection, @@ -200,7 +200,7 @@ test("activity returns fresh leases for dispatch, completion, status and duplica test("session closure supersedes caller cancellation before a late action receipt", async () => { const f = await fixture(); try { - const session = f.control.openSession(f.agentConnection, f.device.id, ["screen", "input"]); + const session = await f.control.openSession(f.agentConnection, f.device.id, ["screen", "input"]); const action = await f.control.execute( f.agentConnection, session.id, @@ -232,7 +232,7 @@ test("session closure supersedes caller cancellation before a late action receip test("a result deadline fails desktop reads in place and keeps unconfirmed writes unknown", async (t) => { const f = await fixture(); try { - const session = f.control.openSession(f.agentConnection, f.device.id, ["screen", "input"]); + const session = await f.control.openSession(f.agentConnection, f.device.id, ["screen", "input"]); t.mock.timers.enable({ apis: ["setTimeout"] }); const missing = [ f.control.execute(f.agentConnection, session.id, "computer_apps", {}), @@ -292,7 +292,7 @@ test("a result deadline fails desktop reads in place and keeps unconfirmed write test("discovery and input occupancy expose only this Agent connection's sessions without renewing or taking over", async () => { const f = await fixture(); try { - const session = f.control.openSession(f.agentConnection, f.device.id, ["screen", "input"]); + const session = await f.control.openSession(f.agentConnection, f.device.id, ["screen", "input"]); assert.match(session.id, /^ses_[A-Za-z0-9_-]{8}$/); f.advance(60); const own = f.control.devices(f.agentConnection)[0]; @@ -302,7 +302,7 @@ test("discovery and input occupancy expose only this Agent connection's sessions ); assert.deepEqual(f.control.devices(f.otherAgentConnection)[0].sessions, []); assert.equal(f.store.session(session.id)?.lease_until, session.lease_until); - assert.throws( + await assert.rejects( () => f.control.openSession(f.agentConnection, f.device.id, ["input"]), (error) => { assert.ok(error instanceof BridgeError); @@ -311,7 +311,7 @@ test("discovery and input occupancy expose only this Agent connection's sessions return true; }, ); - assert.throws( + await assert.rejects( () => f.control.openSession(f.otherAgentConnection, f.device.id, ["input"]), (error) => { assert.ok(error instanceof BridgeError); @@ -321,7 +321,7 @@ test("discovery and input occupancy expose only this Agent connection's sessions ); assert.equal(f.store.session(session.id)?.status, "active"); await f.control.closeSession(f.agentConnection, session.id); - assert.equal(f.control.openSession(f.agentConnection, f.device.id, ["input"]).status, "active"); + assert.equal((await f.control.openSession(f.agentConnection, f.device.id, ["input"])).status, "active"); } finally { await f.close(); } @@ -330,7 +330,7 @@ test("discovery and input occupancy expose only this Agent connection's sessions test("unauthorized requests do not renew and retained results never revive stopped or expired sessions", async () => { const f = await fixture(); try { - const session = f.control.openSession(f.agentConnection, f.device.id, ["screen"]); + const session = await f.control.openSession(f.agentConnection, f.device.id, ["screen"]); const operation = await f.control.execute( f.agentConnection, session.id, @@ -356,7 +356,7 @@ test("unauthorized requests do not renew and retained results never revive stopp assert.equal(stopped.status, "executed"); assert.equal(stopped.session?.status, "stopped"); assert.equal(stopped.session?.lease_until, lease); - const idle = f.control.openSession(f.agentConnection, f.device.id, ["screen"]); + const idle = await f.control.openSession(f.agentConnection, f.device.id, ["screen"]); const idleOperation = await f.control.execute( f.agentConnection, idle.id, @@ -388,7 +388,7 @@ test("renewal cannot exceed Agent connection expiry, including a late completion f.agentConnection.policy, expires, ); - const session = f.control.openSession(agentConnection, f.device.id, ["screen"]); + const session = await f.control.openSession(agentConnection, f.device.id, ["screen"]); const operation = await f.control.execute( agentConnection, session.id, @@ -416,9 +416,9 @@ test("renewal cannot exceed Agent connection expiry, including a late completion test("request keys are session scoped while returned operation IDs survive restart without replay", async () => { const f = await fixture(); try { - const first = f.control.openSession(f.agentConnection, f.device.id, ["screen"]); - const second = f.control.openSession(f.agentConnection, f.device.id, ["screen"]); - const other = f.control.openSession(f.otherAgentConnection, f.device.id, ["screen"]); + const first = await f.control.openSession(f.agentConnection, f.device.id, ["screen"]); + const second = await f.control.openSession(f.agentConnection, f.device.id, ["screen"]); + const other = await f.control.openSession(f.otherAgentConnection, f.device.id, ["screen"]); const a = await f.control.execute(f.agentConnection, first.id, "computer_apps", {}, "apps", false); const b = await f.control.execute(f.agentConnection, second.id, "computer_apps", {}, "apps", false); const c = await f.control.execute(f.otherAgentConnection, other.id, "computer_apps", {}, "apps", false); @@ -443,7 +443,7 @@ test("request keys are session scoped while returned operation IDs survive resta assert.equal(retained.result_available, false); assert.equal(retained.session?.status, "server_restarted"); assert.equal(f.control.operationStatus(f.agentConnection, b.operation_id).status, "outcome_unknown"); - const fresh = f.control.openSession(f.agentConnection, f.device.id, ["screen"]); + const fresh = await f.control.openSession(f.agentConnection, f.device.id, ["screen"]); await assert.rejects( f.control.execute(f.agentConnection, fresh.id, "computer_apps", {}, a.operation_id, false), { @@ -459,7 +459,7 @@ test("request keys are session scoped while returned operation IDs survive resta test("device receipts cannot supply server-owned disconnect diagnostics", async () => { const f = await fixture(); try { - const session = f.control.openSession(f.agentConnection, f.device.id, ["screen"]); + const session = await f.control.openSession(f.agentConnection, f.device.id, ["screen"]); const error = { code: "outcome_unknown", message: "Not confirmed", @@ -503,7 +503,7 @@ test("device receipts cannot supply server-owned disconnect diagnostics", async test("diagnostics preserve desktop causes and heartbeat expiry; session metadata fits minimum output pages", async () => { const f = await fixture(); try { - const session = f.control.openSession(f.agentConnection, f.device.id, ["screen", "shell"]); + const session = await f.control.openSession(f.agentConnection, f.device.id, ["screen", "shell"]); const operation = await f.control.execute( f.agentConnection, session.id, @@ -573,7 +573,7 @@ test("diagnostics preserve desktop causes and heartbeat expiry; session metadata test("short operation IDs preserve distinct keys through collisions and restart", async () => { const f = await fixture(); try { - const session = f.control.openSession(f.agentConnection, f.device.id, ["screen"]); + const session = await f.control.openSession(f.agentConnection, f.device.id, ["screen"]); const keyHash = createHash("sha256") .update(JSON.stringify([f.agentConnection.id, session.id, "retry-key"])) .digest("base64url"); @@ -656,7 +656,7 @@ test("short operation IDs preserve distinct keys through collisions and restart" test("generated operation IDs stay short and unknown returned-ID syntax cannot start work", async () => { const f = await fixture(); try { - const session = f.control.openSession(f.agentConnection, f.device.id, ["screen"]); + const session = await f.control.openSession(f.agentConnection, f.device.id, ["screen"]); const generated = await f.control.execute( f.agentConnection, session.id, diff --git a/docs/architecture.md b/docs/architecture.md index d28ffac..4541035 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -67,7 +67,7 @@ Server 使用 Fastify 5 和官方 MCP TypeScript SDK v2。MCP HTTP transport 按 样式通过 `src/styles/index.css` 有序汇入基础、公共控件、布局和各功能样式,构建后仍输出单个 `/static/app.css`;`public/` 只维护 HTML、字体与图片等静态资产。 -持久化使用 Node 内置 `node:sqlite` 的 `DatabaseSync`,其调用同步占用事件循环。最低运行版本 Node 22.13.0 已取消该模块的启动 flag 要求,但该版本仍将其标为实验 API。当前开发数据库为 schema 6,Agent 连接使用 `agent_connections` / `platform_connections` 表,以及 `agent_connection_id` 引用字段;旧开发数据库须显式调整为当前结构,Server 不自动迁移或清空。当前限制单个数据库由一个 Server 实例持有,内存连接与结果缓存不支持多 worker 或横向部署。[Node 22.13.0 发布说明](https://nodejs.org/en/blog/release/v22.13.0) +持久化使用 Node 内置 `node:sqlite` 的 `DatabaseSync`,其调用同步占用事件循环。最低运行版本 Node 22.13.0 已取消该模块的启动 flag 要求,但该版本仍将其标为实验 API。数据库基线为 schema 6,Agent 连接使用 `agent_connections` / `platform_connections` 表。托管浏览器在启动时补齐独立登记表 `managed_browsers`。已有旧形状的托管登记需要离线转换。当前限制单个数据库由一个 Server 实例持有,内存连接与结果缓存不支持多 worker 或横向部署。[Node 22.13.0 发布说明](https://nodejs.org/en/blog/release/v22.13.0) ## Linux CLI 客户端 @@ -143,6 +143,8 @@ Windows 壳消息和平台动作契约维护在 `packages/protocol/src/windows-s Android 的 hello 和心跳可上报 `interaction_state`(`ready`、`screen_off`、`locked`)。在线时设备摘要包含该状态。熄屏或锁屏暂停屏幕和输入能力并终止受影响的会话,文件能力继续按独立授权判断。亮屏且退出锁屏界面后,任务打开新会话并重新观察。 +浏览器设备的列表状态反映最近的心跳。打开新会话前,Server 用 WebSocket Ping/Pong 确认设备仍能应答。休眠或网络中断后,新会话可以短暂等待同一设备重连,包括原连接已被清理的情况。等待期间持续复核凭据、授权、本机暂停和调用方取消。Server 会持久记录浏览器已上报的暂停和能力关闭,重启后仍阻止新会话和候选换绑,直到有效设备连接上报恢复。已有会话绑定原连接代次。派发新操作前也会确认该连接,已经发出但未取得结果的操作保留 `outcome_unknown`,不会自动重放。 + `devices_list` 与 `session_open` 通过 `available_tools` 公布默认参数下可用的设备工具。会话清单还受本次请求的能力约束。Server 按同一平台清单拒绝未实现的工具。桌面输入被拒绝后,`error.recovery.action` 可提示重新观察或请求用户接管。重新观察后应核对目标,并且只重试一次明确未执行的操作。 设备的 `platform`、`version` 和可选 `details` 保存最近一次通过身份校验且成功发送欢迎消息的连接上报,断连和 Server 重启后仍可读取。后续成功连接替换整份上报,缺失字段保持未知。基础字段 `platform` 保留平台标签,`version` 表示 aBridge 客户端或扩展版本。`details` 可包含系统及版本、发行版、架构和浏览器品牌及主版本。macOS 和 Linux 可提供主机名、型号和客户端进程的系统用户名,Linux 额外提供内核版本。归属账户来自 Server 的绑定关系。设备上报只用于展示和排障,授权仍由 Server 验证,在线状态由连接与心跳判定。失败、过期连接和凭据撤销后的迟到握手不会更新设备信息。 diff --git a/docs/deployment.md b/docs/deployment.md index a254874..afc4b0b 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -215,6 +215,41 @@ npm run build 扩展独立注册为浏览器设备。在管理台把它加入所需的 Agent 连接,并授予 `browser` 能力。更新构建文件后,在扩展管理页选择「重新加载」并确认已连接,原绑定和暂停状态会保留。[浏览器客户端](browser-profile-design.md) +## 无头 Linux 浏览器客户端 + +`abridge-client-browser` 是独立浏览器设备,只提供 `browser`。由 aBridge 打包业务启动器、Playwright 版本和同版本扩展。构建机器执行 `npm run package:browser-client`,取出 `.local/release/browser-client/abridge-client-browser-<版本>-linux.tar.gz`。 + +在目标 Linux 上解包。当前已验证 Linux amd64,客户端要求 Python 3.10 或更新版本。管理员预装 Chromium 系统库与可信 CA;可使用发行物所钉住的 Playwright 执行 `python -m playwright install-deps chromium`。使用专用非 root 账户执行以下命令。在启用受限 user namespace 的发行版上,系统策略须允许此 Chromium 使用 user namespace 沙盒。Ubuntu AppArmor 可为实际安装路径上的受保护 Chromium 二进制设置单独的 `userns` 规则。 + +```sh +cd abridge-client-browser +python3 -m venv .venv +.venv/bin/pip install -r requirements.txt +.venv/bin/python -m playwright install --no-shell chromium +.venv/bin/python -I ./abridge-client-browser bind --server https://bridge.example.com +.venv/bin/python -I ./abridge-client-browser run +``` + +在管理台新建浏览器设备,生成 Browser Device Key,在 `bind` 提示中隐藏输入。然后将该设备加入需要控制它的 Agent 连接。`bind --stdin` 可经私有输入管道读取 Key。远端 HTTP 需要指定 `--allow-http`;回环可直接用于开发验收。运行账户可以用 `status` 查看本地绑定状态,aBridge 设备列表确认 WebSocket 在线。将前台 `run` 交给部署已有的进程管理器,重启沿用 `~/.local/state/abridge-client-browser` 中的 Profile。需要修改存储位置时为该账户设置 `ABRIDGE_BROWSER_HOME`,使用权限 0700 的目录。 + +### 可选平台托管浏览器 + +Server 启用平台委托并设置 `ABRIDGE_MANAGED_BROWSER_ENABLED=true` 后,受信平台可为工作负载登记浏览器。平台向 `GET /api/managed-browsers/status` 提交只读 JWT。首次安装、计划换绑或确认丢失本地绑定时,平台用当前登记版本签发 `POST /api/managed-browsers/provision` 的 JWT。Server 按发行方、客户端与主体登记专属浏览器设备,并维护递增的绑定版本。 + +平台通过私有 stdin 将 `browser_origin`、`device_id`、`revision` 与首次绑定需要的 `bootstrap_token` 交给浏览器客户端的 `start`。客户端从同一公开 Origin 的 `/api/managed-browsers/redeem` 换取 Browser Device Key。客户端从已确认的 Profile 恢复时,交接只需要 Origin、设备 ID 和版本。来宾须能访问公开 Origin 的 HTTPS 与 WebSocket。HTTP 部署须在 Server 显式打开相应配置,并在交接中提供与 Origin 一致的 `http_confirmed_origin`。 + +计划换绑使用 `replace: true`。换绑响应提供候选版本和票据,状态接口的 `binding` 继续报告当前安装,`replacement` 报告候选版本及其有效期。候选票据兑换出的 Key 可用于验证设备身份。新 Profile 保存凭据并通过 WebSocket 往返确认后,Server 才启用候选 Key、推进版本并结束旧会话。候选启动失败时,旧登记继续有效。有效期内可用当前版本及同一候选安装标识重新领票,新票据签发时上一轮候选 Key 即失效。 + +客户端运行时通过 `status` 返回扩展自己的 `connected`。平台应核对此值及 Server `binding` 的同一版本已在线,再将浏览器标为就绪。 + +工作负载的通用 `abridge-delegation` 委托还须携带当前 `installation_id` 与 `revision`。aBridge 只允许它控制本次登记的浏览器。新版本启用时,Server 同时撤销旧版 MCP 连接。若旧 Key 已泄露或需立即取消访问,平台使用 `POST /api/managed-browsers/stop`,按当前版本撤销设备 Key、该工作负载的 MCP 连接和全部候选凭据。客户端本地 `stop` 关闭浏览器进程并保留绑定。已有关闭状态可由受信平台查询,即使该部署随后关闭了新登记。 + +平台也可以在登录用户明确授权后,用该用户的 OIDC `sub` 登记其个人运行环境。`GET /api/personal-browsers/status` 和 `POST /api/personal-browsers/provision` 沿用上述状态和版本协议,分别校验 `abridge-personal-browser-status` 和 `abridge-personal-browser-provision` 用途及对应端点的受众,并使用同一票据兑换接口。个人登记使用账户级平台授权。首次登记时,若该账户尚无此平台连接,Server 会建立覆盖账户全部设备和能力的连接。已有连接沿用用户设定的设备、能力和撤销策略。用户可以在管理台管理平台连接和设备。 + +在管理台为个人浏览器重新生成凭据时,当前安装需要重新连接。管理台签发的 Device Key 可以照常绑定,直到用户在平台重新连接并兑换新凭据。 + +标准 SQLite schema 6 数据库可以直接启用托管浏览器。已有旧试用登记时,部署方先备份,再在隔离副本中转换该表。 + ## 数据与更新 每个数据库由一个 Server 实例使用,启动时会锁定该路径。重启后设备会重新连接,任务需要新建会话。重启前结果未知的操作,可先查询状态,再检查实际结果。 diff --git a/docs/releasing.md b/docs/releasing.md index d279ab4..de3b660 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -85,6 +85,8 @@ CI 上传 **windows-client-unsigned**,保留 30 天。tag 发布另将 `aBridg 发布复用 Linux CI,在原生 amd64 和 arm64 runner 上构建 musl 静态包,并验证打包二进制与 Server 联调、用户级 systemd 生命周期。两个架构均须通过才进入发布。GitHub Release 附带两个架构各自的 `abridge-client--.tar.gz` 和一份 `SHA256SUMS`。各架构的体积报告和单独的校验文件留在 CI artifact 中。下载后按 [Linux 安装说明](https://github.com/xerrors/aBridge/blob/main/apps/linux-client/README.md#安装与绑定) 核对校验和。 +GitHub Release 同时附带 `abridge-client-browser--linux.tar.gz`。Linux 发布任务使用同版本扩展生成发行物,校验包内版本并将包的 SHA-256 汇总到 `SHA256SUMS`。该客户端使用 [无头 Linux 浏览器安装流程](deployment.md#无头-linux-浏览器客户端) 安装 Chromium。 + ## Chrome 应用商店 `dist/releases/abridge-browser-.zip` 是商店上传包。首次上传在开发者信息中心完成,需准备商店名称、简要说明、用途、截图、图标、隐私政策及权限用途说明。上传后还需完成商店审核并取得 item ID;首次发布状态以信息中心为准。 diff --git a/package.json b/package.json index ba96639..e42540f 100644 --- a/package.json +++ b/package.json @@ -45,7 +45,8 @@ "windows:shell:check": "node --import tsx tools/windows-native.ts check", "test:windows:shell:live": "node --import tsx tools/check-windows-shell.ts", "agent:build": "cd apps/agent && go build -o ../../dist/agent/abridge-agent ./cmd/abridge-agent", - "agent:check": "cd apps/agent && go test -race ./... && go vet ./..." + "agent:check": "cd apps/agent && go test -race ./... && go vet ./...", + "package:browser-client": "npm run build && node --import tsx tools/package-browser-client.ts" }, "devDependencies": { "@commitlint/cli": "21.2.4", diff --git a/packages/protocol/src/management.ts b/packages/protocol/src/management.ts index 70507b2..9b06323 100644 --- a/packages/protocol/src/management.ts +++ b/packages/protocol/src/management.ts @@ -14,6 +14,31 @@ import { export const managementUserSchema = z.object({ id: z.string(), username: z.string() }); export type UserView = z.infer; +export const managedBrowserClaimsSchema = z.object({ + sub: z.string().min(1).max(160), + iat: z.number().int().nonnegative(), +}); +export const managedBrowserBindingSchema = z.object({ + installation_id: z.string().min(1).max(160), + revision: z.number().int().positive(), +}); +export const managedBrowserProvisionSchema = managedBrowserBindingSchema.extend({ + revision: z.number().int().nonnegative(), + replace: z.boolean().default(false), +}); +export const personalBrowserProvisionSchema = managedBrowserProvisionSchema.extend({ + name: z.string().trim().min(1).max(120).optional(), +}); +export type BrowserEnrollmentScope = "managed" | "personal"; +export type ManagedBrowserClaims = z.infer; +export type ManagedBrowserBinding = z.infer; +export type ManagedBrowserProvision = z.infer; +export type PersonalBrowserProvision = z.infer; +export const managedBrowserRedeemSchema = z.strictObject({ + device_id: z.string().min(1).max(160), + bootstrap_token: z.string().regex(/^[A-Za-z0-9_-]{43}$/), +}); + export const deviceViewSchema = deviceMetadataSchema.extend({ id: z.string(), name: z.string(), diff --git a/tools/README.md b/tools/README.md index 2b4b8c5..7b2b193 100644 --- a/tools/README.md +++ b/tools/README.md @@ -75,5 +75,13 @@ `test:browser:live` 使用自有本机 HTTP 页面,核对三条批量提交的服务端记录、数字/邮箱替换与清空、跨调用状态、条件等待、长文快照分页、表格提取、键盘、滚动和同源 iframe 输入。测试直接运行实际 BrowserBridge 与 QuickJS,通过薄 Chrome API 适配器调用真实 CDP;它不替代已安装扩展的绑定、WebSocket 重连或商店包验收。标准 `check` 保持无需真实浏览器;服务端与扩展 worker 的线缆集成由自动测试单独覆盖。 +Linux 浏览器换绑验收使用解包后的客户端、启用沙盒的 Chromium、真实 Server 和测试 OIDC。先按[部署文档](../docs/deployment.md#无头-linux-浏览器客户端)准备发行包和依赖,再运行: + +```sh +ABRIDGE_BROWSER_TEST_LAUNCHER=/absolute/path/to/abridge-client-browser \ +ABRIDGE_BROWSER_TEST_PYTHON=/absolute/path/to/.venv/bin/python \ +node --import tsx --test --test-name-pattern='packaged browser restores' apps/server/tests/identity.test.ts +``` + `npm run test:browser:reliability:live` 使用独立真实 Chrome 和自有页面验证通用输入与恢复。`benchmark:miniwob -- --model-catalog /absolute/path/to/models.json` 固定实际模型元数据并记录其摘要,`--holdout` 单独运行额外 seed=2(非盲测)。[对照方法与边界](../docs/benchmarks/browser-reliability-v2.md)。 原生回归覆盖电脑执行、WebSocket/Shell 生命周期、共享契约、授权和原生更新器。`npm run test:desktop` 在 Apple Silicon macOS 构建完整 App,运行 `apps/desktop/tests/` 下的测试以及 `tools/tests/` 下的原生和安装器测试。macOS 上的 `npm run check` 也会构建完整 App 并运行全部测试。 diff --git a/tools/package-browser-client.ts b/tools/package-browser-client.ts new file mode 100644 index 0000000..e3ee880 --- /dev/null +++ b/tools/package-browser-client.ts @@ -0,0 +1,21 @@ +import { execFileSync } from "node:child_process"; +import { cpSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { resolve } from "node:path"; + +const output = resolve(".local/release/browser-client"); +const bundle = resolve(output, "abridge-client-browser"); +const { version } = JSON.parse(readFileSync("package.json", "utf8")) as { version: string }; +rmSync(bundle, { recursive: true, force: true }); +mkdirSync(bundle, { recursive: true }); +cpSync("apps/browser-client/abridge-client-browser", resolve(bundle, "abridge-client-browser")); +cpSync("apps/browser-client/requirements.txt", resolve(bundle, "requirements.txt")); +cpSync("dist/browser", resolve(bundle, "extension"), { recursive: true }); +cpSync("LICENSE", resolve(bundle, "LICENSE")); +writeFileSync(resolve(bundle, "version"), version + "\n"); +execFileSync("tar", [ + "-czf", + resolve(output, `abridge-client-browser-${version}-linux.tar.gz`), + "-C", + output, + "abridge-client-browser", +]);