From 851538bdcd00baa59245713cffe69bafec7adc34 Mon Sep 17 00:00:00 2001 From: shawn Date: Tue, 13 Oct 2026 23:24:12 +0800 Subject: [PATCH 1/6] feat: support optional enrollment keys on custom servers --- README.md | 2 +- README_CN.md | 2 +- Sources/LocalShare/AppState.swift | 7 +- Sources/LocalShare/Lang.swift | 15 ++-- Sources/LocalShare/RemoteAgent.swift | 3 + Sources/LocalShare/SettingsScreen.swift | 2 +- .../LocalShareTests/AppStateRemoteTests.swift | 77 +++++++++++++++++++ docs/ARCHITECTURE.md | 2 +- server/README.md | 2 +- website/server/codex-deploy.md | 2 +- website/server/connect-client.md | 20 ++++- website/server/deploy-cdn.md | 2 +- website/server/deploy-ip.md | 4 +- website/server/deploy-nginx.md | 2 +- website/server/deployment.md | 32 +++++++- website/server/index.md | 4 +- 16 files changed, 151 insertions(+), 27 deletions(-) diff --git a/README.md b/README.md index a1d212b..6f38b31 100644 --- a/README.md +++ b/README.md @@ -43,7 +43,7 @@ The QR code points to something like `http://192.168.x.x:8080/?t=` ### Remote browser sharing -Choose files or send text, then click Internet Sharing → Connect and send the link to a visitor. The built-in service is `https://share.fairydog.net`; first use registers an independent device credential in Keychain. Keep your Mac online. Public connections use HTTPS/WSS, and the relay can read shared content. Remote files are read-only; receiving text over the internet is separate and off by default. LAN permissions remain independent. For self-hosting, enter your Server address and administrator-issued enrollment key in Settings → Network. See the [internet-sharing plan](docs/REMOTE_SHARING_PLAN.md). +Choose files or send text, then click Internet Sharing → Connect and send the link to a visitor. The built-in service is `https://share.fairydog.net`; first use registers an independent device credential in Keychain. Keep your Mac online. Public connections use HTTPS/WSS, and the relay can read shared content. Remote files are read-only; receiving text over the internet is separate and off by default. LAN permissions remain independent. For self-hosting, enter your Server address in Settings → Network. An administrator-issued enrollment key is required unless the Server enables automatic registration with `--registration`, in which case you can leave it blank. See the [Client connection guide](website/server/connect-client.md). ## Terminal usage diff --git a/README_CN.md b/README_CN.md index 0c13e7b..7ab3572 100644 --- a/README_CN.md +++ b/README_CN.md @@ -43,7 +43,7 @@ ### 远程浏览器分享 -选择文件或发送文本后,点击「互联网分享 → 连接」,把链接发给访问者。App 内置默认服务 `https://share.fairydog.net`,首次启用自动注册,凭据存入 Keychain;Mac 需保持在线。公网使用 HTTPS/WSS,中继可读取内容。远程文件只读,远程收文本独立且默认关闭,局域网权限不受影响。自托管用户可在「设置 → 网络」填写服务器地址和管理员配对码。详见[互联网分享方案](docs/REMOTE_SHARING_PLAN.md)。 +选择文件或发送文本后,点击「互联网分享 → 连接」,把链接发给访问者。App 内置默认服务 `https://share.fairydog.net`,首次启用自动注册,凭据存入 Keychain;Mac 需保持在线。公网使用 HTTPS/WSS,中继可读取内容。远程文件只读,远程收文本独立且默认关闭,局域网权限不受影响。自托管用户在「设置 → 网络」填写服务器地址;默认需要管理员提供的配对码,Server 通过 `--registration` 开放自动注册后可留空。详见[连接 Client](website/server/connect-client.md)。 ## 终端用法 diff --git a/Sources/LocalShare/AppState.swift b/Sources/LocalShare/AppState.swift index e9b539b..3a6c1b4 100644 --- a/Sources/LocalShare/AppState.swift +++ b/Sources/LocalShare/AppState.swift @@ -320,14 +320,15 @@ final class AppState: ObservableObject { localBaseURL: localShareBaseURL, localToken: token, deviceName: Host.current().localizedName ?? "Mac", lang: lang, localRelayToken: server?.remoteRequestToken ?? "", receivingText: remoteTextInboxEnabled, - automaticRegistration: remoteSettings.usesDefaultService) + automaticRegistration: enrollmentKey.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) } func pairRemote(enrollmentKey: String) async -> String? { guard let serverURL = remoteSettings.serverURL else { return L.remoteConfigHint(lang) } do { try await remoteAgent.pair(serverURL: serverURL, enrollmentKey: enrollmentKey, - deviceName: Host.current().localizedName ?? "Mac", lang: lang) + deviceName: Host.current().localizedName ?? "Mac", lang: lang, + automaticRegistration: enrollmentKey.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) remotePaired = remoteAgent.isPaired(for: remoteSettings.serverURL) remoteEnrollmentKey = "" remoteError = nil @@ -390,7 +391,7 @@ final class AppState: ObservableObject { remoteAgent.connect(serverURL: serverURL, enrollmentKey: "", localBaseURL: localShareBaseURL, localToken: token, deviceName: Host.current().localizedName ?? "Mac", lang: lang, localRelayToken: server?.remoteRequestToken ?? "", receivingText: remoteTextInboxEnabled, - automaticRegistration: remoteSettings.usesDefaultService) + automaticRegistration: true) } private func startNetworkMonitoring() { diff --git a/Sources/LocalShare/Lang.swift b/Sources/LocalShare/Lang.swift index 819d1eb..c558795 100644 --- a/Sources/LocalShare/Lang.swift +++ b/Sources/LocalShare/Lang.swift @@ -106,7 +106,7 @@ enum L: CaseIterable { case tailscaleTitle, tailscaleDescMissing // 设置 —— 远程访问 - case remoteServerAddress, remoteEnrollmentKey, remotePairedPlaceholder, remoteSave, remoteSaved + case remoteServerAddress, remoteEnrollmentKey, remoteEnrollmentOptional, remotePairedPlaceholder, remoteSave, remoteSaved case remotePair, remotePairing, remotePairSucceeded case remoteConnect, remoteDisconnect, remoteForget, remotePairHint case remoteDefaultService, remoteCustomService, remoteUseDefault, remoteReceiveText, localReceiveText, remotePrivacy, remoteGuide @@ -123,7 +123,7 @@ enum L: CaseIterable { // 远程访问 case remoteAccess, remoteAccessDesc, remoteConfigHint case remoteConnecting, remoteOnline, remoteOffline, remoteReadOnly, scanCaptionRemote - case remoteEnrollmentRequired, remoteInvalidCredentials, remoteEnrollmentRejected + case remoteEnrollmentRequired, remoteInvalidCredentials, remoteEnrollmentRejected, remoteRegistrationClosed case remoteLocalUnavailable, remoteInvalidRequest, remoteServerError // 设置 —— 外观 @@ -299,6 +299,7 @@ enum L: CaseIterable { case .remoteConnectionFailed: return ("无法连接服务器,请检查网络和服务器状态", "Could not connect to the server. Check your network and the server's status.") case .remoteServerAddress: return ("服务器地址", "Server Address") case .remoteEnrollmentKey: return ("配对码", "Enrollment Key") + case .remoteEnrollmentOptional: return ("可选", "Optional") case .remotePairedPlaceholder: return ("已配对", "Paired") case .remoteSave: return ("保存", "Save") case .remoteSaved: return ("已保存", "Saved") @@ -308,8 +309,8 @@ enum L: CaseIterable { case .remoteConnect: return ("连接", "Connect") case .remoteDisconnect: return ("断开", "Disconnect") case .remoteForget: return ("忘记服务器", "Forget Server") - case .remotePairHint: return ("一次性配对码由服务器管理员提供", - "Get a one-time enrollment key from the server administrator") + case .remotePairHint: return ("服务器开放自动注册时可留空,否则向管理员获取配对码", + "Leave blank if the server allows automatic registration; otherwise, ask the administrator for a key") case .portEmptyMsg: return ("请输入端口号", "Enter a port number") case .portNotNumberMsg: return ("端口需为数字", "Port must be a number") @@ -330,8 +331,8 @@ enum L: CaseIterable { case .remoteAccess: return ("互联网分享", "Internet Sharing") case .remoteAccessDesc: return ("Mac 需保持在线", "Keep your Mac online") - case .remoteConfigHint: return ("在设置 → 网络中填写服务器地址和配对码", - "Enter the server address and enrollment key in Settings → Network") + case .remoteConfigHint: return ("在设置 → 网络中选择默认服务或填写服务器地址", + "Choose the default service or enter a server address in Settings → Network") case .remoteConnecting: return ("连接中", "Connecting") case .remoteOnline: return ("在线", "Online") case .remoteOffline: return ("已断开 · 将自动重试", "Offline · retrying") @@ -342,6 +343,8 @@ enum L: CaseIterable { "The Server address or device credential is invalid.") case .remoteEnrollmentRejected: return ("服务器拒绝了配对请求", "The Server rejected the enrollment request.") + case .remoteRegistrationClosed: return ("服务器未开放自动注册,请向管理员获取配对码", + "Automatic registration is disabled. Ask the server administrator for an enrollment key.") case .remoteLocalUnavailable: return ("本机分享未运行。", "The local share is not running.") case .remoteInvalidRequest: return ("远程请求路径无效。", "The remote request path is invalid.") case .remoteServerError: return ("LocalShare Server 无法完成请求。", diff --git a/Sources/LocalShare/RemoteAgent.swift b/Sources/LocalShare/RemoteAgent.swift index 1417782..2fdfe47 100644 --- a/Sources/LocalShare/RemoteAgent.swift +++ b/Sources/LocalShare/RemoteAgent.swift @@ -447,6 +447,9 @@ final class RemoteAgent: NSObject { let session = URLSession(configuration: .ephemeral, delegate: RemoteEnrollmentDelegate(), delegateQueue: nil) defer { session.finishTasksAndInvalidate() } let (data, response) = try await session.data(for: request) + if automaticRegistration, (response as? HTTPURLResponse)?.statusCode == 404 { + throw RemoteDisplayError(message: L.remoteRegistrationClosed(lang)) + } if let code = (response as? HTTPURLResponse)?.statusCode, [429, 503].contains(code) { throw RemoteDisplayError(message: L.remoteLimitReached(lang)) } diff --git a/Sources/LocalShare/SettingsScreen.swift b/Sources/LocalShare/SettingsScreen.swift index 0f7fff4..a9c3eb4 100644 --- a/Sources/LocalShare/SettingsScreen.swift +++ b/Sources/LocalShare/SettingsScreen.swift @@ -254,7 +254,7 @@ struct SettingsScreen: View { if remoteCustomServer { remoteField(title: L.remoteServerAddress(lang), text: $remoteServerText) remoteField(title: L.remoteEnrollmentKey(lang), text: $remoteKeyText, top: true, secure: true, - placeholder: remotePaired ? L.remotePairedPlaceholder(lang) : "", + placeholder: remotePaired ? L.remotePairedPlaceholder(lang) : L.remoteEnrollmentOptional(lang), disabled: remotePaired) if !remotePaired { Text(L.remotePairHint(lang)).font(.sans(11.5)).foregroundStyle(t.inkMute) diff --git a/Tests/LocalShareTests/AppStateRemoteTests.swift b/Tests/LocalShareTests/AppStateRemoteTests.swift index 022ab4c..1bf306f 100644 --- a/Tests/LocalShareTests/AppStateRemoteTests.swift +++ b/Tests/LocalShareTests/AppStateRemoteTests.swift @@ -5,6 +5,83 @@ import Swifter @testable import LocalShare final class AppStateRemoteTests: XCTestCase { + @MainActor func testCustomServerRegistersAndReusesCredentialsWithBlankKey() async throws { + var keychain: SecKeychain? + var status = SecKeychainStatus() + try XCTSkipIf(SecKeychainCopyDefault(&keychain) != errSecSuccess || keychain == nil, + "login keychain is unavailable") + try XCTSkipIf(SecKeychainGetStatus(keychain!, &status) != errSecSuccess || + status & SecKeychainStatus(kSecUnlockStateStatus) == 0, + "login keychain must be unlocked for credential integration testing") + let relay = HttpServer() + let lock = NSLock() + var registrations = 0 + relay["/api/v1/register"] = { request in + let message = try? JSONDecoder().decode(RemoteWireMessage.self, from: Data(request.body)) + XCTAssertEqual(message?.enrollmentKey, "") + lock.withLock { registrations += 1 } + return .ok(.text("{\"device_id\":\"test\",\"device_token\":\"test-token\"}")) + } + relay["/api/v1/enroll"] = { _ in + XCTFail("a blank key must use automatic registration") + return .unauthorized + } + relay["/api/v1/agent"] = websocket(text: { socket, raw in + if (try? JSONDecoder().decode(RemoteWireMessage.self, from: Data(raw.utf8)))?.type == "share.start" { + socket.writeText("{\"type\":\"share.ready\",\"share_url\":\"http://127.0.0.1/share/test/\"}") + } + }, connected: { $0.writeText("{\"type\":\"hello\",\"protocol\":2}") }) + try relay.start(0, forceIPv4: true) + defer { relay.stop() } + let base = URL(string: "http://127.0.0.1:\(try relay.port())")! + try XCTSkipIf(try RemoteKeychain.value(for: RemoteKeychain.deviceAccount(for: base)) != nil, + "test address already has credentials") + let preferences = Preferences() + defer { preferences.restore() } + let state = AppState() + defer { + state.stop() + state.forgetRemoteDevice() + } + state.saveRemoteSettings(RemoteSettings(serverAddress: base.absoluteString)) + state.setSharedText("test") + _ = try await request(state, path: "/ls/text") + state.connectRemote(enrollmentKey: " \n") + _ = try await publishedURL(state) + XCTAssertEqual(lock.withLock { registrations }, 1) + XCTAssertTrue(state.remotePaired) + + state.disconnectRemote() + state.connectRemote(enrollmentKey: "") + _ = try await publishedURL(state) + XCTAssertEqual(lock.withLock { registrations }, 1) + + state.forgetRemoteDevice() + let error = await state.pairRemote(enrollmentKey: " ") + XCTAssertNil(error) + XCTAssertTrue(state.remotePaired) + XCTAssertEqual(lock.withLock { registrations }, 2) + } + + @MainActor func testCustomServerRequiresKeyWhenAutomaticRegistrationIsClosed() async throws { + let relay = HttpServer() + relay["/api/v1/register"] = { _ in .notFound } + relay["/api/v1/enroll"] = { _ in + XCTFail("a blank key must use automatic registration") + return .unauthorized + } + try relay.start(0, forceIPv4: true) + defer { relay.stop() } + let preferences = Preferences() + defer { preferences.restore() } + let state = AppState() + defer { state.stop() } + state.saveRemoteSettings(RemoteSettings(serverAddress: "http://127.0.0.1:\(try relay.port())")) + let error = await state.pairRemote(enrollmentKey: "") + XCTAssertEqual(error, L.remoteRegistrationClosed(state.lang)) + XCTAssertFalse(state.remotePaired) + } + @MainActor func testColdLaunchRestoresDraftWithoutPublishing() async throws { let preferences = Preferences() defer { preferences.restore() } diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index be09870..7f40437 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -139,7 +139,7 @@ The ticket keeps one primary address and folds Bonjour hostname, Tailscale Magic ### Remote Sharing -The default service is `https://share.fairydog.net`. Explicit Connect automatically registers a device; credentials are kept per server in Keychain. Self-hosting uses one-time enrollment keys. `RemoteAgent` opens an outbound WebSocket to `/api/v1/agent` and publishes the current share. Temporary connection failures retry with a 1–60 second capped backoff; invalid credentials and protocol mismatches stop retries. Pending connection attempts are cancelled and checked against a generation before saving credentials or opening a socket. +The default service is `https://share.fairydog.net`. Explicit Connect automatically registers a device; credentials are kept per server in Keychain. Self-hosting uses one-time enrollment keys by default. Leaving the key blank requests automatic registration, which requires the Server's `--registration` flag; supplied keys always use enrollment. `RemoteAgent` opens an outbound WebSocket to `/api/v1/agent` and publishes the current share. Temporary connection failures retry with a 1–60 second capped backoff; invalid credentials and protocol mismatches stop retries. Pending connection attempts are cancelled and checked against a generation before saving credentials or opening a socket. The Server combines the Control Plane and Data Relay on one public port. Browser requests use `/share//...`; the Server sends them over the existing WebSocket to the Client, which calls its local `FileServer` and streams the response back. The Client keeps the existing token and traversal logic as the single source of file-serving truth. Remote files are read-only; optional text reception permits only `POST /ls/text` with a 64 KiB body limit and defaults off. A process-local random credential marks relay requests so LAN upload and text permissions remain independent. Cold launch never publishes automatically. Connect/Disconnect controls the session while Forget Server removes only that server's Keychain credential. Generated media URLs stay inside the share mount; batch downloads use POST and are shown only in LAN mode. diff --git a/server/README.md b/server/README.md index e927542..4c088bc 100644 --- a/server/README.md +++ b/server/README.md @@ -23,7 +23,7 @@ curl --fail --max-time 5 http://127.0.0.1:18080/healthz 在 Client 的「设置 → 网络 → 使用自托管服务器」填写回环地址和一次性配对码,配对后在文件或文本页连接。HTTP 仅适合回环测试,跨机器使用 HTTPS。 -自动注册测试可追加 `--registration`,通过 `POST /api/v1/register` 创建独立设备凭据。自托管默认关闭该入口。普通用户使用 App 内置默认服务,不需要管理 Server。 +追加 `--registration` 可开放自动注册,通过 `POST /api/v1/register` 创建独立设备凭据。自托管默认关闭该入口,首次连接需要一次性配对码;开放后,App 的配对码可留空。运营 App 内置默认服务时必须开启该参数,默认服务用户无需填写配对码。 ## 生产部署和管理 diff --git a/website/server/codex-deploy.md b/website/server/codex-deploy.md index 14d0257..c098acf 100644 --- a/website/server/codex-deploy.md +++ b/website/server/codex-deploy.md @@ -7,7 +7,7 @@ description: 复制一段提示,让 Codex 按 LocalShare 官方 Skill 部署 可以把下面这段话发给 Codex,并指定目标 Linux 服务器。Codex 会先检查环境,给出适合的部署方案,经过你确认后执行。 - + 三种流程的手动步骤见[安装与部署](./deployment)。只使用 IP 时申请 IP 证书;已有 Nginx 时复用代理和续期;已有 CDN 时确认中继直连还是经过 CDN。 diff --git a/website/server/connect-client.md b/website/server/connect-client.md index a344db7..aa2a069 100644 --- a/website/server/connect-client.md +++ b/website/server/connect-client.md @@ -17,9 +17,20 @@ description: 使用默认公共服务或一次配对的自托管服务器,让 默认服务的可用性取决于公共中继是否在线。若之前设置了自托管,在「设置 → 网络」点击「使用默认服务」即可切回。 +默认服务无需填写服务器地址或配对码。运营该服务时,Server 必须使用 `--registration` 开放自动注册。 + ## 使用自托管服务器 -### 1. 首次配对 +### 1. 首次连接 + +配对码是否必填,取决于 Server 是否开放自动注册: + +| Server 配置 | 配对码 | +| --- | --- | +| 默认配置,未加 `--registration` | 首次连接必填,由管理员生成 | +| 已加 `--registration` | 可留空,App 自动注册并保存设备凭据 | + +具体配置步骤见[选择设备注册方式](./deployment#_3-选择设备注册方式)。如果服务器已开放自动注册,跳过下面的 `key create`,直接填写服务器地址并将配对码留空。 先完成 [Server 部署](./deployment),确认公开地址的 `/healthz` 返回 200,再在服务器上生成一次性配对码: @@ -32,9 +43,9 @@ sudo -u localshare /usr/local/bin/localshare-server key create --name macbook | 字段 | 内容 | | --- | --- | | 服务器地址 | HTTPS 基地址,如 `https://1.2.3.4` 或 `https://share.example.com`;自定义端口需一起填写 | -| 配对码 | 上面命令生成的一次性 Enrollment Key | +| 配对码 | 一次性 Enrollment Key;服务器开放自动注册时可留空 | -地址不带额外路径或查询参数。点击「配对」即可保存设备凭据;也可点击「保存」,在分享页首次连接时完成配对。 +地址不带额外路径或查询参数。点击「配对」即可保存设备凭据;也可点击「保存」,在分享页首次连接时完成注册。有配对码时使用该码,留空时请求自动注册。 配对码只使用一次,App 将后续连接所需的设备凭据保存在 macOS 钥匙串中。接收者无需配对码。 @@ -49,7 +60,7 @@ Mac 和 LocalShare 需要保持运行并联网。远程文件只读;接收文 - 点击「断开」,当前远程链接立即失效,保留设备配对。 - 更换分享内容或 Server 重启后,需要使用新链接。 - App 冷启动不会自动公开内容;准备好分享后再点击「连接」。 -- 自托管设置中的「忘记服务器」会删除设备凭据,下次需新的配对码。 +- 自托管设置中的「忘记服务器」会删除设备凭据;下次连接时重新自动注册,或使用新的配对码。 分享内容实时经过中继,中继可读取内容,不保存文件。将远程链接发给需要访问的人即可。 @@ -58,6 +69,7 @@ Mac 和 LocalShare 需要保持运行并联网。远程文件只读;接收文 | --- | --- | | 无法连接服务器 | 从另一网络访问 `<服务器地址>/healthz`,确认 HTTPS 证书有效、入口可达 | | 配对失败 | 配对码是否已使用;用 `key create` 生成新码 | +| 提示服务器未开放自动注册 | 填写管理员提供的配对码;管理员也可通过 `--registration` 开放自动注册 | | 「连接」不可用 | 是否已选择文件、发送文本或开启远程收文本 | | 健康检查通过,App 仍无法上线 | 检查代理与 CDN 是否支持 WebSocket,是否拦截 App 请求 | | 分享链接无法打开 | 是否已断开、更换内容或重启 Server;重新发送当前链接 | diff --git a/website/server/deploy-cdn.md b/website/server/deploy-cdn.md index c41d64c..96a8a02 100644 --- a/website/server/deploy-cdn.md +++ b/website/server/deploy-cdn.md @@ -79,7 +79,7 @@ sudo systemctl reload nginx curl --fail --max-time 10 https://share.example.com/healthz ``` -健康检查返回 200 后,[生成配对码](./deployment#_3-配对与分享)并[连接 Client](./connect-client),用另一网络的浏览器完成以下验证: +健康检查返回 200 后,[选择设备注册方式](./deployment#_3-选择设备注册方式)并[连接 Client](./connect-client),用另一网络的浏览器完成以下验证: 1. 打开分享链接,查看目录并下载一个文件。 2. 保持连接几分钟,再查看文本或下载文件,确认 WebSocket 持续可用。 diff --git a/website/server/deploy-ip.md b/website/server/deploy-ip.md index 14a79f7..f764c90 100644 --- a/website/server/deploy-ip.md +++ b/website/server/deploy-ip.md @@ -114,10 +114,10 @@ curl --fail --max-time 10 https://1.2.3.4/healthz ## 5. 在 LocalShare 中使用 -[生成配对码](./deployment#_3-配对与分享),服务器地址填 `https://1.2.3.4`,然后[连接 Client](./connect-client)。接收者直接在浏览器打开分享链接。 +[选择设备注册方式](./deployment#_3-选择设备注册方式),服务器地址填 `https://1.2.3.4`,然后[连接 Client](./connect-client)。默认使用配对码;Server 开放自动注册后,配对码可留空。接收者直接在浏览器打开分享链接。 ::: details 进阶:之后换成域名 把域名的 A 记录指向该公网 IP,再为域名申请证书,将 `--public-url` 改为域名地址并更新证书配置。续期 hook 也需指向新证书。 -更换服务器地址后,Client 需用新的配对码连接。若已有 Nginx,可以改用 [Nginx 方案](./deploy-nginx)。 +更换服务器地址后,Client 需重新自动注册或使用新的配对码连接。若已有 Nginx,可以改用 [Nginx 方案](./deploy-nginx)。 ::: diff --git a/website/server/deploy-nginx.md b/website/server/deploy-nginx.md index 2766d17..587a6b2 100644 --- a/website/server/deploy-nginx.md +++ b/website/server/deploy-nginx.md @@ -123,4 +123,4 @@ sudo certbot renew --cert-name share.example.com --dry-run --run-deploy-hooks ## 5. 在 LocalShare 中使用 -[生成配对码](./deployment#_3-配对与分享),服务器地址填 `https://share.example.com`,然后[连接 Client](./connect-client)。 +[选择设备注册方式](./deployment#_3-选择设备注册方式),服务器地址填 `https://share.example.com`,然后[连接 Client](./connect-client)。默认使用配对码;Server 开放自动注册后,配对码可留空。 diff --git a/website/server/deployment.md b/website/server/deployment.md index b1b20d5..3514756 100644 --- a/website/server/deployment.md +++ b/website/server/deployment.md @@ -65,7 +65,16 @@ sudo install -d -o localshare -g localshare -m 0700 /var/lib/localshare - [已有 Nginx + Let’s Encrypt](./deploy-nginx) - [已接入 EdgeOne 等 CDN](./deploy-cdn) -## 3. 配对与分享 +## 3. 选择设备注册方式 + +Server 默认使用一次性配对码。是否允许免配对码连接,由 Server 的 `--registration` 参数决定;设置了域名或 HTTPS 地址不会自动开启注册。 + +| 方式 | Server 配置 | App 操作 | +| --- | --- | --- | +| 配对码注册(默认) | 不加 `--registration` | 首次填写管理员提供的配对码 | +| 自动注册 | 加 `--registration` | 配对码留空,App 自动获取并保存设备凭据 | + +### 使用配对码 服务启动且公开地址的 `/healthz` 验证通过后,生成一个一次性配对码: @@ -75,6 +84,25 @@ sudo -u localshare /usr/local/bin/localshare-server key create --name macbook 在 LocalShare 的「设置 → 网络 → 使用自托管服务器」填入 HTTPS 地址和配对码。之后只需在分享页点击「连接」,将生成的链接发给接收者。详见[连接 Client](./connect-client)。 +### 开放自动注册 + +在 systemd 服务的 `ExecStart` 末尾加上 `--registration`。例如,使用同机 Nginx 的完整启动命令是: + +```ini +ExecStart=/usr/local/bin/localshare-server serve --listen 127.0.0.1:18080 --public-url https://share.example.com --behind-proxy --registration +``` + +修改后执行: + +```bash +sudo systemctl daemon-reload +sudo systemctl restart localshare-server +``` + +此方式允许访问这个 Server 的 App 自助注册,无需执行 `key create`。自托管用户填写服务器地址,配对码留空,点击「配对」或保存后在分享页点击「连接」。已注册设备会复用保存的凭据。 + +App 内置默认服务通过自动注册连接;运营默认服务的 Server 也必须加上 `--registration`。使用默认服务的用户无需填写地址或配对码。 + ## 日常维护 升级前备份二进制和服务配置,保留状态目录。直接 TLS 模式续期后要重启 Server;Nginx 模式只需重新加载 Nginx。**Server 重启会使当前分享链接失效**,Client 重连后会获得新链接。 @@ -109,5 +137,5 @@ sudo -u localshare /usr/local/bin/localshare-server device prune 例如整体限制为 1 MiB/s,可追加 `--total-bytes-per-second 1048576`。修改后执行 `systemctl daemon-reload` 和 `systemctl restart localshare-server`。`/healthz` 的累计转发字节数会在重启后归零,实际流量账单以云平台为准。 -自托管默认使用配对码。运营供用户自助连接的公共服务时,才追加 `--registration`;设备容量和注册频率等完整参数见 [Server README](https://github.com/rrbe/LocalShare/tree/master/server)。 +设备容量和注册频率等完整参数见 [Server README](https://github.com/rrbe/LocalShare/tree/master/server)。 ::: diff --git a/website/server/index.md b/website/server/index.md index 0d6e6fa..e9fb40e 100644 --- a/website/server/index.md +++ b/website/server/index.md @@ -7,14 +7,14 @@ description: LocalShare Server 为不同网络之间的临时文件和文本分 LocalShare Server 把远程浏览器的请求转发到 Mac 上的 LocalShare,让不同网络中的人也能打开当前分享。发送端运行 LocalShare,接收端只需浏览器。 -普通用户可直接使用 App 内置默认服务;自托管用户在设置中更换服务器地址,首次用配对码连接。公网使用 HTTPS/WSS,中继可读取内容,分享内容不落盘。 +普通用户可直接使用 App 内置默认服务;自托管用户在设置中更换服务器地址,通过配对码或服务器开放的自动注册连接。公网使用 HTTPS/WSS,中继可读取内容,分享内容不落盘。 ## 它负责什么

