From c3e8e8539fddf3bc1ec39afaebf27ba992fe0d03 Mon Sep 17 00:00:00 2001 From: yibaiba <946100224@qq.com> Date: Wed, 19 Aug 2026 12:20:40 +0800 Subject: [PATCH] fix: preserve notification binding and DNS state --- internal/api/settings_feishu_qr_test.go | 2 +- internal/notify/feishu_binding.go | 38 +++++++++---- internal/notify/feishu_binding_test.go | 15 ++++-- internal/notify/feishu_inbound.go | 12 +++-- internal/notify/feishu_inbound_test.go | 7 ++- .../internal/vowifi/dns/compatibility.go | 11 ++-- .../vowifi-go/internal/vowifi/dns/lookup.go | 4 ++ .../internal/vowifi/dns/lookup_host_test.go | 23 ++++++++ web/src/stores/settings.ts | 11 ++-- .../notificationOnboardingSource.test.ts | 11 ++-- web/tests/settingsNotificationStore.test.ts | 53 +++++++++++++++++++ 11 files changed, 150 insertions(+), 37 deletions(-) create mode 100644 web/tests/settingsNotificationStore.test.ts diff --git a/internal/api/settings_feishu_qr_test.go b/internal/api/settings_feishu_qr_test.go index ef94bcc9..8b07da40 100644 --- a/internal/api/settings_feishu_qr_test.go +++ b/internal/api/settings_feishu_qr_test.go @@ -35,7 +35,7 @@ func TestFeishuQRHandlersPersistConfirmedCredentialsWithoutLeakingSecret(t *test if err := os.WriteFile(configPath, []byte("server:\n port: 7575\n"), 0o600); err != nil { t.Fatal(err) } - cfg := &config.Config{} + cfg := &config.Config{Feishu: config.FeishuConfig{ChatIDs: []string{"oc_configured"}}} stateStore := notify.NewFileRuntimeStateStore(filepath.Join(directory, "notification-state.json")) if err := stateStore.Save(notify.RuntimeState{ Feishu: notify.FeishuRuntimeState{ChatIDs: []string{"oc_unverified"}}, diff --git a/internal/notify/feishu_binding.go b/internal/notify/feishu_binding.go index c777ecb6..78dfe84d 100644 --- a/internal/notify/feishu_binding.go +++ b/internal/notify/feishu_binding.go @@ -21,33 +21,49 @@ func TrustedFeishuBindingFrom(cfg config.FeishuConfig, state FeishuRuntimeState) allowed := mergeUniqueStrings(state.AllowedUsers) chats := configured if state.BindingVerified && len(allowed) > 0 { - chats = mergeUniqueStrings(configured, state.ChatIDs) + chats = mergeUniqueStrings(configured, runtimeFeishuChatIDs(cfg, state)) } return TrustedFeishuBinding{ChatIDs: chats, AllowedUsers: allowed} } -// ApplyFeishuDirectBinding appends a private-chat sender and chat onto the -// trusted binding and marks the binding verified. +// ApplyFeishuDirectBinding records an automatically discovered private chat +// without duplicating statically configured notification targets. func ApplyFeishuDirectBinding(cfg config.FeishuConfig, state FeishuRuntimeState, chatID, senderID string) FeishuRuntimeState { - binding := TrustedFeishuBindingFrom(cfg, state) return FeishuRuntimeState{ - ChatIDs: mergeUniqueStrings(binding.ChatIDs, []string{chatID}), - AllowedUsers: mergeUniqueStrings(binding.AllowedUsers, []string{senderID}), + ChatIDs: mergeUniqueStrings(runtimeFeishuChatIDs(cfg, state), []string{chatID}), + AllowedUsers: mergeUniqueStrings(state.AllowedUsers, []string{senderID}), BindingVerified: true, } } -// ApplyFeishuQRUserBinding records the scanned Open ID without trusting leftover -// unverified runtime chats. +// ApplyFeishuQRUserBinding records the scanned Open ID without copying static or +// leftover unverified chats into runtime state. func ApplyFeishuQRUserBinding(cfg config.FeishuConfig, state FeishuRuntimeState, openID string) FeishuRuntimeState { - binding := TrustedFeishuBindingFrom(cfg, state) return FeishuRuntimeState{ - ChatIDs: binding.ChatIDs, - AllowedUsers: mergeUniqueStrings(binding.AllowedUsers, []string{openID}), + ChatIDs: runtimeFeishuChatIDs(cfg, state), + AllowedUsers: mergeUniqueStrings(state.AllowedUsers, []string{openID}), BindingVerified: true, } } +func runtimeFeishuChatIDs(cfg config.FeishuConfig, state FeishuRuntimeState) []string { + if !state.BindingVerified || len(mergeUniqueStrings(state.AllowedUsers)) == 0 { + return nil + } + configured := mergeUniqueStrings(cfg.ChatIDs, []string{cfg.ChatID}) + configuredSet := make(map[string]struct{}, len(configured)) + for _, chatID := range configured { + configuredSet[chatID] = struct{}{} + } + runtime := make([]string, 0, len(state.ChatIDs)) + for _, chatID := range mergeUniqueStrings(state.ChatIDs) { + if _, isConfigured := configuredSet[chatID]; !isConfigured { + runtime = append(runtime, chatID) + } + } + return runtime +} + func sameFeishuBinding(left, right FeishuRuntimeState) bool { return reflect.DeepEqual(left.ChatIDs, right.ChatIDs) && reflect.DeepEqual(left.AllowedUsers, right.AllowedUsers) && diff --git a/internal/notify/feishu_binding_test.go b/internal/notify/feishu_binding_test.go index f7a029c8..b1f158c8 100644 --- a/internal/notify/feishu_binding_test.go +++ b/internal/notify/feishu_binding_test.go @@ -31,15 +31,17 @@ func TestTrustedFeishuBindingFromMergesVerifiedRuntimeChats(t *testing.T) { } } -func TestApplyFeishuDirectBindingAppendsOntoTrustedSet(t *testing.T) { +func TestApplyFeishuDirectBindingPersistsOnlyRuntimeChats(t *testing.T) { cfg := config.FeishuConfig{ChatIDs: []string{"oc_configured"}} got := ApplyFeishuDirectBinding(cfg, FeishuRuntimeState{ - ChatIDs: []string{"oc_unverified"}, + ChatIDs: []string{"oc_configured", "oc_runtime"}, + AllowedUsers: []string{"ou_existing"}, + BindingVerified: true, }, "oc_owner", "ou_owner") - if !reflect.DeepEqual(got.ChatIDs, []string{"oc_configured", "oc_owner"}) { + if !reflect.DeepEqual(got.ChatIDs, []string{"oc_runtime", "oc_owner"}) { t.Fatalf("bound chats = %#v", got.ChatIDs) } - if !reflect.DeepEqual(got.AllowedUsers, []string{"ou_owner"}) || !got.BindingVerified { + if !reflect.DeepEqual(got.AllowedUsers, []string{"ou_existing", "ou_owner"}) || !got.BindingVerified { t.Fatalf("bound state = %+v", got) } } @@ -49,10 +51,13 @@ func TestApplyFeishuQRUserBindingDropsUnverifiedChats(t *testing.T) { got := ApplyFeishuQRUserBinding(cfg, FeishuRuntimeState{ ChatIDs: []string{"oc_unverified"}, }, "ou_owner") - if !reflect.DeepEqual(got.ChatIDs, []string{"oc_configured"}) { + if len(got.ChatIDs) != 0 { t.Fatalf("qr chats = %#v", got.ChatIDs) } if !reflect.DeepEqual(got.AllowedUsers, []string{"ou_owner"}) || !got.BindingVerified { t.Fatalf("qr state = %+v", got) } + if reloaded := TrustedFeishuBindingFrom(config.FeishuConfig{}, got); len(reloaded.ChatIDs) != 0 { + t.Fatalf("removed configured chat was restored: %#v", reloaded.ChatIDs) + } } diff --git a/internal/notify/feishu_inbound.go b/internal/notify/feishu_inbound.go index 109ae41a..5e920bad 100644 --- a/internal/notify/feishu_inbound.go +++ b/internal/notify/feishu_inbound.go @@ -129,8 +129,7 @@ func (f *FeishuChannel) persistDirectBindingLocked(chatID, senderID string) (boo ChatIDs: f.chatIDs, AllowedUsers: f.allowedUsers, BindingVerified: true, } next := ApplyFeishuDirectBinding(f.cfg, current, chatID, senderID) - f.chatIDs = next.ChatIDs - f.allowedUsers = next.AllowedUsers + f.applyTrustedBindingLocked(next) return !sameFeishuBinding(current, next), nil } bound := false @@ -145,11 +144,16 @@ func (f *FeishuChannel) persistDirectBindingLocked(chatID, senderID string) (boo }); err != nil { return false, err } - f.chatIDs = stored.ChatIDs - f.allowedUsers = stored.AllowedUsers + f.applyTrustedBindingLocked(stored) return bound, nil } +func (f *FeishuChannel) applyTrustedBindingLocked(state FeishuRuntimeState) { + binding := TrustedFeishuBindingFrom(f.cfg, state) + f.chatIDs = binding.ChatIDs + f.allowedUsers = binding.AllowedUsers +} + func feishuSenderID(event *larkim.P2MessageReceiveV1) string { if event == nil || event.Event == nil || event.Event.Sender == nil || event.Event.Sender.SenderId == nil { return "" diff --git a/internal/notify/feishu_inbound_test.go b/internal/notify/feishu_inbound_test.go index 9ede90bc..fcc9f8e8 100644 --- a/internal/notify/feishu_inbound_test.go +++ b/internal/notify/feishu_inbound_test.go @@ -75,8 +75,8 @@ func TestFeishuFirstPrivateBindingRemovesUnverifiedRuntimeChats(t *testing.T) { if err != nil { t.Fatal(err) } - if !reflect.DeepEqual(state.Feishu.ChatIDs, []string{"oc_configured", "oc_owner"}) { - t.Fatalf("trusted chat ids = %#v", state.Feishu.ChatIDs) + if !reflect.DeepEqual(state.Feishu.ChatIDs, []string{"oc_owner"}) { + t.Fatalf("runtime chat ids = %#v", state.Feishu.ChatIDs) } if !reflect.DeepEqual(state.Feishu.AllowedUsers, []string{"ou_owner"}) { t.Fatalf("allowed users = %#v", state.Feishu.AllowedUsers) @@ -84,6 +84,9 @@ func TestFeishuFirstPrivateBindingRemovesUnverifiedRuntimeChats(t *testing.T) { if !state.Feishu.BindingVerified { t.Fatal("binding was not marked verified") } + if got := channel.notificationChatIDs(); !reflect.DeepEqual(got, []string{"oc_configured", "oc_owner"}) { + t.Fatalf("notification chat ids = %#v", got) + } } func TestFeishuChannelIgnoresUnverifiedRuntimeChatsOnStartup(t *testing.T) { diff --git a/third_party/vowifi-go/internal/vowifi/dns/compatibility.go b/third_party/vowifi-go/internal/vowifi/dns/compatibility.go index d4a31950..0e9523e4 100644 --- a/third_party/vowifi-go/internal/vowifi/dns/compatibility.go +++ b/third_party/vowifi-go/internal/vowifi/dns/compatibility.go @@ -170,11 +170,14 @@ func resolverForEndpoint(endpoint string) (queryResolver, error) { if err != nil { host, port = endpoint, defaultDNSPort } - ip := net.ParseIP(strings.Trim(host, "[]")) - if ip == nil { - return nil, fmt.Errorf("dns: DNS server must be an IP address: %q", endpoint) + host = strings.Trim(strings.TrimSpace(host), "[]") + if ip := net.ParseIP(host); ip != nil { + return newServerResolverAt(nil, ip, port), nil } - return newServerResolverAt(nil, ip, port), nil + if err != nil || host == "" { + return nil, fmt.Errorf("dns: DNS server must be an IP address or host:port: %q", endpoint) + } + return newServerResolverForAddress(nil, net.JoinHostPort(host, port)), nil } // NormalizeRegistrarCandidates retains structured defaulting and deduplication. diff --git a/third_party/vowifi-go/internal/vowifi/dns/lookup.go b/third_party/vowifi-go/internal/vowifi/dns/lookup.go index 4f940219..dfcbe93d 100644 --- a/third_party/vowifi-go/internal/vowifi/dns/lookup.go +++ b/third_party/vowifi-go/internal/vowifi/dns/lookup.go @@ -29,6 +29,10 @@ func newServerResolver(bindIP, server net.IP) queryResolver { func newServerResolverAt(bindIP, server net.IP, port string) queryResolver { address := net.JoinHostPort(server.String(), port) + return newServerResolverForAddress(bindIP, address) +} + +func newServerResolverForAddress(bindIP net.IP, address string) queryResolver { dialer := &net.Dialer{} if bindIP != nil { dialer.LocalAddr = &net.UDPAddr{IP: bindIP} diff --git a/third_party/vowifi-go/internal/vowifi/dns/lookup_host_test.go b/third_party/vowifi-go/internal/vowifi/dns/lookup_host_test.go index cbc19160..4eec0158 100644 --- a/third_party/vowifi-go/internal/vowifi/dns/lookup_host_test.go +++ b/third_party/vowifi-go/internal/vowifi/dns/lookup_host_test.go @@ -16,6 +16,29 @@ func TestLookupHostIPStagedRejectsInvalidConfiguredServer(t *testing.T) { } } +func TestLookupHostIPStagedAcceptsConfiguredHostnameEndpoint(t *testing.T) { + ClearHostIPCache() + t.Cleanup(ClearHostIPCache) + got, err := lookupHostIPStaged(context.Background(), "epdg.test", "dns.google:53", hostLookupFuncs{ + viaServer: func(_ context.Context, _ string, server string) ([]net.IP, error) { + if server != "dns.google:53" { + t.Fatalf("server = %q", server) + } + return []net.IP{net.IPv4(192, 0, 2, 41)}, nil + }, + viaSystem: func(context.Context, string) ([]net.IP, error) { + t.Fatal("system resolver should not run after configured success") + return nil, errors.New("unused") + }, + }) + if err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(ipStrings(got), []string{"192.0.2.41"}) { + t.Fatalf("ips = %v", ipStrings(got)) + } +} + func TestLookupHostIPStagedPrefersLiveLookupOverCache(t *testing.T) { ClearHostIPCache() t.Cleanup(ClearHostIPCache) diff --git a/web/src/stores/settings.ts b/web/src/stores/settings.ts index 0b0cdcfa..3b005f59 100644 --- a/web/src/stores/settings.ts +++ b/web/src/stores/settings.ts @@ -240,7 +240,7 @@ export const useSettingsStore = defineStore('settings', () => { if (!options.silent) { loadingNotifications.value = true } - const result = await getNotificationSnapshot() + const result = await getNotificationSnapshot(true) if (result.ok) { notifications.value = result.data || {} const tg = result.data.telegram || {} @@ -353,7 +353,8 @@ export const useSettingsStore = defineStore('settings', () => { return result } - async function getNotificationSnapshot() { + async function getNotificationSnapshot(fresh = false) { + if (fresh) return systemService.getNotifications() if (!notificationSnapshotRequest) { notificationSnapshotRequest = systemService.getNotifications() } @@ -405,15 +406,11 @@ export const useSettingsStore = defineStore('settings', () => { } } - function mergeNotificationBinding(channel: NotificationBindingChannel, data: NotificationsSettingsResponse) { - notificationBindingHandlers[channel].merge(data) - } - async function refreshNotificationSnapshot( channel: NotificationBindingChannel, mode: 'replace' | 'merge' ) { - const result = await getNotificationSnapshot() + const result = await getNotificationSnapshot(mode === 'replace') if (result.ok) { notificationBindingHandlers[channel][mode](result.data) error.value = null diff --git a/web/tests/notificationOnboardingSource.test.ts b/web/tests/notificationOnboardingSource.test.ts index 0efe13ee..48c9a6ed 100644 --- a/web/tests/notificationOnboardingSource.test.ts +++ b/web/tests/notificationOnboardingSource.test.ts @@ -65,12 +65,17 @@ test('WeCom QR reminds the user to message the bot after scan', () => { assert.match(qrPanel, /shouldShowQRActivateHint\(props\.session, props\.connected\)/) }) -test('binding polling merges only target IDs and coalesces overlapping requests', () => { +test('binding polling coalesces snapshots while full refresh starts a fresh request', () => { assert.match(settingsStore, /notificationSnapshotRequest/) - assert.match(settingsStore, /mergeNotificationBinding/) + assert.match(settingsStore, /notificationBindingHandlers\[channel\]\[mode\]/) assert.match(settingsStore, /mergeIDs\(feishuForm\.value\.chat_ids/) assert.doesNotMatch(bindingPolling, /fetchNotifications/) - assert.equal(settingsStore.match(/systemService\.getNotifications\(\)/g)?.length, 1) + assert.match( + settingsStore, + /async function fetchNotifications[\s\S]*?const result = await getNotificationSnapshot\(true\)/ + ) + assert.match(settingsStore, /getNotificationSnapshot\(mode === 'replace'\)/) + assert.equal(settingsStore.match(/systemService\.getNotifications\(\)/g)?.length, 2) }) test('QR panel renders a stable code and accessible status and actions', () => { diff --git a/web/tests/settingsNotificationStore.test.ts b/web/tests/settingsNotificationStore.test.ts new file mode 100644 index 00000000..b49c4f77 --- /dev/null +++ b/web/tests/settingsNotificationStore.test.ts @@ -0,0 +1,53 @@ +import assert from 'node:assert/strict' +import test from 'node:test' +import { createPinia, setActivePinia } from 'pinia' +import { + systemService, + type NotificationsSettingsResponse +} from '../src/services/system.ts' +import { useSettingsStore } from '../src/stores/settings.ts' +import { ok, type ServiceResult } from '../src/types/domain.ts' + +function deferred() { + let resolve!: (value: T) => void + const promise = new Promise(done => { resolve = done }) + return { promise, resolve } +} + +test('a full notification refresh does not reuse an older binding snapshot', async () => { + const originalGetNotifications = systemService.getNotifications + const stale = deferred>() + const current = deferred>() + const requests = [stale, current] + let requestCount = 0 + systemService.getNotifications = async () => { + requestCount += 1 + return requests.shift()!.promise + } + + try { + setActivePinia(createPinia()) + const store = useSettingsStore() + const staleBindingRefresh = store.refreshNotificationBinding('feishu') + const currentFullRefresh = store.fetchNotifications({ silent: true }) + + assert.equal(requestCount, 2) + current.resolve(ok({ + feishu: { chat_ids: ['oc_current'] }, + qq: { enabled: true, app_id: 'qq_current', direct_ids: 'user_current' } + })) + await currentFullRefresh + + stale.resolve(ok({ + feishu: { chat_ids: ['oc_stale'] }, + qq: { enabled: false, app_id: 'qq_stale', direct_ids: '' } + })) + await staleBindingRefresh + + assert.equal(store.qqForm.enabled, true) + assert.equal(store.qqForm.app_id, 'qq_current') + assert.equal(store.qqForm.direct_ids, 'user_current') + } finally { + systemService.getNotifications = originalGetNotifications + } +})