diff --git a/CHANGELOG.md b/CHANGELOG.md index c11317619..6c57bccf0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,8 @@ All notable HyperMeow changes are documented here. HyperMeow uses commit pseudo- - Decode newsletter milestone positions from either quoted or numeric integers without losing precision. - Preserve reported newsletter counter presence, explicit zeros and distinct view definitions. Omit malformed or ambiguous observations, including duplicate view definitions, instead of reporting fabricated zeros or truncated reaction lists. - Copy group-cache metadata under its lock before send-permission checks, including participant and admin slices, so notifications cannot race those reads. +- Stop automatic reconnect and emit `CATRefreshError` to generic and connection-scoped observers when a 413/414 failure cannot refresh its token, including when `RefreshCAT` is unset. The missing callback returns `ErrCATRefreshUnavailable` instead of retrying unchanged credentials. +- Protect the unified-session interval check during concurrent sends. - Keep connection handler completion pending until an active handler exits, and process retired stream errors before automatic reconnect decisions. Manual disconnect retains its five-second wait bound. - Keep the newest pairing secret through bursts of rotation notifications and refresh the active QR code. - Report the destination in `SendFBMessage` responses and decrypt full bot edits using their target message ID. diff --git a/README.md b/README.md index d89bb26c9..e5a0ef861 100644 --- a/README.md +++ b/README.md @@ -249,7 +249,7 @@ See [LICENSING.md](LICENSING.md) for the file-level boundary. ### Connection lifecycle observers `AddConnectionEventHandler(func(context.Context, any))` observes `Connected`, -`Disconnected`, `QR`, `LoggedOut` and `StreamReplaced`. The context is the original +`Disconnected`, `QR`, `LoggedOut`, `StreamReplaced` and `CATRefreshError`. The context is the original connection's `ConnectContext` argument, captured before asynchronous delivery. A delayed event can arrive after that context is cancelled. Compare it with the connection authority your application owns before updating state; do not label an diff --git a/client.go b/client.go index 177db403f..7630e473b 100644 --- a/client.go +++ b/client.go @@ -120,6 +120,7 @@ type Client struct { EnableDecryptedEventBuffer bool synchronousMessageNameUpdates atomic.Bool lastDecryptedBufferClear time.Time + unifiedSessionLock sync.Mutex lastUnifiedSessionSend time.Time UnifiedSessionInterval time.Duration @@ -1345,10 +1346,13 @@ func (cli *Client) sendUnifiedSession(checkLastSend bool) { if cli == nil { return } + cli.unifiedSessionLock.Lock() if checkLastSend && time.Since(cli.lastUnifiedSessionSend) < cli.UnifiedSessionInterval { + cli.unifiedSessionLock.Unlock() return } cli.lastUnifiedSessionSend = time.Now() + cli.unifiedSessionLock.Unlock() node := waBinary.Node{ Tag: "ib", Attrs: waBinary.Attrs{}, diff --git a/client_unified_session_test.go b/client_unified_session_test.go new file mode 100644 index 000000000..08364f18c --- /dev/null +++ b/client_unified_session_test.go @@ -0,0 +1,30 @@ +package whatsmeow + +import ( + "slices" + "sync" + "testing" + "time" +) + +func TestConcurrentUnifiedSessionChecksRespectInterval(t *testing.T) { + cli, _, sent := newTestRemote(t) + cli.UnifiedSessionInterval = time.Hour + start := make(chan struct{}) + var workers sync.WaitGroup + for range 32 { + workers.Go(func() { + <-start + cli.sendUnifiedSession(true) + }) + } + close(start) + workers.Wait() + if tags := sent.tags(); !slices.Equal(tags, []string{"ib:"}) { + t.Fatalf("concurrent interval checks sent %v", tags) + } + cli.sendUnifiedSession(false) + if len(sent.tags()) != 2 { + t.Fatal("explicit unified-session send was incorrectly suppressed") + } +} diff --git a/connection_lifecycle.go b/connection_lifecycle.go index 6c1c151df..191db3a78 100644 --- a/connection_lifecycle.go +++ b/connection_lifecycle.go @@ -10,8 +10,9 @@ import ( "github.com/polymorfa/hypermeow/types/events" ) -// ConnectionEventHandler receives Connected, Disconnected, QR, LoggedOut and -// StreamReplaced with the original connection's ConnectContext. The context may +// ConnectionEventHandler receives Connected, Disconnected, QR, LoggedOut, +// StreamReplaced and CATRefreshError with the original connection's ConnectContext. +// The context may // already be cancelled when a delayed event arrives. Consumers must check their // own current connection authority; an event does not establish ownership. // Other events continue through the existing generic event API only. @@ -52,7 +53,7 @@ func (cli *Client) RemoveConnectionEventHandler(id uint32) bool { // scheduling. Never replace it with client.BackgroundEventCtx or current state. func (cli *Client) dispatchConnectionEvent(ctx context.Context, evt any) (handlerFailed bool) { switch evt.(type) { - case *events.Connected, *events.Disconnected, *events.QR, *events.LoggedOut, *events.StreamReplaced: + case *events.Connected, *events.Disconnected, *events.QR, *events.LoggedOut, *events.StreamReplaced, *events.CATRefreshError: cli.connectionEventHandlersLock.Lock() handlers := append([]wrappedConnectionEventHandler(nil), cli.connectionEventHandlers...) cli.connectionEventHandlersLock.Unlock() diff --git a/connectionevents.go b/connectionevents.go index e96755743..abcdc38f8 100644 --- a/connectionevents.go +++ b/connectionevents.go @@ -53,16 +53,11 @@ func (cli *Client) handleStreamError(ctx context.Context, node *waBinary.Node) { // This seems to happen when the server wants to restart or something. // The disconnection will be emitted as an events.Disconnected and then the auto-reconnect will do its thing. cli.Log.Warnf("Got 503 stream error, assuming automatic reconnect will handle it") - case cli.RefreshCAT != nil && (code == events.ConnectFailureCATInvalid.NumberString() || code == events.ConnectFailureCATExpired.NumberString()): + case code == events.ConnectFailureCATInvalid.NumberString() || code == events.ConnectFailureCATExpired.NumberString(): cli.Log.Infof("Got %s stream error, refreshing CAT before reconnecting...", code) cli.socketLock.RLock() defer cli.socketLock.RUnlock() - err := cli.RefreshCAT(ctx) - if err != nil { - cli.Log.Errorf("Failed to refresh CAT: %v", err) - cli.expectDisconnect() - go cli.dispatchEvent(&events.CATRefreshError{Error: err}) - } + cli.refreshCAT(ctx) default: cli.Log.Errorf("Unknown stream error: %s", node) go cli.dispatchEvent(&events.StreamError{Code: code, Raw: node}) @@ -139,14 +134,9 @@ func (cli *Client) handleConnectFailure(ctx context.Context, node *waBinary.Node } else if reason == events.ConnectFailureClientOutdated { cli.Log.Errorf("Client outdated (405) connect failure (client version: %s)", store.GetWAVersion().String()) go cli.dispatchEvent(&events.ClientOutdated{}) - } else if cli.RefreshCAT != nil && (reason == events.ConnectFailureCATInvalid || reason == events.ConnectFailureCATExpired) { + } else if reason == events.ConnectFailureCATInvalid || reason == events.ConnectFailureCATExpired { cli.Log.Infof("Got %d/%s connect failure, refreshing CAT before reconnecting...", int(reason), message) - err := cli.RefreshCAT(ctx) - if err != nil { - cli.Log.Errorf("Failed to refresh CAT: %v", err) - cli.expectDisconnect() - go cli.dispatchEvent(&events.CATRefreshError{Error: err}) - } + cli.refreshCAT(ctx) } else if willAutoReconnect { cli.Log.Warnf("Got %d/%s connect failure, assuming automatic reconnect will handle it", int(reason), message) } else { @@ -155,6 +145,18 @@ func (cli *Client) handleConnectFailure(ctx context.Context, node *waBinary.Node } } +func (cli *Client) refreshCAT(ctx context.Context) { + err := ErrCATRefreshUnavailable + if cli.RefreshCAT != nil { + err = cli.RefreshCAT(ctx) + } + if err != nil { + cli.Log.Errorf("Failed to refresh CAT: %v", err) + cli.expectDisconnect() + go cli.dispatchConnectionEvent(ctx, &events.CATRefreshError{Error: err}) + } +} + func (cli *Client) handleConnectSuccess(ctx context.Context, node *waBinary.Node) { if !cli.paired.Load() { cli.Log.Warnf("Received connect success without pairing, ignoring") diff --git a/connectionevents_cat_test.go b/connectionevents_cat_test.go new file mode 100644 index 000000000..d54b75c39 --- /dev/null +++ b/connectionevents_cat_test.go @@ -0,0 +1,90 @@ +package whatsmeow + +import ( + "context" + "errors" + "testing" + "time" + + waBinary "github.com/polymorfa/hypermeow/binary" + "github.com/polymorfa/hypermeow/types/events" +) + +func TestCATFailuresRequireSuccessfulRefreshBeforeReconnect(t *testing.T) { + refreshErr := errors.New("synthetic CAT refresh failure") + for _, reason := range []events.ConnectFailureReason{events.ConnectFailureCATExpired, events.ConnectFailureCATInvalid} { + for _, source := range []string{"connect", "stream"} { + for _, outcome := range []string{"unconfigured", "failed", "refreshed"} { + t.Run(source+"/"+reason.NumberString()+"/"+outcome, func(t *testing.T) { + cli, _, _ := newTestRemote(t) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + failures := make(chan *events.CATRefreshError, 1) + scopedFailures := make(chan context.Context, 1) + cli.AddConnectionEventHandler(func(source context.Context, evt any) { + if _, ok := evt.(*events.CATRefreshError); ok { + scopedFailures <- source + } + }) + cli.AddEventHandler(func(evt any) { + if failure, ok := evt.(*events.CATRefreshError); ok { + failures <- failure + } + }) + calls := 0 + if outcome != "unconfigured" { + cli.RefreshCAT = func(got context.Context) error { + calls++ + if got != ctx { + t.Error("CAT refresh lost its connection context") + } + if outcome == "failed" { + return refreshErr + } + return nil + } + } + cli.forceAutoReconnect.Store(true) + if source == "connect" { + cli.handleConnectFailure(ctx, &waBinary.Node{Tag: "failure", Attrs: waBinary.Attrs{"reason": reason.NumberString()}}) + } else { + cli.handleStreamError(ctx, &waBinary.Node{Tag: "stream:error", Attrs: waBinary.Attrs{"code": reason.NumberString()}}) + } + if outcome == "refreshed" { + if calls != 1 || cli.isExpectedDisconnect() { + t.Fatal("successful refresh did not leave reconnect available") + } + select { + case <-failures: + t.Fatal("successful refresh emitted a failure") + default: + } + return + } + if !cli.isExpectedDisconnect() || cli.forceAutoReconnect.Load() { + t.Fatal("CAT failure left automatic reconnect enabled") + } + if outcome == "failed" && calls != 1 || outcome == "unconfigured" && calls != 0 { + t.Fatalf("unexpected CAT refresh calls: %d", calls) + } + select { + case failure := <-failures: + if failure.Error == nil || outcome == "failed" && !errors.Is(failure.Error, refreshErr) { + t.Fatalf("CAT failure lost its error: %v", failure.Error) + } + case <-time.After(time.Second): + t.Fatal("CAT failure did not emit its permanent-disconnect event") + } + select { + case source := <-scopedFailures: + if source != ctx { + t.Fatal("CAT failure lost its original connection context") + } + default: + t.Fatal("CAT failure did not reach connection lifecycle observers") + } + }) + } + } + } +} diff --git a/errors.go b/errors.go index d7ba63306..be16aaf78 100644 --- a/errors.go +++ b/errors.go @@ -25,7 +25,8 @@ var ( ErrNotLoggedIn = errors.New("the store doesn't contain a device JID") ErrMessageTimedOut = errors.New("timed out waiting for message send response") - ErrAlreadyConnected = errors.New("websocket is already connected") + ErrAlreadyConnected = errors.New("websocket is already connected") + ErrCATRefreshUnavailable = errors.New("CAT refresh callback is not configured") ErrPhoneNumberTooShort = errors.New("phone number too short") ErrPhoneNumberIsNotInternational = errors.New("international phone number required (must not start with 0)")