PasteFerry (隔空贴): clipboard and file sync across macOS, Windows and Linux. Direct-first, end-to-end encrypted. Optional official access: no server to host. Independent self-hosting remains available.
Dart airdrop-alternativeclipboardclipboard-sharingclipboard-synccopy-pastecross-platformend-to-end-encryptionfile-syncfile-transferfluttergolanglinuxmacosnat-traversalp2pself-hostedtailscaleuniversal-clipboardwebrtcwindows
fix(windows): request firewall access from the phone QR dialog
baiyuze870a7de48251
diff --git a/client-core/internal/transport/lan/firewall_rules.go b/client-core/internal/transport/lan/firewall_rules.gonew file mode 100644index 0000000..bb1542c--- /dev/null+++ b/client-core/internal/transport/lan/firewall_rules.go@@ -0,0 +1,54 @@+package lan++// Windows 防火墙 COM 规则的语言无关属性。单独放置以便在所有平台验证判定逻辑。+type firewallRule struct {+ Enabled bool+ Direction int+ Action int+ Profiles int+ Protocol int+ ServiceName string+ LocalPorts string+ RemotePorts string+ LocalAddresses string+ RemoteAddresses string+ InterfaceTypes string+ Interfaces []string+}++func firewallRulesAllowProgram(rules []firewallRule) bool {+ var tcp, udp int+ for _, r := range rules {+ if !r.Enabled || r.Direction != 1 { // inbound+ continue+ }+ if r.Action == 0 { // 显式阻止优先于允许,包括用户取消系统防火墙弹窗留下的规则+ return false+ }+ if r.Action != 1 || r.ServiceName != "" ||+ !unrestrictedFirewallValue(r.LocalPorts) || !unrestrictedFirewallValue(r.RemotePorts) ||+ !unrestrictedFirewallValue(r.LocalAddresses) || !unrestrictedFirewallValue(r.RemoteAddresses) ||+ r.InterfaceTypes != "All" {+ continue+ }+ restrictedInterface := false+ for _, name := range r.Interfaces {+ if name != "" {+ restrictedInterface = true+ }+ }+ if restrictedInterface {+ continue+ }+ if r.Protocol == 6 || r.Protocol == 256 {+ tcp |= r.Profiles+ }+ if r.Protocol == 17 || r.Protocol == 256 {+ udp |= r.Profiles+ }+ }+ // Domain、Private、Public 都要放行,切换网络类型后仍然可用。+ return tcp&7 == 7 && udp&7 == 7+}++func unrestrictedFirewallValue(s string) bool { return s == "" || s == "*" }diff --git a/client-core/internal/transport/lan/firewall_rules_test.go b/client-core/internal/transport/lan/firewall_rules_test.gonew file mode 100644index 0000000..f78342a--- /dev/null+++ b/client-core/internal/transport/lan/firewall_rules_test.go@@ -0,0 +1,62 @@+package lan++import "testing"++func TestFirewallRulesAllowProgram(t *testing.T) {+ allow := firewallRule{Enabled: true, Direction: 1, Action: 1, Profiles: 7, Protocol: 256, InterfaceTypes: "All"}+ change := func(edit func(*firewallRule)) firewallRule {+ r := allow+ edit(&r)+ return r+ }+ tests := []struct {+ name string+ rules []firewallRule+ want bool+ }{+ {"no rules", nil, false},+ {"all traffic", []firewallRule{allow}, true},+ {"TCP only cannot sync", []firewallRule{change(func(r *firewallRule) { r.Protocol = 6 })}, false},+ {"UDP only cannot serve phone", []firewallRule{change(func(r *firewallRule) { r.Protocol = 17 })}, false},+ {"separate TCP UDP", []firewallRule{change(func(r *firewallRule) { r.Protocol = 6 }), change(func(r *firewallRule) { r.Protocol = 17 })}, true},+ {"disabled", []firewallRule{change(func(r *firewallRule) { r.Enabled = false })}, false},+ {"outbound only", []firewallRule{change(func(r *firewallRule) { r.Direction = 2 })}, false},+ {"private only", []firewallRule{change(func(r *firewallRule) { r.Profiles = 2 })}, false},+ {"profiles combined", []firewallRule{change(func(r *firewallRule) { r.Profiles = 3 }), change(func(r *firewallRule) { r.Profiles = 4 })}, true},+ {"cancelled prompt block wins", []firewallRule{allow, change(func(r *firewallRule) { r.Action = 0 })}, false},+ {"disabled block ignored", []firewallRule{allow, change(func(r *firewallRule) { r.Action, r.Enabled = 0, false })}, true},+ {"outbound block ignored", []firewallRule{allow, change(func(r *firewallRule) { r.Action, r.Direction = 0, 2 })}, true},+ }+ for _, field := range []string{"local port", "remote port", "local address", "remote address", "interface", "interface name", "service"} {+ r := change(func(r *firewallRule) {+ switch field {+ case "local port":+ r.LocalPorts = "8790"+ case "remote port":+ r.RemotePorts = "443"+ case "local address":+ r.LocalAddresses = "192.168.1.5"+ case "remote address":+ r.RemoteAddresses = "192.168.1.6"+ case "interface":+ r.InterfaceTypes = "Wireless"+ case "interface name":+ r.Interfaces = []string{"Ethernet 2"}+ case "service":+ r.ServiceName = "Dnscache"+ }+ })+ tests = append(tests, struct {+ name string+ rules []firewallRule+ want bool+ }{"restricted " + field, []firewallRule{r}, false})+ }+ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ if got := firewallRulesAllowProgram(tt.rules); got != tt.want {+ t.Fatalf("firewallRulesAllowProgram() = %v, want %v", got, tt.want)+ }+ })+ }+}diff --git a/client-core/internal/transport/lan/permission_windows.go b/client-core/internal/transport/lan/permission_windows.goindex 816860a..ad3f79f 100644--- a/client-core/internal/transport/lan/permission_windows.go+++ b/client-core/internal/transport/lan/permission_windows.go@@ -3,42 +3,125 @@package lanimport (+ "context"+ "encoding/base64"+ "encoding/binary"+ "encoding/json""fmt""net/netip""os"+ "os/exec"+ "path/filepath""strings"-- "golang.org/x/sys/windows"+ "sync"+ "syscall"+ "time"+ "unicode/utf16")-// RequestPermission 申请一次管理员权限(弹出 UAC),在 Windows 防火墙里放行后台服务。-//-// 第一次运行时 Windows 会问是否允许后台服务通过防火墙;点了取消会留下阻止规则,-// 而且那条规则只对当时的网络类型生效。不放行时本机仍能主动连别人,-// 但别人连不上本机——跨网段配对时要输入地址的那一方正是被连的一方。-// 这里删掉本程序原有的入站规则(包括阻止规则,阻止优先于允许),-// 再加对所有网络类型生效的允许规则:UDP 给同步,TCP 给隔空传送的局域网快速通道(2.5.1)。+var permissionMu sync.Mutex++// RequestPermission 检查后台服务的入站规则;需要修复时弹出 UAC,并等待+// netsh 完成后重新检查。二维码窗口每次打开都会调用,已放行时不再弹 UAC。+// TCP 用于手机网页传输和隔空传送,UDP 用于设备同步。func RequestPermission() error {+ permissionMu.Lock()+ defer permissionMu.Unlock()exe, err := os.Executable()if err != nil {return err}- if strings.ContainsRune(exe, '"') {- return fmt.Errorf("程序路径含引号,无法放行: %s", exe)- }- script := fmt.Sprintf(- `/c netsh advfirewall firewall delete rule name=all dir=in program="%[1]s" & `+- `netsh advfirewall firewall add rule name="PasteFerry" dir=in action=allow program="%[1]s" protocol=UDP profile=any & `+- `netsh advfirewall firewall add rule name="PasteFerry" dir=in action=allow program="%[1]s" protocol=TCP profile=any`,- exe)- verb, _ := windows.UTF16PtrFromString("runas")- file, _ := windows.UTF16PtrFromString("cmd.exe")- args, err := windows.UTF16PtrFromString(script)+ allowed, err := firewallAllowsProgram(exe)if err != nil {return err}- // 用户在 UAC 里点了「否」时返回 ERROR_CANCELLED- return windows.ShellExecute(0, verb, file, args, nil, windows.SW_HIDE)+ if allowed {+ return nil+ }+ // 不经过 cmd.exe:路径中的 %、&、引号等不能变成命令或环境变量。+ // 先移除旧的入站阻止规则(阻止优先于允许),保留原有的出站规则。+ repair := `$ErrorActionPreference = 'Stop'+$exe = ` + powershellLiteral(exe) + `+$netsh = Join-Path $env:SystemRoot 'System32\netsh.exe'+& $netsh advfirewall firewall delete rule name=all dir=in "program=$exe" | Out-Null+foreach ($protocol in @('UDP', 'TCP')) {+ & $netsh advfirewall firewall add rule name=PasteFerry dir=in action=allow "program=$exe" "protocol=$protocol" profile=any | Out-Null+ if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }+}+exit 0+`+ // Start-Process -Wait 等待提权后的进程退出,不能把「UAC 已启动」当成成功。+ script := `$ErrorActionPreference = 'Stop'+$p = Start-Process -FilePath (Join-Path $PSHOME 'powershell.exe') -Verb RunAs -WindowStyle Hidden -Wait -PassThru -ArgumentList @('-NoProfile', '-NonInteractive', '-EncodedCommand', '` + encodePowershell(repair) + `')+exit $p.ExitCode+`+ if _, err := runFirewallScript(script, 2*time.Minute); err != nil {+ return fmt.Errorf("防火墙授权未完成,请在系统弹窗中允许管理员操作后重试: %w", err)+ }+ allowed, err = firewallAllowsProgram(exe)+ if err != nil {+ return err+ }+ if !allowed {+ return fmt.Errorf("防火墙规则未生效,请检查系统或组织的防火墙策略后重试")+ }+ return nil+}++func firewallAllowsProgram(exe string) (bool, error) {+ // COM 的属性与系统语言无关;NetSecurity cmdlet 启动较慢。+ script := `$ErrorActionPreference = 'Stop'+$policy = New-Object -ComObject HNetCfg.FwPolicy2+$rules = @($policy.Rules | Where-Object { $_.ApplicationName -ieq ` + powershellLiteral(exe) + ` } | ForEach-Object {+ $localPorts = $remotePorts = ''+ if ($_.Protocol -eq 6 -or $_.Protocol -eq 17) {+ $localPorts = $_.LocalPorts+ $remotePorts = $_.RemotePorts+ }+ [PSCustomObject]@{+ Enabled = $_.Enabled; Direction = $_.Direction; Action = $_.Action+ Profiles = $_.Profiles; Protocol = $_.Protocol; ServiceName = $_.ServiceName+ LocalPorts = $localPorts; RemotePorts = $remotePorts+ LocalAddresses = $_.LocalAddresses; RemoteAddresses = $_.RemoteAddresses+ InterfaceTypes = $_.InterfaceTypes; Interfaces = @($_.Interfaces)+ }+})+ConvertTo-Json -InputObject $rules -Depth 4 -Compress+`+ out, err := runFirewallScript(script, 15*time.Second)+ if err != nil {+ return false, fmt.Errorf("检查 Windows 防火墙失败: %w", err)+ }+ var rules []firewallRule+ if err := json.Unmarshal(out, &rules); err != nil {+ return false, fmt.Errorf("读取 Windows 防火墙规则失败: %w", err)+ }+ return firewallRulesAllowProgram(rules), nil+}++func powershellLiteral(s string) string { return "'" + strings.ReplaceAll(s, "'", "''") + "'" }++func encodePowershell(script string) string {+ units := utf16.Encode([]rune(script))+ b := make([]byte, len(units)*2)+ for i, u := range units {+ binary.LittleEndian.PutUint16(b[i*2:], u)+ }+ return base64.StdEncoding.EncodeToString(b)+}++func runFirewallScript(script string, timeout time.Duration) ([]byte, error) {+ ctx, cancel := context.WithTimeout(context.Background(), timeout)+ defer cancel()+ // 使用系统自带的 PowerShell,避免 PATH 中的同名程序接到提权请求。+ ps := filepath.Join(os.Getenv("SystemRoot"), "System32", "WindowsPowerShell", "v1.0", "powershell.exe")+ cmd := exec.CommandContext(ctx, ps, "-NoProfile", "-NonInteractive", "-EncodedCommand", encodePowershell(script))+ cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}+ out, err := cmd.Output()+ if ctx.Err() != nil {+ return nil, ctx.Err()+ }+ return out, err}// Windows 不会在发送时拦截,防火墙只挡入站。diff --git a/ui/lib/l10n/app_en.arb b/ui/lib/l10n/app_en.arbindex 78df8a7..14bd5a6 100644--- a/ui/lib/l10n/app_en.arb+++ b/ui/lib/l10n/app_en.arb@@ -1752,5 +1752,9 @@}},"mDeleteConfirm": "Delete this record?",- "mDelete": "Delete"+ "mDelete": "Delete",+ "webShareFirewallPreparing": "Checking Windows Firewall. If Windows asks for administrator approval, choose Yes so your phone can connect.",+ "webShareFirewallReady": "Windows Firewall rules are ready. Connect your phone to the same network and scan the QR code. If it still cannot connect, check the firewall again below.",+ "webShareFirewallFailed": "Firewall setup did not finish. Your phone may be unable to open the page. Try again and approve the Windows administrator prompt.",+ "webShareFirewallAllow": "Check and allow phone connections"}diff --git a/ui/lib/l10n/app_ja.arb b/ui/lib/l10n/app_ja.arbindex c00661e..920bf99 100644--- a/ui/lib/l10n/app_ja.arb+++ b/ui/lib/l10n/app_ja.arb@@ -695,5 +695,9 @@"mAllow": "許可","mVersion": "バージョン {version}","mDeleteConfirm": "この履歴を削除しますか?",- "mDelete": "削除"+ "mDelete": "削除",+ "webShareFirewallPreparing": "Windows ファイアウォールを確認しています。管理者の承認を求められたら「はい」を選び、スマートフォンからの接続を許可してください。",+ "webShareFirewallReady": "Windows ファイアウォールの設定が完了しました。同じネットワークに接続してスキャンしてください。接続できない場合は、下のボタンで再確認できます。",+ "webShareFirewallFailed": "ファイアウォールの設定が完了していません。スマートフォンでページを開けない場合があります。再試行し、Windows の管理者確認で「はい」を選んでください。",+ "webShareFirewallAllow": "スマートフォンの接続を確認・許可"}diff --git a/ui/lib/l10n/app_localizations.dart b/ui/lib/l10n/app_localizations.dartindex 4a07b8a..440aac5 100644--- a/ui/lib/l10n/app_localizations.dart+++ b/ui/lib/l10n/app_localizations.dart@@ -4285,6 +4285,30 @@ abstract class AppLocalizations {/// In en, this message translates to:/// **'Delete'**String get mDelete;++ /// No description provided for @webShareFirewallPreparing.+ ///+ /// In en, this message translates to:+ /// **'Checking Windows Firewall. If Windows asks for administrator approval, choose Yes so your phone can connect.'**+ String get webShareFirewallPreparing;++ /// No description provided for @webShareFirewallReady.+ ///+ /// In en, this message translates to:+ /// **'Windows Firewall rules are ready. Connect your phone to the same network and scan the QR code. If it still cannot connect, check the firewall again below.'**+ String get webShareFirewallReady;++ /// No description provided for @webShareFirewallFailed.+ ///+ /// In en, this message translates to:+ /// **'Firewall setup did not finish. Your phone may be unable to open the page. Try again and approve the Windows administrator prompt.'**+ String get webShareFirewallFailed;++ /// No description provided for @webShareFirewallAllow.+ ///+ /// In en, this message translates to:+ /// **'Check and allow phone connections'**+ String get webShareFirewallAllow;}class _AppLocalizationsDelegatediff --git a/ui/lib/l10n/app_localizations_en.dart b/ui/lib/l10n/app_localizations_en.dartindex 5734e8f..e339774 100644--- a/ui/lib/l10n/app_localizations_en.dart+++ b/ui/lib/l10n/app_localizations_en.dart@@ -2620,4 +2620,19 @@ class AppLocalizationsEn extends AppLocalizations {@overrideString get mDelete => 'Delete';++ @override+ String get webShareFirewallPreparing =>+ 'Checking Windows Firewall. If Windows asks for administrator approval, choose Yes so your phone can connect.';++ @override+ String get webShareFirewallReady =>+ 'Windows Firewall rules are ready. Connect your phone to the same network and scan the QR code. If it still cannot connect, check the firewall again below.';++ @override+ String get webShareFirewallFailed =>+ 'Firewall setup did not finish. Your phone may be unable to open the page. Try again and approve the Windows administrator prompt.';++ @override+ String get webShareFirewallAllow => 'Check and allow phone connections';}diff --git a/ui/lib/l10n/app_localizations_ja.dart b/ui/lib/l10n/app_localizations_ja.dartindex 2e7a2f9..3b19053 100644--- a/ui/lib/l10n/app_localizations_ja.dart+++ b/ui/lib/l10n/app_localizations_ja.dart@@ -2437,4 +2437,19 @@ class AppLocalizationsJa extends AppLocalizations {@overrideString get mDelete => '削除';++ @override+ String get webShareFirewallPreparing =>+ 'Windows ファイアウォールを確認しています。管理者の承認を求められたら「はい」を選び、スマートフォンからの接続を許可してください。';++ @override+ String get webShareFirewallReady =>+ 'Windows ファイアウォールの設定が完了しました。同じネットワークに接続してスキャンしてください。接続できない場合は、下のボタンで再確認できます。';++ @override+ String get webShareFirewallFailed =>+ 'ファイアウォールの設定が完了していません。スマートフォンでページを開けない場合があります。再試行し、Windows の管理者確認で「はい」を選んでください。';++ @override+ String get webShareFirewallAllow => 'スマートフォンの接続を確認・許可';}diff --git a/ui/lib/l10n/app_localizations_zh.dart b/ui/lib/l10n/app_localizations_zh.dartindex 6645c57..a09897f 100644--- a/ui/lib/l10n/app_localizations_zh.dart+++ b/ui/lib/l10n/app_localizations_zh.dart@@ -2410,6 +2410,21 @@ class AppLocalizationsZh extends AppLocalizations {@overrideString get mDelete => '删除';++ @override+ String get webShareFirewallPreparing =>+ '正在检查 Windows 防火墙。如弹出管理员授权窗口,请选择“是”,让手机可以连接这台电脑。';++ @override+ String get webShareFirewallReady =>+ 'Windows 防火墙已放行。请让手机和电脑连接同一网络后扫码;如果仍无法连接,可点击下方按钮重新检查。';++ @override+ String get webShareFirewallFailed =>+ '防火墙授权尚未完成,手机可能无法打开网页。请点击下方按钮重试,并在 Windows 管理员授权窗口中选择“是”。';++ @override+ String get webShareFirewallAllow => '检查并允许手机连接';}/// The translations for Chinese, as used in Hong Kong, using the Han script (`zh_Hant_HK`).@@ -4818,6 +4833,21 @@ class AppLocalizationsZhHantHk extends AppLocalizationsZh {@overrideString get mDelete => '刪除';++ @override+ String get webShareFirewallPreparing =>+ '正在檢查 Windows 防火牆。如出現管理員授權視窗,請選擇「是」,讓手機可以連接這部電腦。';++ @override+ String get webShareFirewallReady =>+ 'Windows 防火牆已允許連線。請讓手機和電腦連接同一網絡後掃碼;如仍無法連接,可按下方按鈕重新檢查。';++ @override+ String get webShareFirewallFailed =>+ '防火牆授權尚未完成,手機可能無法開啟網頁。請按下方按鈕重試,並在 Windows 管理員授權視窗中選擇「是」。';++ @override+ String get webShareFirewallAllow => '檢查並允許手機連線';}/// The translations for Chinese, as used in Taiwan, using the Han script (`zh_Hant_TW`).@@ -7226,4 +7256,19 @@ class AppLocalizationsZhHantTw extends AppLocalizationsZh {@overrideString get mDelete => '刪除';++ @override+ String get webShareFirewallPreparing =>+ '正在檢查 Windows 防火牆。若出現系統管理員授權視窗,請選擇「是」,讓手機可以連線到這台電腦。';++ @override+ String get webShareFirewallReady =>+ 'Windows 防火牆已允許連入。請讓手機和電腦連上同一網路後掃碼;若仍無法連線,可點選下方按鈕重新檢查。';++ @override+ String get webShareFirewallFailed =>+ '防火牆授權尚未完成,手機可能無法開啟網頁。請點選下方按鈕重試,並在 Windows 系統管理員授權視窗中選擇「是」。';++ @override+ String get webShareFirewallAllow => '檢查並允許手機連線';}diff --git a/ui/lib/l10n/app_zh.arb b/ui/lib/l10n/app_zh.arbindex 5a026d8..2a9fca0 100644--- a/ui/lib/l10n/app_zh.arb+++ b/ui/lib/l10n/app_zh.arb@@ -695,5 +695,9 @@"mAllow": "允许","mVersion": "版本 {version}","mDeleteConfirm": "删除这条记录?",- "mDelete": "删除"+ "mDelete": "删除",+ "webShareFirewallPreparing": "正在检查 Windows 防火墙。如弹出管理员授权窗口,请选择“是”,让手机可以连接这台电脑。",+ "webShareFirewallReady": "Windows 防火墙已放行。请让手机和电脑连接同一网络后扫码;如果仍无法连接,可点击下方按钮重新检查。",+ "webShareFirewallFailed": "防火墙授权尚未完成,手机可能无法打开网页。请点击下方按钮重试,并在 Windows 管理员授权窗口中选择“是”。",+ "webShareFirewallAllow": "检查并允许手机连接"}diff --git a/ui/lib/l10n/app_zh_Hant_HK.arb b/ui/lib/l10n/app_zh_Hant_HK.arbindex 238fc47..7a7e2d7 100644--- a/ui/lib/l10n/app_zh_Hant_HK.arb+++ b/ui/lib/l10n/app_zh_Hant_HK.arb@@ -695,5 +695,9 @@"mAllow": "允許","mVersion": "版本 {version}","mDeleteConfirm": "刪除這條記錄?",- "mDelete": "刪除"+ "mDelete": "刪除",+ "webShareFirewallPreparing": "正在檢查 Windows 防火牆。如出現管理員授權視窗,請選擇「是」,讓手機可以連接這部電腦。",+ "webShareFirewallReady": "Windows 防火牆已允許連線。請讓手機和電腦連接同一網絡後掃碼;如仍無法連接,可按下方按鈕重新檢查。",+ "webShareFirewallFailed": "防火牆授權尚未完成,手機可能無法開啟網頁。請按下方按鈕重試,並在 Windows 管理員授權視窗中選擇「是」。",+ "webShareFirewallAllow": "檢查並允許手機連線"}diff --git a/ui/lib/l10n/app_zh_Hant_TW.arb b/ui/lib/l10n/app_zh_Hant_TW.arbindex afc45cd..26bbe8f 100644--- a/ui/lib/l10n/app_zh_Hant_TW.arb+++ b/ui/lib/l10n/app_zh_Hant_TW.arb@@ -695,5 +695,9 @@"mAllow": "允許","mVersion": "版本 {version}","mDeleteConfirm": "刪除這筆記錄?",- "mDelete": "刪除"+ "mDelete": "刪除",+ "webShareFirewallPreparing": "正在檢查 Windows 防火牆。若出現系統管理員授權視窗,請選擇「是」,讓手機可以連線到這台電腦。",+ "webShareFirewallReady": "Windows 防火牆已允許連入。請讓手機和電腦連上同一網路後掃碼;若仍無法連線,可點選下方按鈕重新檢查。",+ "webShareFirewallFailed": "防火牆授權尚未完成,手機可能無法開啟網頁。請點選下方按鈕重試,並在 Windows 系統管理員授權視窗中選擇「是」。",+ "webShareFirewallAllow": "檢查並允許手機連線"}diff --git a/ui/lib/widgets/web_share.dart b/ui/lib/widgets/web_share.dartindex 2ec8636..fa212ea 100644--- a/ui/lib/widgets/web_share.dart+++ b/ui/lib/widgets/web_share.dart@@ -83,7 +83,11 @@ class WebShareSection extends StatelessWidget {}} catch (e) {if (context.mounted) {- showToast(context, AppState.describeError(e), error: true);+ showToast(+ context,+ AppState.describeError(e),+ error: true,+ );}}},@@ -172,6 +176,8 @@ class _WebShareDialogState extends State<WebShareDialog> {String _address = '';String? _error;bool _refreshing = false;+ bool _preparingFirewall = false;+ String? _firewallError;Timer? _expiry;StreamSubscription<String>? _used;late final AppState _state = AppScope.read(context);@@ -189,6 +195,30 @@ class _WebShareDialogState extends State<WebShareDialog> {_refresh(closeOld: false);});_refresh();+ // 包括开关自动打开、二维码按钮和托盘入口;只在窗口打开时申请,+ // 不随邀请轮换重复弹 UAC。后台服务会先检查,已放行时直接返回。+ if (_state.self?.platform == 'windows') {+ _preparingFirewall = true;+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (mounted) _prepareFirewall();+ });+ }+ }++ Future<void> _prepareFirewall() async {+ setState(() {+ _preparingFirewall = true;+ _firewallError = null;+ });+ try {+ await _state.requestLocalNetworkPermission();+ } catch (e) {+ if (mounted) {+ setState(() => _firewallError = AppState.describeError(e));+ }+ } finally {+ if (mounted) setState(() => _preparingFirewall = false);+ }}@override@@ -252,149 +282,183 @@ class _WebShareDialogState extends State<WebShareDialog> {return Dialog(child: SizedBox(width: 420,- child: Padding(- padding: const EdgeInsets.fromLTRB(- Insets.xl,- Insets.lg,- Insets.md,- Insets.xl,- ),- child: Column(- mainAxisSize: MainAxisSize.min,- crossAxisAlignment: CrossAxisAlignment.stretch,- children: [- Row(- children: [- Expanded(- child: Text(- l.webShareDialogTitle,- style: context.text.titleMedium,- ),- ),- IconAction(- icon: AppIcons.xmark,- tooltip: l.close,- onTap: () => Navigator.pop(context),- ),- ],- ),- Padding(- padding: const EdgeInsets.only(right: Insets.md),- child: Column(- crossAxisAlignment: CrossAxisAlignment.stretch,+ child: SingleChildScrollView(+ child: Padding(+ padding: const EdgeInsets.fromLTRB(+ Insets.xl,+ Insets.lg,+ Insets.md,+ Insets.xl,+ ),+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ Row(children: [- const SizedBox(height: Insets.sm),- Text(- l.webShareDialogBody,- style: context.text.bodyMedium?.copyWith(- color: p.textDim,+ Expanded(+ child: Text(+ l.webShareDialogTitle,+ style: context.text.titleMedium,),),- const SizedBox(height: Insets.lg),- Center(- child: Container(- width: 232,- height: 232,- padding: const EdgeInsets.all(Insets.md),- // 二维码一律深色画在白底上:深色模式下也是,反色的码很多扫码器认不出- decoration: BoxDecoration(- color: Colors.white,- borderRadius: BorderRadius.circular(Radii.lg),- border: Border.all(color: p.border),- ),- child: _invite == null- ? Center(- child: _error == null- ? const SizedBox(- width: 20,- height: 20,- child: CircularProgressIndicator(- strokeWidth: 2,- ),- )- : Text(- _error!,- textAlign: TextAlign.center,- style: context.text.bodySmall?.copyWith(- color: p.danger,- ),- ),- )- : QrCodeView(- size: _invite!.qrSize,- modules: Uint8List.fromList(_invite!.qrModules),- ),- ),+ IconAction(+ icon: AppIcons.xmark,+ tooltip: l.close,+ onTap: () => Navigator.pop(context),),- const SizedBox(height: Insets.md),- if (_invite != null)- SelectableText(- _invite!.url.split('#').first,- textAlign: TextAlign.center,- style: context.text.bodySmall?.copyWith(- fontFamily: monoFamily,+ ],+ ),+ Padding(+ padding: const EdgeInsets.only(right: Insets.md),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ const SizedBox(height: Insets.sm),+ Text(+ l.webShareDialogBody,+ style: context.text.bodyMedium?.copyWith(+ color: p.textDim,),),- if (addresses.length > 1) ...[- const SizedBox(height: Insets.md),- Row(- mainAxisAlignment: MainAxisAlignment.center,- children: [+ if (_state.self?.platform == 'windows') ...[+ const SizedBox(height: Insets.md),+ _Note(+ icon: AppIcons.lockShield,+ text: _preparingFirewall+ ? l.webShareFirewallPreparing+ : _firewallError != null+ ? l.webShareFirewallFailed+ : l.webShareFirewallReady,+ ),+ if (_firewallError != null) ...[+ const SizedBox(height: Insets.sm),Text(- l.webShareAddress,- style: context.text.bodySmall,- ),- const SizedBox(width: Insets.sm),- DropdownButton<String>(- value: addresses.contains(current)- ? current- : addresses.first,- isDense: true,- underline: const SizedBox.shrink(),+ _firewallError!,style: context.text.bodySmall?.copyWith(- color: p.text,- fontFamily: monoFamily,+ color: p.danger,),- items: [- for (final a in addresses)- DropdownMenuItem(value: a, child: Text(a)),- ],- onChanged: (a) {- if (a == null || a == current) return;- setState(() => _address = a);- _refresh();- },),],- ),- ] else if (addresses.isEmpty) ...[- const SizedBox(height: Insets.sm),- Text(- l.webShareNoAddress,- textAlign: TextAlign.center,- style: context.text.bodySmall?.copyWith(- color: p.warning,+ if (!_preparingFirewall)+ Align(+ alignment: Alignment.centerLeft,+ child: OutlinedButton(+ onPressed: _prepareFirewall,+ child: Text(l.webShareFirewallAllow),+ ),+ ),+ ],+ const SizedBox(height: Insets.lg),+ Center(+ child: Container(+ width: 232,+ height: 232,+ padding: const EdgeInsets.all(Insets.md),+ // 二维码一律深色画在白底上:深色模式下也是,反色的码很多扫码器认不出+ decoration: BoxDecoration(+ color: Colors.white,+ borderRadius: BorderRadius.circular(Radii.lg),+ border: Border.all(color: p.border),+ ),+ child: _invite == null+ ? Center(+ child: _error == null+ ? const SizedBox(+ width: 20,+ height: 20,+ child: CircularProgressIndicator(+ strokeWidth: 2,+ ),+ )+ : Text(+ _error!,+ textAlign: TextAlign.center,+ style: context.text.bodySmall+ ?.copyWith(color: p.danger),+ ),+ )+ : QrCodeView(+ size: _invite!.qrSize,+ modules: Uint8List.fromList(+ _invite!.qrModules,+ ),+ ),),),- ],- if (st?.portFallback ?? false) ...[- const SizedBox(height: Insets.sm),- Text(- l.webSharePortFallback,- textAlign: TextAlign.center,- style: context.text.bodySmall?.copyWith(- color: p.warning,+ const SizedBox(height: Insets.md),+ if (_invite != null)+ SelectableText(+ _invite!.url.split('#').first,+ textAlign: TextAlign.center,+ style: context.text.bodySmall?.copyWith(+ fontFamily: monoFamily,+ ),+ ),+ if (addresses.length > 1) ...[+ const SizedBox(height: Insets.md),+ Row(+ mainAxisAlignment: MainAxisAlignment.center,+ children: [+ Text(+ l.webShareAddress,+ style: context.text.bodySmall,+ ),+ const SizedBox(width: Insets.sm),+ DropdownButton<String>(+ value: addresses.contains(current)+ ? current+ : addresses.first,+ isDense: true,+ underline: const SizedBox.shrink(),+ style: context.text.bodySmall?.copyWith(+ color: p.text,+ fontFamily: monoFamily,+ ),+ items: [+ for (final a in addresses)+ DropdownMenuItem(value: a, child: Text(a)),+ ],+ onChanged: (a) {+ if (a == null || a == current) return;+ setState(() => _address = a);+ _refresh();+ },+ ),+ ],+ ),+ ] else if (addresses.isEmpty) ...[+ const SizedBox(height: Insets.sm),+ Text(+ l.webShareNoAddress,+ textAlign: TextAlign.center,+ style: context.text.bodySmall?.copyWith(+ color: p.warning,+ ),),+ ],+ if (st?.portFallback ?? false) ...[+ const SizedBox(height: Insets.sm),+ Text(+ l.webSharePortFallback,+ textAlign: TextAlign.center,+ style: context.text.bodySmall?.copyWith(+ color: p.warning,+ ),+ ),+ ],+ const SizedBox(height: Insets.lg),+ _Note(+ icon: AppIcons.lockShield,+ text: l.webShareSecurity,),+ const SizedBox(height: Insets.sm),+ _Note(icon: AppIcons.info, text: l.webShareCantOpen),],- const SizedBox(height: Insets.lg),- _Note(icon: AppIcons.lockShield, text: l.webShareSecurity),- const SizedBox(height: Insets.sm),- _Note(icon: AppIcons.info, text: l.webShareCantOpen),- ],+ ),),- ),- ],+ ],+ ),),),),diff --git a/ui/test/web_share_test.dart b/ui/test/web_share_test.dartindex f45f414..ffd071d 100644--- a/ui/test/web_share_test.dart+++ b/ui/test/web_share_test.dart@@ -1,3 +1,4 @@+import 'dart:async';import 'dart:typed_data';import 'package:fixnum/fixnum.dart';@@ -11,7 +12,8 @@ import 'package:pasteferry_ui/main.dart';import 'package:pasteferry_ui/records.dart';import 'package:pasteferry_ui/widgets/web_share.dart';-Int64 _now([int ago = 0]) => Int64(DateTime.now().millisecondsSinceEpoch ~/ 1000 - ago);+Int64 _now([int ago = 0]) =>+ Int64(DateTime.now().millisecondsSinceEpoch ~/ 1000 - ago);/// 21×21 的点阵:左上角一个定位图案,够界面画出来就行List<int> _modules() {@@ -29,9 +31,18 @@ class _WebShareState extends AppState {final closed = <String>[];final toggles = <bool>[];final removed = <String>[];+ int firewallRequests = 0;+ Future<void> Function()? firewallPermission;var _serial = 0;- WebShareStatus _status(bool on, {List<WebSession> sessions = const []}) => WebShareStatus(+ @override+ Future<void> requestLocalNetworkPermission() async {+ firewallRequests++;+ await firewallPermission?.call();+ }++ WebShareStatus _status(bool on, {List<WebSession> sessions = const []}) =>+ WebShareStatus(enabled: on,listening: on,port: 8790,@@ -59,40 +70,69 @@ class _WebShareState extends AppState {@overrideFuture<void> setWebShare(bool enabled) async {toggles.add(enabled);- debugEvent(Event(webShareChanged: _status(enabled, sessions: webShare?.sessions ?? const [])));+ debugEvent(+ Event(+ webShareChanged: _status(+ enabled,+ sessions: webShare?.sessions ?? const [],+ ),+ ),+ );}@overrideFuture<void> removeWebSession(String id) async {removed.add(id);- debugEvent(Event(- webShareChanged: _status(true, sessions: webShare!.sessions.where((s) => s.id != id).toList()),- ));+ debugEvent(+ Event(+ webShareChanged: _status(+ true,+ sessions: webShare!.sessions.where((s) => s.id != id).toList(),+ ),+ ),+ );}}-_WebShareState _demo({bool on = true, List<WebSession> sessions = const []}) {+_WebShareState _demo({+ bool on = true,+ List<WebSession> sessions = const [],+ String platform = 'darwin',+ String language = 'zh-Hans',+}) {final state = _WebShareState();state.debugSeed(status: Status(version: '2.7.0'),- config: Config(language: 'zh-Hans', deviceName: 'MacBook Pro'),- self: Device(id: 'self', name: 'MacBook Pro', platform: 'darwin'),+ config: Config(language: language, deviceName: 'MacBook Pro'),+ self: Device(id: 'self', name: 'MacBook Pro', platform: platform),webShare: state._status(on, sessions: sessions),);return state;}-final _iphone = WebSession(id: 's1', name: 'iPhone', createdAtUnix: _now(7200), lastSeenUnix: _now(120));+final _iphone = WebSession(+ id: 's1',+ name: 'iPhone',+ createdAtUnix: _now(7200),+ lastSeenUnix: _now(120),+);void main() {setUp(() {- final view = TestWidgetsFlutterBinding.instance.platformDispatcher.views.first;+ final view =+ TestWidgetsFlutterBinding.instance.platformDispatcher.views.first;view.physicalSize = const Size(1180, 900);view.devicePixelRatio = 1;});- tearDown(() => TestWidgetsFlutterBinding.instance.platformDispatcher.views.first.reset());+ tearDown(+ () => TestWidgetsFlutterBinding.instance.platformDispatcher.views.first+ .reset(),+ );- Future<AppLocalizations> openDevices(WidgetTester tester, AppState state) async {+ Future<AppLocalizations> openDevices(+ WidgetTester tester,+ AppState state,+ ) async {await tester.pumpWidget(PasteFerryApp(state: state));await tester.pump();final l = AppLocalizations.of(tester.element(find.byType(Shell)));@@ -117,7 +157,7 @@ void main() {});testWidgets('关着时没有二维码按钮;打开开关后直接弹出二维码', (tester) async {- final state = _demo(on: false);+ final state = _demo(on: false, platform: 'windows');final l = await openDevices(tester, state);expect(find.text(l.webShareOff), findsOneWidget);expect(find.text(l.webShareShowQr), findsNothing);@@ -128,27 +168,118 @@ void main() {expect(find.byType(WebShareDialog), findsOneWidget);expect(find.byType(QrCodeView), findsOneWidget);expect(find.text('http://192.168.1.5:8790/'), findsOneWidget);+ expect(state.firewallRequests, 1);+ expect(find.text(l.webShareFirewallReady), findsOneWidget);});+ testWidgets('Windows 二维码窗口等待授权,失败后可以原地重试', (tester) async {+ final pending = Completer<void>();+ final state = _demo(platform: 'windows')+ ..firewallPermission = () => pending.future;+ final l = await openDevices(tester, state);+ await tester.tap(find.text(l.webShareShowQr));+ await tester.pumpAndSettle();+ expect(state.firewallRequests, 1);+ expect(find.text(l.webShareFirewallPreparing), findsOneWidget);+ expect(find.text(l.webShareFirewallReady), findsNothing);+ expect(find.text(l.webShareFirewallAllow), findsNothing);++ pending.completeError(StateError('UAC cancelled'));+ await tester.pumpAndSettle();+ expect(find.text(l.webShareFirewallFailed), findsOneWidget);+ expect(find.textContaining('UAC cancelled'), findsOneWidget);+ expect(find.text(l.webShareFirewallReady), findsNothing);++ state.firewallPermission = () async {};+ await tester.ensureVisible(find.text(l.webShareFirewallAllow));+ await tester.tap(find.text(l.webShareFirewallAllow));+ await tester.pumpAndSettle();+ expect(state.firewallRequests, 2);+ expect(find.text(l.webShareFirewallReady), findsOneWidget);+ expect(find.text(l.webShareFirewallFailed), findsNothing);++ // 邀请自动轮换不再申请;重新打开窗口才重新检查,避免每次 UAC。+ state.debugEvent(+ Event(webShareChanged: state._status(true)..inviteUsed = 'inv1'),+ );+ await tester.pumpAndSettle();+ expect(state.invites, ['', '']);+ expect(state.firewallRequests, 2);+ await tester.tap(find.byTooltip(l.close));+ await tester.pumpAndSettle();+ await tester.tap(find.text(l.webShareShowQr));+ await tester.pumpAndSettle();+ expect(state.firewallRequests, 3);+ });++ testWidgets('Windows 授权中关闭二维码窗口不会在完成时访问已销毁界面', (tester) async {+ final pending = Completer<void>();+ final state = _demo(platform: 'windows')+ ..firewallPermission = () => pending.future;+ final l = await openDevices(tester, state);+ await tester.tap(find.text(l.webShareShowQr));+ await tester.pumpAndSettle();+ await tester.tap(find.byTooltip(l.close));+ await tester.pumpAndSettle();+ pending.complete();+ await tester.pumpAndSettle();+ expect(tester.takeException(), isNull);+ expect(find.byType(WebShareDialog), findsNothing);+ });++ for (final language in ['en', 'ja', 'zh-Hans', 'zh-Hant-TW', 'zh-Hant-HK']) {+ testWidgets('Windows 最小窗口的 $language 授权提示和二维码可滚动访问', (tester) async {+ tester.view.physicalSize = const Size(760, 520);+ final state = _demo(platform: 'windows', language: language)+ ..firewallPermission = () async => throw StateError('UAC cancelled');+ await tester.pumpWidget(PasteFerryApp(state: state));+ await tester.pumpAndSettle();+ final context = tester.element(find.byType(Shell));+ final l = AppLocalizations.of(context);+ unawaited(showWebShareDialog(context));+ await tester.pumpAndSettle();+ expect(tester.takeException(), isNull);+ await tester.ensureVisible(find.text(l.webShareFirewallAllow));+ await tester.pumpAndSettle();+ state.firewallPermission = () async {};+ await tester.tap(find.text(l.webShareFirewallAllow));+ await tester.pumpAndSettle();+ expect(state.firewallRequests, 2);+ expect(find.text(l.webShareFirewallReady), findsOneWidget);+ await tester.ensureVisible(find.byType(QrCodeView));+ await tester.pumpAndSettle();+ expect(tester.takeException(), isNull);+ });+ }+testWidgets('二维码窗口:被扫码用掉后换一张新的,切换地址,关掉时作废', (tester) async {final state = _demo(sessions: [_iphone]);final l = await openDevices(tester, state);await tester.tap(find.text(l.webShareShowQr));await tester.pumpAndSettle();expect(state.invites, ['']);+ expect(state.firewallRequests, 0);+ expect(find.text(l.webShareFirewallPreparing), findsNothing);// 手机扫码登记:后台服务推来 invite_used,窗口换一张新的二维码并提示- final android = WebSession(id: 's2', name: 'Android 手机', createdAtUnix: _now(), lastSeenUnix: _now());- state.debugEvent(Event(- webShareChanged: WebShareStatus(- enabled: true,- listening: true,- port: 8790,- addresses: ['192.168.1.5', '10.0.0.8'],- sessions: [android, _iphone],- inviteUsed: 'inv1',+ final android = WebSession(+ id: 's2',+ name: 'Android 手机',+ createdAtUnix: _now(),+ lastSeenUnix: _now(),+ );+ state.debugEvent(+ Event(+ webShareChanged: WebShareStatus(+ enabled: true,+ listening: true,+ port: 8790,+ addresses: ['192.168.1.5', '10.0.0.8'],+ sessions: [android, _iphone],+ inviteUsed: 'inv1',+ ),),- ));+ );await tester.pumpAndSettle();expect(state.invites, ['', '']);expect(find.text(l.webShareNewPhone('Android 手机')), findsOneWidget);@@ -181,15 +312,30 @@ void main() {});test('网页发来的记录显示手机的名字', () {- final r = ClipRecord(outgoing: true, viaName: 'iPhone', originDeviceName: 'MacBook Pro');+ final r = ClipRecord(+ outgoing: true,+ viaName: 'iPhone',+ originDeviceName: 'MacBook Pro',+ );expect(recordSource(r), appL10n.fromDevice('iPhone'));expect(recordSource(ClipRecord(outgoing: true)), appL10n.thisDeviceShort);});testWidgets('二维码按点阵画出来', (tester) async {- await tester.pumpWidget(MaterialApp(- home: Center(child: SizedBox(width: 200, height: 200, child: QrCodeView(size: 21, modules: Uint8List.fromList(_modules())))),- ));+ await tester.pumpWidget(+ MaterialApp(+ home: Center(+ child: SizedBox(+ width: 200,+ height: 200,+ child: QrCodeView(+ size: 21,+ modules: Uint8List.fromList(_modules()),+ ),+ ),+ ),+ ),+ );expect(find.byType(CustomPaint), findsWidgets);});}diff --git a/ui/tool/l10n/strings.py b/ui/tool/l10n/strings.pyindex 6c5350c..d35e49b 100644--- a/ui/tool/l10n/strings.py+++ b/ui/tool/l10n/strings.py@@ -439,6 +439,12 @@ S = [("notifyClipboardFailedTitle", "Received; clipboard was not updated", "已接收,但未能写入剪贴板", "受信済みですがクリップボードを更新できませんでした", "已接收,但無法寫入剪貼簿", "已接收,但無法寫入剪貼簿"),("notifyClipboardFailedBody", "{name}\n{error}\nUse Copy to clipboard to try again, here or in History.", "{name}\n{error}\n可从此通知或复制记录重新放入剪贴板。", "{name}\n{error}\nこの通知または履歴からクリップボードに入れて再試行できます。", "{name}\n{error}\n可從此通知或複製記錄重新放入剪貼簿。", "{name}\n{error}\n可從此通知或複製記錄重新放入剪貼簿。"),+ # Windows firewall setup in the phone QR dialog+ ('webShareFirewallPreparing', 'Checking Windows Firewall. If Windows asks for administrator approval, choose Yes so your phone can connect.', '正在检查 Windows 防火墙。如弹出管理员授权窗口,请选择“是”,让手机可以连接这台电脑。', 'Windows ファイアウォールを確認しています。管理者の承認を求められたら「はい」を選び、スマートフォンからの接続を許可してください。', '正在檢查 Windows 防火牆。若出現系統管理員授權視窗,請選擇「是」,讓手機可以連線到這台電腦。', '正在檢查 Windows 防火牆。如出現管理員授權視窗,請選擇「是」,讓手機可以連接這部電腦。'),+ ('webShareFirewallReady', 'Windows Firewall rules are ready. Connect your phone to the same network and scan the QR code. If it still cannot connect, check the firewall again below.', 'Windows 防火墙已放行。请让手机和电脑连接同一网络后扫码;如果仍无法连接,可点击下方按钮重新检查。', 'Windows ファイアウォールの設定が完了しました。同じネットワークに接続してスキャンしてください。接続できない場合は、下のボタンで再確認できます。', 'Windows 防火牆已允許連入。請讓手機和電腦連上同一網路後掃碼;若仍無法連線,可點選下方按鈕重新檢查。', 'Windows 防火牆已允許連線。請讓手機和電腦連接同一網絡後掃碼;如仍無法連接,可按下方按鈕重新檢查。'),+ ('webShareFirewallFailed', 'Firewall setup did not finish. Your phone may be unable to open the page. Try again and approve the Windows administrator prompt.', '防火墙授权尚未完成,手机可能无法打开网页。请点击下方按钮重试,并在 Windows 管理员授权窗口中选择“是”。', 'ファイアウォールの設定が完了していません。スマートフォンでページを開けない場合があります。再試行し、Windows の管理者確認で「はい」を選んでください。', '防火牆授權尚未完成,手機可能無法開啟網頁。請點選下方按鈕重試,並在 Windows 系統管理員授權視窗中選擇「是」。', '防火牆授權尚未完成,手機可能無法開啟網頁。請按下方按鈕重試,並在 Windows 管理員授權視窗中選擇「是」。'),+ ('webShareFirewallAllow', 'Check and allow phone connections', '检查并允许手机连接', 'スマートフォンの接続を確認・許可', '檢查並允許手機連線', '檢查並允許手機連線'),+]# 数字类占位符的类型;其余都是字符串