From 48af73edf3b92ff455e73058fa6d53b17287b27b Mon Sep 17 00:00:00 2001 From: Rajeh Taher Date: Tue, 17 Nov 2026 00:02:43 +0200 Subject: [PATCH 1/3] prekeys: keep each bundle's device identity The prekey response carries a (serialized ADVSignedDeviceIdentity) for companion devices, beside the identity key. fetchPreKeys now keeps it, and DangerousInternals gains FetchPreKeysWithIdentityNoError, which returns it with each bundle so a caller can verify a companion against its account before encrypting. Existing fetch calls are unchanged. --- internals.go | 6 +++ prekeys.go | 69 +++++++++++++++++++++++++++++++-- prekeys_device_identity_test.go | 53 +++++++++++++++++++++++++ 3 files changed, 125 insertions(+), 3 deletions(-) create mode 100644 prekeys_device_identity_test.go diff --git a/internals.go b/internals.go index b14481b53..a389c6a74 100644 --- a/internals.go +++ b/internals.go @@ -655,6 +655,12 @@ func (int *DangerousInternalClient) FetchPreKeysNoError(ctx context.Context, ret return int.c.fetchPreKeysNoError(ctx, retryDevices) } +// FetchPreKeysWithIdentityNoError fetches prekey bundles and keeps the +// each companion device's bundle carries. +func (int *DangerousInternalClient) FetchPreKeysWithIdentityNoError(ctx context.Context, devices []types.JID) map[types.JID]FetchedPreKey { + return int.c.fetchPreKeysWithIdentityNoError(ctx, devices) +} + func (int *DangerousInternalClient) FetchPreKeys(ctx context.Context, users []types.JID) (map[types.JID]preKeyResp, error) { return int.c.fetchPreKeys(ctx, users) } diff --git a/prekeys.go b/prekeys.go index 693e297ca..a6739d361 100644 --- a/prekeys.go +++ b/prekeys.go @@ -134,8 +134,57 @@ func (cli *Client) fetchPreKeysNoError(ctx context.Context, retryDevices []types } type preKeyResp struct { - bundle *prekey.Bundle - err error + bundle *prekey.Bundle + deviceIdentity []byte + err error +} + +// FetchedPreKey is one device's prekey bundle together with the +// (serialized ADVSignedDeviceIdentity) the server returned +// with it. Companion devices carry one; a primary device has none, so +// DeviceIdentity is nil. +type FetchedPreKey struct { + Bundle *prekey.Bundle + DeviceIdentity []byte +} + +// fetchPreKeysWithIdentityNoError is fetchPreKeysNoError, keeping each +// bundle's . A headless client fetches through its relay, +// which returns bundles only, so DeviceIdentity is nil there. +func (cli *Client) fetchPreKeysWithIdentityNoError(ctx context.Context, devices []types.JID) map[types.JID]FetchedPreKey { + if len(devices) == 0 { + return nil + } + if cli.isShadow() { + bundles, err := cli.shadowRelay.FetchPreKeys(ctx, devices) + if err != nil { + cli.Log.Warnf("Failed to fetch prekeys for %v via relay: %v", devices, err) + return nil + } + out := make(map[types.JID]FetchedPreKey, len(bundles)) + for jid, bundle := range bundles { + out[jid] = FetchedPreKey{Bundle: bundle} + } + return out + } + resp, err := cli.fetchPreKeys(ctx, devices) + if err != nil { + cli.Log.Warnf("Failed to fetch prekeys for %v: %v", devices, err) + return nil + } + out := make(map[types.JID]FetchedPreKey, len(devices)) + for _, jid := range devices { + r, ok := resp[jid] + if !ok { + continue + } + if r.err != nil { + cli.Log.Warnf("Failed to fetch prekey for %s: %v", jid, r.err) + continue + } + out[jid] = FetchedPreKey{Bundle: r.bundle, DeviceIdentity: r.deviceIdentity} + } + return out } func (cli *Client) fetchPreKeys(ctx context.Context, users []types.JID) (map[types.JID]preKeyResp, error) { @@ -169,11 +218,25 @@ func (cli *Client) fetchPreKeys(ctx context.Context, users []types.JID) (map[typ } jid := child.AttrGetter().JID("jid") bundle, err := nodeToPreKeyBundle(uint32(jid.Device), child) - respData[jid] = preKeyResp{bundle, err} + respData[jid] = preKeyResp{bundle: bundle, deviceIdentity: preKeyDeviceIdentity(child), err: err} } return respData, nil } +// preKeyDeviceIdentity returns the bytes of one prekey +// response entry. WhatsApp places it beside the identity key, which may sit +// under a wrapper. +func preKeyDeviceIdentity(node waBinary.Node) []byte { + for _, parent := range []waBinary.Node{node, node.GetChildByTag("keys")} { + if child, ok := parent.GetOptionalChildByTag("device-identity"); ok { + if content, ok := child.Content.([]byte); ok && len(content) > 0 { + return content + } + } + } + return nil +} + func preKeyToNode(key *keys.PreKey) waBinary.Node { var keyID [4]byte binary.BigEndian.PutUint32(keyID[:], key.KeyID) diff --git a/prekeys_device_identity_test.go b/prekeys_device_identity_test.go new file mode 100644 index 000000000..5a7be2544 --- /dev/null +++ b/prekeys_device_identity_test.go @@ -0,0 +1,53 @@ +// Copyright (c) 2026 Rajeh Taher +// Licensed under the MIT License. See LICENSE-MIT for details. + +package whatsmeow + +import ( + "bytes" + "testing" + + waBinary "github.com/polymorfa/hypermeow/binary" +) + +func TestPreKeyDeviceIdentity(t *testing.T) { + identity := []byte{0x0a, 0x01, 0x02} + cases := []struct { + name string + node waBinary.Node + want []byte + }{ + { + name: "beside the identity key", + node: waBinary.Node{Tag: "user", Content: []waBinary.Node{ + {Tag: "registration", Content: []byte{0, 0, 0, 1}}, + {Tag: "device-identity", Content: identity}, + }}, + want: identity, + }, + { + name: "inside a keys wrapper", + node: waBinary.Node{Tag: "user", Content: []waBinary.Node{ + {Tag: "keys", Content: []waBinary.Node{{Tag: "device-identity", Content: identity}}}, + }}, + want: identity, + }, + { + name: "primary device without one", + node: waBinary.Node{Tag: "user", Content: []waBinary.Node{ + {Tag: "registration", Content: []byte{0, 0, 0, 1}}, + }}, + }, + { + name: "empty element", + node: waBinary.Node{Tag: "user", Content: []waBinary.Node{{Tag: "device-identity"}}}, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if got := preKeyDeviceIdentity(tc.node); !bytes.Equal(got, tc.want) { + t.Fatalf("preKeyDeviceIdentity = %x, want %x", got, tc.want) + } + }) + } +} From 4792d8dfc24c793711dd563079bba8fae787ec98 Mon Sep 17 00:00:00 2001 From: Rajeh Taher Date: Tue, 17 Nov 2026 01:07:16 +0200 Subject: [PATCH 2/3] remote signal: forward a pkmsg's device identity A prekey message from a companion device carries beside its . Pass it to the remote Signal store in RemoteReceive.DeviceIdentity so it can verify the sender against its account before decrypting. --- remote_signal.go | 23 +++++++++++++++++++++++ remote_signal_test.go | 25 +++++++++++++++++++++++++ 2 files changed, 48 insertions(+) diff --git a/remote_signal.go b/remote_signal.go index e6c22d45b..b0b8ebbbb 100644 --- a/remote_signal.go +++ b/remote_signal.go @@ -107,6 +107,10 @@ type RemoteReceive struct { Ciphertext []byte PaddingVersion int IsFromMe bool + // DeviceIdentity is the stanza's (a serialized + // ADVSignedDeviceIdentity), which a pkmsg from a companion device + // carries. Nil for other payloads. + DeviceIdentity []byte } // RemoteReceiveResult is what the client learns about a received payload. @@ -351,6 +355,20 @@ func (s *remotePreKeyStore) UploadedPreKeyCount(ctx context.Context) (int, error return s.remote.UploadedPreKeyCount(ctx) } +// messageDeviceIdentity returns the a message stanza +// carries beside its payloads, or nil. +func messageDeviceIdentity(node *waBinary.Node) []byte { + child, ok := node.GetOptionalChildByTag("device-identity") + if !ok { + return nil + } + content, ok := child.Content.([]byte) + if !ok || len(content) == 0 { + return nil + } + return content +} + // decryptMessagesRemote is decryptMessages for a remote-keyed client: each // `` payload goes to the remote store, and only delivery metadata comes // back. Receipts, retry receipts and acks follow the local path. @@ -393,6 +411,10 @@ func (cli *Client) decryptMessagesRemote(ctx context.Context, info *types.Messag if senderEncryptionJID == info.SenderAlt && senderEncryptionJID != info.Sender { senderAlt = info.Sender } + var deviceIdentity []byte + if encType == "pkmsg" { + deviceIdentity = messageDeviceIdentity(node) + } result, err := cli.remoteSignal.Receive(ctx, RemoteReceive{ Timestamp: info.Timestamp, SenderAlt: senderAlt, @@ -403,6 +425,7 @@ func (cli *Client) decryptMessagesRemote(ctx context.Context, info *types.Messag Ciphertext: ciphertext, PaddingVersion: ag.OptionalInt("v"), IsFromMe: info.IsFromMe, + DeviceIdentity: deviceIdentity, }) var decryptErr *RemoteDecryptError isDecryptErr := errors.As(err, &decryptErr) diff --git a/remote_signal_test.go b/remote_signal_test.go index 1a325b852..b197f9132 100644 --- a/remote_signal_test.go +++ b/remote_signal_test.go @@ -4,6 +4,7 @@ package whatsmeow import ( + "bytes" "context" "errors" "fmt" @@ -290,6 +291,30 @@ func TestRemoteReceiveDeliversMetadataAndAcknowledges(t *testing.T) { } } +func TestRemoteReceiveForwardsPreKeyDeviceIdentity(t *testing.T) { + identity := []byte{0x0a, 0x01, 0x02} + for _, tc := range []struct { + encType string + want []byte + }{ + {"pkmsg", identity}, + {"msg", nil}, + } { + t.Run(tc.encType, func(t *testing.T) { + cli, remote, _ := newTestRemote(t) + info, node := encMessage(tc.encType) + node.Content = append(node.GetChildren(), waBinary.Node{Tag: "device-identity", Content: identity}) + cli.decryptMessages(context.Background(), info, node) + if len(remote.receives) != 1 { + t.Fatalf("Receive calls = %d, want 1", len(remote.receives)) + } + if got := remote.receives[0].DeviceIdentity; !bytes.Equal(got, tc.want) { + t.Fatalf("DeviceIdentity = %x, want %x", got, tc.want) + } + }) + } +} + func TestRemoteReceivePreservesProviderTimeAndAlternateSender(t *testing.T) { pn := types.NewJID("15551234567", types.DefaultUserServer) lid := types.NewJID("123456789", types.HiddenUserServer) From 88c3b217ffbdeb602ce602b93d459dc305d08661 Mon Sep 17 00:00:00 2001 From: Rajeh Taher Date: Tue, 17 Nov 2026 08:53:52 +0200 Subject: [PATCH 3/3] remote signal: forward a retry receipt's device identity A retry receipt's carry the requester's beside its identity key. The remote path parsed the bundle but dropped it, so a remote Signal store that verifies companions refused every companion retry that brought fresh keys. Carry it in RemoteResend.DeviceIdentity. --- remote_signal.go | 5 +++++ remote_signal_test.go | 44 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+) diff --git a/remote_signal.go b/remote_signal.go index b0b8ebbbb..d54bdc80c 100644 --- a/remote_signal.go +++ b/remote_signal.go @@ -172,6 +172,10 @@ type RemoteResend struct { // Bundle carries keys from the retry receipt, used to start a fresh // session. Nil when the receipt had none. Bundle *prekey.Bundle + // DeviceIdentity is the (a serialized + // ADVSignedDeviceIdentity) the receipt's keys carry, so the remote store + // can verify a companion requester before using Bundle. Nil without one. + DeviceIdentity []byte } // ErrRemoteSignalUnsupported is returned for flows a remote-keyed client @@ -543,6 +547,7 @@ func (cli *Client) handleRetryReceiptRemote(ctx context.Context, receipt *events return fmt.Errorf("failed to read prekey bundle in retry receipt: %w", err) } req.Bundle = bundle + req.DeviceIdentity = preKeyDeviceIdentity(*node) } if hostedSender, ok := rawHostedSender(node); ok { req.EncryptionJID = cli.hostedSignalJID(ctx, hostedSender) diff --git a/remote_signal_test.go b/remote_signal_test.go index b197f9132..308283fa6 100644 --- a/remote_signal_test.go +++ b/remote_signal_test.go @@ -585,6 +585,50 @@ func TestRemoteRetryReceiptAsksTheStoreToResend(t *testing.T) { } } +func TestRemoteRetryReceiptForwardsItsKeysDeviceIdentity(t *testing.T) { + cli, remote, _ := newTestRemote(t) + requester := types.JID{User: "123", Server: types.HiddenUserServer, Device: 2} + remote.resendWith = marshalStanza(t, waBinary.Node{ + Tag: "message", + Attrs: waBinary.Attrs{"id": "MSG9", "to": requester, "type": "text"}, + }) + identity := keys.NewKeyPair() + signed := identity.CreateSignedPreKey(1) + deviceIdentity := []byte{0x0a, 0x01, 0x02} + receipt := &events.Receipt{ + MessageSource: types.MessageSource{Chat: requester.ToNonAD(), Sender: requester}, + } + node := &waBinary.Node{ + Tag: "receipt", + Attrs: waBinary.Attrs{"id": "MSG9", "from": requester, "type": "retry"}, + Content: []waBinary.Node{ + {Tag: "retry", Attrs: waBinary.Attrs{"id": "MSG9", "t": "1700000000", "count": "2"}}, + {Tag: "registration", Content: []byte{0, 0, 0, 7}}, + // The layout retry.go sends: the device identity sits in . + {Tag: "keys", Content: []waBinary.Node{ + {Tag: "type", Content: []byte{5}}, + {Tag: "identity", Content: identity.Pub[:]}, + preKeyToNode(keys.NewPreKey(9)), + preKeyToNode(signed), + {Tag: "device-identity", Content: deviceIdentity}, + }}, + }, + } + if err := cli.handleRetryReceipt(context.Background(), receipt, node); err != nil { + t.Fatal(err) + } + if len(remote.resends) != 1 { + t.Fatalf("resends = %+v", remote.resends) + } + got := remote.resends[0] + if got.Bundle == nil || got.Bundle.RegistrationID() != 7 { + t.Fatalf("retry bundle was not parsed: %+v", got.Bundle) + } + if !bytes.Equal(got.DeviceIdentity, deviceIdentity) { + t.Fatalf("DeviceIdentity = %x, want %x", got.DeviceIdentity, deviceIdentity) + } +} + func TestRemoteClientRefusesLocalSends(t *testing.T) { cli, _, _ := newTestRemote(t) _, err := cli.SendMessage(context.Background(), types.NewJID("123", types.DefaultUserServer), nil)