fix: preserve notification binding and DNS state

This commit is contained in:
yibaiba committed 2026-08-19 12:20:40 +08:00
1 parent 84b86ecccd
commit c3e8e8539f
11 files changed
+150 -37

No files matched your search

+1 -1
View File
@@ -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"}},
+27 -11
View File
@@ -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) &&
+10 -5
View File
@@ -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)
}
}
+8 -4
View File
@@ -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 ""
+5 -2
View File
@@ -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) {
+7 -4
View File
@@ -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.
+4
View File
@@ -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}
@@ -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)
+4 -7
View File
@@ -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
@@ -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', () => {
@@ -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<T>() {
let resolve!: (value: T) => void
const promise = new Promise<T>(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<ServiceResult<NotificationsSettingsResponse>>()
const current = deferred<ServiceResult<NotificationsSettingsResponse>>()
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
}
})