From 1381b538015f47f30cf95ea37db401a92dda341b Mon Sep 17 00:00:00 2001 From: Wenjie Zhang Date: Tue, 24 Nov 2026 17:28:22 +0800 Subject: [PATCH 1/7] test(desktop): verify HTTP consent in the packaged Mac client --- apps/desktop/tests/native-client.test.ts | 205 ++++++++++++++++++++--- 1 file changed, 180 insertions(+), 25 deletions(-) diff --git a/apps/desktop/tests/native-client.test.ts b/apps/desktop/tests/native-client.test.ts index 10a88c5..57391f7 100644 --- a/apps/desktop/tests/native-client.test.ts +++ b/apps/desktop/tests/native-client.test.ts @@ -1,20 +1,32 @@ import test from "node:test"; import assert from "node:assert/strict"; +import { createHash } from "node:crypto"; +import { once } from "node:events"; import { createServer } from "node:http"; import { spawn, execFile, type ChildProcess } from "node:child_process"; import { promisify } from "node:util"; import { mkdtemp, mkdir, chmod, writeFile, readFile, readdir, rm } from "node:fs/promises"; -import { hostname, tmpdir } from "node:os"; +import { hostname, networkInterfaces, tmpdir } from "node:os"; import { join, resolve } from "node:path"; +import { createInterface } from "node:readline"; import { setTimeout as delay } from "node:timers/promises"; import { WebSocketServer, type WebSocket } from "ws"; -import { VERSION, deviceDetailsSchema, deviceHelloSchema } from "@abridge/protocol"; +import { + VERSION, + deviceAuthorizationCancelSchema, + deviceAuthorizationRequestSchema, + deviceDetailsSchema, + deviceHelloSchema, +} from "@abridge/protocol"; const exec = promisify(execFile); const binary = resolve( process.env.ABRIDGE_NATIVE_TEST_APP ?? "dist/desktop/aBridge.app", "Contents/MacOS/abridge-desktop", ); const native = process.platform === "darwin" && process.arch === "arm64"; +const deviceKey = "abr_device_fixture"; +const authorizationPath = "/api/device-authorizations"; +const authorizationId = "a".repeat(43); type Frame = Record; async function until( check: () => T | Promise, @@ -29,18 +41,46 @@ async function until( } throw Error(typeof message === "function" ? message() : message); } -async function fixture() { +async function fixture({ host = "127.0.0.1", seedBinding = true } = {}) { const directory = await mkdtemp(join(tmpdir(), "abridge-native-client-")); await chmod(directory, 0o700); let name = "Fixture Mac", responseId = "fixture", reject = false; + const requests: { + method: string | undefined; + path: string | undefined; + authorization: string | undefined; + body: unknown; + }[] = []; const http = createServer(async (request, response) => { - assert.equal(request.headers.authorization, "Bearer abr_device_fixture"); - let body = ""; - for await (const chunk of request) body += chunk; - if (request.method === "PATCH") name = (JSON.parse(body) as { name: string }).name; + let rawBody = ""; + for await (const chunk of request) rawBody += chunk; + const body: unknown = rawBody ? JSON.parse(rawBody) : null; + requests.push({ + method: request.method, + path: request.url, + authorization: request.headers.authorization, + body, + }); response.setHeader("content-type", "application/json"); + if (request.method === "POST" && request.url === authorizationPath) { + response.end( + JSON.stringify({ + id: authorizationId, + authorization_url: authorizationURL, + expires_at: Date.now() / 1000 + 60, + }), + ); + return; + } + if (request.method === "DELETE" && request.url === `${authorizationPath}/${authorizationId}`) { + response.writeHead(204).end(); + return; + } + assert.equal(request.url, "/api/device"); + assert.equal(request.headers.authorization, `Bearer ${deviceKey}`); + if (request.method === "PATCH") name = (body as { name: string }).name; response.end( JSON.stringify( request.method === "PATCH" @@ -49,17 +89,19 @@ async function fixture() { ), ); }); - await new Promise((done) => http.listen(0, "127.0.0.1", done)); + await once(http.listen(0, host), "listening"); const address = http.address(); assert.ok(address && typeof address === "object"); - const url = `http://127.0.0.1:${address.port}`; + const url = `http://${host}:${address.port}`; + const authorizationURL = `${url}/?authorize=${authorizationId}`; const server = new WebSocketServer({ noServer: true }); http.on("upgrade", (request, socket, head) => { if (reject) { socket.end("HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n"); return; } - assert.equal(request.headers.authorization, "Bearer abr_device_fixture"); + assert.equal(request.url, "/ws/device"); + assert.equal(request.headers.authorization, `Bearer ${deviceKey}`); server.handleUpgrade(request, socket, head, (ws) => server.emit("connection", ws)); }); let peer: WebSocket | undefined, @@ -101,21 +143,23 @@ async function fixture() { if (frame.type === "unbind") socket.send(JSON.stringify({ type: "revoke", connection_epoch: epoch })); }); }); - await mkdir(join(directory, "credentials"), { mode: 0o700 }); - await writeFile( - join(directory, "config.json"), - JSON.stringify({ - url, - paused: false, - capabilities: { shell: true, files: true, screen: false, input: false }, - }), - { mode: 0o600 }, - ); - await writeFile( - join(directory, "credentials/device.json"), - JSON.stringify({ server_url: url, device_key: "abr_device_fixture" }), - { mode: 0o600 }, - ); + if (seedBinding) { + await mkdir(join(directory, "credentials"), { mode: 0o700 }); + await writeFile( + join(directory, "config.json"), + JSON.stringify({ + url, + paused: false, + capabilities: { shell: true, files: true, screen: false, input: false }, + }), + { mode: 0o600 }, + ); + await writeFile( + join(directory, "credentials/device.json"), + JSON.stringify({ server_url: url, device_key: deviceKey }), + { mode: 0o600 }, + ); + } async function cli(...args: string[]): Promise { const result = await exec(binary, [...args, "--state-dir", directory], { timeout: 20000 }); return JSON.parse(result.stdout) as Frame; @@ -178,6 +222,7 @@ async function fixture() { return { directory, url, + requests, cli, start, stop, @@ -209,6 +254,35 @@ async function fixture() { }; } +async function authorize(directory: string, input: Frame) { + const child = spawn(binary, ["authorize", "--stdin", "--state-dir", directory], { + env: { ...process.env, ABRIDGE_PARENT_PID: String(process.pid) }, + stdio: "pipe", + }); + const exited = once(child, "close"); + const watchdog = setTimeout(() => child.kill("SIGKILL"), 15000); + const events: Frame[] = []; + let stderr = ""; + child.stderr.on("data", (data) => (stderr += String(data))); + try { + child.stdin.write(JSON.stringify(input) + "\n"); + for await (const line of createInterface({ input: child.stdout })) { + const event = JSON.parse(line) as Frame; + events.push(event); + if (event.event === "authorization") child.stdin.end(); + if (event.event === "ready") + child.stdin.write(JSON.stringify({ command: "commit", capabilities: { files: true } }) + "\n"); + } + const [code, signal] = await exited; + assert.equal(signal, null, `Authorization helper terminated: ${stderr}`); + return { code, events }; + } finally { + clearTimeout(watchdog); + if (child.exitCode === null && child.signalCode === null) child.kill("SIGKILL"); + await exited.catch(() => {}); + } +} + test( "native client: startup loads independently of broken binding and bundles no JS runtime", { skip: !native }, @@ -236,6 +310,87 @@ test( }, ); +test( + "native client: bundled helper authorizes and reconnects over HTTP with exact origin consent", + { skip: !native }, + async () => { + const host = Object.values(networkInterfaces()) + .flat() + .find((entry) => entry?.family === "IPv4" && !entry.internal)?.address; + assert.ok(host, "HTTP consent regression requires a non-loopback IPv4 address on this Mac"); + const f = await fixture({ host, seedBinding: false }); + try { + const mismatched = new URL(f.url); + mismatched.port = mismatched.port === "8080" ? "8081" : "8080"; + for (const device_key of [undefined, deviceKey]) { + for (const http_confirmed_origin of [undefined, mismatched.origin]) { + const { code, events } = await authorize(f.directory, { + url: f.url, + device_key, + http_confirmed_origin, + }); + assert.equal(code, 1); + assert.deepEqual( + events.map((event) => event.event), + ["error"], + ); + assert.match(String(events[0]?.error), /未加密.*HTTP/); + assert.deepEqual(f.requests, [], "Consent must be checked before the helper contacts the server"); + } + } + + const input = { url: f.url, http_confirmed_origin: f.url }; + const browser = await authorize(f.directory, input); + assert.equal(browser.code, 1); + assert.deepEqual( + browser.events.map((event) => event.event), + ["authorization", "error"], + ); + assert.equal(browser.events[0]?.authorization_url, `${f.url}/?authorize=${authorizationId}`); + assert.deepEqual( + f.requests.map(({ method, path }) => [method, path]), + [ + ["POST", authorizationPath], + ["DELETE", `${authorizationPath}/${authorizationId}`], + ], + ); + const request = deviceAuthorizationRequestSchema.parse(f.requests[0]?.body); + const cancellation = deviceAuthorizationCancelSchema.parse(f.requests[1]?.body); + assert.equal(request.kind, "computer"); + assert.equal( + createHash("sha256").update(cancellation.code_verifier).digest("base64url"), + request.code_challenge, + ); + assert.deepEqual(await readdir(f.directory), []); + + const token = await authorize(f.directory, { ...input, device_key: deviceKey }); + assert.equal(token.code, 0); + assert.deepEqual( + token.events.map((event) => event.event), + ["ready", "complete"], + ); + assert.deepEqual(f.requests.slice(2), [ + { method: "GET", path: "/api/device", authorization: `Bearer ${deviceKey}`, body: null }, + ]); + const config = JSON.parse(await readFile(join(f.directory, "config.json"), "utf8")) as Frame; + assert.equal(config.http_confirmed_origin, f.url); + assert.deepEqual(JSON.parse(await readFile(join(f.directory, "credentials/device.json"), "utf8")), { + server_url: f.url, + device_key: deviceKey, + }); + await f.start(); + f.peer.terminate(); + await until( + () => f.frames.filter((frame) => frame.type === "hello").length >= 2, + "Expected HTTP WebSocket reconnect", + ); + await until(async () => (await f.cli("status")).connection === "online"); + } finally { + await f.close(); + } + }, +); + test( "native client: signed runtime speaks protocol, persists no-replay journal and rejects invalid admission", { skip: !native }, From 5619223536c02f432f10f0c9f2ca569c94a4683a Mon Sep 17 00:00:00 2001 From: Wenjie Zhang Date: Tue, 24 Nov 2026 17:34:21 +0800 Subject: [PATCH 2/7] test(desktop): verify HTTP consent for IP and DNS servers on macOS --- .github/workflows/ci.yml | 21 ++- apps/desktop/tests/native-client.test.ts | 178 +++++++++++++---------- 2 files changed, 119 insertions(+), 80 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3ffc93a..551215d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -48,7 +48,26 @@ jobs: run: npm run desktop:compile-check - name: Build and test native desktop if: runner.os == 'macOS' && inputs.full_macos - run: npm run test:desktop + env: + ABRIDGE_NATIVE_TEST_HTTP_ADDRESS: 198.51.100.93 + ABRIDGE_NATIVE_TEST_HTTP_HOSTNAME: abridge-server.example.test + run: | + sudo ifconfig lo0 inet "$ABRIDGE_NATIVE_TEST_HTTP_ADDRESS" netmask 255.255.255.255 alias + printf '%s %s\n' "$ABRIDGE_NATIVE_TEST_HTTP_ADDRESS" "$ABRIDGE_NATIVE_TEST_HTTP_HOSTNAME" | sudo tee -a /etc/hosts > /dev/null + export NO_PROXY="${NO_PROXY:+$NO_PROXY,}localhost,127.0.0.1,$ABRIDGE_NATIVE_TEST_HTTP_ADDRESS,$ABRIDGE_NATIVE_TEST_HTTP_HOSTNAME" + export no_proxy="$NO_PROXY" + npm run test:desktop + - name: Package the tested macOS app + if: matrix.os == 'macos-latest' && inputs.full_macos + run: npm run package:macos -- --reuse-build + - name: Retain macOS test build + if: matrix.os == 'macos-latest' && inputs.full_macos + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: aBridge-macOS-arm64-test + path: dist/releases/aBridge-*-macos-arm64-unsigned.zip + if-no-files-found: error + retention-days: 7 - name: Retain local package candidates if: runner.os == 'Linux' && matrix.node == '22.13.0' uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 diff --git a/apps/desktop/tests/native-client.test.ts b/apps/desktop/tests/native-client.test.ts index 57391f7..f9bc2a0 100644 --- a/apps/desktop/tests/native-client.test.ts +++ b/apps/desktop/tests/native-client.test.ts @@ -1,6 +1,7 @@ import test from "node:test"; import assert from "node:assert/strict"; import { createHash } from "node:crypto"; +import { lookup } from "node:dns/promises"; import { once } from "node:events"; import { createServer } from "node:http"; import { spawn, execFile, type ChildProcess } from "node:child_process"; @@ -41,7 +42,11 @@ async function until( } throw Error(typeof message === "function" ? message() : message); } -async function fixture({ host = "127.0.0.1", seedBinding = true } = {}) { +async function fixture({ + host = "127.0.0.1", + urlHost = host, + seedBinding = true, +}: { host?: string; urlHost?: string; seedBinding?: boolean } = {}) { const directory = await mkdtemp(join(tmpdir(), "abridge-native-client-")); await chmod(directory, 0o700); let name = "Fixture Mac", @@ -92,7 +97,7 @@ async function fixture({ host = "127.0.0.1", seedBinding = true } = {}) { await once(http.listen(0, host), "listening"); const address = http.address(); assert.ok(address && typeof address === "object"); - const url = `http://${host}:${address.port}`; + const url = `http://${urlHost}:${address.port}`; const authorizationURL = `${url}/?authorize=${authorizationId}`; const server = new WebSocketServer({ noServer: true }); http.on("upgrade", (request, socket, head) => { @@ -310,86 +315,101 @@ test( }, ); -test( - "native client: bundled helper authorizes and reconnects over HTTP with exact origin consent", - { skip: !native }, - async () => { - const host = Object.values(networkInterfaces()) - .flat() - .find((entry) => entry?.family === "IPv4" && !entry.internal)?.address; - assert.ok(host, "HTTP consent regression requires a non-loopback IPv4 address on this Mac"); - const f = await fixture({ host, seedBinding: false }); - try { - const mismatched = new URL(f.url); - mismatched.port = mismatched.port === "8080" ? "8081" : "8080"; - for (const device_key of [undefined, deviceKey]) { - for (const http_confirmed_origin of [undefined, mismatched.origin]) { - const { code, events } = await authorize(f.directory, { - url: f.url, - device_key, - http_confirmed_origin, - }); - assert.equal(code, 1); - assert.deepEqual( - events.map((event) => event.event), - ["error"], - ); - assert.match(String(events[0]?.error), /未加密.*HTTP/); - assert.deepEqual(f.requests, [], "Consent must be checked before the helper contacts the server"); +function testHttpConsent(label: string, bindAddress?: string, urlHost?: string) { + test( + `native client: bundled helper authorizes and reconnects over HTTP with exact origin consent (${label})`, + { skip: !native }, + async () => { + const address = + bindAddress ?? + Object.values(networkInterfaces()) + .flat() + .find((entry) => entry?.family === "IPv4" && !entry.internal)?.address; + assert.ok(address, "HTTP consent regression requires a non-loopback IPv4 address on this Mac"); + if (urlHost && urlHost !== address) + assert.deepEqual(await lookup(urlHost, { all: true }), [{ address, family: 4 }]); + const f = await fixture({ host: address, urlHost, seedBinding: false }); + try { + const mismatched = new URL(f.url); + mismatched.port = mismatched.port === "8080" ? "8081" : "8080"; + for (const device_key of [undefined, deviceKey]) { + for (const http_confirmed_origin of [undefined, mismatched.origin]) { + const { code, events } = await authorize(f.directory, { + url: f.url, + device_key, + http_confirmed_origin, + }); + assert.equal(code, 1); + assert.deepEqual( + events.map((event) => event.event), + ["error"], + ); + assert.match(String(events[0]?.error), /未加密.*HTTP/); + assert.deepEqual(f.requests, [], "Consent must be checked before the helper contacts the server"); + } } - } - const input = { url: f.url, http_confirmed_origin: f.url }; - const browser = await authorize(f.directory, input); - assert.equal(browser.code, 1); - assert.deepEqual( - browser.events.map((event) => event.event), - ["authorization", "error"], - ); - assert.equal(browser.events[0]?.authorization_url, `${f.url}/?authorize=${authorizationId}`); - assert.deepEqual( - f.requests.map(({ method, path }) => [method, path]), - [ - ["POST", authorizationPath], - ["DELETE", `${authorizationPath}/${authorizationId}`], - ], - ); - const request = deviceAuthorizationRequestSchema.parse(f.requests[0]?.body); - const cancellation = deviceAuthorizationCancelSchema.parse(f.requests[1]?.body); - assert.equal(request.kind, "computer"); - assert.equal( - createHash("sha256").update(cancellation.code_verifier).digest("base64url"), - request.code_challenge, - ); - assert.deepEqual(await readdir(f.directory), []); + const input = { url: f.url, http_confirmed_origin: f.url }; + const browser = await authorize(f.directory, input); + assert.equal(browser.code, 1); + assert.deepEqual( + browser.events.map((event) => event.event), + ["authorization", "error"], + `HTTP requests received: ${f.requests.length}. Helper events: ${JSON.stringify(browser.events)}`, + ); + assert.equal(browser.events[0]?.authorization_url, `${f.url}/?authorize=${authorizationId}`); + assert.deepEqual( + f.requests.map(({ method, path }) => [method, path]), + [ + ["POST", authorizationPath], + ["DELETE", `${authorizationPath}/${authorizationId}`], + ], + ); + const request = deviceAuthorizationRequestSchema.parse(f.requests[0]?.body); + const cancellation = deviceAuthorizationCancelSchema.parse(f.requests[1]?.body); + assert.equal(request.kind, "computer"); + assert.equal( + createHash("sha256").update(cancellation.code_verifier).digest("base64url"), + request.code_challenge, + ); + assert.deepEqual(await readdir(f.directory), []); - const token = await authorize(f.directory, { ...input, device_key: deviceKey }); - assert.equal(token.code, 0); - assert.deepEqual( - token.events.map((event) => event.event), - ["ready", "complete"], - ); - assert.deepEqual(f.requests.slice(2), [ - { method: "GET", path: "/api/device", authorization: `Bearer ${deviceKey}`, body: null }, - ]); - const config = JSON.parse(await readFile(join(f.directory, "config.json"), "utf8")) as Frame; - assert.equal(config.http_confirmed_origin, f.url); - assert.deepEqual(JSON.parse(await readFile(join(f.directory, "credentials/device.json"), "utf8")), { - server_url: f.url, - device_key: deviceKey, - }); - await f.start(); - f.peer.terminate(); - await until( - () => f.frames.filter((frame) => frame.type === "hello").length >= 2, - "Expected HTTP WebSocket reconnect", - ); - await until(async () => (await f.cli("status")).connection === "online"); - } finally { - await f.close(); - } - }, -); + const token = await authorize(f.directory, { ...input, device_key: deviceKey }); + assert.equal(token.code, 0, JSON.stringify(token.events)); + assert.deepEqual( + token.events.map((event) => event.event), + ["ready", "complete"], + ); + assert.deepEqual(f.requests.slice(2), [ + { method: "GET", path: "/api/device", authorization: `Bearer ${deviceKey}`, body: null }, + ]); + const config = JSON.parse(await readFile(join(f.directory, "config.json"), "utf8")) as Frame; + assert.equal(config.http_confirmed_origin, f.url); + assert.deepEqual(JSON.parse(await readFile(join(f.directory, "credentials/device.json"), "utf8")), { + server_url: f.url, + device_key: deviceKey, + }); + await f.start(); + f.peer.terminate(); + await until( + () => f.frames.filter((frame) => frame.type === "hello").length >= 2, + "Expected HTTP WebSocket reconnect", + ); + await until(async () => (await f.cli("status")).connection === "online"); + } finally { + await f.close(); + } + }, + ); +} + +testHttpConsent("LAN IPv4"); +const testHttpAddress = process.env.ABRIDGE_NATIVE_TEST_HTTP_ADDRESS; +const testHttpHostname = process.env.ABRIDGE_NATIVE_TEST_HTTP_HOSTNAME; +if (testHttpAddress && testHttpHostname) { + testHttpConsent(`TEST-NET IPv4 ${testHttpAddress}`, testHttpAddress); + testHttpConsent(`DNS hostname ${testHttpHostname}`, testHttpAddress, testHttpHostname); +} test( "native client: signed runtime speaks protocol, persists no-replay journal and rejects invalid admission", From f7c08958720d6195839447f4a04be46c604d677f Mon Sep 17 00:00:00 2001 From: Wenjie Zhang Date: Tue, 24 Nov 2026 17:40:02 +0800 Subject: [PATCH 3/7] fix(desktop): support confirmed HTTP servers in the macOS client --- apps/desktop/native/aBridge.swift | 2 +- .../native/runtime/Authorization.swift | 82 +++++++++++------ apps/desktop/native/runtime/Client.swift | 12 +-- .../native/runtime/DeviceServerSession.swift | 21 +++++ apps/desktop/native/runtime/Info.plist | 12 +++ apps/desktop/tests/native-client.test.ts | 91 ++++++++++++++++--- docs/architecture.md | 4 +- tools/build-native.ts | 9 ++ tools/tests/native-admission.test.ts | 1 + tools/tests/native-lifecycle.test.ts | 62 +++++++++++-- 10 files changed, 234 insertions(+), 62 deletions(-) create mode 100644 apps/desktop/native/runtime/DeviceServerSession.swift create mode 100644 apps/desktop/native/runtime/Info.plist diff --git a/apps/desktop/native/aBridge.swift b/apps/desktop/native/aBridge.swift index cd49560..1ae90c1 100644 --- a/apps/desktop/native/aBridge.swift +++ b/apps/desktop/native/aBridge.swift @@ -834,7 +834,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, NSMe authorizationServer = address authorizationURL = nil authorizationCommitting = false - authorizationLabel.stringValue = tokenMode ? "正在验证设备 Token…" : "正在打开浏览器授权…" + authorizationLabel.stringValue = tokenMode ? "正在验证设备 Token…" : "正在获取授权链接…" authorizationLabel.isHidden = false do { try process.run() diff --git a/apps/desktop/native/runtime/Authorization.swift b/apps/desktop/native/runtime/Authorization.swift index d9bcf61..c715eb4 100644 --- a/apps/desktop/native/runtime/Authorization.swift +++ b/apps/desktop/native/runtime/Authorization.swift @@ -3,10 +3,6 @@ import CryptoKit import Security import Darwin -private final class AuthorizationHTTPDelegate: NSObject, URLSessionTaskDelegate, @unchecked Sendable { - func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping @Sendable (URLRequest?) -> Void) { completionHandler(nil) } -} - private actor AuthorizationInput { private var lines: [JSONObject] = [] private var failure: Error? @@ -67,7 +63,13 @@ private struct AuthorizationCallback: Sendable { var length = socklen_t(MemoryLayout.size) guard withUnsafeMutablePointer(to: &address, { $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { getsockname(fd, $0, &length) } }) == 0 else { throw posixFailure("Read authorization listener") } return AuthorizationCallback(fd: fd, redirect: "http://127.0.0.1:\(UInt16(bigEndian: address.sin_port))/abridge/callback") - } catch { if fd >= 0 { Darwin.close(fd) }; throw error } + } catch { + if fd >= 0 { Darwin.close(fd) } + let failure = error as NSError + guard failure.domain == NSPOSIXErrorDomain else { throw error } + let reason = String(cString: strerror(Int32(failure.code))) + throw DesktopError(code: "authorization_failed", message: "无法开启本机授权回调(\(reason)),请重试") + } } func receive(state: String, expires: Double) async throws -> String { guard let expected = URLComponents(string: redirect), let expectedHost = expected.host, let expectedPort = expected.port else { throw DesktopError(code: "authorization_failed", message: "授权回调地址无效") } @@ -129,37 +131,52 @@ private func randomAuthorizationValue() throws -> String { } enum NativeAuthorization { - private static func fetch(_ url: String, method: String = "GET", body: JSONObject? = nil, key: String? = nil, timeout: Double = 10) async throws -> JSONObject { + private static func fetch(_ url: String, stage: String, method: String = "GET", body: JSONObject? = nil, key: String? = nil, timeout: Double = 10) async throws -> JSONObject { guard let url = URL(string: url) else { throw DesktopError(code: "invalid_url", message: "Server 地址无效") } var request = URLRequest(url: url, timeoutInterval: timeout) request.httpMethod = method request.setValue("application/json", forHTTPHeaderField: "Accept") if let key { request.setValue("Bearer \(key)", forHTTPHeaderField: "Authorization") } if let body { request.httpBody = try body.encoded(); request.setValue("application/json", forHTTPHeaderField: "Content-Type") } - let configuration = URLSessionConfiguration.ephemeral - configuration.httpShouldSetCookies = false - configuration.timeoutIntervalForRequest = timeout - configuration.timeoutIntervalForResource = timeout - let session = URLSession(configuration: configuration, delegate: AuthorizationHTTPDelegate(), delegateQueue: nil) + let session = deviceServerSession(timeout: timeout) defer { session.invalidateAndCancel() } - let (bytes, response) = try await session.bytes(for: request) - guard let response = response as? HTTPURLResponse else { throw DesktopError(code: "authorization_failed", message: "Server 返回无效响应") } - guard (200..<300).contains(response.statusCode) else { - throw DesktopError(code: "authorization_failed", message: response.statusCode == 401 ? "Device Key 无效或已撤销" : "Server 拒绝了设备授权请求(\(response.statusCode))") - } - var data = Data() - for try await byte in bytes { - guard data.count < 65536 else { throw DesktopError(code: "authorization_failed", message: "Server 响应过大") } - data.append(byte) + do { + let (bytes, response) = try await session.bytes(for: request) + guard let response = response as? HTTPURLResponse else { throw DesktopError(code: "authorization_failed", message: "Server 返回无效响应") } + guard (200..<300).contains(response.statusCode) else { + let reason = response.statusCode == 401 && key != nil ? "设备凭证无效或已撤销" : "Server 拒绝了请求" + throw DesktopError(code: "authorization_failed", message: "\(stage)失败。\(reason)(HTTP \(response.statusCode))") + } + var data = Data() + for try await byte in bytes { + guard data.count < 65536 else { throw DesktopError(code: "authorization_failed", message: "Server 响应过大") } + data.append(byte) + } + if method == "DELETE", data.isEmpty { return [:] } + guard let object = (try? JSONValue.decode(data))?.object else { + throw DesktopError(code: "authorization_failed", message: "\(stage)失败。Server 返回了无效的 JSON 响应,请检查 Server 地址和版本") + } + return object + } catch let error as URLError { + let message: String + switch error.code { + case .cancelled: throw CancellationError() + case .cannotConnectToHost: message = "无法连接 Server,请检查地址、端口及 Server 是否运行" + case .cannotFindHost, .dnsLookupFailed: message = "无法解析 Server 域名,请检查地址和 DNS 设置" + case .timedOut: message = "连接 Server 超时,请检查网络后重试" + case .appTransportSecurityRequiresSecureConnection: message = "macOS 的传输安全策略拒绝了连接(-1022)" + case .secureConnectionFailed, .serverCertificateHasBadDate, .serverCertificateUntrusted, + .serverCertificateHasUnknownRoot, .serverCertificateNotYetValid: + message = "无法建立 Server 的 HTTPS 连接,请检查证书和 TLS 配置" + default: message = "与 Server 通信失败(网络错误 \(error.code.rawValue)),请检查网络后重试" + } + throw DesktopError(code: "authorization_failed", message: "\(stage)失败。\(message)") } - if method == "DELETE", data.isEmpty { return [:] } - guard let object = try JSONValue.decode(data).object else { throw DesktopError(code: "authorization_failed", message: "Server 返回无效响应") } - return object } static func verifyToken(server: String, key: String, confirmedHttpOrigin: String? = nil) async throws -> JSONObject { let normalized = try normalizeServerURL(server, confirmedHttpOrigin: confirmedHttpOrigin) guard key.hasPrefix("abr_device_"), key.utf8.count <= 4096 else { throw DesktopError(code: "invalid_arguments", message: "请输入 Device Key") } - let value = try await fetch(normalized + "/api/device", key: key) + let value = try await fetch(normalized + "/api/device", stage: "验证设备凭证", key: key) let identity = try NativeContract.load().validate("deviceIdentity", value) guard identity.string("kind") == "computer" else { throw DesktopError(code: "authorization_failed", message: "此 Device Key 不属于电脑客户端") } return identity @@ -171,7 +188,7 @@ enum NativeAuthorization { defer { Darwin.close(callback.fd) } let challenge = base64URL(Data(SHA256.hash(data: Data(verifier.utf8)))) let name = String((Host.current().localizedName ?? ProcessInfo.processInfo.hostName).trimmingCharacters(in: .whitespacesAndNewlines).prefix(80)) - let start = try contract.validate("deviceAuthorizationStart", await fetch(server + "/api/device-authorizations", method: "POST", body: ["kind": .string("computer"), "name": .string(name.isEmpty ? "Computer" : name), "capabilities": .array(["screen", "input", "shell", "files"].map(JSONValue.string)), "redirect_uri": .string(callback.redirect), "code_challenge": .string(challenge), "code_challenge_method": .string("S256"), "state": .string(state)])) + let start = try contract.validate("deviceAuthorizationStart", await fetch(server + "/api/device-authorizations", stage: "发起浏览器授权", method: "POST", body: ["kind": .string("computer"), "name": .string(name.isEmpty ? "Computer" : name), "capabilities": .array(["screen", "input", "shell", "files"].map(JSONValue.string)), "redirect_uri": .string(callback.redirect), "code_challenge": .string(challenge), "code_challenge_method": .string("S256"), "state": .string(state)])) guard let id = start.string("id") else { throw DesktopError(code: "authorization_failed", message: "Server 返回无效授权") } do { guard let authorization = start.string("authorization_url"), let url = URL(string: authorization), let selected = URL(string: server), serverOrigin(url) == serverOrigin(selected), url.user == nil, url.password == nil, url.fragment == nil, @@ -180,13 +197,13 @@ enum NativeAuthorization { let deadline = min(expires, epochSeconds() + 300) let code = try await callback.receive(state: state, expires: deadline) guard epochSeconds() < deadline else { throw DesktopError(code: "authorization_expired", message: "授权已过期,请重新发起") } - let token = try contract.validate("deviceAuthorizationToken", await fetch(server + "/api/device-authorizations/token", method: "POST", body: ["code": .string(code), "code_verifier": .string(verifier), "redirect_uri": .string(callback.redirect)], timeout: min(10, max(0.1, deadline - epochSeconds())))) + let token = try contract.validate("deviceAuthorizationToken", await fetch(server + "/api/device-authorizations/token", stage: "兑换设备凭证", method: "POST", body: ["code": .string(code), "code_verifier": .string(verifier), "redirect_uri": .string(callback.redirect)], timeout: min(10, max(0.1, deadline - epochSeconds())))) guard token.string("kind") == "computer", let key = token.string("key"), let capabilities = token.array("capabilities"), capabilities.allSatisfy({ ["screen", "input", "shell", "files"].contains($0.string ?? "") }) else { throw DesktopError(code: "authorization_failed", message: "Server 返回的设备类型无效") } guard epochSeconds() < deadline else { throw DesktopError(code: "authorization_expired", message: "授权已过期,请重新发起") } return key } catch { // A detached bounded cancellation also runs when the command task was cancelled. - let cleanup = Task.detached { _ = try? await fetch(server + "/api/device-authorizations/\(id)", method: "DELETE", body: ["code_verifier": .string(verifier)], timeout: 1) } + let cleanup = Task.detached { _ = try? await fetch(server + "/api/device-authorizations/\(id)", stage: "取消浏览器授权", method: "DELETE", body: ["code_verifier": .string(verifier)], timeout: 1) } await cleanup.value throw error } @@ -214,7 +231,16 @@ enum NativeAuthorization { emitJSON(["event": .string("complete"), "ok": .bool(true), "url": .string(url)]) return 0 } catch { - emitJSON(["event": .string("error"), "error": .string(Task.isCancelled ? "授权已取消或过期,请重新发起" : (error as? DesktopError)?.message ?? "设备授权失败")]) + let message: String + if Task.isCancelled || error is CancellationError { + message = "授权已取消或过期,请重新发起" + } else if let failure = error as? DesktopError { + message = failure.message + } else { + let failure = error as NSError + message = "设备授权失败(\(failure.domain) \(failure.code))" + } + emitJSON(["event": .string("error"), "error": .string(message)]) return 1 } } diff --git a/apps/desktop/native/runtime/Client.swift b/apps/desktop/native/runtime/Client.swift index 0fd4182..af22bba 100644 --- a/apps/desktop/native/runtime/Client.swift +++ b/apps/desktop/native/runtime/Client.swift @@ -31,11 +31,6 @@ private func systemDetails() -> JSONObject { } } -/// Credentials never follow HTTP or WebSocket redirects to another endpoint. -final class DeviceNetworkDelegate: NSObject, URLSessionTaskDelegate, @unchecked Sendable { - func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping @Sendable (URLRequest?) -> Void) { completionHandler(nil) } -} - actor DeviceClient { private enum CancellationSource { case caller, stop } private struct Admission { @@ -134,9 +129,7 @@ actor DeviceClient { components.path += "/ws/device" var request = URLRequest(url: components.url!); request.timeoutInterval = 10 request.setValue("Bearer \(key)", forHTTPHeaderField: "Authorization") - let sessionConfig = URLSessionConfiguration.ephemeral - sessionConfig.httpShouldSetCookies = false; sessionConfig.urlCredentialStorage = nil - let session = URLSession(configuration: sessionConfig, delegate: DeviceNetworkDelegate(), delegateQueue: nil) + let session = deviceServerSession() let ws = session.webSocketTask(with: request) ws.maximumMessageSize = Int(contract.limit("messageBytes")) let identity = UUID(); connection = identity; socket = ws; status = "connecting" @@ -349,8 +342,7 @@ actor DeviceClient { guard status == "online", !key.isEmpty, !deviceId.isEmpty, config.revoked != true else { throw DesktopError(code: "device_offline", message: "请连接 Server 后再修改设备名称") } var request = URLRequest(url: URL(string: config.url + "/api/device")!); request.httpMethod = "PATCH"; request.timeoutInterval = 10 request.setValue("Bearer \(key)", forHTTPHeaderField: "Authorization"); request.setValue("application/json", forHTTPHeaderField: "Content-Type"); request.httpBody = try body.encoded() - let configuration = URLSessionConfiguration.ephemeral; configuration.httpShouldSetCookies = false; configuration.urlCredentialStorage = nil - let session = URLSession(configuration: configuration, delegate: DeviceNetworkDelegate(), delegateQueue: nil); defer { session.invalidateAndCancel() } + let session = deviceServerSession(); defer { session.invalidateAndCancel() } let (stream, response) = try await session.bytes(for: request) var bytes = Data() for try await byte in stream { guard bytes.count < 65536 else { throw DesktopError(code: "invalid_response", message: "Server response exceeds limit") }; bytes.append(byte) } diff --git a/apps/desktop/native/runtime/DeviceServerSession.swift b/apps/desktop/native/runtime/DeviceServerSession.swift new file mode 100644 index 0000000..b2613e3 --- /dev/null +++ b/apps/desktop/native/runtime/DeviceServerSession.swift @@ -0,0 +1,21 @@ +import Foundation +import Security + +/// 设备授权请求、改名和 WebSocket 都只连接已选 Server,不随重定向传递凭据。 +private final class DeviceNetworkDelegate: NSObject, URLSessionTaskDelegate, @unchecked Sendable { + func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping @Sendable (URLRequest?) -> Void) { + completionHandler(nil) + } +} + +func deviceServerSession(timeout: TimeInterval? = nil) -> URLSession { + let configuration = URLSessionConfiguration.ephemeral + configuration.urlCredentialStorage = nil + configuration.httpShouldSetCookies = false + configuration.tlsMinimumSupportedProtocolVersion = .TLSv12 + if let timeout { + configuration.timeoutIntervalForRequest = timeout + configuration.timeoutIntervalForResource = timeout + } + return URLSession(configuration: configuration, delegate: DeviceNetworkDelegate(), delegateQueue: nil) +} diff --git a/apps/desktop/native/runtime/Info.plist b/apps/desktop/native/runtime/Info.plist new file mode 100644 index 0000000..1873505 --- /dev/null +++ b/apps/desktop/native/runtime/Info.plist @@ -0,0 +1,12 @@ + + + + + NSAppTransportSecurity + + + NSAllowsArbitraryLoads + + + + diff --git a/apps/desktop/tests/native-client.test.ts b/apps/desktop/tests/native-client.test.ts index f9bc2a0..c685c9b 100644 --- a/apps/desktop/tests/native-client.test.ts +++ b/apps/desktop/tests/native-client.test.ts @@ -8,14 +8,16 @@ import { spawn, execFile, type ChildProcess } from "node:child_process"; import { promisify } from "node:util"; import { mkdtemp, mkdir, chmod, writeFile, readFile, readdir, rm } from "node:fs/promises"; import { hostname, networkInterfaces, tmpdir } from "node:os"; -import { join, resolve } from "node:path"; +import { dirname, join, resolve } from "node:path"; import { createInterface } from "node:readline"; import { setTimeout as delay } from "node:timers/promises"; import { WebSocketServer, type WebSocket } from "ws"; import { + DESKTOP_AUTH_CALLBACK_PATH, VERSION, deviceAuthorizationCancelSchema, deviceAuthorizationRequestSchema, + deviceAuthorizationTokenRequestSchema, deviceDetailsSchema, deviceHelloSchema, } from "@abridge/protocol"; @@ -26,8 +28,10 @@ const binary = resolve( ); const native = process.platform === "darwin" && process.arch === "arm64"; const deviceKey = "abr_device_fixture"; +const browserDeviceKey = "abr_device_browser_fixture"; const authorizationPath = "/api/device-authorizations"; const authorizationId = "a".repeat(43); +const authorizationCode = "c".repeat(43); type Frame = Record; async function until( check: () => T | Promise, @@ -51,7 +55,8 @@ async function fixture({ await chmod(directory, 0o700); let name = "Fixture Mac", responseId = "fixture", - reject = false; + reject = false, + socketKey = deviceKey; const requests: { method: string | undefined; path: string | undefined; @@ -83,6 +88,19 @@ async function fixture({ response.writeHead(204).end(); return; } + if (request.method === "POST" && request.url === `${authorizationPath}/token`) { + socketKey = browserDeviceKey; + response.end( + JSON.stringify({ + device_id: responseId, + key: browserDeviceKey, + name, + kind: "computer", + capabilities: ["files"], + }), + ); + return; + } assert.equal(request.url, "/api/device"); assert.equal(request.headers.authorization, `Bearer ${deviceKey}`); if (request.method === "PATCH") name = (body as { name: string }).name; @@ -106,7 +124,7 @@ async function fixture({ return; } assert.equal(request.url, "/ws/device"); - assert.equal(request.headers.authorization, `Bearer ${deviceKey}`); + assert.equal(request.headers.authorization, `Bearer ${socketKey}`); server.handleUpgrade(request, socket, head, (ws) => server.emit("connection", ws)); }); let peer: WebSocket | undefined, @@ -259,8 +277,9 @@ async function fixture({ }; } -async function authorize(directory: string, input: Frame) { - const child = spawn(binary, ["authorize", "--stdin", "--state-dir", directory], { +async function authorize(directory: string, input: Frame, approveInBrowser?: () => Promise) { + const child = spawn(binary, ["--state-dir", directory, "authorize", "--stdin"], { + cwd: dirname(binary), env: { ...process.env, ABRIDGE_PARENT_PID: String(process.pid) }, stdio: "pipe", }); @@ -274,7 +293,10 @@ async function authorize(directory: string, input: Frame) { for await (const line of createInterface({ input: child.stdout })) { const event = JSON.parse(line) as Frame; events.push(event); - if (event.event === "authorization") child.stdin.end(); + if (event.event === "authorization") { + if (approveInBrowser) await approveInBrowser(); + else child.stdin.end(); + } if (event.event === "ready") child.stdin.write(JSON.stringify({ command: "commit", capabilities: { files: true } }) + "\n"); } @@ -374,13 +396,61 @@ function testHttpConsent(label: string, bindAddress?: string, urlHost?: string) ); assert.deepEqual(await readdir(f.directory), []); + const approvalOffset = f.requests.length; + const approval = await authorize(f.directory, input, async () => { + const start = deviceAuthorizationRequestSchema.parse(f.requests[approvalOffset]?.body); + const callback = new URL(start.redirect_uri); + assert.equal(callback.protocol, "http:"); + assert.equal(callback.hostname, "127.0.0.1"); + assert.equal(callback.pathname, DESKTOP_AUTH_CALLBACK_PATH); + callback.searchParams.set("state", start.state); + callback.searchParams.set("code", authorizationCode); + const response = await fetch(callback, { redirect: "error", signal: AbortSignal.timeout(5000) }); + assert.equal(response.status, 200); + await response.text(); + }); + assert.equal(approval.code, 0, JSON.stringify(approval.events)); + assert.deepEqual( + approval.events.map((event) => event.event), + ["authorization", "ready", "complete"], + ); + const approvalRequests = f.requests.slice(approvalOffset); + assert.deepEqual( + approvalRequests.map(({ method, path }) => [method, path]), + [ + ["POST", authorizationPath], + ["POST", `${authorizationPath}/token`], + ], + ); + const start = deviceAuthorizationRequestSchema.parse(approvalRequests[0]?.body); + const exchange = deviceAuthorizationTokenRequestSchema.parse(approvalRequests[1]?.body); + assert.equal(exchange.code, authorizationCode); + assert.equal(exchange.redirect_uri, start.redirect_uri); + assert.equal( + createHash("sha256").update(exchange.code_verifier).digest("base64url"), + start.code_challenge, + ); + assert.deepEqual(JSON.parse(await readFile(join(f.directory, "credentials/device.json"), "utf8")), { + server_url: f.url, + device_key: browserDeviceKey, + }); + await f.start(); + f.peer.terminate(); + await until( + () => f.frames.filter((frame) => frame.type === "hello").length >= 2, + "Expected HTTP WebSocket reconnect", + ); + await until(async () => (await f.cli("status")).connection === "online"); + await f.stop(); + + const tokenOffset = f.requests.length; const token = await authorize(f.directory, { ...input, device_key: deviceKey }); assert.equal(token.code, 0, JSON.stringify(token.events)); assert.deepEqual( token.events.map((event) => event.event), ["ready", "complete"], ); - assert.deepEqual(f.requests.slice(2), [ + assert.deepEqual(f.requests.slice(tokenOffset), [ { method: "GET", path: "/api/device", authorization: `Bearer ${deviceKey}`, body: null }, ]); const config = JSON.parse(await readFile(join(f.directory, "config.json"), "utf8")) as Frame; @@ -389,13 +459,6 @@ function testHttpConsent(label: string, bindAddress?: string, urlHost?: string) server_url: f.url, device_key: deviceKey, }); - await f.start(); - f.peer.terminate(); - await until( - () => f.frames.filter((frame) => frame.type === "hello").length >= 2, - "Expected HTTP WebSocket reconnect", - ); - await until(async () => (await f.cli("status")).connection === "online"); } finally { await f.close(); } diff --git a/docs/architecture.md b/docs/architecture.md index d28ffac..9d41654 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -230,4 +230,6 @@ macOS App 包含 AppKit 主程序、Swift 设备客户端、更新器、共享 设备凭据的手动签发与浏览器 PKCE 授权共享同一设备身份。`GET /api/device` 是设备凭据验证入口,电脑/浏览器客户端在绑定提交前校验设备类型;管理员 Token 和 Agent Key 不作为设备凭据。macOS 继续使用先验证、再停止旧运行时、最后提交的私有双阶段管道;扩展在验证期间保持旧绑定,提交前显式退役旧连接,避免迟到的撤销/关闭消息改变新绑定。 -公网 HTTP 由用户显式确认具体 Origin;共享协议包负责地址规范化和确认匹配。确认写入成功绑定的本机配置,连接恢复时再次校验,浏览器 PKCE 状态与回调校验保持不变。HTTP 风险确认不代替 Server Host/Origin 访问校验,OIDC 的公网 HTTP 另由部署管理员通过 `--allow-insecure-http` / `ABRIDGE_ALLOW_INSECURE_HTTP=true` 显式开启;默认 HTTPS 策略和身份校验保持不变。 +公网 HTTP 由用户显式确认具体 Origin;共享协议包负责地址规范化和确认匹配。确认写入成功绑定的本机配置,连接恢复时再次校验,浏览器 PKCE 状态与回调校验保持不变。HTTP 风险确认不代替 Server Host/Origin 访问校验,OIDC 的公网 HTTP 另由部署管理员通过 `--allow-insecure-http` / `ABRIDGE_ALLOW_INSECURE_HTTP=true` 显式开启。 + +macOS 的设备进程使用系统 URLSession 连接用户指定的 Server。在此进程中允许明文传输,HTTP 和 WS 受上述 Origin 确认约束。HTTPS 和 WSS 要求 TLS 1.2 或更高版本,并使用系统证书和主机名校验。此配置会放宽设备进程的 ATS 附加限制,例如前向保密要求。更新器在独立进程中使用系统默认的 ATS 策略。 diff --git a/tools/build-native.ts b/tools/build-native.ts index 520492e..d9c1bf4 100644 --- a/tools/build-native.ts +++ b/tools/build-native.ts @@ -108,6 +108,7 @@ export async function nativeBuildInputs( .sort(); const files = [ "apps/desktop/native/aBridge.swift", + "apps/desktop/native/runtime/Info.plist", ...nativeSources.map((name) => "apps/desktop/native/runtime/" + name), "dist/desktop/desktop-contract.json", "docs/third-party-notices.md", @@ -215,6 +216,14 @@ export async function buildNative( frameworks, "-lcua_driver_sdk", "-Xlinker", + "-sectcreate", + "-Xlinker", + "__TEXT", + "-Xlinker", + "__info_plist", + "-Xlinker", + join(root, "apps/desktop/native/runtime/Info.plist"), + "-Xlinker", "-rpath", "-Xlinker", "@executable_path/../Frameworks", diff --git a/tools/tests/native-admission.test.ts b/tools/tests/native-admission.test.ts index 4f8bc4a..69a0ef4 100644 --- a/tools/tests/native-admission.test.ts +++ b/tools/tests/native-admission.test.ts @@ -51,6 +51,7 @@ test( "NativeDriver", "Computer", "Executor", + "DeviceServerSession", "Client", ].map((name) => join(runtime, name + ".swift")), join(root, "tools/fixtures/native-admission.swift"), diff --git a/tools/tests/native-lifecycle.test.ts b/tools/tests/native-lifecycle.test.ts index a6e903b..057325d 100644 --- a/tools/tests/native-lifecycle.test.ts +++ b/tools/tests/native-lifecycle.test.ts @@ -28,8 +28,8 @@ test( "-swift-version", "6", "-parse-as-library", - ...["JSON", "Contract", "Storage", "LocalControl", "Authorization"].map((name) => - join(root, `apps/desktop/native/runtime/${name}.swift`), + ...["JSON", "Contract", "Storage", "LocalControl", "DeviceServerSession", "Authorization"].map( + (name) => join(root, `apps/desktop/native/runtime/${name}.swift`), ), join(root, "tools/fixtures/native-lifecycle.swift"), "-lsqlite3", @@ -51,6 +51,10 @@ test( "invalid-token", "wrong-kind", "redirect", + "connection-refused", + "server-refused", + "malformed-token", + "token-timeout", ] as const) { await t.test(scenario, async () => { const directory = await mkdtemp(join(work, "state-")); @@ -90,12 +94,17 @@ test( ); } else if (incoming.url === "/api/device-authorizations" && incoming.method === "POST") { request = body; + if (scenario === "server-refused") { + response.writeHead(401).end("{}"); + return; + } response.end( JSON.stringify({ id: "a".repeat(43), authorization_url: scenario === "cross-origin" ? "https://other.invalid/authorize" : origin + "/authorize", - expires_at: Date.now() / 1000 + (scenario === "expired" ? -1 : 60), + expires_at: + Date.now() / 1000 + (scenario === "expired" ? -1 : scenario === "token-timeout" ? 5 : 60), }), ); } else if (incoming.url === "/api/device-authorizations/token") { @@ -105,6 +114,14 @@ test( request.code_challenge, ); assert.equal(body.redirect_uri, request.redirect_uri); + if (scenario === "malformed-token") { + response.end('{"key":"abr_device_fixture_secret"'); + return; + } + if (scenario === "token-timeout") { + response.flushHeaders(); + return; + } response.end( JSON.stringify({ device_id: "fixture-device", @@ -123,6 +140,8 @@ test( const address = server.address(); assert.ok(address && typeof address !== "string"); const origin = `http://127.0.0.1:${address.port}`; + if (scenario === "connection-refused") + await new Promise((resolve) => server.close(() => resolve())); const manual = ["manual", "invalid-token", "wrong-kind", "redirect"].includes(scenario); const child = spawn(executable, ["authorize", directory], { stdio: ["pipe", "pipe", "pipe"], @@ -134,6 +153,7 @@ test( const exited = once(child, "exit"); const output: string[] = []; let completed = false; + let authorizationError: unknown; let stderr = ""; child.stderr.on("data", (chunk: Buffer) => { stderr += chunk.toString(); @@ -165,9 +185,16 @@ test( 200, ); else { - assert.equal(scenario, "pkce"); - assert.equal((await callback({ state: "wrong-state", code: "c".repeat(43) })).status, 400); - assert.equal(exchange, undefined); + assert.ok( + scenario === "pkce" || scenario === "malformed-token" || scenario === "token-timeout", + ); + if (scenario === "pkce") { + assert.equal( + (await callback({ state: "wrong-state", code: "c".repeat(43) })).status, + 400, + ); + assert.equal(exchange, undefined); + } assert.equal( (await callback({ state: String(request.state), code: "c".repeat(43) })).status, 200, @@ -185,13 +212,32 @@ test( } else if (event.event === "complete") { completed = true; child.stdin.end(); - } else assert.equal(event.event, "error"); + } else { + assert.equal(event.event, "error"); + authorizationError = event.error; + } } const success = scenario === "pkce" || scenario === "manual"; assert.equal((await exited)[0], success ? 0 : 1, stderr); assert.equal(completed, success); assert.ok(!output.join("").includes("abr_device_new")); if (exchange) assert.ok(!output.join("").includes(String(exchange.code_verifier))); + if (scenario === "connection-refused") { + assert.match(String(authorizationError), /^发起浏览器授权失败。无法连接 Server/); + } else if (scenario === "server-refused") { + assert.match(String(authorizationError), /^发起浏览器授权失败。Server 拒绝了请求(HTTP 401)$/); + assert.equal(cancellations, 0); + } else if (scenario === "invalid-token") { + assert.match( + String(authorizationError), + /^验证设备凭证失败。设备凭证无效或已撤销(HTTP 401)$/, + ); + } else if (scenario === "malformed-token") { + assert.match(String(authorizationError), /^兑换设备凭证失败。Server 返回了无效的 JSON 响应/); + assert.ok(!output.join("").includes("abr_device_fixture_secret")); + } else if (scenario === "token-timeout") { + assert.match(String(authorizationError), /^兑换设备凭证失败。连接 Server 超时/); + } const config = JSON.parse( await readFile(join(directory, "config.json"), "utf8"), ) as typeof previous; @@ -205,7 +251,7 @@ test( assert.deepEqual(config, previous); assert.deepEqual(credential, oldCredential); } - if (!manual && scenario !== "parent") { + if (!manual && !["parent", "connection-refused", "server-refused"].includes(scenario)) { assert.equal(cancellations, success ? 0 : 1); await assert.rejects(fetch(String(request.redirect_uri))); } From e3dd5deb351d8d9ed952b98a9d6c6a6f9113dbbc Mon Sep 17 00:00:00 2001 From: Wenjie Zhang Date: Tue, 24 Nov 2026 18:07:44 +0800 Subject: [PATCH 4/7] fix(desktop): explain macOS binding and connection failures --- apps/desktop/native/aBridge.swift | 185 ++++++++++++------ apps/desktop/native/main.swift | 8 + .../native/runtime/Authorization.swift | 119 +++++++---- apps/desktop/native/runtime/Client.swift | 136 ++++++++++--- apps/desktop/native/runtime/Contract.swift | 4 +- .../native/runtime/DeviceServerSession.swift | 54 +++++ .../desktop/native/runtime/LocalControl.swift | 5 +- apps/desktop/tests/native-appkit-errors.swift | 123 ++++++++++++ .../tests/native-appkit-errors.test.ts | 82 ++++++++ apps/desktop/tests/native-client.test.ts | 115 +++++++++-- tools/build-native.ts | 1 + tools/fixtures/native-lifecycle.swift | 10 +- tools/lib/desktop-swift.ts | 1 + tools/tests/native-lifecycle.test.ts | 106 ++++++++-- 14 files changed, 793 insertions(+), 156 deletions(-) create mode 100644 apps/desktop/native/main.swift create mode 100644 apps/desktop/tests/native-appkit-errors.swift create mode 100644 apps/desktop/tests/native-appkit-errors.test.ts diff --git a/apps/desktop/native/aBridge.swift b/apps/desktop/native/aBridge.swift index 1ae90c1..214c53d 100644 --- a/apps/desktop/native/aBridge.swift +++ b/apps/desktop/native/aBridge.swift @@ -37,7 +37,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, NSMe private var window: NSWindow! private let urlField = NSTextField(string: "http://127.0.0.1:8765") private let deviceNameField = NSTextField(string: String((Host.current().localizedName ?? ProcessInfo.processInfo.hostName).prefix(80))) - private let deviceNameMessage = StatusTextField(labelWithString: "") + private let deviceNameMessage = StatusTextField(wrappingLabelWithString: "") private var saveNameButton: NSButton! private var deviceNameDirty = false private var savingDeviceName = false @@ -56,7 +56,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, NSMe private var unbindButton: NSButton! private var authorizationCancelButton: NSButton! private var authorizationOpenButton: NSButton! - private let authorizationLabel = StatusTextField(labelWithString: "") + private let authorizationLabel = StatusTextField(wrappingLabelWithString: "") private var authorizationProcess: Process? private var authorizationInput: FileHandle? private var authorizationURL: URL? @@ -86,6 +86,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, NSMe private var runtime: [String: String] = [:] private var current: [String: Any] = [:] private var monitor: Any? + private var lastControlFailure: String? private var checkingEnvironment = false private var stoppingDaemon = false private var daemonStopActions: [() -> Void] = [] @@ -403,12 +404,12 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, NSMe addFullWidth(nameRow, to: connection) deviceNameMessage.font = .systemFont(ofSize: 12) deviceNameMessage.textColor = .secondaryLabelColor - deviceNameMessage.lineBreakMode = .byTruncatingTail + deviceNameMessage.isSelectable = true deviceNameMessage.isHidden = true addFullWidth(deviceNameMessage, to: connection) authorizationLabel.font = .systemFont(ofSize: 12) authorizationLabel.textColor = .secondaryLabelColor - authorizationLabel.lineBreakMode = .byTruncatingTail + authorizationLabel.isSelectable = true authorizationLabel.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) addFullWidth(authorizationLabel, to: connection) authorizationLabel.isHidden = true @@ -750,6 +751,9 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, NSMe httpConfirmedOrigin = nil if authorizationProcess != nil && !sameServer(urlField.stringValue, authorizationServer) { cancelAuthorization() + } else if authorizationProcess == nil && !authorizationLabel.isHidden { + authorizationLabel.isHidden = true + resizeSettingsWindow() } renderMenu() } @@ -764,11 +768,17 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, NSMe beginAuthorization() } - private func sendAuthorization(_ value: [String: Any]) throws { - guard let handle = authorizationInput else { throw CocoaError(.fileWriteUnknown) } - var data = try JSONSerialization.data(withJSONObject: value) - data.append(0x0a) - try handle.write(contentsOf: data) + private func sendAuthorization(_ value: [String: Any]) { + guard let handle = authorizationInput else { return } + do { + var data = try JSONSerialization.data(withJSONObject: value) + data.append(0x0a) + try handle.write(contentsOf: data) + } catch { + // 子进程可能已在 stdout 写出启动或提交错误,让同一个读取任务消费最终结果。 + try? handle.close() + authorizationInput = nil + } } @objc private func bindingMethodChanged() { @@ -808,20 +818,18 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, NSMe private func beginAuthorization() { guard let address = normalizedServerAddress(urlField.stringValue) else { - authorizationLabel.stringValue = "请填写完整的 HTTP 或 HTTPS Server 地址" - authorizationLabel.isHidden = false + finishAuthorization("请填写完整的 HTTP 或 HTTPS 服务地址,例如 http://主机:端口。") return } let tokenMode = bindingMethod.indexOfSelectedItem == 1 let token = (revealToken.state == .on ? visibleTokenField.stringValue : deviceTokenField.stringValue).trimmingCharacters(in: .whitespacesAndNewlines) if tokenMode && (!token.hasPrefix("abr_device_") || token.count > 4096) { - authorizationLabel.stringValue = "请输入电脑设备的 Device Token,不能使用 Agent Key 或管理员 Token" - authorizationLabel.isHidden = false + finishAuthorization("请输入电脑设备的 Device Token,不能使用 Agent Key 或管理员 Token。") return } guard confirmHttp(address) else { return } guard let process = runtimeProcess(arguments: clientArguments(["authorize", "--stdin"])) else { - statusLabel.stringValue = "运行时文件缺失" + finishAuthorization("找不到 aBridge 的设备客户端,请重新安装完整的 Mac 应用。") return } let output = Pipe() @@ -831,21 +839,20 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, NSMe process.standardError = errorLog() authorizationProcess = process authorizationInput = input.fileHandleForWriting + _ = fcntl(input.fileHandleForWriting.fileDescriptor, F_SETNOSIGPIPE, 1) authorizationServer = address authorizationURL = nil authorizationCommitting = false authorizationLabel.stringValue = tokenMode ? "正在验证设备 Token…" : "正在获取授权链接…" authorizationLabel.isHidden = false - do { - try process.run() - var request: [String: Any] = ["url": address] - if tokenMode { request["device_key"] = token } - if let origin = httpConfirmedOrigin { request["http_confirmed_origin"] = origin } - try sendAuthorization(request) - } catch { - finishAuthorization("无法启动浏览器授权,请查看日志") + do { try process.run() } catch { + finishAuthorization("无法启动本机授权进程,请重新打开 aBridge 后重试。") return } + var request: [String: Any] = ["url": address] + if tokenMode { request["device_key"] = token } + if let origin = httpConfirmedOrigin { request["http_confirmed_origin"] = origin } + sendAuthorization(request) renderMenu() resizeSettingsWindow() DispatchQueue.global().async { [weak self] in @@ -865,19 +872,23 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, NSMe process.waitUntilExit() DispatchQueue.main.async { guard let self, self.authorizationProcess === process else { return } - self.finishAuthorization("授权未完成,请重新发起") + self.finishAuthorization(Self.exitMessage(process, name: "本机授权进程") + ",请重新发起绑定。") } } } private func handleAuthorization(_ event: [String: Any], from process: Process) { guard authorizationProcess === process else { return } + if let failure = Self.clientFailure(event) { + finishAuthorization(failure) + return + } switch event["event"] as? String { case "authorization": guard let address = event["authorization_url"] as? String, let destination = URL(string: address), validAuthorizationOrigin(destination, server: authorizationServer ?? "") else { - finishAuthorization("授权页面与服务地址不匹配") + finishAuthorization("授权页面与填写的服务地址不一致,请检查服务地址和反向代理的对外地址。") return } authorizationURL = destination @@ -890,9 +901,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, NSMe renderMenu() stopDaemon { [weak self] in guard let self, self.authorizationProcess === process else { return } - do { - try self.sendAuthorization(["command": "commit", "capabilities": self.capabilityButtons.mapValues { $0.state == .on }]) - } catch { self.finishAuthorization("无法保存绑定,请重新发起") } + self.sendAuthorization(["command": "commit", "capabilities": self.capabilityButtons.mapValues { $0.state == .on }]) } case "complete": deviceTokenField.stringValue = "" @@ -923,7 +932,8 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, NSMe @objc private func openAuthorization() { guard let address = authorizationURL else { return } if !NSWorkspace.shared.open(address) { - authorizationLabel.stringValue = "无法打开浏览器,请点击重新打开授权页" + authorizationLabel.stringValue = "macOS 未能打开默认浏览器,请检查默认浏览器设置,再点「重新打开授权页」。" + resizeSettingsWindow() } } @@ -1051,7 +1061,14 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, NSMe @objc private func showDiagnostics() { let alert = NSAlert() alert.messageText = "aBridge 诊断" - alert.informativeText = current["error"] as? String ?? "暂无错误记录" + var details = ["设备连接:\(statusLabel.stringValue)"] + if !authorizationLabel.isHidden { details.append("设备绑定:\(authorizationLabel.stringValue)") } + if !deviceNameMessage.isHidden { details.append("设备名称:\(deviceNameMessage.stringValue)") } + if let failure = lastControlFailure, failure != statusLabel.stringValue, + deviceNameMessage.isHidden || failure != deviceNameMessage.stringValue { + details.append("本机操作:\(failure)") + } + alert.informativeText = details.joined(separator: "\n\n") alert.addButton(withTitle: "查看运行日志") alert.addButton(withTitle: "关闭") alert.buttons[0].isEnabled = FileManager.default.fileExists(atPath: logURL.path) @@ -1172,25 +1189,40 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, NSMe } daemon = process let log = errorLog() - process.standardOutput = log + let output = Pipe() + process.standardOutput = output process.standardError = log - process.terminationHandler = { terminated in - let message = "Device client exited: status=\(terminated.terminationStatus), reason=\(terminated.terminationReason.rawValue)\n" - if let data = message.data(using: .utf8) { try? log.write(contentsOf: data) } - Task { @MainActor [weak self] in - guard let self, self.daemon === terminated else { return } - self.daemon = nil - self.current["connection"] = "offline" - self.statusLabel.stringValue = "客户端已退出,可重试连接或查看诊断" - self.renderMenu() - } - } do { try process.run() statusLabel.stringValue = "正在连接" } catch { - if daemon === process { daemon = nil } - statusLabel.stringValue = "无法启动运行时,请查看诊断" + daemon = nil + statusLabel.stringValue = "无法启动设备客户端,请重新打开 aBridge。若再次失败,请检查 Mac 应用是否安装完整。" + return + } + DispatchQueue.global().async { [weak self] in + // run 只在退出失败时写一行回执。持续排空 stdout,仅保留末尾用于读取错误码。 + var tail = Data() + while true { + let chunk = output.fileHandleForReading.availableData + if chunk.isEmpty { break } + tail.append(chunk) + if tail.count > 8192 { tail = Data(tail.suffix(8192)) } + } + process.waitUntilExit() + let reply = tail.split(separator: 10).last.flatMap { try? JSONSerialization.jsonObject(with: Data($0)) as? [String: Any] } + DispatchQueue.main.async { [weak self] in + let exit = Self.exitMessage(process, name: "设备客户端") + let failure = reply.flatMap(Self.clientFailure) + try? log.write(contentsOf: Data(((failure.map { exit + "。" + $0 } ?? exit) + "\n").utf8)) + guard let self, self.daemon === process else { return } + self.daemon = nil + self.current["connection"] = "offline" + if let failure { self.statusLabel.stringValue = failure } + else if process.terminationStatus == 0 && self.boundServerAddress() == nil { self.statusLabel.stringValue = "尚未绑定这台 Mac" } + else { self.statusLabel.stringValue = exit + ",可重新连接或查看运行日志。" } + self.renderMenu() + } } } @@ -1248,27 +1280,63 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, NSMe ["--state-dir", stateDirectory.path] + arguments } + /// 只解析失败回执。成功的状态快照也有 error 字段,内容属于设备连接状态。 + private static func clientFailure(_ reply: [String: Any]) -> String? { + guard reply["ok"] as? Bool == false else { return nil } + let error = reply["error"] as? [String: Any] + switch error?["code"] as? String { + case "invalid_contract": return "无法读取 aBridge 随附的协议文件,请重新安装完整的 Mac 应用。" + case "control_timeout": return "本机设备客户端响应超时。请先检查当前状态,再决定是否重试。" + case "control_failed", "runtime_error": return "本机设备客户端未能完成操作,请打开「运行诊断」查看运行日志。" + case "already_running": return "已有 aBridge 设备客户端正在运行,请检查是否同时打开了两份应用。" + case "credential_permissions": return "本机绑定文件的所有者或权限不正确,请使用创建绑定的 macOS 账户打开 aBridge,并检查数据目录权限。" + case "credential_invalid", "credential_mismatch", "configuration_invalid": return "本机绑定记录无效或与服务地址不匹配,请检查地址并重新绑定这台 Mac。" + case "status_write_failed", "journal_failed": return "设备客户端无法保存本机状态,请检查磁盘可用空间和 aBridge 数据目录的写入权限。" + case "invalid_url": return "本机绑定记录的服务地址无效或缺少 HTTP 确认,设备连接已停止。请检查已有的本机绑定配置。" + case "device_offline", "rename_failed", "control_unavailable": + if let message = error?["message"] as? String, !message.isEmpty { return message } + default: break + } + return "本机设备客户端拒绝了请求,请检查当前连接并查看运行日志。" + } + + private static func exitMessage(_ process: Process, name: String) -> String { + process.terminationReason == .uncaughtSignal + ? "\(name)被系统信号 \(process.terminationStatus) 中断" + : "\(name)已退出(退出码 \(process.terminationStatus))" + } + private func runClient( _ arguments: [String], completion: @escaping ([String: Any]) -> Void ) { + // 状态每秒刷新,诊断保留用户最近一次本机控制的失败原因。 + let complete: ([String: Any]) -> Void = { result in + if arguments.first == "control", !arguments.contains("--if-desktop-active") { + self.lastControlFailure = result["ok"] as? Bool == true ? nil : result["error"] as? String + } + completion(result) + } guard let process = runtimeProcess(arguments: clientArguments(arguments)) else { - completion(["error": "运行时文件缺失"]) + complete(["error": "找不到设备客户端,请重新安装完整的 Mac 应用。"]) return } let output = Pipe() process.standardOutput = output process.standardError = errorLog() do { try process.run() } catch { - completion(["error": "无法启动运行时,请查看诊断"]) + complete(["error": "无法启动本机设备客户端,请重新打开 aBridge 后重试。"]) return } DispatchQueue.global().async { let data = output.fileHandleForReading.readDataToEndOfFile() process.waitUntilExit() - let result = (try? JSONSerialization.jsonObject(with: data) as? [String: Any]) - ?? ["error": "运行时返回异常,请查看诊断"] - DispatchQueue.main.async { completion(result) } + let reply = try? JSONSerialization.jsonObject(with: data) as? [String: Any] + DispatchQueue.main.async { + if let reply, let failure = Self.clientFailure(reply) { complete(["error": failure]) } + else if let reply, process.terminationStatus == 0 { complete(reply) } + else { complete(["error": Self.exitMessage(process, name: "本机设备客户端") + ",未收到有效结果,请查看运行日志。"]) } + } } } @@ -1363,14 +1431,12 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, NSMe } else { statusLabel.stringValue = connection == "connecting" ? "正在连接" : "连接已断开" } - statusLabel.toolTip = nil - if let error = status["error"] as? String, !error.isEmpty { - statusLabel.toolTip = error - if error.contains("Device credential revoked") { - statusLabel.stringValue = authorizationProcess != nil ? "正在重新绑定,请在浏览器确认授权" : "设备授权已撤销,请重新绑定这台 Mac" - } else { - statusLabel.stringValue = error - } + if connection == "revoked" && authorizationProcess != nil { + statusLabel.stringValue = "正在重新绑定这台 Mac" + } else if let error = status["error"] as? String, !error.isEmpty { + statusLabel.stringValue = error + } else if connection == "revoked" { + statusLabel.stringValue = "设备授权已失效,请重新绑定这台 Mac。" } let pauseTitle = paused ? "恢复访问" : "暂停访问" pauseItem.title = pauseTitle @@ -1439,10 +1505,3 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, NSMe return handle } } - -MainActor.assumeIsolated { - let app = NSApplication.shared - let delegate = AppDelegate() - app.delegate = delegate - app.run() -} diff --git a/apps/desktop/native/main.swift b/apps/desktop/native/main.swift new file mode 100644 index 0000000..4b24a1f --- /dev/null +++ b/apps/desktop/native/main.swift @@ -0,0 +1,8 @@ +import AppKit + +MainActor.assumeIsolated { + let app = NSApplication.shared + let delegate = AppDelegate() + app.delegate = delegate + app.run() +} diff --git a/apps/desktop/native/runtime/Authorization.swift b/apps/desktop/native/runtime/Authorization.swift index c715eb4..953af6e 100644 --- a/apps/desktop/native/runtime/Authorization.swift +++ b/apps/desktop/native/runtime/Authorization.swift @@ -96,12 +96,12 @@ private struct AuthorizationCallback: Sendable { guard states.count == 1, let received = states[0].value, constantTimeEqual(received, state), (codes.count == 1 && errors.isEmpty) || (errors.count == 1 && codes.isEmpty) else { throw DesktopError(code: "callback_invalid", message: "Invalid callback") } if let code = codes.first?.value, code.range(of: "^[A-Za-z0-9_-]{16,256}$", options: .regularExpression) != nil { - try await respond(client, status: 200, message: "授权完成,可以关闭此页面并返回 aBridge。") + try await respond(client, status: 200, message: "已收到授权,请返回 aBridge 查看绑定结果。") return code } if errors.count == 1, errors[0].value != nil { try await respond(client, status: 200, message: "授权已取消,可以关闭此页面。") - throw DesktopError(code: "access_denied", message: "用户取消了设备授权") + throw DesktopError(code: "access_denied", message: "浏览器授权已取消。如需绑定,请重新发起") } throw DesktopError(code: "callback_invalid", message: "Invalid callback") } catch { @@ -131,8 +131,19 @@ private func randomAuthorizationValue() throws -> String { } enum NativeAuthorization { - private static func fetch(_ url: String, stage: String, method: String = "GET", body: JSONObject? = nil, key: String? = nil, timeout: Double = 10) async throws -> JSONObject { - guard let url = URL(string: url) else { throw DesktopError(code: "invalid_url", message: "Server 地址无效") } + private enum Stage: String { + case start = "发起浏览器授权" + case redeem = "兑换设备凭证" + case cancel = "取消浏览器授权" + case verify = "验证设备凭证" + + func failure(_ reason: String) -> DesktopError { + DesktopError(code: "authorization_failed", message: "\(rawValue)失败。\(reason)") + } + } + + private static func fetch(_ url: String, stage: Stage, method: String = "GET", body: JSONObject? = nil, key: String? = nil, timeout: Double = 10) async throws -> JSONObject { + guard let url = URL(string: url) else { throw stage.failure("Server 地址无效,请检查所填地址") } var request = URLRequest(url: url, timeoutInterval: timeout) request.httpMethod = method request.setValue("application/json", forHTTPHeaderField: "Accept") @@ -142,43 +153,52 @@ enum NativeAuthorization { defer { session.invalidateAndCancel() } do { let (bytes, response) = try await session.bytes(for: request) - guard let response = response as? HTTPURLResponse else { throw DesktopError(code: "authorization_failed", message: "Server 返回无效响应") } + guard let response = response as? HTTPURLResponse else { + throw stage.failure("Server 返回了无效响应,请检查 Server 地址") + } guard (200..<300).contains(response.statusCode) else { - let reason = response.statusCode == 401 && key != nil ? "设备凭证无效或已撤销" : "Server 拒绝了请求" - throw DesktopError(code: "authorization_failed", message: "\(stage)失败。\(reason)(HTTP \(response.statusCode))") + // 错误正文和重定向地址可能包含敏感信息,提示只使用阶段和状态码。 + let status = response.statusCode + let reason: String + switch status { + case 400 where stage == .redeem: reason = "授权码无效或已过期,请重新发起浏览器授权" + case 401 where stage == .verify: reason = "设备凭证无效或已撤销,请使用此 Server 的 Device Key" + case 422: reason = "Server 无法识别此请求,请检查 Server 和客户端版本" + default: throw stage.failure(deviceServerHTTPFailure(status)) + } + throw stage.failure("\(reason)(HTTP \(status))") } var data = Data() for try await byte in bytes { - guard data.count < 65536 else { throw DesktopError(code: "authorization_failed", message: "Server 响应过大") } + guard data.count < 65536 else { throw stage.failure("Server 响应过大,请检查 Server 地址") } data.append(byte) } if method == "DELETE", data.isEmpty { return [:] } guard let object = (try? JSONValue.decode(data))?.object else { - throw DesktopError(code: "authorization_failed", message: "\(stage)失败。Server 返回了无效的 JSON 响应,请检查 Server 地址和版本") + throw stage.failure("Server 返回了无效的 JSON 响应,请检查 Server 地址和版本") } return object } catch let error as URLError { - let message: String - switch error.code { - case .cancelled: throw CancellationError() - case .cannotConnectToHost: message = "无法连接 Server,请检查地址、端口及 Server 是否运行" - case .cannotFindHost, .dnsLookupFailed: message = "无法解析 Server 域名,请检查地址和 DNS 设置" - case .timedOut: message = "连接 Server 超时,请检查网络后重试" - case .appTransportSecurityRequiresSecureConnection: message = "macOS 的传输安全策略拒绝了连接(-1022)" - case .secureConnectionFailed, .serverCertificateHasBadDate, .serverCertificateUntrusted, - .serverCertificateHasUnknownRoot, .serverCertificateNotYetValid: - message = "无法建立 Server 的 HTTPS 连接,请检查证书和 TLS 配置" - default: message = "与 Server 通信失败(网络错误 \(error.code.rawValue)),请检查网络后重试" - } - throw DesktopError(code: "authorization_failed", message: "\(stage)失败。\(message)") + if error.code == .cancelled { throw CancellationError() } + throw stage.failure(deviceServerNetworkFailure(error)) } } + + private static func validateServerResponse(_ value: JSONObject, schema: String, contract: NativeContract, stage: Stage) throws -> JSONObject { + guard let result = try? contract.validate(schema, value) else { + throw stage.failure("Server 响应与当前客户端不兼容,请检查 Server 地址和版本") + } + return result + } + static func verifyToken(server: String, key: String, confirmedHttpOrigin: String? = nil) async throws -> JSONObject { let normalized = try normalizeServerURL(server, confirmedHttpOrigin: confirmedHttpOrigin) guard key.hasPrefix("abr_device_"), key.utf8.count <= 4096 else { throw DesktopError(code: "invalid_arguments", message: "请输入 Device Key") } - let value = try await fetch(normalized + "/api/device", stage: "验证设备凭证", key: key) - let identity = try NativeContract.load().validate("deviceIdentity", value) - guard identity.string("kind") == "computer" else { throw DesktopError(code: "authorization_failed", message: "此 Device Key 不属于电脑客户端") } + let value = try await fetch(normalized + "/api/device", stage: .verify, key: key) + let identity = try validateServerResponse(value, schema: "deviceIdentity", contract: NativeContract.load(), stage: .verify) + guard identity.string("kind") == "computer" else { + throw Stage.verify.failure("此 Device Key 不属于电脑设备,请换用电脑设备的 Device Key") + } return identity } private static func authorize(server: String) async throws -> String { @@ -188,22 +208,41 @@ enum NativeAuthorization { defer { Darwin.close(callback.fd) } let challenge = base64URL(Data(SHA256.hash(data: Data(verifier.utf8)))) let name = String((Host.current().localizedName ?? ProcessInfo.processInfo.hostName).trimmingCharacters(in: .whitespacesAndNewlines).prefix(80)) - let start = try contract.validate("deviceAuthorizationStart", await fetch(server + "/api/device-authorizations", stage: "发起浏览器授权", method: "POST", body: ["kind": .string("computer"), "name": .string(name.isEmpty ? "Computer" : name), "capabilities": .array(["screen", "input", "shell", "files"].map(JSONValue.string)), "redirect_uri": .string(callback.redirect), "code_challenge": .string(challenge), "code_challenge_method": .string("S256"), "state": .string(state)])) - guard let id = start.string("id") else { throw DesktopError(code: "authorization_failed", message: "Server 返回无效授权") } + let response = try await fetch(server + "/api/device-authorizations", stage: .start, method: "POST", body: [ + "kind": .string("computer"), "name": .string(name.isEmpty ? "Computer" : name), + "capabilities": .array(["screen", "input", "shell", "files"].map(JSONValue.string)), + "redirect_uri": .string(callback.redirect), "code_challenge": .string(challenge), + "code_challenge_method": .string("S256"), "state": .string(state), + ]) + let start = try validateServerResponse(response, schema: "deviceAuthorizationStart", contract: contract, stage: .start) + guard let id = start.string("id") else { throw Stage.start.failure("Server 未返回授权编号,请检查 Server 版本") } do { - guard let authorization = start.string("authorization_url"), let url = URL(string: authorization), let selected = URL(string: server), serverOrigin(url) == serverOrigin(selected), url.user == nil, url.password == nil, url.fragment == nil, - let expires = start.number("expires_at"), expires > epochSeconds() else { throw DesktopError(code: "authorization_failed", message: "Server 返回的授权地址或有效期无效") } + guard let authorization = start.string("authorization_url"), let url = URL(string: authorization), + let selected = URL(string: server), serverOrigin(url) == serverOrigin(selected), + url.user == nil, url.password == nil, url.fragment == nil else { + throw Stage.start.failure("Server 返回的授权链接无法用于此地址,请检查所填地址及 Server 对外地址设置") + } + guard let expires = start.number("expires_at"), expires > epochSeconds() else { + throw DesktopError(code: "authorization_expired", message: "授权已过期,请重新发起") + } emitJSON(["event": .string("authorization"), "authorization_url": .string(authorization), "expires_at": .number(expires)]) let deadline = min(expires, epochSeconds() + 300) let code = try await callback.receive(state: state, expires: deadline) guard epochSeconds() < deadline else { throw DesktopError(code: "authorization_expired", message: "授权已过期,请重新发起") } - let token = try contract.validate("deviceAuthorizationToken", await fetch(server + "/api/device-authorizations/token", stage: "兑换设备凭证", method: "POST", body: ["code": .string(code), "code_verifier": .string(verifier), "redirect_uri": .string(callback.redirect)], timeout: min(10, max(0.1, deadline - epochSeconds())))) - guard token.string("kind") == "computer", let key = token.string("key"), let capabilities = token.array("capabilities"), capabilities.allSatisfy({ ["screen", "input", "shell", "files"].contains($0.string ?? "") }) else { throw DesktopError(code: "authorization_failed", message: "Server 返回的设备类型无效") } + let response = try await fetch(server + "/api/device-authorizations/token", stage: .redeem, method: "POST", body: [ + "code": .string(code), "code_verifier": .string(verifier), "redirect_uri": .string(callback.redirect), + ], timeout: min(10, max(0.1, deadline - epochSeconds()))) + let token = try validateServerResponse(response, schema: "deviceAuthorizationToken", contract: contract, stage: .redeem) + guard token.string("kind") == "computer", let key = token.string("key"), + let capabilities = token.array("capabilities"), + capabilities.allSatisfy({ ["screen", "input", "shell", "files"].contains($0.string ?? "") }) else { + throw Stage.redeem.failure("Server 返回的设备类型或能力与 Mac 客户端不匹配,请检查 Server 版本") + } guard epochSeconds() < deadline else { throw DesktopError(code: "authorization_expired", message: "授权已过期,请重新发起") } return key } catch { // A detached bounded cancellation also runs when the command task was cancelled. - let cleanup = Task.detached { _ = try? await fetch(server + "/api/device-authorizations/\(id)", stage: "取消浏览器授权", method: "DELETE", body: ["code_verifier": .string(verifier)], timeout: 1) } + let cleanup = Task.detached { _ = try? await fetch(server + "/api/device-authorizations/\(id)", stage: .cancel, method: "DELETE", body: ["code_verifier": .string(verifier)], timeout: 1) } await cleanup.value throw error } @@ -227,7 +266,21 @@ enum NativeAuthorization { let commit = try await input.next() guard Set(commit.keys) == ["command", "capabilities"], commit.string("command") == "commit", let values = commit.object("capabilities"), values.values.allSatisfy({ $0.bool != nil }), Set(values.keys).isSubset(of: ["screen", "input", "shell", "files"]) else { throw DesktopError(code: "invalid_arguments", message: "授权提交无效") } try Task.checkCancellation() - _ = try NativeStorage(stateDir: stateDir).configure(url: url, key: key, httpConfirmedOrigin: confirmed, capabilities: values.compactMapValues(\.bool)) + do { + _ = try NativeStorage(stateDir: stateDir).configure(url: url, key: key, httpConfirmedOrigin: confirmed, capabilities: values.compactMapValues(\.bool)) + } catch { + let reason: String + if let failure = error as? DesktopError { + reason = failure.code == "credential_permissions" + ? "请检查 aBridge 数据目录和绑定文件的所有者与访问权限" + : "请检查已有的本机绑定配置和服务地址" + } else if error is DecodingError { + reason = "请检查已有的本机绑定配置是否完整" + } else { + reason = "请检查磁盘可用空间和 aBridge 数据目录的写入权限" + } + throw DesktopError(code: "binding_save_failed", message: "已取得设备凭据,但未能保存本机绑定。\(reason)。") + } emitJSON(["event": .string("complete"), "ok": .bool(true), "url": .string(url)]) return 0 } catch { diff --git a/apps/desktop/native/runtime/Client.swift b/apps/desktop/native/runtime/Client.swift index af22bba..0f48ab1 100644 --- a/apps/desktop/native/runtime/Client.swift +++ b/apps/desktop/native/runtime/Client.swift @@ -1,6 +1,8 @@ import Foundation import Darwin +private let deviceCredentialRejected = "设备凭证无效或已撤销,请重新绑定这台 Mac" + private func systemDetails() -> JSONObject { let info = ProcessInfo.processInfo let version = info.operatingSystemVersion @@ -32,6 +34,10 @@ private func systemDetails() -> JSONObject { } actor DeviceClient { + private enum ConnectionFailure: Error { + case revoked(String) + case unavailable(String) + } private enum CancellationSource { case caller, stop } private struct Admission { let hash: String, session: String @@ -86,11 +92,16 @@ actor DeviceClient { if config.revoked == true { try? await sleepMilliseconds(100); continue } do { try await connect(); backoff = 1 } catch { - if !stopping { - if let e = error as? DesktopError, e.code == "device_revoked" { + if !stopping && status != "revoked" { + switch error as? ConnectionFailure { + case .revoked(let message)?: config.revoked = true; try storage.saveConfig(config); status = "revoked" - self.error = "Device credential revoked; bind this device again" - } else { status = "offline"; self.error = "Server connection unavailable" } + self.error = message + case .unavailable(let message)?: + status = "offline"; self.error = message + case nil: + status = "offline"; self.error = "设备连接失败,请检查 Server 地址、网络及服务状态" + } } } await stopOperations(); await executor.stop(); try await writeStatus() @@ -134,11 +145,14 @@ actor DeviceClient { ws.maximumMessageSize = Int(contract.limit("messageBytes")) let identity = UUID(); connection = identity; socket = ws; status = "connecting" defer { ws.cancel(with: .goingAway, reason: nil); session.invalidateAndCancel(); if connection == identity { socket = nil } } - try await writeStatus(); ws.resume() do { + try await writeStatus(); ws.resume() let caps = await capabilities() try await send(["type": .string("hello"), "protocol": .string(contract.protocolVersion), "platform": .string("darwin"), "version": .string(contract.version), "capabilities": .object(caps), "paused": .bool(config.paused), "details": .object(systemDetails())]) - let welcome = try contract.validate("welcome", try await next(ws, timeout: 10)) + let frame = try await next(ws, timeout: 10) + guard let welcome = try? contract.validate("welcome", frame) else { + throw ConnectionFailure.unavailable("Server 返回了不兼容的设备握手响应,请检查 Server 和 Mac 客户端版本") + } epoch = welcome.number("connection_epoch")!; deviceId = welcome.string("device_id")! deviceName = welcome.string("device_name") ?? ""; owner = welcome.string("owner_name")! sequence = 0; closedSessions.removeAll(); lastAck = monotonicSeconds() @@ -158,19 +172,55 @@ actor DeviceClient { try await receive(frame) } } catch { - if let response = ws.response as? HTTPURLResponse, [401, 403].contains(response.statusCode) { - throw DesktopError(code: "device_revoked", message: "Device connection rejected") + throw connectionFailure(error, socket: ws) + } + } + /// 连接状态只发布本机定义的诊断,HTTP 响应正文和 WebSocket 关闭原因始终留在传输层。 + private func connectionFailure(_ cause: Error, socket ws: URLSessionWebSocketTask) -> ConnectionFailure { + if let failure = cause as? ConnectionFailure { return failure } + if let failure = cause as? DesktopError, failure.code == "status_write_failed" { + return .unavailable(failure.message) + } + let responseStatus = (ws.response as? HTTPURLResponse)?.statusCode + let message: String + if responseStatus == 401 { return .revoked("\(deviceCredentialRejected)(HTTP 401)") } + if responseStatus == 403 { + return .revoked("Server 拒绝了设备连接(HTTP 403),请检查 Server 和反向代理的访问规则后重新绑定这台 Mac") + } + if status == "connecting", let code = responseStatus, code != 101 { + switch code { + case 200..<300, 400, 404, 426: + message = "Server 未建立 WebSocket 连接,请检查 Server 地址和反向代理的 WebSocket 转发(HTTP \(code))" + default: + message = deviceServerHTTPFailure(code) } - throw error + } else if status == "online", monotonicSeconds() - lastAck >= lease { + message = "等待 Server 心跳确认超时,请检查网络及 Server 是否运行" + } else if let network = cause as? URLError, network.code != .cancelled { + if status == "connecting", [.badServerResponse, .cannotParseResponse].contains(network.code) { + message = "Server 返回了无效的 WebSocket 握手响应,请检查 Server 地址和反向代理的 WebSocket 转发" + } else { + message = deviceServerNetworkFailure(network) + } + } else if status == "connecting" { + message = "设备连接握手未完成,请检查 Server 及反向代理的 WebSocket 配置" + } else { + message = "与 Server 的设备连接中断,请检查网络及 Server 是否运行" } + return .unavailable(message) } private func next(_ ws: URLSessionWebSocketTask, timeout: Double) async throws -> JSONObject { let timer = Task { try await sleepMilliseconds(timeout * 1000); ws.cancel(with: .goingAway, reason: nil) } defer { timer.cancel() } let message = try await ws.receive() let bytes: Data - switch message { case .data(let data): bytes = data; case .string(let text): bytes = Data(text.utf8); @unknown default: throw DesktopError(code: "protocol_error", message: "Invalid message") } - guard bytes.count <= Int(contract.limit("messageBytes")), let frame = try JSONValue.decode(bytes).object else { throw DesktopError(code: "protocol_error", message: "Invalid server message") } + let invalid = ConnectionFailure.unavailable("Server 发送了无效的设备消息,请检查 Server 和 Mac 客户端版本") + switch message { + case .data(let data): bytes = data + case .string(let text): bytes = Data(text.utf8) + @unknown default: throw invalid + } + guard bytes.count <= Int(contract.limit("messageBytes")), let frame = (try? JSONValue.decode(bytes))?.object else { throw invalid } return frame } private func send(_ value: JSONObject) async throws { @@ -208,7 +258,8 @@ actor DeviceClient { } case "stop": await stopOperations(); await executor.stop() case "revoke": - config.revoked = true; try storage.saveConfig(config); status = "revoked"; unbindAcknowledged = true + config.revoked = true; try storage.saveConfig(config); status = "revoked" + error = "设备授权已撤销,请重新绑定这台 Mac"; unbindAcknowledged = true await stopOperations(); socket?.cancel(with: .goingAway, reason: nil) default: break } @@ -338,18 +389,7 @@ actor DeviceClient { if cap == "screen" || cap == "input" { await executor.stopComputer() } } case "rename": - let body = try contract.validate("deviceRename", ["name": request["name"] ?? .null]) - guard status == "online", !key.isEmpty, !deviceId.isEmpty, config.revoked != true else { throw DesktopError(code: "device_offline", message: "请连接 Server 后再修改设备名称") } - var request = URLRequest(url: URL(string: config.url + "/api/device")!); request.httpMethod = "PATCH"; request.timeoutInterval = 10 - request.setValue("Bearer \(key)", forHTTPHeaderField: "Authorization"); request.setValue("application/json", forHTTPHeaderField: "Content-Type"); request.httpBody = try body.encoded() - let session = deviceServerSession(); defer { session.invalidateAndCancel() } - let (stream, response) = try await session.bytes(for: request) - var bytes = Data() - for try await byte in stream { guard bytes.count < 65536 else { throw DesktopError(code: "invalid_response", message: "Server response exceeds limit") }; bytes.append(byte) } - guard (response as? HTTPURLResponse)?.statusCode == 200, let value = try JSONValue.decode(bytes).object else { throw DesktopError(code: "rename_failed", message: "设备名称保存失败") } - let result = try contract.validate("deviceRenameResult", value) - guard result.string("id") == deviceId else { throw DesktopError(code: "invalid_response", message: "Server 返回了不匹配的设备名称") } - deviceName = result.string("name")! + try await rename(request["name"] ?? .null) case "unbind": config.paused = true; config.revoked = true; try storage.saveConfig(config); try storage.deleteCredential(); await stopOperations() unbindAcknowledged = false @@ -364,6 +404,49 @@ actor DeviceClient { try await writeStatus(); if status == "online" { try? await heartbeat() } return await snapshot() } + /// 改名请求的网络和响应错误只通过本机定义的消息返回给 UI。 + private func rename(_ name: JSONValue) async throws { + let body = try contract.validate("deviceRename", ["name": name]) + guard status == "online", !key.isEmpty, !deviceId.isEmpty, config.revoked != true else { + throw DesktopError(code: "device_offline", message: "请连接 Server 后再修改设备名称") + } + var request = URLRequest(url: URL(string: config.url + "/api/device")!, timeoutInterval: 10) + request.httpMethod = "PATCH" + request.setValue("Bearer \(key)", forHTTPHeaderField: "Authorization") + request.setValue("application/json", forHTTPHeaderField: "Content-Type") + request.httpBody = try body.encoded() + let session = deviceServerSession() + defer { session.invalidateAndCancel() } + let failure = { (detail: String) in DesktopError(code: "rename_failed", message: "修改设备名称失败。\(detail)") } + do { + let (stream, response) = try await session.bytes(for: request) + guard let code = (response as? HTTPURLResponse)?.statusCode else { + throw failure("Server 返回了无效响应,请检查 Server 地址") + } + guard code == 200 else { + throw failure(code == 401 ? "\(deviceCredentialRejected)(HTTP 401)" : deviceServerHTTPFailure(code)) + } + var bytes = Data() + for try await byte in stream { + guard bytes.count < 65536 else { throw failure("Server 响应过大,请检查 Server 地址和版本") } + bytes.append(byte) + } + guard let value = (try? JSONValue.decode(bytes))?.object, + let result = try? contract.validate("deviceRenameResult", value) else { + throw failure("Server 返回了无效的设备名称响应,请检查 Server 版本") + } + guard result.string("id") == deviceId else { + throw failure("Server 返回了其他设备的响应,请确认绑定的 Server 地址") + } + deviceName = result.string("name")! + } catch let error as URLError { + throw failure(deviceServerNetworkFailure(error)) + } catch let error as DesktopError { + throw error + } catch { + throw failure("无法与 Server 通信,请检查网络及 Server 是否运行") + } + } func snapshot() async -> JSONObject { let caps = await capabilities(), diagnostics = await executor.diagnostics(initialize: false) let active = Array(operations.values) @@ -373,6 +456,9 @@ actor DeviceClient { private func writeStatus() async throws { let previous = statusWrite let next = Task { [self] in _ = try? await previous?.value; try storage.writeStatus(await snapshot()) } - statusWrite = next; try await next.value + statusWrite = next + do { try await next.value } catch { + throw DesktopError(code: "status_write_failed", message: "无法保存本机连接状态,请确认 aBridge 数据目录可写且磁盘空间充足。") + } } } diff --git a/apps/desktop/native/runtime/Contract.swift b/apps/desktop/native/runtime/Contract.swift index 4fa721f..67fe38f 100644 --- a/apps/desktop/native/runtime/Contract.swift +++ b/apps/desktop/native/runtime/Contract.swift @@ -7,9 +7,9 @@ struct NativeContract: Sendable { static func load(path: String? = nil) throws -> NativeContract { let executable = URL(fileURLWithPath: CommandLine.arguments[0]).standardizedFileURL let url = path.map { URL(fileURLWithPath: $0) } ?? executable.deletingLastPathComponent().deletingLastPathComponent().appendingPathComponent("Resources/desktop-contract.json") - guard let data = try JSONValue.decode(Data(contentsOf: url)).object, + guard let bytes = try? Data(contentsOf: url), let data = (try? JSONValue.decode(bytes))?.object, data.string("version") != nil, data.object("schemas") != nil else { - throw DesktopError(code: "invalid_contract", message: "Missing native protocol contract") + throw DesktopError(code: "invalid_contract", message: "无法读取 aBridge 随附的协议文件,请重新安装完整的 Mac 应用。") } return NativeContract(data: data) } diff --git a/apps/desktop/native/runtime/DeviceServerSession.swift b/apps/desktop/native/runtime/DeviceServerSession.swift index b2613e3..7e4a3d8 100644 --- a/apps/desktop/native/runtime/DeviceServerSession.swift +++ b/apps/desktop/native/runtime/DeviceServerSession.swift @@ -19,3 +19,57 @@ func deviceServerSession(timeout: TimeInterval? = nil) -> URLSession { } return URLSession(configuration: configuration, delegate: DeviceNetworkDelegate(), delegateQueue: nil) } + +/// 仅根据系统错误码说明故障,避免显示请求地址和底层诊断原文。 +func deviceServerNetworkFailure(_ error: URLError) -> String { + switch error.code { + case .badURL, .unsupportedURL: + return "Server 地址无效,请检查地址是否使用 HTTP 或 HTTPS" + case .cannotConnectToHost: + return "无法连接 Server,请检查地址、端口及 Server 是否运行" + case .cannotFindHost, .dnsLookupFailed: + return "无法解析 Server 域名,请检查地址和 DNS 设置" + case .notConnectedToInternet: + return "此 Mac 无法访问网络,请检查网络。若使用局域网,请在「隐私与安全性 → 本地网络」中允许 aBridge" + case .networkConnectionLost, .cancelled: + return "与 Server 的连接中断,请检查网络及 Server 是否运行" + case .timedOut: + return "连接 Server 超时,请检查网络、地址和防火墙" + case .appTransportSecurityRequiresSecureConnection: + return "macOS 拒绝了未加密连接(-1022),请确认当前使用支持 HTTP 的 aBridge 客户端" + case .secureConnectionFailed: + return "无法建立 HTTPS 连接,请检查 Server 地址的协议和 TLS 配置" + case .serverCertificateHasBadDate, .serverCertificateNotYetValid: + return "Server 的 HTTPS 证书已过期或尚未生效,请检查证书有效期及此 Mac 的日期与时间" + case .serverCertificateUntrusted, .serverCertificateHasUnknownRoot: + return "此 Mac 无法信任 Server 的 HTTPS 证书,请检查证书域名和证书链" + case .clientCertificateRejected, .clientCertificateRequired: + return "Server 要求客户端证书或拒绝了证书,请检查反向代理的 TLS 认证设置" + case .badServerResponse, .cannotParseResponse: + return "Server 返回了无法识别的响应,请检查地址及反向代理设置" + default: + return "与 Server 通信失败(网络错误 \(error.code.rawValue)),请检查网络及 Server 状态" + } +} + +/// HTTP 失败只显示状态码和固定排查建议。 +func deviceServerHTTPFailure(_ status: Int) -> String { + let message: String + switch status { + case 300..<400: + message = "Server 返回了重定向,请填写最终的 Server 地址" + case 401, 403: + message = "Server 拒绝访问,请检查 Server 和反向代理的访问规则" + case 404, 405: + message = "Server 未提供此接口,请检查地址、反向代理路由和 Server 版本" + case 421: + message = "Server 拒绝了请求的 Host,请检查 Server 对外地址和反向代理的 Host 转发设置" + case 429: + message = "请求过于频繁,请稍后重试" + case 500..<600: + message = "Server 或反向代理暂时无法处理请求,请检查服务状态后重试" + default: + message = "Server 返回了意外的 HTTP 状态,请检查地址和 Server 配置" + } + return "\(message)(HTTP \(status))" +} diff --git a/apps/desktop/native/runtime/LocalControl.swift b/apps/desktop/native/runtime/LocalControl.swift index adace1c..8a2bded 100644 --- a/apps/desktop/native/runtime/LocalControl.swift +++ b/apps/desktop/native/runtime/LocalControl.swift @@ -169,7 +169,10 @@ actor LocalControlServer { let deadline = monotonicSeconds() + timeout let path = controlSocketPath(stateDir) var info = stat() - guard lstat(path, &info) == 0 else { throw posixFailure("Read local socket") } + guard lstat(path, &info) == 0 else { + if errno == ENOENT { throw DesktopError(code: "control_unavailable", message: "本机设备客户端尚未启动,请在 aBridge 设置中检查绑定和连接状态。") } + throw posixFailure("Read local socket") + } guard info.st_mode & S_IFMT == S_IFSOCK, info.st_uid == getuid(), info.st_mode & 0o777 == 0o600 else { throw DesktopError(code: "control_failed", message: "Unsafe local socket permissions") } let fd = try await connectUnix(path, deadline: deadline) defer { Darwin.close(fd) } diff --git a/apps/desktop/tests/native-appkit-errors.swift b/apps/desktop/tests/native-appkit-errors.swift new file mode 100644 index 0000000..9ea10c7 --- /dev/null +++ b/apps/desktop/tests/native-appkit-errors.swift @@ -0,0 +1,123 @@ +import AppKit + +@main +@MainActor +struct NativeAppKitErrors { + static func main() { + let app = NSApplication.shared + let delegate = AppDelegate() + app.delegate = delegate + Task { + let state = URL(fileURLWithPath: CommandLine.arguments[1], isDirectory: true) + await verifyErrors(state: state, secret: CommandLine.arguments[2]) + FileHandle.standardOutput.write(Data("PASS native AppKit errors\n".utf8)) + app.terminate(nil) + } + withExtendedLifetime(delegate) { app.run() } + } + + private static func verifyErrors(state: URL, secret: String) async { + let settings = await waitFor("设置窗口没有打开") { + NSApp.windows.first(where: { $0.title == "aBridge 设置" && $0.isVisible })?.contentView + } + let connect = button("在浏览器授权", in: settings) + connect.performClick(nil) + + let expected = "无法读取 aBridge 随附的协议文件,请重新安装完整的 Mac 应用。" + let field = await waitFor("设备绑定没有显示协议文件错误") { + fields(in: settings).first { $0.stringValue == expected } + } + precondition(field.cell?.wraps == true, "设备绑定错误需要在设置窗口内完整显示") + assertRedacted(settings, secret: secret) + button("运行诊断", in: settings).performClick(nil) + assertDiagnostics("设备绑定:\(expected)", in: settings, secret: secret) + + connect.performClick(nil) + _ = await waitFor("无效的运行时输出应显示真实退出码和恢复操作") { + fields(in: settings).first { $0.stringValue == "本机授权进程已退出(退出码 7),请重新发起绑定。" } + } + assertRedacted(settings, secret: secret) + + do { try storeBinding(in: state, secret: secret) } + catch { fatalError("无法准备测试绑定:\(error)") } + _ = await waitFor("已有绑定时应提供重新连接入口") { + connect.title == "重新连接" && connect.isEnabled ? connect : nil + } + connect.performClick(nil) + + let alreadyRunning = "已有 aBridge 设备客户端正在运行,请检查是否同时打开了两份应用。" + _ = await waitFor("设备客户端结构化退出应显示重复运行提示") { + fields(in: settings).first { $0.stringValue == alreadyRunning } + } + assertRedacted(settings, secret: secret) + assertDiagnostics("设备连接:\(alreadyRunning)", in: settings, secret: secret) + } + + private static func storeBinding(in state: URL, secret: String) throws { + let manager = FileManager.default + let server = "http://127.0.0.1:8765" + try manager.createDirectory( + at: state.appendingPathComponent("credentials"), + withIntermediateDirectories: false, + attributes: [.posixPermissions: 0o700] + ) + let records: [(String, [String: Any])] = [ + ("config.json", ["url": server, "paused": false, "capabilities": ["files": true]]), + ("credentials/device.json", ["server_url": server, "device_key": secret]), + ] + for (file, record) in records { + let data = try JSONSerialization.data(withJSONObject: record) + precondition(manager.createFile( + atPath: state.appendingPathComponent(file).path, + contents: data, + attributes: [.posixPermissions: 0o600] + ), "无法写入测试绑定文件 \(file)") + } + } + + private static func assertDiagnostics(_ expected: String, in settings: NSView, secret: String) { + let diagnostics = Timer(timeInterval: 0.02, repeats: true) { timer in + MainActor.assumeIsolated { + guard let content = NSApp.modalWindow?.contentView else { return } + precondition(fields(in: content).contains { $0.stringValue.contains(expected) }, + "连接诊断没有显示完整错误") + assertRedacted(content, secret: secret) + timer.invalidate() + NSApp.stopModal(withCode: .alertSecondButtonReturn) + } + } + RunLoop.main.add(diagnostics, forMode: .modalPanel) + button("连接诊断", in: settings).performClick(nil) + precondition(!diagnostics.isValid, "连接诊断窗口没有打开") + } + + private static func visibleViews(in view: NSView) -> [NSView] { + if view.isHidden { return [] } + return [view] + view.subviews.flatMap { visibleViews(in: $0) } + } + + private static func fields(in view: NSView) -> [NSTextField] { + visibleViews(in: view).compactMap { $0 as? NSTextField } + } + + private static func assertRedacted(_ view: NSView, secret: String) { + precondition(fields(in: view).allSatisfy { + !$0.stringValue.contains(secret) && $0.toolTip?.contains(secret) != true + }, "设置窗口或诊断泄露了运行时原始输出") + } + + private static func button(_ title: String, in view: NSView) -> NSButton { + guard let result = visibleViews(in: view).compactMap({ $0 as? NSButton }).first(where: { $0.title == title }) else { + fatalError("找不到按钮 \(title)") + } + return result + } + + private static func waitFor(_ message: String, _ check: () -> T?) async -> T { + for _ in 0..<200 { + if let value = check() { return value } + try? await Task.sleep(for: .milliseconds(20)) + } + fatalError(message) + } +} diff --git a/apps/desktop/tests/native-appkit-errors.test.ts b/apps/desktop/tests/native-appkit-errors.test.ts new file mode 100644 index 0000000..1fd2ee6 --- /dev/null +++ b/apps/desktop/tests/native-appkit-errors.test.ts @@ -0,0 +1,82 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { plist } from "../../../tools/build-native.js"; +import { desktopSwiftTargets } from "../../../tools/lib/desktop-swift.js"; +import { run } from "../../../tools/lib/process.js"; + +const secret = "abr_device_fixture_secret"; + +test( + "native AppKit settings and diagnostics show actionable binding and startup errors", + { skip: process.platform !== "darwin" || process.arch !== "arm64", timeout: 120_000 }, + async () => { + const work = await mkdtemp(join(tmpdir(), "abridge-appkit-errors-")); + const root = resolve(import.meta.dirname, "../../.."); + const contents = join(work, "aBridge Test.app", "Contents"); + const executable = join(contents, "MacOS", "AppKitErrorTest"); + const state = join(work, "state"); + try { + await mkdir(join(contents, "MacOS"), { recursive: true }); + await mkdir(join(contents, "Resources")); + await mkdir(state, { mode: 0o700 }); + await writeFile( + join(contents, "Info.plist"), + plist({ + CFBundleIdentifier: "dev.abridge.appkit-error-test", + CFBundleExecutable: "AppKitErrorTest", + CFBundlePackageType: "APPL", + LSUIElement: true, + }), + ); + await writeFile(join(contents, "Resources", "runtime.json"), JSON.stringify({ state_dir: state })); + await writeFile( + join(contents, "MacOS", "abridge-desktop"), + String.raw`#!/bin/sh +set -eu +test "$1" = "--state-dir" +case "$3" in + diagnose) + printf '%s\n' '{"runtime":{"ready":true,"version":"fixture"}}' + ;; + run) + test -f "$2/credentials/device.json" + printf '%s\n' '{"ok":false,"error":{"code":"already_running","message":"${secret}"}}' + exit 1 + ;; + authorize) + test "$4" = "--stdin" + if [ ! -e "$2/first-attempt" ]; then + exec 0<&- + touch "$2/first-attempt" + printf '%s\n' '{"ok":false,"error":{"code":"invalid_contract","message":"${secret}"}}' + exit 1 + fi + IFS= read -r request + test -n "$request" + printf '%s\n' 'unexpected stdout: ${secret}' + exit 7 + ;; + *) exit 99 ;; +esac +`, + { mode: 0o700 }, + ); + + const swift = await desktopSwiftTargets(root); + await run("/usr/bin/swiftc", [ + "-parse-as-library", + ...swift.aBridge.filter((argument) => argument !== join(root, "apps/desktop/native/main.swift")), + join(import.meta.dirname, "native-appkit-errors.swift"), + "-o", + executable, + ]); + assert.match(await run(executable, [state, secret], { timeout: 20_000 }), /PASS native AppKit errors/); + assert.ok(!(await readFile(join(state, "logs/client.log"), "utf8")).includes(secret)); + } finally { + await rm(work, { recursive: true, force: true }); + } + }, +); diff --git a/apps/desktop/tests/native-client.test.ts b/apps/desktop/tests/native-client.test.ts index c685c9b..5d14be7 100644 --- a/apps/desktop/tests/native-client.test.ts +++ b/apps/desktop/tests/native-client.test.ts @@ -55,8 +55,9 @@ async function fixture({ await chmod(directory, 0o700); let name = "Fixture Mac", responseId = "fixture", - reject = false, socketKey = deviceKey; + let upgradeStatus: number | undefined; + let renameResponse: { status: number; body: string } | undefined; const requests: { method: string | undefined; path: string | undefined; @@ -103,6 +104,10 @@ async function fixture({ } assert.equal(request.url, "/api/device"); assert.equal(request.headers.authorization, `Bearer ${deviceKey}`); + if (request.method === "PATCH" && renameResponse) { + response.writeHead(renameResponse.status).end(renameResponse.body); + return; + } if (request.method === "PATCH") name = (body as { name: string }).name; response.end( JSON.stringify( @@ -119,12 +124,14 @@ async function fixture({ const authorizationURL = `${url}/?authorize=${authorizationId}`; const server = new WebSocketServer({ noServer: true }); http.on("upgrade", (request, socket, head) => { - if (reject) { - socket.end("HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n"); - return; - } assert.equal(request.url, "/ws/device"); assert.equal(request.headers.authorization, `Bearer ${socketKey}`); + if (upgradeStatus !== undefined) { + socket.end( + `HTTP/1.1 ${upgradeStatus} Fixture response\r\nContent-Length: ${deviceKey.length}\r\nConnection: close\r\n\r\n${deviceKey}`, + ); + return; + } server.handleUpgrade(request, socket, head, (ws) => server.emit("connection", ws)); }); let peer: WebSocket | undefined, @@ -264,8 +271,11 @@ async function fixture({ set responseId(value: string) { responseId = value; }, - set reject(value: boolean) { - reject = value; + set upgradeStatus(value: number | undefined) { + upgradeStatus = value; + }, + set renameResponse(value: { status: number; body: string } | undefined) { + renameResponse = value; }, async close() { await stop(); @@ -337,6 +347,24 @@ test( }, ); +test("native client: local status write errors survive runtime exit", { skip: !native }, async () => { + const f = await fixture(); + try { + await mkdir(join(f.directory, "status.json")); + await assert.rejects(f.cli("run"), (failure: unknown) => { + assert.ok(failure instanceof Error && "stdout" in failure); + const result = JSON.parse(String(failure.stdout)) as { error: Frame; ok: boolean }; + assert.equal(result.ok, false); + assert.equal(result.error.code, "status_write_failed"); + assert.match(String(result.error.message), /无法保存本机连接状态.*目录可写.*磁盘空间/); + assert.equal(String(result.error.message).includes(f.directory), false); + return true; + }); + } finally { + await f.close(); + } +}); + function testHttpConsent(label: string, bindAddress?: string, urlHost?: string) { test( `native client: bundled helper authorizes and reconnects over HTTP with exact origin consent (${label})`, @@ -474,6 +502,50 @@ if (testHttpAddress && testHttpHostname) { testHttpConsent(`DNS hostname ${testHttpHostname}`, testHttpAddress, testHttpHostname); } +test( + "native client: connection status diagnoses invalid frames and failed WebSocket upgrades", + { skip: !native }, + async () => { + const f = await fixture(); + try { + await f.start(); + let latest: Frame | undefined; + async function expectConnectionError(connection: string, pattern: RegExp) { + const message = await until( + async () => { + latest = await f.cli("status"); + const message = String(latest.error); + return latest.connection === connection && pattern.test(message) ? message : undefined; + }, + () => `Missing ${pattern} in ${connection} status (last status: ${JSON.stringify(latest)})`, + ); + assert.equal(message.includes(deviceKey), false); + assert.equal(message.includes(f.url), false); + } + + f.upgradeStatus = 404; + f.peer.send(`Invalid frame with private content ${deviceKey}`); + await expectConnectionError("offline", /无效的设备消息.*版本/); + await expectConnectionError("offline", /WebSocket.*HTTP 404/); + assert.notEqual(JSON.parse(await readFile(join(f.directory, "config.json"), "utf8")).revoked, true); + + f.upgradeStatus = undefined; + const recovered = await until(async () => { + const status = await f.cli("status"); + return status.connection === "online" ? status : undefined; + }); + assert.equal(recovered.error, ""); + + f.upgradeStatus = 403; + f.peer.terminate(); + await expectConnectionError("revoked", /HTTP 403.*访问规则.*重新绑定/); + assert.equal(JSON.parse(await readFile(join(f.directory, "config.json"), "utf8")).revoked, true); + } finally { + await f.close(); + } + }, +); + test( "native client: signed runtime speaks protocol, persists no-replay journal and rejects invalid admission", { skip: !native }, @@ -579,8 +651,25 @@ test( JSON.stringify({ type: "heartbeat_ack", connection_epoch: f.epoch, device_name: "Console Name" }), ); await until(async () => (await f.cli("status")).device_name === "Console Name"); - f.responseId = "wrong"; - await assert.rejects(f.cli("control", "rename", "--name", "wrong-device")); + async function expectRenameFailure(pattern: RegExp) { + await assert.rejects(f.cli("control", "rename", "--name", "Rejected rename"), (failure: unknown) => { + assert.ok(failure instanceof Error && "stdout" in failure); + const result = JSON.parse(String(failure.stdout)) as { error: Frame; ok: boolean }; + assert.equal(result.ok, false); + assert.equal(result.error.code, "rename_failed"); + assert.match(String(result.error.message), pattern); + assert.equal(String(result.error.message).includes(deviceKey), false); + return true; + }); + } + f.renameResponse = { status: 503, body: deviceKey }; + await expectRenameFailure(/修改设备名称失败.*HTTP 503/); + f.renameResponse = { status: 200, body: deviceKey }; + await expectRenameFailure(/无效的设备名称响应.*Server 版本/); + f.renameResponse = undefined; + f.responseId = deviceKey; + await expectRenameFailure(/其他设备的响应.*Server 地址/); + assert.equal((await f.cli("status")).device_name, "Console Name"); f.peer.send( JSON.stringify({ type: "session_close", connection_epoch: f.epoch, session_id: "fixture_session" }), ); @@ -619,9 +708,13 @@ test( await f.cli("control", "stop"); for (let i = 1; i < 8; i++) assert.equal((await f.result(`busy_${i}`)).status, "outcome_unknown"); assert.equal((await f.cli("status")).active_operations, 0); - f.reject = true; + f.upgradeStatus = 401; f.peer.terminate(); - await until(async () => (await f.cli("status")).connection === "revoked"); + const revoked = await until(async () => { + const status = await f.cli("status"); + return status.connection === "revoked" ? status : undefined; + }); + assert.match(String(revoked.error), /设备凭证.*重新绑定.*HTTP 401/); assert.equal( (JSON.parse(await readFile(join(f.directory, "config.json"), "utf8")) as Frame).revoked, true, diff --git a/tools/build-native.ts b/tools/build-native.ts index d9c1bf4..31c240b 100644 --- a/tools/build-native.ts +++ b/tools/build-native.ts @@ -108,6 +108,7 @@ export async function nativeBuildInputs( .sort(); const files = [ "apps/desktop/native/aBridge.swift", + "apps/desktop/native/main.swift", "apps/desktop/native/runtime/Info.plist", ...nativeSources.map((name) => "apps/desktop/native/runtime/" + name), "dist/desktop/desktop-contract.json", diff --git a/tools/fixtures/native-lifecycle.swift b/tools/fixtures/native-lifecycle.swift index 7e73994..827b2ca 100644 --- a/tools/fixtures/native-lifecycle.swift +++ b/tools/fixtures/native-lifecycle.swift @@ -48,10 +48,18 @@ func refuses(_ body: () throws -> Void) throws { do { try body() } catch { retur do { _ = try await LocalControlServer.start(stateDir:root) { _ in [:] }; throw DesktopError(code:"test_failed",message:"Duplicate listener allowed") } catch { try expect((error as? DesktopError)?.code == "already_running","Duplicate listener refused") } await server.close() try expect(!FileManager.default.fileExists(atPath:controlSocketPath(root)),"Socket cleanup") + do { + _ = try await LocalControlServer.request(stateDir: root, request: ["command": .string("status")]) + throw DesktopError(code: "test_failed", message: "Expected control socket to be unavailable") + } catch { try expect((error as? DesktopError)?.code == "control_unavailable", "Report missing device process") } + do { + _ = try NativeContract.load(path: root + "/missing-contract.json") + throw DesktopError(code: "test_failed", message: "Expected missing bundled contract") + } catch { try expect((error as? DesktopError)?.code == "invalid_contract", "Identify missing app resource") } let restarted = try await LocalControlServer.start(stateDir:root) { _ in [:] } await restarted.close() try storage.deleteCredential() try refuses { _ = try storage.loadCredential(url:config.url) } - print("native lifecycle storage/socket: 22 checks passed") + print("native lifecycle storage/socket: checks passed") } } diff --git a/tools/lib/desktop-swift.ts b/tools/lib/desktop-swift.ts index 39038fb..3b36292 100644 --- a/tools/lib/desktop-swift.ts +++ b/tools/lib/desktop-swift.ts @@ -17,6 +17,7 @@ export async function desktopSwiftTargets(root: string) { "-target", desktopTarget, join(native, "aBridge.swift"), + join(native, "main.swift"), "-framework", "AppKit", "-framework", diff --git a/tools/tests/native-lifecycle.test.ts b/tools/tests/native-lifecycle.test.ts index 057325d..d81acca 100644 --- a/tools/tests/native-lifecycle.test.ts +++ b/tools/tests/native-lifecycle.test.ts @@ -5,7 +5,7 @@ import { createHash } from "node:crypto"; import { spawn } from "node:child_process"; import { once } from "node:events"; import { createInterface } from "node:readline"; -import { mkdtemp, mkdir, readFile, writeFile, copyFile, rm } from "node:fs/promises"; +import { chmod, mkdtemp, mkdir, readFile, writeFile, copyFile, rm } from "node:fs/promises"; import { join, resolve } from "node:path"; import { tmpdir } from "node:os"; import { run } from "../lib/process.js"; @@ -37,7 +37,7 @@ test( executable, ]); await t.test("private storage, URL consent, journal recovery and socket ownership", async () => { - assert.match(await run(executable, []), /22 checks passed/); + assert.match(await run(executable, []), /native lifecycle storage\/socket: checks passed/); }); for (const scenario of [ "pkce", @@ -49,11 +49,15 @@ test( "expired", "cross-origin", "invalid-token", + "unsafe-binding-file", "wrong-kind", "redirect", "connection-refused", "server-refused", + "missing-route", + "grant-rejected", "malformed-token", + "incompatible-token", "token-timeout", ] as const) { await t.test(scenario, async () => { @@ -73,6 +77,7 @@ test( let request: Record = {}, exchange: Record | undefined; let cancellations = 0; + const responseSecret = "abr_device_fixture_secret"; const server = createServer(async (incoming, response) => { const chunks: Buffer[] = []; for await (const chunk of incoming) chunks.push(Buffer.from(chunk)); @@ -81,7 +86,7 @@ test( if (incoming.url === "/api/device") { assert.equal(incoming.headers.authorization, "Bearer abr_device_new"); if (scenario === "redirect") { - response.writeHead(302, { location: "http://127.0.0.1:1/forbidden" }).end("{}"); + response.writeHead(302, { location: "http://127.0.0.1:1/" + responseSecret }).end("{}"); return; } response.writeHead(scenario === "invalid-token" ? 401 : 200).end( @@ -95,7 +100,13 @@ test( } else if (incoming.url === "/api/device-authorizations" && incoming.method === "POST") { request = body; if (scenario === "server-refused") { - response.writeHead(401).end("{}"); + response + .writeHead(401) + .end(JSON.stringify({ error: { code: "unauthorized", message: responseSecret } })); + return; + } + if (scenario === "missing-route") { + response.writeHead(404).end(JSON.stringify({ message: responseSecret })); return; } response.end( @@ -114,8 +125,18 @@ test( request.code_challenge, ); assert.equal(body.redirect_uri, request.redirect_uri); + if (scenario === "grant-rejected") { + response + .writeHead(400) + .end(JSON.stringify({ error: { code: "invalid_grant", message: responseSecret } })); + return; + } if (scenario === "malformed-token") { - response.end('{"key":"abr_device_fixture_secret"'); + response.end('{"key":' + JSON.stringify(responseSecret)); + return; + } + if (scenario === "incompatible-token") { + response.end(JSON.stringify({ key: responseSecret })); return; } if (scenario === "token-timeout") { @@ -142,7 +163,13 @@ test( const origin = `http://127.0.0.1:${address.port}`; if (scenario === "connection-refused") await new Promise((resolve) => server.close(() => resolve())); - const manual = ["manual", "invalid-token", "wrong-kind", "redirect"].includes(scenario); + const manual = [ + "manual", + "invalid-token", + "unsafe-binding-file", + "wrong-kind", + "redirect", + ].includes(scenario); const child = spawn(executable, ["authorize", directory], { stdio: ["pipe", "pipe", "pipe"], env: { @@ -186,7 +213,13 @@ test( ); else { assert.ok( - scenario === "pkce" || scenario === "malformed-token" || scenario === "token-timeout", + [ + "pkce", + "grant-rejected", + "malformed-token", + "incompatible-token", + "token-timeout", + ].includes(scenario), ); if (scenario === "pkce") { assert.equal( @@ -195,17 +228,17 @@ test( ); assert.equal(exchange, undefined); } - assert.equal( - (await callback({ state: String(request.state), code: "c".repeat(43) })).status, - 200, - ); + const response = await callback({ state: String(request.state), code: "c".repeat(43) }); + assert.equal(response.status, 200); + assert.equal(await response.text(), "已收到授权,请返回 aBridge 查看绑定结果。"); } } else if (event.event === "ready") { - assert.ok(scenario === "pkce" || scenario === "manual"); + assert.ok(scenario === "pkce" || scenario === "manual" || scenario === "unsafe-binding-file"); assert.deepEqual( JSON.parse(await readFile(join(directory, "config.json"), "utf8")), previous, ); + if (scenario === "unsafe-binding-file") await chmod(join(directory, "config.json"), 0o644); child.stdin.write( JSON.stringify({ command: "commit", capabilities: { files: true } }) + "\n", ); @@ -220,21 +253,53 @@ test( const success = scenario === "pkce" || scenario === "manual"; assert.equal((await exited)[0], success ? 0 : 1, stderr); assert.equal(completed, success); - assert.ok(!output.join("").includes("abr_device_new")); - if (exchange) assert.ok(!output.join("").includes(String(exchange.code_verifier))); + const diagnostics = output.join("\n") + stderr; + assert.ok(!diagnostics.includes("abr_device_new")); + assert.ok(!diagnostics.includes(responseSecret)); + if (exchange) assert.ok(!diagnostics.includes(String(exchange.code_verifier))); if (scenario === "connection-refused") { assert.match(String(authorizationError), /^发起浏览器授权失败。无法连接 Server/); } else if (scenario === "server-refused") { - assert.match(String(authorizationError), /^发起浏览器授权失败。Server 拒绝了请求(HTTP 401)$/); - assert.equal(cancellations, 0); + assert.match(String(authorizationError), /^发起浏览器授权失败。.*访问规则(HTTP 401)$/); + } else if (scenario === "missing-route") { + assert.match(String(authorizationError), /^发起浏览器授权失败。.*Server 版本(HTTP 404)$/); + } else if (scenario === "unsafe-binding-file") { + assert.match( + String(authorizationError), + /已取得设备凭据,但未能保存本机绑定。.*所有者与访问权限/, + ); + assert.ok(!diagnostics.includes(directory)); } else if (scenario === "invalid-token") { assert.match( String(authorizationError), - /^验证设备凭证失败。设备凭证无效或已撤销(HTTP 401)$/, + /^验证设备凭证失败。设备凭证无效或已撤销,请使用此 Server 的 Device Key(HTTP 401)$/, + ); + } else if (scenario === "wrong-kind") { + assert.match(String(authorizationError), /^验证设备凭证失败。.*请换用电脑设备的 Device Key$/); + } else if (scenario === "redirect") { + assert.match( + String(authorizationError), + /^验证设备凭证失败。.*最终的 Server 地址(HTTP 302)$/, + ); + } else if (scenario === "denial") { + assert.equal(authorizationError, "浏览器授权已取消。如需绑定,请重新发起"); + } else if (scenario === "expired") { + assert.equal(authorizationError, "授权已过期,请重新发起"); + } else if (scenario === "cross-origin") { + assert.match( + String(authorizationError), + /^发起浏览器授权失败。.*检查所填地址及 Server 对外地址设置$/, + ); + assert.ok(!diagnostics.includes("https://other.invalid/authorize")); + } else if (scenario === "grant-rejected") { + assert.match( + String(authorizationError), + /^兑换设备凭证失败。.*请重新发起浏览器授权(HTTP 400)$/, ); } else if (scenario === "malformed-token") { assert.match(String(authorizationError), /^兑换设备凭证失败。Server 返回了无效的 JSON 响应/); - assert.ok(!output.join("").includes("abr_device_fixture_secret")); + } else if (scenario === "incompatible-token") { + assert.match(String(authorizationError), /^兑换设备凭证失败。.*请检查 Server 地址和版本$/); } else if (scenario === "token-timeout") { assert.match(String(authorizationError), /^兑换设备凭证失败。连接 Server 超时/); } @@ -251,8 +316,9 @@ test( assert.deepEqual(config, previous); assert.deepEqual(credential, oldCredential); } - if (!manual && !["parent", "connection-refused", "server-refused"].includes(scenario)) { - assert.equal(cancellations, success ? 0 : 1); + if (!manual && !["parent", "connection-refused"].includes(scenario)) { + const startRejected = scenario === "server-refused" || scenario === "missing-route"; + assert.equal(cancellations, success || startRejected ? 0 : 1); await assert.rejects(fetch(String(request.redirect_uri))); } } finally { From 1c9a91d5ad66ac5b994fbe0e6aa611039bfb311e Mon Sep 17 00:00:00 2001 From: Wenjie Zhang Date: Wed, 25 Nov 2026 01:06:24 +0800 Subject: [PATCH 5/7] fix(desktop): isolate HTTP transport and retry denied upgrades --- apps/desktop/native/aBridge.swift | 23 ++- .../native/runtime/Authorization.swift | 2 + apps/desktop/native/runtime/Client.swift | 5 +- .../native/runtime/DeviceServerSession.swift | 16 ++ .../runtime/DeviceServerTransport.swift | 22 +++ .../runtime/{Info.plist => HTTPInfo.plist} | 2 +- apps/desktop/native/runtime/Main.swift | 4 +- apps/desktop/native/runtime/Storage.swift | 2 +- apps/desktop/native/runtime/Updater.swift | 8 +- apps/desktop/tests/native-client.test.ts | 155 ++++++++++++++++-- docs/architecture.md | 4 +- docs/deployment.md | 2 + tools/build-native.ts | 60 ++++--- tools/install-desktop.ts | 32 +++- tools/lib/desktop-swift.ts | 20 ++- tools/tests/native-admission.test.ts | 1 + tools/tests/native-lifecycle.test.ts | 12 +- 17 files changed, 285 insertions(+), 85 deletions(-) create mode 100644 apps/desktop/native/runtime/DeviceServerTransport.swift rename apps/desktop/native/runtime/{Info.plist => HTTPInfo.plist} (74%) diff --git a/apps/desktop/native/aBridge.swift b/apps/desktop/native/aBridge.swift index 214c53d..b069d3e 100644 --- a/apps/desktop/native/aBridge.swift +++ b/apps/desktop/native/aBridge.swift @@ -101,7 +101,6 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, NSMe let settings = try? JSONSerialization.jsonObject(with: data) as? [String: String] { runtime = settings } - runtime["cli_path"] = Bundle.main.bundleURL.appendingPathComponent("Contents/MacOS/abridge-desktop").path if runtime["state_dir"] == nil { runtime["state_dir"] = FileManager.default.homeDirectoryForCurrentUser .appendingPathComponent("Library/Application Support/aBridge").path @@ -799,8 +798,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, NSMe } private func confirmHttp(_ server: String) -> Bool { - guard let url = URL(string: server), url.scheme == "http", - let host = url.host, !["localhost", "127.0.0.1", "::1", "[::1]"].contains(host) else { return true } + guard let url = URL(string: server), DeviceServerTransport(server: url) == .confirmedHTTP else { return true } var parts = URLComponents(url: url, resolvingAgainstBaseURL: false)! parts.path = "" let origin = parts.string! @@ -828,7 +826,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, NSMe return } guard confirmHttp(address) else { return } - guard let process = runtimeProcess(arguments: clientArguments(["authorize", "--stdin"])) else { + guard let process = runtimeProcess(arguments: clientArguments(["authorize", "--stdin"]), server: address) else { finishAuthorization("找不到 aBridge 的设备客户端,请重新安装完整的 Mac 应用。") return } @@ -1180,9 +1178,9 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, NSMe private func startDaemon() { guard !stoppingDaemon, - boundServerAddress() != nil, + let server = boundServerAddress(), daemon?.isRunning != true else { return } - guard let process = runtimeProcess(arguments: clientArguments(["run"])) else { + guard let process = runtimeProcess(arguments: clientArguments(["run"]), server: server) else { statusLabel.stringValue = "运行时文件缺失" environmentLabels["runtime"]?.stringValue = "未安装 / 路径失效" return @@ -1262,14 +1260,14 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, NSMe } } - private func runtimeProcess(arguments: [String]) -> Process? { - guard let cli = runtime["cli_path"], cli.hasPrefix("/"), - FileManager.default.isExecutableFile(atPath: cli) - else { return nil } + private func runtimeProcess(arguments: [String], server: String? = nil) -> Process? { + let transport = server.flatMap { URL(string: $0) }.map(DeviceServerTransport.init) ?? .standard + let cli = Bundle.main.bundleURL.appendingPathComponent("Contents/MacOS/" + transport.executableName) + guard FileManager.default.isExecutableFile(atPath: cli.path) else { return nil } let process = Process() - process.executableURL = URL(fileURLWithPath: cli) + process.executableURL = cli process.arguments = arguments - process.currentDirectoryURL = URL(fileURLWithPath: cli).deletingLastPathComponent() + process.currentDirectoryURL = cli.deletingLastPathComponent() var environment = ProcessInfo.processInfo.environment environment["ABRIDGE_PARENT_PID"] = String(ProcessInfo.processInfo.processIdentifier) process.environment = environment @@ -1293,6 +1291,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, NSMe case "credential_invalid", "credential_mismatch", "configuration_invalid": return "本机绑定记录无效或与服务地址不匹配,请检查地址并重新绑定这台 Mac。" case "status_write_failed", "journal_failed": return "设备客户端无法保存本机状态,请检查磁盘可用空间和 aBridge 数据目录的写入权限。" case "invalid_url": return "本机绑定记录的服务地址无效或缺少 HTTP 确认,设备连接已停止。请检查已有的本机绑定配置。" + case "transport_mismatch": return "本机服务地址与设备客户端的传输方式不匹配,请检查绑定配置并重新连接。" case "device_offline", "rename_failed", "control_unavailable": if let message = error?["message"] as? String, !message.isEmpty { return message } default: break diff --git a/apps/desktop/native/runtime/Authorization.swift b/apps/desktop/native/runtime/Authorization.swift index 953af6e..e9541a2 100644 --- a/apps/desktop/native/runtime/Authorization.swift +++ b/apps/desktop/native/runtime/Authorization.swift @@ -193,6 +193,7 @@ enum NativeAuthorization { static func verifyToken(server: String, key: String, confirmedHttpOrigin: String? = nil) async throws -> JSONObject { let normalized = try normalizeServerURL(server, confirmedHttpOrigin: confirmedHttpOrigin) + try requireDeviceServerTransport(normalized) guard key.hasPrefix("abr_device_"), key.utf8.count <= 4096 else { throw DesktopError(code: "invalid_arguments", message: "请输入 Device Key") } let value = try await fetch(normalized + "/api/device", stage: .verify, key: key) let identity = try validateServerResponse(value, schema: "deviceIdentity", contract: NativeContract.load(), stage: .verify) @@ -256,6 +257,7 @@ enum NativeAuthorization { guard let rawURL = start.string("url") else { throw DesktopError(code: "invalid_arguments", message: "Server 地址无效") } let confirmed = start.string("http_confirmed_origin") let url = try normalizeServerURL(rawURL, confirmedHttpOrigin: confirmed) + try requireDeviceServerTransport(url) let key: String if let supplied = start.string("device_key") { _ = try await verifyToken(server: url, key: supplied, confirmedHttpOrigin: confirmed) diff --git a/apps/desktop/native/runtime/Client.swift b/apps/desktop/native/runtime/Client.swift index 0f48ab1..ecd1c17 100644 --- a/apps/desktop/native/runtime/Client.swift +++ b/apps/desktop/native/runtime/Client.swift @@ -136,7 +136,7 @@ actor DeviceClient { } private func connect() async throws { var components = URLComponents(string: config.url)! - components.scheme = components.scheme == "https" ? "wss" : "ws" + components.scheme = components.scheme?.lowercased() == "https" ? "wss" : "ws" components.path += "/ws/device" var request = URLRequest(url: components.url!); request.timeoutInterval = 10 request.setValue("Bearer \(key)", forHTTPHeaderField: "Authorization") @@ -184,9 +184,6 @@ actor DeviceClient { let responseStatus = (ws.response as? HTTPURLResponse)?.statusCode let message: String if responseStatus == 401 { return .revoked("\(deviceCredentialRejected)(HTTP 401)") } - if responseStatus == 403 { - return .revoked("Server 拒绝了设备连接(HTTP 403),请检查 Server 和反向代理的访问规则后重新绑定这台 Mac") - } if status == "connecting", let code = responseStatus, code != 101 { switch code { case 200..<300, 400, 404, 426: diff --git a/apps/desktop/native/runtime/DeviceServerSession.swift b/apps/desktop/native/runtime/DeviceServerSession.swift index 7e4a3d8..ca85fa0 100644 --- a/apps/desktop/native/runtime/DeviceServerSession.swift +++ b/apps/desktop/native/runtime/DeviceServerSession.swift @@ -1,6 +1,22 @@ import Foundation import Security +func requireDeviceServerTransport(_ normalizedServer: String) throws { + guard let server = URL(string: normalizedServer) else { + throw DesktopError(code: "invalid_url", message: "Server 地址无效") + } + let transport = DeviceServerTransport(server: server) + #if ABRIDGE_CONFIRMED_HTTP + guard transport == .confirmedHTTP else { + throw DesktopError(code: "transport_mismatch", message: "此设备客户端仅用于明确确认的远端 HTTP Server。请使用 abridge-desktop 连接 HTTPS 或回环地址。") + } + #else + guard transport == .standard else { + throw DesktopError(code: "transport_mismatch", message: "连接已确认的远端 HTTP Server 需要使用 abridge-desktop-http。") + } + #endif +} + /// 设备授权请求、改名和 WebSocket 都只连接已选 Server,不随重定向传递凭据。 private final class DeviceNetworkDelegate: NSObject, URLSessionTaskDelegate, @unchecked Sendable { func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping @Sendable (URLRequest?) -> Void) { diff --git a/apps/desktop/native/runtime/DeviceServerTransport.swift b/apps/desktop/native/runtime/DeviceServerTransport.swift new file mode 100644 index 0000000..acc3662 --- /dev/null +++ b/apps/desktop/native/runtime/DeviceServerTransport.swift @@ -0,0 +1,22 @@ +import Foundation + +enum DeviceServerTransport: Equatable { + case standard, confirmedHTTP + + init(server: URL) { + if server.scheme?.lowercased() == "http", + let host = server.host?.lowercased(), + !["localhost", "127.0.0.1", "::1", "[::1]"].contains(host) { + self = .confirmedHTTP + } else { + self = .standard + } + } + + var executableName: String { + switch self { + case .standard: "abridge-desktop" + case .confirmedHTTP: "abridge-desktop-http" + } + } +} diff --git a/apps/desktop/native/runtime/Info.plist b/apps/desktop/native/runtime/HTTPInfo.plist similarity index 74% rename from apps/desktop/native/runtime/Info.plist rename to apps/desktop/native/runtime/HTTPInfo.plist index 1873505..7ccafb5 100644 --- a/apps/desktop/native/runtime/Info.plist +++ b/apps/desktop/native/runtime/HTTPInfo.plist @@ -4,7 +4,7 @@ NSAppTransportSecurity - + NSAllowsArbitraryLoads diff --git a/apps/desktop/native/runtime/Main.swift b/apps/desktop/native/runtime/Main.swift index 9280296..72af9e6 100644 --- a/apps/desktop/native/runtime/Main.swift +++ b/apps/desktop/native/runtime/Main.swift @@ -30,7 +30,9 @@ import Darwin switch positionals.first ?? "status" { case "startup-check": emitJSON(["ready": .bool(true), "native": .bool(true), "version": .string(contract.version)]) case "run": - let config = try storage.loadConfig(), key = try storage.loadCredential(url: config.url) + let config = try storage.loadConfig() + try requireDeviceServerTransport(config.url) + let key = try storage.loadCredential(url: config.url) let parent = ProcessInfo.processInfo.environment["ABRIDGE_PARENT_PID"].flatMap(Int32.init) let client = DeviceClient(storage: storage, config: config, key: key, contract: contract, parentPid: parent.flatMap { $0 > 0 ? $0 : nil }) let signals = [SIGINT, SIGTERM].map { value -> DispatchSourceSignal in diff --git a/apps/desktop/native/runtime/Storage.swift b/apps/desktop/native/runtime/Storage.swift index 4066712..23f35f1 100644 --- a/apps/desktop/native/runtime/Storage.swift +++ b/apps/desktop/native/runtime/Storage.swift @@ -43,7 +43,7 @@ func normalizeServerURL(_ value: String, confirmedHttpOrigin: String? = nil) thr components.scheme = scheme components.host = host.lowercased() if components.port == (scheme == "https" ? 443 : 80) { components.port = nil } - if scheme == "http", !["localhost", "127.0.0.1", "::1", "[::1]"].contains(host.lowercased()), confirmedHttpOrigin != origin { + if DeviceServerTransport(server: url) == .confirmedHTTP, confirmedHttpOrigin != origin { throw DesktopError(code: "invalid_url", message: "请先确认此 Server 使用未加密的 HTTP 连接") } guard var normalized = components.url?.absoluteString else { diff --git a/apps/desktop/native/runtime/Updater.swift b/apps/desktop/native/runtime/Updater.swift index 15d2f9b..90ae931 100644 --- a/apps/desktop/native/runtime/Updater.swift +++ b/apps/desktop/native/runtime/Updater.swift @@ -187,10 +187,12 @@ func prepareNativeUpdate(app: String, current: String, version: String, stateDir try rejectSymlinks(candidate) try assertNativeApp(candidate, version: version) try verifyTeam(app, candidate) - let runtime = childPath(candidate, "Contents/MacOS/abridge-desktop") - guard updaterFiles.isExecutableFile(atPath: runtime), updaterFiles.isExecutableFile(atPath: childPath(candidate, "Contents/MacOS/abridge-updater")) else { throw UpdateFailure("更新缺少原生运行时") } + let binaries = ["abridge-desktop", "abridge-desktop-http", "abridge-updater"].map { childPath(candidate, "Contents/MacOS/" + $0) } + guard binaries.allSatisfy({ updaterFiles.isExecutableFile(atPath: $0) }) else { throw UpdateFailure("更新缺少原生运行时") } let smokeState = childPath(work, "smoke-state") - _ = try JSONSerialization.jsonObject(with: Data(updaterRun(runtime, ["status", "--state-dir", smokeState]).utf8)) + for runtime in binaries.dropLast() { + _ = try JSONSerialization.jsonObject(with: Data(updaterRun(runtime, ["status", "--state-dir", smokeState]).utf8)) + } try? updaterFiles.removeItem(atPath: smokeState) try updaterFiles.copyItem(atPath: CommandLine.arguments[0], toPath: childPath(work, "abridge-updater")) guard chmod(childPath(work, "abridge-updater"), 0o700) == 0 else { throw UpdateFailure("更新程序不可执行") } diff --git a/apps/desktop/tests/native-client.test.ts b/apps/desktop/tests/native-client.test.ts index 5d14be7..8dd460a 100644 --- a/apps/desktop/tests/native-client.test.ts +++ b/apps/desktop/tests/native-client.test.ts @@ -4,6 +4,7 @@ import { createHash } from "node:crypto"; import { lookup } from "node:dns/promises"; import { once } from "node:events"; import { createServer } from "node:http"; +import { createServer as createSecureServer } from "node:https"; import { spawn, execFile, type ChildProcess } from "node:child_process"; import { promisify } from "node:util"; import { mkdtemp, mkdir, chmod, writeFile, readFile, readdir, rm } from "node:fs/promises"; @@ -26,6 +27,7 @@ const binary = resolve( process.env.ABRIDGE_NATIVE_TEST_APP ?? "dist/desktop/aBridge.app", "Contents/MacOS/abridge-desktop", ); +const httpBinary = join(dirname(binary), "abridge-desktop-http"); const native = process.platform === "darwin" && process.arch === "arm64"; const deviceKey = "abr_device_fixture"; const browserDeviceKey = "abr_device_browser_fixture"; @@ -50,7 +52,8 @@ async function fixture({ host = "127.0.0.1", urlHost = host, seedBinding = true, -}: { host?: string; urlHost?: string; seedBinding?: boolean } = {}) { + executable = binary, +}: { host?: string; urlHost?: string; seedBinding?: boolean; executable?: string } = {}) { const directory = await mkdtemp(join(tmpdir(), "abridge-native-client-")); await chmod(directory, 0o700); let name = "Fixture Mac", @@ -125,10 +128,10 @@ async function fixture({ const server = new WebSocketServer({ noServer: true }); http.on("upgrade", (request, socket, head) => { assert.equal(request.url, "/ws/device"); - assert.equal(request.headers.authorization, `Bearer ${socketKey}`); - if (upgradeStatus !== undefined) { + const status = request.headers.authorization === `Bearer ${socketKey}` ? upgradeStatus : 401; + if (status !== undefined) { socket.end( - `HTTP/1.1 ${upgradeStatus} Fixture response\r\nContent-Length: ${deviceKey.length}\r\nConnection: close\r\n\r\n${deviceKey}`, + `HTTP/1.1 ${status} Fixture response\r\nContent-Length: ${deviceKey.length}\r\nConnection: close\r\n\r\n${deviceKey}`, ); return; } @@ -204,7 +207,7 @@ async function fixture({ clearTimeout(forced); } async function start() { - child = spawn(binary, ["run", "--state-dir", directory], { stdio: ["ignore", "pipe", "pipe"] }); + child = spawn(executable, ["run", "--state-dir", directory], { stdio: ["ignore", "pipe", "pipe"] }); child.stderr!.on("data", (data) => { stderr += String(data); }); @@ -274,6 +277,9 @@ async function fixture({ set upgradeStatus(value: number | undefined) { upgradeStatus = value; }, + rotateDeviceKey() { + socketKey = "abr_device_rotated_fixture"; + }, set renameResponse(value: { status: number; body: string } | undefined) { renameResponse = value; }, @@ -287,9 +293,14 @@ async function fixture({ }; } -async function authorize(directory: string, input: Frame, approveInBrowser?: () => Promise) { - const child = spawn(binary, ["--state-dir", directory, "authorize", "--stdin"], { - cwd: dirname(binary), +async function authorize( + directory: string, + input: Frame, + executable = binary, + approveInBrowser?: () => Promise, +) { + const child = spawn(executable, ["--state-dir", directory, "authorize", "--stdin"], { + cwd: dirname(executable), env: { ...process.env, ABRIDGE_PARENT_PID: String(process.pid) }, stdio: "pipe", }); @@ -378,17 +389,17 @@ function testHttpConsent(label: string, bindAddress?: string, urlHost?: string) assert.ok(address, "HTTP consent regression requires a non-loopback IPv4 address on this Mac"); if (urlHost && urlHost !== address) assert.deepEqual(await lookup(urlHost, { all: true }), [{ address, family: 4 }]); - const f = await fixture({ host: address, urlHost, seedBinding: false }); + const f = await fixture({ host: address, urlHost, seedBinding: false, executable: httpBinary }); try { const mismatched = new URL(f.url); mismatched.port = mismatched.port === "8080" ? "8081" : "8080"; for (const device_key of [undefined, deviceKey]) { for (const http_confirmed_origin of [undefined, mismatched.origin]) { - const { code, events } = await authorize(f.directory, { - url: f.url, - device_key, - http_confirmed_origin, - }); + const { code, events } = await authorize( + f.directory, + { url: f.url, device_key, http_confirmed_origin }, + httpBinary, + ); assert.equal(code, 1); assert.deepEqual( events.map((event) => event.event), @@ -400,7 +411,12 @@ function testHttpConsent(label: string, bindAddress?: string, urlHost?: string) } const input = { url: f.url, http_confirmed_origin: f.url }; - const browser = await authorize(f.directory, input); + const standard = await authorize(f.directory, { ...input, device_key: deviceKey }); + assert.equal(standard.code, 1); + assert.match(String(standard.events[0]?.error), /需要使用 abridge-desktop-http/); + assert.equal(f.requests.length, 0); + + const browser = await authorize(f.directory, input, httpBinary); assert.equal(browser.code, 1); assert.deepEqual( browser.events.map((event) => event.event), @@ -425,7 +441,7 @@ function testHttpConsent(label: string, bindAddress?: string, urlHost?: string) assert.deepEqual(await readdir(f.directory), []); const approvalOffset = f.requests.length; - const approval = await authorize(f.directory, input, async () => { + const approval = await authorize(f.directory, input, httpBinary, async () => { const start = deviceAuthorizationRequestSchema.parse(f.requests[approvalOffset]?.body); const callback = new URL(start.redirect_uri); assert.equal(callback.protocol, "http:"); @@ -472,7 +488,7 @@ function testHttpConsent(label: string, bindAddress?: string, urlHost?: string) await f.stop(); const tokenOffset = f.requests.length; - const token = await authorize(f.directory, { ...input, device_key: deviceKey }); + const token = await authorize(f.directory, { ...input, device_key: deviceKey }, httpBinary); assert.equal(token.code, 0, JSON.stringify(token.events)); assert.deepEqual( token.events.map((event) => event.event), @@ -502,6 +518,101 @@ if (testHttpAddress && testHttpHostname) { testHttpConsent(`DNS hostname ${testHttpHostname}`, testHttpAddress, testHttpHostname); } +test("packaged desktop runtime keeps HTTPS under default ATS", { skip: !native }, async () => { + const directory = await mkdtemp(join(tmpdir(), "abridge-native-tls-")); + try { + const [standard, http, updater] = await Promise.all( + [binary, httpBinary, join(dirname(binary), "abridge-updater")].map((executable) => + exec("/usr/bin/otool", ["-l", executable]), + ), + ); + assert.doesNotMatch(standard.stdout, /sectname __info_plist/); + assert.doesNotMatch(updater.stdout, /sectname __info_plist/); + assert.match(http.stdout, /sectname __info_plist/); + assert.doesNotMatch( + await readFile(join(dirname(dirname(binary)), "Info.plist"), "utf8"), + /NSAllowsArbitraryLoads/, + ); + + // Use a fresh untrusted identity, so a machine's existing trust store cannot accept it. + const key = join(directory, "key.pem"); + const cert = join(directory, "cert.pem"); + await exec("/usr/bin/openssl", [ + "req", + "-x509", + "-newkey", + "rsa:2048", + "-nodes", + "-subj", + "/CN=localhost", + "-days", + "1", + "-keyout", + key, + "-out", + cert, + ]); + let requests = 0; + const server = createSecureServer( + { key: await readFile(key), cert: await readFile(cert), minVersion: "TLSv1.2" }, + (_request, response) => { + requests++; + response.writeHead(500).end(); + }, + ); + server.on("upgrade", (_request, socket) => { + requests++; + socket.destroy(); + }); + try { + await once(server.listen(0, "127.0.0.1"), "listening"); + const address = server.address(); + assert.ok(address && typeof address === "object"); + const input = { url: `https://localhost:${address.port}`, device_key: deviceKey }; + const unsecured = await authorize(directory, input, httpBinary); + assert.equal(unsecured.code, 1); + assert.match(String(unsecured.events[0]?.error), /仅用于明确确认的远端 HTTP/); + const hardened = await authorize(directory, input); + assert.equal(hardened.code, 1); + assert.match(String(hardened.events[0]?.error), /HTTPS.*证书/); + + await mkdir(join(directory, "credentials"), { mode: 0o700 }); + await writeFile( + join(directory, "config.json"), + JSON.stringify({ url: input.url, capabilities: {}, paused: false }), + { mode: 0o600 }, + ); + await writeFile( + join(directory, "credentials/device.json"), + JSON.stringify({ server_url: input.url, device_key: deviceKey }), + { mode: 0o600 }, + ); + const child = spawn(binary, ["run", "--state-dir", directory], { stdio: "ignore" }); + const exited = once(child, "close"); + try { + await until(async () => { + const { stdout } = await exec(binary, ["status", "--state-dir", directory], { timeout: 2000 }); + const status = JSON.parse(stdout) as Frame; + return status.connection === "offline" && /HTTPS.*证书/.test(String(status.error)); + }, "The WSS connection must report a certificate error"); + } finally { + child.kill("SIGTERM"); + const watchdog = setTimeout(() => child.kill("SIGKILL"), 6000); + try { + await exited; + } finally { + clearTimeout(watchdog); + } + } + assert.equal(requests, 0, "The untrusted peer must not receive the Device Key"); + } finally { + await new Promise((done) => server.close(() => done())); + } + } finally { + await rm(directory, { recursive: true, force: true }); + } +}); + test( "native client: connection status diagnoses invalid frames and failed WebSocket upgrades", { skip: !native }, @@ -538,7 +649,15 @@ test( f.upgradeStatus = 403; f.peer.terminate(); - await expectConnectionError("revoked", /HTTP 403.*访问规则.*重新绑定/); + await expectConnectionError("offline", /访问规则.*HTTP 403/); + assert.notEqual(JSON.parse(await readFile(join(f.directory, "config.json"), "utf8")).revoked, true); + f.upgradeStatus = undefined; + await until(async () => (await f.cli("status")).connection === "online"); + assert.equal((await f.cli("status")).error, ""); + + f.rotateDeviceKey(); + f.peer.terminate(); + await expectConnectionError("revoked", /HTTP 401/); assert.equal(JSON.parse(await readFile(join(f.directory, "config.json"), "utf8")).revoked, true); } finally { await f.close(); diff --git a/docs/architecture.md b/docs/architecture.md index 9d41654..56d4c4e 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -232,4 +232,6 @@ macOS App 包含 AppKit 主程序、Swift 设备客户端、更新器、共享 公网 HTTP 由用户显式确认具体 Origin;共享协议包负责地址规范化和确认匹配。确认写入成功绑定的本机配置,连接恢复时再次校验,浏览器 PKCE 状态与回调校验保持不变。HTTP 风险确认不代替 Server Host/Origin 访问校验,OIDC 的公网 HTTP 另由部署管理员通过 `--allow-insecure-http` / `ABRIDGE_ALLOW_INSECURE_HTTP=true` 显式开启。 -macOS 的设备进程使用系统 URLSession 连接用户指定的 Server。在此进程中允许明文传输,HTTP 和 WS 受上述 Origin 确认约束。HTTPS 和 WSS 要求 TLS 1.2 或更高版本,并使用系统证书和主机名校验。此配置会放宽设备进程的 ATS 附加限制,例如前向保密要求。更新器在独立进程中使用系统默认的 ATS 策略。 +macOS 的设备进程使用系统 URLSession 连接用户指定的 Server。HTTPS、WSS 和回环连接由使用系统默认 ATS 策略的 `abridge-desktop` 处理。经 Origin 确认的远端 HTTP 和 WS 由单独签名的 `abridge-desktop-http` 处理,只有这个进程包含 ATS 例外。绑定和启动时,设备进程在连接前复核所选传输方式。更新器也使用系统默认的 ATS 策略。 + +设备 WebSocket 握手的访问拒绝(HTTP 403)按普通连接错误重试。Server 的凭据拒绝(HTTP 401)或已建立连接收到的撤销消息会停止自动重连,直至重新绑定。 diff --git a/docs/deployment.md b/docs/deployment.md index a254874..be3ffe7 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -167,6 +167,8 @@ dist/desktop/aBridge.app/Contents/MacOS/abridge-desktop diagnose 自定义状态目录使用 `--state-dir`,日志位于 `/logs/client.log`。检查屏幕录制及辅助功能时,请打开实际安装的 App,用自己的窗口验证截图和输入。 +App 自动为经明确确认的远端 HTTP Server 选择 `Contents/MacOS/abridge-desktop-http`。直接运行 CLI 的 `authorize`、`configure` 或 `run` 时,远端 HTTP 使用该程序,HTTPS 和回环地址使用 `abridge-desktop`。`status`、`diagnose` 和本机控制继续使用 `abridge-desktop`。 + ### 应用内更新 在 macOS 菜单选择“检查更新…”,或在设置的“软件更新”中检查。发现正式新版后,依次点击“下载更新”和“安装并重启”。下载期间可以继续使用;安装会结束当前执行,保留设备绑定、能力开关、暂停状态和数据目录。应用必须位于可写的本机目录;从磁盘镜像或 App Translocation 启动时先移入 Applications。 diff --git a/tools/build-native.ts b/tools/build-native.ts index 31c240b..5a27a8f 100644 --- a/tools/build-native.ts +++ b/tools/build-native.ts @@ -4,7 +4,7 @@ import { createHash, randomUUID } from "node:crypto"; import { access, chmod, cp, lstat, mkdir, readFile, readdir, rename, rm, writeFile } from "node:fs/promises"; import { dirname, join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; -import { desktopSwiftTargets, desktopTarget } from "./lib/desktop-swift.js"; +import { desktopRuntimeExecutables, desktopSwiftTargets, desktopTarget } from "./lib/desktop-swift.js"; import { run } from "./lib/process.js"; import { resolvePackageDirectory } from "./lib/native-sdk.js"; export const PROJECT_ROOT = resolve(import.meta.dirname, ".."); @@ -109,7 +109,7 @@ export async function nativeBuildInputs( const files = [ "apps/desktop/native/aBridge.swift", "apps/desktop/native/main.swift", - "apps/desktop/native/runtime/Info.plist", + "apps/desktop/native/runtime/HTTPInfo.plist", ...nativeSources.map((name) => "apps/desktop/native/runtime/" + name), "dist/desktop/desktop-contract.json", "docs/third-party-notices.md", @@ -210,30 +210,42 @@ export async function buildNative( const library = join(frameworks, "libcua_driver_sdk.dylib"); await run("/usr/bin/lipo", [await nativeLibrary(root), "-thin", "arm64", "-output", library]); await run("/usr/bin/install_name_tool", ["-id", "@rpath/libcua_driver_sdk.dylib", library]); - await run("/usr/bin/swiftc", [ - "-O", - ...swift["abridge-desktop"], - "-L", - frameworks, - "-lcua_driver_sdk", - "-Xlinker", - "-sectcreate", - "-Xlinker", - "__TEXT", - "-Xlinker", - "__info_plist", - "-Xlinker", - join(root, "apps/desktop/native/runtime/Info.plist"), - "-Xlinker", - "-rpath", - "-Xlinker", - "@executable_path/../Frameworks", - "-o", - join(macos, "abridge-desktop"), - ]); + for (const name of desktopRuntimeExecutables) { + const httpPlist = + name === "abridge-desktop-http" + ? [ + "-Xlinker", + "-sectcreate", + "-Xlinker", + "__TEXT", + "-Xlinker", + "__info_plist", + "-Xlinker", + join(root, "apps/desktop/native/runtime/HTTPInfo.plist"), + ] + : []; + await run("/usr/bin/swiftc", [ + "-O", + ...swift[name], + "-L", + frameworks, + "-lcua_driver_sdk", + ...httpPlist, + "-Xlinker", + "-rpath", + "-Xlinker", + "@executable_path/../Frameworks", + "-o", + join(macos, name), + ]); + } await run("/usr/bin/swiftc", ["-O", ...swift["abridge-updater"], "-o", join(macos, "abridge-updater")]); await clearBuildMetadata(staging); - for (const binary of [library, join(macos, "abridge-desktop"), join(macos, "abridge-updater")]) { + for (const binary of [ + library, + ...desktopRuntimeExecutables.map((name) => join(macos, name)), + join(macos, "abridge-updater"), + ]) { await chmod(binary, 0o755); await run("/usr/bin/codesign", [ ...(options.signingIdentity === "-" ? [] : ["--options", "runtime", "--timestamp"]), diff --git a/tools/install-desktop.ts b/tools/install-desktop.ts index d82f5a8..fdcf5da 100644 --- a/tools/install-desktop.ts +++ b/tools/install-desktop.ts @@ -7,6 +7,7 @@ import { fileURLToPath } from "node:url"; import { createConnection } from "node:net"; import { createHash, randomUUID } from "node:crypto"; import { buildNative, PROJECT_ROOT } from "./build-native.js"; +import { desktopRuntimeExecutables } from "./lib/desktop-swift.js"; import { run } from "./lib/process.js"; export type DesktopInstallOptions = { app: string; @@ -62,23 +63,36 @@ export async function assertClientStopped(stateDir: string): Promise { } async function assertAppStopped(app: string): Promise { const running = (await run("/bin/ps", ["-ww", "-axo", "comm="])).split("\n").map((line) => line.trim()); - if (["aBridge", "abridge-desktop"].some((binary) => running.includes(join(app, "Contents/MacOS", binary)))) + if ( + ["aBridge", ...desktopRuntimeExecutables].some((binary) => + running.includes(join(app, "Contents/MacOS", binary)), + ) + ) throw Error("Quit aBridge before replacing its application bundle"); } export async function smokeDesktopRuntime(app: string): Promise> { const home = await mkdtemp(join(tmpdir(), "abridge-native-smoke-")); try { const env = { HOME: home, PATH: "/usr/bin:/bin", LANG: "en_US.UTF-8", TMPDIR: tmpdir() }; - const executable = join(app, "Contents/MacOS/abridge-desktop"); - const result = JSON.parse( - await run(executable, ["smoke", "--state-dir", join(home, "state")], { env, timeout: 30000 }), - ) as Record; - if (result.embedded !== true || result.desktop_actions !== 0 || result.authorizations !== 0) - throw Error("Native smoke returned unsafe or incomplete evidence"); + const results = await Promise.all( + desktopRuntimeExecutables.map(async (name) => { + const executable = join(app, "Contents/MacOS", name); + const result = JSON.parse( + await run(executable, ["smoke", "--state-dir", join(home, "state")], { env, timeout: 30000 }), + ) as Record; + if (result.embedded !== true || result.desktop_actions !== 0 || result.authorizations !== 0) + throw Error(`${name} smoke returned unsafe or incomplete evidence`); + return result; + }), + ); JSON.parse( - await run(executable, ["status", "--state-dir", join(home, "state")], { env, timeout: 10000 }), + await run( + join(app, "Contents/MacOS", desktopRuntimeExecutables[0]), + ["status", "--state-dir", join(home, "state")], + { env, timeout: 10000 }, + ), ); - return result; + return results[0]!; } finally { await rm(home, { recursive: true, force: true }); } diff --git a/tools/lib/desktop-swift.ts b/tools/lib/desktop-swift.ts index 3b36292..e3aa1bd 100644 --- a/tools/lib/desktop-swift.ts +++ b/tools/lib/desktop-swift.ts @@ -2,6 +2,7 @@ import { readdir } from "node:fs/promises"; import { join } from "node:path"; export const desktopTarget = "arm64-apple-macosx14.0"; +export const desktopRuntimeExecutables = ["abridge-desktop", "abridge-desktop-http"] as const; export async function desktopSwiftTargets(root: string) { const native = join(root, "apps/desktop/native"); @@ -11,6 +12,14 @@ export async function desktopSwiftTargets(root: string) { .sort() .map((name) => join(runtime, name)); const swift6 = ["-swift-version", "6", "-target", desktopTarget]; + const deviceRuntime = [ + ...swift6, + "-import-objc-header", + join(runtime, "cua_driver_abi.h"), + ...sources, + "-framework", + "ApplicationServices", + ]; return { aBridge: [ @@ -18,19 +27,14 @@ export async function desktopSwiftTargets(root: string) { desktopTarget, join(native, "aBridge.swift"), join(native, "main.swift"), + join(runtime, "DeviceServerTransport.swift"), "-framework", "AppKit", "-framework", "ApplicationServices", ], - "abridge-desktop": [ - ...swift6, - "-import-objc-header", - join(runtime, "cua_driver_abi.h"), - ...sources, - "-framework", - "ApplicationServices", - ], + "abridge-desktop": deviceRuntime, + "abridge-desktop-http": [...deviceRuntime, "-D", "ABRIDGE_CONFIRMED_HTTP"], "abridge-updater": [...swift6, join(runtime, "Updater.swift"), join(runtime, "UpdaterMain.swift")], }; } diff --git a/tools/tests/native-admission.test.ts b/tools/tests/native-admission.test.ts index 69a0ef4..ce2efc7 100644 --- a/tools/tests/native-admission.test.ts +++ b/tools/tests/native-admission.test.ts @@ -52,6 +52,7 @@ test( "Computer", "Executor", "DeviceServerSession", + "DeviceServerTransport", "Client", ].map((name) => join(runtime, name + ".swift")), join(root, "tools/fixtures/native-admission.swift"), diff --git a/tools/tests/native-lifecycle.test.ts b/tools/tests/native-lifecycle.test.ts index d81acca..641231f 100644 --- a/tools/tests/native-lifecycle.test.ts +++ b/tools/tests/native-lifecycle.test.ts @@ -28,9 +28,15 @@ test( "-swift-version", "6", "-parse-as-library", - ...["JSON", "Contract", "Storage", "LocalControl", "DeviceServerSession", "Authorization"].map( - (name) => join(root, `apps/desktop/native/runtime/${name}.swift`), - ), + ...[ + "JSON", + "Contract", + "Storage", + "LocalControl", + "DeviceServerTransport", + "DeviceServerSession", + "Authorization", + ].map((name) => join(root, `apps/desktop/native/runtime/${name}.swift`)), join(root, "tools/fixtures/native-lifecycle.swift"), "-lsqlite3", "-o", From 82c9d9dfcf6ecdd8ed06fdf66aefda4d0f8f2235 Mon Sep 17 00:00:00 2001 From: Wenjie Zhang Date: Wed, 25 Nov 2026 01:16:19 +0800 Subject: [PATCH 6/7] fix(desktop): confirm device key rejection before revoking --- apps/desktop/native/runtime/Client.swift | 36 +++++++++++--- apps/desktop/native/runtime/Contract.swift | 5 ++ apps/desktop/tests/native-client.test.ts | 28 +++++++++++ apps/server/src/server.ts | 15 +++++- apps/server/tests/server.test.ts | 55 ++++++++++++++++++++++ docs/architecture.md | 2 +- packages/protocol/src/desktop-contract.ts | 1 + packages/protocol/src/index.ts | 4 ++ 8 files changed, 137 insertions(+), 9 deletions(-) diff --git a/apps/desktop/native/runtime/Client.swift b/apps/desktop/native/runtime/Client.swift index ecd1c17..d8152e5 100644 --- a/apps/desktop/native/runtime/Client.swift +++ b/apps/desktop/native/runtime/Client.swift @@ -92,6 +92,7 @@ actor DeviceClient { if config.revoked == true { try? await sleepMilliseconds(100); continue } do { try await connect(); backoff = 1 } catch { + if status == "online" { backoff = 1 } if !stopping && status != "revoked" { switch error as? ConnectionFailure { case .revoked(let message)?: @@ -172,19 +173,31 @@ actor DeviceClient { try await receive(frame) } } catch { - throw connectionFailure(error, socket: ws) + throw await connectionFailure(error, socket: ws) } } /// 连接状态只发布本机定义的诊断,HTTP 响应正文和 WebSocket 关闭原因始终留在传输层。 - private func connectionFailure(_ cause: Error, socket ws: URLSessionWebSocketTask) -> ConnectionFailure { + private func connectionFailure(_ cause: Error, socket ws: URLSessionWebSocketTask) async -> ConnectionFailure { if let failure = cause as? ConnectionFailure { return failure } if let failure = cause as? DesktopError, failure.code == "status_write_failed" { return .unavailable(failure.message) } - let responseStatus = (ws.response as? HTTPURLResponse)?.statusCode + let response = ws.response as? HTTPURLResponse + if let response, contract.isDeviceKeyRejection(response) { + return .revoked("\(deviceCredentialRejected)(HTTP 401)") + } + if status == "connecting", response == nil || response?.statusCode == 401 { + // URLSession can surface a failed upgrade without its HTTP response. Ask the same Server. + let identity = await deviceIdentityResponse() + if let identity, contract.isDeviceKeyRejection(identity) { + return .revoked("\(deviceCredentialRejected)(HTTP 401)") + } + if response?.statusCode == 401 || identity?.statusCode == 401 { + return .unavailable("设备连接需要认证,请检查反向代理是否转发 WebSocket 的 Authorization,以及管理台中的设备凭据(HTTP 401)") + } + } let message: String - if responseStatus == 401 { return .revoked("\(deviceCredentialRejected)(HTTP 401)") } - if status == "connecting", let code = responseStatus, code != 101 { + if status == "connecting", let code = response?.statusCode, code != 101 { switch code { case 200..<300, 400, 404, 426: message = "Server 未建立 WebSocket 连接,请检查 Server 地址和反向代理的 WebSocket 转发(HTTP \(code))" @@ -194,8 +207,8 @@ actor DeviceClient { } else if status == "online", monotonicSeconds() - lastAck >= lease { message = "等待 Server 心跳确认超时,请检查网络及 Server 是否运行" } else if let network = cause as? URLError, network.code != .cancelled { - if status == "connecting", [.badServerResponse, .cannotParseResponse].contains(network.code) { - message = "Server 返回了无效的 WebSocket 握手响应,请检查 Server 地址和反向代理的 WebSocket 转发" + if status == "connecting", [.badServerResponse, .cannotParseResponse, .networkConnectionLost].contains(network.code) { + message = "设备连接未完成 WebSocket 握手,请检查 Server 和反向代理的认证与 WebSocket 转发" } else { message = deviceServerNetworkFailure(network) } @@ -206,6 +219,15 @@ actor DeviceClient { } return .unavailable(message) } + private func deviceIdentityResponse() async -> HTTPURLResponse? { + guard !stopping, let url = URL(string: config.url + "/api/device") else { return nil } + var request = URLRequest(url: url, timeoutInterval: 2) + request.setValue("Bearer \(key)", forHTTPHeaderField: "Authorization") + let session = deviceServerSession(timeout: 2) + defer { session.invalidateAndCancel() } + guard let (_, response) = try? await session.bytes(for: request) else { return nil } + return response as? HTTPURLResponse + } private func next(_ ws: URLSessionWebSocketTask, timeout: Double) async throws -> JSONObject { let timer = Task { try await sleepMilliseconds(timeout * 1000); ws.cancel(with: .goingAway, reason: nil) } defer { timer.cancel() } diff --git a/apps/desktop/native/runtime/Contract.swift b/apps/desktop/native/runtime/Contract.swift index 67fe38f..00f4e35 100644 --- a/apps/desktop/native/runtime/Contract.swift +++ b/apps/desktop/native/runtime/Contract.swift @@ -17,6 +17,11 @@ struct NativeContract: Sendable { var protocolVersion: String { data.string("protocol")! } var desktopCapabilities: [String] { data.array("desktopCapabilities")!.compactMap(\.string) } var capabilities: [String] { data.array("capabilities")!.compactMap(\.string) } + func isDeviceKeyRejection(_ response: HTTPURLResponse) -> Bool { + guard response.statusCode == 401, let rejection = data.object("deviceKeyRejection"), + let header = rejection.string("header"), let value = rejection.string("value") else { return false } + return response.value(forHTTPHeaderField: header) == value + } func limit(_ name: String) -> Double { data.object("limits")!.number(name)! } func requiredCapabilities(_ tool: String, _ arguments: JSONObject) -> Set { guard let capability = data.object("toolCapabilities")?.string(tool) else { return [] } diff --git a/apps/desktop/tests/native-client.test.ts b/apps/desktop/tests/native-client.test.ts index 8dd460a..34b4f73 100644 --- a/apps/desktop/tests/native-client.test.ts +++ b/apps/desktop/tests/native-client.test.ts @@ -15,6 +15,7 @@ import { setTimeout as delay } from "node:timers/promises"; import { WebSocketServer, type WebSocket } from "ws"; import { DESKTOP_AUTH_CALLBACK_PATH, + DEVICE_KEY_REJECTION, VERSION, deviceAuthorizationCancelSchema, deviceAuthorizationRequestSchema, @@ -59,6 +60,7 @@ async function fixture({ let name = "Fixture Mac", responseId = "fixture", socketKey = deviceKey; + let revokedKey: string | undefined; let upgradeStatus: number | undefined; let renameResponse: { status: number; body: string } | undefined; const requests: { @@ -107,6 +109,17 @@ async function fixture({ } assert.equal(request.url, "/api/device"); assert.equal(request.headers.authorization, `Bearer ${deviceKey}`); + if (request.method === "GET") { + if (revokedKey && request.headers.authorization === `Bearer ${revokedKey}`) { + response.setHeader(DEVICE_KEY_REJECTION.header, DEVICE_KEY_REJECTION.value); + response.writeHead(401).end(); + return; + } + if (upgradeStatus === 401) { + response.writeHead(401).end(); + return; + } + } if (request.method === "PATCH" && renameResponse) { response.writeHead(renameResponse.status).end(renameResponse.body); return; @@ -278,6 +291,7 @@ async function fixture({ upgradeStatus = value; }, rotateDeviceKey() { + revokedKey = socketKey; socketKey = "abr_device_rotated_fixture"; }, set renameResponse(value: { status: number; body: string } | undefined) { @@ -655,9 +669,23 @@ test( await until(async () => (await f.cli("status")).connection === "online"); assert.equal((await f.cli("status")).error, ""); + f.upgradeStatus = 401; + f.peer.terminate(); + await expectConnectionError("offline", /需要认证.*反向代理.*HTTP 401/); + assert.notEqual(JSON.parse(await readFile(join(f.directory, "config.json"), "utf8")).revoked, true); + f.upgradeStatus = undefined; + await until(async () => (await f.cli("status")).connection === "online"); + assert.equal((await f.cli("status")).error, ""); + + const beforeRotation = f.requests.length; f.rotateDeviceKey(); f.peer.terminate(); await expectConnectionError("revoked", /HTTP 401/); + assert.ok( + f.requests + .slice(beforeRotation) + .some(({ method, path }) => method === "GET" && path === "/api/device"), + ); assert.equal(JSON.parse(await readFile(join(f.directory, "config.json"), "utf8")).revoked, true); } finally { await f.close(); diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index d6adfe5..547dd96 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -7,6 +7,7 @@ import { NodeStreamableHTTPServerTransport } from "@modelcontextprotocol/node"; import { z } from "zod"; import { VERSION, + DEVICE_KEY_REJECTION, MAX_MESSAGE_BYTES, capabilitySchema, agentConnectionInputSchema, @@ -202,8 +203,20 @@ export async function createServer(config: ServerConfig) { `${name}=${token}; HttpOnly; SameSite=Strict; Path=/; Max-Age=${maxAge}${sameOrigin(request).startsWith("https:") ? "; Secure" : ""}`, ); } - app.setErrorHandler((error, _request, reply) => { + app.setErrorHandler((error, request, reply) => { if (error instanceof BridgeError) { + const path = request.routeOptions.url; + if ( + error.status === 401 && + error.code === "unauthorized" && + request.method === "GET" && + (path === "/api/device" || path === "/ws/device") + ) { + // A proxy can remove Authorization. Mark only a Device Key received and rejected here. + if (bearer(request).startsWith("abr_device_")) + reply.header(DEVICE_KEY_REJECTION.header, DEVICE_KEY_REJECTION.value); + if (path === "/ws/device") reply.header("connection", "close"); + } reply.code(error.status).send({ error: { code: error.code, message: error.message } }); return; } diff --git a/apps/server/tests/server.test.ts b/apps/server/tests/server.test.ts index ac5c644..2f910e8 100644 --- a/apps/server/tests/server.test.ts +++ b/apps/server/tests/server.test.ts @@ -1,11 +1,13 @@ import { test } from "node:test"; import assert from "node:assert/strict"; +import { get, type IncomingMessage } from "node:http"; import { mkdtemp, rm } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { once } from "node:events"; import { setTimeout as delay } from "node:timers/promises"; import { WebSocket } from "ws"; +import { DEVICE_KEY_REJECTION } from "@abridge/protocol"; import { createServer } from "../src/server.js"; import { commandOutputPage, characterLength } from "../src/command-output.js"; import { contentResponse } from "../src/mcp.js"; @@ -129,6 +131,59 @@ test("HTTP bootstrap, exact origin scopes, account auth, and same-data-dir proce } }); +test("device credential checks mark a rejected Device Key and leave missing auth unmarked", async () => { + const f = await fixture(); + try { + const owner = await f.store.createUser("websocket-auth-user", "fixture-password-123"); + const computer = f.store.createDevice(owner.id, "Fixture Mac", ["shell"], "computer"); + const browser = f.store.createDevice(owner.id, "Fixture Browser", ["browser"], "browser"); + f.store.rotateDevice(computer.device.id); + for (const [key, marker] of [ + [undefined, undefined], + [f.adminToken, undefined], + [computer.key, DEVICE_KEY_REJECTION.value], + [browser.key, DEVICE_KEY_REJECTION.value], + ] as const) { + const response = await new Promise((resolve, reject) => { + const request = get( + f.url + "/ws/device", + { + agent: false, + signal: AbortSignal.timeout(3000), + headers: { + connection: "Upgrade", + upgrade: "websocket", + "sec-websocket-version": "13", + "sec-websocket-key": "dGhlIHNhbXBsZSBub25jZQ==", + ...(key ? { authorization: "Bearer " + key } : {}), + }, + }, + (reply) => { + reply.resume(); + resolve(reply); + }, + ); + request.once("error", reject); + request.once("upgrade", (_reply, socket) => { + socket.destroy(); + reject(Error("Invalid device credentials must be rejected before upgrading")); + }); + }); + assert.equal(response.statusCode, 401); + assert.equal(response.headers[DEVICE_KEY_REJECTION.header], marker); + + if (key === browser.key) continue; + const identity = await fetch(f.url + "/api/device", { + headers: key ? { authorization: "Bearer " + key } : {}, + }); + assert.equal(identity.status, 401); + assert.equal(identity.headers.get(DEVICE_KEY_REJECTION.header), marker ?? null); + } + } finally { + await f.dispose(); + } +}); + test("device names are editable by their account or device key while capabilities stay client-controlled", async () => { const f = await fixture(); try { diff --git a/docs/architecture.md b/docs/architecture.md index 56d4c4e..35d27ef 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -234,4 +234,4 @@ macOS App 包含 AppKit 主程序、Swift 设备客户端、更新器、共享 macOS 的设备进程使用系统 URLSession 连接用户指定的 Server。HTTPS、WSS 和回环连接由使用系统默认 ATS 策略的 `abridge-desktop` 处理。经 Origin 确认的远端 HTTP 和 WS 由单独签名的 `abridge-desktop-http` 处理,只有这个进程包含 ATS 例外。绑定和启动时,设备进程在连接前复核所选传输方式。更新器也使用系统默认的 ATS 策略。 -设备 WebSocket 握手的访问拒绝(HTTP 403)按普通连接错误重试。Server 的凭据拒绝(HTTP 401)或已建立连接收到的撤销消息会停止自动重连,直至重新绑定。 +设备 WebSocket 握手的 HTTP 401/403 通常按连接错误重试。如果系统未提供握手响应或只返回普通 401,Mac 客户端会向同一 Server 发起有时限的 `GET /api/device` 验证。Server 收到并拒绝设备凭据时,HTTP 401 包含 `abridge-device-auth: invalid_device_key`。带这个标记的 401 和已建立连接收到的撤销消息会停止自动重连,直至重新绑定。反向代理需要传递设备请求的 Authorization 和 Server 的认证错误标记。 diff --git a/packages/protocol/src/desktop-contract.ts b/packages/protocol/src/desktop-contract.ts index 1931974..a98b28e 100644 --- a/packages/protocol/src/desktop-contract.ts +++ b/packages/protocol/src/desktop-contract.ts @@ -19,6 +19,7 @@ export function desktopContract() { return { version: p.VERSION, protocol: p.PROTOCOL_VERSION, + deviceKeyRejection: p.DEVICE_KEY_REJECTION, capabilities: p.CAPABILITIES, desktopCapabilities: p.DESKTOP_CAPABILITIES, toolCapabilities: p.TOOL_CAPABILITIES, diff --git a/packages/protocol/src/index.ts b/packages/protocol/src/index.ts index ff91bee..a37dd03 100644 --- a/packages/protocol/src/index.ts +++ b/packages/protocol/src/index.ts @@ -66,6 +66,10 @@ export const adminOverviewSchema = z.object({ }); export type AdminOverview = z.infer; export const PROTOCOL_VERSION = "abridge/1"; +export const DEVICE_KEY_REJECTION = { + header: "abridge-device-auth", + value: "invalid_device_key", +} as const; export const OBSERVATION_SECONDS = 60; export const DESKTOP_OBSERVATION_SECONDS = 120; export type DesktopFocusStatus = "confirmed" | "unconfirmed"; From f234bb43cf069f736b6403439be676b8bfca35f3 Mon Sep 17 00:00:00 2001 From: Wenjie Zhang Date: Wed, 25 Nov 2026 01:17:29 +0800 Subject: [PATCH 7/7] test(desktop): rotate the key in the runtime revocation fixture --- apps/desktop/tests/native-client.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/desktop/tests/native-client.test.ts b/apps/desktop/tests/native-client.test.ts index 34b4f73..91979a8 100644 --- a/apps/desktop/tests/native-client.test.ts +++ b/apps/desktop/tests/native-client.test.ts @@ -855,7 +855,7 @@ test( await f.cli("control", "stop"); for (let i = 1; i < 8; i++) assert.equal((await f.result(`busy_${i}`)).status, "outcome_unknown"); assert.equal((await f.cli("status")).active_operations, 0); - f.upgradeStatus = 401; + f.rotateDeviceKey(); f.peer.terminate(); const revoked = await until(async () => { const status = await f.cli("status");