Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions internals.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

69 changes: 66 additions & 3 deletions prekeys.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
// <device-identity> (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 <device-identity>. 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) {
Expand Down Expand Up @@ -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 <device-identity> bytes of one prekey
// response entry. WhatsApp places it beside the identity key, which may sit
// under a <keys> 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)
Expand Down
53 changes: 53 additions & 0 deletions prekeys_device_identity_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
})
}
}
28 changes: 28 additions & 0 deletions remote_signal.go
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,10 @@ type RemoteReceive struct {
Ciphertext []byte
PaddingVersion int
IsFromMe bool
// DeviceIdentity is the stanza's <device-identity> (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.
Expand Down Expand Up @@ -168,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 <device-identity> (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
Expand Down Expand Up @@ -351,6 +359,20 @@ func (s *remotePreKeyStore) UploadedPreKeyCount(ctx context.Context) (int, error
return s.remote.UploadedPreKeyCount(ctx)
}

// messageDeviceIdentity returns the <device-identity> a message stanza
// carries beside its <enc> 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
// `<enc>` payload goes to the remote store, and only delivery metadata comes
// back. Receipts, retry receipts and acks follow the local path.
Expand Down Expand Up @@ -393,6 +415,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,
Expand All @@ -403,6 +429,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)
Expand Down Expand Up @@ -520,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)
Expand Down
69 changes: 69 additions & 0 deletions remote_signal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
package whatsmeow

import (
"bytes"
"context"
"errors"
"fmt"
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -560,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 <keys>.
{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)
Expand Down
Loading