|
| 1 | +// Copyright (c) 2026 Tulir Asokan |
| 2 | +// |
| 3 | +// This Source Code Form is subject to the terms of the Mozilla Public |
| 4 | +// License, v. 2.0. If a copy of the MPL was not distributed with this |
| 5 | +// file, You can obtain one at http://mozilla.org/MPL/2.0/. |
| 6 | + |
| 7 | +package whatsmeow |
| 8 | + |
| 9 | +import ( |
| 10 | + "context" |
| 11 | + "crypto/hmac" |
| 12 | + "crypto/sha256" |
| 13 | + |
| 14 | + "go.mau.fi/whatsmeow/types" |
| 15 | +) |
| 16 | + |
| 17 | +func shouldSendCsToken(jid types.JID) bool { |
| 18 | + jid = jid.ToNonAD() |
| 19 | + return (jid.Server == types.DefaultUserServer || jid.Server == types.HiddenUserServer) && |
| 20 | + jid.User != types.PSAJID.User && |
| 21 | + !jid.IsBot() |
| 22 | +} |
| 23 | + |
| 24 | +// derives a cstoken for the given JID using HMAC-SHA256(nctSalt, recipientLID). |
| 25 | +func (cli *Client) generateCsToken(ctx context.Context, jid types.JID) []byte { |
| 26 | + if !shouldSendCsToken(jid) { |
| 27 | + return nil |
| 28 | + } |
| 29 | + if cli.Store == nil || cli.Store.NCTSalt == nil { |
| 30 | + return nil |
| 31 | + } |
| 32 | + salt, err := cli.Store.NCTSalt.GetNCTSalt(ctx) |
| 33 | + if err != nil { |
| 34 | + cli.Log.Debugf("Failed to load NCT salt for cstoken: %v", err) |
| 35 | + return nil |
| 36 | + } |
| 37 | + if len(salt) == 0 { |
| 38 | + return nil |
| 39 | + } |
| 40 | + var recipientLID types.JID |
| 41 | + switch jid.Server { |
| 42 | + case types.HiddenUserServer: |
| 43 | + recipientLID = jid.ToNonAD() |
| 44 | + case types.DefaultUserServer: |
| 45 | + if cli.Store == nil || cli.Store.LIDs == nil { |
| 46 | + return nil |
| 47 | + } |
| 48 | + pn := jid.ToNonAD() |
| 49 | + lid, err := cli.Store.LIDs.GetLIDForPN(ctx, pn) |
| 50 | + if err != nil { |
| 51 | + cli.Log.Debugf("Failed to resolve LID for cstoken JID %s: %v", pn, err) |
| 52 | + return nil |
| 53 | + } |
| 54 | + if lid.IsEmpty() { |
| 55 | + return nil |
| 56 | + } |
| 57 | + recipientLID = lid.ToNonAD() |
| 58 | + default: |
| 59 | + return nil |
| 60 | + } |
| 61 | + |
| 62 | + if recipientLID.Server != types.HiddenUserServer { |
| 63 | + return nil |
| 64 | + } |
| 65 | + |
| 66 | + h := hmac.New(sha256.New, salt) |
| 67 | + h.Write([]byte(recipientLID.String())) |
| 68 | + return h.Sum(nil) |
| 69 | +} |
| 70 | + |
| 71 | +func (cli *Client) storeNCTSalt(ctx context.Context, salt []byte) error { |
| 72 | + if cli.Store == nil || cli.Store.NCTSalt == nil { |
| 73 | + return nil |
| 74 | + } |
| 75 | + if len(salt) == 0 { |
| 76 | + return nil |
| 77 | + } |
| 78 | + return cli.Store.NCTSalt.PutNCTSalt(ctx, salt) |
| 79 | +} |
| 80 | + |
| 81 | +func (cli *Client) clearNCTSalt(ctx context.Context) error { |
| 82 | + if cli.Store == nil || cli.Store.NCTSalt == nil { |
| 83 | + return nil |
| 84 | + } |
| 85 | + return cli.Store.NCTSalt.DeleteNCTSalt(ctx) |
| 86 | +} |
0 commit comments