Skip to content

GOWA - WhatsApp REST API with support for UI, Multi Account, Webhooks, and MCP, and Chatwoot. Built with Golang for efficient memory use.

fix(send): stop retrying WhatsApp error 463 and surface it honestly (#708)

Aldino Kemal496e6d7c3e56
diff --git a/src/infrastructure/whatsapp/reachout_error.go b/src/infrastructure/whatsapp/reachout_error.go
new file mode 100644
index 00000000..e8208add
--- /dev/null
+++ b/src/infrastructure/whatsapp/reachout_error.go
@@ -0,0 +1,27 @@
+package whatsapp
+
+import (
+ "errors"
+ "strings"
+
+ "go.mau.fi/whatsmeow"
+)
+
+// IsReachoutTimelockError reports whether err is WhatsApp server error 463
+// (NackCallerReachoutTimelocked / "reach-out timelock"). This is WhatsApp's
+// server-side anti-spam restriction on starting new chats: it surfaces when the
+// recipient has no prior conversation with this account (no stored privacy
+// token) or the sending account is temporarily restricted from reaching new
+// contacts. It is enforced by WhatsApp and cannot be bypassed by the client —
+// the trusted-contact token whatsmeow attaches on the outbound path can only
+// originate from the recipient's side (an inbound message, a privacy_token
+// notification, or history sync).
+//
+// whatsmeow formats this error as fmt.Errorf("%w %d", ErrServerReturnedError,
+// code) → "server returned error 463". errors.Is gates on the sentinel; the
+// leading-space suffix guards against false matches like "4631".
+func IsReachoutTimelockError(err error) bool {
+ return err != nil &&
+ errors.Is(err, whatsmeow.ErrServerReturnedError) &&
+ strings.HasSuffix(err.Error(), " 463")
+}
diff --git a/src/infrastructure/whatsapp/reachout_error_test.go b/src/infrastructure/whatsapp/reachout_error_test.go
new file mode 100644
index 00000000..e2059266
--- /dev/null
+++ b/src/infrastructure/whatsapp/reachout_error_test.go
@@ -0,0 +1,42 @@
+package whatsapp
+
+import (
+ "errors"
+ "testing"
+
+ "go.mau.fi/whatsmeow"
+)
+
+// reachoutErr mimics the error whatsmeow produces for server error 463:
+// fmt.Errorf("%w %d", ErrServerReturnedError, 463).
+func reachoutErr() error {
+ return errors.Join(whatsmeow.ErrServerReturnedError, errors.New("server returned error 463"))
+}
+
+func nonReachoutServerErr(code string) error {
+ return errors.Join(whatsmeow.ErrServerReturnedError, errors.New("server returned error "+code))
+}
+
+func TestIsReachoutTimelockError(t *testing.T) {
+ tests := []struct {
+ name string
+ err error
+ want bool
+ }{
+ {"nil", nil, false},
+ {"wrapped 463", reachoutErr(), true},
+ {"wrapped non-463", nonReachoutServerErr("500"), false},
+ {"unrelated error", errors.New("network unreachable"), false},
+ {"bare 463 string without sentinel", errors.New("error 463"), false},
+ {"sentinel but no 463", nonReachoutServerErr("400"), false},
+ {"superstring 4631 must not match", nonReachoutServerErr("4631"), false},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ if got := IsReachoutTimelockError(tt.err); got != tt.want {
+ t.Fatalf("IsReachoutTimelockError(%v) = %v, want %v", tt.err, got, tt.want)
+ }
+ })
+ }
+}
diff --git a/src/infrastructure/whatsapp/send_retry.go b/src/infrastructure/whatsapp/send_retry.go
deleted file mode 100644
index 185fa182..00000000
--- a/src/infrastructure/whatsapp/send_retry.go
+++ /dev/null
@@ -1,130 +0,0 @@
-package whatsapp
-
-import (
- "context"
- "errors"
- "strings"
- "time"
-
- "github.com/sirupsen/logrus"
- "go.mau.fi/whatsmeow"
- "go.mau.fi/whatsmeow/proto/waE2E"
- "go.mau.fi/whatsmeow/types"
-)
-
-// reachoutSubscribeTimeout bounds the pre-warm SubscribePresence so an
-// unhealthy socket cannot stall the retry. One round-trip's worth of slack.
-const reachoutSubscribeTimeout = 3 * time.Second
-
-var (
- reachoutPrivacyTokenWait = 2 * time.Second
- reachoutPrivacyTokenPollPeriod = 50 * time.Millisecond
-)
-
-// Seams for unit tests. Mirrors the submitWebhookFn pattern in webhook_forward.go.
-var (
- sendMessageFn = func(ctx context.Context, client *whatsmeow.Client, recipient types.JID, msg *waE2E.Message) (whatsmeow.SendResponse, error) {
- return client.SendMessage(ctx, recipient, msg)
- }
- subscribePresenceFn = func(ctx context.Context, client *whatsmeow.Client, recipient types.JID) error {
- return client.SubscribePresence(ctx, recipient)
- }
-)
-
-// IsReachoutTimelockError reports whether err is WhatsApp server error 463
-// (NackCallerReachoutTimelocked) — surfaced when the recipient's privacy
-// token (tctoken) is missing/expired or the recipient is a cold contact.
-//
-// whatsmeow formats this error as fmt.Errorf("%w %d", ErrServerReturnedError,
-// code) → "server returned error 463". errors.Is gates on the sentinel; the
-// leading-space suffix guards against false matches like "4631".
-func IsReachoutTimelockError(err error) bool {
- return err != nil &&
- errors.Is(err, whatsmeow.ErrServerReturnedError) &&
- strings.HasSuffix(err.Error(), " 463")
-}
-
-// SendMessageWithReachoutRetry sends msg to recipient and, if the send fails
-// with WhatsApp error 463 on a 1:1 user JID, performs a SubscribePresence
-// pre-warm and retries the send exactly once.
-//
-// SubscribePresence is the only step in WA-Web's chat-open sequence that
-// participates in whatsmeow's privacy-token path (it attaches any cached
-// tctoken to the subscribe stanza). The retry itself does the real work:
-// whatsmeow's post-send issuePrivacyTokenAndSave runs on the failed first
-// attempt and lets the second succeed once a token is in place.
-//
-// Group/broadcast/newsletter/legacy-server JIDs skip the retry — 463 does
-// not apply to them.
-func SendMessageWithReachoutRetry(ctx context.Context, client *whatsmeow.Client, recipient types.JID, msg *waE2E.Message) (whatsmeow.SendResponse, error) {
- resp, err := sendMessageFn(ctx, client, recipient, msg)
- if err == nil || !IsReachoutTimelockError(err) || !isUserJID(recipient) {
- return resp, err
- }
-
- logrus.Warnf("Send to %s rejected with WhatsApp error 463; subscribing to presence and retrying once", recipient.String())
-
- // Detached context so an upstream cancel cannot abort the subscribe
- // mid-flight. Device scoping (via ContextWithDevice) is preserved.
- warmCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), reachoutSubscribeTimeout)
- if subscribeErr := subscribePresenceFn(warmCtx, client, recipient); subscribeErr != nil {
- logrus.Debugf("Pre-warm SubscribePresence for %s failed: %v", recipient.String(), subscribeErr)
- }
- cancel()
-
- if waitForReachoutPrivacyToken(ctx, client, recipient) {
- logrus.Debugf("Privacy token for %s became available before retry", recipient.String())
- } else {
- logrus.Debugf("Retrying send to %s without an observed privacy token", recipient.String())
- }
-
- resp, err = sendMessageFn(ctx, client, recipient, msg)
- if err != nil {
- logrus.Warnf("Retry send to %s after pre-warm still failed: %v", recipient.String(), err)
- } else {
- logrus.Infof("Retry send to %s after pre-warm succeeded", recipient.String())
- }
- return resp, err
-}
-
-// isUserJID reports whether the JID is a 1:1 user JID (regular or hidden/LID).
-// Error 463 does not apply to group/broadcast/newsletter/legacy-server JIDs.
-func isUserJID(jid types.JID) bool {
- return jid.Server == types.DefaultUserServer || jid.Server == types.HiddenUserServer
-}
-
-func waitForReachoutPrivacyToken(ctx context.Context, client *whatsmeow.Client, recipient types.JID) bool {
- if client == nil || client.Store == nil || client.Store.PrivacyTokens == nil {
- return false
- }
-
- waitCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), reachoutPrivacyTokenWait)
- defer cancel()
-
- if hasReachoutPrivacyToken(waitCtx, client, recipient) {
- return true
- }
-
- ticker := time.NewTicker(reachoutPrivacyTokenPollPeriod)
- defer ticker.Stop()
-
- for {
- select {
- case <-waitCtx.Done():
- return false
- case <-ticker.C:
- if hasReachoutPrivacyToken(waitCtx, client, recipient) {
- return true
- }
- }
- }
-}
-
-func hasReachoutPrivacyToken(ctx context.Context, client *whatsmeow.Client, recipient types.JID) bool {
- token, err := client.Store.PrivacyTokens.GetPrivacyToken(ctx, recipient.ToNonAD())
- if err != nil {
- logrus.Debugf("Failed to check privacy token for %s before retry: %v", recipient.String(), err)
- return false
- }
- return token != nil && len(token.Token) > 0
-}
diff --git a/src/infrastructure/whatsapp/send_retry_test.go b/src/infrastructure/whatsapp/send_retry_test.go
deleted file mode 100644
index fd82d524..00000000
--- a/src/infrastructure/whatsapp/send_retry_test.go
+++ /dev/null
@@ -1,330 +0,0 @@
-package whatsapp
-
-import (
- "context"
- "errors"
- "sync"
- "testing"
- "time"
-
- "go.mau.fi/whatsmeow"
- "go.mau.fi/whatsmeow/proto/waE2E"
- "go.mau.fi/whatsmeow/store"
- "go.mau.fi/whatsmeow/types"
-)
-
-// reachoutErr mimics the error whatsmeow produces for server error 463:
-// fmt.Errorf("%w %d", ErrServerReturnedError, 463).
-func reachoutErr() error {
- return errors.Join(whatsmeow.ErrServerReturnedError, errors.New("server returned error 463"))
-}
-
-func nonReachoutServerErr(code string) error {
- return errors.Join(whatsmeow.ErrServerReturnedError, errors.New("server returned error "+code))
-}
-
-func TestIsReachoutTimelockError(t *testing.T) {
- tests := []struct {
- name string
- err error
- want bool
- }{
- {"nil", nil, false},
- {"wrapped 463", reachoutErr(), true},
- {"wrapped non-463", nonReachoutServerErr("500"), false},
- {"unrelated error", errors.New("network unreachable"), false},
- {"bare 463 string without sentinel", errors.New("error 463"), false},
- {"sentinel but no 463", nonReachoutServerErr("400"), false},
- {"superstring 4631 must not match", nonReachoutServerErr("4631"), false},
- }
-
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- if got := IsReachoutTimelockError(tt.err); got != tt.want {
- t.Fatalf("IsReachoutTimelockError(%v) = %v, want %v", tt.err, got, tt.want)
- }
- })
- }
-}
-
-func TestSendMessageWithReachoutRetry(t *testing.T) {
- userJID := types.JID{User: "12345", Server: types.DefaultUserServer}
- lidJID := types.JID{User: "12345", Server: types.HiddenUserServer}
- groupJID := types.JID{User: "12345-67890", Server: types.GroupServer}
-
- type result struct {
- resp whatsmeow.SendResponse
- err error
- }
-
- tests := []struct {
- name string
- recipient types.JID
- first result
- second result
- wantSendCalls int
- wantSubscribes int
- wantErrIs error
- wantRespID string
- }{
- {
- name: "success on first attempt",
- recipient: userJID,
- first: result{resp: whatsmeow.SendResponse{ID: "msg-1"}},
- wantSendCalls: 1,
- wantSubscribes: 0,
- wantRespID: "msg-1",
- },
- {
- name: "non-463 error is not retried",
- recipient: userJID,
- first: result{err: nonReachoutServerErr("500")},
- wantSendCalls: 1,
- wantSubscribes: 0,
- wantErrIs: whatsmeow.ErrServerReturnedError,
- },
- {
- name: "463 on user JID retries and succeeds",
- recipient: userJID,
- first: result{err: reachoutErr()},
- second: result{resp: whatsmeow.SendResponse{ID: "msg-retry"}},
- wantSendCalls: 2,
- wantSubscribes: 1,
- wantRespID: "msg-retry",
- },
- {
- name: "463 on LID JID retries and succeeds",
- recipient: lidJID,
- first: result{err: reachoutErr()},
- second: result{resp: whatsmeow.SendResponse{ID: "msg-retry-lid"}},
- wantSendCalls: 2,
- wantSubscribes: 1,
- wantRespID: "msg-retry-lid",
- },
- {
- name: "463 on user JID retries and still fails",
- recipient: userJID,
- first: result{err: reachoutErr()},
- second: result{err: reachoutErr()},
- wantSendCalls: 2,
- wantSubscribes: 1,
- wantErrIs: whatsmeow.ErrServerReturnedError,
- },
- {
- name: "463 on group JID is not retried",
- recipient: groupJID,
- first: result{err: reachoutErr()},
- wantSendCalls: 1,
- wantSubscribes: 0,
- wantErrIs: whatsmeow.ErrServerReturnedError,
- },
- }
-
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- origSend := sendMessageFn
- origSub := subscribePresenceFn
- defer func() {
- sendMessageFn = origSend
- subscribePresenceFn = origSub
- }()
-
- var sendCalls, subscribes int
- sendMessageFn = func(_ context.Context, _ *whatsmeow.Client, _ types.JID, _ *waE2E.Message) (whatsmeow.SendResponse, error) {
- sendCalls++
- if sendCalls == 1 {
- return tt.first.resp, tt.first.err
- }
- return tt.second.resp, tt.second.err
- }
- subscribePresenceFn = func(_ context.Context, _ *whatsmeow.Client, _ types.JID) error {
- subscribes++
- return nil
- }
-
- resp, err := SendMessageWithReachoutRetry(context.Background(), nil, tt.recipient, &waE2E.Message{})
-
- if sendCalls != tt.wantSendCalls {
- t.Errorf("send calls = %d, want %d", sendCalls, tt.wantSendCalls)
- }
- if subscribes != tt.wantSubscribes {
- t.Errorf("subscribe calls = %d, want %d", subscribes, tt.wantSubscribes)
- }
- if tt.wantErrIs != nil {
- if !errors.Is(err, tt.wantErrIs) {
- t.Errorf("err = %v, want errors.Is(..., %v)", err, tt.wantErrIs)
- }
- } else {
- if err != nil {
- t.Errorf("err = %v, want nil", err)
- }
- if resp.ID != tt.wantRespID {
- t.Errorf("resp.ID = %q, want %q", resp.ID, tt.wantRespID)
- }
- }
- })
- }
-}
-
-func TestSendMessageWithReachoutRetry_SubscribeFailureDoesNotAbortRetry(t *testing.T) {
- origSend := sendMessageFn
- origSub := subscribePresenceFn
- defer func() {
- sendMessageFn = origSend
- subscribePresenceFn = origSub
- }()
-
- var sendCalls int
- sendMessageFn = func(_ context.Context, _ *whatsmeow.Client, _ types.JID, _ *waE2E.Message) (whatsmeow.SendResponse, error) {
- sendCalls++
- if sendCalls == 1 {
- return whatsmeow.SendResponse{}, reachoutErr()
- }
- return whatsmeow.SendResponse{ID: "msg-retry"}, nil
- }
- subscribePresenceFn = func(_ context.Context, _ *whatsmeow.Client, _ types.JID) error {
- return errors.New("subscribe boom")
- }
-
- resp, err := SendMessageWithReachoutRetry(
- context.Background(),
- nil,
- types.JID{User: "12345", Server: types.DefaultUserServer},
- &waE2E.Message{},
- )
- if err != nil {
- t.Fatalf("expected retry to succeed despite subscribe failure, got %v", err)
- }
- if resp.ID != "msg-retry" {
- t.Fatalf("expected retry result, got %q", resp.ID)
- }
- if sendCalls != 2 {
- t.Fatalf("expected 2 send attempts, got %d", sendCalls)
- }
-}
-
-func TestSendMessageWithReachoutRetry_WaitsForPrivacyTokenBeforeRetry(t *testing.T) {
- origSend := sendMessageFn
- origSub := subscribePresenceFn
- defer func() {
- sendMessageFn = origSend
- subscribePresenceFn = origSub
- }()
-
- recipient := types.JID{User: "12345", Server: types.DefaultUserServer}
- tokenStore := &memoryPrivacyTokenStore{}
- client := &whatsmeow.Client{
- Store: &store.Device{
- PrivacyTokens: tokenStore,
- },
- }
-
- var sendCalls int
- sendMessageFn = func(ctx context.Context, client *whatsmeow.Client, recipient types.JID, _ *waE2E.Message) (whatsmeow.SendResponse, error) {
- sendCalls++
- if sendCalls == 1 {
- return whatsmeow.SendResponse{}, reachoutErr()
- }
- token, err := client.Store.PrivacyTokens.GetPrivacyToken(ctx, recipient)
- if err != nil {
- return whatsmeow.SendResponse{}, err
- }
- if token == nil {
- return whatsmeow.SendResponse{}, reachoutErr()
- }
- return whatsmeow.SendResponse{ID: "msg-after-token"}, nil
- }
- subscribePresenceFn = func(context.Context, *whatsmeow.Client, types.JID) error {
- go func() {
- time.Sleep(25 * time.Millisecond)
- _ = tokenStore.PutPrivacyTokens(context.Background(), store.PrivacyToken{
- User: recipient,
- Token: []byte("token"),
- Timestamp: time.Now(),
- })
- }()
- return nil
- }
-
- resp, err := SendMessageWithReachoutRetry(context.Background(), client, recipient, &waE2E.Message{})
- if err != nil {
- t.Fatalf("expected retry to wait for token and succeed, got %v", err)
- }
- if resp.ID != "msg-after-token" {
- t.Fatalf("expected retry response after token, got %q", resp.ID)
- }
- if sendCalls != 2 {
- t.Fatalf("expected 2 send attempts, got %d", sendCalls)
- }
-}
-
-func TestSendMessageWithReachoutRetry_RetriesWhenPrivacyTokenNeverAppears(t *testing.T) {
- origSend := sendMessageFn
- origSub := subscribePresenceFn
- origWait := reachoutPrivacyTokenWait
- origPoll := reachoutPrivacyTokenPollPeriod
- defer func() {
- sendMessageFn = origSend
- subscribePresenceFn = origSub
- reachoutPrivacyTokenWait = origWait
- reachoutPrivacyTokenPollPeriod = origPoll
- }()
-
- reachoutPrivacyTokenWait = 20 * time.Millisecond
- reachoutPrivacyTokenPollPeriod = 5 * time.Millisecond
-
- recipient := types.JID{User: "12345", Server: types.DefaultUserServer}
- client := &whatsmeow.Client{
- Store: &store.Device{
- PrivacyTokens: &memoryPrivacyTokenStore{},
- },
- }
-
- var sendCalls int
- sendMessageFn = func(context.Context, *whatsmeow.Client, types.JID, *waE2E.Message) (whatsmeow.SendResponse, error) {
- sendCalls++
- return whatsmeow.SendResponse{}, reachoutErr()
- }
- subscribePresenceFn = func(context.Context, *whatsmeow.Client, types.JID) error {
- return nil
- }
-
- _, err := SendMessageWithReachoutRetry(context.Background(), client, recipient, &waE2E.Message{})
- if !errors.Is(err, whatsmeow.ErrServerReturnedError) {
- t.Fatalf("expected original reachout error after retry, got %v", err)
- }
- if sendCalls != 2 {
- t.Fatalf("expected 2 send attempts, got %d", sendCalls)
- }
-}
-
-type memoryPrivacyTokenStore struct {
- mu sync.RWMutex
- tokens map[types.JID]store.PrivacyToken
-}
-
-func (s *memoryPrivacyTokenStore) PutPrivacyTokens(_ context.Context, tokens ...store.PrivacyToken) error {
- s.mu.Lock()
- defer s.mu.Unlock()
- if s.tokens == nil {
- s.tokens = make(map[types.JID]store.PrivacyToken)
- }
- for _, token := range tokens {
- s.tokens[token.User.ToNonAD()] = token
- }
- return nil
-}
-
-func (s *memoryPrivacyTokenStore) GetPrivacyToken(_ context.Context, user types.JID) (*store.PrivacyToken, error) {
- s.mu.RLock()
- defer s.mu.RUnlock()
- token, ok := s.tokens[user.ToNonAD()]
- if !ok {
- return nil, nil
- }
- return &token, nil
-}
-
-func (s *memoryPrivacyTokenStore) DeleteExpiredPrivacyTokens(context.Context, time.Time) (int64, error) {
- return 0, nil
-}
diff --git a/src/pkg/error/whatsapp_error.go b/src/pkg/error/whatsapp_error.go
index 7295b468..2e62607c 100644
--- a/src/pkg/error/whatsapp_error.go
+++ b/src/pkg/error/whatsapp_error.go
@@ -91,5 +91,5 @@ const (
ErrInvalidJID = InvalidJID("your JID is invalid")
ErrUserNotRegistered = InvalidJID("user is not registered")
ErrWaCLI = WaCliError("your WhatsApp CLI is invalid or empty")
- ErrWaReachoutTimelock = WaReachoutTimelockError("WhatsApp rejected this send (error 463). This usually means the recipient is a cold contact (no prior conversation), the WhatsApp account is restricted to mobile-only by Meta, or privacy tokens are missing/expired. Try messaging this number from the official WhatsApp app once, ask the recipient to message you first, or wait a few minutes before retrying. An automatic pre-warm + retry has already been attempted by the server.")
+ ErrWaReachoutTimelock = WaReachoutTimelockError("WhatsApp rejected this send with error 463 (reach-out timelock). This is WhatsApp's server-side anti-spam restriction on starting new chats and cannot be bypassed by the API. It usually means there is no prior conversation with this recipient, or the sending account is temporarily restricted from reaching new contacts. To get through: ask the recipient to message you first, reply within an already-established conversation, or open and send the chat once from the phone linked to this session, then reduce your sending rate and wait for the restriction to clear. Newly-linked or low-activity numbers are affected most.")
)
diff --git a/src/usecase/send.go b/src/usecase/send.go
index d3670bee..b415afda 100644
--- a/src/usecase/send.go
+++ b/src/usecase/send.go
@@ -51,11 +51,11 @@ func NewSendService(appService app.IAppUsecase, chatStorageRepo domainChatStorag
}
// wrapSendMessage sends the message and stores it asynchronously on success.
-// The send goes through whatsapp.SendMessageWithReachoutRetry, which retries
-// once on WhatsApp error 463 after a SubscribePresence pre-warm — see
-// infrastructure/whatsapp/send_retry.go for the protocol-level rationale.
+// whatsmeow handles the trusted-contact (tctoken) lifecycle internally; a 463
+// "reach-out timelock" rejection is a WhatsApp server-side restriction that the
+// client cannot retry around, so it is surfaced as-is via normalizeSendError.
func (service serviceSend) wrapSendMessage(ctx context.Context, client *whatsmeow.Client, recipient types.JID, msg *waE2E.Message, content string) (whatsmeow.SendResponse, error) {
- ts, err := whatsapp.SendMessageWithReachoutRetry(ctx, client, recipient, msg)
+ ts, err := client.SendMessage(ctx, recipient, msg)
if err != nil {
return whatsmeow.SendResponse{}, normalizeSendError(err)
}