diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index e9ef535..52a9314 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -44,10 +44,13 @@ jobs: 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/ + installer="install-browser-client.sh" + cp -- ".local/release/browser-client/$archive" ".local/release/browser-client/$installer" dist/releases/ cd dist/releases test "$(tar -xOf "$archive" abridge-client-browser/version)" = "$version" + bash -n "$installer" sha256sum -- "$archive" > "$archive.sha256" + sha256sum -- "$installer" > "$installer.sha256" - name: Build portable unsigned macOS candidate if: runner.os == 'macOS' run: npm run package:macos -- --reuse-build @@ -94,6 +97,7 @@ jobs: dist/releases/*.tgz dist/releases/abridge-browser-*.zip dist/releases/abridge-client-browser-*.tar.gz* + dist/releases/install-browser-client.sh* dist/releases/aBridge-*-android.apk if-no-files-found: error retention-days: 14 @@ -184,12 +188,15 @@ jobs: 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") + installer="install-browser-client.sh" + mv -- "$GITHUB_WORKSPACE/release/$browser_archive" "$GITHUB_WORKSPACE/release/$browser_archive.sha256" \ + "$GITHUB_WORKSPACE/release/$installer" "$GITHUB_WORKSPACE/release/$installer.sha256" . + archives+=("$browser_archive" "$installer") + checksums+=("$browser_archive.sha256" "$installer.sha256") sha256sum --check --strict -- "${checksums[@]}" - cp -- "${archives[@]}" "$GITHUB_WORKSPACE/release/" + cp -- "${archives[@]}" "$installer.sha256" "$GITHUB_WORKSPACE/release/" sha256sum -- "${archives[@]}" > "$GITHUB_WORKSPACE/release/SHA256SUMS" + (cd "$GITHUB_WORKSPACE/release" && sha256sum --check --strict SHA256SUMS) - name: Verify Windows release assets working-directory: release shell: bash diff --git a/apps/agent/cmd/abridge-agent/main.go b/apps/agent/cmd/abridge-agent/main.go index 137e77e..c62da04 100644 --- a/apps/agent/cmd/abridge-agent/main.go +++ b/apps/agent/cmd/abridge-agent/main.go @@ -37,6 +37,9 @@ func endpoint(name, value string) string { if err != nil || u.Host == "" || (u.Scheme != "https" && u.Scheme != "http") || u.User != nil || u.Fragment != "" || u.RawQuery != "" { log.Fatalf("%s must be an HTTP(S) service URL", name) } + if u.Scheme == "http" && !strings.EqualFold(u.Hostname(), "localhost") && !net.ParseIP(u.Hostname()).IsLoopback() { + log.Printf("Warning: %s uses unencrypted HTTP. Credentials and requests are sent without TLS.", name) + } return value } diff --git a/apps/agent/cmd/abridge-agent/model_settings_test.go b/apps/agent/cmd/abridge-agent/model_settings_test.go index 1629c5d..33e8fb8 100644 --- a/apps/agent/cmd/abridge-agent/model_settings_test.go +++ b/apps/agent/cmd/abridge-agent/model_settings_test.go @@ -1,6 +1,11 @@ package main -import "testing" +import ( + "bytes" + "log" + "strings" + "testing" +) func TestModelSettingsUsesSystemDeepSeekKeyOnlyForOfficialEndpoint(t *testing.T) { env := map[string]string{"DEEPSEEK_API_KEY": "system-test-value"} @@ -16,3 +21,27 @@ func TestModelSettingsUsesSystemDeepSeekKeyOnlyForOfficialEndpoint(t *testing.T) t.Fatal("custom model endpoint must require its own credentials") } } + +func TestEndpointSupportsHTTPAndWarnsForRemoteCleartext(t *testing.T) { + for _, test := range []struct { + address string + warn bool + }{ + {"http://bridge.example:8765/mcp", true}, + {"http://127.0.0.1:8765/mcp", false}, + {"https://bridge.example/mcp", false}, + } { + t.Run(test.address, func(t *testing.T) { + var stderr bytes.Buffer + previous := log.Writer() + log.SetOutput(&stderr) + t.Cleanup(func() { log.SetOutput(previous) }) + if endpoint("ABRIDGE_MCP_URL", test.address) != test.address { + t.Fatal("endpoint changed the configured address") + } + if strings.Contains(stderr.String(), "unencrypted HTTP") != test.warn { + t.Fatalf("unexpected transport warning: %q", stderr.String()) + } + }) + } +} diff --git a/apps/android/README.md b/apps/android/README.md index dfdc9a7..10d7f42 100644 --- a/apps/android/README.md +++ b/apps/android/README.md @@ -12,7 +12,7 @@ The client reports screen-off and locked states separately. Screen and input cap To unbind, open **设置 → 解除设备绑定** and confirm. The app stops accepting operations and returns to the connection form immediately. When connected, it also requests revocation from the server. If the app cannot confirm revocation, remove the old device in the server console. -Use HTTPS for remote connections. If you enter an HTTP address, the app asks you to confirm it because the key and device traffic will travel without encryption. The confirmation applies to the saved address, and a device bound over HTTPS keeps using HTTPS. +The app accepts HTTP and HTTPS server addresses. When you enter an HTTP address, the app asks you to confirm that the key and device traffic will travel without encryption. The confirmation applies to the saved address, and a device bound over HTTPS keeps using HTTPS. To update the signed app, go to **设置 → 检查更新**. Open the downloaded APK and follow the Android installer. [Android release process](../../docs/releasing.md#android) diff --git a/apps/browser-client/abridge-client-browser b/apps/browser-client/abridge-client-browser index d23b3aa..8a84540 100755 --- a/apps/browser-client/abridge-client-browser +++ b/apps/browser-client/abridge-client-browser @@ -25,6 +25,7 @@ from playwright.sync_api import Error, sync_playwright INSTALLATION = Path(__file__).resolve().parent MAX_MESSAGE = 8192 FAILED = {"status": "failed"} +LOOPBACK_HOSTS = {"localhost", "127.0.0.1", "::1"} class BindingMissing(ValueError): @@ -43,7 +44,7 @@ def valid_origin(origin: str, allow_http: bool = False) -> str: 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"}) + or (url.scheme == "http" and not allow_http and host not in LOOPBACK_HOSTS) ): raise ValueError("invalid server origin") if port == (443 if url.scheme == "https" else 80): @@ -51,6 +52,23 @@ def valid_origin(origin: str, allow_http: bool = False) -> str: return origin +def bind_origin(server: str, *, private_stdin: bool, allow_http: bool) -> str: + """交互绑定先确认远端 HTTP,私有输入使用显式确认参数。""" + origin = valid_origin(server, allow_http=True) + url = urlsplit(origin) + if url.scheme != "http" or url.hostname in LOOPBACK_HOSTS: + return origin + print(f"HTTP 会明文传输设备凭证和操作数据:{origin}", file=sys.stderr) + if not allow_http: + if private_stdin or not sys.stdin.isatty(): + sys.exit("请在交互终端确认,或为此地址显式指定 --allow-http。") + print("继续使用 HTTP?[y/N] ", end="", file=sys.stderr, flush=True) + answer = sys.stdin.readline(32) + if not answer.endswith("\n") or answer.strip().lower() not in {"y", "yes"}: + sys.exit("已取消 HTTP 绑定。") + return origin + + class NoRedirect(urllib.request.HTTPRedirectHandler): """禁止跟随携带凭据的请求重定向。""" @@ -471,7 +489,7 @@ def main() -> None: if bundled_browser.exists(): os.environ["PLAYWRIGHT_BROWSERS_PATH"] = str(bundled_browser) if args.action == "bind": - origin = valid_origin(args.server, args.allow_http) + origin = bind_origin(args.server, private_stdin=args.stdin, allow_http=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: ") diff --git a/apps/browser-client/install-browser-client.sh b/apps/browser-client/install-browser-client.sh new file mode 100755 index 0000000..837bf8e --- /dev/null +++ b/apps/browser-client/install-browser-client.sh @@ -0,0 +1,378 @@ +#!/usr/bin/env bash +# aBridge Linux 浏览器安装器。发布时写入对应的版本和包摘要。 +set -euo pipefail + +usage() { + printf '%s\n' '用法:bash install-browser-client.sh [aBridge HTTP(S) 根地址]' +} + +unit_quote() { + # systemd 路径按字面值传递,保留空格并转义说明符。 + local value=$1 + if [[ $value =~ [[:cntrl:]] ]]; then + printf '%s\n' '服务路径不能包含控制字符。' >&2 + return 1 + fi + value=${value//\\/\\\\} + value=${value//\"/\\\"} + value=${value//%/%%} + printf '"%s"' "$value" +} + +install_service() { + local unit=$1 python=$2 client=$3 + shift 3 + local executable script assignment temporary + executable=$(unit_quote "$python") + script=$(unit_quote "$client") + mkdir -p -- "${unit%/*}" + temporary=$(mktemp -- "${unit%/*}/.abridge-browser.XXXXXX") + ( + trap 'if [[ -f $temporary ]]; then rm -- "$temporary"; fi' EXIT + { + cat <<'EOF' +# Managed by the aBridge browser installer +[Unit] +Description=aBridge Headless Browser + +[Service] +Type=exec +Restart=on-failure +RestartSec=5 +UMask=0077 +EOF + printf 'ExecStart=:%s -I %s run\n' "$executable" "$script" + for assignment in "$@"; do + assignment=$(unit_quote "$assignment") + printf 'Environment=%s\n' "$assignment" + done + printf '\n[Install]\nWantedBy=default.target\n' + } > "$temporary" + mv -fT -- "$temporary" "$unit" + ) +} + +resolve_environment() { + # 重写 unit 时沿用既有服务与用户管理器的环境,避免重跑后 Chromium 路径或 Profile 丢失。 + "$1" -I -c ' +import os +import shlex +import sys + +config = dict(line.split("=", 1) for line in sys.argv[1].splitlines() if "=" in line) +manager = dict(line.split("=", 1) for line in sys.argv[2].splitlines() if "=" in line) +existing = {} +if config.get("FragmentPath") and "Environment" in config: + try: + existing = dict(word.replace("\\$", "$").replace("\\`", "`").split("=", 1) + for word in shlex.split(config["Environment"])) + except ValueError: + existing = {} +for name in ("ABRIDGE_BROWSER_HOME", "PLAYWRIGHT_BROWSERS_PATH", "XDG_CACHE_HOME"): + value = existing.get(name) or manager.get(name) or os.environ.get(name) + if value is None: + continue + if not value.isprintable(): + sys.exit("服务环境包含控制字符,未停止或替换服务。") + print(f"{name}={value}") +' "$2" "$3" +} + +resolve_home() { + # 使用已展开的服务环境锁定 Profile,避免重跑安装器时切换绑定目录。 + "$1" -I -c ' +import os +import pathlib +import pwd +import shlex +import sys + +config = dict(line.split("=", 1) for line in sys.argv[1].splitlines() if "=" in line) +manager = dict(line.split("=", 1) for line in sys.argv[3].splitlines() if "=" in line) +default = pathlib.Path(pwd.getpwuid(os.getuid()).pw_dir) / ".local/state/abridge-client-browser" +target = os.environ.get("ABRIDGE_BROWSER_HOME") +home = pathlib.Path(target or default).resolve() +if config.get("FragmentPath"): + if config.get("LoadState") != "loaded" or "Environment" not in config: + sys.exit("无法核对已有服务的 Profile,未停止或替换服务。") + try: + environment = dict(word.replace("\\$", "$").replace("\\`", "`").split("=", 1) + for word in shlex.split(config["Environment"])) + except ValueError: + sys.exit("无法核对已有服务的 Profile,未停止或替换服务。") + # unit 未定义时服务仍继承用户管理器环境,忽略它会孤立原 Profile。 + existing = pathlib.Path(environment.get("ABRIDGE_BROWSER_HOME") or manager.get("ABRIDGE_BROWSER_HOME") or default) + if not existing.is_absolute(): + sys.exit("已有服务的 Profile 不是绝对路径,未停止或替换服务。") + existing = existing.resolve() + if target is not None and home != existing: + sys.exit("ABRIDGE_BROWSER_HOME 与已有服务的 Profile 不同,未停止或替换服务;请使用原目录重试。") + home = existing +elif pathlib.Path(sys.argv[2]).exists() or config.get("LoadState") != "not-found": + sys.exit("无法核对已有服务的 Profile,未停止或替换服务。") +print(home) +' "$2" "$3" "$4" +} + +validate_binding() { + "$1" -I -c ' +import json +import sys + +binding = json.loads(sys.argv[1]) +if binding.get("revision"): + sys.exit("当前浏览器由平台托管,请使用普通 Linux 账号的独立绑定。") +if binding.get("browser_origin") and binding["browser_origin"] != sys.argv[2]: + sys.exit("当前浏览器已绑定其他 aBridge 地址,请核对地址和运行账号。") +print(binding.get("status", "")) +' "$2" "$3" +} + +validate_runtime() { + # unbound 回执不含平台版本;用同用户 socket 的真实进程确认只停止普通 run。 + "$1" -I -c ' +import os +import pathlib +import socket +import struct +import sys + +with socket.socket(socket.AF_UNIX) as peer: + peer.settimeout(2) + try: + peer.connect(str(pathlib.Path(sys.argv[1]) / "control.sock")) + except (FileNotFoundError, ConnectionRefusedError): + sys.exit(0) + pid, uid, _ = struct.unpack("3i", peer.getsockopt(socket.SOL_SOCKET, socket.SO_PEERCRED, 12)) + if uid != os.getuid(): + sys.exit("浏览器运行账号不匹配,未停止进程。") + process = pathlib.Path("/proc") / str(pid) + command = process.joinpath("cmdline").read_bytes().split(b"\0") + if command[-2] != b"run": + sys.exit("当前浏览器不是普通 run 实例,可能由平台托管;未停止进程。") + for line in process.joinpath("cgroup").read_text().splitlines(): + groups = line.split(":", 2)[2].split("/") + manager = f"user@{uid}.service" + services = [group for group in groups if group.endswith(".service") and group != manager] + if services and (services != ["abridge-browser.service"] or manager not in groups or not pathlib.Path(sys.argv[2]).is_file()): + sys.exit("当前浏览器由自定义服务托管,请先自行停止;未停止进程。") +' "$2" "$3" +} + +wait_profile_released() { + local python=$1 home=$2 + # stop 的 socket 回执先于监督进程退出;等待同一 flock,而不是删除锁文件。 + "$python" -I -c ' +import fcntl +import pathlib +import sys +import time + +with (pathlib.Path(sys.argv[1]) / "profile.lock").open("a") as lock: + deadline = time.monotonic() + 30 + while True: + try: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + break + except BlockingIOError: + if time.monotonic() >= deadline: + sys.exit("浏览器 Profile 仍被占用,未执行绑定或启动;请检查原进程后重试。") + time.sleep(0.1) +' "$home" +} + +stop_browser() { + local python=$1 client=$2 home=$3 unit=$4 + validate_runtime "$python" "$home" "$unit" + if ! "$python" -I "$client" stop; then + printf '%s\n' '无法停止原浏览器,未执行绑定或启动;请检查原进程后重试。' >&2 + return 1 + fi + wait_profile_released "$python" "$home" +} + +main() { + if [[ ${1:-} == --help ]]; then + usage + exit 0 + fi + if (( $# > 1 )); then + usage >&2 + exit 2 + fi + local version='@VERSION@' + local archive_sha256='@ARCHIVE_SHA256@' + if [[ ! $archive_sha256 =~ ^[a-f0-9]{64}$ ]]; then + printf '%s\n' '请从 aBridge 的 GitHub Release 下载生成的安装脚本。' >&2 + exit 2 + fi + # Bash 从下载管道读取脚本,交互输入单独走控制终端。 + if ! { exec 3<> /dev/tty; } 2>/dev/null; then + printf '%s\n' '请在交互终端运行。通过 SSH 执行时请分配终端(ssh -t)。' >&2 + exit 2 + fi + local origin=${1:-} + if [[ -z $origin ]]; then + printf '%s' 'aBridge HTTP(S) 地址:' >&2 + if ! IFS= read -r origin <&3; then + exit 2 + fi + fi + origin=${origin%/} + origin=${origin,,} + if [[ ! $origin =~ ^https?://([a-z0-9.-]+|\[[a-f0-9:]+\])(:[0-9]{1,5})?$ ]]; then + printf '%s\n' '请输入 aBridge 的 HTTP 或 HTTPS 根地址。' >&2 + exit 2 + fi + case "$origin" in + http://*:80) origin=${origin%:80} ;; + https://*:443) origin=${origin%:443} ;; + esac + if (( EUID == 0 )) || [[ $(uname -m) != x86_64 ]] || ! command -v apt-get >/dev/null; then + printf '%s\n' '请在 Ubuntu 或 Debian amd64 上使用可运行 sudo 的普通账号。' >&2 + exit 1 + fi + + local archive="abridge-client-browser-${version}-linux.tar.gz" + local install_base="$HOME/.local/lib" + local install_dir="$install_base/abridge-client-browser-$version" + local python="$install_dir/.venv/bin/python" + local client="$install_dir/abridge-client-browser" + umask 077 + mkdir -p "$install_dir" + exec 9>"$install_base/.abridge-browser-install.lock" + flock 9 + local service=abridge-browser.service + local unit="${XDG_CONFIG_HOME:-$HOME/.config}/systemd/user/$service" + if [[ -e $unit || -L $unit ]]; then + if [[ -L $unit || ! -f $unit || ! -O $unit ]] || + [[ $(head -n 1 -- "$unit") != '# Managed by the aBridge browser installer' ]]; then + printf '已有自定义用户服务 %s,请先处理后再运行安装脚本。\n' "$unit" >&2 + exit 1 + fi + fi + if ! systemctl --user show --property=Version --value >/dev/null; then + printf '%s\n' '无法连接 systemd 用户管理器。请通过 SSH 直接登录普通用户后重试。' >&2 + exit 1 + fi + local manager_env='' + if ! manager_env=$(systemctl --user show-environment 2>/dev/null); then + manager_env='' + fi + local service_config property value + if ! service_config=$(systemctl --user show --all --property=LoadState --property=FragmentPath --property=DropInPaths --property=Environment "$service"); then + if [[ $service_config != *'LoadState=not-found'* ]]; then + printf '%s\n' '无法核对已有用户服务,未停止或替换服务。' >&2 + exit 1 + fi + fi + while IFS='=' read -r property value; do + if [[ $property == FragmentPath && -n $value && ( $value != "$unit" || ! -f $unit ) ]] || + [[ $property == DropInPaths && -n $value ]]; then + printf '%s\n' '已有自定义用户服务或覆盖配置,请先处理后再运行安装脚本。' >&2 + exit 1 + fi + done <<< "$service_config" + + if ! python3 -I -c 'import sys; sys.exit(sys.version_info < (3, 10))' 2>/dev/null; then + printf '%s\n' '需要 3.10 或更高版本的系统 python3,请先安装或升级后重试。' >&2 + exit 1 + fi + if [[ ! -f "$install_dir/.installed" || ! -x "$python" || ! -x "$client" ]]; then + sudo apt-get update + sudo env DEBIAN_FRONTEND=noninteractive apt-get install -y ca-certificates curl python3-venv + ( + download_dir=$(mktemp -d) + trap 'rm -rf -- "$download_dir"' EXIT + cd "$download_dir" + curl --proto '=https' -fLSs -o "$archive" "https://github.com/xerrors/aBridge/releases/download/v$version/$archive" + printf '%s %s\n' "$archive_sha256" "$archive" | sha256sum --check - + tar -xzf "$archive" --strip-components=1 -C "$install_dir" + ) + python3 -m venv "$install_dir/.venv" + "$python" -m pip install -r "$install_dir/requirements.txt" + sudo env DEBIAN_FRONTEND=noninteractive "$python" -m playwright install-deps chromium + "$python" -m playwright install --no-shell chromium + touch "$install_dir/.installed" + fi + + local status state home prior assignments assignment bound=false + home=$(resolve_home "$python" "$service_config" "$unit" "$manager_env") + export ABRIDGE_BROWSER_HOME=$home + if ! assignments=$(resolve_environment "$python" "$service_config" "$manager_env"); then + return 1 + fi + local -a environment=() + while IFS= read -r assignment; do + if [[ -n $assignment ]]; then + environment+=("$assignment") + fi + done <<< "$assignments" + # status 发现撤销会删除 binding.json;先保留地址/平台边界,避免误停托管实例。 + prior=$("$python" -I -c 'import pathlib, sys; p = pathlib.Path(sys.argv[1]) / "binding.json"; print(p.read_text() if p.exists() else "{}")' "$home") + validate_binding "$python" "$prior" "$origin" >/dev/null + validate_runtime "$python" "$home" "$unit" + if ! status=$("$python" -I "$client" status); then + printf '%s\n' '无法读取浏览器绑定状态,未停止或替换服务。' >&2 + return 1 + fi + state=$(validate_binding "$python" "$status" "$origin") + if [[ $state == unbound ]]; then + # systemd 必须先 stop,防止 Restart=on-failure 与新绑定争抢 Profile。 + if [[ -f $unit ]]; then + if ! systemctl --user stop "$service"; then + printf '%s\n' '无法停止安装器托管服务,未执行绑定;请检查服务后重试。' >&2 + return 1 + fi + fi + stop_browser "$python" "$client" "$home" "$unit" + if ! "$python" -I "$client" bind --server "$origin" <&3; then + printf '%s\n' '绑定未完成,安装器未启动服务;请核对地址与 Key 后重试。' >&2 + return 1 + fi + bound=true + fi + + sudo loginctl enable-linger "$EUID" + if [[ $state == running ]] && ! systemctl --user is-active --quiet "$service"; then + stop_browser "$python" "$client" "$home" "$unit" + fi + install_service "$unit" "$python" "$client" "${environment[@]}" + systemctl --user daemon-reload + systemctl --user enable "$service" + systemctl --user restart "$service" + local attempt + for (( attempt=0; attempt<30; attempt++ )); do + if ! status=$("$python" -I "$client" status 2>/dev/null); then + sleep 1 + continue + fi + if ! state=$(validate_binding "$python" "$status" "$origin"); then + return 1 + fi + if [[ $state == unbound && $bound == false ]]; then + # 运行中撤销会删除 binding.json;停服并等待真实锁释放后重新交互绑定。 + if [[ -f $unit ]] && ! systemctl --user stop "$service"; then + printf '%s\n' '无法停止安装器托管服务,未执行绑定;请检查服务后重试。' >&2 + return 1 + fi + wait_profile_released "$python" "$home" + if ! "$python" -I "$client" bind --server "$origin" <&3; then + printf '%s\n' '绑定未完成,安装器未启动服务;请核对地址与 Key 后重试。' >&2 + return 1 + fi + bound=true + systemctl --user restart "$service" + continue + fi + if "$python" -I -c 'import json, sys; sys.exit(not json.loads(sys.argv[1]).get("connected"))' "$status"; then + printf '%s\n' '浏览器已上线,后台服务已启用开机自启。' + return + fi + sleep 1 + done + printf '%s\n' '服务已注册,30 秒内未连上 aBridge。请运行 journalctl --user -u abridge-browser.service 查看日志。' >&2 + return 1 +} + +main "$@" diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 8c2b294..48a6f2f 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -1,5 +1,5 @@ -import { existsSync } from "node:fs"; -import { resolve } from "node:path"; +import { createReadStream, existsSync, statSync } from "node:fs"; +import { dirname, join, resolve } from "node:path"; import Fastify, { type FastifyReply, type FastifyRequest } from "fastify"; import websocket from "@fastify/websocket"; import staticFiles from "@fastify/static"; @@ -782,6 +782,24 @@ export async function createServer(config: ServerConfig) { } addSocket("/ws/device", "computer"); addSocket("/ws/browser", "browser"); + const androidApkPath = join(dirname(config.dbPath), "downloads", "abridge-android.apk"); + app.route({ + method: ["GET", "HEAD"], + url: "/download/abridge-android.apk", + handler: async (request, reply) => { + if (!existsSync(androidApkPath)) + throw new BridgeError("not_found", "Android APK is not published on this server", 404); + reply.header("content-type", "application/vnd.android.package-archive"); + reply.header("content-disposition", 'attachment; filename="abridge-android.apk"'); + reply.header("cache-control", "private, no-store"); + reply.header("x-content-type-options", "nosniff"); + if (request.method === "HEAD") { + reply.header("content-length", statSync(androidApkPath).size); + return reply.send(); + } + return reply.send(createReadStream(androidApkPath)); + }, + }); if (config.staticRoot && existsSync(config.staticRoot)) { await app.register(staticFiles, { root: resolve(config.staticRoot), diff --git a/apps/server/tests/android-download.test.ts b/apps/server/tests/android-download.test.ts new file mode 100644 index 0000000..3f14ac4 --- /dev/null +++ b/apps/server/tests/android-download.test.ts @@ -0,0 +1,40 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { createServer } from "../src/server.js"; + +const url = "/download/abridge-android.apk"; + +test("android apk download serves the published file and 404s without it", async () => { + const dir = await mkdtemp(join(tmpdir(), "abridge-apk-")); + const server = await createServer({ dbPath: join(dir, "server.db"), port: 0 }); + try { + const missing = await server.app.inject({ method: "GET", url }); + assert.equal(missing.statusCode, 404); + const missingHead = await server.app.inject({ method: "HEAD", url }); + assert.equal(missingHead.statusCode, 404); + + await mkdir(join(dir, "downloads"), { recursive: true }); + const payload = Buffer.from("fixture-apk-payload"); + await writeFile(join(dir, "downloads", "abridge-android.apk"), payload); + + const head = await server.app.inject({ method: "HEAD", url }); + assert.equal(head.statusCode, 200); + assert.equal(head.headers["content-type"], "application/vnd.android.package-archive"); + assert.equal(head.headers["content-length"], String(payload.length)); + assert.equal(head.headers["cache-control"], "private, no-store"); + assert.equal(head.body, ""); + + const response = await server.app.inject({ method: "GET", url }); + assert.equal(response.statusCode, 200); + assert.equal(response.headers["content-type"], "application/vnd.android.package-archive"); + assert.equal(response.headers["content-disposition"], 'attachment; filename="abridge-android.apk"'); + assert.equal(response.headers["x-content-type-options"], "nosniff"); + assert.equal(response.rawPayload.toString(), payload.toString()); + } finally { + await server.close(); + await rm(dir, { recursive: true, force: true }); + } +}); diff --git a/apps/web/public/login-bridge-studio.webp b/apps/web/public/login-bridge-studio.webp new file mode 100644 index 0000000..c1e89d2 Binary files /dev/null and b/apps/web/public/login-bridge-studio.webp differ diff --git a/apps/web/src/app/app.tsx b/apps/web/src/app/app.tsx index 0c1e33b..e05f2db 100644 --- a/apps/web/src/app/app.tsx +++ b/apps/web/src/app/app.tsx @@ -1,6 +1,6 @@ import { LayoutDashboard, Monitor, Link2, ListFilter, ShieldCheck } from "lucide-preact"; import { VERSION } from "@abridge/protocol"; -import { useCallback, useEffect, useState } from "preact/hooks"; +import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "preact/hooks"; import { api, objectResultSchema } from "../lib/api.js"; import { Authentication, ExternalLogin } from "../features/auth/page.js"; import { ActionMenu } from "../components/actions.js"; @@ -25,7 +25,7 @@ import { ConnectionCreatePage, ConnectionPage } from "../features/connections/pa const tabs: readonly [Tab, string][] = [ ["overview", "概览"], ["devices", "设备"], - ["connections", "Agent 连接"], + ["connections", "授权 Agent"], ["activity", "操作记录"], ]; function NavIcon({ name }: { name: Tab }) { @@ -74,8 +74,28 @@ function ManagementApp() { const [loginDialog, setLoginDialog] = useState(false); const userReady = phase === "ready" && user !== null; const adminReady = admin.phase === "ready"; + const showConsole = (userReady || adminReady) && admin.phase !== "loading"; const visibleTab = adminReady && (!userReady || tab === "admin") ? "admin" : tab === "admin" ? "overview" : tab; + const navRef = useRef(null); + const [indicator, setIndicator] = useState<{ x: number; y: number; w: number; h: number } | null>(null); + useLayoutEffect(() => { + const nav = navRef.current; + if (!nav) return; + const update = () => { + const active = nav.querySelector('a[aria-current="page"]'); + setIndicator( + active + ? { x: active.offsetLeft, y: active.offsetTop, w: active.offsetWidth, h: active.offsetHeight } + : null, + ); + }; + update(); + const observer = new ResizeObserver(update); + observer.observe(nav); + nav.querySelectorAll("a").forEach((link) => observer.observe(link)); + return () => observer.disconnect(); + }, [visibleTab, userReady, adminReady, showConsole]); const [dialog, setDialog] = useState(null); useEffect(() => { setDialog(null); @@ -108,7 +128,7 @@ function ManagementApp() { const createConnection = () => { location.hash = "connections/new"; }; - if ((!userReady && !adminReady) || admin.phase === "loading") + if (!showConsole) return ( -