设备配对

-

默认服务自动完成注册。自托管使用一次性配对码,配对后 App 保存设备凭据,后续无需再次输入。

+

默认服务自动完成注册。自托管默认使用一次性配对码;Server 开放自动注册后,配对码可留空。App 保存设备凭据,供后续连接使用。

请求中继

From 8ef7fa4f21f464da9913034cb2a7158a5736e2c6 Mon Sep 17 00:00:00 2001 From: shawn Date: Tue, 13 Oct 2026 23:24:27 +0800 Subject: [PATCH 2/6] fix: show remote text reception only on the text screen --- Sources/LocalShare/RemoteAccessCard.swift | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/Sources/LocalShare/RemoteAccessCard.swift b/Sources/LocalShare/RemoteAccessCard.swift index b1e7725..3620339 100644 --- a/Sources/LocalShare/RemoteAccessCard.swift +++ b/Sources/LocalShare/RemoteAccessCard.swift @@ -48,11 +48,13 @@ struct RemoteAccessCard: View { .font(.sans(11.5)).foregroundStyle(t.inkMute) .fixedSize(horizontal: false, vertical: true) } - HStack { - Text(L.remoteReceiveText(state.lang)).font(.sans(12.5)).foregroundStyle(t.ink) - Spacer() - ToggleSwitch(t: t, isOn: state.remoteTextInboxEnabled) { - state.setRemoteTextInboxEnabled(!state.remoteTextInboxEnabled) + if state.screen == .text { + HStack { + Text(L.remoteReceiveText(state.lang)).font(.sans(12.5)).foregroundStyle(t.ink) + Spacer() + ToggleSwitch(t: t, isOn: state.remoteTextInboxEnabled) { + state.setRemoteTextInboxEnabled(!state.remoteTextInboxEnabled) + } } } HStack { From 9c889cc89fa817cc9e1d7342be6c327dfb969bbf Mon Sep 17 00:00:00 2001 From: shawn Date: Wed, 14 Oct 2026 01:42:00 +0800 Subject: [PATCH 3/6] feat: unify sharing addresses and access mode controls --- DESIGN.md | 8 +- Sources/LocalShare/AppState.swift | 90 ++++--- Sources/LocalShare/Components.swift | 87 ------- Sources/LocalShare/HomeScreen.swift | 1 - Sources/LocalShare/Lang.swift | 28 +- Sources/LocalShare/NoNetworkScreen.swift | 3 +- Sources/LocalShare/RemoteAccessCard.swift | 97 ++++--- Sources/LocalShare/SettingsScreen.swift | 8 +- Sources/LocalShare/ShareAddress.swift | 12 +- Sources/LocalShare/ShareAddressList.swift | 242 ++++++++++++++++++ Sources/LocalShare/ShareScreen.swift | 33 +-- Sources/LocalShare/TextScreen.swift | 31 +-- .../LocalShareTests/AppStateRemoteTests.swift | 44 +++- docs/ARCHITECTURE.md | 9 +- 14 files changed, 465 insertions(+), 228 deletions(-) create mode 100644 Sources/LocalShare/ShareAddressList.swift diff --git a/DESIGN.md b/DESIGN.md index bf5b8cd..57db898 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -133,7 +133,11 @@ New icons must keep the same visual weight and 16px grid. - **QR**: decorative placeholder in mocks, deterministic pseudo QR, white background, rounded corners, foreground `#1a1813` (dark mode `#0e0c09`). **Replace with a real QR code in implementation**, but keep size, radius, white background, and padding. - **CopyPill**: `field` rounded bar. Left side is a mono address with middle ellipsis and a full-address hover tooltip. Right side has copy (green check for 1.3s after success) and open-in-browser buttons; expand/collapse appears only when the full address does not fit on one line. Expanded addresses wrap without a fixed row height. -- File tickets and the home drop zone use `Scan to access on the same Wi-Fi`. Text captions reflect direction: `Scan to view text on the same Wi-Fi`, `Scan to send text to this Mac on the same Wi-Fi`, or `Scan to view or send text on the same Wi-Fi` when both channels are active. +- File tickets show the QR code's network scope beneath the code. Text captions reflect direction: `Scan to view text`, `Scan to send text to this Mac`, or `Scan to view or send text`, followed by the network scope. +- **Share address list**: one bordered list below the QR code, with thin dividers between Local Network, Internet, and Tailscale, in that order. Local IP remains visible while internet sharing is active. Collapse the hostname by default behind a narrow, softly faded Gaussian-blurred preview at the bottom of the LAN addresses, with a centered chevron. Keep it below the URL row with a small gap. The expanded list retains a centered collapse chevron. Clicking an address row selects its QR code. Each row has a label and separate expand, copy, and browser-open controls. Highlight the selected QR entry with `accentSoft`. Enabling a network preserves the current QR selection; disabling or losing the selected entry chooses the first available address, preferring LAN. +- Internet title, access hint, connection dot, and Switch share one line. Online = green, connecting = amber, failed/offline = red; status text is available through hover and accessibility only. Show the actual share link rather than the relay configuration address. Label the public address “Using Relay Service | domain”. Truncate a long domain before the other elements. Show a green verification seal only for the exact host share.fairydog.net; keep the seal visible. Retain actionable errors and a yellow warning with an alert icon: the relay can read shared content, so use a trusted relay. +- Tailscale has one Switch for both MagicDNS and IP addresses. Hide the entire group and its Settings control when Tailscale is not detected. Turning it off keeps the group header and hides its addresses. +- Access-code presentation is a share-level setting. Place a Share Link / Access Code segmented selector above the QR code. Reserve an equal-height row immediately below it for the share-link hint or access code, keeping the QR position stable when switching modes. LAN/Tailscale display their origins in access-code mode while QR codes retain their authenticated URLs; public links retain their relay credentials. --- @@ -201,7 +205,7 @@ Browser navigation to `.md(.markdown)` / `.json(.geojson)` / `.csv(.tsv)` render Screen sections, top to bottom: -1. **QR card**: service running with URL -> QRCard (172x172, padding 18, radius 14) + direction-specific caption + CopyPill. When the service is idle, show one line: `Share text or enable receiving to show the QR code`, without an empty-state card. Preserve the network warning when offline. +1. **QR card**: service running with URL -> QRCard (172x172, padding 18, radius 14) + direction-specific caption + network scope + shared address list. The Internet group contains the optional internet text-receive Switch; it appears only on Text Transfer. When idle, show `Share text or enable receiving to show the QR code` and keep the network controls available. Preserve the network warning when offline. 2. **Send text card**: `surface` radius 16, padding 16, `line` border. `Send` section label -> `PlainTextEditor` (`field`, radius 12, **mono 13**, min-height 118, placeholder `Enter or paste text`, compatible with Chinese IME, accent caret) -> PrimaryBtn "Share" or "Update"; show "Withdraw" GhostBtn when already shared. 3. **Receive text row**: `surface` radius 14, padding 14. Title + Switch, with no persistent helper copy. Opt-in and off by default. 4. **Inbox card**: visible only when receiving is enabled or messages exist. Header = accent status dot + title + unread badge + Clear action. List shows up to 12 items, then a count. Each row has TextGlyph, source device/IP and relative time, text preview up to 3 selectable lines, copy success check, and delete button. diff --git a/Sources/LocalShare/AppState.swift b/Sources/LocalShare/AppState.swift index 3a6c1b4..03997d4 100644 --- a/Sources/LocalShare/AppState.swift +++ b/Sources/LocalShare/AppState.swift @@ -25,15 +25,21 @@ final class AppState: ObservableObject { @Published var sharedItems: [URL] = [] // 当前分享的项:0=空、1=单项、N=多选 @Published var sharedIsFile = false // 仅单项有意义:true=单个文件,false=单个文件夹 @Published var sharedDetail: String? // 人类可读元数据:文件→大小,文件夹/多选→项数 - @Published var sharedText: String? // 当前广播的一段文本(nil=未分享文本);与 sharedItems 正交 + @Published var sharedText: String? { // 当前广播的一段文本(nil=未分享文本);与 sharedItems 正交 + didSet { restoreQRSelection() } + } @Published var textDraft = "" // 文本编辑器草稿(重启回填、再次编辑用);与 sharedText 解耦 @Published private(set) var autoStopMinutes = ShareAutoStop.defaultMinutes // 0 = never @Published private(set) var customAutoStopMinutes = ShareAutoStop.defaultMinutes @Published private(set) var autoStopAt: Date? - @Published var isRunning = false + @Published var isRunning = false { + didSet { restoreQRSelection() } + } @Published var port: in_port_t = 0 // 实际绑定端口(可能因占用回退而异于 configuredPort) @Published var interfaces: [NetworkInterface] = [] - @Published var selectedInterface: NetworkInterface? + @Published var selectedInterface: NetworkInterface? { + didSet { restoreQRSelection() } + } @Published var lastError: String? @Published var viewerCount = 0 // 最近 45s 内活跃的访客设备数(FileServer 在线感知) @Published var viewers: [ViewerInfo] = [] // 在线访客明细(设备名 / 完整 IP),最近活跃在前 @@ -44,7 +50,9 @@ final class AppState: ObservableObject { @Published var permission = Permission() // read 常开;add 可切(仅单文件夹分享);edit/del 未开放 @Published var configuredPort: in_port_t = 8080 // 用户期望端口(设置页可改,持久化) @Published var recents: [RecentShare] = [] // 最近分享(持久化) - @Published var screen: Screen = .share // 屏幕路由(默认落功能主页) + @Published var screen: Screen = .share { // 屏幕路由(默认落功能主页) + didSet { restoreQRSelection() } + } @Published var wideLayout = false // 当前窗口是否使用宽屏内容布局(仅会话内) @Published var selectedSettingsCategory: SettingsCategory = .network // 设置页分类(仅会话内) @Published var appearance: AppearancePref = .system // 外观:跟随系统 / 浅色 / 深色(持久化) @@ -54,16 +62,27 @@ final class AppState: ObservableObject { @Published var textInboxEnabled = false // 「允许收文本」闸门(默认关,持久化;不限分享形态) @Published var persistReceivedText = false // 「记住收到的文本」(默认关,持久化) @Published var accessCodeEnabled = false // 电脑间手输入口:网址 + 短码(默认关,持久化) - @Published var tailscaleAccessEnabled = false // Tailscale 入站闸门(默认关,持久化) - @Published private(set) var tailscaleStatus: TailscaleStatus? + @Published var tailscaleAccessEnabled = false { // Tailscale 入站闸门(默认关,持久化) + didSet { restoreQRSelection() } + } + @Published private(set) var tailscaleStatus: TailscaleStatus? { + didSet { restoreQRSelection() } + } + @Published private(set) var selectedAddressKind: ShareAddress.Kind = .localIP @Published var cliStatus: CLIInstaller.Status = .notInstalled // 命令行工具安装状态 @Published var remoteSettings = RemoteSettings() @Published var remoteEnrollmentKey = "" // 仅用于首次配对;成功后不落盘 - @Published private(set) var remoteAccessEnabled = false - @Published private(set) var remoteTextInboxEnabled = false + @Published private(set) var remoteAccessEnabled = false { + didSet { restoreQRSelection() } + } + @Published private(set) var remoteTextInboxEnabled = false { + didSet { restoreQRSelection() } + } @Published private(set) var remoteStatus: RemoteAgent.Status = .disconnected @Published private(set) var remotePaired = false - @Published private(set) var remoteShareBaseURL: String? + @Published private(set) var remoteShareBaseURL: String? { + didSet { restoreQRSelection() } + } @Published private(set) var remoteError: String? // GUI 进程仅构造一次,init 末尾自登记;AppDelegate 的 open 事件回调经它触达状态。 @@ -215,26 +234,22 @@ final class AppState: ObservableObject { return makeURL(base: base, authenticated: false) } - private var primaryHost: String? { - selectedInterface?.ip ?? (tailscaleAccessEnabled ? tailscaleStatus?.ipv4 : nil) + var selectedShareAddress: ShareAddress? { + shareAddresses.first { $0.kind == selectedAddressKind } ?? shareAddresses.first } var primaryURL: String? { - if let remoteURL { return remoteURL } - guard isRunning, port != 0, let host = primaryHost else { return nil } - return makeURL(host: host) + selectedShareAddress?.qrURL } // 票据上的手输入口:默认仍显示/复制完整 token URL;访问码模式只给 origin,浏览器再经 /ls/join // 输入短码。二维码始终使用 primaryURL,不因展示模式降低安全性或增加扫码步骤。 var presentedURL: String? { - if let remoteURL { return remoteURL } - guard isRunning, port != 0, let host = primaryHost else { return nil } - return makePresentedURL(host: host) + selectedShareAddress?.url } var presentedAccessCode: String? { - isRunning && remoteURL == nil && accessCodeEnabled ? accessCode : nil + isRunning && accessCodeEnabled ? accessCode : nil } var qrImage: NSImage? { @@ -242,28 +257,43 @@ final class AppState: ObservableObject { return QRCode.image(for: primaryURL) } - // 主地址之外的入口统一收在折叠区。访问码模式下它们只显示 origin,与主地址共用一枚短码; - // 普通模式则保留当前分享路径和 token。Tailscale 两项只在用户显式开放且检测到时出现。 - var otherAddresses: [ShareAddress] { - guard isRunning, port != 0, remoteURL == nil else { return [] } + // 三种网络同时列出;启用网络不改变用户选中的二维码入口。 + var shareAddresses: [ShareAddress] { + guard isRunning, port != 0 else { return [] } var result: [ShareAddress] = [] - if selectedInterface != nil, let hostname = NetworkInfo.localHostName(), hostname != primaryHost { + if let host = selectedInterface?.ip { + result.append(ShareAddress(kind: .localIP, scope: .localNetwork, + url: makePresentedURL(host: host), qrURL: makeURL(host: host))) + } + if selectedInterface != nil, let hostname = NetworkInfo.localHostName() { result.append(ShareAddress(kind: .localHostname, scope: .localNetwork, - url: makePresentedURL(host: hostname))) + url: makePresentedURL(host: hostname), qrURL: makeURL(host: hostname))) + } + if let remoteURL { + result.append(ShareAddress(kind: .publicRelay, scope: .publicInternet, url: remoteURL)) } if tailscaleAccessEnabled, let status = tailscaleStatus { - if let dnsName = status.dnsName, dnsName != primaryHost { + if let dnsName = status.dnsName { result.append(ShareAddress(kind: .tailscaleMagicDNS, scope: .tailscale, - url: makePresentedURL(host: dnsName))) - } - if status.ipv4 != primaryHost { - result.append(ShareAddress(kind: .tailscaleIP, scope: .tailscale, - url: makePresentedURL(host: status.ipv4))) + url: makePresentedURL(host: dnsName), qrURL: makeURL(host: dnsName))) } + result.append(ShareAddress(kind: .tailscaleIP, scope: .tailscale, + url: makePresentedURL(host: status.ipv4), qrURL: makeURL(host: status.ipv4))) } return result } + func selectShareAddress(_ kind: ShareAddress.Kind) { + guard shareAddresses.contains(where: { $0.kind == kind }) else { return } + selectedAddressKind = kind + } + + private func restoreQRSelection() { + guard !shareAddresses.contains(where: { $0.kind == selectedAddressKind }) else { return } + let kind = shareAddresses.first?.kind ?? .localIP + if kind != selectedAddressKind { selectedAddressKind = kind } + } + private func makePresentedURL(host: String) -> String { accessCodeEnabled ? "http://\(host):\(port)" : makeURL(host: host) } diff --git a/Sources/LocalShare/Components.swift b/Sources/LocalShare/Components.swift index 320fbc9..a7ef972 100644 --- a/Sources/LocalShare/Components.swift +++ b/Sources/LocalShare/Components.swift @@ -498,93 +498,6 @@ struct AccessCodePill: View { } } -private struct DisclosureButtonStyle: ButtonStyle { - func makeBody(configuration: Configuration) -> some View { configuration.label } -} - -// 主票据只保留一个首选入口,其它解析方式按需展开,避免长 hostname / MagicDNS 抢走二维码的视觉层级。 -struct OtherAddressesDisclosure: View { - let t: Theme - var lang: Lang - var addresses: [ShareAddress] - @State private var expanded = false - - var body: some View { - VStack(spacing: 0) { - Button { expanded.toggle() } label: { - HStack(spacing: 8) { - Image(systemName: "network").font(.system(size: 12, weight: .semibold)) - Text(L.otherAddresses(lang)).font(.sans(12, .semibold)) - Spacer(minLength: 8) - Text("\(addresses.count)").font(.mono(10.5, .bold)).foregroundStyle(t.inkFaint) - Image(systemName: "chevron.right").font(.system(size: 9, weight: .bold)) - .rotationEffect(.degrees(expanded ? 90 : 0)) - } - .foregroundStyle(t.inkMute) - .contentShape(Rectangle()) - } - .buttonStyle(DisclosureButtonStyle()) - .padding(.horizontal, 12).frame(height: 40) - - if expanded { - Divider().overlay(t.line) - VStack(spacing: 0) { - ForEach(Array(addresses.enumerated()), id: \.element.id) { index, address in - AlternateAddressRow(t: t, lang: lang, address: address) - if index < addresses.count - 1 { Divider().overlay(t.line).padding(.leading, 12) } - } - } - } - } - .background(RoundedRectangle(cornerRadius: 11, style: .continuous).fill(t.surfaceAlt)) - .overlay(RoundedRectangle(cornerRadius: 11, style: .continuous).strokeBorder(t.line, lineWidth: 1)) - } -} - -private struct AlternateAddressRow: View { - let t: Theme - var lang: Lang - var address: ShareAddress - - var body: some View { - VStack(alignment: .leading, spacing: 4) { - HStack(alignment: .firstTextBaseline, spacing: 7) { - Text(title).font(.sans(11.5, .semibold)).foregroundStyle(t.ink) - if let scope { - Text(scope).font(.sans(10.5)).foregroundStyle(t.inkFaint).lineLimit(1) - } - Spacer(minLength: 4) - } - ExpandableAddressLine(t: t, lang: lang, value: address.url, - font: .mono(11.5), color: t.inkMute, - hoverBackdrop: t.surfaceAlt, spacing: 2, onOpen: open) - } - .padding(.leading, 12).padding(.trailing, 5).padding(.vertical, 8) - } - - private var title: String { - switch address.kind { - case .localHostname: return "Hostname" - case .tailscaleMagicDNS: return L.tailscaleMagicDNSAddress(lang) - case .tailscaleIP: return L.tailscaleIPAddress(lang) - case .publicRelay: return L.publicRelayAddress(lang) - } - } - - private var scope: String? { - switch address.scope { - case .localNetwork: return nil - case .tailscale: return L.tailscaleNetworkOnly(lang) - case .publicInternet: return L.publicInternet(lang) - } - } - - private func open() { - guard let url = URL(string: address.url) else { return } - NSWorkspace.shared.open(url) - } -} - // 分享票据上的凭证呈现模式切换;与「改权限」同属轻量就地入口,不抢主操作层级。 struct AccessModeButton: View { let t: Theme diff --git a/Sources/LocalShare/HomeScreen.swift b/Sources/LocalShare/HomeScreen.swift index 88e88ff..8e792d2 100644 --- a/Sources/LocalShare/HomeScreen.swift +++ b/Sources/LocalShare/HomeScreen.swift @@ -57,7 +57,6 @@ struct HomeScreen: View { .overlay(Image(systemName: "arrow.up.to.line").font(.system(size: 24, weight: .medium)).foregroundStyle(t.accent)) .padding(.bottom, 14) Text(L.dropZoneTitle(state.lang)).font(.sans(15.5, .semibold)).foregroundStyle(t.ink) - Text(L.scanCaptionAccess(state.lang)).font(.sans(12.5)).foregroundStyle(t.inkMute).padding(.top, 4) PrimaryButton(t: t, title: L.pickAnyButton(state.lang), systemImage: "doc.badge.plus") { state.pickAny() } .padding(.top, 18) } diff --git a/Sources/LocalShare/Lang.swift b/Sources/LocalShare/Lang.swift index c558795..91f8378 100644 --- a/Sources/LocalShare/Lang.swift +++ b/Sources/LocalShare/Lang.swift @@ -88,10 +88,13 @@ enum L: CaseIterable { // 分享屏 case shareFileTitle // 文件票据二级页标题(与「传递文本」并列) case received, changePerm, useAccessCode, useFullURL, broadcastStopped, selectSource - case sharingKicker, scanCaptionAccess + case sharingKicker case revealShareItems, revealInFinder, viewing case otherAddresses, tailscaleMagicDNSAddress, tailscaleIPAddress, publicRelayAddress case tailscaleNetworkOnly, publicInternet + case localNetwork, sameNetwork, localIPAddress, localHostname, internet, internetAccessHint + case tailscaleAccessHint, showAddressQR, shareLink + case accessEnabled, accessDisabled, shareLinkHint, accessCodeMode, usingRelayService // 未接入网络 case noNetwork, noNetworkHint @@ -249,7 +252,6 @@ enum L: CaseIterable { case .broadcastStopped: return ("已停止广播", "Broadcast stopped") case .selectSource: return ("选择信号源", "Choose source") case .sharingKicker: return ("正在分享", "Sharing") - case .scanCaptionAccess: return ("同一 Wi-Fi 扫码访问", "Scan to access on the same Wi-Fi") case .revealShareItems: return ("在 Finder 中显示分享项", "Show shared items in Finder") case .revealInFinder: return ("在 Finder 中显示", "Show in Finder") case .viewing: return ("正在浏览", "Viewing") @@ -259,6 +261,20 @@ enum L: CaseIterable { case .publicRelayAddress: return ("公网中继", "Public Relay") case .tailscaleNetworkOnly: return ("仅限 Tailscale", "Tailscale only") case .publicInternet: return ("可通过公网访问", "Available over the internet") + case .localNetwork: return ("局域网", "Local Network") + case .sameNetwork: return ("同一网络", "Same network") + case .localIPAddress: return ("IP 地址", "IP Address") + case .localHostname: return ("本机名称", "Hostname") + case .internet: return ("互联网", "Internet") + case .internetAccessHint: return ("公共网络 · Mac 需保持在线", "Public network · Keep your Mac online") + case .tailscaleAccessHint: return ("对方需连接 Tailscale", "Recipient needs Tailscale") + case .showAddressQR: return ("显示二维码", "Show QR Code") + case .shareLinkHint: return ("扫码或打开分享链接", "Scan the QR code or open the share link") + case .accessCodeMode: return ("访问码", "Access Code") + case .usingRelayService: return ("使用中继服务", "Using Relay Service") + case .shareLink: return ("分享链接", "Share Link") + case .accessEnabled: return ("开启", "On") + case .accessDisabled: return ("关闭", "Off") case .noNetwork: return ("未发现局域网地址", "No local network address") case .noNetworkHint: return ("局域网访问需要同一 Wi-Fi 或有线网络。", @@ -291,7 +307,7 @@ enum L: CaseIterable { case .remoteUseDefault: return ("使用默认服务", "Use the Default Service") case .localReceiveText: return ("允许局域网收文本", "Receive Text on the Local Network") case .remoteReceiveText: return ("允许通过互联网收文本", "Receive Text over the Internet") - case .remotePrivacy: return ("中继服务可读取分享内容", "The relay can read shared content") + case .remotePrivacy: return ("中继服务可读取分享内容,请使用可信任的中继", "The relay can read shared content. Use a relay you trust.") case .remoteGuide: return ("使用说明", "User Guide") case .remoteProtocolMismatch: return ("服务器版本不匹配,请更新服务器", "Server version mismatch. Update the server.") case .remoteLimitReached: return ("服务额度已用完,请稍后再试", "Service limit reached. Try again later.") @@ -404,12 +420,12 @@ enum L: CaseIterable { case .textShareAction: return ("分享", "Share") case .textUpdateAction: return ("更新", "Update") case .sharingTextKicker: return ("正在分享文本", "Sharing text") - case .scanCaptionText: return ("同一 Wi-Fi 扫码查看文本", "Scan to view text on the same Wi-Fi") + case .scanCaptionText: return ("扫码查看文本", "Scan to view text") case .editTextButton: return ("编辑文本", "Edit Text") case .transferText: return ("传递文本", "Transfer Text") case .sendTextKicker: return ("发送", "Send") - case .scanCaptionTransfer: return ("同一 Wi-Fi 扫码查看或发送文本", "Scan to view or send text on the same Wi-Fi") - case .scanCaptionSend: return ("同一 Wi-Fi 扫码发送到 Mac", "Scan to send text to this Mac on the same Wi-Fi") + case .scanCaptionTransfer: return ("扫码查看或发送文本", "Scan to view or send text") + case .scanCaptionSend: return ("扫码发送到 Mac", "Scan to send text to this Mac") case .textIdleHint: return ("分享文本或开启接收后显示二维码", "Share text or enable receiving to show the QR code") case .retract: return ("撤回", "Retract") diff --git a/Sources/LocalShare/NoNetworkScreen.swift b/Sources/LocalShare/NoNetworkScreen.swift index cbf7363..be1b796 100644 --- a/Sources/LocalShare/NoNetworkScreen.swift +++ b/Sources/LocalShare/NoNetworkScreen.swift @@ -25,7 +25,8 @@ struct NoNetworkScreen: View { .multilineTextAlignment(.center).lineSpacing(3) GhostButton(t: t, title: L.refresh(state.lang), systemImage: "arrow.clockwise") { state.refreshNetwork() } .padding(.top, 4) - RemoteAccessCard(t: t) + if state.isRunning { ShareAccessMode(t: t) } + ShareAddressList(t: t) .padding(.top, 12) Spacer(minLength: 40) } diff --git a/Sources/LocalShare/RemoteAccessCard.swift b/Sources/LocalShare/RemoteAccessCard.swift index 3620339..cfafc26 100644 --- a/Sources/LocalShare/RemoteAccessCard.swift +++ b/Sources/LocalShare/RemoteAccessCard.swift @@ -1,83 +1,83 @@ import SwiftUI +// 统一地址列表中的互联网分组。 struct RemoteAccessCard: View { let t: Theme @EnvironmentObject var state: AppState + var body: some View { - VStack(alignment: .leading, spacing: 10) { - HStack(spacing: 10) { - GlobeLineIcon(color: t.accent) - VStack(alignment: .leading, spacing: 2) { - Text(L.remoteAccess(state.lang)).font(.sans(13.5, .semibold)).foregroundStyle(t.ink) - if !state.remoteAccessEnabled { - Text(L.remoteAccessDesc(state.lang)).font(.sans(11.5)).foregroundStyle(t.inkMute) - } + VStack(alignment: .leading, spacing: 0) { + HStack(spacing: 8) { + Image(systemName: "globe").font(.system(size: 12)).foregroundStyle(t.inkMute) + Text(L.internet(state.lang)).font(.sans(12, .semibold)).foregroundStyle(t.ink) + .fixedSize() + Text(L.internetAccessHint(state.lang)).font(.sans(10.5)).foregroundStyle(t.inkMute) + .lineLimit(1).truncationMode(.tail) + .help(L.internetAccessHint(state.lang)) + Spacer(minLength: 0) + if state.remoteAccessEnabled || state.remoteError != nil { + Circle().fill(remoteStatusColor).frame(width: 6, height: 6) + .help(remoteStatusText) + .accessibilityLabel(Text(remoteStatusText)) } - Spacer(minLength: 8) - if state.remoteAccessEnabled { - GhostButton(t: t, title: L.remoteDisconnect(state.lang), systemImage: "xmark.circle") { - state.disconnectRemote() - } - } else { - GhostButton(t: t, title: L.remoteConnect(state.lang), systemImage: "link") { - state.connectRemote(enrollmentKey: state.remoteEnrollmentKey) - } - .disabled(!state.canEnableRemote) + ToggleSwitch(t: t, isOn: state.remoteAccessEnabled, + locked: !state.remoteAccessEnabled && !state.canEnableRemote) { + if state.remoteAccessEnabled { state.disconnectRemote() } + else { state.connectRemote(enrollmentKey: state.remoteEnrollmentKey) } } + .accessibilityLabel(Text(L.remoteAccess(state.lang))) + .accessibilityValue(Text(state.remoteAccessEnabled ? L.accessEnabled(state.lang) : L.accessDisabled(state.lang))) } - if state.remoteAccessEnabled { - HStack(spacing: 7) { - Text(state.remoteSettings.displayAddress) - .font(.mono(11.5)) - .foregroundStyle(t.inkMute) - .lineLimit(1) - .truncationMode(.middle) - .frame(maxWidth: .infinity, alignment: .leading) - Circle().fill(remoteStatusColor).frame(width: 7, height: 7) - Text(remoteStatusText).font(.sans(11.5, .semibold)).foregroundStyle(t.inkMute) - } - if let error = state.remoteError, !error.isEmpty { - Text(error).font(.sans(11)).foregroundStyle(t.danger).lineLimit(2) - } - } else if let error = state.remoteError, !error.isEmpty { - Text(error) - .font(.sans(11.5)).foregroundStyle(t.danger) + .padding(12) + ForEach(state.shareAddresses.filter { $0.scope == .publicInternet }) { address in + ShareAddressRow(t: t, address: address) + } + if let error = state.remoteError, !error.isEmpty { + Text(error).font(.sans(11)).foregroundStyle(t.danger) .fixedSize(horizontal: false, vertical: true) + .padding(.horizontal, 12).padding(.bottom, 10) } else if !state.remoteSettings.isValid { - Text(L.remoteConfigHint(state.lang)) - .font(.sans(11.5)).foregroundStyle(t.inkMute) + Text(L.remoteConfigHint(state.lang)).font(.sans(11)).foregroundStyle(t.inkMute) .fixedSize(horizontal: false, vertical: true) + .padding(.horizontal, 12).padding(.bottom, 10) } if state.screen == .text { - HStack { - Text(L.remoteReceiveText(state.lang)).font(.sans(12.5)).foregroundStyle(t.ink) - Spacer() + HStack(spacing: 8) { + Text(L.remoteReceiveText(state.lang)).font(.sans(12)).foregroundStyle(t.ink) + Spacer(minLength: 0) ToggleSwitch(t: t, isOn: state.remoteTextInboxEnabled) { state.setRemoteTextInboxEnabled(!state.remoteTextInboxEnabled) } + .accessibilityLabel(Text(L.remoteReceiveText(state.lang))) + .accessibilityValue(Text(state.remoteTextInboxEnabled ? L.accessEnabled(state.lang) : L.accessDisabled(state.lang))) } + .padding(.horizontal, 12).padding(.bottom, 10) } - HStack { - Text(L.remotePrivacy(state.lang)).font(.sans(11)).foregroundStyle(t.inkMute) - Spacer(minLength: 8) - RemoteGuideLink(t: t, lang: state.lang) + if state.remoteAccessEnabled { + HStack(spacing: 8) { + Label(L.remotePrivacy(state.lang), systemImage: "exclamationmark.triangle") + .font(.sans(10.5)).foregroundStyle(t.warn) + .fixedSize(horizontal: false, vertical: true) + Spacer(minLength: 0) + RemoteGuideLink(t: t, lang: state.lang) + } + .padding(.horizontal, 12).padding(.bottom, 10) } } - .padding(14) - .background(RoundedRectangle(cornerRadius: 14, style: .continuous).fill(t.surface)) - .overlay(RoundedRectangle(cornerRadius: 14, style: .continuous).strokeBorder(t.line, lineWidth: 1)) } private var remoteStatusText: String { + if let error = state.remoteError, !state.remoteAccessEnabled { return error } switch state.remoteStatus { case .connecting: return L.remoteConnecting(state.lang) case .connected: return L.remoteOnline(state.lang) case .reconnecting: return L.remoteOffline(state.lang) - case .disconnected: return L.remoteConfigHint(state.lang) + case .disconnected: return L.accessDisabled(state.lang) } } private var remoteStatusColor: Color { + if state.remoteError != nil, !state.remoteAccessEnabled { return t.danger } switch state.remoteStatus { case .connected: return t.ok case .reconnecting: return t.danger @@ -85,7 +85,6 @@ struct RemoteAccessCard: View { case .disconnected: return t.inkFaint } } - } struct RemoteGuideLink: View { diff --git a/Sources/LocalShare/SettingsScreen.swift b/Sources/LocalShare/SettingsScreen.swift index a9c3eb4..99e2d8b 100644 --- a/Sources/LocalShare/SettingsScreen.swift +++ b/Sources/LocalShare/SettingsScreen.swift @@ -217,9 +217,11 @@ struct SettingsScreen: View { } .padding(.vertical, 12) - settingRow(top: true, title: L.tailscaleTitle(lang), desc: tailscaleDescription) { - ToggleSwitch(t: t, isOn: state.tailscaleAccessEnabled) { - state.setTailscaleAccessEnabled(!state.tailscaleAccessEnabled) + if state.tailscaleStatus != nil { + settingRow(top: true, title: L.tailscaleTitle(lang), desc: tailscaleDescription) { + ToggleSwitch(t: t, isOn: state.tailscaleAccessEnabled) { + state.setTailscaleAccessEnabled(!state.tailscaleAccessEnabled) + } } } } diff --git a/Sources/LocalShare/ShareAddress.swift b/Sources/LocalShare/ShareAddress.swift index 1ae759c..cd32b62 100644 --- a/Sources/LocalShare/ShareAddress.swift +++ b/Sources/LocalShare/ShareAddress.swift @@ -1,9 +1,9 @@ import Foundation -// 票据里的替代入口保存“完整可打开 URL”,而不是假定都能由 host + 本地 token 拼出。前三种当前 -// 由本机生成;publicRelay 留给未来由中继服务返回不透明公网 URL,当前不会创建或展示。 +// 展示地址与扫码地址分开:访问码模式展示 origin,扫码仍携带完整凭证。 struct ShareAddress: Identifiable, Equatable { enum Kind: String { + case localIP case localHostname case tailscaleMagicDNS case tailscaleIP @@ -19,5 +19,13 @@ struct ShareAddress: Identifiable, Equatable { let kind: Kind let scope: Scope let url: String + let qrURL: String var id: Kind { kind } + + init(kind: Kind, scope: Scope, url: String, qrURL: String? = nil) { + self.kind = kind + self.scope = scope + self.url = url + self.qrURL = qrURL ?? url + } } diff --git a/Sources/LocalShare/ShareAddressList.swift b/Sources/LocalShare/ShareAddressList.swift new file mode 100644 index 0000000..0de42af --- /dev/null +++ b/Sources/LocalShare/ShareAddressList.swift @@ -0,0 +1,242 @@ +import SwiftUI +import AppKit + +// 同一列表内按访问范围分组;网络开关与二维码选择互相独立。 +struct ShareAddressList: View { + let t: Theme + @State private var hostnameExpanded = false + @EnvironmentObject var state: AppState + + var body: some View { + VStack(spacing: 6) { + VStack(spacing: 0) { + if !localAddresses.isEmpty { + localSection + Divider().overlay(t.line) + } + RemoteAccessCard(t: t) + if state.tailscaleStatus != nil { + Divider().overlay(t.line) + tailscaleSection + } + } + .background(RoundedRectangle(cornerRadius: 12, style: .continuous).fill(t.surface)) + .overlay(RoundedRectangle(cornerRadius: 12, style: .continuous).strokeBorder(t.line, lineWidth: 1)) + } + } + + private var localAddresses: [ShareAddress] { + state.shareAddresses.filter { $0.scope == .localNetwork } + } + + private var localSection: some View { + VStack(spacing: 0) { + HStack(spacing: 8) { + Image(systemName: "wifi").font(.system(size: 12)).foregroundStyle(t.inkMute) + Text(L.localNetwork(state.lang)).font(.sans(12, .semibold)) + Text(L.sameNetwork(state.lang)).font(.sans(10.5)).foregroundStyle(t.inkMute) + Spacer(minLength: 0) + } + .foregroundStyle(t.ink) + .padding(12) + ForEach(localAddresses.filter { $0.kind == .localIP || hostnameExpanded }) { address in + ShareAddressRow(t: t, address: address) + } + if localAddresses.contains(where: { $0.kind == .localHostname }) { + hostnameDisclosure + } + } + .padding(.bottom, 4) + } + + private var hostnameDisclosure: some View { + Button { + withAnimation(.easeInOut(duration: 0.18)) { hostnameExpanded.toggle() } + } label: { + Image(systemName: hostnameExpanded ? "chevron.up" : "chevron.down") + .font(.system(size: 9, weight: .semibold)).foregroundStyle(t.inkMute) + .frame(maxWidth: .infinity).frame(height: 16) + .background(alignment: .top) { + if !hostnameExpanded, + let hostname = localAddresses.first(where: { $0.kind == .localHostname }) { + ShareAddressRow(t: t, address: hostname) + .frame(height: 16, alignment: .top).clipped() + .blur(radius: 4) + .mask(LinearGradient(colors: [.white, .clear], startPoint: .top, endPoint: .bottom)) + .allowsHitTesting(false).accessibilityHidden(true) + } + } + .contentShape(RoundedRectangle(cornerRadius: 5, style: .continuous)) + } + .buttonStyle(.plain) + .help(L.localHostname(state.lang)) + .accessibilityLabel(Text(L.localHostname(state.lang))) + .accessibilityValue(Text(hostnameExpanded ? L.collapseAddress(state.lang) : L.expandAddress(state.lang))) + .padding(.horizontal, 6).padding(.top, 1).padding(.bottom, 2) + } + + private var tailscaleSection: some View { + VStack(spacing: 0) { + HStack(spacing: 8) { + Image(systemName: "network").font(.system(size: 12)).foregroundStyle(t.inkMute) + Text("Tailscale").font(.sans(12, .semibold)).foregroundStyle(t.ink) + Text(L.tailscaleAccessHint(state.lang)).font(.sans(10.5)).foregroundStyle(t.inkMute) + .lineLimit(1).truncationMode(.tail) + .help(L.tailscaleAccessHint(state.lang)) + Spacer(minLength: 0) + ToggleSwitch(t: t, isOn: state.tailscaleAccessEnabled) { + state.setTailscaleAccessEnabled(!state.tailscaleAccessEnabled) + } + .accessibilityLabel(Text(L.tailscaleTitle(state.lang))) + .accessibilityValue(Text(state.tailscaleAccessEnabled ? L.accessEnabled(state.lang) : L.accessDisabled(state.lang))) + } + .padding(12) + ForEach(state.shareAddresses.filter { $0.scope == .tailscale }) { address in + ShareAddressRow(t: t, address: address) + } + } + .padding(.bottom, state.tailscaleAccessEnabled && state.isRunning ? 6 : 0) + } + +} + +struct ShareAccessMode: View { + let t: Theme + @EnvironmentObject var state: AppState + + var body: some View { + VStack(spacing: 8) { + HStack(spacing: 4) { + option(L.shareLink, usingCode: false) + option(L.accessCodeMode, usingCode: true) + } + .padding(3) + .background(RoundedRectangle(cornerRadius: 10).fill(t.surfaceAlt)) + .overlay(RoundedRectangle(cornerRadius: 10).strokeBorder(t.line, lineWidth: 1)) + Group { + if let code = state.presentedAccessCode { + AccessCodePill(t: t, lang: state.lang, value: code) + } else { + Text(L.shareLinkHint(state.lang)).font(.sans(14, .medium)).foregroundStyle(t.ink) + .frame(maxWidth: .infinity) + } + } + .frame(height: 40) + } + } + + private func option(_ title: L, usingCode: Bool) -> some View { + let selected = state.accessCodeEnabled == usingCode + return Button { state.setAccessCodeEnabled(usingCode) } label: { + Text(title(state.lang)).font(.sans(12, .semibold)) + .foregroundStyle(selected ? .white : t.inkMute) + .frame(maxWidth: .infinity).frame(height: 30) + .background(RoundedRectangle(cornerRadius: 7).fill(selected ? t.accent : .clear)) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .accessibilityAddTraits(selected ? .isSelected : []) + } +} + +struct ShareAddressRow: View { + let t: Theme + let address: ShareAddress + @EnvironmentObject var state: AppState + @State private var copied = false + @State private var expanded = false + + private var selected: Bool { state.selectedShareAddress?.kind == address.kind } + private var relayHost: String? { + address.kind == .publicRelay ? URL(string: address.url)?.host?.lowercased() : nil + } + + var body: some View { + Button { state.selectShareAddress(address.kind) } label: { + VStack(alignment: .leading, spacing: 3) { + HStack(spacing: 5) { + Text(title).font(.sans(10.5, .medium)) + .foregroundStyle(selected ? t.accent : t.inkMute) + .fixedSize(horizontal: true, vertical: false) + if let host = relayHost { + Text("|").font(.sans(10.5)).foregroundStyle(t.inkMute) + Text(host).font(.sans(10.5)).foregroundStyle(t.inkMute) + .lineLimit(1).truncationMode(.middle).layoutPriority(-1) + .help(host) + if host == URL(string: RemoteSettings.defaultServerAddress)?.host { + Image(systemName: "checkmark.seal.fill").font(.system(size: 11)) + .foregroundStyle(t.ok).fixedSize() + .help(L.remoteDefaultService(state.lang)) + .accessibilityLabel(Text(L.remoteDefaultService(state.lang))) + } + } + if relayHost == nil { Spacer(minLength: 0) } + } + .frame(minHeight: 24).padding(.trailing, 84) + Text(address.url).font(.mono(11.5)).foregroundStyle(t.ink) + .lineLimit(expanded ? nil : 1).truncationMode(.middle) + .multilineTextAlignment(.leading) + .frame(maxWidth: .infinity, alignment: .leading) + } + .padding(.horizontal, 9).padding(.vertical, 6) + .background(RoundedRectangle(cornerRadius: 8, style: .continuous).fill(selected ? t.accentSoft : .clear)) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .help(address.url) + .accessibilityLabel(Text("\(title) · \(address.url)")) + .accessibilityHint(Text(L.showAddressQR(state.lang))) + .accessibilityAddTraits(selected ? .isSelected : []) + .overlay(alignment: .topTrailing) { + HStack(spacing: 4) { + HoverIcon(t: t, + systemImage: expanded ? "arrow.down.right.and.arrow.up.left" : "arrow.up.left.and.arrow.down.right", + color: t.inkMute, + help: expanded ? L.collapseAddress(state.lang) : L.expandAddress(state.lang), + size: 24, iconSize: 12) { expanded.toggle() } + HoverIcon(t: t, systemImage: copied ? "checkmark" : "doc.on.doc", + color: copied ? t.ok : t.inkMute, help: L.copy(state.lang), + size: 24, iconSize: 12) { + NSPasteboard.general.clearContents() + NSPasteboard.general.setString(address.url, forType: .string) + copied = true + DispatchQueue.main.asyncAfter(deadline: .now() + 1.3) { copied = false } + } + HoverIcon(t: t, systemImage: "arrow.up.right", color: t.inkMute, + help: L.openInBrowser(state.lang), size: 24, iconSize: 12) { + if let url = URL(string: address.url) { NSWorkspace.shared.open(url) } + } + } + .padding(.trailing, 9).padding(.top, 6) + } + .padding(.horizontal, 6).padding(.bottom, 3) + } + + private var title: String { + switch address.kind { + case .localIP, .tailscaleIP: return L.localIPAddress(state.lang) + case .localHostname: return L.localHostname(state.lang) + case .tailscaleMagicDNS: return "MagicDNS" + case .publicRelay: return L.usingRelayService(state.lang) + } + } +} + +struct ShareQRScope: View { + let t: Theme + @EnvironmentObject var state: AppState + + var body: some View { + if let address = state.selectedShareAddress { + Text(scopeLabel(address.scope)).font(.sans(11)).foregroundStyle(t.inkMute) + } + } + + private func scopeLabel(_ scope: ShareAddress.Scope) -> String { + switch scope { + case .localNetwork: return "\(L.localNetwork(state.lang)) · \(L.sameNetwork(state.lang))" + case .tailscale: return "Tailscale · \(L.tailscaleAccessHint(state.lang))" + case .publicInternet: return "\(L.internet(state.lang)) · \(L.internetAccessHint(state.lang))" + } + } +} diff --git a/Sources/LocalShare/ShareScreen.swift b/Sources/LocalShare/ShareScreen.swift index 795f19b..ba2c98f 100644 --- a/Sources/LocalShare/ShareScreen.swift +++ b/Sources/LocalShare/ShareScreen.swift @@ -10,12 +10,12 @@ struct ShareScreen: View { @State private var showText = false // 文本编辑弹层(编辑当前分享的文本) private func editText() { showText = true } var body: some View { - let remoteMode = state.remoteURL != nil + let remoteMode = state.selectedShareAddress?.scope == .publicInternet let ps = permSummary(remoteMode ? Permission() : state.effectivePermission, state.lang, remoteMode: remoteMode) ScreenFrame(t: t) { // 二级页头部,与传递文本页同款:← 返回主页 + 标题 +齿轮。运行态/地址在票据正文(QR 说明 + - // CopyPill)已具,头部不再堆 StatusPill,避免与正文重复、并与 TextScreen 一致。 + // 地址列表)已具,头部不再堆 StatusPill,避免与正文重复、并与 TextScreen 一致。 HStack(spacing: 10) { IconButton(t: t, systemImage: "chevron.left", help: L.back(state.lang)) { state.goShare() } Text(L.shareFileTitle(state.lang)).font(.display(21, .semibold)).foregroundStyle(t.ink) @@ -26,7 +26,6 @@ struct ShareScreen: View { } content: { VStack(spacing: 16) { ticket(ps) - RemoteAccessCard(t: t) // 文本与文件共存:在票据下补一张「附带文本」小卡(预览 + 编辑)。纯文本分享则文本就是票据本身。 if state.hasText && !state.isTextOnly { attachedTextCard } if !state.received.isEmpty { receivedCard } @@ -175,7 +174,7 @@ struct ShareScreen: View { state.selectedSettingsCategory = .permission state.openSettings() } label: { - Text(state.remoteURL != nil ? L.changeLocalPerm(state.lang) : L.changePerm(state.lang)) + Text(state.selectedShareAddress?.scope == .publicInternet ? L.changeLocalPerm(state.lang) : L.changePerm(state.lang)) .font(.sans(11)).foregroundStyle(t.accent) }.buttonStyle(.plain) } @@ -204,30 +203,18 @@ struct ShareScreen: View { .overlay(RoundedRectangle(cornerRadius: 14, style: .continuous).strokeBorder(t.line, lineWidth: 1)) } - // 通行区:QR + 说明 + 复制条 + // 通行区:当前入口的二维码 + 按网络分组的完整地址列表。 private var qrPass: some View { let running = state.isRunning - let caption = state.remoteURL != nil ? L.scanCaptionRemote(state.lang) - : (state.isTextOnly ? L.scanCaptionText(state.lang) : L.scanCaptionAccess(state.lang)) return VStack(spacing: 0) { + if running { ShareAccessMode(t: t).padding(.top, 14) } QRCard(image: state.qrImage, size: 172, dimmed: !running).padding(.top, 22) - Text(running ? caption : L.broadcastStopped(state.lang)) - .font(.sans(13, .semibold)).foregroundStyle(t.ink).padding(.top, 14) - CopyPill(t: t, lang: state.lang, value: state.presentedURL ?? "—", - compact: true, onOpen: openInBrowser).padding(.top, 10) - if let code = state.presentedAccessCode { - AccessCodePill(t: t, lang: state.lang, value: code).padding(.top, 7) - } - if !state.otherAddresses.isEmpty { - OtherAddressesDisclosure(t: t, lang: state.lang, addresses: state.otherAddresses) - .padding(.top, 7) - } - if state.remoteURL == nil { - AccessModeButton(t: t, lang: state.lang, usingAccessCode: state.accessCodeEnabled) { - state.setAccessCodeEnabled(!state.accessCodeEnabled) - } - .padding(.top, 6) + if !running || state.isTextOnly { + Text(running ? L.scanCaptionText(state.lang) : L.broadcastStopped(state.lang)) + .font(.sans(13, .semibold)).foregroundStyle(t.ink).padding(.top, 14) } + if running { ShareQRScope(t: t).padding(.top, state.isTextOnly ? 5 : 12) } + ShareAddressList(t: t).padding(.top, 14) AutoStopDeadline(t: t).padding(.top, 8) // 在线访客:小绿点 + 摘要文案;点一下展开全部访客明细(设备名 / 完整 IP)。 // 0 人时整行隐藏(不占位、不留空文案)。 diff --git a/Sources/LocalShare/TextScreen.swift b/Sources/LocalShare/TextScreen.swift index fd53b69..777c80f 100644 --- a/Sources/LocalShare/TextScreen.swift +++ b/Sources/LocalShare/TextScreen.swift @@ -142,6 +142,7 @@ struct TextScreen: View { @State private var draft = "" var body: some View { let lang = state.lang + let showQR = state.isRunning && (state.hasText || state.isReceivingText) && state.qrImage != nil ScreenFrame(t: t) { HStack(spacing: 10) { IconButton(t: t, systemImage: "chevron.left", help: L.back(lang)) { state.goShare() } @@ -152,7 +153,7 @@ struct TextScreen: View { } } content: { VStack(spacing: 16) { - if state.isRunning, state.hasText || state.isReceivingText, state.qrImage != nil { + if showQR { qrCard } else if !state.hasNetwork { noNetworkHint @@ -160,7 +161,10 @@ struct TextScreen: View { Text(L.textIdleHint(lang)).font(.sans(12.5)).foregroundStyle(t.inkMute) .multilineTextAlignment(.center) } - RemoteAccessCard(t: t) + if !showQR { + if state.isRunning { ShareAccessMode(t: t) } + ShareAddressList(t: t) + } composeCard receiveRow if state.isReceivingText || !state.receivedTexts.isEmpty { ReceivedTextsCard(t: t) } @@ -215,27 +219,16 @@ struct TextScreen: View { // 二维码恒指 /ls/text;说明随收发状态表达扫码后的动作。 private var qrCard: some View { let lang = state.lang - let receiving = state.remoteURL != nil ? state.remoteTextInboxEnabled : state.textInboxEnabled - let caption = state.remoteURL != nil ? L.scanCaptionRemote(lang) : (state.hasText + let receiving = state.selectedShareAddress?.scope == .publicInternet ? state.remoteTextInboxEnabled : state.textInboxEnabled + let caption = state.hasText ? (receiving ? L.scanCaptionTransfer(lang) : L.scanCaptionText(lang)) - : L.scanCaptionSend(lang)) + : L.scanCaptionSend(lang) return VStack(spacing: 0) { + ShareAccessMode(t: t).padding(.bottom, 12) QRCard(image: state.qrImage, size: 172, dimmed: !state.isRunning).padding(.top, 4) Text(caption).font(.sans(13, .semibold)).foregroundStyle(t.ink).padding(.top, 14) - CopyPill(t: t, lang: lang, value: state.presentedURL ?? "—", compact: true, onOpen: openInBrowser).padding(.top, 10) - if let code = state.presentedAccessCode { - AccessCodePill(t: t, lang: lang, value: code).padding(.top, 7) - } - if !state.otherAddresses.isEmpty { - OtherAddressesDisclosure(t: t, lang: lang, addresses: state.otherAddresses) - .padding(.top, 7) - } - if state.remoteURL == nil { - AccessModeButton(t: t, lang: lang, usingAccessCode: state.accessCodeEnabled) { - state.setAccessCodeEnabled(!state.accessCodeEnabled) - } - .padding(.top, 6) - } + ShareQRScope(t: t).padding(.top, 5) + ShareAddressList(t: t).padding(.top, 14) AutoStopDeadline(t: t).padding(.top, 8) } .frame(maxWidth: .infinity) diff --git a/Tests/LocalShareTests/AppStateRemoteTests.swift b/Tests/LocalShareTests/AppStateRemoteTests.swift index 1bf306f..1bb034d 100644 --- a/Tests/LocalShareTests/AppStateRemoteTests.swift +++ b/Tests/LocalShareTests/AppStateRemoteTests.swift @@ -5,6 +5,35 @@ import Swifter @testable import LocalShare final class AppStateRemoteTests: XCTestCase { + @MainActor func testAccessCodeAddressesKeepAuthenticatedQRCodes() throws { + let preferences = Preferences() + defer { preferences.restore() } + let state = AppState() + defer { state.stop() } + state.setSharedText("demo") + state.selectedInterface = NetworkInterface(name: "en0", ip: "192.168.1.2") + state.setAccessCodeEnabled(true) + + let address = try XCTUnwrap(state.shareAddresses.first { $0.kind == .localIP }) + XCTAssertEqual(address.url, "http://192.168.1.2:\(state.port)") + XCTAssertEqual(address.qrURL, "http://192.168.1.2:\(state.port)/ls/text?t=\(state.token)") + XCTAssertEqual(state.primaryURL, address.qrURL) + XCTAssertEqual(state.presentedURL, address.url) + + if let hostname = state.shareAddresses.first(where: { $0.kind == .localHostname }) { + state.selectShareAddress(.localHostname) + XCTAssertEqual(state.primaryURL, hostname.qrURL) + XCTAssertEqual(state.presentedURL, hostname.url) + XCTAssertTrue(hostname.qrURL.contains("?t=\(state.token)")) + } + let selected = state.selectedAddressKind + state.selectShareAddress(.publicRelay) + XCTAssertEqual(state.selectedAddressKind, selected, "unavailable addresses cannot be selected") + state.stop() + XCTAssertNil(state.primaryURL) + XCTAssertTrue(state.shareAddresses.isEmpty) + } + @MainActor func testCustomServerRegistersAndReusesCredentialsWithBlankKey() async throws { var keychain: SecKeychain? var status = SecKeychainStatus() @@ -51,9 +80,17 @@ final class AppStateRemoteTests: XCTestCase { XCTAssertEqual(lock.withLock { registrations }, 1) XCTAssertTrue(state.remotePaired) + state.selectedInterface = NetworkInterface(name: "en0", ip: "192.168.1.2") + let local = try XCTUnwrap(state.shareAddresses.first { $0.kind == .localIP }) + XCTAssertEqual(state.primaryURL, local.qrURL, "connecting must preserve the current QR entry") + state.selectShareAddress(.publicRelay) + XCTAssertEqual(state.primaryURL, state.remoteURL) state.disconnectRemote() + XCTAssertEqual(state.selectedAddressKind, .localIP) + XCTAssertEqual(state.primaryURL, local.qrURL) state.connectRemote(enrollmentKey: "") _ = try await publishedURL(state) + XCTAssertEqual(state.primaryURL, local.qrURL, "reconnecting must not switch the QR back to the internet") XCTAssertEqual(lock.withLock { registrations }, 1) state.forgetRemoteDevice() @@ -256,6 +293,11 @@ final class AppStateRemoteTests: XCTestCase { state.connectRemote(enrollmentKey: "test-key") let first = try await publishedURL(state) XCTAssertEqual(messages.last, state.token) + state.selectedInterface = NetworkInterface(name: "en0", ip: "192.168.1.2") + XCTAssertTrue(state.shareAddresses.contains { $0.kind == .localIP }) + XCTAssertTrue(state.shareAddresses.contains { $0.kind == .publicRelay && $0.url == first }) + XCTAssertNotEqual(state.primaryURL, first) + state.selectShareAddress(.publicRelay) XCTAssertEqual(state.primaryURL, first) let republished = expectation(description: "text edits must keep the published link") @@ -358,7 +400,7 @@ final class AppStateRemoteTests: XCTestCase { private let keys = ["autoStopMinutes", "customAutoStopMinutes", "configuredPort", "remoteServerAddress", "remotePairedServerAddresses", "bindSelectedOnly", "tailscaleAccessEnabled", "textInboxEnabled", "persistSharedText", "lastSharedText", "persistReceivedText", - "receivedTexts", "recentShares", "languagePref"] + "receivedTexts", "recentShares", "languagePref", "accessCodeEnabled"] private var saved: [String: Any] = [:] private let lang = Lang.current diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 7f40437..0c5a884 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -27,7 +27,7 @@ The typical crash this project avoids is an arm64 binary that **misses a dynamic | Share model | Three shapes: single folder -> mobile-friendly directory listing, serving `index.html` directly when present; single file -> scan opens the file and sibling files are not exposed; multiple files/folders -> synthetic virtual root listing selected items, with the first path segment mapped to a real URL. All shapes block directory traversal, each item using its own root | | Auth | Every share action creates a random token embedded in the LAN QR URL as `?t=...`; first visit validates it and sets a session cookie. An optional short access code can exchange for that cookie at `/ls/join`, with per-client rate limiting. Remote mode uses separate high-entropy device and share tokens. Changing, stopping, or switching access-code mode rotates the applicable share credentials immediately | | Protocol | LAN and Tailscale use plain HTTP. Remote mode uses the Server's HTTP/WebSocket relay, and the self-hosted Server can terminate TLS when configured with a certificate and key | -| QR code | Uses the public origin while remote mode is active; otherwise uses the selected LAN IP or Tailscale IP when it is the only enabled network. It is generated with CoreImage `CIQRCodeGenerator`; the ticket can fold out the Bonjour hostname and enabled Tailscale alternatives | +| QR code | Uses the selected available address from the LAN, Internet, or Tailscale group. Enabling a network preserves the current selection; losing it falls back to the first available address. CoreImage `CIQRCodeGenerator` generates the authenticated URL; access-code mode changes the displayed address only | | GUI | Single window: functional home screen with drag/drop and picker, Text Transfer entry, and Recent Shares; file ticket, Text Transfer, Settings, and History are secondary pages with back navigation | | Lifecycle | Cold launch does **not** replay the last share or remote switch. The app starts on the home screen; the last share remains in Recent Shares for one-click restart. Closing the window does not quit; process and server continue running, and menu bar activation restores the previous screen. Ports are selected automatically; an enabled remote agent stops on app quit | | Distribution | Xcode ad-hoc signing. The first Gatekeeper approval is handled manually and then remembered by macOS | @@ -71,7 +71,8 @@ LocalShare/ RemoteAgent.swift # Server pairing, Keychain device token, WebSocket relay, reconnect NetworkInfo.swift # getifaddrs -> private IPv4 candidates, Tailscale IP, and .local hostname TailscaleInfo.swift # optional CLI status probe -> Tailscale IPv4 + MagicDNS name - ShareAddress.swift # complete alternate URL + network scope; includes a future opaque public-relay kind + ShareAddress.swift # displayed/authenticated URLs + network scope + ShareAddressList.swift # unified LAN, Internet, and detected Tailscale entries + QR selection QRCode.swift # CoreImage QR -> NSImage, plus terminal ANSI output Token.swift / Mime.swift # Random token and extension -> MIME mapping with charset=utf-8 for text Lang.swift # i18n string tables compiled into the binary: L / LStr / i18nJSON @@ -135,13 +136,13 @@ The GUI no longer exposes a current-network-only toggle and new installations li Tailscale access is persisted but defaults off. `NetworkInfo` detects its IPv4 by the documented `100.64.0.0/10` range rather than an interface-name assumption. When an installed Tailscale CLI is available, `TailscaleInfo` runs `status --json --peers=false` off the main actor with a two-second timeout and extracts `Self.DNSName`; failure degrades to the detected IP only. Enabling Tailscale permits tailnet clients through the request gate. Disabling it keeps the all-interface listener but rejects `100.64/10` clients before auth. -The ticket keeps one primary address and folds Bonjour hostname, Tailscale MagicDNS, and Tailscale IP into `otherAddresses`. In access-code mode each is an origin paired with the shared short code; otherwise each preserves the current path and token. `ShareAddress` stores a complete URL so opaque relay URLs can be represented without being forced into the LAN host/query-token shape. The current remote URL is shown as the primary ticket URL rather than an alternate address. +The ticket lists LAN, Internet, and detected Tailscale addresses together in `shareAddresses`. Internet sharing never hides local addresses or automatically replaces an existing QR selection. `selectedAddressKind` chooses the QR entry; losing or disabling that entry selects the first available address, preferring LAN. `ShareAddress.url` is the displayed/copied URL and `qrURL` is the authenticated scan URL. The share-level Share Link / Access Code selector appears above the QR code. Its hint/code row reserves the same height in both modes so switching leaves the QR position stable. LAN IP remains visible; the hostname starts collapsed and expands through a centered chevron over a narrow, faded blurred preview at the bottom of the LAN addresses. Access-code mode displays LAN/Tailscale origins paired with the shared short code while QR codes keep the full path and token. Public links retain the relay's own credentials. File and Text Transfer screens reuse the same list; only Text Transfer exposes internet text reception. Internet connection states use a colored dot with hover/accessibility text. The public-address subtitle shows “Using Relay Service | domain”, truncating long domains; a green verification seal appears only for the exact host share.fairydog.net, and a yellow alert reminds users that the relay can read shared content and should be trusted. Undetected Tailscale controls are hidden both in the list and Settings. ### Remote Sharing The default service is `https://share.fairydog.net`. Explicit Connect automatically registers a device; credentials are kept per server in Keychain. Self-hosting uses one-time enrollment keys by default. Leaving the key blank requests automatic registration, which requires the Server's `--registration` flag; supplied keys always use enrollment. `RemoteAgent` opens an outbound WebSocket to `/api/v1/agent` and publishes the current share. Temporary connection failures retry with a 1–60 second capped backoff; invalid credentials and protocol mismatches stop retries. Pending connection attempts are cancelled and checked against a generation before saving credentials or opening a socket. -The Server combines the Control Plane and Data Relay on one public port. Browser requests use `/share//...`; the Server sends them over the existing WebSocket to the Client, which calls its local `FileServer` and streams the response back. The Client keeps the existing token and traversal logic as the single source of file-serving truth. Remote files are read-only; optional text reception permits only `POST /ls/text` with a 64 KiB body limit and defaults off. A process-local random credential marks relay requests so LAN upload and text permissions remain independent. Cold launch never publishes automatically. Connect/Disconnect controls the session while Forget Server removes only that server's Keychain credential. Generated media URLs stay inside the share mount; batch downloads use POST and are shown only in LAN mode. +The Server combines the Control Plane and Data Relay on one public port. Browser requests use `/share//...`; the Server sends them over the existing WebSocket to the Client, which calls its local `FileServer` and streams the response back. The Client keeps the existing token and traversal logic as the single source of file-serving truth. Remote files are read-only; optional text reception permits only `POST /ls/text` with a 64 KiB body limit and defaults off. A process-local random credential marks relay requests so LAN upload and text permissions remain independent. Cold launch never publishes automatically. The Internet switch controls the session while Forget Server removes only that server's Keychain credential. Generated media URLs stay inside the share mount; batch downloads use POST and are shown only in LAN mode. Generated browser pages use relative links because the same `FileServer` HTML is mounted both at LAN `/` and remote `/share//`. `share.start` registers a `share_id` generation and every relayed request echoes it; the Client From ec5ac93bd8008388d45fd75d400162a039d9fb20 Mon Sep 17 00:00:00 2001 From: shawn Date: Wed, 14 Oct 2026 01:42:07 +0800 Subject: [PATCH 4/6] fix: clarify automatic sharing stop time --- Sources/LocalShare/AutoStopSettings.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sources/LocalShare/AutoStopSettings.swift b/Sources/LocalShare/AutoStopSettings.swift index a8a197f..a051cb9 100644 --- a/Sources/LocalShare/AutoStopSettings.swift +++ b/Sources/LocalShare/AutoStopSettings.swift @@ -126,6 +126,6 @@ struct AutoStopDeadline: View { formatter.dateStyle = .short formatter.timeStyle = .short let date = formatter.string(from: deadline) - return state.lang == .zh ? "\(date) 关闭分享" : "Stops \(date)" + return state.lang == .zh ? "将于 \(date) 自动关闭分享" : "Sharing will stop automatically at \(date)" } } From 991b29d99db885e8e52fed235b78b0d62cc764cc Mon Sep 17 00:00:00 2001 From: shawn Date: Wed, 14 Oct 2026 01:42:13 +0800 Subject: [PATCH 5/6] docs: update sharing guides and add an interactive demo --- README.md | 2 +- README_CN.md | 2 +- design-demos/share-addresses.html | 425 ++++++++++++++++++++++++++++++ website/server/connect-client.md | 14 +- website/server/deployment.md | 4 +- 5 files changed, 436 insertions(+), 11 deletions(-) create mode 100644 design-demos/share-addresses.html diff --git a/README.md b/README.md index 6f38b31..c70a516 100644 --- a/README.md +++ b/README.md @@ -43,7 +43,7 @@ The QR code points to something like `http://192.168.x.x:8080/?t=` ### Remote browser sharing -Choose files or send text, then click Internet Sharing → Connect and send the link to a visitor. The built-in service is `https://share.fairydog.net`; first use registers an independent device credential in Keychain. Keep your Mac online. Public connections use HTTPS/WSS, and the relay can read shared content. Remote files are read-only; receiving text over the internet is separate and off by default. LAN permissions remain independent. For self-hosting, enter your Server address in Settings → Network. An administrator-issued enrollment key is required unless the Server enables automatic registration with `--registration`, in which case you can leave it blank. See the [Client connection guide](website/server/connect-client.md). +Choose files or send text, then turn on Internet in the address list and send that group’s share link to a visitor. LAN, Internet, and detected Tailscale entries share one list; click an address row to change the scan entry. The built-in service is `https://share.fairydog.net`; first use registers an independent device credential in Keychain. Keep your Mac online. Public connections use HTTPS/WSS, and the relay can read shared content. Remote files are read-only; receiving text over the internet is separate and off by default. LAN permissions remain independent. For self-hosting, enter your Server address in Settings → Network. An administrator-issued enrollment key is required unless the Server enables automatic registration with `--registration`, in which case you can leave it blank. See the [Client connection guide](website/server/connect-client.md). ## Terminal usage diff --git a/README_CN.md b/README_CN.md index 7ab3572..80ecf7e 100644 --- a/README_CN.md +++ b/README_CN.md @@ -43,7 +43,7 @@ ### 远程浏览器分享 -选择文件或发送文本后,点击「互联网分享 → 连接」,把链接发给访问者。App 内置默认服务 `https://share.fairydog.net`,首次启用自动注册,凭据存入 Keychain;Mac 需保持在线。公网使用 HTTPS/WSS,中继可读取内容。远程文件只读,远程收文本独立且默认关闭,局域网权限不受影响。自托管用户在「设置 → 网络」填写服务器地址;默认需要管理员提供的配对码,Server 通过 `--registration` 开放自动注册后可留空。详见[连接 Client](website/server/connect-client.md)。 +选择文件或发送文本后,开启地址列表中的「互联网」开关,把该组的分享链接发给访问者。局域网、互联网和 Tailscale 地址在同一列表中;点击某条地址切换扫码入口。App 内置默认服务 `https://share.fairydog.net`,首次启用自动注册,凭据存入 Keychain;Mac 需保持在线。公网使用 HTTPS/WSS,中继可读取内容。远程文件只读,远程收文本独立且默认关闭,局域网权限不受影响。自托管用户在「设置 → 网络」填写服务器地址;默认需要管理员提供的配对码,Server 通过 `--registration` 开放自动注册后可留空。详见[连接 Client](website/server/connect-client.md)。 ## 终端用法 diff --git a/design-demos/share-addresses.html b/design-demos/share-addresses.html new file mode 100644 index 0000000..2ff17c0 --- /dev/null +++ b/design-demos/share-addresses.html @@ -0,0 +1,425 @@ + + + + + + LocalShare · 分享地址设计 Demo + + + + + +
+ + +
+
LocalShare
+
+ +

分享文件

+ +
+
+
+
+
+
秋日旅行
12 个项目 · 128 MB
只读可下载
+
+
+
+
+
+
局域网 IP 地址的二维码
+ +
局域网 · 同一网络
+
+
+ +
+
+
+ + +
+
+
+ +

+ + + + diff --git a/website/server/connect-client.md b/website/server/connect-client.md index aa2a069..020a3e6 100644 --- a/website/server/connect-client.md +++ b/website/server/connect-client.md @@ -10,10 +10,10 @@ description: 使用默认公共服务或一次配对的自托管服务器,让 ## 使用默认服务 1. 在 LocalShare 中选择文件、文件夹或要分享的文本。 -2. 在分享页的远程访问区域点击「连接」。App 会自动注册并连接默认服务。 -3. 将生成的远程链接或二维码发给接收者。 +2. 在分享页的地址列表中开启「互联网」开关。App 会自动注册并连接默认服务。 +3. 将互联网分组中的分享链接发给接收者;需要二维码时,点击该链接所在的地址行。 -
准备分享 ──▶ 连接 ──▶ 发送链接 ──▶ 对方浏览器打开
+
准备分享 ──▶ 开启互联网 ──▶ 发送链接 ──▶ 对方浏览器打开
默认服务的可用性取决于公共中继是否在线。若之前设置了自托管,在「设置 → 网络」点击「使用默认服务」即可切回。 @@ -51,15 +51,15 @@ sudo -u localshare /usr/local/bin/localshare-server key create --name macbook ### 2. 发布分享 -回到文件或文本页,准备好分享内容后点击「连接」。显示远程地址后,将链接发给接收者。后续使用同一服务器时无需再次输入配对码。 +回到文件或文本页,准备好分享内容后开启「互联网」开关。显示分享链接后,将该链接发给接收者。后续使用同一服务器时无需再次输入配对码。 ## 分享期间 Mac 和 LocalShare 需要保持运行并联网。远程文件只读;接收文本需单独开启「允许通过互联网收文本」,局域网权限保持原设置。 -- 点击「断开」,当前远程链接立即失效,保留设备配对。 +- 关闭「互联网」开关,当前远程链接立即失效,保留设备配对;局域网和 Tailscale 可继续使用。 - 更换分享内容或 Server 重启后,需要使用新链接。 -- App 冷启动不会自动公开内容;准备好分享后再点击「连接」。 +- App 冷启动不会自动公开内容;准备好分享后再开启「互联网」开关。 - 自托管设置中的「忘记服务器」会删除设备凭据;下次连接时重新自动注册,或使用新的配对码。 分享内容实时经过中继,中继可读取内容,不保存文件。将远程链接发给需要访问的人即可。 @@ -70,7 +70,7 @@ Mac 和 LocalShare 需要保持运行并联网。远程文件只读;接收文 | 无法连接服务器 | 从另一网络访问 `<服务器地址>/healthz`,确认 HTTPS 证书有效、入口可达 | | 配对失败 | 配对码是否已使用;用 `key create` 生成新码 | | 提示服务器未开放自动注册 | 填写管理员提供的配对码;管理员也可通过 `--registration` 开放自动注册 | -| 「连接」不可用 | 是否已选择文件、发送文本或开启远程收文本 | +| 「互联网」开关不可用 | 是否已选择文件、发送文本或开启远程收文本 | | 健康检查通过,App 仍无法上线 | 检查代理与 CDN 是否支持 WebSocket,是否拦截 App 请求 | | 分享链接无法打开 | 是否已断开、更换内容或重启 Server;重新发送当前链接 | diff --git a/website/server/deployment.md b/website/server/deployment.md index 3514756..f059da6 100644 --- a/website/server/deployment.md +++ b/website/server/deployment.md @@ -82,7 +82,7 @@ Server 默认使用一次性配对码。是否允许免配对码连接,由 Ser sudo -u localshare /usr/local/bin/localshare-server key create --name macbook ``` -在 LocalShare 的「设置 → 网络 → 使用自托管服务器」填入 HTTPS 地址和配对码。之后只需在分享页点击「连接」,将生成的链接发给接收者。详见[连接 Client](./connect-client)。 +在 LocalShare 的「设置 → 网络 → 使用自托管服务器」填入 HTTPS 地址和配对码。之后只需在分享页开启「互联网」开关,将生成的链接发给接收者。详见[连接 Client](./connect-client)。 ### 开放自动注册 @@ -99,7 +99,7 @@ sudo systemctl daemon-reload sudo systemctl restart localshare-server ``` -此方式允许访问这个 Server 的 App 自助注册,无需执行 `key create`。自托管用户填写服务器地址,配对码留空,点击「配对」或保存后在分享页点击「连接」。已注册设备会复用保存的凭据。 +此方式允许访问这个 Server 的 App 自助注册,无需执行 `key create`。自托管用户填写服务器地址,配对码留空,点击「配对」或保存后在分享页开启「互联网」开关。已注册设备会复用保存的凭据。 App 内置默认服务通过自动注册连接;运营默认服务的 Server 也必须加上 `--registration`。使用默认服务的用户无需填写地址或配对码。 From d55d8912ca4315a81adbb940679bbc23783cabeb Mon Sep 17 00:00:00 2001 From: shawn Date: Wed, 14 Oct 2026 09:18:39 +0800 Subject: [PATCH 6/6] test: run qr address state checks in an async actor context --- Tests/LocalShareTests/AppStateRemoteTests.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Tests/LocalShareTests/AppStateRemoteTests.swift b/Tests/LocalShareTests/AppStateRemoteTests.swift index 1bb034d..c8d6f3e 100644 --- a/Tests/LocalShareTests/AppStateRemoteTests.swift +++ b/Tests/LocalShareTests/AppStateRemoteTests.swift @@ -5,7 +5,7 @@ import Swifter @testable import LocalShare final class AppStateRemoteTests: XCTestCase { - @MainActor func testAccessCodeAddressesKeepAuthenticatedQRCodes() throws { + @MainActor func testAccessCodeAddressesKeepAuthenticatedQRCodes() async throws { let preferences = Preferences() defer { preferences.restore() } let state = AppState()