Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(whatsmeow): port the whatsmeow linked-device client to Rust (#8527)

Wolf Mermelstein52c0cfef70b2
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.json
index dd4f0aeea9..0bccf37ca8 100644
--- a/.github/workspace-dep-closures.json
+++ b/.github/workspace-dep-closures.json
@@ -13786,6 +13786,15 @@
"crates/webhook_signature",
"crates/workspace-hack"
],
+ "whatsmeow": [
+ "crates/whatsmeow",
+ "crates/whatsmeow_proto",
+ "crates/workspace-hack"
+ ],
+ "whatsmeow_proto": [
+ "crates/whatsmeow_proto",
+ "crates/workspace-hack"
+ ],
"work_feed": [
"crates/activity",
"crates/agent",
diff --git a/Cargo.lock b/Cargo.lock
index 6220ab7896..c0981f72cc 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3288,6 +3288,15 @@ dependencies = [
"zeroize",
]
+[[package]]
+name = "block-padding"
+version = "0.3.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a8894febbff9f758034a5b8e12d87918f56dfc64a8e1fe757d65e29041538d93"
+dependencies = [
+ "generic-array 0.14.9",
+]
+
[[package]]
name = "block-padding"
version = "0.4.2"
@@ -3974,6 +3983,15 @@ dependencies = [
"rustversion",
]
+[[package]]
+name = "cbc"
+version = "0.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "26b52a9543ae338f279b96b0b9fed9c8093744685043739079ce85cd58f289a6"
+dependencies = [
+ "cipher 0.4.4",
+]
+
[[package]]
name = "cbc"
version = "0.2.1"
@@ -6338,13 +6356,13 @@ dependencies = [
[[package]]
name = "displaydoc"
-version = "0.2.5"
+version = "0.2.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0"
+checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8"
dependencies = [
"proc-macro2",
"quote",
- "syn 2.0.117",
+ "syn 3.0.3",
]
[[package]]
@@ -10572,6 +10590,7 @@ version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01"
dependencies = [
+ "block-padding 0.3.3",
"generic-array 0.14.9",
]
@@ -10581,7 +10600,7 @@ version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4250ce6452e92010fdf7268ccc5d14faa80bb12fc741938534c58f16804e03c7"
dependencies = [
- "block-padding",
+ "block-padding 0.4.2",
"hybrid-array",
]
@@ -14454,7 +14473,7 @@ dependencies = [
"heck 0.4.1",
"itertools 0.11.0",
"prost 0.12.6",
- "prost-types",
+ "prost-types 0.12.6",
]
[[package]]
@@ -14468,7 +14487,7 @@ dependencies = [
"pbjson",
"pbjson-build",
"prost 0.12.6",
- "prost-build",
+ "prost-build 0.12.6",
"serde",
]
@@ -14874,7 +14893,7 @@ checksum = "63d440a804ec8d6fafbb6b84471e013286658d373248927692ab3366686220ca"
dependencies = [
"aes 0.9.3",
"aes-gcm 0.11.1",
- "cbc",
+ "cbc 0.2.1",
"der 0.8.2",
"pbkdf2",
"rand_core 0.10.1",
@@ -15437,7 +15456,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "22505a5c94da8e3b7c2996394d1c933236c4d743e81a410bcca4e6989fc066a4"
dependencies = [
"bytes",
- "heck 0.4.1",
+ "heck 0.5.0",
"itertools 0.12.1",
"log",
"multimap",
@@ -15445,7 +15464,26 @@ dependencies = [
"petgraph 0.6.5",
"prettyplease",
"prost 0.12.6",
- "prost-types",
+ "prost-types 0.12.6",
+ "regex",
+ "syn 2.0.117",
+ "tempfile",
+]
+
+[[package]]
+name = "prost-build"
+version = "0.14.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "343d3bd7056eda839b03204e68deff7d1b13aba7af2b2fd16890697274262ee7"
+dependencies = [
+ "heck 0.5.0",
+ "itertools 0.14.0",
+ "log",
+ "multimap",
+ "petgraph 0.8.3",
+ "prettyplease",
+ "prost 0.14.3",
+ "prost-types 0.14.3",
"regex",
"syn 2.0.117",
"tempfile",
@@ -15477,6 +15515,18 @@ dependencies = [
"syn 2.0.117",
]
+[[package]]
+name = "prost-reflect"
+version = "0.16.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "01b80ea363c31af2de2b92e3c07ed1156628f7838c4afb4df75ee78a37fedbd1"
+dependencies = [
+ "logos",
+ "miette",
+ "prost 0.14.3",
+ "prost-types 0.14.3",
+]
+
[[package]]
name = "prost-types"
version = "0.12.6"
@@ -15486,6 +15536,42 @@ dependencies = [
"prost 0.12.6",
]
+[[package]]
+name = "prost-types"
+version = "0.14.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8991c4cbdb8bc5b11f0b074ffe286c30e523de90fee5ba8132f1399f23cb3dd7"
+dependencies = [
+ "prost 0.14.3",
+]
+
+[[package]]
+name = "protox"
+version = "0.10.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f43240d7f22cf77d1625885e547acf874dd63cd2790f29f4a38e86256f41996f"
+dependencies = [
+ "bytes",
+ "miette",
+ "prost 0.14.3",
+ "prost-reflect",
+ "prost-types 0.14.3",
+ "protox-parse",
+ "thiserror 2.0.18",
+]
+
+[[package]]
+name = "protox-parse"
+version = "0.10.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "34efee6fad0cf6d71642d20a66bfe0c281919c9577e7c66d20360dfcb7549272"
+dependencies = [
+ "logos",
+ "miette",
+ "prost-types 0.14.3",
+ "thiserror 2.0.18",
+]
+
[[package]]
name = "psd_engine"
version = "0.1.0"
@@ -16547,10 +16633,10 @@ checksum = "036204edbd199552a5b3832f63c60dcdf395dc44c7f06b4af1c0e8139cc11bce"
dependencies = [
"aes 0.9.3",
"bitflags 2.11.1",
- "block-padding",
+ "block-padding 0.4.2",
"byteorder",
"bytes",
- "cbc",
+ "cbc 0.2.1",
"cipher 0.5.2",
"crypto-bigint 0.7.5",
"ctr 0.10.1",
@@ -21323,6 +21409,56 @@ version = "0.1.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88"
+[[package]]
+name = "whatsmeow"
+version = "0.1.0"
+dependencies = [
+ "aes 0.8.4",
+ "aes-gcm 0.10.3",
+ "async-trait",
+ "axum",
+ "base64 0.22.1",
+ "cbc 0.1.2",
+ "chrono",
+ "constant_time_eq 0.3.1",
+ "flate2",
+ "futures",
+ "hex",
+ "hkdf 0.12.4",
+ "hmac 0.12.1",
+ "lazy-regex",
+ "md-5 0.10.6",
+ "miniz_oxide",
+ "prost 0.14.3",
+ "rand 0.9.4",
+ "reqwest 0.13.4",
+ "rootcause",
+ "serde",
+ "serde_json",
+ "sha2 0.10.9",
+ "strum 0.27.2",
+ "tempfile",
+ "thiserror 2.0.18",
+ "tokio",
+ "tokio-tungstenite 0.28.0",
+ "tokio-util",
+ "tracing",
+ "uuid",
+ "whatsmeow_proto",
+ "workspace-hack",
+ "x25519-dalek",
+]
+
+[[package]]
+name = "whatsmeow_proto"
+version = "0.1.0"
+dependencies = [
+ "prost 0.14.3",
+ "prost-build 0.14.3",
+ "protox",
+ "workspace-hack",
+]
+
[[package]]
name = "whoami"
version = "1.6.1"
@@ -22038,6 +22174,7 @@ dependencies = [
"cc",
"chacha20",
"chrono",
+ "cipher 0.4.4",
"cipher 0.5.2",
"crossbeam-epoch",
"crossbeam-utils",
@@ -22045,6 +22182,7 @@ dependencies = [
"crypto-common 0.1.6",
"crypto-common 0.2.2",
"ctutils",
+ "curve25519-dalek 4.1.3",
"data-encoding",
"derive_more 2.1.1",
"derive_more-impl",
@@ -22070,9 +22208,11 @@ dependencies = [
"futures-task",
"futures-util",
"generic-array 0.14.9",
+ "getrandom 0.2.17",
"getrandom 0.3.4",
"getrandom 0.4.2",
"hashbrown 0.14.5",
+ "hashbrown 0.15.5",
"hashbrown 0.16.1",
"hashbrown 0.17.1",
"hmac 0.12.1",
@@ -22083,6 +22223,7 @@ dependencies = [
"hyper-util",
"idna",
"indexmap 2.14.0",
+ "inout 0.1.4",
"inout 0.2.2",
"insta",
"ipnet",
@@ -22093,6 +22234,7 @@ dependencies = [
"libz-sys",
"linux-raw-sys 0.12.1",
"log",
+ "md-5 0.10.6",
"memchr",
"mime_guess",
"miniz_oxide",
@@ -22113,6 +22255,7 @@ dependencies = [
"opentelemetry-http",
"opentelemetry_sdk",
"percent-encoding",
+ "petgraph 0.8.3",
"phf 0.13.1",
"phf_shared 0.10.0",
"phf_shared 0.11.3",
@@ -22126,6 +22269,7 @@ dependencies = [
"rand 0.9.4",
"rand_core 0.6.4",
"redis",
+ "regex",
"regex-automata",
"regex-syntax",
"reqwest 0.13.4",
@@ -22223,6 +22367,18 @@ version = "0.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd"
+[[package]]
+name = "x25519-dalek"
+version = "2.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c7e468321c81fb07fa7f4c636c3972b9100f0346e5b6a9f2bd0603a52f7ed277"
+dependencies = [
+ "curve25519-dalek 4.1.3",
+ "rand_core 0.6.4",
+ "serde",
+ "zeroize",
+]
+
[[package]]
name = "xmlparser"
version = "0.13.6"
diff --git a/Cargo.toml b/Cargo.toml
index a982d2756a..69304f9865 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -125,6 +125,8 @@ members = [
"crates/unfurl",
"crates/user_api_key",
"crates/webhook_signature",
+ "crates/whatsmeow",
+ "crates/whatsmeow_proto",
"crates/work_feed",
"crates/worker-rs-otel",
"crates/workspace-hack",
@@ -178,6 +180,7 @@ members = [
]
[workspace.dependencies]
+aes = "0.8.4"
aes-gcm = { version = "0.10.3", features = ["zeroize"] }
anyhow = "1.0.100"
apollo-compiler = "1"
@@ -234,6 +237,7 @@ chrono = { version = "0.4.39", features = ["serde"] }
chrono-tz = { version = "0.10.4", features = ["serde"] }
clap = { version = "4.5.20", features = ["derive"] }
cloudfront_sign = "0.3.0"
+cbc = { version = "0.1.2", features = ["std"] }
constant_time_eq = "0.3.1"
console_error_panic_hook = "0.1.7"
crossterm = "0.28"
@@ -247,6 +251,7 @@ dotenvy = "0.15.7"
ego-tree = "0.6.2"
either = "1"
eventsource-stream = "0.2.3"
+flate2 = "1"
fractional_index = { version = "2.0.2", default-features = false }
futures = "0.3.31"
getrandom = "0.3"
@@ -258,6 +263,7 @@ glob = "0.3.3"
# hakari release is built against.
guppy = "0.17.24"
hex = "0.4.3"
+hkdf = "0.12.4"
hmac = "0.12.1"
encoding_rs = "0.8"
http = "1"
@@ -292,6 +298,7 @@ logos = "0.16"
lol_html = "2.4.0"
loro = "1.16.2"
lru = "0.16"
+md-5 = "0.10.6"
miniz_oxide = { version = "0.8", features = ["with-alloc"] }
mockall = "0.13"
nom = "8"
@@ -319,6 +326,9 @@ png = "0.18"
postcard = { version = "1", features = ["use-std"] }
pollster = "0.4"
proptest = { version = "1.11", default-features = false, features = ["std"] }
+prost = "0.14"
+prost-build = "0.14"
+protox = "0.10"
quote = "1"
rand = "0.9.0"
ratatui = "0.29"
@@ -435,6 +445,7 @@ web-time = "1.1.0"
webbrowser = { version = "=1.2.2", features = ["hardened"] }
windows-sys = "0.61"
worker = "0.8.1"
+x25519-dalek = { version = "2.0.1", features = ["static_secrets"] }
# this is pinned to match axum 0.7.9 dependency requirements
async-stripe = { version = "0.41", default-features = false, features = [
"billing",
diff --git a/crates/whatsmeow/AGENTS.md b/crates/whatsmeow/AGENTS.md
new file mode 100644
index 0000000000..0dd13accfb
--- /dev/null
+++ b/crates/whatsmeow/AGENTS.md
@@ -0,0 +1,198 @@
+# whatsmeow
+
+## What it is
+
+A faithful 1:1 Rust port of [whatsmeow](https://github.com/tulir/whatsmeow), the
+Go client for WhatsApp's web multidevice (linked device) API. Ported from
+revision `b2b1e71d45e2ff171153b025b5a42f475bb30ef8`.
+
+## Start here
+
+- `src/lib.rs`: module map; one module per Go package, one file per Go file.
+- `src/client.rs`: the `Client` (Go's `client.go`); every other top-level
+ file adds an `impl Client` block for its Go file. Its header lists the
+ deliberate deviations (config struct, `Dialer`, async event handlers).
+- Phone-number pairing: `pair_phone` after the first QR event; passkey
+ pairing: `Event::PairPasskeyRequest` → `send_passkey_response`,
+ `Event::PairPasskeyConfirmation` → `send_passkey_confirmation` (the QR
+ channel surfaces both and confirms by itself when the handoff UX can be
+ skipped).
+- `src/testing.rs`: the fake WhatsApp server and fake Signal used by the
+ client tests (also exported behind the `testing` feature).
+- `src/signal.rs`: the libsignal boundary (see below) — read before porting
+ anything that encrypts, decrypts or signs.
+- `src/appstate.rs`: the `appstate` package. `Processor::new(&Device)` clones
+ the device's `app_state_keys` and `app_state` handles; the client port
+ (`appstate.go`) calls `decode_patches`, `encode_patch`,
+ `get_missing_key_ids`, `process_recovery`, `parse_patch_list` and
+ `parse_recovery`, and checks `DecodeError::sentinel()` where Go uses
+ `errors.Is(err, ErrKeyNotFound)`.
+- `src/appstate/client.rs`: the top-level `appstate.go` (the exception to
+ `src/<file>.rs`, since `src/appstate.rs` is the package): fetching,
+ applying and sending patches, `server_sync` notifications and
+ `handle_app_state_sync_key_share` (from `message.go`). Key requests go
+ through `Client::send_peer_message`, which encrypts and sends to the
+ account’s other devices.
+
+## Public API (what services use)
+
+```rust
+let client = Client::new(device, signal /* Arc<dyn Signal> */, ClientConfig::default());
+let mut events = client.subscribe(); // or add_event_handler(Arc<dyn EventHandler>)
+let qr = client.get_qr_channel(cancel).await?; // before connect, unpaired devices only
+client.connect().await?;
+client.send_message(&group_jid, message, SendRequestExtra::default()).await?;
+client.get_joined_groups().await?; client.get_group_info(&group_jid).await?;
+client.download(&*image_message).await?; client.upload(&bytes, MediaType::Image).await?;
+client.mark_read(&ids, now, &chat, &sender, None).await?;
+client.disconnect().await; client.shutdown().await;
+```
+
+- `device`: a `store::Device` whose store handles are your persistence
+ (`MemoryStore` in tests). The client owns it as `client.store`
+ (`tokio::sync::RwLock<Device>`); pairing and logins write it back with
+ `Device::save`.
+- `Signal` is `SignalProtocol + CurveSignatures` (blanket impl): pass one
+ `Arc` of the libsignal implementation.
+- Events (`types::events::Event`): `Qr`, `PairSuccess`, `PairError`,
+ `Connected`, `Disconnected`, `LoggedOut`, `StreamReplaced`, `Message`,
+ `UndecryptableMessage`, `Receipt`, `GroupInfo`, `JoinedGroup`,
+ `HistorySync`, `PushName`, … With `ClientConfig::synchronous_ack`, an
+ `EventHandler` returning `false` leaves the node unacked so the server
+ redelivers it.
+- `SendRequestExtra::no_disconnect_retry` (not in whatsmeow; #8304 patched
+ it in) makes a send fail with `ClientError::Disconnected` instead of
+ resending after a reconnect, so an unacked send can be recorded as unknown.
+- Deviation from Go: the handler queue loop handles a `stream:error` it
+ dequeued after the connection ended (Go drops it), so the post-pairing
+ 515 that arrives with the socket close still triggers the login.
+- `ClientConfig::media_base_url` (not in whatsmeow) sends media uploads,
+ downloads and deletes to one `scheme://host[:port]` instead of the media
+ connection's hosts, for a local fake media server in tests.
+- `ClientConfig::dialer` opens the websocket; `testing::FakeServer` (feature
+ `testing`) provides an in-memory one and `testing::FakeSignal` a fake
+ Signal implementation for service tests.
+
+## What is ported
+
+Client core (`client`, `request`, `connectionevents`, `keepalive`, `qrchan`,
+`pair`, `prekeys`, `notification`, `tctoken`, `cstoken`), receiving
+(`message`, `receipt`, `retry`, history sync download), sending (`send`:
+1:1, groups with sender keys, peer messages, revoke/reaction/edit
+builders), `user`, `group`, `presence`, app state (`appstate` package and
+its client in `appstate/client.rs`), media (`mediaconn`, `download`,
+`download_to_file`, `upload`, `mediaretry`), pairing by QR, phone number
+code (`pair_code`) and passkey (`pair_passkey`), `privacysettings`,
+`msgsecret` (encrypted reactions, comments, poll votes, secret edits).
+
+Not ported (skipped features): newsletters, calls, status/broadcast lists,
+business profiles and links, communities admin, bots and Meta AI (`msmsg`,
+WASA), Messenger/Instagram (`sendfb.go`, Armadillo `v=3`, FB device lists),
+WASA/bot parts of `msgsecret.go`, reporting tokens, `armadillomessage.go`, `push.go`,
+`update.go`, `store/sqlstore` (the Postgres store lives in
+`crates/whatsapp_store_pg`).
+
+## Porting rules
+
+- Mirror the Go layout: Go package `x/y` → module `x::y` (`src/x/y.rs`
+ re-exporting its files), `x/y/file.go` → `src/x/y/file.rs`, Go `FuncName` →
+ `func_name`. A package whose only file shares its name collapses into
+ `src/x/y.rs` (`binary/token`). Top-level Go files (`handshake.go`) map to
+ `src/<file>.rs`.
+- Every ported file starts with the MPL-2.0 header and a line naming the Go
+ file it ports: `// Ported from whatsmeow <path> (MPL-2.0, Copyright (c) Tulir Asokan)`.
+ Files that aren't ports (`signal.rs`, `store/memorystore.rs`) say so.
+- Keep Go's logic, including its string splitting; repo rules such as CS-58
+ (nom) don't override a line-by-line port. Where Go panics, silently
+ truncates, or uses a sentinel/`Found` flag, return an error or `Option`
+ and say so in the doc comment.
+- Go callbacks and channels become event receivers (`socket::FrameEvent`,
+ `socket::NoiseEvent`); `context.Context` parameters are dropped.
+- Protobuf types come from `crates/whatsmeow_proto`, re-exported as `proto`.
+- whatsmeow has almost no Go tests. Tests here use expected values produced by
+ running whatsmeow's Go code at the pinned revision, so the port is checked
+ byte for byte. The generators live in `testdata/generator/` (see its
+ README): `inpackage/generate.sh` copies its `*_test.go` files into a
+ whatsmeow checkout (they are `package whatsmeow`, so they reach unexported
+ code) and writes `testdata/*.json`, read by `src/vectors.rs`; the `media`
+ and `appstate` programs reach unexported code with `go:linkname` and write
+ `testdata/<area>/vectors.json`.
+- The media functions are free functions taking what the client supplies
+ (`download::download(&MediaHttpClient, &MediaConn, msg)`); `Client` wraps
+ them.
+- Client behaviour (pairing, login, IQs, reconnects) is tested against the
+ fake server in `src/testing.rs` over in-memory websockets, with
+ `#[tokio::test(start_paused = true)]` so timeouts run instantly.
+- Nodes the client sends are checked against Go's: the generator's
+ `captureNode` records what a Go client method sends (its send log fires
+ right before a zero `NoiseSocket` panics), and `client::test::capture_request`
+ gets the Rust side; both replace the iq `id` and usync `sid`.
+- Go formats JIDs (and sometimes node XML) into error messages; ported errors
+ leave them out, since `#[tracing::instrument(err)]` logs them.
+- Methods that spawn work which can reconnect return `BoxFuture` (see
+ `Client::auto_reconnect`): without it, `Send` inference cycles through
+ `connect`.
+- Log opaque values only (tags, IDs, counts); unlike Go, never log node XML,
+ JIDs or phone numbers.
+
+## Signal protocol boundary
+
+Every Signal call goes through the traits in `src/signal.rs`:
+
+- `CurveSignatures`: XEdDSA signing and verification for prekeys, pairing,
+ and the server's Noise certificate.
+- `SignalProtocol`: pairwise sessions and group sender keys.
+- `SignalProtocolStore`: opaque protocol records, implemented by
+ `store::DeviceSignalStore`.
+
+`crates/whatsmeow_signal` implements these traits with Signal's official
+AGPL-3.0-only libsignal core and vendored X3DH protocol modules. The repository
+is AGPL-3.0; retain MPL-2.0 headers on the whatsmeow port and Signal's SPDX
+headers and NOTICE on its protocol implementation. Client unit tests use fakes;
+Signal interop and linked-device end-to-end tests exercise the implementation.
+
+## Checks
+
+- `cargo test -p whatsmeow -p whatsmeow_proto`
+- After changing a generator: `go run -ldflags=-checklinkname=0 ./appstate`
+ in `testdata/generator`, then the tests.
+
+## Gotchas
+
+- License is MPL-2.0 (`LICENSE`), file-level copyleft: keep ported code in
+ these crates, don't copy it into Macro crates.
+- Never connect to real WhatsApp servers or link a real account from tests;
+ socket tests run over in-memory websockets (`tokio::io::duplex`).
+- `FrameSocket::connect` dials `wss://` with rustls; the binary must install a
+ rustls crypto provider first.
+- Media functions take `download::MediaHttpClient`; its crate-private
+ `scheme` and `host_override` (set by `with_base_url`) let tests talk plain
+ HTTP to local fake hosts (Go hardcodes `https`). Tests never contact WhatsApp media hosts.
+- Regenerating `testdata/media/vectors.json` changes it every run: Go's
+ `Upload` picks a random media key, which the vectors record.
+- Node hex in the `inpackage` vectors changes every run (Go map order of
+ attributes), so tests compare unmarshaled nodes; revert files whose only
+ change is that churn.
+- tungstenite has no permessage-deflate, so connections are uncompressed
+ (Go negotiates compression).
+- `store::clientpayload` keeps the WA version and OS info in process-wide
+ locks, as Go keeps package variables; tests use the private builders instead
+ of the setters so they don't race.
+
+- Async closures that borrow their captures don't produce `Send` futures,
+ so a Go callback awaited inside an async fn becomes an enum or trait
+ (`appstate::PreviousValueMacs`); `appstate/keys/test.rs` asserts the
+ `Processor` futures are `Send`.
+- Go's appstate encodes with random IVs, so encoded patches are tested by
+ decoding them with MAC checks, not byte comparison.
+- Go marshals node attributes in random map order: compare Go-generated
+ nodes decoded (`Vectors::node`), not as bytes. In-package generators
+ capture a request by logging it through `sendLog` and sending with a
+ cancelled context (`appstate_client_vectors_test.go`).
+- Go's `EncodePatch` doesn't set the patch version (the server does) and
+ doesn't look inside its own patch for an earlier SET of the same index, so
+ a test patch must not set one index twice (`BuildArchive` also unpins).
+
+## Related
+
+- `crates/whatsmeow_proto/AGENTS.md`
diff --git a/crates/whatsmeow/CLAUDE.md b/crates/whatsmeow/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/whatsmeow/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/whatsmeow/Cargo.toml b/crates/whatsmeow/Cargo.toml
new file mode 100644
index 0000000000..5eb68e8f4f
--- /dev/null
+++ b/crates/whatsmeow/Cargo.toml
@@ -0,0 +1,51 @@
+[package]
+edition = "2024"
+name = "whatsmeow"
+publish = false
+version = "0.1.0"
+license = "MPL-2.0"
+description = "Rust port of the whatsmeow WhatsApp multidevice client library."
+
+[dependencies]
+aes = { workspace = true }
+aes-gcm = { workspace = true }
+async-trait = { workspace = true }
+base64 = { workspace = true }
+cbc = { workspace = true }
+chrono = { workspace = true }
+constant_time_eq = { workspace = true }
+flate2 = { workspace = true }
+futures = { workspace = true }
+hex = { workspace = true }
+hkdf = { workspace = true }
+hmac = { workspace = true }
+lazy-regex = { workspace = true }
+md-5 = { workspace = true }
+miniz_oxide = { workspace = true }
+prost = { workspace = true }
+rand = { workspace = true }
+reqwest = { workspace = true }
+rootcause = { workspace = true }
+serde = { workspace = true }
+serde_json = { workspace = true }
+sha2 = { workspace = true }
+strum = { workspace = true }
+thiserror = { workspace = true }
+tokio = { workspace = true, features = ["sync", "time"] }
+tokio-tungstenite = { workspace = true }
+tokio-util = { workspace = true, features = ["rt"] }
+tracing = { workspace = true }
+uuid = { workspace = true }
+whatsmeow_proto = { path = "../whatsmeow_proto" }
+workspace-hack = { version = "0.1", path = "../workspace-hack" }
+x25519-dalek = { workspace = true }
+
+[features]
+# The fake WhatsApp server and fake Signal implementation in `testing`, for
+# other crates' tests.
+testing = []
+
+[dev-dependencies]
+axum = { workspace = true }
+tempfile = { workspace = true }
+tokio = { workspace = true, features = ["io-util", "macros", "net", "rt", "test-util"] }
diff --git a/crates/whatsmeow/LICENSE b/crates/whatsmeow/LICENSE
new file mode 100644
index 0000000000..a612ad9813
--- /dev/null
+++ b/crates/whatsmeow/LICENSE
@@ -0,0 +1,373 @@
+Mozilla Public License Version 2.0
+==================================
+
+1. Definitions
+--------------
+
+1.1. "Contributor"
+ means each individual or legal entity that creates, contributes to
+ the creation of, or owns Covered Software.
+
+1.2. "Contributor Version"
+ means the combination of the Contributions of others (if any) used
+ by a Contributor and that particular Contributor's Contribution.
+
+1.3. "Contribution"
+ means Covered Software of a particular Contributor.
+
+1.4. "Covered Software"
+ means Source Code Form to which the initial Contributor has attached
+ the notice in Exhibit A, the Executable Form of such Source Code
+ Form, and Modifications of such Source Code Form, in each case
+ including portions thereof.
+
+1.5. "Incompatible With Secondary Licenses"
+ means
+
+ (a) that the initial Contributor has attached the notice described
+ in Exhibit B to the Covered Software; or
+
+ (b) that the Covered Software was made available under the terms of
+ version 1.1 or earlier of the License, but not also under the
+ terms of a Secondary License.
+
+1.6. "Executable Form"
+ means any form of the work other than Source Code Form.
+
+1.7. "Larger Work"
+ means a work that combines Covered Software with other material, in
+ a separate file or files, that is not Covered Software.
+
+1.8. "License"
+ means this document.
+
+1.9. "Licensable"
+ means having the right to grant, to the maximum extent possible,
+ whether at the time of the initial grant or subsequently, any and
+ all of the rights conveyed by this License.
+
+1.10. "Modifications"
+ means any of the following:
+
+ (a) any file in Source Code Form that results from an addition to,
+ deletion from, or modification of the contents of Covered
+ Software; or
+
+ (b) any new file in Source Code Form that contains any Covered
+ Software.
+
+1.11. "Patent Claims" of a Contributor
+ means any patent claim(s), including without limitation, method,
+ process, and apparatus claims, in any patent Licensable by such
+ Contributor that would be infringed, but for the grant of the
+ License, by the making, using, selling, offering for sale, having
+ made, import, or transfer of either its Contributions or its
+ Contributor Version.
+
+1.12. "Secondary License"
+ means either the GNU General Public License, Version 2.0, the GNU
+ Lesser General Public License, Version 2.1, the GNU Affero General
+ Public License, Version 3.0, or any later versions of those
+ licenses.
+
+1.13. "Source Code Form"
+ means the form of the work preferred for making modifications.
+
+1.14. "You" (or "Your")
+ means an individual or a legal entity exercising rights under this
+ License. For legal entities, "You" includes any entity that
+ controls, is controlled by, or is under common control with You. For
+ purposes of this definition, "control" means (a) the power, direct
+ or indirect, to cause the direction or management of such entity,
+ whether by contract or otherwise, or (b) ownership of more than
+ fifty percent (50%) of the outstanding shares or beneficial
+ ownership of such entity.
+
+2. License Grants and Conditions
+--------------------------------
+
+2.1. Grants
+
+Each Contributor hereby grants You a world-wide, royalty-free,
+non-exclusive license:
+
+(a) under intellectual property rights (other than patent or trademark)
+ Licensable by such Contributor to use, reproduce, make available,
+ modify, display, perform, distribute, and otherwise exploit its
+ Contributions, either on an unmodified basis, with Modifications, or
+ as part of a Larger Work; and
+
+(b) under Patent Claims of such Contributor to make, use, sell, offer
+ for sale, have made, import, and otherwise transfer either its
+ Contributions or its Contributor Version.
+
+2.2. Effective Date
+
+The licenses granted in Section 2.1 with respect to any Contribution
+become effective for each Contribution on the date the Contributor first
+distributes such Contribution.
+
+2.3. Limitations on Grant Scope
+
+The licenses granted in this Section 2 are the only rights granted under
+this License. No additional rights or licenses will be implied from the
+distribution or licensing of Covered Software under this License.
+Notwithstanding Section 2.1(b) above, no patent license is granted by a
+Contributor:
+
+(a) for any code that a Contributor has removed from Covered Software;
+ or
+
+(b) for infringements caused by: (i) Your and any other third party's
+ modifications of Covered Software, or (ii) the combination of its
+ Contributions with other software (except as part of its Contributor
+ Version); or
+
+(c) under Patent Claims infringed by Covered Software in the absence of
+ its Contributions.
+
+This License does not grant any rights in the trademarks, service marks,
+or logos of any Contributor (except as may be necessary to comply with
+the notice requirements in Section 3.4).
+
+2.4. Subsequent Licenses
+
+No Contributor makes additional grants as a result of Your choice to
+distribute the Covered Software under a subsequent version of this
+License (see Section 10.2) or under the terms of a Secondary License (if
+permitted under the terms of Section 3.3).
+
+2.5. Representation
+
+Each Contributor represents that the Contributor believes its
+Contributions are its original creation(s) or it has sufficient rights
+to grant the rights to its Contributions conveyed by this License.
+
+2.6. Fair Use
+
+This License is not intended to limit any rights You have under
+applicable copyright doctrines of fair use, fair dealing, or other
+equivalents.
+
+2.7. Conditions
+
+Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
+in Section 2.1.
+
+3. Responsibilities
+-------------------
+
+3.1. Distribution of Source Form
+
+All distribution of Covered Software in Source Code Form, including any
+Modifications that You create or to which You contribute, must be under
+the terms of this License. You must inform recipients that the Source
+Code Form of the Covered Software is governed by the terms of this
+License, and how they can obtain a copy of this License. You may not
+attempt to alter or restrict the recipients' rights in the Source Code
+Form.
+
+3.2. Distribution of Executable Form
+
+If You distribute Covered Software in Executable Form then:
+
+(a) such Covered Software must also be made available in Source Code
+ Form, as described in Section 3.1, and You must inform recipients of
+ the Executable Form how they can obtain a copy of such Source Code
+ Form by reasonable means in a timely manner, at a charge no more
+ than the cost of distribution to the recipient; and
+
+(b) You may distribute such Executable Form under the terms of this
+ License, or sublicense it under different terms, provided that the
+ license for the Executable Form does not attempt to limit or alter
+ the recipients' rights in the Source Code Form under this License.
+
+3.3. Distribution of a Larger Work
+
+You may create and distribute a Larger Work under terms of Your choice,
+provided that You also comply with the requirements of this License for
+the Covered Software. If the Larger Work is a combination of Covered
+Software with a work governed by one or more Secondary Licenses, and the
+Covered Software is not Incompatible With Secondary Licenses, this
+License permits You to additionally distribute such Covered Software
+under the terms of such Secondary License(s), so that the recipient of
+the Larger Work may, at their option, further distribute the Covered
+Software under the terms of either this License or such Secondary
+License(s).
+
+3.4. Notices
+
+You may not remove or alter the substance of any license notices
+(including copyright notices, patent notices, disclaimers of warranty,
+or limitations of liability) contained within the Source Code Form of
+the Covered Software, except that You may alter any license notices to
+the extent required to remedy known factual inaccuracies.
+
+3.5. Application of Additional Terms
+
+You may choose to offer, and to charge a fee for, warranty, support,
+indemnity or liability obligations to one or more recipients of Covered
+Software. However, You may do so only on Your own behalf, and not on
+behalf of any Contributor. You must make it absolutely clear that any
+such warranty, support, indemnity, or liability obligation is offered by
+You alone, and You hereby agree to indemnify every Contributor for any
+liability incurred by such Contributor as a result of warranty, support,
+indemnity or liability terms You offer. You may include additional
+disclaimers of warranty and limitations of liability specific to any
+jurisdiction.
+
+4. Inability to Comply Due to Statute or Regulation
+---------------------------------------------------
+
+If it is impossible for You to comply with any of the terms of this
+License with respect to some or all of the Covered Software due to
+statute, judicial order, or regulation then You must: (a) comply with
+the terms of this License to the maximum extent possible; and (b)
+describe the limitations and the code they affect. Such description must
+be placed in a text file included with all distributions of the Covered
+Software under this License. Except to the extent prohibited by statute
+or regulation, such description must be sufficiently detailed for a
+recipient of ordinary skill to be able to understand it.
+
+5. Termination
+--------------
+
+5.1. The rights granted under this License will terminate automatically
+if You fail to comply with any of its terms. However, if You become
+compliant, then the rights granted under this License from a particular
+Contributor are reinstated (a) provisionally, unless and until such
+Contributor explicitly and finally terminates Your grants, and (b) on an
+ongoing basis, if such Contributor fails to notify You of the
+non-compliance by some reasonable means prior to 60 days after You have
+come back into compliance. Moreover, Your grants from a particular
+Contributor are reinstated on an ongoing basis if such Contributor
+notifies You of the non-compliance by some reasonable means, this is the
+first time You have received notice of non-compliance with this License
+from such Contributor, and You become compliant prior to 30 days after
+Your receipt of the notice.
+
+5.2. If You initiate litigation against any entity by asserting a patent
+infringement claim (excluding declaratory judgment actions,
+counter-claims, and cross-claims) alleging that a Contributor Version
+directly or indirectly infringes any patent, then the rights granted to
+You by any and all Contributors for the Covered Software under Section
+2.1 of this License shall terminate.
+
+5.3. In the event of termination under Sections 5.1 or 5.2 above, all
+end user license agreements (excluding distributors and resellers) which
+have been validly granted by You or Your distributors under this License
+prior to termination shall survive termination.
+
+************************************************************************
+* *
+* 6. Disclaimer of Warranty *
+* ------------------------- *
+* *
+* Covered Software is provided under this License on an "as is" *
+* basis, without warranty of any kind, either expressed, implied, or *
+* statutory, including, without limitation, warranties that the *
+* Covered Software is free of defects, merchantable, fit for a *
+* particular purpose or non-infringing. The entire risk as to the *
+* quality and performance of the Covered Software is with You. *
+* Should any Covered Software prove defective in any respect, You *
+* (not any Contributor) assume the cost of any necessary servicing, *
+* repair, or correction. This disclaimer of warranty constitutes an *
+* essential part of this License. No use of any Covered Software is *
+* authorized under this License except under this disclaimer. *
+* *
+************************************************************************
+
+************************************************************************
+* *
+* 7. Limitation of Liability *
+* -------------------------- *
+* *
+* Under no circumstances and under no legal theory, whether tort *
+* (including negligence), contract, or otherwise, shall any *
+* Contributor, or anyone who distributes Covered Software as *
+* permitted above, be liable to You for any direct, indirect, *
+* special, incidental, or consequential damages of any character *
+* including, without limitation, damages for lost profits, loss of *
+* goodwill, work stoppage, computer failure or malfunction, or any *
+* and all other commercial damages or losses, even if such party *
+* shall have been informed of the possibility of such damages. This *
+* limitation of liability shall not apply to liability for death or *
+* personal injury resulting from such party's negligence to the *
+* extent applicable law prohibits such limitation. Some *
+* jurisdictions do not allow the exclusion or limitation of *
+* incidental or consequential damages, so this exclusion and *
+* limitation may not apply to You. *
+* *
+************************************************************************
+
+8. Litigation
+-------------
+
+Any litigation relating to this License may be brought only in the
+courts of a jurisdiction where the defendant maintains its principal
+place of business and such litigation shall be governed by laws of that
+jurisdiction, without reference to its conflict-of-law provisions.
+Nothing in this Section shall prevent a party's ability to bring
+cross-claims or counter-claims.
+
+9. Miscellaneous
+----------------
+
+This License represents the complete agreement concerning the subject
+matter hereof. If any provision of this License is held to be
+unenforceable, such provision shall be reformed only to the extent
+necessary to make it enforceable. Any law or regulation which provides
+that the language of a contract shall be construed against the drafter
+shall not be used to construe this License against a Contributor.
+
+10. Versions of the License
+---------------------------
+
+10.1. New Versions
+
+Mozilla Foundation is the license steward. Except as provided in Section
+10.3, no one other than the license steward has the right to modify or
+publish new versions of this License. Each version will be given a
+distinguishing version number.
+
+10.2. Effect of New Versions
+
+You may distribute the Covered Software under the terms of the version
+of the License under which You originally received the Covered Software,
+or under the terms of any subsequent version published by the license
+steward.
+
+10.3. Modified Versions
+
+If you create software not governed by this License, and you want to
+create a new license for such software, you may create and use a
+modified version of this License if you rename the license and remove
+any references to the name of the license steward (except to note that
+such modified license differs from this License).
+
+10.4. Distributing Source Code Form that is Incompatible With Secondary
+Licenses
+
+If You choose to distribute Source Code Form that is Incompatible With
+Secondary Licenses under the terms of this version of the License, the
+notice described in Exhibit B of this License must be attached.
+
+Exhibit A - Source Code Form License Notice
+-------------------------------------------
+
+ This Source Code Form is subject to the terms of the Mozilla Public
+ License, v. 2.0. If a copy of the MPL was not distributed with this
+ file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+If it is not possible or desirable to put the notice in a particular
+file, then You may include the notice in a location (such as a LICENSE
+file in a relevant directory) where a recipient would be likely to look
+for such a notice.
+
+You may add additional accurate notices of copyright ownership.
+
+Exhibit B - "Incompatible With Secondary Licenses" Notice
+---------------------------------------------------------
+
+ This Source Code Form is "Incompatible With Secondary Licenses", as
+ defined by the Mozilla Public License, v. 2.0.
diff --git a/crates/whatsmeow/src/appstate.rs b/crates/whatsmeow/src/appstate.rs
new file mode 100644
index 0000000000..06548dcd11
--- /dev/null
+++ b/crates/whatsmeow/src/appstate.rs
@@ -0,0 +1,37 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+//
+// Ported from whatsmeow appstate/ (MPL-2.0, Copyright (c) Tulir Asokan)
+
+//! Encoding and decoding WhatsApp's app state patches.
+//!
+//! [`Processor`] decodes the patch lists and snapshots the server sends
+//! ([`Processor::decode_patches`]), encodes outgoing patches
+//! ([`Processor::encode_patch`]) and applies recovery snapshots from the
+//! primary device ([`Processor::process_recovery`]).
+//!
+//! The client side (whatsmeow's top-level `appstate.go`: fetching, applying
+//! and sending patches) is in `client.rs`, an `impl Client` block
+//! ([`crate::Client::fetch_app_state`], [`crate::Client::send_app_state`]),
+//! plus the free functions [`build_app_state_recovery_request`] and
+//! [`build_fatal_app_state_exception_notification`].
+
+mod client;
+mod decode;
+mod encode;
+mod errors;
+mod hash;
+mod keys;
+pub mod lthash;
+mod recovery;
+#[cfg(test)]
+mod vectors;
+
+pub use client::{build_app_state_recovery_request, build_fatal_app_state_exception_notification};
+pub use decode::*;
+pub use encode::*;
+pub use errors::*;
+pub use hash::*;
+pub use keys::*;
+pub use recovery::*;
diff --git a/crates/whatsmeow/src/appstate/client.rs b/crates/whatsmeow/src/appstate/client.rs
new file mode 100644
index 0000000000..8ac3949e82
--- /dev/null
+++ b/crates/whatsmeow/src/appstate/client.rs
@@ -0,0 +1,1110 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+//
+// Ported from whatsmeow appstate.go (MPL-2.0, Copyright (c) Tulir Asokan)
+//
+// The top-level `appstate.go` (the client side of app state: fetching,
+// applying, sending) lives here rather than in `src/appstate.rs`, which is
+// the `appstate` package. Also here: `handleAppStateSyncKeyShare` from
+// `message.go`, `handleAppStateNotification` from `notification.go`, and
+// `storeNCTSalt`/`clearNCTSalt` from `cstoken.go` (inlined).
+//
+// Deviations:
+// - Go dispatches the same `error` value in `AppStateSyncError` that it
+// returns; `ClientError` isn't `Clone`, so the event carries the message.
+// - `ErrAppStateUpdate` wraps its detail instead of being wrapped by it, so
+// `ClientError::is(&ClientError::AppStateUpdate)` holds; the message order
+// differs from Go's.
+// - Mutation logs carry the index kind and versions only, never the index
+// (JIDs) or the action.
+
+use std::sync::Arc;
+use std::time::Duration;
+
+use async_trait::async_trait;
+use chrono::{DateTime, Utc};
+use futures::future::BoxFuture;
+
+use super::{
+ ALL_PATCH_NAMES, AppStateError, DownloadExternal, HashState, INDEX_ARCHIVE, INDEX_CLEAR_CHAT,
+ INDEX_CONTACT, INDEX_DELETE_CHAT, INDEX_DELETE_MESSAGE_FOR_ME, INDEX_LABEL_ASSOCIATION_CHAT,
+ INDEX_LABEL_ASSOCIATION_MESSAGE, INDEX_LABEL_EDIT, INDEX_MARK_CHAT_AS_READ, INDEX_MUTE,
+ INDEX_NCT_SALT_SYNC, INDEX_PIN, INDEX_SETTING_PUSH_NAME, INDEX_SETTING_UNARCHIVE_CHATS,
+ INDEX_STAR, INDEX_USER_STATUS_MUTE, INDEX_WASA_ROOT_SECRET_ACTION, Mutation, PatchInfo,
+ PatchList, WA_PATCH_CRITICAL_UNBLOCK_LOW, WaPatchName, parse_patch_list, parse_recovery,
+};
+use crate::binary::{Attrs, Node, NodeContent};
+use crate::client::{Client, lock};
+use crate::errors::{ClientError, DisconnectedError, element_missing};
+use crate::proto::wa_e2e::peer_data_operation_request_message::SyncDCollectionFatalRecoveryRequest;
+use crate::proto::wa_e2e::peer_data_operation_request_response_message::PeerDataOperationResult;
+use crate::proto::wa_e2e::{
+ self, AppStateFatalExceptionNotification, AppStateSyncKeyId, AppStateSyncKeyRequest,
+ AppStateSyncKeyShare, PeerDataOperationRequestMessage, PeerDataOperationRequestType,
+ ProtocolMessage, protocol_message,
+};
+use crate::proto::wa_server_sync::ExternalBlobReference;
+use crate::proto::wa_server_sync::syncd_mutation::SyncdOperation;
+use crate::proto::wa_sync_action::wasa_root_secret_action::RootSecretEntry;
+use crate::proto::wa_sync_action::wasa_root_secret_action::root_secret_entry::Status as RootSecretStatus;
+use crate::request::{InfoQuery, IqType};
+use crate::store::{AppStateSyncKey, ContactEntry, MUTED_FOREVER, MessageSecretInsert};
+use crate::types::events::{
+ AppState, AppStateSyncComplete, AppStateSyncError, Archive, ClearChat, Contact, DeleteChat,
+ DeleteForMe, Event, LabelAssociationChat, LabelAssociationMessage, LabelEdit, MarkChatAsRead,
+ Mute, Pin, PushNameSetting, Star, UnarchiveChatsSetting, UserStatusMute,
+};
+use crate::types::{Jid, SERVER_JID, parse_jid};
+
+/// How long to wait before asking the phone for the same missing key again.
+const KEY_REQUEST_INTERVAL: Duration = Duration::from_secs(24 * 60 * 60);
+
+/// Go's `types.ParseJID` with the error ignored: the empty JID.
+fn parse_jid_or_empty(jid: &str) -> Jid {
+ parse_jid(jid).unwrap_or_default()
+}
+
+/// Go's `time.UnixMilli`; out of range is the Unix epoch.
+fn unix_milli(milliseconds: i64) -> DateTime<Utc> {
+ DateTime::from_timestamp_millis(milliseconds).unwrap_or_default()
+}
+
+#[async_trait]
+impl DownloadExternal for Client {
+ /// `downloadExternalAppStateBlob`: downloads through the media hosts.
+ async fn download_external(
+ &self,
+ reference: &ExternalBlobReference,
+ ) -> Result<Vec<u8>, Box<dyn std::error::Error + Send + Sync>> {
+ Ok(self.download(reference).await?)
+ }
+}
+
+impl Client {
+ /// Fetches updates to the given type of app state and dispatches their
+ /// events. With `full_sync`, the cached state is removed and every patch
+ /// is fetched again; with `only_if_not_synced`, nothing happens when the
+ /// collection was synced before.
+ pub async fn fetch_app_state(
+ self: &Arc<Self>,
+ name: &WaPatchName,
+ full_sync: bool,
+ only_if_not_synced: bool,
+ ) -> Result<(), ClientError> {
+ let events = self
+ .fetch_app_state_events(name, full_sync, only_if_not_synced)
+ .await?;
+ for event in events {
+ self.dispatch_event(event).await;
+ }
+ Ok(())
+ }
+
+ /// `fetchAppState`: syncs the collection and returns the events to
+ /// dispatch.
+ #[tracing::instrument(
+ name = "whatsmeow.app_state.fetch",
+ skip_all,
+ fields(name = %name, full_sync, only_if_not_synced),
+ err
+ )]
+ async fn fetch_app_state_events(
+ self: &Arc<Self>,
+ name: &WaPatchName,
+ mut full_sync: bool,
+ only_if_not_synced: bool,
+ ) -> Result<Vec<Event>, ClientError> {
+ let _sync = self.app_state_sync_lock.lock().await;
+ let app_state = Arc::clone(&self.store.read().await.app_state);
+ if full_sync {
+ app_state
+ .delete_app_state_version(name.as_str())
+ .await
+ .map_err(|error| {
+ ClientError::from(error)
+ .wrap(format!("failed to reset app state {name} version"))
+ })?;
+ }
+ let (version, hash) = app_state
+ .get_app_state_version(name.as_str())
+ .await
+ .map_err(|error| {
+ ClientError::from(error).wrap(format!("failed to get app state {name} version"))
+ })?;
+ if version == 0 {
+ full_sync = true;
+ } else if only_if_not_synced {
+ return Ok(Vec::new());
+ }
+
+ let mut state = HashState { version, hash };
+ let mut has_more = true;
+ let mut want_snapshot = full_sync;
+ let mut events = Vec::new();
+ let emit = !full_sync || self.config.emit_app_state_events_on_full_sync;
+ while has_more {
+ let patches = match self
+ .fetch_app_state_patches(name, state.version, want_snapshot)
+ .await
+ {
+ Ok(patches) => patches,
+ Err(error) => {
+ if full_sync && !self.background.is_cancelled() {
+ self.dispatch_event(Event::AppStateSyncError(AppStateSyncError {
+ name: name.clone(),
+ error: Arc::new(ClientError::Other(error.to_string())),
+ full_sync,
+ }))
+ .await;
+ }
+ return Err(error.wrap(format!("failed to fetch app state {name} patches")));
+ }
+ };
+ if !want_snapshot && patches.snapshot.is_some() {
+ return Err(ClientError::Other(format!(
+ "server unexpectedly returned snapshot for {name} without asking"
+ )));
+ } else if patches.snapshot.is_some() && state != HashState::default() {
+ return Err(ClientError::Other(format!(
+ "unexpected non-empty input state (v{}) for {name} when applying snapshot",
+ state.version
+ )));
+ }
+ want_snapshot = false;
+ has_more = patches.has_more_patches;
+ state = self
+ .apply_app_state_patches(
+ name,
+ state,
+ &patches,
+ full_sync,
+ emit.then_some(&mut events),
+ )
+ .await?;
+ }
+ if full_sync {
+ tracing::debug!(name = %name, version = state.version, "full sync of app state completed");
+ events.push(Event::AppStateSyncComplete(AppStateSyncComplete {
+ name: name.clone(),
+ version: state.version,
+ recovery: false,
+ }));
+ } else {
+ tracing::debug!(name = %name, from = version, to = state.version, "synced app state");
+ }
+ Ok(events)
+ }
+
+ /// `handleAppStateRecovery`: applies a recovery snapshot the phone sent
+ /// in response to [`build_app_state_recovery_request`]. Returns `false`
+ /// when an event handler failed.
+ #[expect(dead_code, reason = "called by the message receive path, ported next")]
+ pub(crate) async fn handle_app_state_recovery(
+ &self,
+ request_id: &str,
+ result: &[PeerDataOperationResult],
+ ) -> bool {
+ let Some(response) = result
+ .first()
+ .and_then(|first| first.syncd_snapshot_fatal_recovery_response.as_ref())
+ else {
+ tracing::warn!(request_id, "no app state recovery data received");
+ return true;
+ };
+ if result.len() > 1 {
+ tracing::warn!(
+ request_id,
+ count = result.len(),
+ "unexpected number of app state recovery results"
+ );
+ }
+ let snapshot = match parse_recovery(response) {
+ Ok(snapshot) => snapshot,
+ Err(error) => {
+ tracing::warn!(request_id, error = %error, "failed to parse app state recovery blob");
+ return true;
+ }
+ };
+ let name = WaPatchName::from(snapshot.collection_name.clone().unwrap_or_default());
+ let version = snapshot
+ .version
+ .as_ref()
+ .and_then(|version| version.version)
+ .unwrap_or_default();
+ let app_state = Arc::clone(&self.store.read().await.app_state);
+ match app_state.get_app_state_version(name.as_str()).await {
+ Err(error) => {
+ tracing::error!(request_id, name = %name, error = %error, "failed to get current app state version");
+ return true;
+ }
+ Ok((current_version, _)) if current_version >= version => {
+ tracing::info!(
+ request_id,
+ name = %name,
+ current_version,
+ version,
+ "ignoring app state recovery response as current version is newer or equal"
+ );
+ return true;
+ }
+ Ok(_) => {}
+ }
+ tracing::debug!(request_id, "handling app state recovery response");
+ let mutations = match self.app_state_processor().process_recovery(&snapshot).await {
+ Ok(mutations) => mutations,
+ Err(error) => {
+ tracing::warn!(request_id, error = %error, "failed to parse app state recovery blob");
+ return true;
+ }
+ };
+ let mut events = Vec::new();
+ let emit = self.config.emit_app_state_events_on_full_sync;
+ if let Err(error) = self
+ .collect_events_to_dispatch(&name, mutations, true, emit.then_some(&mut events))
+ .await
+ {
+ tracing::warn!(request_id, error = %error, "failed to collect app state events");
+ return true;
+ }
+ events.push(Event::AppStateSyncComplete(AppStateSyncComplete {
+ name: name.clone(),
+ version,
+ recovery: true,
+ }));
+ for event in events {
+ if self.dispatch_event(event).await {
+ return false;
+ }
+ }
+ tracing::debug!(request_id, name = %name, version, "finished handling app state recovery response");
+ true
+ }
+
+ /// `applyAppStatePatches`: decodes the patches on top of `state` and
+ /// collects their events. A missing key is requested from the phone in
+ /// the background.
+ async fn apply_app_state_patches(
+ self: &Arc<Self>,
+ name: &WaPatchName,
+ state: HashState,
+ patches: &PatchList,
+ full_sync: bool,
+ events: Option<&mut Vec<Event>>,
+ ) -> Result<HashState, ClientError> {
+ match self
+ .app_state_processor()
+ .decode_patches(patches, state, true)
+ .await
+ {
+ Ok((mutations, new_state)) => {
+ self.collect_events_to_dispatch(name, mutations, full_sync, events)
+ .await?;
+ Ok(new_state)
+ }
+ Err(error) => {
+ if error.sentinel() == Some(AppStateError::KeyNotFound) {
+ let client = Arc::clone(self);
+ let patches = patches.clone();
+ self.spawn(
+ async move { client.request_missing_app_state_keys(&patches).await },
+ );
+ } else {
+ self.dispatch_event(Event::AppStateSyncError(AppStateSyncError {
+ name: name.clone(),
+ error: Arc::new(ClientError::Other(error.to_string())),
+ full_sync,
+ }))
+ .await;
+ }
+ Err(ClientError::from(error)
+ .wrap(format!("failed to decode app state {name} patches")))
+ }
+ }
+ }
+
+ /// `collectEventsToDispatch`: applies each mutation to the store and
+ /// collects its events when `events` is given. A full sync of the
+ /// contact list without events stores all contacts in one call.
+ async fn collect_events_to_dispatch(
+ &self,
+ name: &WaPatchName,
+ mut mutations: Vec<Mutation>,
+ full_sync: bool,
+ mut events: Option<&mut Vec<Event>>,
+ ) -> Result<(), ClientError> {
+ if *name == WA_PATCH_CRITICAL_UNBLOCK_LOW
+ && full_sync
+ && !self.config.emit_app_state_events_on_full_sync
+ {
+ let contacts;
+ (mutations, contacts) = filter_contacts(mutations);
+ tracing::debug!(
+ count = contacts.len(),
+ "mass inserting app state snapshot contacts into the store"
+ );
+ let contact_store = Arc::clone(&self.store.read().await.contacts);
+ // A serious failure, so the whole sync is aborted.
+ contact_store
+ .put_all_contact_names(&contacts)
+ .await
+ .map_err(|error| {
+ ClientError::Other(format!(
+ "failed to update contact store with data from snapshot: {error}"
+ ))
+ })?;
+ }
+ for mutation in mutations {
+ if let Some(events) = &mut events
+ && mutation.operation == SyncdOperation::Set as i32
+ {
+ events.push(Event::AppState(Box::new(AppState {
+ index: mutation.index.clone(),
+ sync_action_value: mutation.action.clone(),
+ })));
+ }
+ let event = self.dispatch_app_state(name, &mutation, full_sync).await;
+ if let (Some(events), Some(event)) = (&mut events, event) {
+ events.push(event);
+ }
+ }
+ Ok(())
+ }
+
+ /// `dispatchAppState`: applies one mutation's side effects to the store
+ /// and returns its event. Where Go indexes past the end of a short index
+ /// and panics, this returns `None`.
+ async fn dispatch_app_state(
+ &self,
+ name: &WaPatchName,
+ mutation: &Mutation,
+ full_sync: bool,
+ ) -> Option<Event> {
+ let kind = mutation.index.first().map(String::as_str);
+ tracing::trace!(
+ patch_name = %name,
+ patch_version = mutation.patch_version,
+ operation = mutation.operation,
+ version = mutation.version,
+ kind,
+ "received app state mutation"
+ );
+ let kind = kind?;
+ let action = mutation.action.clone().unwrap_or_default();
+ let set = mutation.operation == SyncdOperation::Set as i32;
+
+ if mutation.index.len() == 1 && kind == INDEX_NCT_SALT_SYNC {
+ let nct_salt = Arc::clone(&self.store.read().await.nct_salt);
+ let result = if set {
+ let salt = action
+ .nct_salt_sync_action
+ .and_then(|action| action.salt)
+ .unwrap_or_default();
+ if salt.is_empty() {
+ Ok(())
+ } else {
+ let result = nct_salt.put_nct_salt(salt).await;
+ if result.is_ok() {
+ tracing::debug!("stored new NCT salt");
+ }
+ result
+ }
+ } else if mutation.operation == SyncdOperation::Remove as i32 {
+ tracing::debug!("clearing NCT salt");
+ nct_salt.delete_nct_salt().await
+ } else {
+ Ok(())
+ };
+ if let Err(error) = result {
+ tracing::warn!(error = %error, "failed to update NCT salt from app state mutation");
+ }
+ return None;
+ }
+
+ if !set {
+ return None;
+ }
+
+ let jid = mutation
+ .index
+ .get(1)
+ .map(|jid| parse_jid_or_empty(jid))
+ .unwrap_or_default();
+ let timestamp = unix_milli(action.timestamp.unwrap_or_default());
+ let (contacts, chat_settings, msg_secrets) = {
+ let store = self.store.read().await;
+ (
+ Arc::clone(&store.contacts),
+ Arc::clone(&store.chat_settings),
+ Arc::clone(&store.msg_secrets),
+ )
+ };
+
+ let mut store_update_result = Ok(());
+ let event = match kind {
+ INDEX_MUTE => {
+ let action = action.mute_action;
+ let muted_until = action
+ .as_ref()
+ .filter(|action| action.muted.unwrap_or_default())
+ .map(|action| {
+ let end = action.mute_end_timestamp.unwrap_or_default();
+ if end < 0 {
+ *MUTED_FOREVER
+ } else {
+ unix_milli(end)
+ }
+ });
+ store_update_result = chat_settings.put_muted_until(&jid, muted_until).await;
+ Event::Mute(Box::new(Mute {
+ jid,
+ timestamp,
+ action,
+ from_full_sync: full_sync,
+ }))
+ }
+ INDEX_PIN => {
+ let action = action.pin_action;
+ let pinned = action
+ .as_ref()
+ .and_then(|action| action.pinned)
+ .unwrap_or_default();
+ store_update_result = chat_settings.put_pinned(&jid, pinned).await;
+ Event::Pin(Box::new(Pin {
+ jid,
+ timestamp,
+ action,
+ from_full_sync: full_sync,
+ }))
+ }
+ INDEX_ARCHIVE => {
+ let action = action.archive_chat_action;
+ let archived = action
+ .as_ref()
+ .and_then(|action| action.archived)
+ .unwrap_or_default();
+ store_update_result = chat_settings.put_archived(&jid, archived).await;
+ Event::Archive(Box::new(Archive {
+ jid,
+ timestamp,
+ action,
+ from_full_sync: full_sync,
+ }))
+ }
+ INDEX_CONTACT => {
+ let action = action.contact_action;
+ let (first_name, full_name) = action.as_ref().map_or((None, None), |action| {
+ (action.first_name.as_deref(), action.full_name.as_deref())
+ });
+ // Go passes (first, full) to an interface declared (full,
+ // first) whose SQL implementation takes (first, full).
+ store_update_result = contacts
+ .put_contact_name(
+ &jid,
+ full_name.unwrap_or_default(),
+ first_name.unwrap_or_default(),
+ )
+ .await;
+ Event::Contact(Box::new(Contact {
+ jid,
+ timestamp,
+ action,
+ from_full_sync: full_sync,
+ }))
+ }
+ INDEX_CLEAR_CHAT => Event::ClearChat(Box::new(ClearChat {
+ jid,
+ timestamp,
+ action: action.clear_chat_action,
+ from_full_sync: full_sync,
+ // Go doesn't know what index 2 is either.
+ delete_media: mutation.index.get(3).is_some_and(|value| value == "1"),
+ })),
+ INDEX_DELETE_CHAT => Event::DeleteChat(Box::new(DeleteChat {
+ jid,
+ timestamp,
+ action: action.delete_chat_action,
+ from_full_sync: full_sync,
+ delete_media: mutation.index.get(2).is_some_and(|value| value == "1"),
+ })),
+ INDEX_STAR => {
+ let [_, _, message_id, from_me, sender, ..] = mutation.index.as_slice() else {
+ return None;
+ };
+ Event::Star(Box::new(Star {
+ chat_jid: jid,
+ sender_jid: sender_of(sender),
+ is_from_me: from_me == "1",
+ message_id: message_id.clone(),
+ timestamp,
+ action: action.star_action,
+ from_full_sync: full_sync,
+ }))
+ }
+ INDEX_DELETE_MESSAGE_FOR_ME => {
+ let [_, _, message_id, from_me, sender, ..] = mutation.index.as_slice() else {
+ return None;
+ };
+ Event::DeleteForMe(Box::new(DeleteForMe {
+ chat_jid: jid,
+ sender_jid: sender_of(sender),
+ is_from_me: from_me == "1",
+ message_id: message_id.clone(),
+ timestamp,
+ action: action.delete_message_for_me_action,
+ from_full_sync: full_sync,
+ }))
+ }
+ INDEX_MARK_CHAT_AS_READ => Event::MarkChatAsRead(Box::new(MarkChatAsRead {
+ jid,
+ timestamp,
+ action: action.mark_chat_as_read_action,
+ from_full_sync: full_sync,
+ })),
+ INDEX_SETTING_PUSH_NAME => {
+ let action = action.push_name_setting;
+ let mut store = self.store.write().await;
+ store.push_name = action
+ .as_ref()
+ .and_then(|action| action.name.clone())
+ .unwrap_or_default();
+ if let Err(error) = store.save().await {
+ tracing::error!(error = %error, "failed to save device store after updating push name");
+ }
+ Event::PushNameSetting(Box::new(PushNameSetting {
+ timestamp,
+ action,
+ from_full_sync: full_sync,
+ }))
+ }
+ INDEX_SETTING_UNARCHIVE_CHATS => {
+ Event::UnarchiveChatsSetting(Box::new(UnarchiveChatsSetting {
+ timestamp,
+ action: action.unarchive_chats_setting,
+ from_full_sync: full_sync,
+ }))
+ }
+ INDEX_USER_STATUS_MUTE => Event::UserStatusMute(Box::new(UserStatusMute {
+ jid,
+ timestamp,
+ action: action.user_status_mute_action,
+ from_full_sync: full_sync,
+ })),
+ INDEX_LABEL_EDIT => Event::LabelEdit(Box::new(LabelEdit {
+ timestamp,
+ label_id: mutation.index.get(1)?.clone(),
+ action: action.label_edit_action,
+ from_full_sync: full_sync,
+ })),
+ INDEX_LABEL_ASSOCIATION_CHAT => {
+ let [_, label_id, chat, ..] = mutation.index.as_slice() else {
+ return None;
+ };
+ Event::LabelAssociationChat(Box::new(LabelAssociationChat {
+ jid: parse_jid_or_empty(chat),
+ timestamp,
+ label_id: label_id.clone(),
+ action: action.label_association_action,
+ from_full_sync: full_sync,
+ }))
+ }
+ INDEX_LABEL_ASSOCIATION_MESSAGE => {
+ let [_, label_id, chat, message_id, _, _, ..] = mutation.index.as_slice() else {
+ return None;
+ };
+ Event::LabelAssociationMessage(Box::new(LabelAssociationMessage {
+ jid: parse_jid_or_empty(chat),
+ timestamp,
+ label_id: label_id.clone(),
+ message_id: message_id.clone(),
+ action: action.label_association_action,
+ from_full_sync: full_sync,
+ }))
+ }
+ INDEX_WASA_ROOT_SECRET_ACTION => {
+ let bot_jid = mutation.index.get(1).map(|jid| parse_jid_or_empty(jid))?;
+ let own_lid = self.get_own_lid().await;
+ let secrets = action
+ .wasa_root_secret_action
+ .map(|action| action.secrets)
+ .unwrap_or_default();
+ let inserts: Vec<MessageSecretInsert> = secrets
+ .iter()
+ .map(|secret| MessageSecretInsert {
+ chat: bot_jid.clone(),
+ sender: own_lid.clone(),
+ id: secret.id.clone().unwrap_or_default(),
+ secret: secret.root_secret.clone().unwrap_or_default(),
+ })
+ .collect();
+ store_update_result = msg_secrets.put_message_secrets(&inserts).await;
+ if store_update_result.is_ok() {
+ let mut active: Option<&RootSecretEntry> = None;
+ for secret in &secrets {
+ if secret.status == Some(RootSecretStatus::Active as i32)
+ && active.is_none_or(|current| {
+ secret.epoch.unwrap_or_default() > current.epoch.unwrap_or_default()
+ })
+ {
+ active = Some(secret);
+ }
+ }
+ let active_id = active
+ .and_then(|active| active.id.clone())
+ .unwrap_or_default();
+ store_update_result = chat_settings
+ .put_wasa_root_secret_id(&bot_jid, &active_id)
+ .await;
+ }
+ if store_update_result.is_ok() {
+ tracing::debug!(
+ count = inserts.len(),
+ "stored WASA root secrets from app state"
+ );
+ }
+ if let Err(error) = store_update_result {
+ tracing::error!(error = %error, "failed to update device store after app state mutation");
+ }
+ return None;
+ }
+ _ => return None,
+ };
+ if let Err(error) = store_update_result {
+ tracing::error!(error = %error, "failed to update device store after app state mutation");
+ }
+ Some(event)
+ }
+
+ /// `fetchAppStatePatches`: asks the server for the collection's patches
+ /// after `from_version`, or for a snapshot.
+ async fn fetch_app_state_patches(
+ &self,
+ name: &WaPatchName,
+ from_version: u64,
+ snapshot: bool,
+ ) -> Result<PatchList, ClientError> {
+ let mut attrs = Attrs::from([
+ ("name".to_owned(), name.as_str().into()),
+ ("return_snapshot".to_owned(), snapshot.into()),
+ ]);
+ if !snapshot {
+ attrs.insert("version".to_owned(), from_version.into());
+ }
+ let response = self
+ .send_iq(InfoQuery {
+ namespace: "w:sync:app:state",
+ r#type: IqType::Set,
+ to: SERVER_JID.clone(),
+ content: Some(NodeContent::Nodes(vec![Node {
+ tag: "sync".to_owned(),
+ attrs: Attrs::new(),
+ content: Some(NodeContent::Nodes(vec![Node {
+ tag: "collection".to_owned(),
+ attrs,
+ content: None,
+ }])),
+ }])),
+ ..Default::default()
+ })
+ .await?;
+ let collection = response
+ .get_optional_child_by_tag(&["sync", "collection"])
+ .ok_or_else(|| element_missing("collection", "app state patch response"))?;
+ Ok(parse_patch_list(collection, Some(self as &dyn DownloadExternal)).await?)
+ }
+
+ /// `requestMissingAppStateKeys`: asks the phone for the keys the patches
+ /// need, at most once a day per key.
+ async fn request_missing_app_state_keys(self: &Arc<Self>, patches: &PatchList) {
+ let raw_key_ids = self
+ .app_state_processor()
+ .get_missing_key_ids(patches)
+ .await;
+ let now = tokio::time::Instant::now();
+ let filtered_key_ids = {
+ let mut requests = lock(&self.app_state_key_requests);
+ raw_key_ids
+ .into_iter()
+ .filter(|key_id| {
+ let string_key_id = hex::encode(key_id);
+ let due = requests
+ .get(&string_key_id)
+ .is_none_or(|last_request| *last_request + KEY_REQUEST_INTERVAL < now);
+ if due {
+ requests.insert(string_key_id, now);
+ }
+ due
+ })
+ .collect::<Vec<_>>()
+ };
+ self.request_app_state_keys(&filtered_key_ids).await;
+ }
+
+ /// `requestAppStateKeys`: sends the phone a key request for the keys.
+ async fn request_app_state_keys(self: &Arc<Self>, raw_key_ids: &[Vec<u8>]) {
+ if raw_key_ids.is_empty() {
+ return;
+ }
+ let key_ids: Vec<String> = raw_key_ids.iter().map(hex::encode).collect();
+ tracing::info!(key_ids = ?key_ids, "sending key request for app state keys");
+ if let Err(error) = self
+ .send_peer_message(build_app_state_key_request(raw_key_ids))
+ .await
+ {
+ tracing::warn!(error = %error, "failed to send app state key request");
+ }
+ }
+
+ /// Sends an app state patch, then resyncs that collection to update the
+ /// local state and dispatch the events of the change. Build the patch
+ /// with the `build_*` functions of [`crate::appstate`], e.g.
+ /// [`build_mute`](crate::appstate::build_mute).
+ #[tracing::instrument(
+ name = "whatsmeow.app_state.send",
+ skip_all,
+ fields(name = %patch.patch_type),
+ err
+ )]
+ pub async fn send_app_state(self: &Arc<Self>, patch: PatchInfo) -> Result<(), ClientError> {
+ self.send_app_state_inner(patch, true).await
+ }
+
+ /// Boxed because a conflict retries once by recursing.
+ fn send_app_state_inner(
+ self: &Arc<Self>,
+ patch: PatchInfo,
+ allow_retry: bool,
+ ) -> BoxFuture<'_, Result<(), ClientError>> {
+ Box::pin(async move {
+ let (app_state, app_state_keys) = {
+ let store = self.store.read().await;
+ (
+ Arc::clone(&store.app_state),
+ Arc::clone(&store.app_state_keys),
+ )
+ };
+ let (version, hash) = app_state
+ .get_app_state_version(patch.patch_type.as_str())
+ .await?;
+ // Go: TODO create new key instead of reusing the primary
+ // client's keys.
+ let latest_key_id = app_state_keys
+ .get_latest_app_state_sync_key_id()
+ .await
+ .map_err(|error| {
+ ClientError::from(error).wrap("failed to get latest app state key ID")
+ })?
+ .ok_or_else(|| {
+ ClientError::Other(
+ "no app state keys found, creating app state keys is not yet supported"
+ .to_owned(),
+ )
+ })?;
+ let state = HashState { version, hash };
+ let encoded_patch = self
+ .app_state_processor()
+ .encode_patch(&latest_key_id, state, patch.clone())
+ .await?;
+
+ let response = self
+ .send_iq(InfoQuery {
+ namespace: "w:sync:app:state",
+ r#type: IqType::Set,
+ to: SERVER_JID.clone(),
+ content: Some(NodeContent::Nodes(vec![Node {
+ tag: "sync".to_owned(),
+ attrs: Attrs::new(),
+ content: Some(NodeContent::Nodes(vec![Node {
+ tag: "collection".to_owned(),
+ attrs: Attrs::from([
+ ("name".to_owned(), patch.patch_type.as_str().into()),
+ ("version".to_owned(), version.into()),
+ ("return_snapshot".to_owned(), false.into()),
+ ]),
+ content: Some(NodeContent::Nodes(vec![Node {
+ tag: "patch".to_owned(),
+ attrs: Attrs::new(),
+ content: Some(NodeContent::Bytes(encoded_patch)),
+ }])),
+ }])),
+ }])),
+ ..Default::default()
+ })
+ .await?;
+
+ let collection = response
+ .get_optional_child_by_tag(&["sync", "collection"])
+ .ok_or_else(|| element_missing("collection", "app state send response"))?;
+ if collection.attr_getter().optional_string("type") == "error" {
+ let error_tag = collection.get_optional_child_by_tag(&["error"]);
+ let main_error = match error_tag {
+ Some(error_tag) => ClientError::AppStateUpdate
+ .wrap(format!("{} {error_tag}", patch.patch_type)),
+ None => ClientError::AppStateUpdate.wrap(collection.to_string()),
+ };
+ if let Some(error_tag) = error_tag
+ && error_tag.attr_getter().int("code") == 409
+ && allow_retry
+ {
+ tracing::warn!(error = %main_error, "failed to update app state, trying to apply conflicts and retry");
+ let patches =
+ parse_patch_list(collection, Some(self.as_ref() as &dyn DownloadExternal))
+ .await
+ .map_err(|error| {
+ main_error.wrap(format!(
+ "also, parsing patches in the response failed: {error}"
+ ))
+ })?;
+ let mut events = Vec::new();
+ if let Err(error) = self
+ .apply_app_state_patches(
+ &patch.patch_type,
+ state,
+ &patches,
+ false,
+ Some(&mut events),
+ )
+ .await
+ {
+ return Err(ClientError::AppStateUpdate.wrap(format!(
+ "{} (also, applying patches in the response failed: {error})",
+ patch.patch_type
+ )));
+ }
+ tracing::debug!("retrying app state send after applying conflicting patches");
+ self.spawn_dispatch_all(events);
+ return self.send_app_state_inner(patch, false).await;
+ }
+ return Err(main_error);
+ }
+ let events = self
+ .fetch_app_state_events(&patch.patch_type, false, false)
+ .await
+ .map_err(|error| error.wrap("failed to fetch app state after sending update"))?;
+ self.spawn_dispatch_all(events);
+ Ok(())
+ })
+ }
+
+ /// Dispatches the events in order in the background (Go's goroutine
+ /// looping over `dispatchEvent`).
+ fn spawn_dispatch_all(self: &Arc<Self>, events: Vec<Event>) {
+ let client = Arc::clone(self);
+ self.spawn(async move {
+ for event in events {
+ client.dispatch_event(event).await;
+ }
+ });
+ }
+
+ /// Tells the server that a dirty bit of the given type is clean.
+ pub async fn mark_not_dirty(
+ &self,
+ clean_type: &str,
+ timestamp: DateTime<Utc>,
+ ) -> Result<(), ClientError> {
+ self.send_iq(InfoQuery {
+ namespace: "urn:xmpp:whatsapp:dirty",
+ r#type: IqType::Set,
+ to: SERVER_JID.clone(),
+ content: Some(NodeContent::Nodes(vec![Node {
+ tag: "clean".to_owned(),
+ attrs: Attrs::from([
+ ("type".to_owned(), clean_type.into()),
+ ("timestamp".to_owned(), timestamp.timestamp().into()),
+ ]),
+ content: None,
+ }])),
+ ..Default::default()
+ })
+ .await
+ .map(|_| ())
+ }
+
+ /// Stores the app state keys the phone shared, then fetches every
+ /// collection: all of them when a key answers one of our requests,
+ /// otherwise only the ones never synced (`handleAppStateSyncKeyShare` in
+ /// Go's `message.go`). The message receive path calls this for a
+ /// protocol message's `app_state_sync_key_share`.
+ pub(crate) async fn handle_app_state_sync_key_share(
+ self: &Arc<Self>,
+ keys: &AppStateSyncKeyShare,
+ ) {
+ let mut only_resync_if_not_synced = true;
+ tracing::debug!(count = keys.keys.len(), "got new app state keys");
+ let app_state_keys = Arc::clone(&self.store.read().await.app_state_keys);
+ for key in &keys.keys {
+ let key_id = key
+ .key_id
+ .as_ref()
+ .and_then(|key_id| key_id.key_id.clone())
+ .unwrap_or_default();
+ let key_data = key.key_data.clone().unwrap_or_default();
+ let fingerprint = key_data
+ .fingerprint
+ .as_ref()
+ .map(prost::Message::encode_to_vec)
+ .unwrap_or_default();
+ if lock(&self.app_state_key_requests).contains_key(&hex::encode(&key_id)) {
+ only_resync_if_not_synced = false;
+ }
+ let timestamp = key_data.timestamp.unwrap_or_default();
+ if let Err(error) = app_state_keys
+ .put_app_state_sync_key(
+ &key_id,
+ AppStateSyncKey {
+ data: key_data.key_data.unwrap_or_default(),
+ fingerprint,
+ timestamp,
+ },
+ )
+ .await
+ {
+ tracing::error!(key_id = %hex::encode_upper(&key_id), error = %error, "failed to store app state sync key");
+ continue;
+ }
+ tracing::debug!(key_id = %hex::encode_upper(&key_id), timestamp, "received app state sync key");
+ }
+
+ for name in &ALL_PATCH_NAMES {
+ if let Err(error) = self
+ .fetch_app_state(name, false, only_resync_if_not_synced)
+ .await
+ {
+ tracing::error!(name = %name, error = %error, "failed to do initial fetch of app state");
+ }
+ }
+ }
+
+ /// `handleAppStateNotification`: a `server_sync` notification lists the
+ /// collections that changed; fetch each, stopping when disconnected.
+ pub(crate) async fn handle_app_state_notification(self: &Arc<Self>, node: &Node) {
+ for collection in node.get_children_by_tag("collection") {
+ let mut attrs = collection.attr_getter();
+ let name = WaPatchName::from(attrs.string("name"));
+ let version = attrs.uint64("version");
+ tracing::debug!(name = %name, version, "got server sync notification that app state was updated");
+ match self.fetch_app_state(&name, false, false).await {
+ Err(error)
+ if error.is(&DisconnectedError::iq().into())
+ || error.is(&ClientError::NotConnected) =>
+ {
+ // There are some app state changes right before a remote
+ // logout, so stop syncing when disconnected.
+ tracing::debug!(error = %error, "failed to sync app state after notification, not trying to sync other states");
+ return;
+ }
+ Err(error) => {
+ tracing::error!(error = %error, "failed to sync app state after notification");
+ }
+ Ok(()) => {}
+ }
+ }
+ }
+}
+
+/// Go's `SenderJID` for stars and deletes: empty when the index says `0`.
+fn sender_of(sender: &str) -> Jid {
+ if sender == "0" {
+ Jid::default()
+ } else {
+ parse_jid_or_empty(sender)
+ }
+}
+
+/// `filterContacts`: splits contact mutations off as store entries.
+fn filter_contacts(mutations: Vec<Mutation>) -> (Vec<Mutation>, Vec<ContactEntry>) {
+ let mut filtered_mutations = Vec::with_capacity(mutations.len());
+ let mut contacts = Vec::with_capacity(mutations.len());
+ for mutation in mutations {
+ match mutation.index.as_slice() {
+ [kind, jid, ..] if kind == INDEX_CONTACT => {
+ let action = mutation
+ .action
+ .as_ref()
+ .and_then(|action| action.contact_action.as_ref());
+ contacts.push(ContactEntry {
+ jid: parse_jid_or_empty(jid),
+ first_name: action
+ .and_then(|action| action.first_name.clone())
+ .unwrap_or_default(),
+ full_name: action
+ .and_then(|action| action.full_name.clone())
+ .unwrap_or_default(),
+ });
+ }
+ _ => filtered_mutations.push(mutation),
+ }
+ }
+ (filtered_mutations, contacts)
+}
+
+/// The protocol message asking the phone for app state keys (built in Go's
+/// `requestAppStateKeys`).
+pub(crate) fn build_app_state_key_request(raw_key_ids: &[Vec<u8>]) -> wa_e2e::Message {
+ wa_e2e::Message {
+ protocol_message: Some(Box::new(ProtocolMessage {
+ r#type: Some(protocol_message::Type::AppStateSyncKeyRequest as i32),
+ app_state_sync_key_request: Some(AppStateSyncKeyRequest {
+ key_i_ds: raw_key_ids
+ .iter()
+ .map(|key_id| AppStateSyncKeyId {
+ key_id: Some(key_id.clone()),
+ })
+ .collect(),
+ }),
+ ..ProtocolMessage::default()
+ })),
+ ..wa_e2e::Message::default()
+ }
+}
+
+/// Builds a message asking the user's primary device to reset the given app
+/// state collections, which logs out every linked device. Send it with the
+/// client's peer message sending; there is no response.
+pub fn build_fatal_app_state_exception_notification(
+ collections: &[WaPatchName],
+) -> wa_e2e::Message {
+ wa_e2e::Message {
+ protocol_message: Some(Box::new(ProtocolMessage {
+ r#type: Some(protocol_message::Type::AppStateFatalExceptionNotification as i32),
+ app_state_fatal_exception_notification: Some(AppStateFatalExceptionNotification {
+ collection_names: collections
+ .iter()
+ .map(|collection| collection.as_str().to_owned())
+ .collect(),
+ timestamp: Some(Utc::now().timestamp_millis()),
+ }),
+ ..ProtocolMessage::default()
+ })),
+ ..wa_e2e::Message::default()
+ }
+}
+
+/// Builds a message asking the user's primary device for an unencrypted copy
+/// of the collection. The response comes as a protocol message of type
+/// `PEER_DATA_OPERATION_RESPONSE_MESSAGE`.
+pub fn build_app_state_recovery_request(collection: &WaPatchName) -> wa_e2e::Message {
+ wa_e2e::Message {
+ protocol_message: Some(Box::new(ProtocolMessage {
+ r#type: Some(protocol_message::Type::PeerDataOperationRequestMessage as i32),
+ peer_data_operation_request_message: Some(PeerDataOperationRequestMessage {
+ peer_data_operation_request_type: Some(
+ PeerDataOperationRequestType::CompanionSyncdSnapshotFatalRecovery as i32,
+ ),
+ syncd_collection_fatal_recovery_request: Some(
+ SyncDCollectionFatalRecoveryRequest {
+ collection_name: Some(collection.as_str().to_owned()),
+ timestamp: Some(Utc::now().timestamp()),
+ },
+ ),
+ ..PeerDataOperationRequestMessage::default()
+ }),
+ ..ProtocolMessage::default()
+ })),
+ ..wa_e2e::Message::default()
+ }
+}
+
+#[cfg(test)]
+mod test;
diff --git a/crates/whatsmeow/src/appstate/client/test.rs b/crates/whatsmeow/src/appstate/client/test.rs
new file mode 100644
index 0000000000..3f421ded4b
--- /dev/null
+++ b/crates/whatsmeow/src/appstate/client/test.rs
@@ -0,0 +1,834 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+//! The app state client against the fake server, checked against
+//! `testdata/appstate_client.json`, which whatsmeow's own client code wrote
+//! (`testdata/generator/inpackage/appstate_client_vectors_test.go`).
+
+use std::sync::Arc;
+
+use chrono::DateTime;
+use prost::Message as _;
+use serde_json::{Value, json};
+
+use super::*;
+use crate::appstate::{Processor, WA_PATCH_REGULAR_HIGH, WA_PATCH_REGULAR_LOW, build_pin};
+use crate::binary::AttributeValue;
+use crate::client::test::{
+ bytes, children, connect_paired, harness, harness_with, is_noise, jid, next_event, node, text,
+};
+use crate::proto::wa_e2e::{AppStateSyncKey as SharedKey, AppStateSyncKeyData};
+use crate::proto::wa_server_sync::{SyncdPatch, SyncdVersion};
+use crate::store::{
+ AppStateStore, AppStateSyncKeyStore, ChatSettingsStore, ContactStore, MemoryStore,
+};
+use crate::testing::{ServerConnection, attr_string, is_iq};
+use crate::vectors::Vectors;
+
+const OWN_JID: (&str, &str) = ("1234:[email protected]", "9876:5@lid");
+
+/// The next request, skipping keepalives and the client's acks.
+async fn next_request(connection: &mut ServerConnection) -> Node {
+ connection
+ .recv_node_skipping(|node| is_noise(node) || node.tag == "ack")
+ .await
+ .expect("client sent a node")
+}
+
+/// The request with the ID Go's vector has. Nodes are compared decoded:
+/// Go marshals attributes in its random map order.
+fn with_vector_id(mut request: Node, vector: &Node) -> Node {
+ request
+ .attrs
+ .insert("id".to_owned(), vector.attrs["id"].clone());
+ request
+}
+
+fn server_sync(collection: &str, version: &str) -> Node {
+ node(
+ "notification",
+ &[
+ ("id", text("notification-1")),
+ ("type", text("server_sync")),
+ ("from", jid("s.whatsapp.net")),
+ ],
+ children(vec![node(
+ "collection",
+ &[("name", text(collection)), ("version", text(version))],
+ None,
+ )]),
+ )
+}
+
+/// `<sync><collection><patches>…` with the patches as the server sends them.
+fn patches_response(collection: &str, version: &str, patches: &[Vec<u8>]) -> Vec<Node> {
+ vec![node(
+ "sync",
+ &[],
+ children(vec![node(
+ "collection",
+ &[("name", text(collection)), ("version", text(version))],
+ children(vec![node(
+ "patches",
+ &[],
+ children(
+ patches
+ .iter()
+ .map(|patch| node("patch", &[], bytes(patch)))
+ .collect(),
+ ),
+ )]),
+ )]),
+ )]
+}
+
+async fn put_key(store: &MemoryStore, vectors: &Vectors, number: u8) {
+ store
+ .put_app_state_sync_key(
+ &vectors.bytes(&format!("key_{number}_id")),
+ AppStateSyncKey {
+ data: vectors.bytes(&format!("key_{number}_data")),
+ fingerprint: Vec::new(),
+ timestamp: 0,
+ },
+ )
+ .await
+ .unwrap();
+}
+
+/// An event in the shape the Go generator writes.
+fn event_vector(event: &Event) -> Value {
+ fn action(message: Option<&impl prost::Message>) -> String {
+ message
+ .map(|message| hex::encode(message.encode_to_vec()))
+ .unwrap_or_default()
+ }
+ match event {
+ Event::AppState(event) => json!({
+ "type": "AppState",
+ "index": event.index,
+ "action": action(event.sync_action_value.as_ref()),
+ }),
+ Event::Contact(event) => json!({
+ "type": "Contact", "jid": event.jid.to_string(),
+ "timestamp": event.timestamp.timestamp_millis(),
+ "action": action(event.action.as_ref()), "from_full_sync": event.from_full_sync,
+ }),
+ Event::Mute(event) => json!({
+ "type": "Mute", "jid": event.jid.to_string(),
+ "timestamp": event.timestamp.timestamp_millis(),
+ "action": action(event.action.as_ref()), "from_full_sync": event.from_full_sync,
+ }),
+ Event::Pin(event) => json!({
+ "type": "Pin", "jid": event.jid.to_string(),
+ "timestamp": event.timestamp.timestamp_millis(),
+ "action": action(event.action.as_ref()), "from_full_sync": event.from_full_sync,
+ }),
+ Event::Archive(event) => json!({
+ "type": "Archive", "jid": event.jid.to_string(),
+ "timestamp": event.timestamp.timestamp_millis(),
+ "action": action(event.action.as_ref()), "from_full_sync": event.from_full_sync,
+ }),
+ Event::MarkChatAsRead(event) => json!({
+ "type": "MarkChatAsRead", "jid": event.jid.to_string(),
+ "timestamp": event.timestamp.timestamp_millis(),
+ "action": action(event.action.as_ref()), "from_full_sync": event.from_full_sync,
+ }),
+ Event::ClearChat(event) => json!({
+ "type": "ClearChat", "jid": event.jid.to_string(),
+ "timestamp": event.timestamp.timestamp_millis(),
+ "action": action(event.action.as_ref()), "from_full_sync": event.from_full_sync,
+ "delete_media": event.delete_media,
+ }),
+ Event::DeleteChat(event) => json!({
+ "type": "DeleteChat", "jid": event.jid.to_string(),
+ "timestamp": event.timestamp.timestamp_millis(),
+ "action": action(event.action.as_ref()), "from_full_sync": event.from_full_sync,
+ "delete_media": event.delete_media,
+ }),
+ Event::Star(event) => json!({
+ "type": "Star", "jid": event.chat_jid.to_string(),
+ "sender_jid": event.sender_jid.to_string(), "is_from_me": event.is_from_me,
+ "message_id": event.message_id, "timestamp": event.timestamp.timestamp_millis(),
+ "action": action(event.action.as_ref()), "from_full_sync": event.from_full_sync,
+ }),
+ Event::DeleteForMe(event) => json!({
+ "type": "DeleteForMe", "jid": event.chat_jid.to_string(),
+ "sender_jid": event.sender_jid.to_string(), "is_from_me": event.is_from_me,
+ "message_id": event.message_id, "timestamp": event.timestamp.timestamp_millis(),
+ "action": action(event.action.as_ref()), "from_full_sync": event.from_full_sync,
+ }),
+ Event::PushNameSetting(event) => json!({
+ "type": "PushNameSetting", "timestamp": event.timestamp.timestamp_millis(),
+ "action": action(event.action.as_ref()), "from_full_sync": event.from_full_sync,
+ }),
+ Event::UnarchiveChatsSetting(event) => json!({
+ "type": "UnarchiveChatsSetting", "timestamp": event.timestamp.timestamp_millis(),
+ "action": action(event.action.as_ref()), "from_full_sync": event.from_full_sync,
+ }),
+ Event::UserStatusMute(event) => json!({
+ "type": "UserStatusMute", "jid": event.jid.to_string(),
+ "timestamp": event.timestamp.timestamp_millis(),
+ "action": action(event.action.as_ref()), "from_full_sync": event.from_full_sync,
+ }),
+ Event::LabelEdit(event) => json!({
+ "type": "LabelEdit", "label_id": event.label_id,
+ "timestamp": event.timestamp.timestamp_millis(),
+ "action": action(event.action.as_ref()), "from_full_sync": event.from_full_sync,
+ }),
+ Event::LabelAssociationChat(event) => json!({
+ "type": "LabelAssociationChat", "jid": event.jid.to_string(),
+ "label_id": event.label_id, "timestamp": event.timestamp.timestamp_millis(),
+ "action": action(event.action.as_ref()), "from_full_sync": event.from_full_sync,
+ }),
+ Event::LabelAssociationMessage(event) => json!({
+ "type": "LabelAssociationMessage", "jid": event.jid.to_string(),
+ "label_id": event.label_id, "message_id": event.message_id,
+ "timestamp": event.timestamp.timestamp_millis(),
+ "action": action(event.action.as_ref()), "from_full_sync": event.from_full_sync,
+ }),
+ other => panic!("unexpected event {other:?}"),
+ }
+}
+
+async fn next_events(
+ events: &mut tokio::sync::mpsc::UnboundedReceiver<Event>,
+ count: usize,
+) -> Vec<Value> {
+ let mut out = Vec::with_capacity(count);
+ for _ in 0..count {
+ out.push(event_vector(&next_event(events).await));
+ }
+ out
+}
+
+#[tokio::test(start_paused = true)]
+async fn server_sync_full_sync_then_incremental_sync() {
+ let vectors = Vectors::load("appstate_client.json");
+ let mut harness = harness_with(Some(OWN_JID), |config| {
+ config.emit_app_state_events_on_full_sync = true;
+ });
+ put_key(&harness.store, &vectors, 1).await;
+ let mut connection = connect_paired(&mut harness).await;
+
+ // Version 0: a full sync asking for a snapshot.
+ connection
+ .send_node(&server_sync("regular_high", "1"))
+ .await;
+ let request = next_request(&mut connection).await;
+ let expected = vectors.node("fetch_snapshot_iq");
+ assert_eq!(with_vector_id(request.clone(), &expected), expected);
+ connection
+ .respond_iq(
+ &request,
+ patches_response(
+ "regular_high",
+ "1",
+ &[vectors.bytes("regular_high_v1_patch")],
+ ),
+ )
+ .await;
+ let expected_events = vectors.value("regular_high_v1_events").as_array().unwrap();
+ let events = next_events(&mut harness.events, expected_events.len()).await;
+ assert_eq!(&events, expected_events);
+ let Event::AppStateSyncComplete(complete) = next_event(&mut harness.events).await else {
+ panic!("expected AppStateSyncComplete");
+ };
+ assert_eq!(
+ complete,
+ AppStateSyncComplete {
+ name: WA_PATCH_REGULAR_HIGH,
+ version: 1,
+ recovery: false,
+ }
+ );
+
+ let chat = parse_jid("[email protected]").unwrap();
+ let group = parse_jid("[email protected]").unwrap();
+ let chat_settings = harness
+ .store
+ .get_chat_settings(&chat)
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(
+ chat_settings.muted_until,
+ DateTime::from_timestamp_millis(1_700_003_600_000)
+ );
+ assert!(chat_settings.archived);
+ assert!(!chat_settings.pinned);
+ assert!(
+ harness
+ .store
+ .get_chat_settings(&group)
+ .await
+ .unwrap()
+ .unwrap()
+ .pinned
+ );
+ let contact = harness
+ .store
+ .get_contact(&parse_jid("[email protected]").unwrap())
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(
+ (contact.first_name.as_str(), contact.full_name.as_str()),
+ ("Contact", "Contact Full")
+ );
+ assert_eq!(harness.client.store.read().await.push_name, "New Name");
+ assert_eq!(
+ harness
+ .store
+ .get_app_state_version("regular_high")
+ .await
+ .unwrap()
+ .0,
+ 1
+ );
+
+ // The next notification fetches from the stored version.
+ connection
+ .send_node(&server_sync("regular_high", "2"))
+ .await;
+ let request = next_request(&mut connection).await;
+ let expected = vectors.node("fetch_version_iq");
+ assert_eq!(with_vector_id(request.clone(), &expected), expected);
+ connection
+ .respond_iq(
+ &request,
+ patches_response(
+ "regular_high",
+ "2",
+ &[vectors.bytes("regular_high_v2_patch")],
+ ),
+ )
+ .await;
+ let expected_events = vectors.value("regular_high_v2_events").as_array().unwrap();
+ let events = next_events(&mut harness.events, expected_events.len()).await;
+ assert_eq!(&events, expected_events);
+ let chat_settings = harness
+ .store
+ .get_chat_settings(&chat)
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(chat_settings.muted_until, None);
+ assert!(!chat_settings.pinned);
+ assert_eq!(
+ harness
+ .store
+ .get_app_state_version("regular_high")
+ .await
+ .unwrap()
+ .0,
+ 2
+ );
+}
+
+#[tokio::test(start_paused = true)]
+async fn full_sync_of_contacts_without_events_stores_them_in_bulk() {
+ let vectors = Vectors::load("appstate_client.json");
+ let mut harness = harness(Some(OWN_JID));
+ put_key(&harness.store, &vectors, 1).await;
+ let mut connection = connect_paired(&mut harness).await;
+
+ connection
+ .send_node(&server_sync("critical_unblock_low", "1"))
+ .await;
+ let request = next_request(&mut connection).await;
+ assert!(is_iq(&request, "w:sync:app:state"));
+ connection
+ .respond_iq(
+ &request,
+ patches_response(
+ "critical_unblock_low",
+ "1",
+ &[vectors.bytes("critical_unblock_low_v1_patch")],
+ ),
+ )
+ .await;
+ // Only the completion is dispatched on a full sync by default.
+ let Event::AppStateSyncComplete(complete) = next_event(&mut harness.events).await else {
+ panic!("expected AppStateSyncComplete");
+ };
+ assert_eq!(complete.version, 1);
+ let contact = harness
+ .store
+ .get_contact(&parse_jid("[email protected]").unwrap())
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(
+ (contact.first_name.as_str(), contact.full_name.as_str()),
+ ("Contact", "Contact Full")
+ );
+ // The other mutations still update the store.
+ let chat = parse_jid("[email protected]").unwrap();
+ assert!(
+ harness
+ .store
+ .get_chat_settings(&chat)
+ .await
+ .unwrap()
+ .unwrap()
+ .pinned
+ );
+}
+
+#[tokio::test(start_paused = true)]
+async fn failed_full_sync_fetch_dispatches_sync_error() {
+ let mut harness = harness(Some(OWN_JID));
+ let mut connection = connect_paired(&mut harness).await;
+
+ connection.send_node(&server_sync("regular", "1")).await;
+ let request = next_request(&mut connection).await;
+ connection
+ .respond_iq_error(&request, 500, "internal-server-error")
+ .await;
+ let Event::AppStateSyncError(error) = next_event(&mut harness.events).await else {
+ panic!("expected AppStateSyncError");
+ };
+ assert_eq!(error.name.as_str(), "regular");
+ assert!(error.full_sync);
+ assert_eq!(
+ error.error.to_string(),
+ "info query returned status 500: internal-server-error"
+ );
+}
+
+#[tokio::test(start_paused = true)]
+async fn missing_key_is_requested_and_key_share_resyncs() {
+ let vectors = Vectors::load("appstate_client.json");
+ let mut harness = harness(Some(OWN_JID));
+ let mut connection = connect_paired(&mut harness).await;
+ let client = Arc::clone(&harness.client);
+
+ let patch = vectors.bytes("regular_low_v1_patch_key_2");
+ let regular_low = WA_PATCH_REGULAR_LOW;
+ let fetch = client.fetch_app_state(&regular_low, false, false);
+ let respond = async {
+ let request = next_request(&mut connection).await;
+ connection
+ .respond_iq(
+ &request,
+ patches_response("regular_low", "1", std::slice::from_ref(&patch)),
+ )
+ .await;
+ };
+ let (result, ()) = tokio::join!(fetch, respond);
+ let error = result.unwrap_err();
+ let ClientError::Wrapped { source, .. } = &error else {
+ panic!("expected a wrapped decode error, got {error}");
+ };
+ let ClientError::AppStateDecode(decode) = source.as_ref() else {
+ panic!("expected a decode error, got {source}");
+ };
+ assert_eq!(decode.sentinel(), Some(AppStateError::KeyNotFound));
+
+ // The background request and this one race; either records the request.
+ let list = PatchList {
+ name: WA_PATCH_REGULAR_LOW,
+ has_more_patches: false,
+ patches: vec![SyncdPatch::decode(patch.as_slice()).unwrap()],
+ snapshot: None,
+ };
+ client.request_missing_app_state_keys(&list).await;
+ let requested = lock(&client.app_state_key_requests)
+ .get("00000002")
+ .copied();
+ assert!(requested.is_some());
+ // Within a day, the key isn't requested again.
+ client.request_missing_app_state_keys(&list).await;
+ assert_eq!(
+ lock(&client.app_state_key_requests)
+ .get("00000002")
+ .copied(),
+ requested
+ );
+
+ // The phone shares the key: every collection is fetched again.
+ let share = AppStateSyncKeyShare {
+ keys: vec![SharedKey {
+ key_id: Some(AppStateSyncKeyId {
+ key_id: Some(vectors.bytes("key_2_id")),
+ }),
+ key_data: Some(AppStateSyncKeyData {
+ key_data: Some(vectors.bytes("key_2_data")),
+ fingerprint: None,
+ timestamp: Some(1_700_000_000),
+ }),
+ }],
+ };
+ let respond = async {
+ let mut names = Vec::new();
+ for _ in 0..ALL_PATCH_NAMES.len() {
+ let request = next_request(&mut connection).await;
+ let name = attr_string(request.get_child_by_tag(&["sync", "collection"]), "name");
+ let patches = if name == "regular_low" {
+ vec![patch.clone()]
+ } else {
+ Vec::new()
+ };
+ connection
+ .respond_iq(&request, patches_response(&name, "1", &patches))
+ .await;
+ names.push(name);
+ }
+ names
+ };
+ let ((), names) = tokio::join!(client.handle_app_state_sync_key_share(&share), respond);
+ assert_eq!(
+ names,
+ [
+ "critical_block",
+ "critical_unblock_low",
+ "regular_high",
+ "regular",
+ "regular_low"
+ ]
+ );
+ let stored = harness
+ .store
+ .get_app_state_sync_key(&vectors.bytes("key_2_id"))
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(stored.data, vectors.bytes("key_2_data"));
+ assert_eq!(stored.timestamp, 1_700_000_000);
+ let chat = parse_jid("[email protected]").unwrap();
+ assert!(
+ harness
+ .store
+ .get_chat_settings(&chat)
+ .await
+ .unwrap()
+ .unwrap()
+ .archived
+ );
+}
+
+#[test]
+fn key_request_message_lists_the_key_ids() {
+ let message = build_app_state_key_request(&[vec![0, 0, 0, 2], vec![0, 0, 0, 3]]);
+ let protocol = message.protocol_message.unwrap();
+ assert_eq!(
+ protocol.r#type,
+ Some(protocol_message::Type::AppStateSyncKeyRequest as i32)
+ );
+ assert_eq!(
+ protocol.app_state_sync_key_request.unwrap().key_i_ds,
+ [
+ AppStateSyncKeyId {
+ key_id: Some(vec![0, 0, 0, 2])
+ },
+ AppStateSyncKeyId {
+ key_id: Some(vec![0, 0, 0, 3])
+ },
+ ]
+ );
+}
+
+#[tokio::test(start_paused = true)]
+async fn send_app_state_sends_a_valid_patch_and_resyncs() {
+ let vectors = Vectors::load("appstate_client.json");
+ let mut harness = harness(Some(OWN_JID));
+ put_key(&harness.store, &vectors, 1).await;
+ let mut connection = connect_paired(&mut harness).await;
+ let client = Arc::clone(&harness.client);
+ let chat = parse_jid("[email protected]").unwrap();
+
+ let server = async {
+ let request = next_request(&mut connection).await;
+ let patch = request.get_child_by_tag(&["sync", "collection", "patch"]);
+ let Some(NodeContent::Bytes(patch)) = patch.content.clone() else {
+ panic!("the request has no patch");
+ };
+ let mut without_patch = request.clone();
+ let Some(NodeContent::Nodes(sync)) = &mut without_patch.content else {
+ panic!("the request has no sync node");
+ };
+ let Some(NodeContent::Nodes(collection)) = &mut sync[0].content else {
+ panic!("the request has no collection node");
+ };
+ let Some(NodeContent::Nodes(patch_node)) = &mut collection[0].content else {
+ panic!("the request has no patch node");
+ };
+ patch_node[0].content = None;
+ let expected = vectors.node("send_app_state_iq_without_patch");
+ assert_eq!(with_vector_id(without_patch, &expected), expected);
+
+ // The server assigns version 1; a processor with the same key
+ // verifies and decodes it.
+ let mut patch = SyncdPatch::decode(patch.as_slice()).unwrap();
+ patch.version = Some(SyncdVersion { version: Some(1) });
+ let verifier_store = Arc::new(MemoryStore::default());
+ put_key(&verifier_store, &vectors, 1).await;
+ let verifier = Processor::new(&verifier_store.new_device(&crate::testing::FakeSignatures));
+ let list = PatchList {
+ name: WA_PATCH_REGULAR_LOW,
+ has_more_patches: false,
+ patches: vec![patch.clone()],
+ snapshot: None,
+ };
+ let (mutations, state) = verifier
+ .decode_patches(&list, HashState::default(), true)
+ .await
+ .unwrap();
+ assert_eq!(state.version, 1);
+ assert_eq!(mutations.len(), 1);
+ assert_eq!(mutations[0].index, ["pin_v1", "[email protected]"]);
+ assert_eq!(
+ mutations[0]
+ .action
+ .as_ref()
+ .and_then(|action| action.pin_action.as_ref())
+ .and_then(|action| action.pinned),
+ Some(true)
+ );
+ connection
+ .respond_iq(
+ &request,
+ vec![node(
+ "sync",
+ &[],
+ children(vec![node(
+ "collection",
+ &[("name", text("regular_low")), ("version", text("1"))],
+ None,
+ )]),
+ )],
+ )
+ .await;
+
+ // The client resyncs; the server returns the patch it stored.
+ let request = next_request(&mut connection).await;
+ assert_eq!(
+ request.get_child_by_tag(&["sync", "collection"]).attrs["return_snapshot"],
+ AttributeValue::String("true".to_owned())
+ );
+ connection
+ .respond_iq(
+ &request,
+ patches_response("regular_low", "1", &[patch.encode_to_vec()]),
+ )
+ .await;
+ };
+ let (result, ()) = tokio::join!(client.send_app_state(build_pin(&chat, true)), server);
+ result.unwrap();
+ let Event::AppStateSyncComplete(complete) = next_event(&mut harness.events).await else {
+ panic!("expected AppStateSyncComplete");
+ };
+ assert_eq!(complete.version, 1);
+ assert!(
+ harness
+ .store
+ .get_chat_settings(&chat)
+ .await
+ .unwrap()
+ .unwrap()
+ .pinned
+ );
+}
+
+#[tokio::test(start_paused = true)]
+async fn send_app_state_applies_a_conflict_and_retries() {
+ let vectors = Vectors::load("appstate_client.json");
+ let mut harness = harness(Some(OWN_JID));
+ put_key(&harness.store, &vectors, 1).await;
+ let mut connection = connect_paired(&mut harness).await;
+ let client = Arc::clone(&harness.client);
+ let chat = parse_jid("[email protected]").unwrap();
+ let group = parse_jid("[email protected]").unwrap();
+
+ // Another device pinned the group first: version 1 on the server.
+ let other_store = Arc::new(MemoryStore::default());
+ put_key(&other_store, &vectors, 1).await;
+ let other = Processor::new(&other_store.new_device(&crate::testing::FakeSignatures));
+ let mut conflict = SyncdPatch::decode(
+ other
+ .encode_patch(
+ &vectors.bytes("key_1_id"),
+ HashState::default(),
+ build_pin(&group, true),
+ )
+ .await
+ .unwrap()
+ .as_slice(),
+ )
+ .unwrap();
+ conflict.version = Some(SyncdVersion { version: Some(1) });
+
+ let collection_version =
+ |request: &Node| attr_string(request.get_child_by_tag(&["sync", "collection"]), "version");
+ let server = async {
+ let request = next_request(&mut connection).await;
+ assert_eq!(collection_version(&request), "0");
+ connection
+ .respond_iq(
+ &request,
+ vec![node(
+ "sync",
+ &[],
+ children(vec![node(
+ "collection",
+ &[
+ ("name", text("regular_low")),
+ ("type", text("error")),
+ ("version", text("1")),
+ ],
+ children(vec![
+ node(
+ "error",
+ &[("code", text("409")), ("text", text("conflict"))],
+ None,
+ ),
+ node(
+ "patches",
+ &[],
+ children(vec![node(
+ "patch",
+ &[],
+ bytes(&conflict.encode_to_vec()),
+ )]),
+ ),
+ ]),
+ )]),
+ )],
+ )
+ .await;
+
+ // The retry builds on the conflicting patch.
+ let request = next_request(&mut connection).await;
+ assert_eq!(collection_version(&request), "1");
+ let Some(NodeContent::Bytes(patch)) = request
+ .get_child_by_tag(&["sync", "collection", "patch"])
+ .content
+ .clone()
+ else {
+ panic!("the retry has no patch");
+ };
+ let mut patch = SyncdPatch::decode(patch.as_slice()).unwrap();
+ patch.version = Some(SyncdVersion { version: Some(2) });
+ connection
+ .respond_iq(
+ &request,
+ vec![node(
+ "sync",
+ &[],
+ children(vec![node(
+ "collection",
+ &[("name", text("regular_low")), ("version", text("2"))],
+ None,
+ )]),
+ )],
+ )
+ .await;
+
+ let request = next_request(&mut connection).await;
+ assert_eq!(collection_version(&request), "1");
+ connection
+ .respond_iq(
+ &request,
+ patches_response("regular_low", "2", &[patch.encode_to_vec()]),
+ )
+ .await;
+ };
+ let (result, ()) = tokio::join!(client.send_app_state(build_pin(&chat, true)), server);
+ result.unwrap();
+ assert!(
+ harness
+ .store
+ .get_chat_settings(&chat)
+ .await
+ .unwrap()
+ .unwrap()
+ .pinned
+ );
+ assert!(
+ harness
+ .store
+ .get_chat_settings(&group)
+ .await
+ .unwrap()
+ .unwrap()
+ .pinned
+ );
+ assert_eq!(
+ harness
+ .store
+ .get_app_state_version("regular_low")
+ .await
+ .unwrap()
+ .0,
+ 2
+ );
+}
+
+#[tokio::test(start_paused = true)]
+async fn mark_not_dirty_matches_whatsmeow() {
+ let vectors = Vectors::load("appstate_client.json");
+ let mut harness = harness(Some(OWN_JID));
+ let mut connection = connect_paired(&mut harness).await;
+ let client = Arc::clone(&harness.client);
+
+ let server = async {
+ let request = next_request(&mut connection).await;
+ let expected = vectors.node("mark_not_dirty_iq");
+ assert_eq!(with_vector_id(request.clone(), &expected), expected);
+ connection.respond_iq(&request, vec![]).await;
+ };
+ let timestamp = DateTime::from_timestamp(1_700_000_000, 0).unwrap();
+ let (result, ()) = tokio::join!(client.mark_not_dirty("groups", timestamp), server);
+ result.unwrap();
+}
+
+#[test]
+fn recovery_request_matches_whatsmeow() {
+ let vectors = Vectors::load("appstate_client.json");
+ let mut message = build_app_state_recovery_request(&WA_PATCH_REGULAR_HIGH);
+ message
+ .protocol_message
+ .as_mut()
+ .and_then(|protocol| protocol.peer_data_operation_request_message.as_mut())
+ .and_then(|request| request.syncd_collection_fatal_recovery_request.as_mut())
+ .unwrap()
+ .timestamp = Some(1_700_000_000);
+ assert_eq!(message.encode_to_vec(), vectors.bytes("recovery_request"));
+}
+
+#[test]
+fn filter_contacts_splits_contact_mutations() {
+ let contact = |index: &[&str]| Mutation {
+ key_id: Vec::new(),
+ operation: SyncdOperation::Set as i32,
+ action: Some(crate::proto::wa_sync_action::SyncActionValue {
+ contact_action: Some(crate::proto::wa_sync_action::ContactAction {
+ full_name: Some("Full".to_owned()),
+ first_name: Some("First".to_owned()),
+ ..Default::default()
+ }),
+ ..Default::default()
+ }),
+ version: 2,
+ index: index.iter().map(|part| (*part).to_owned()).collect(),
+ index_mac: Vec::new(),
+ value_mac: Vec::new(),
+ patch_version: 1,
+ };
+ let (rest, contacts) = filter_contacts(vec![
+ contact(&["contact", "[email protected]"]),
+ contact(&["contact"]),
+ contact(&["pin_v1", "[email protected]"]),
+ ]);
+ assert_eq!(
+ contacts,
+ [ContactEntry {
+ jid: parse_jid("[email protected]").unwrap(),
+ first_name: "First".to_owned(),
+ full_name: "Full".to_owned(),
+ }]
+ );
+ assert_eq!(rest.len(), 2);
+}
diff --git a/crates/whatsmeow/src/appstate/decode.rs b/crates/whatsmeow/src/appstate/decode.rs
new file mode 100644
index 0000000000..93c1a88873
--- /dev/null
+++ b/crates/whatsmeow/src/appstate/decode.rs
@@ -0,0 +1,707 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+//
+// Ported from whatsmeow appstate/decode.go (MPL-2.0, Copyright (c) Tulir Asokan)
+
+use std::collections::HashMap;
+
+use async_trait::async_trait;
+use constant_time_eq::constant_time_eq;
+use hmac::Hmac;
+use prost::Message;
+use sha2::Sha256;
+
+use super::errors::AppStateError;
+use super::hash::{
+ HashState, MissingPreviousSetValueWarning, Mutation, PreviousValueMacs, ShortValueError,
+ UpdateHashError, concat_and_hmac, generate_content_mac, generate_patch_mac, mutation_index,
+ mutation_value,
+};
+use super::keys::{ExpandedAppStateKeys, GetKeyError, Processor, WaPatchName};
+use crate::binary::{ErrorList, Node, NodeContent};
+use crate::proto::wa_server_sync::syncd_mutation::SyncdOperation;
+use crate::proto::wa_server_sync::{
+ ExternalBlobReference, SyncdMutation, SyncdMutations, SyncdPatch, SyncdSnapshot,
+};
+use crate::proto::wa_sync_action::SyncActionData;
+use crate::store::{AppStateMutationMac, StoreError};
+use crate::util::cbcutil::{self, CbcError};
+
+/// A decoded response to getting app state patches from the WhatsApp servers.
+#[derive(Clone, Debug, PartialEq)]
+pub struct PatchList {
+ /// The collection.
+ pub name: WaPatchName,
+ /// Whether the server has more patches after these.
+ pub has_more_patches: bool,
+ /// The patches.
+ pub patches: Vec<SyncdPatch>,
+ /// The snapshot, if the server sent one.
+ pub snapshot: Option<SyncdSnapshot>,
+}
+
+/// Downloads a blob of external app state patches (Go's
+/// `DownloadExternalFunc`).
+#[async_trait]
+pub trait DownloadExternal: Send + Sync {
+ /// Downloads and decrypts the referenced blob.
+ async fn download_external(
+ &self,
+ reference: &ExternalBlobReference,
+ ) -> Result<Vec<u8>, Box<dyn std::error::Error + Send + Sync>>;
+}
+
+/// Parsing a patch list failed.
+#[derive(Debug, thiserror::Error)]
+pub enum ParsePatchListError {
+ /// The snapshot reference isn't a valid protobuf.
+ #[error("failed to unmarshal snapshot: {0}")]
+ UnmarshalSnapshot(#[source] prost::DecodeError),
+ /// There is a snapshot but no downloader. Go calls the nil function and
+ /// panics.
+ #[error("no function to download the external snapshot")]
+ MissingDownloader,
+ /// Downloading the snapshot or external mutations failed.
+ #[error("failed to download external mutations: {0}")]
+ Download(#[source] Box<dyn std::error::Error + Send + Sync>),
+ /// The downloaded snapshot or mutation list isn't a valid protobuf.
+ #[error("failed to unmarshal mutation list: {0}")]
+ UnmarshalMutationList(#[source] prost::DecodeError),
+ /// A patch isn't a valid protobuf.
+ #[error("failed to unmarshal patch #{number}: {source}")]
+ UnmarshalPatch {
+ /// The position of the patch node, from 1.
+ number: usize,
+ /// The decode failure.
+ source: prost::DecodeError,
+ },
+ /// The downloaded mutation list is empty.
+ #[error("didn't get any mutations from download")]
+ EmptyDownload,
+ /// The collection's attributes are missing or invalid.
+ #[error(transparent)]
+ Attrs(#[from] ErrorList),
+}
+
+async fn parse_snapshot_internal(
+ collection: &Node,
+ download_external: Option<&dyn DownloadExternal>,
+) -> Result<Option<SyncdSnapshot>, ParsePatchListError> {
+ let snapshot_node = collection.get_child_by_tag(&["snapshot"]);
+ let Some(NodeContent::Bytes(raw_snapshot)) = &snapshot_node.content else {
+ return Ok(None);
+ };
+ if snapshot_node.tag != "snapshot" {
+ return Ok(None);
+ }
+ let snapshot = ExternalBlobReference::decode(raw_snapshot.as_slice())
+ .map_err(ParsePatchListError::UnmarshalSnapshot)?;
+ let download_external = download_external.ok_or(ParsePatchListError::MissingDownloader)?;
+ let raw_data = download_external
+ .download_external(&snapshot)
+ .await
+ .map_err(ParsePatchListError::Download)?;
+ let downloaded = SyncdSnapshot::decode(raw_data.as_slice())
+ .map_err(ParsePatchListError::UnmarshalMutationList)?;
+ Ok(Some(downloaded))
+}
+
+async fn parse_patch_list_internal(
+ collection: &Node,
+ download_external: Option<&dyn DownloadExternal>,
+) -> Result<Vec<SyncdPatch>, ParsePatchListError> {
+ let patches_node = collection.get_child_by_tag(&["patches"]);
+ let patch_nodes = patches_node.get_children();
+ let mut patches = Vec::with_capacity(patch_nodes.len());
+ for (i, patch_node) in patch_nodes.iter().enumerate() {
+ let Some(NodeContent::Bytes(raw_patch)) = &patch_node.content else {
+ continue;
+ };
+ if patch_node.tag != "patch" {
+ continue;
+ }
+ let mut patch = SyncdPatch::decode(raw_patch.as_slice()).map_err(|source| {
+ ParsePatchListError::UnmarshalPatch {
+ number: i + 1,
+ source,
+ }
+ })?;
+ if let (Some(external_mutations), Some(download_external)) =
+ (&patch.external_mutations, download_external)
+ {
+ let raw_data = download_external
+ .download_external(external_mutations)
+ .await
+ .map_err(ParsePatchListError::Download)?;
+ let downloaded = SyncdMutations::decode(raw_data.as_slice())
+ .map_err(ParsePatchListError::UnmarshalMutationList)?;
+ if downloaded.mutations.is_empty() {
+ return Err(ParsePatchListError::EmptyDownload);
+ }
+ patch.mutations = downloaded.mutations;
+ }
+ patches.push(patch);
+ }
+ Ok(patches)
+}
+
+/// Decodes an XML node containing app state patches, including downloading
+/// any external blobs.
+///
+/// Go also returns the list when only the attributes are invalid; this
+/// returns just the error.
+pub async fn parse_patch_list(
+ collection: &Node,
+ download_external: Option<&dyn DownloadExternal>,
+) -> Result<PatchList, ParsePatchListError> {
+ let mut ag = collection.attr_getter();
+ let snapshot = parse_snapshot_internal(collection, download_external).await?;
+ let patches = parse_patch_list_internal(collection, download_external).await?;
+ let list = PatchList {
+ name: WaPatchName::from(ag.string("name")),
+ has_more_patches: ag.optional_bool("has_more_patches"),
+ patches,
+ snapshot,
+ };
+ ag.error()?;
+ Ok(list)
+}
+
+/// Decoding app state failed.
+#[derive(Debug, thiserror::Error)]
+pub enum DecodeError {
+ /// The key of a mutation couldn't be loaded.
+ #[error("failed to get key {} to decode mutation: {source}", hex::encode_upper(.key_id))]
+ MutationKey {
+ /// The key ID.
+ key_id: Vec<u8>,
+ /// The failure.
+ source: GetKeyError,
+ },
+ /// A mutation value is too short for its IV and MAC. Go panics.
+ #[error("mutation #{number} value of {length} bytes is too short for its IV and MAC")]
+ ShortMutationValue {
+ /// The position of the mutation, from 1.
+ number: usize,
+ /// The value length.
+ length: usize,
+ },
+ /// A mutation's content or index MAC doesn't match.
+ #[error("failed to verify mutation #{number}: {sentinel}")]
+ VerifyMutation {
+ /// The position of the mutation, from 1.
+ number: usize,
+ /// [`AppStateError::MismatchingContentMac`] or
+ /// [`AppStateError::MismatchingIndexMac`].
+ sentinel: AppStateError,
+ },
+ /// A mutation couldn't be decrypted.
+ #[error("failed to decrypt mutation #{number}: {source}")]
+ DecryptMutation {
+ /// The position of the mutation, from 1.
+ number: usize,
+ /// The failure.
+ source: CbcError,
+ },
+ /// A decrypted mutation isn't a valid protobuf.
+ #[error("failed to unmarshal mutation #{number}: {source}")]
+ UnmarshalMutation {
+ /// The position of the mutation, from 1.
+ number: usize,
+ /// The failure.
+ source: prost::DecodeError,
+ },
+ /// A mutation's index isn't a JSON list of strings.
+ #[error("failed to unmarshal index of mutation #{number}: {source}")]
+ UnmarshalIndex {
+ /// The position of the mutation, from 1.
+ number: usize,
+ /// The failure.
+ source: serde_json::Error,
+ },
+ /// Storing the new version failed.
+ #[error("failed to update app state version in the database: {0}")]
+ PutVersion(#[source] StoreError),
+ /// Deleting the removed mutation MACs failed.
+ #[error("failed to remove deleted mutation MACs from the database: {0}")]
+ DeleteMacs(#[source] StoreError),
+ /// Storing the added mutation MACs failed.
+ #[error("failed to insert added mutation MACs to the database: {0}")]
+ PutMacs(#[source] StoreError),
+ /// The key of a snapshot or patch couldn't be loaded.
+ #[error("failed to get key {} to verify patch v{version} MACs: {source}", hex::encode_upper(.key_id))]
+ SnapshotKey {
+ /// The key ID.
+ key_id: Vec<u8>,
+ /// The version being verified.
+ version: u64,
+ /// The failure.
+ source: GetKeyError,
+ },
+ /// A snapshot or patch MAC doesn't match.
+ #[error("failed to verify patch v{version}: {sentinel}")]
+ VerifyPatch {
+ /// The version being verified.
+ version: u64,
+ /// [`AppStateError::MismatchingLtHash`] or
+ /// [`AppStateError::MismatchingPatchMac`].
+ sentinel: AppStateError,
+ },
+ /// Updating the LT hash failed.
+ #[error("failed to update state hash: {0}")]
+ UpdateHash(#[source] UpdateHashError),
+ /// A patch value is shorter than its MAC. Go panics.
+ #[error(transparent)]
+ ShortValue(#[from] ShortValueError),
+ /// The snapshot MAC couldn't be verified.
+ #[error("failed to verify snapshot: {0}")]
+ VerifySnapshot(#[source] Box<DecodeError>),
+ /// The snapshot's records couldn't be decoded.
+ #[error("failed to decode snapshot of v{version}: {source}")]
+ DecodeSnapshot {
+ /// The snapshot version.
+ version: u64,
+ /// The failure.
+ source: Box<DecodeError>,
+ },
+}
+
+impl DecodeError {
+ /// The wrapped [`AppStateError`], like Go's `errors.Is`. The client
+ /// requests missing keys on [`AppStateError::KeyNotFound`].
+ pub fn sentinel(&self) -> Option<AppStateError> {
+ match self {
+ DecodeError::MutationKey { source, .. } | DecodeError::SnapshotKey { source, .. } => {
+ source.sentinel()
+ }
+ DecodeError::VerifyMutation { sentinel, .. }
+ | DecodeError::VerifyPatch { sentinel, .. } => Some(*sentinel),
+ DecodeError::VerifySnapshot(source) | DecodeError::DecodeSnapshot { source, .. } => {
+ source.sentinel()
+ }
+ _ => None,
+ }
+ }
+}
+
+#[derive(Default)]
+struct PatchOutput {
+ removed_macs: Vec<Vec<u8>>,
+ added_macs: Vec<AppStateMutationMac>,
+ mutations: Vec<Mutation>,
+}
+
+impl PatchOutput {
+ fn remove_mac(&mut self, index_mac: &[u8]) {
+ self.removed_macs.push(index_mac.to_vec());
+ // If the mutation was previously added in this patch, remove it from added_macs
+ self.added_macs
+ .retain(|mac| !constant_time_eq(&mac.index_mac, index_mac));
+ }
+
+ fn add_mac(&mut self, index_mac: &[u8], value_mac: &[u8]) {
+ self.added_macs.push(AppStateMutationMac {
+ index_mac: index_mac.to_vec(),
+ value_mac: value_mac.to_vec(),
+ });
+ }
+}
+
+struct DecodedMutation {
+ index_mac: Vec<u8>,
+ value_mac: Vec<u8>,
+ index: Vec<String>,
+ sync_action: SyncActionData,
+}
+
+fn index_mac_to_array(index_mac: &[u8]) -> [u8; 32] {
+ <[u8; 32]>::try_from(index_mac).unwrap_or_default()
+}
+
+/// Parses a JSON index like Go's `json.Unmarshal` into a `[]string`: `null`
+/// is an empty list.
+pub(super) fn unmarshal_index(index: &[u8]) -> Result<Vec<String>, serde_json::Error> {
+ Ok(serde_json::from_slice::<Option<Vec<String>>>(index)?.unwrap_or_default())
+}
+
+impl Processor {
+ async fn decode_mutation(
+ &self,
+ mutation: &SyncdMutation,
+ i: usize,
+ validate_macs: bool,
+ ) -> Result<DecodedMutation, DecodeError> {
+ let key_id = mutation
+ .record
+ .as_ref()
+ .and_then(|record| record.key_id.as_ref())
+ .and_then(|key| key.id.as_deref())
+ .unwrap_or_default();
+ let keys: ExpandedAppStateKeys =
+ self.get_app_state_key(key_id)
+ .await
+ .map_err(|source| DecodeError::MutationKey {
+ key_id: key_id.to_vec(),
+ source,
+ })?;
+ let blob = mutation_value(mutation);
+ if blob.len() < 48 {
+ return Err(DecodeError::ShortMutationValue {
+ number: i + 1,
+ length: blob.len(),
+ });
+ }
+ let (content, value_mac) = blob.split_at(blob.len() - 32);
+ if validate_macs {
+ let expected_value_mac = generate_content_mac(
+ mutation.operation.unwrap_or_default(),
+ content,
+ key_id,
+ &keys.value_mac,
+ );
+ if !constant_time_eq(&expected_value_mac, value_mac) {
+ return Err(DecodeError::VerifyMutation {
+ number: i + 1,
+ sentinel: AppStateError::MismatchingContentMac,
+ });
+ }
+ }
+ let (iv, content) = content.split_at(16);
+ let plaintext =
+ cbcutil::decrypt(&keys.value_encryption, iv, content).map_err(|source| {
+ DecodeError::DecryptMutation {
+ number: i + 1,
+ source,
+ }
+ })?;
+ let sync_action = SyncActionData::decode(plaintext.as_slice()).map_err(|source| {
+ DecodeError::UnmarshalMutation {
+ number: i + 1,
+ source,
+ }
+ })?;
+ let index_mac = mutation_index(mutation);
+ let action_index = sync_action.index.as_deref().unwrap_or_default();
+ if validate_macs {
+ let expected_index_mac = concat_and_hmac::<Hmac<Sha256>>(&keys.index, &[action_index]);
+ if !constant_time_eq(&expected_index_mac, index_mac) {
+ return Err(DecodeError::VerifyMutation {
+ number: i + 1,
+ sentinel: AppStateError::MismatchingIndexMac,
+ });
+ }
+ }
+ let index =
+ unmarshal_index(action_index).map_err(|source| DecodeError::UnmarshalIndex {
+ number: i + 1,
+ source,
+ })?;
+ Ok(DecodedMutation {
+ index_mac: index_mac.to_vec(),
+ value_mac: value_mac.to_vec(),
+ index,
+ sync_action,
+ })
+ }
+
+ async fn decode_mutations(
+ &self,
+ mutations: &[SyncdMutation],
+ out: &mut PatchOutput,
+ validate_macs: bool,
+ patch_version: u64,
+ fake_indexes_to_remove: &HashMap<[u8; 32], Vec<u8>>,
+ ) -> Result<(), DecodeError> {
+ for (i, mutation) in mutations.iter().enumerate() {
+ let decoded = self.decode_mutation(mutation, i, validate_macs).await?;
+ let operation = mutation.operation.unwrap_or_default();
+ if operation == SyncdOperation::Remove as i32 {
+ out.remove_mac(&decoded.index_mac);
+ if let Some(alt_index_mac) =
+ fake_indexes_to_remove.get(&index_mac_to_array(&decoded.index_mac))
+ && decoded.index_mac.len() == 32
+ {
+ out.remove_mac(alt_index_mac);
+ }
+ } else if operation == SyncdOperation::Set as i32 {
+ out.add_mac(&decoded.index_mac, &decoded.value_mac);
+ }
+ out.mutations.push(Mutation {
+ key_id: mutation
+ .record
+ .as_ref()
+ .and_then(|record| record.key_id.as_ref())
+ .and_then(|key| key.id.clone())
+ .unwrap_or_default(),
+ operation,
+ action: decoded.sync_action.value,
+ version: decoded.sync_action.version.unwrap_or_default(),
+ index: decoded.index,
+ index_mac: decoded.index_mac,
+ value_mac: decoded.value_mac,
+
+ patch_version,
+ });
+ }
+ Ok(())
+ }
+
+ async fn store_macs(
+ &self,
+ name: &WaPatchName,
+ current_state: HashState,
+ out: &PatchOutput,
+ ) -> Result<(), DecodeError> {
+ self.app_state
+ .put_app_state_version(name.as_str(), current_state.version, current_state.hash)
+ .await
+ .map_err(DecodeError::PutVersion)?;
+ self.app_state
+ .delete_app_state_mutation_macs(name.as_str(), &out.removed_macs)
+ .await
+ .map_err(DecodeError::DeleteMacs)?;
+ self.app_state
+ .put_app_state_mutation_macs(name.as_str(), current_state.version, &out.added_macs)
+ .await
+ .map_err(DecodeError::PutMacs)?;
+ Ok(())
+ }
+
+ async fn validate_snapshot_mac(
+ &self,
+ name: &WaPatchName,
+ current_state: HashState,
+ key_id: &[u8],
+ expected_snapshot_mac: &[u8],
+ ) -> Result<ExpandedAppStateKeys, DecodeError> {
+ let keys =
+ self.get_app_state_key(key_id)
+ .await
+ .map_err(|source| DecodeError::SnapshotKey {
+ key_id: key_id.to_vec(),
+ version: current_state.version,
+ source,
+ })?;
+ let snapshot_mac = current_state.generate_snapshot_mac(name, &keys.snapshot_mac);
+ if !constant_time_eq(&snapshot_mac, expected_snapshot_mac) {
+ return Err(DecodeError::VerifyPatch {
+ version: current_state.version,
+ sentinel: AppStateError::MismatchingLtHash,
+ });
+ }
+ Ok(keys)
+ }
+
+ async fn decode_snapshot(
+ &self,
+ name: &WaPatchName,
+ ss: &SyncdSnapshot,
+ initial_state: HashState,
+ validate_macs: bool,
+ new_mutations_input: Vec<Mutation>,
+ ) -> Result<(Vec<Mutation>, HashState), DecodeError> {
+ let mut current_state = initial_state;
+ current_state.version = ss
+ .version
+ .as_ref()
+ .and_then(|version| version.version)
+ .unwrap_or_default();
+
+ let encrypted_mutations: Vec<SyncdMutation> = ss
+ .records
+ .iter()
+ .map(|record| SyncdMutation {
+ operation: Some(SyncdOperation::Set as i32),
+ record: Some(record.clone()),
+ })
+ .collect();
+
+ // Go passes a nil map.
+ let fake_indexes_to_remove = HashMap::new();
+ let (warn, result) = current_state
+ .update_hash(&encrypted_mutations, PreviousValueMacs::Empty)
+ .await;
+ result.map_err(DecodeError::UpdateHash)?;
+
+ if validate_macs
+ && let Err(error) = self
+ .validate_snapshot_mac(
+ name,
+ current_state,
+ ss.key_id
+ .as_ref()
+ .and_then(|key| key.id.as_deref())
+ .unwrap_or_default(),
+ ss.mac.as_deref().unwrap_or_default(),
+ )
+ .await
+ {
+ if !warn.is_empty() {
+ tracing::warn!(name = %name, warnings = ?warn, "Warnings while updating hash");
+ }
+ return Err(DecodeError::VerifySnapshot(Box::new(error)));
+ }
+
+ let mut out = PatchOutput {
+ mutations: new_mutations_input,
+ ..PatchOutput::default()
+ };
+ self.decode_mutations(
+ &encrypted_mutations,
+ &mut out,
+ validate_macs,
+ current_state.version,
+ &fake_indexes_to_remove,
+ )
+ .await
+ .map_err(|error| DecodeError::DecodeSnapshot {
+ version: current_state.version,
+ source: Box::new(error),
+ })?;
+ self.store_macs(name, current_state, &out).await?;
+ Ok((out.mutations, current_state))
+ }
+
+ async fn validate_patch(
+ &self,
+ patch_name: &WaPatchName,
+ patch: &SyncdPatch,
+ current_state: HashState,
+ validate_macs: bool,
+ ) -> (
+ Vec<MissingPreviousSetValueWarning>,
+ Result<HashState, DecodeError>,
+ ) {
+ let version = patch
+ .version
+ .as_ref()
+ .and_then(|version| version.version)
+ .unwrap_or_default();
+ let mut new_state = current_state;
+ new_state.version = version;
+ let (warn, result) = new_state
+ .update_hash(
+ &patch.mutations,
+ PreviousValueMacs::PatchThenStore {
+ app_state: self.app_state.as_ref(),
+ name: patch_name,
+ },
+ )
+ .await;
+ if let Err(error) = result {
+ return (warn, Err(DecodeError::UpdateHash(error)));
+ }
+
+ if validate_macs {
+ let keys = match self
+ .validate_snapshot_mac(
+ patch_name,
+ new_state,
+ patch
+ .key_id
+ .as_ref()
+ .and_then(|key| key.id.as_deref())
+ .unwrap_or_default(),
+ patch.snapshot_mac.as_deref().unwrap_or_default(),
+ )
+ .await
+ {
+ Ok(keys) => keys,
+ Err(error) => return (warn, Err(error)),
+ };
+ let patch_mac = match generate_patch_mac(patch, patch_name, &keys.patch_mac, version) {
+ Ok(patch_mac) => patch_mac,
+ Err(error) => return (warn, Err(error.into())),
+ };
+ if !constant_time_eq(&patch_mac, patch.patch_mac.as_deref().unwrap_or_default()) {
+ return (
+ warn,
+ Err(DecodeError::VerifyPatch {
+ version,
+ sentinel: AppStateError::MismatchingPatchMac,
+ }),
+ );
+ }
+ }
+ (warn, Ok(new_state))
+ }
+
+ /// Decodes all the patches in a patch list into a list of app state
+ /// mutations, verifying them against `initial_state` when `validate_macs`
+ /// is set, and stores the new version, LT hash and mutation MACs after the
+ /// snapshot and after each patch.
+ ///
+ /// Go also returns the mutations and state decoded before a failure; this
+ /// returns just the error. Use [`DecodeError::sentinel`] for Go's
+ /// `errors.Is`.
+ pub async fn decode_patches(
+ &self,
+ list: &PatchList,
+ initial_state: HashState,
+ validate_macs: bool,
+ ) -> Result<(Vec<Mutation>, HashState), DecodeError> {
+ let mut current_state = initial_state;
+ let mut expected_length = list
+ .snapshot
+ .as_ref()
+ .map_or(0, |snapshot| snapshot.records.len());
+ for patch in &list.patches {
+ expected_length += patch.mutations.len();
+ }
+ let mut new_mutations = Vec::with_capacity(expected_length);
+
+ if let Some(snapshot) = &list.snapshot {
+ (new_mutations, current_state) = self
+ .decode_snapshot(
+ &list.name,
+ snapshot,
+ current_state,
+ validate_macs,
+ new_mutations,
+ )
+ .await?;
+ }
+
+ for patch in &list.patches {
+ // Go passes a nil map.
+ let fake_indexes_to_remove = HashMap::new();
+ let (warn, result) = self
+ .validate_patch(&list.name, patch, current_state, validate_macs)
+ .await;
+ let new_state = match result {
+ Ok(new_state) => new_state,
+ Err(error) => {
+ if !warn.is_empty() {
+ tracing::warn!(
+ name = %list.name,
+ warnings = ?warn,
+ "Warnings while updating hash"
+ );
+ }
+ return Err(error);
+ }
+ };
+
+ let mut out = PatchOutput {
+ mutations: new_mutations,
+ ..PatchOutput::default()
+ };
+ self.decode_mutations(
+ &patch.mutations,
+ &mut out,
+ validate_macs,
+ new_state.version,
+ &fake_indexes_to_remove,
+ )
+ .await?;
+ self.store_macs(&list.name, new_state, &out).await?;
+ new_mutations = out.mutations;
+ current_state = new_state;
+ }
+ Ok((new_mutations, current_state))
+ }
+}
+
+#[cfg(test)]
+mod test;
diff --git a/crates/whatsmeow/src/appstate/decode/test.rs b/crates/whatsmeow/src/appstate/decode/test.rs
new file mode 100644
index 0000000000..1799302678
--- /dev/null
+++ b/crates/whatsmeow/src/appstate/decode/test.rs
@@ -0,0 +1,324 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+//! Expected values were produced by whatsmeow's Go code at the pinned revision:
+//! the generator builds a snapshot and patches with fixed IVs (one patch comes
+//! from Go's `EncodePatch` with random IVs), and decodes them with Go's
+//! `DecodePatches`.
+
+use std::collections::BTreeMap;
+use std::sync::Mutex;
+
+use super::*;
+use crate::appstate::vectors;
+use crate::binary::AttributeValue;
+use crate::proto::wa_server_sync::SyncdVersion;
+use crate::store::AppStateStore;
+
+#[tokio::test]
+async fn decode_patches_matches_go_for_a_snapshot_and_patches_then_more_patches() {
+ let vectors = vectors::load();
+ let sequence = vectors.sequence;
+ let (store, processor) = vectors::processor_with_keys(&sequence.keys).await;
+ assert_eq!(sequence.steps.len(), 2);
+
+ for step in &sequence.steps {
+ let list = step.list.to_patch_list(&sequence.name);
+ let (mutations, state) = processor
+ .decode_patches(&list, step.initial_state.0, true)
+ .await
+ .unwrap();
+ assert_eq!(
+ mutations,
+ step.mutations
+ .iter()
+ .map(vectors::MutationVector::to_mutation)
+ .collect::<Vec<_>>()
+ );
+ assert_eq!(state, step.state.0);
+ let (stored_version, stored_hash) =
+ store.get_app_state_version(&sequence.name).await.unwrap();
+ assert_eq!(stored_version, step.stored_state.0.version);
+ assert_eq!(stored_hash, step.stored_state.0.hash);
+ vectors::assert_lookups(&store, &sequence.name, &step.lookups).await;
+ }
+
+ // The first list: a 4-record snapshot, then a patch with SETs and
+ // REMOVEs (one without a previous SET), then Go's EncodePatch output.
+ let first = &sequence.steps[0];
+ assert_eq!(first.mutations.len(), 11);
+ assert_eq!(
+ first
+ .mutations
+ .iter()
+ .map(|mutation| mutation.operation)
+ .collect::<Vec<_>>(),
+ vec![0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0]
+ );
+ assert_eq!(
+ first.mutations[3].index,
+ vec!["clearChat", "[email protected]", "<&>", "1"]
+ );
+}
+
+#[tokio::test]
+async fn decode_patches_without_mac_validation_skips_the_checks() {
+ let vectors = vectors::load();
+ let sequence = vectors.sequence;
+ let (_, processor) = vectors::processor_with_keys(&sequence.keys).await;
+ let step = &sequence.steps[0];
+ let mut list = step.list.to_patch_list(&sequence.name);
+ list.patches[0].patch_mac = Some(vec![0; 32]);
+ list.snapshot.as_mut().unwrap().mac = Some(vec![0; 32]);
+
+ let (mutations, state) = processor
+ .decode_patches(&list, HashState::default(), false)
+ .await
+ .unwrap();
+ assert_eq!(mutations.len(), step.mutations.len());
+ assert_eq!(state, step.state.0);
+}
+
+#[tokio::test]
+async fn decode_patches_fails_like_go() {
+ let vectors = vectors::load();
+ let sequence = vectors.sequence;
+ let descriptions: Vec<&str> = vectors
+ .decode_errors
+ .iter()
+ .map(|vector| vector.description.as_str())
+ .collect();
+ assert_eq!(
+ descriptions,
+ vec![
+ "snapshot MAC mismatch",
+ "content MAC mismatch",
+ "index MAC mismatch",
+ "patch MAC mismatch",
+ "patch LT hash mismatch",
+ "missing snapshot key",
+ "missing record key"
+ ]
+ );
+ for vector in &vectors.decode_errors {
+ let (_, processor) = vectors::processor_with_keys(&sequence.keys).await;
+ let list = vector.list.to_patch_list(&sequence.name);
+ let error = processor
+ .decode_patches(&list, vector.initial_state.0, true)
+ .await
+ .unwrap_err();
+ assert_eq!(error.to_string(), vector.error, "{}", vector.description);
+ assert_eq!(
+ error.sentinel() == Some(AppStateError::KeyNotFound),
+ vector.key_not_found,
+ "{}",
+ vector.description
+ );
+ assert_eq!(
+ processor.get_missing_key_ids(&list).await,
+ vector
+ .missing_keys
+ .iter()
+ .map(|key| key.0.clone())
+ .collect::<Vec<_>>(),
+ "{}",
+ vector.description
+ );
+ }
+}
+
+#[tokio::test]
+async fn decode_patches_rejects_values_go_panics_on() {
+ let vectors = vectors::load();
+ let sequence = vectors.sequence;
+ let (_, processor) = vectors::processor_with_keys(&sequence.keys).await;
+ let mut list = sequence.steps[0].list.to_patch_list(&sequence.name);
+ let record = &mut list.snapshot.as_mut().unwrap().records[0];
+ record.value.as_mut().unwrap().blob = Some(vec![0; 40]);
+ let error = processor
+ .decode_patches(&list, HashState::default(), false)
+ .await
+ .unwrap_err();
+ assert_eq!(
+ error.to_string(),
+ "failed to decode snapshot of v3: mutation #1 value of 40 bytes is too short for its IV and MAC"
+ );
+}
+
+struct FakeDownloader {
+ blobs: BTreeMap<String, Vec<u8>>,
+ requested: Mutex<Vec<String>>,
+}
+
+#[async_trait]
+impl DownloadExternal for FakeDownloader {
+ async fn download_external(
+ &self,
+ reference: &ExternalBlobReference,
+ ) -> Result<Vec<u8>, Box<dyn std::error::Error + Send + Sync>> {
+ let path = reference.direct_path.clone().unwrap_or_default();
+ self.requested.lock().unwrap().push(path.clone());
+ self.blobs
+ .get(&path)
+ .cloned()
+ .ok_or_else(|| format!("no blob at {path}").into())
+ }
+}
+
+fn reference(path: &str) -> Vec<u8> {
+ ExternalBlobReference {
+ direct_path: Some(path.to_owned()),
+ ..ExternalBlobReference::default()
+ }
+ .encode_to_vec()
+}
+
+#[tokio::test]
+async fn parse_patch_list_downloads_the_snapshot_and_external_mutations() {
+ let vectors = vectors::load();
+ let step = &vectors.sequence.steps[0];
+ let snapshot = step.list.snapshot.as_ref().unwrap().0.clone();
+ let patch = SyncdPatch::decode(step.list.patches[0].0.as_slice()).unwrap();
+ let external_patch = SyncdPatch {
+ version: Some(SyncdVersion { version: Some(9) }),
+ external_mutations: Some(ExternalBlobReference {
+ direct_path: Some("/mutations".to_owned()),
+ ..ExternalBlobReference::default()
+ }),
+ ..SyncdPatch::default()
+ };
+ let downloader = FakeDownloader {
+ blobs: BTreeMap::from([
+ ("/snapshot".to_owned(), snapshot.clone()),
+ (
+ "/mutations".to_owned(),
+ SyncdMutations {
+ mutations: patch.mutations.clone(),
+ }
+ .encode_to_vec(),
+ ),
+ ]),
+ requested: Mutex::new(Vec::new()),
+ };
+ let collection = Node {
+ tag: "collection".to_owned(),
+ attrs: [
+ ("name".to_owned(), AttributeValue::from("regular_high")),
+ ("has_more_patches".to_owned(), AttributeValue::from("true")),
+ ]
+ .into(),
+ content: Some(NodeContent::Nodes(vec![
+ Node {
+ tag: "snapshot".to_owned(),
+ content: Some(NodeContent::Bytes(reference("/snapshot"))),
+ ..Node::default()
+ },
+ Node {
+ tag: "patches".to_owned(),
+ content: Some(NodeContent::Nodes(vec![
+ Node {
+ tag: "patch".to_owned(),
+ content: Some(NodeContent::Bytes(patch.encode_to_vec())),
+ ..Node::default()
+ },
+ Node {
+ tag: "other".to_owned(),
+ content: Some(NodeContent::Bytes(vec![1, 2, 3])),
+ ..Node::default()
+ },
+ Node {
+ tag: "patch".to_owned(),
+ content: Some(NodeContent::Bytes(external_patch.encode_to_vec())),
+ ..Node::default()
+ },
+ ])),
+ ..Node::default()
+ },
+ ])),
+ };
+
+ let list = parse_patch_list(&collection, Some(&downloader))
+ .await
+ .unwrap();
+ assert_eq!(list.name.as_str(), "regular_high");
+ assert!(list.has_more_patches);
+ assert_eq!(
+ list.snapshot,
+ Some(SyncdSnapshot::decode(snapshot.as_slice()).unwrap())
+ );
+ assert_eq!(list.patches.len(), 2);
+ assert_eq!(list.patches[0], patch);
+ assert_eq!(list.patches[1].mutations, patch.mutations);
+ assert_eq!(
+ *downloader.requested.lock().unwrap(),
+ vec!["/snapshot", "/mutations"]
+ );
+
+ // Without a downloader, external mutations are left alone, and a
+ // snapshot (where Go would call a nil function) is an error.
+ let error = parse_patch_list(&collection, None).await.unwrap_err();
+ assert_eq!(
+ error.to_string(),
+ "no function to download the external snapshot"
+ );
+}
+
+#[tokio::test]
+async fn parse_patch_list_reports_bad_patches_and_attributes() {
+ let downloader = FakeDownloader {
+ blobs: BTreeMap::from([("/empty".to_owned(), Vec::new())]),
+ requested: Mutex::new(Vec::new()),
+ };
+ let collection_with = |patches: Vec<Node>, attrs: bool| Node {
+ tag: "collection".to_owned(),
+ attrs: if attrs {
+ [("name".to_owned(), AttributeValue::from("regular"))].into()
+ } else {
+ Default::default()
+ },
+ content: Some(NodeContent::Nodes(vec![Node {
+ tag: "patches".to_owned(),
+ content: Some(NodeContent::Nodes(patches)),
+ ..Node::default()
+ }])),
+ };
+ let patch_node = |content: Vec<u8>| Node {
+ tag: "patch".to_owned(),
+ content: Some(NodeContent::Bytes(content)),
+ ..Node::default()
+ };
+
+ let error = parse_patch_list(
+ &collection_with(vec![patch_node(Vec::new()), patch_node(vec![0xff])], true),
+ Some(&downloader),
+ )
+ .await
+ .unwrap_err();
+ assert!(
+ error
+ .to_string()
+ .starts_with("failed to unmarshal patch #2: "),
+ "{error}"
+ );
+
+ let empty_external = SyncdPatch {
+ external_mutations: Some(ExternalBlobReference {
+ direct_path: Some("/empty".to_owned()),
+ ..ExternalBlobReference::default()
+ }),
+ ..SyncdPatch::default()
+ };
+ let error = parse_patch_list(
+ &collection_with(vec![patch_node(empty_external.encode_to_vec())], true),
+ Some(&downloader),
+ )
+ .await
+ .unwrap_err();
+ assert_eq!(error.to_string(), "didn't get any mutations from download");
+
+ let error = parse_patch_list(&collection_with(Vec::new(), false), Some(&downloader))
+ .await
+ .unwrap_err();
+ assert!(matches!(error, ParsePatchListError::Attrs(_)), "{error}");
+}
diff --git a/crates/whatsmeow/src/appstate/encode.rs b/crates/whatsmeow/src/appstate/encode.rs
new file mode 100644
index 0000000000..a30214f924
--- /dev/null
+++ b/crates/whatsmeow/src/appstate/encode.rs
@@ -0,0 +1,585 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+//
+// Ported from whatsmeow appstate/encode.go (MPL-2.0, Copyright (c) Tulir Asokan)
+
+use chrono::{DateTime, TimeDelta, Utc};
+use hmac::Hmac;
+use prost::Message;
+use sha2::Sha256;
+
+use super::errors::AppStateError;
+use super::hash::{
+ HashState, PreviousValueMacs, ShortValueError, UpdateHashError, concat_and_hmac,
+ generate_content_mac, generate_patch_mac,
+};
+use super::keys::*;
+use crate::proto::wa_common::MessageKey;
+use crate::proto::wa_server_sync::syncd_mutation::SyncdOperation;
+use crate::proto::wa_server_sync::{
+ KeyId, SyncdIndex, SyncdMutation, SyncdPatch, SyncdRecord, SyncdValue,
+};
+use crate::proto::wa_sync_action::{
+ ArchiveChatAction, DeleteChatAction, LabelAssociationAction, LabelEditAction,
+ MarkChatAsReadAction, MuteAction, PinAction, PushNameSetting, StarAction, SyncActionData,
+ SyncActionMessage, SyncActionMessageRange, SyncActionValue,
+};
+use crate::types::Jid;
+use crate::util::cbcutil::{self, CbcError};
+
+/// Information about a single mutation to the app state.
+#[derive(Clone, Debug, PartialEq)]
+pub struct MutationInfo {
+ /// The thing being mutated (like `mute` or `pin_v1`), followed by
+ /// parameters like the target JID.
+ pub index: Vec<String>,
+ /// A static number that depends on the thing being mutated.
+ pub version: i32,
+ /// The data for the mutation. Go holds a pointer that may be nil (and
+ /// then panics in `EncodePatch`).
+ pub value: SyncActionValue,
+}
+
+/// Information about a patch to the app state. A patch can contain multiple
+/// mutations, as long as all mutations are in the same app state type.
+#[derive(Clone, Debug, PartialEq)]
+pub struct PatchInfo {
+ /// When the patch was created; [`Processor::encode_patch`] uses the
+ /// current time when `None` (Go's zero time).
+ pub timestamp: Option<DateTime<Utc>>,
+ /// The app state type being mutated (Go's `Type`).
+ pub patch_type: WaPatchName,
+ /// The individual mutations to apply to the app state in this patch.
+ pub mutations: Vec<MutationInfo>,
+}
+
+/// Builds an app state patch for muting or unmuting a chat.
+///
+/// If mute is true and the mute duration is zero (or negative), the chat is
+/// muted forever.
+pub fn build_mute(target: &Jid, mute: bool, mute_duration: TimeDelta) -> PatchInfo {
+ let mute_end_timestamp = (mute_duration > TimeDelta::zero())
+ .then(|| (Utc::now() + mute_duration).timestamp_millis());
+ build_mute_abs(target, mute, mute_end_timestamp)
+}
+
+/// Builds an app state patch for muting or unmuting a chat with an absolute
+/// timestamp in milliseconds.
+pub fn build_mute_abs(target: &Jid, mute: bool, mute_end_timestamp: Option<i64>) -> PatchInfo {
+ let mute_end_timestamp = match mute_end_timestamp {
+ None if mute => Some(-1),
+ other => other,
+ };
+ PatchInfo {
+ timestamp: None,
+ patch_type: WA_PATCH_REGULAR_HIGH,
+ mutations: vec![MutationInfo {
+ index: vec![INDEX_MUTE.to_owned(), target.to_string()],
+ version: 2,
+ value: SyncActionValue {
+ mute_action: Some(MuteAction {
+ muted: Some(mute),
+ mute_end_timestamp,
+ ..MuteAction::default()
+ }),
+ ..SyncActionValue::default()
+ },
+ }],
+ }
+}
+
+fn new_pin_mutation_info(target: &Jid, pin: bool) -> MutationInfo {
+ MutationInfo {
+ index: vec![INDEX_PIN.to_owned(), target.to_string()],
+ version: 5,
+ value: SyncActionValue {
+ pin_action: Some(PinAction { pinned: Some(pin) }),
+ ..SyncActionValue::default()
+ },
+ }
+}
+
+/// Builds an app state patch for pinning or unpinning a chat.
+pub fn build_pin(target: &Jid, pin: bool) -> PatchInfo {
+ PatchInfo {
+ timestamp: None,
+ patch_type: WA_PATCH_REGULAR_LOW,
+ mutations: vec![new_pin_mutation_info(target, pin)],
+ }
+}
+
+/// Builds an app state patch for archiving or unarchiving a chat.
+///
+/// The last message timestamp and last message key are optional (`None` for
+/// the timestamp means now, like Go's zero time).
+///
+/// Archiving a chat will also unpin it automatically.
+pub fn build_archive(
+ target: &Jid,
+ archive: bool,
+ last_message_timestamp: Option<DateTime<Utc>>,
+ last_message_key: Option<MessageKey>,
+) -> PatchInfo {
+ let archive_mutation_info = MutationInfo {
+ index: vec![INDEX_ARCHIVE.to_owned(), target.to_string()],
+ version: 3,
+ value: SyncActionValue {
+ archive_chat_action: Some(ArchiveChatAction {
+ archived: Some(archive),
+ message_range: Some(new_message_range(last_message_timestamp, last_message_key)),
+ // TODO set LastSystemMessageTimestamp?
+ }),
+ ..SyncActionValue::default()
+ },
+ };
+
+ let mut mutations = vec![archive_mutation_info];
+ if archive {
+ mutations.push(new_pin_mutation_info(target, false));
+ }
+
+ PatchInfo {
+ timestamp: None,
+ patch_type: WA_PATCH_REGULAR_LOW,
+ mutations,
+ }
+}
+
+/// Builds an app state patch for marking a chat as read or unread.
+pub fn build_mark_chat_as_read(
+ target: &Jid,
+ read: bool,
+ last_message_timestamp: Option<DateTime<Utc>>,
+ last_message_key: Option<MessageKey>,
+) -> PatchInfo {
+ let action = MarkChatAsReadAction {
+ read: Some(read),
+ message_range: Some(new_message_range(last_message_timestamp, last_message_key)),
+ };
+
+ PatchInfo {
+ timestamp: None,
+ patch_type: WA_PATCH_REGULAR_LOW,
+ mutations: vec![MutationInfo {
+ index: vec![INDEX_MARK_CHAT_AS_READ.to_owned(), target.to_string()],
+ version: 3,
+ value: SyncActionValue {
+ mark_chat_as_read_action: Some(action),
+ ..SyncActionValue::default()
+ },
+ }],
+ }
+}
+
+fn new_label_chat_mutation(target: &Jid, label_id: &str, labeled: bool) -> MutationInfo {
+ MutationInfo {
+ index: vec![
+ INDEX_LABEL_ASSOCIATION_CHAT.to_owned(),
+ label_id.to_owned(),
+ target.to_string(),
+ ],
+ version: 3,
+ value: SyncActionValue {
+ label_association_action: Some(LabelAssociationAction {
+ labeled: Some(labeled),
+ ..LabelAssociationAction::default()
+ }),
+ ..SyncActionValue::default()
+ },
+ }
+}
+
+/// Builds an app state patch for labeling or un(labeling) a chat.
+pub fn build_label_chat(target: &Jid, label_id: &str, labeled: bool) -> PatchInfo {
+ PatchInfo {
+ timestamp: None,
+ patch_type: WA_PATCH_REGULAR,
+ mutations: vec![new_label_chat_mutation(target, label_id, labeled)],
+ }
+}
+
+fn new_label_message_mutation(
+ target: &Jid,
+ label_id: &str,
+ message_id: &str,
+ labeled: bool,
+) -> MutationInfo {
+ MutationInfo {
+ index: vec![
+ INDEX_LABEL_ASSOCIATION_MESSAGE.to_owned(),
+ label_id.to_owned(),
+ target.to_string(),
+ message_id.to_owned(),
+ "0".to_owned(),
+ "0".to_owned(),
+ ],
+ version: 3,
+ value: SyncActionValue {
+ label_association_action: Some(LabelAssociationAction {
+ labeled: Some(labeled),
+ ..LabelAssociationAction::default()
+ }),
+ ..SyncActionValue::default()
+ },
+ }
+}
+
+/// Builds an app state patch for labeling or un(labeling) a message.
+pub fn build_label_message(
+ target: &Jid,
+ label_id: &str,
+ message_id: &str,
+ labeled: bool,
+) -> PatchInfo {
+ PatchInfo {
+ timestamp: None,
+ patch_type: WA_PATCH_REGULAR,
+ mutations: vec![new_label_message_mutation(
+ target, label_id, message_id, labeled,
+ )],
+ }
+}
+
+fn new_label_edit_mutation(
+ label_id: &str,
+ label_name: &str,
+ label_color: i32,
+ deleted: bool,
+) -> MutationInfo {
+ MutationInfo {
+ index: vec![INDEX_LABEL_EDIT.to_owned(), label_id.to_owned()],
+ version: 3,
+ value: SyncActionValue {
+ label_edit_action: Some(LabelEditAction {
+ name: Some(label_name.to_owned()),
+ color: Some(label_color),
+ deleted: Some(deleted),
+ ..LabelEditAction::default()
+ }),
+ ..SyncActionValue::default()
+ },
+ }
+}
+
+/// Builds an app state patch for editing a label.
+pub fn build_label_edit(
+ label_id: &str,
+ label_name: &str,
+ label_color: i32,
+ deleted: bool,
+) -> PatchInfo {
+ PatchInfo {
+ timestamp: None,
+ patch_type: WA_PATCH_REGULAR,
+ mutations: vec![new_label_edit_mutation(
+ label_id,
+ label_name,
+ label_color,
+ deleted,
+ )],
+ }
+}
+
+fn new_setting_push_name_mutation(push_name: &str) -> MutationInfo {
+ MutationInfo {
+ index: vec![INDEX_SETTING_PUSH_NAME.to_owned()],
+ version: 1,
+ value: SyncActionValue {
+ push_name_setting: Some(PushNameSetting {
+ name: Some(push_name.to_owned()),
+ }),
+ ..SyncActionValue::default()
+ },
+ }
+}
+
+/// Builds an app state patch for setting the push name.
+pub fn build_setting_push_name(push_name: &str) -> PatchInfo {
+ PatchInfo {
+ timestamp: None,
+ patch_type: WA_PATCH_CRITICAL_BLOCK,
+ mutations: vec![new_setting_push_name_mutation(push_name)],
+ }
+}
+
+fn new_star_mutation(
+ target_jid: String,
+ sender_jid: String,
+ message_id: &str,
+ from_me: &str,
+ starred: bool,
+) -> MutationInfo {
+ MutationInfo {
+ index: vec![
+ INDEX_STAR.to_owned(),
+ target_jid,
+ message_id.to_owned(),
+ from_me.to_owned(),
+ sender_jid,
+ ],
+ version: 2,
+ value: SyncActionValue {
+ star_action: Some(StarAction {
+ starred: Some(starred),
+ }),
+ ..SyncActionValue::default()
+ },
+ }
+}
+
+/// Builds an app state patch for starring or unstarring a message.
+pub fn build_star(
+ target: &Jid,
+ sender: &Jid,
+ message_id: &str,
+ from_me: bool,
+ starred: bool,
+) -> PatchInfo {
+ let is_from_me = if from_me { "1" } else { "0" };
+ let target_jid = target.to_string();
+ let sender_jid = if target.user == sender.user {
+ "0".to_owned()
+ } else {
+ sender.to_string()
+ };
+ PatchInfo {
+ timestamp: None,
+ patch_type: WA_PATCH_REGULAR_HIGH,
+ mutations: vec![new_star_mutation(
+ target_jid, sender_jid, message_id, is_from_me, starred,
+ )],
+ }
+}
+
+/// Encoding a patch failed.
+#[derive(Debug, thiserror::Error)]
+pub enum EncodeError {
+ /// The key couldn't be loaded.
+ #[error("failed to get app state key details with key ID {}: {source}", hex::encode(.key_id))]
+ Key {
+ /// The key ID.
+ key_id: Vec<u8>,
+ /// The failure.
+ source: GetKeyError,
+ },
+ /// A mutation couldn't be encrypted.
+ #[error("failed to encrypt mutation: {0}")]
+ Encrypt(#[source] CbcError),
+ /// Updating the LT hash failed.
+ #[error("failed to update state hash: {0}")]
+ UpdateHash(#[source] UpdateHashError),
+ /// A value is shorter than its MAC. Can't happen for encoded values; Go
+ /// would panic.
+ #[error(transparent)]
+ ShortValue(#[from] ShortValueError),
+}
+
+impl EncodeError {
+ /// The wrapped [`AppStateError`], like Go's `errors.Is`.
+ pub fn sentinel(&self) -> Option<AppStateError> {
+ match self {
+ EncodeError::Key { source, .. } => source.sentinel(),
+ _ => None,
+ }
+ }
+}
+
+/// Encodes an index like Go's `json.Marshal` of a `[]string`, which escapes
+/// `<`, `>`, `&`, U+2028 and U+2029. Go marshals a nil slice as `null`; an
+/// empty list here is `[]`.
+pub(super) fn marshal_index(index: &[String]) -> Vec<u8> {
+ const HEX: &[u8; 16] = b"0123456789abcdef";
+ let mut output = vec![b'['];
+ for (position, item) in index.iter().enumerate() {
+ if position > 0 {
+ output.push(b',');
+ }
+ output.push(b'"');
+ for character in item.chars() {
+ match character {
+ '\\' | '"' => output.extend_from_slice(&[b'\\', character as u8]),
+ '\u{8}' => output.extend_from_slice(b"\\b"),
+ '\u{c}' => output.extend_from_slice(b"\\f"),
+ '\n' => output.extend_from_slice(b"\\n"),
+ '\r' => output.extend_from_slice(b"\\r"),
+ '\t' => output.extend_from_slice(b"\\t"),
+ '\u{0}'..='\u{1f}' | '<' | '>' | '&' => {
+ let byte = character as u8;
+ output.extend_from_slice(&[
+ b'\\',
+ b'u',
+ b'0',
+ b'0',
+ HEX[usize::from(byte >> 4)],
+ HEX[usize::from(byte & 0xf)],
+ ]);
+ }
+ '\u{2028}' => output.extend_from_slice(b"\\u2028"),
+ '\u{2029}' => output.extend_from_slice(b"\\u2029"),
+ _ => {
+ let mut buffer = [0; 4];
+ output.extend_from_slice(character.encode_utf8(&mut buffer).as_bytes());
+ }
+ }
+ }
+ output.push(b'"');
+ }
+ output.push(b']');
+ output
+}
+
+impl Processor {
+ /// Encodes and encrypts a patch on top of `state` with the key `key_id`,
+ /// returning the serialized `SyncdPatch` to send. Each mutation gets a
+ /// random IV and the patch's timestamp (now when unset).
+ pub async fn encode_patch(
+ &self,
+ key_id: &[u8],
+ mut state: HashState,
+ mut patch_info: PatchInfo,
+ ) -> Result<Vec<u8>, EncodeError> {
+ let keys = self
+ .get_app_state_key(key_id)
+ .await
+ .map_err(|source| EncodeError::Key {
+ key_id: key_id.to_vec(),
+ source,
+ })?;
+
+ let timestamp = *patch_info.timestamp.get_or_insert_with(Utc::now);
+
+ let mut mutations = Vec::with_capacity(patch_info.mutations.len());
+ for mutation_info in patch_info.mutations {
+ let mut value = mutation_info.value;
+ value.timestamp = Some(timestamp.timestamp_millis());
+
+ let index_bytes = marshal_index(&mutation_info.index);
+
+ let pb_obj = SyncActionData {
+ index: Some(index_bytes.clone()),
+ value: Some(value),
+ padding: Some(Vec::new()),
+ version: Some(mutation_info.version),
+ };
+
+ let content = pb_obj.encode_to_vec();
+
+ let mut encrypted_content = cbcutil::encrypt(&keys.value_encryption, None, &content)
+ .map_err(EncodeError::Encrypt)?;
+
+ let value_mac = generate_content_mac(
+ SyncdOperation::Set as i32,
+ &encrypted_content,
+ key_id,
+ &keys.value_mac,
+ );
+ let index_mac = concat_and_hmac::<Hmac<Sha256>>(&keys.index, &[&index_bytes]);
+
+ encrypted_content.extend_from_slice(&value_mac);
+ mutations.push(SyncdMutation {
+ operation: Some(SyncdOperation::Set as i32),
+ record: Some(SyncdRecord {
+ index: Some(SyncdIndex {
+ blob: Some(index_mac),
+ }),
+ value: Some(SyncdValue {
+ blob: Some(encrypted_content),
+ }),
+ key_id: Some(KeyId {
+ id: Some(key_id.to_vec()),
+ }),
+ }),
+ });
+ }
+
+ let patch_type = &patch_info.patch_type;
+ let (warn, result) = state
+ .update_hash(
+ &mutations,
+ PreviousValueMacs::Store {
+ app_state: self.app_state.as_ref(),
+ name: patch_type,
+ },
+ )
+ .await;
+ if !warn.is_empty() {
+ tracing::warn!(
+ name = %patch_type,
+ warnings = ?warn,
+ "Warnings while updating hash (sending new app state)"
+ );
+ }
+ result.map_err(EncodeError::UpdateHash)?;
+
+ state.version += 1;
+
+ let mut syncd_patch = SyncdPatch {
+ snapshot_mac: Some(state.generate_snapshot_mac(patch_type, &keys.snapshot_mac)),
+ key_id: Some(KeyId {
+ id: Some(key_id.to_vec()),
+ }),
+ mutations,
+ ..SyncdPatch::default()
+ };
+ syncd_patch.patch_mac = Some(generate_patch_mac(
+ &syncd_patch,
+ patch_type,
+ &keys.patch_mac,
+ state.version,
+ )?);
+
+ Ok(syncd_patch.encode_to_vec())
+ }
+}
+
+/// Builds an app state patch for deleting a chat.
+pub fn build_delete_chat(
+ target: &Jid,
+ last_message_timestamp: Option<DateTime<Utc>>,
+ last_message_key: Option<MessageKey>,
+ delete_media: bool,
+) -> PatchInfo {
+ let action = DeleteChatAction {
+ message_range: Some(new_message_range(last_message_timestamp, last_message_key)),
+ };
+ let delete_media_int = if delete_media { "1" } else { "0" };
+
+ PatchInfo {
+ timestamp: None,
+ patch_type: WA_PATCH_REGULAR_HIGH,
+ mutations: vec![MutationInfo {
+ index: vec![
+ INDEX_DELETE_CHAT.to_owned(),
+ target.to_string(),
+ delete_media_int.to_owned(),
+ ],
+ version: 6,
+ value: SyncActionValue {
+ delete_chat_action: Some(action),
+ ..SyncActionValue::default()
+ },
+ }],
+ }
+}
+
+fn new_message_range(
+ last_message_timestamp: Option<DateTime<Utc>>,
+ last_message_key: Option<MessageKey>,
+) -> SyncActionMessageRange {
+ let last_message_timestamp = last_message_timestamp.unwrap_or_else(Utc::now);
+ let mut message_range = SyncActionMessageRange {
+ last_message_timestamp: Some(last_message_timestamp.timestamp()),
+ ..SyncActionMessageRange::default()
+ };
+ if let Some(last_message_key) = last_message_key {
+ message_range.messages = vec![SyncActionMessage {
+ key: Some(last_message_key),
+ timestamp: Some(last_message_timestamp.timestamp()),
+ }];
+ }
+ message_range
+}
+
+#[cfg(test)]
+mod test;
diff --git a/crates/whatsmeow/src/appstate/encode/test.rs b/crates/whatsmeow/src/appstate/encode/test.rs
new file mode 100644
index 0000000000..30902824cc
--- /dev/null
+++ b/crates/whatsmeow/src/appstate/encode/test.rs
@@ -0,0 +1,209 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+//! Expected values were produced by whatsmeow's Go code at the pinned revision.
+//! Go encodes with random IVs, so encoded patches are checked by decoding them
+//! with MAC validation on top of the state Go's patches left behind.
+
+use chrono::TimeZone;
+
+use super::*;
+use crate::appstate::decode::PatchList;
+use crate::appstate::hash::Mutation;
+use crate::appstate::vectors;
+use crate::proto::wa_server_sync::SyncdVersion;
+use crate::store::AppStateStore;
+use crate::types::{DEFAULT_USER_SERVER, GROUP_SERVER, new_jid};
+
+#[test]
+fn marshal_index_matches_go_json() {
+ let vectors = vectors::load();
+ assert_eq!(vectors.index_json.len(), 3);
+ for vector in vectors.index_json {
+ assert_eq!(
+ String::from_utf8(marshal_index(&vector.index)).unwrap(),
+ vector.json
+ );
+ }
+}
+
+#[test]
+fn builders_match_go() {
+ let vectors = vectors::load();
+ let chat_a = new_jid("111111111", DEFAULT_USER_SERVER);
+ let chat_b = new_jid("222222222", DEFAULT_USER_SERVER);
+ let chat_c = new_jid("333333333", DEFAULT_USER_SERVER);
+ let group = new_jid("120363000000000000", GROUP_SERVER);
+ let at = Utc.timestamp_opt(1_760_000_000, 0).unwrap();
+ let key = MessageKey {
+ remote_jid: Some(chat_a.to_string()),
+ from_me: Some(true),
+ id: Some("3EB0KEY".to_owned()),
+ participant: None,
+ };
+ let built = vec![
+ build_mute_abs(&chat_a, true, None),
+ build_mute_abs(&chat_a, true, Some(1_760_003_600_000)),
+ build_mute_abs(&chat_a, false, None),
+ build_pin(&chat_b, true),
+ build_archive(&chat_a, true, Some(at), Some(key.clone())),
+ build_archive(&chat_a, false, Some(at), None),
+ build_mark_chat_as_read(&chat_b, false, Some(at), Some(key.clone())),
+ build_label_chat(&chat_a, "7", true),
+ build_label_message(&chat_a, "7", "3EB0MSG", false),
+ build_label_edit("7", "Work", 3, false),
+ build_setting_push_name("Wolf"),
+ build_star(&chat_a, &chat_a, "3EB0MSG", true, true),
+ build_star(&group, &chat_b, "3EB0MSG", false, false),
+ build_delete_chat(&chat_c, Some(at), Some(key), true),
+ ];
+ assert_eq!(built.len(), vectors.builders.len());
+ for (patch_info, expected) in built.into_iter().zip(vectors.builders) {
+ assert_eq!(patch_info.timestamp, None);
+ assert_eq!(patch_info.patch_type.as_str(), expected.patch_type);
+ assert_eq!(
+ patch_info.mutations,
+ expected
+ .mutations
+ .iter()
+ .map(|mutation| MutationInfo {
+ index: mutation.index.clone(),
+ version: mutation.version,
+ value: SyncActionValue::decode(mutation.value.0.as_slice()).unwrap(),
+ })
+ .collect::<Vec<_>>()
+ );
+ }
+}
+
+#[test]
+fn build_mute_with_a_duration_ends_after_it() {
+ let chat = new_jid("111111111", DEFAULT_USER_SERVER);
+ let before = Utc::now().timestamp_millis();
+ let patch_info = build_mute(&chat, true, TimeDelta::hours(8));
+ let end = patch_info.mutations[0]
+ .value
+ .mute_action
+ .unwrap()
+ .mute_end_timestamp
+ .unwrap();
+ let after = Utc::now().timestamp_millis();
+ assert!(end >= before + 8 * 3_600_000 && end <= after + 8 * 3_600_000);
+ assert_eq!(
+ build_mute(&chat, true, TimeDelta::zero()).mutations[0]
+ .value
+ .mute_action
+ .unwrap()
+ .mute_end_timestamp,
+ Some(-1)
+ );
+}
+
+#[tokio::test]
+async fn encoded_patches_decode_with_valid_macs_on_top_of_gos_state() {
+ let vectors = vectors::load();
+ let sequence = vectors.sequence;
+ let (store, processor) = vectors::processor_with_keys(&sequence.keys).await;
+ for step in &sequence.steps {
+ processor
+ .decode_patches(
+ &step.list.to_patch_list(&sequence.name),
+ step.initial_state.0,
+ true,
+ )
+ .await
+ .unwrap();
+ }
+ let (version, hash) = store.get_app_state_version(&sequence.name).await.unwrap();
+ let state = HashState { version, hash };
+ assert_eq!(state, sequence.steps[1].state.0);
+
+ // Overwrites the mute of chat A that Go set in the snapshot and patch v4, and adds a star.
+ let chat_a = new_jid("111111111", DEFAULT_USER_SERVER);
+ let chat_d = new_jid("444444444", DEFAULT_USER_SERVER);
+ let mut patch_info = build_mute_abs(&chat_a, true, Some(1_770_000_000_000));
+ patch_info
+ .mutations
+ .extend(build_star(&chat_d, &chat_a, "3EB0NEW", false, true).mutations);
+ patch_info.timestamp = Some(Utc.timestamp_millis_opt(1_760_000_009_000).unwrap());
+ let key_id = &sequence.keys[0].id.0;
+
+ let encoded = processor
+ .encode_patch(key_id, state, patch_info.clone())
+ .await
+ .unwrap();
+
+ let mut patch = SyncdPatch::decode(encoded.as_slice()).unwrap();
+ assert_eq!(patch.version, None);
+ // The server assigns the next version.
+ patch.version = Some(SyncdVersion {
+ version: Some(version + 1),
+ });
+ let list = PatchList {
+ name: WA_PATCH_REGULAR_HIGH,
+ has_more_patches: false,
+ patches: vec![patch.clone()],
+ snapshot: None,
+ };
+ let (mutations, new_state) = processor.decode_patches(&list, state, true).await.unwrap();
+ assert_eq!(new_state.version, version + 1);
+ assert_ne!(new_state.hash, state.hash);
+ let expected: Vec<Mutation> = patch_info
+ .mutations
+ .iter()
+ .zip(&patch.mutations)
+ .map(|(info, encoded)| {
+ let mut value = info.value.clone();
+ value.timestamp = Some(1_760_000_009_000);
+ let record = encoded.record.clone().unwrap();
+ let blob = record.value.unwrap().blob.unwrap();
+ Mutation {
+ key_id: key_id.clone(),
+ operation: SyncdOperation::Set as i32,
+ action: Some(value),
+ version: info.version,
+ index: info.index.clone(),
+ index_mac: record.index.unwrap().blob.unwrap(),
+ value_mac: blob[blob.len() - 32..].to_vec(),
+ patch_version: version + 1,
+ }
+ })
+ .collect();
+ assert_eq!(mutations, expected);
+ // The overwritten mute's index MAC is the one Go stored for chat A.
+ assert_eq!(
+ mutations[0].index_mac,
+ sequence.steps[0].mutations[0].index_mac.0
+ );
+
+ // The same patch on a stale state fails the LT hash check.
+ let error = processor
+ .decode_patches(&list, sequence.steps[0].state.0, true)
+ .await
+ .unwrap_err();
+ assert_eq!(
+ error.sentinel(),
+ Some(AppStateError::MismatchingLtHash),
+ "{error}"
+ );
+}
+
+#[tokio::test]
+async fn encode_patch_reports_missing_keys() {
+ let vectors = vectors::load();
+ let (_, processor) = vectors::processor_with_keys(&vectors.sequence.keys).await;
+ let error = processor
+ .encode_patch(
+ b"missing",
+ HashState::default(),
+ build_setting_push_name("Wolf"),
+ )
+ .await
+ .unwrap_err();
+ assert_eq!(
+ error.to_string(),
+ "failed to get app state key details with key ID 6d697373696e67: didn't find app state key"
+ );
+ assert_eq!(error.sentinel(), Some(AppStateError::KeyNotFound));
+}
diff --git a/crates/whatsmeow/src/appstate/errors.rs b/crates/whatsmeow/src/appstate/errors.rs
new file mode 100644
index 0000000000..fb0f8f1c36
--- /dev/null
+++ b/crates/whatsmeow/src/appstate/errors.rs
@@ -0,0 +1,30 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+//
+// Ported from whatsmeow appstate/errors.go (MPL-2.0, Copyright (c) Tulir Asokan)
+
+/// Errors that this package can return: Go's `Err*` sentinels. The error
+/// types of the package's functions wrap them; their `sentinel` methods take
+/// the place of Go's `errors.Is`.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
+pub enum AppStateError {
+ /// `ErrMissingPreviousSetValueOperation`.
+ #[error("missing value MAC of previous SET operation")]
+ MissingPreviousSetValueOperation,
+ /// `ErrMismatchingLTHash`.
+ #[error("mismatching LTHash")]
+ MismatchingLtHash,
+ /// `ErrMismatchingPatchMAC`.
+ #[error("mismatching patch MAC")]
+ MismatchingPatchMac,
+ /// `ErrMismatchingContentMAC`.
+ #[error("mismatching content MAC")]
+ MismatchingContentMac,
+ /// `ErrMismatchingIndexMAC`.
+ #[error("mismatching index MAC")]
+ MismatchingIndexMac,
+ /// `ErrKeyNotFound`.
+ #[error("didn't find app state key")]
+ KeyNotFound,
+}
diff --git a/crates/whatsmeow/src/appstate/hash.rs b/crates/whatsmeow/src/appstate/hash.rs
new file mode 100644
index 0000000000..a0998e1ab8
--- /dev/null
+++ b/crates/whatsmeow/src/appstate/hash.rs
@@ -0,0 +1,295 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+//
+// Ported from whatsmeow appstate/hash.go (MPL-2.0, Copyright (c) Tulir Asokan)
+
+use constant_time_eq::constant_time_eq;
+use hmac::digest::KeyInit;
+use hmac::{Hmac, Mac};
+use sha2::{Sha256, Sha512};
+
+use super::errors::AppStateError;
+use super::keys::WaPatchName;
+use super::lthash;
+use crate::proto::wa_server_sync::SyncdMutation;
+use crate::proto::wa_server_sync::SyncdPatch;
+use crate::proto::wa_server_sync::syncd_mutation::SyncdOperation;
+use crate::proto::wa_sync_action::SyncActionValue;
+use crate::store::{AppStateStore, StoreError};
+
+/// One decoded app state mutation.
+#[derive(Clone, Debug, PartialEq)]
+pub struct Mutation {
+ /// The ID of the key the mutation was encrypted with.
+ pub key_id: Vec<u8>,
+ /// The raw `SyncdOperation` value, as prost stores enums; Go's enum type
+ /// can also hold values it doesn't name. Compare with
+ /// `SyncdOperation::Set as i32`.
+ pub operation: i32,
+ /// The decoded action; `None` when the mutation carried none.
+ pub action: Option<SyncActionValue>,
+ /// The action version.
+ pub version: i32,
+ /// The thing being mutated (like `mute`), followed by its parameters.
+ pub index: Vec<String>,
+ /// The MAC of the index.
+ pub index_mac: Vec<u8>,
+ /// The MAC of the value.
+ pub value_mac: Vec<u8>,
+
+ /// The version of the patch or snapshot the mutation came in.
+ pub patch_version: u64,
+}
+
+/// The version and LT hash of one app state collection.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct HashState {
+ /// The version.
+ pub version: u64,
+ /// The LT hash of the value MACs of every mutation that is set.
+ pub hash: [u8; 128],
+}
+
+impl Default for HashState {
+ fn default() -> Self {
+ HashState {
+ version: 0,
+ hash: [0; 128],
+ }
+ }
+}
+
+/// A mutation value blob is shorter than the 32-byte value MAC that ends it.
+/// Go slices without checking and panics.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
+#[error("mutation value of {0} bytes is shorter than its 32-byte MAC")]
+pub struct ShortValueError(pub usize);
+
+/// A REMOVE mutation without a previous SET of its index. Go collects these as
+/// warnings and ignores them.
+#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
+#[error("{} for {}", AppStateError::MissingPreviousSetValueOperation, hex::encode_upper(.index_mac))]
+pub struct MissingPreviousSetValueWarning {
+ /// The index MAC of the REMOVE mutation.
+ pub index_mac: Vec<u8>,
+}
+
+/// Updating an LT hash failed.
+#[derive(Debug, thiserror::Error)]
+pub enum UpdateHashError {
+ /// Looking up the previous value MAC of an index failed.
+ #[error("failed to get value MAC of previous SET operation: {0}")]
+ PreviousSetValueMac(#[source] StoreError),
+ /// A value blob is too short.
+ #[error(transparent)]
+ ShortValue(#[from] ShortValueError),
+}
+
+/// The value MAC at the end of a mutation value blob.
+pub(super) fn value_mac(value: &[u8]) -> Result<&[u8], ShortValueError> {
+ value
+ .len()
+ .checked_sub(32)
+ .map(|start| &value[start..])
+ .ok_or(ShortValueError(value.len()))
+}
+
+pub(super) fn mutation_value(mutation: &SyncdMutation) -> &[u8] {
+ mutation
+ .record
+ .as_ref()
+ .and_then(|record| record.value.as_ref())
+ .and_then(|value| value.blob.as_deref())
+ .unwrap_or_default()
+}
+
+pub(super) fn mutation_index(mutation: &SyncdMutation) -> &[u8] {
+ mutation
+ .record
+ .as_ref()
+ .and_then(|record| record.index.as_ref())
+ .and_then(|index| index.blob.as_deref())
+ .unwrap_or_default()
+}
+
+/// Where [`HashState::update_hash`] finds the value MAC an index had before a
+/// mutation. Go passes a closure; these are the three closures its callers
+/// pass (an enum, because async closures borrowing their captures don't give
+/// `Send` futures).
+pub(super) enum PreviousValueMacs<'a> {
+ /// Nothing was set before (Go's `decodeSnapshot`).
+ Empty,
+ /// The stored MACs of the collection (Go's `EncodePatch`).
+ Store {
+ /// The app state store.
+ app_state: &'a dyn AppStateStore,
+ /// The collection.
+ name: &'a WaPatchName,
+ },
+ /// The latest earlier mutation of the same index in the patch, else the
+ /// stored MACs of the collection (Go's `validatePatch`).
+ PatchThenStore {
+ /// The app state store.
+ app_state: &'a dyn AppStateStore,
+ /// The collection.
+ name: &'a WaPatchName,
+ },
+}
+
+impl PreviousValueMacs<'_> {
+ async fn get_prev_set_value_mac(
+ &self,
+ mutations: &[SyncdMutation],
+ index_mac: &[u8],
+ max_index: usize,
+ ) -> Result<Option<Vec<u8>>, StoreError> {
+ match self {
+ PreviousValueMacs::Empty => Ok(None),
+ PreviousValueMacs::Store { app_state, name } => {
+ app_state
+ .get_app_state_mutation_mac(name.as_str(), index_mac)
+ .await
+ }
+ PreviousValueMacs::PatchThenStore { app_state, name } => {
+ for previous in mutations[..max_index].iter().rev() {
+ if constant_time_eq(mutation_index(previous), index_mac) {
+ if previous.operation.unwrap_or_default() == SyncdOperation::Set as i32 {
+ // update_hash already checked the length of every
+ // SET value before max_index.
+ return Ok(value_mac(mutation_value(previous))
+ .ok()
+ .map(<[u8]>::to_vec));
+ }
+ // Found a REMOVE operation, no previous value
+ return Ok(None);
+ }
+ }
+ // Previous value not found in current patch, look in the database
+ app_state
+ .get_app_state_mutation_mac(name.as_str(), index_mac)
+ .await
+ }
+ }
+ }
+}
+
+impl HashState {
+ /// Adds the value MACs of the SET mutations to the hash and subtracts the
+ /// previous value MACs of every mutated index, which `previous_value_macs`
+ /// looks up.
+ ///
+ /// Returns the REMOVE mutations without a previous value as warnings, also
+ /// when it fails, as Go does.
+ pub(super) async fn update_hash(
+ &mut self,
+ mutations: &[SyncdMutation],
+ previous_value_macs: PreviousValueMacs<'_>,
+ ) -> (
+ Vec<MissingPreviousSetValueWarning>,
+ Result<(), UpdateHashError>,
+ ) {
+ let mut added: Vec<Vec<u8>> = Vec::new();
+ let mut removed: Vec<Vec<u8>> = Vec::new();
+ let mut warnings = Vec::new();
+
+ for (i, mutation) in mutations.iter().enumerate() {
+ let operation = mutation.operation.unwrap_or_default();
+ if operation == SyncdOperation::Set as i32 {
+ match value_mac(mutation_value(mutation)) {
+ Ok(value_mac) => added.push(value_mac.to_vec()),
+ Err(error) => return (warnings, Err(error.into())),
+ }
+ }
+ let index_mac = mutation_index(mutation);
+ match previous_value_macs
+ .get_prev_set_value_mac(mutations, index_mac, i)
+ .await
+ {
+ Err(error) => return (warnings, Err(UpdateHashError::PreviousSetValueMac(error))),
+ Ok(Some(removal)) => removed.push(removal),
+ Ok(None) if operation == SyncdOperation::Remove as i32 => {
+ // TODO figure out if there are certain cases that are safe to
+ // ignore and others that aren't. At least removing contact
+ // access from WhatsApp seems to create a REMOVE op for your
+ // own JID that points to a non-existent index and is safe to
+ // ignore here. Other keys might not be safe to ignore.
+ warnings.push(MissingPreviousSetValueWarning {
+ index_mac: index_mac.to_vec(),
+ });
+ }
+ Ok(None) => {}
+ }
+ }
+
+ lthash::WA_PATCH_INTEGRITY
+ .subtract_then_add_in_place(&mut self.hash, &removed, &added)
+ .expect("the 128-byte hash fits WA_PATCH_INTEGRITY's 128-byte items");
+ (warnings, Ok(()))
+ }
+
+ pub(super) fn generate_snapshot_mac(&self, name: &WaPatchName, key: &[u8]) -> Vec<u8> {
+ concat_and_hmac::<Hmac<Sha256>>(
+ key,
+ &[
+ &self.hash,
+ &uint64_to_bytes(self.version),
+ name.as_str().as_bytes(),
+ ],
+ )
+ }
+}
+
+fn uint64_to_bytes(value: u64) -> [u8; 8] {
+ value.to_be_bytes()
+}
+
+/// HMACs the concatenation of `data` with the HMAC type `Hmac` (Go passes the
+/// hash constructor).
+pub(super) fn concat_and_hmac<Hmac: Mac + KeyInit>(key: &[u8], data: &[&[u8]]) -> Vec<u8> {
+ let mut hmac = <Hmac as KeyInit>::new_from_slice(key).expect("HMAC accepts keys of any length");
+ for item in data {
+ hmac.update(item);
+ }
+ hmac.finalize().into_bytes().to_vec()
+}
+
+/// The MAC of a whole patch: its snapshot MAC, every value MAC, the version
+/// and the collection name. Fails on a value shorter than its MAC, where Go
+/// panics.
+pub(super) fn generate_patch_mac(
+ patch: &SyncdPatch,
+ name: &WaPatchName,
+ key: &[u8],
+ version: u64,
+) -> Result<Vec<u8>, ShortValueError> {
+ let version = uint64_to_bytes(version);
+ let mut data_to_hash: Vec<&[u8]> = Vec::with_capacity(patch.mutations.len() + 3);
+ data_to_hash.push(patch.snapshot_mac.as_deref().unwrap_or_default());
+ for mutation in &patch.mutations {
+ data_to_hash.push(value_mac(mutation_value(mutation))?);
+ }
+ data_to_hash.push(&version);
+ data_to_hash.push(name.as_str().as_bytes());
+ Ok(concat_and_hmac::<Hmac<Sha256>>(key, &data_to_hash))
+}
+
+/// The MAC of one encrypted mutation value. `operation` is the raw
+/// `SyncdOperation` value.
+pub(super) fn generate_content_mac(
+ operation: i32,
+ data: &[u8],
+ key_id: &[u8],
+ key: &[u8],
+) -> Vec<u8> {
+ // Go's byte(operation) + 1: truncate, then wrap.
+ let operation_bytes = [operation.to_le_bytes()[0].wrapping_add(1)];
+ let key_data_length = uint64_to_bytes(key_id.len() as u64 + 1);
+ let mut mac =
+ concat_and_hmac::<Hmac<Sha512>>(key, &[&operation_bytes, key_id, data, &key_data_length]);
+ mac.truncate(32);
+ mac
+}
+
+#[cfg(test)]
+mod test;
diff --git a/crates/whatsmeow/src/appstate/hash/test.rs b/crates/whatsmeow/src/appstate/hash/test.rs
new file mode 100644
index 0000000000..2558b29786
--- /dev/null
+++ b/crates/whatsmeow/src/appstate/hash/test.rs
@@ -0,0 +1,148 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+//! Expected values were produced by whatsmeow's Go code at the pinned revision.
+
+use prost::Message;
+
+use super::*;
+use crate::appstate::vectors;
+use crate::store::{NoopError, NoopStore};
+
+#[test]
+fn generate_snapshot_mac_matches_go() {
+ let vectors = vectors::load();
+ for vector in vectors.snapshot_mac {
+ let state = HashState {
+ version: vector.version,
+ hash: vector.hash.0.try_into().unwrap(),
+ };
+ let name = WaPatchName::from(vector.name);
+ assert_eq!(
+ hex::encode(state.generate_snapshot_mac(&name, &vector.key.0)),
+ hex::encode(&vector.mac.0)
+ );
+ }
+}
+
+#[test]
+fn generate_patch_mac_matches_go() {
+ let vectors = vectors::load();
+ assert_eq!(vectors.patch_mac.len(), 2);
+ for vector in vectors.patch_mac {
+ let patch = SyncdPatch::decode(vector.patch.0.as_slice()).unwrap();
+ let name = WaPatchName::from(vector.name);
+ assert_eq!(
+ hex::encode(generate_patch_mac(&patch, &name, &vector.key.0, vector.version).unwrap()),
+ hex::encode(&vector.mac.0)
+ );
+ }
+}
+
+#[test]
+fn generate_patch_mac_rejects_short_values() {
+ let patch = SyncdPatch {
+ mutations: vec![SyncdMutation {
+ operation: Some(SyncdOperation::Remove as i32),
+ record: Some(crate::proto::wa_server_sync::SyncdRecord {
+ value: Some(crate::proto::wa_server_sync::SyncdValue {
+ blob: Some(vec![1; 31]),
+ }),
+ ..Default::default()
+ }),
+ }],
+ ..SyncdPatch::default()
+ };
+ let name = WaPatchName::from("regular".to_owned());
+ assert_eq!(
+ generate_patch_mac(&patch, &name, &[0; 32], 1),
+ Err(ShortValueError(31))
+ );
+}
+
+#[test]
+fn generate_content_mac_matches_go_for_every_operation_byte() {
+ let vectors = vectors::load();
+ // SET, REMOVE, and 255, which Go's byte(operation)+1 wraps to 0.
+ assert_eq!(
+ vectors
+ .content_mac
+ .iter()
+ .map(|vector| vector.operation)
+ .collect::<Vec<_>>(),
+ vec![0, 1, 255]
+ );
+ for vector in vectors.content_mac {
+ assert_eq!(
+ hex::encode(generate_content_mac(
+ vector.operation,
+ &vector.data.0,
+ &vector.key_id.0,
+ &vector.key.0
+ )),
+ hex::encode(&vector.mac.0)
+ );
+ }
+}
+
+#[test]
+fn index_mac_matches_go() {
+ let vectors = vectors::load();
+ for vector in vectors.index_mac {
+ assert_eq!(
+ hex::encode(concat_and_hmac::<Hmac<Sha256>>(
+ &vector.key.0,
+ &[&vector.index.0]
+ )),
+ hex::encode(&vector.mac.0)
+ );
+ }
+}
+
+#[tokio::test]
+async fn update_hash_warns_on_remove_without_previous_value_and_stops_on_store_errors() {
+ let remove = SyncdMutation {
+ operation: Some(SyncdOperation::Remove as i32),
+ record: Some(crate::proto::wa_server_sync::SyncdRecord {
+ index: Some(crate::proto::wa_server_sync::SyncdIndex {
+ blob: Some(vec![0xab, 0xcd]),
+ }),
+ ..Default::default()
+ }),
+ };
+ let mut state = HashState::default();
+ let (warnings, result) = state
+ .update_hash(std::slice::from_ref(&remove), PreviousValueMacs::Empty)
+ .await;
+ result.unwrap();
+ assert_eq!(
+ warnings,
+ vec![MissingPreviousSetValueWarning {
+ index_mac: vec![0xab, 0xcd]
+ }]
+ );
+ assert_eq!(
+ warnings[0].to_string(),
+ "missing value MAC of previous SET operation for ABCD"
+ );
+ assert_eq!(state, HashState::default());
+
+ let deleted = NoopStore {
+ error: NoopError::DeviceDeleted,
+ };
+ let name = WaPatchName::from("regular".to_owned());
+ let (_, result) = state
+ .update_hash(
+ &[remove],
+ PreviousValueMacs::Store {
+ app_state: &deleted,
+ name: &name,
+ },
+ )
+ .await;
+ assert_eq!(
+ result.unwrap_err().to_string(),
+ "failed to get value MAC of previous SET operation: invalid use of deleted device"
+ );
+}
diff --git a/crates/whatsmeow/src/appstate/keys.rs b/crates/whatsmeow/src/appstate/keys.rs
new file mode 100644
index 0000000000..a0777a6b27
--- /dev/null
+++ b/crates/whatsmeow/src/appstate/keys.rs
@@ -0,0 +1,404 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+//
+// Ported from whatsmeow appstate/keys.go (MPL-2.0, Copyright (c) Tulir Asokan)
+
+use std::borrow::Cow;
+use std::collections::{HashMap, HashSet};
+use std::fmt;
+use std::sync::Arc;
+
+use super::decode::PatchList;
+use super::errors::AppStateError;
+use crate::store::{AppStateStore, AppStateSyncKeyStore, Device, StoreError};
+use crate::util::hkdfutil;
+
+/// A type of app state patch.
+#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
+pub struct WaPatchName(pub Cow<'static, str>);
+
+impl WaPatchName {
+ /// The name as a string.
+ pub fn as_str(&self) -> &str {
+ &self.0
+ }
+}
+
+impl fmt::Display for WaPatchName {
+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
+ formatter.write_str(&self.0)
+ }
+}
+
+impl From<String> for WaPatchName {
+ fn from(name: String) -> Self {
+ WaPatchName(Cow::Owned(name))
+ }
+}
+
+/// Contains the user's settings like push name and locale.
+pub const WA_PATCH_CRITICAL_BLOCK: WaPatchName = WaPatchName(Cow::Borrowed("critical_block"));
+/// Contains the user's contact list.
+pub const WA_PATCH_CRITICAL_UNBLOCK_LOW: WaPatchName =
+ WaPatchName(Cow::Borrowed("critical_unblock_low"));
+/// Contains some local chat settings like pin, archive status, and the
+/// setting of whether to unarchive chats when messages come in.
+pub const WA_PATCH_REGULAR_LOW: WaPatchName = WaPatchName(Cow::Borrowed("regular_low"));
+/// Contains more local chat settings like mute status and starred messages.
+pub const WA_PATCH_REGULAR_HIGH: WaPatchName = WaPatchName(Cow::Borrowed("regular_high"));
+/// Contains protocol info about app state patches like key expiration.
+pub const WA_PATCH_REGULAR: WaPatchName = WaPatchName(Cow::Borrowed("regular"));
+
+/// All currently known patch state names.
+pub const ALL_PATCH_NAMES: [WaPatchName; 5] = [
+ WA_PATCH_CRITICAL_BLOCK,
+ WA_PATCH_CRITICAL_UNBLOCK_LOW,
+ WA_PATCH_REGULAR_HIGH,
+ WA_PATCH_REGULAR,
+ WA_PATCH_REGULAR_LOW,
+];
+
+// Constants for the regular_low app state indexes.
+
+/// regular_low index.
+pub const INDEX_PIN: &str = "pin_v1";
+/// regular_low index.
+pub const INDEX_RECENT_EMOJI_WEIGHTS_ACTION: &str = "recent_emoji_weights_action";
+/// regular_low index.
+pub const INDEX_ARCHIVE: &str = "archive";
+/// regular_low index.
+pub const INDEX_SENTINEL: &str = "sentinel";
+/// regular_low index.
+pub const INDEX_MARK_CHAT_AS_READ: &str = "markChatAsRead";
+/// regular_low index.
+pub const INDEX_SETTING_UNARCHIVE_CHATS: &str = "setting_unarchiveChats";
+/// regular_low index.
+pub const INDEX_ANDROID_UNSUPPORTED_ACTIONS: &str = "android_unsupported_actions";
+/// regular_low index.
+pub const INDEX_TIME_FORMAT: &str = "time_format";
+/// regular_low index.
+pub const INDEX_NUX: &str = "nux";
+/// regular_low index.
+pub const INDEX_PRIMARY_VERSION: &str = "primary_version";
+/// regular_low index.
+pub const INDEX_FAVORITE_STICKER: &str = "favoriteSticker";
+/// regular_low index.
+pub const INDEX_REMOVE_RECENT_STICKER: &str = "removeRecentSticker";
+/// regular_low index.
+pub const INDEX_BOT_WELCOME_REQUEST: &str = "bot_welcome_request";
+/// regular_low index.
+pub const INDEX_PAYMENT_INFO: &str = "payment_info";
+/// regular_low index.
+pub const INDEX_CUSTOM_PAYMENT_METHODS: &str = "custom_payment_methods";
+/// regular_low index.
+pub const INDEX_LOCK: &str = "lock";
+/// regular_low index.
+pub const INDEX_SETTING_CHAT_LOCK: &str = "setting_chatLock";
+/// regular_low index.
+pub const INDEX_DEVICE_CAPABILITIES: &str = "device_capabilities";
+/// regular_low index.
+pub const INDEX_DEVICE_CAPABILITIES_V2: &str = "device_capabilities_v2";
+/// regular_low index.
+pub const INDEX_NOTE_EDIT: &str = "note_edit";
+/// regular_low index.
+pub const INDEX_MERCHANT_PAYMENT_PARTNER: &str = "merchant_payment_partner";
+/// regular_low index.
+pub const INDEX_PAYMENT_TOS: &str = "payment_tos";
+/// regular_low index.
+pub const INDEX_AI_THREAD_RENAME: &str = "ai_thread_rename";
+/// regular_low index.
+pub const INDEX_INTERACTIVE_MESSAGE_ACTION: &str = "interactive_message_action";
+/// regular_low index.
+pub const INDEX_SETTINGS_SYNC: &str = "settings_sync";
+/// regular_low index.
+pub const INDEX_OUT_CONTACT: &str = "out_contact";
+/// regular_low index.
+pub const INDEX_CUSTOMER_DATA: &str = "customer_data";
+/// regular_low index.
+pub const INDEX_THREAD_PIN: &str = "thread_pin";
+/// regular_low index.
+pub const INDEX_SETTING_AUTO_ORGANIZE_BUSINESS_CHAT: &str = "setting_autoOrganizeBusinessChat";
+/// regular_low index.
+pub const INDEX_COEX_V2_VERSION: &str = "coexV2Version";
+/// regular_low index.
+pub const INDEX_LOCK_MESSAGE: &str = "lock_message";
+/// regular_low index.
+pub const INDEX_CONTACT_MANAGER_METADATA: &str = "contact_manager_metadata";
+/// regular_low index.
+pub const INDEX_BUSINESS_FOLDER_ACTIVATION: &str = "business_folder_activation";
+/// regular_low index.
+pub const INDEX_GROUP_HISTORY_TOGGLE: &str = "group_history_toggle";
+/// regular_low index.
+pub const INDEX_BB_PRO_PENDING_CUSTOMER_BASE_ACTION: &str = "bb_pro_pending_customer_base_action";
+/// regular_low index.
+pub const INDEX_COMMUNITY_NESTING_STATE: &str = "community_nesting_state";
+
+// Constants for the regular app state indexes.
+
+/// regular index.
+pub const INDEX_QUICK_REPLY: &str = "quick_reply";
+/// regular index.
+pub const INDEX_LABEL_ASSOCIATION_MESSAGE: &str = "label_message";
+/// regular index.
+pub const INDEX_LABEL_EDIT: &str = "label_edit";
+/// regular index.
+pub const INDEX_LABEL_ASSOCIATION_CHAT: &str = "label_jid";
+/// regular index.
+pub const INDEX_PRIMARY_FEATURE: &str = "primary_feature";
+/// regular index.
+pub const INDEX_DEVICE_AGENT: &str = "deviceAgent";
+/// regular index.
+pub const INDEX_SUBSCRIPTION: &str = "subscription";
+/// regular index.
+pub const INDEX_AGENT_CHAT_ASSIGNMENT: &str = "agentChatAssignment";
+/// regular index.
+pub const INDEX_AGENT_CHAT_ASSIGNMENT_OPENED_STATUS: &str = "agentChatAssignmentOpenedStatus";
+/// regular index.
+pub const INDEX_PN_FOR_LID_CHAT: &str = "pnForLidChat";
+/// regular index.
+pub const INDEX_MARKETING_MESSAGE: &str = "marketingMessage";
+/// regular index.
+pub const INDEX_MARKETING_MESSAGE_BROADCAST: &str = "marketingMessageBroadcast";
+/// regular index.
+pub const INDEX_EXTERNAL_WEB_BETA: &str = "external_web_beta";
+/// regular index.
+pub const INDEX_SETTING_RELAY_ALL_CALLS: &str = "setting_relayAllCalls";
+/// regular index.
+pub const INDEX_CALL_LOG: &str = "call_log";
+/// regular index.
+pub const INDEX_DELETE_INDIVIDUAL_CALL_LOG: &str = "delete_individual_call_log";
+/// regular index.
+pub const INDEX_LABEL_REORDERING: &str = "label_reordering";
+/// regular index.
+pub const INDEX_SETTING_DISABLE_LINK_PREVIEWS: &str = "setting_disableLinkPreviews";
+/// regular index.
+pub const INDEX_USERNAME_CHAT_START_MODE: &str = "usernameChatStartMode";
+/// regular index.
+pub const INDEX_NOTIFICATION_ACTIVITY_SETTING: &str = "notificationActivitySetting";
+/// regular index.
+pub const INDEX_SETTING_CHANNELS_PERSONALISED_RECOMMENDATION_OPTOUT: &str =
+ "setting_channels_personalised_recommendation_optout";
+/// regular index.
+pub const INDEX_BROADCAST_JID: &str = "broadcast_jid";
+/// regular index.
+pub const INDEX_DETECTED_OUTCOMES_STATUS_ACTION: &str = "detected_outcomes_status_action";
+/// regular index.
+pub const INDEX_BUSINESS_BROADCAST_LIST: &str = "business_broadcast_list";
+/// regular index.
+pub const INDEX_MUSIC_USER_ID: &str = "music_user_id";
+/// regular index.
+pub const INDEX_AVATAR_UPDATED_ACTION: &str = "avatar_updated_action";
+/// regular index.
+pub const INDEX_GALAXY_FLOW_ACTION: &str = "galaxy_flow_action";
+/// regular index.
+pub const INDEX_NEWSLETTER_SAVED_INTERESTS: &str = "newsletter_saved_interests";
+/// regular index.
+pub const INDEX_SHARE_OWN_PN: &str = "shareOwnPn";
+/// regular index.
+pub const INDEX_BROADCAST: &str = "broadcast";
+/// regular index.
+pub const INDEX_SUBSCRIPTIONS_SYNC: &str = "subscriptions_sync_v2";
+/// regular index.
+pub const INDEX_LABEL_SUBLIST: &str = "label_sublist";
+/// regular index.
+pub const INDEX_CTWA_MESSAGE_RECEIVED: &str = "ctwa_message_received";
+
+// Constants for the regular_high app state indexes.
+
+/// regular_high index.
+pub const INDEX_STAR: &str = "star";
+/// regular_high index.
+pub const INDEX_MUTE: &str = "mute";
+/// regular_high index.
+pub const INDEX_DELETE_MESSAGE_FOR_ME: &str = "deleteMessageForMe";
+/// regular_high index.
+pub const INDEX_CLEAR_CHAT: &str = "clearChat";
+/// regular_high index.
+pub const INDEX_DELETE_CHAT: &str = "deleteChat";
+/// regular_high index.
+pub const INDEX_USER_STATUS_MUTE: &str = "userStatusMute";
+/// regular_high index.
+pub const INDEX_UGC_BOT: &str = "ugc_bot";
+/// regular_high index.
+pub const INDEX_STATUS_PRIVACY: &str = "status_privacy";
+/// regular_high index.
+pub const INDEX_FAVORITES: &str = "favorites";
+/// regular_high index.
+pub const INDEX_WAFFLE_ACCOUNT_LINK_STATE: &str = "waffle_account_link_state";
+/// regular_high index.
+pub const INDEX_CTWA_PER_CUSTOMER_DATA_SHARING: &str = "ctwaPerCustomerDataSharing";
+/// regular_high index.
+pub const INDEX_MAIBA_AI_FEATURES_CONTROL: &str = "maiba_ai_features_control";
+/// regular_high index.
+pub const INDEX_STATUS_POST_OPT_IN_NOTIFICATION_PREFERENCES_ACTION: &str =
+ "status_post_opt_in_notification_preferences_action";
+/// regular_high index.
+pub const INDEX_PRIVATE_PROCESSING_SETTING: &str = "private_processing_setting";
+/// regular_high index.
+pub const INDEX_AI_THREAD_DELETE: &str = "ai_thread_delete";
+/// regular_high index.
+pub const INDEX_NCT_SALT_SYNC: &str = "nct_salt_sync";
+/// regular_high index.
+pub const INDEX_BIZ_AI_SETTINGS_NUDGE_ACTION: &str = "biz_ai_settings_nudge";
+/// regular_high index.
+pub const INDEX_WASA_ROOT_SECRET_ACTION: &str = "wasa_root_secret";
+/// regular_high index.
+pub const INDEX_SHARED_DEVICE_ALLOWLIST: &str = "shared_device_allowlist";
+/// regular_high index.
+pub const INDEX_SHARED_DEVICE_SECRET: &str = "shared_device_secret";
+
+// Constants for the critical_unblock_low app state indexes.
+
+/// critical_unblock_low index.
+pub const INDEX_CONTACT: &str = "contact";
+/// critical_unblock_low index.
+pub const INDEX_LID_CONTACT: &str = "lid_contact";
+
+// Constants for the critical_block app state indexes.
+
+/// critical_block index.
+pub const INDEX_SETTING_SECURITY_NOTIFICATION: &str = "setting_securityNotification";
+/// critical_block index.
+pub const INDEX_SETTING_PUSH_NAME: &str = "setting_pushName";
+/// critical_block index.
+pub const INDEX_SETTING_LOCALE: &str = "setting_locale";
+/// critical_block index.
+pub const INDEX_GENERATED_WUI: &str = "generated_wui";
+
+/// Encodes and decodes app state patches with a device's app state stores.
+///
+/// Go keeps the `*store.Device` and reads `Store.AppStateKeys` and
+/// `Store.AppState` on every call; this holds those two handles, cloned from
+/// the device in [`Processor::new`]. After `Device::set_all_stores` or
+/// `Device::delete` swaps the device's stores, make a new processor. Go's
+/// logger is replaced by `tracing`.
+pub struct Processor {
+ /// Expanded keys by key ID. A tokio lock, because Go holds the lock across
+ /// the store lookup.
+ pub(super) key_cache: tokio::sync::Mutex<HashMap<Vec<u8>, ExpandedAppStateKeys>>,
+ /// The device's app state sync keys (Go's `Store.AppStateKeys`).
+ pub app_state_keys: Arc<dyn AppStateSyncKeyStore>,
+ /// The device's app state versions and mutation MACs (Go's
+ /// `Store.AppState`).
+ pub app_state: Arc<dyn AppStateStore>,
+}
+
+impl Processor {
+ /// A processor for the device's app state stores.
+ pub fn new(store: &Device) -> Self {
+ Processor {
+ key_cache: tokio::sync::Mutex::new(HashMap::new()),
+ app_state_keys: store.app_state_keys.clone(),
+ app_state: store.app_state.clone(),
+ }
+ }
+}
+
+/// The keys derived from one app state sync key.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct ExpandedAppStateKeys {
+ /// Key for the index MACs.
+ pub index: [u8; 32],
+ /// Key for encrypting mutation values.
+ pub value_encryption: [u8; 32],
+ /// Key for the value MACs.
+ pub value_mac: [u8; 32],
+ /// Key for the snapshot MACs.
+ pub snapshot_mac: [u8; 32],
+ /// Key for the patch MACs.
+ pub patch_mac: [u8; 32],
+}
+
+/// Getting an app state key failed.
+#[derive(Debug, thiserror::Error)]
+pub enum GetKeyError {
+ /// The store failed.
+ #[error(transparent)]
+ Store(#[from] StoreError),
+ /// The store has no such key ([`AppStateError::KeyNotFound`]).
+ #[error("{}", AppStateError::KeyNotFound)]
+ KeyNotFound,
+}
+
+impl GetKeyError {
+ /// The wrapped [`AppStateError`], like Go's `errors.Is`.
+ pub fn sentinel(&self) -> Option<AppStateError> {
+ match self {
+ GetKeyError::Store(_) => None,
+ GetKeyError::KeyNotFound => Some(AppStateError::KeyNotFound),
+ }
+ }
+}
+
+pub(super) fn expand_app_state_keys(key_data: &[u8]) -> ExpandedAppStateKeys {
+ let expanded = hkdfutil::sha256(key_data, &[], b"WhatsApp Mutation Keys", 160);
+ let mut keys = [[0; 32]; 5];
+ for (key, chunk) in keys.iter_mut().zip(expanded.chunks_exact(32)) {
+ key.copy_from_slice(chunk);
+ }
+ let [index, value_encryption, value_mac, snapshot_mac, patch_mac] = keys;
+ ExpandedAppStateKeys {
+ index,
+ value_encryption,
+ value_mac,
+ snapshot_mac,
+ patch_mac,
+ }
+}
+
+impl Processor {
+ pub(super) async fn get_app_state_key(
+ &self,
+ key_id: &[u8],
+ ) -> Result<ExpandedAppStateKeys, GetKeyError> {
+ let mut key_cache = self.key_cache.lock().await;
+ if let Some(keys) = key_cache.get(key_id) {
+ return Ok(*keys);
+ }
+ let key_data = self
+ .app_state_keys
+ .get_app_state_sync_key(key_id)
+ .await?
+ .ok_or(GetKeyError::KeyNotFound)?;
+ let keys = expand_app_state_keys(&key_data.data);
+ key_cache.insert(key_id.to_vec(), keys);
+ Ok(keys)
+ }
+
+ /// The IDs of the keys the patch list uses that aren't in the store, in
+ /// order of first use. Lookup failures are logged and don't count as
+ /// missing.
+ pub async fn get_missing_key_ids(&self, pl: &PatchList) -> Vec<Vec<u8>> {
+ let mut cache = HashSet::new();
+ let mut missing_keys = Vec::new();
+ let mut key_ids: Vec<Option<&[u8]>> = Vec::new();
+ if let Some(snapshot) = &pl.snapshot {
+ key_ids.push(snapshot.key_id.as_ref().and_then(|key| key.id.as_deref()));
+ for record in &snapshot.records {
+ key_ids.push(record.key_id.as_ref().and_then(|key| key.id.as_deref()));
+ }
+ }
+ for patch in &pl.patches {
+ key_ids.push(patch.key_id.as_ref().and_then(|key| key.id.as_deref()));
+ }
+ for key_id in key_ids.into_iter().flatten() {
+ if !cache.insert(key_id) {
+ continue;
+ }
+ match self.app_state_keys.get_app_state_sync_key(key_id).await {
+ Ok(Some(_)) => {}
+ Ok(None) => missing_keys.push(key_id.to_vec()),
+ Err(error) => tracing::warn!(
+ key_id = %hex::encode_upper(key_id),
+ error = %error,
+ "Error fetching key while checking if it's missing"
+ ),
+ }
+ }
+ missing_keys
+ }
+}
+
+#[cfg(test)]
+mod test;
diff --git a/crates/whatsmeow/src/appstate/keys/test.rs b/crates/whatsmeow/src/appstate/keys/test.rs
new file mode 100644
index 0000000000..a11b9c6e91
--- /dev/null
+++ b/crates/whatsmeow/src/appstate/keys/test.rs
@@ -0,0 +1,89 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+//! Expected values were produced by whatsmeow's Go code at the pinned revision.
+
+use super::*;
+use crate::appstate::vectors;
+
+#[test]
+fn expand_app_state_keys_matches_go() {
+ let vectors = vectors::load();
+ assert_eq!(vectors.expanded_keys.len(), 2);
+ for vector in vectors.expanded_keys {
+ let keys = expand_app_state_keys(&vector.key_data.0);
+ assert_eq!(keys.index.to_vec(), vector.index.0);
+ assert_eq!(keys.value_encryption.to_vec(), vector.value_encryption.0);
+ assert_eq!(keys.value_mac.to_vec(), vector.value_mac.0);
+ assert_eq!(keys.snapshot_mac.to_vec(), vector.snapshot_mac.0);
+ assert_eq!(keys.patch_mac.to_vec(), vector.patch_mac.0);
+ }
+}
+
+#[tokio::test]
+async fn get_app_state_key_caches_and_reports_missing_keys() {
+ let vectors = vectors::load();
+ let (store, processor) = vectors::processor_with_keys(&vectors.sequence.keys).await;
+ let key = &vectors.sequence.keys[0];
+
+ let keys = processor.get_app_state_key(&key.id.0).await.unwrap();
+ assert_eq!(keys, expand_app_state_keys(&key.data.0));
+
+ // Served from the cache once loaded, even if the store changes.
+ store
+ .put_app_state_sync_key(
+ &key.id.0,
+ crate::store::AppStateSyncKey {
+ data: vec![9; 32],
+ fingerprint: Vec::new(),
+ timestamp: 0,
+ },
+ )
+ .await
+ .unwrap();
+ assert_eq!(processor.get_app_state_key(&key.id.0).await.unwrap(), keys);
+
+ let missing = processor.get_app_state_key(b"missing").await.unwrap_err();
+ assert_eq!(missing.to_string(), "didn't find app state key");
+ assert_eq!(missing.sentinel(), Some(AppStateError::KeyNotFound));
+}
+
+#[test]
+fn patch_names_match_go() {
+ assert_eq!(
+ ALL_PATCH_NAMES.map(|name| name.to_string()),
+ [
+ "critical_block",
+ "critical_unblock_low",
+ "regular_high",
+ "regular",
+ "regular_low"
+ ]
+ );
+}
+
+#[test]
+fn processor_futures_are_send_for_spawning() {
+ fn assert_send<Future: Send>(_: Future) {}
+ let store = Arc::new(crate::store::MemoryStore::default());
+ let processor = Processor {
+ key_cache: Default::default(),
+ app_state_keys: store.clone(),
+ app_state: store,
+ };
+ let list = PatchList {
+ name: WA_PATCH_REGULAR,
+ has_more_patches: false,
+ patches: Vec::new(),
+ snapshot: None,
+ };
+ assert_send(processor.decode_patches(&list, Default::default(), true));
+ assert_send(processor.get_missing_key_ids(&list));
+ assert_send(processor.encode_patch(
+ b"key",
+ Default::default(),
+ crate::appstate::build_setting_push_name("Wolf"),
+ ));
+ assert_send(processor.process_recovery(&Default::default()));
+}
diff --git a/crates/whatsmeow/src/appstate/lthash.rs b/crates/whatsmeow/src/appstate/lthash.rs
new file mode 100644
index 0000000000..023742d40a
--- /dev/null
+++ b/crates/whatsmeow/src/appstate/lthash.rs
@@ -0,0 +1,108 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+//
+// Ported from whatsmeow appstate/lthash/lthash.go (MPL-2.0, Copyright (c) Tulir Asokan)
+
+//! A summation based hash algorithm that maintains the integrity of a piece
+//! of data over a series of mutations. You can add/remove mutations, and it'll
+//! return a hash equal to if the same series of mutations was made
+//! sequentially.
+
+use std::borrow::Cow;
+
+use crate::util::hkdfutil;
+
+/// An LT hash instance: each item is expanded with HKDF-SHA256 under
+/// `hkdf_info` to `hkdf_size` bytes, which are added to or subtracted from the
+/// hash as little-endian 16-bit words.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct LtHash {
+ /// The HKDF info string.
+ pub hkdf_info: Cow<'static, [u8]>,
+ /// How many bytes each item expands to.
+ pub hkdf_size: u8,
+}
+
+/// The LT hash instance used for verifying the integrity of WhatsApp app
+/// state sync patches.
+pub const WA_PATCH_INTEGRITY: LtHash = LtHash {
+ hkdf_info: Cow::Borrowed(b"WhatsApp Patch Integrity"),
+ hkdf_size: 128,
+};
+
+/// The base hash can't be combined with the expanded items. Go panics.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
+#[error("LT hash base of {base_length} bytes doesn't fit {hkdf_size}-byte items of 16-bit words")]
+pub struct LtHashLengthError {
+ /// The length of the base hash.
+ pub base_length: usize,
+ /// The length of each expanded item.
+ pub hkdf_size: u8,
+}
+
+impl LtHash {
+ /// Returns a copy of `base` with every `subtract` item subtracted, then
+ /// every `add` item added.
+ ///
+ /// Fails when `base` is odd-length or longer than `hkdf_size`, where Go
+ /// panics.
+ pub fn subtract_then_add(
+ &self,
+ base: &[u8],
+ subtract: &[impl AsRef<[u8]>],
+ add: &[impl AsRef<[u8]>],
+ ) -> Result<Vec<u8>, LtHashLengthError> {
+ let mut output = base.to_vec();
+ self.subtract_then_add_in_place(&mut output, subtract, add)?;
+ Ok(output)
+ }
+
+ /// Subtracts every `subtract` item from `base`, then adds every `add` item.
+ ///
+ /// Fails without changing `base` when it is odd-length or longer than
+ /// `hkdf_size`, where Go panics.
+ pub fn subtract_then_add_in_place(
+ &self,
+ base: &mut [u8],
+ subtract: &[impl AsRef<[u8]>],
+ add: &[impl AsRef<[u8]>],
+ ) -> Result<(), LtHashLengthError> {
+ if !base.len().is_multiple_of(2) || base.len() > usize::from(self.hkdf_size) {
+ return Err(LtHashLengthError {
+ base_length: base.len(),
+ hkdf_size: self.hkdf_size,
+ });
+ }
+ self.multiple_op(base, subtract, true);
+ self.multiple_op(base, add, false);
+ Ok(())
+ }
+
+ fn multiple_op(&self, base: &mut [u8], input: &[impl AsRef<[u8]>], subtract: bool) {
+ for item in input {
+ perform_pointwise_with_overflow(
+ base,
+ &hkdfutil::sha256(item.as_ref(), &[], &self.hkdf_info, self.hkdf_size),
+ subtract,
+ );
+ }
+ }
+}
+
+/// `base` is at most as long as `input` and even-length (checked by the caller).
+fn perform_pointwise_with_overflow(base: &mut [u8], input: &[u8], subtract: bool) {
+ for (base_word, input_word) in base.chunks_exact_mut(2).zip(input.chunks_exact(2)) {
+ let x = u16::from_le_bytes([base_word[0], base_word[1]]);
+ let y = u16::from_le_bytes([input_word[0], input_word[1]]);
+ let result = if subtract {
+ x.wrapping_sub(y)
+ } else {
+ x.wrapping_add(y)
+ };
+ base_word.copy_from_slice(&result.to_le_bytes());
+ }
+}
+
+#[cfg(test)]
+mod test;
diff --git a/crates/whatsmeow/src/appstate/lthash/test.rs b/crates/whatsmeow/src/appstate/lthash/test.rs
new file mode 100644
index 0000000000..b339068a02
--- /dev/null
+++ b/crates/whatsmeow/src/appstate/lthash/test.rs
@@ -0,0 +1,51 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+//! Expected values were produced by whatsmeow's Go code at the pinned revision.
+
+use super::*;
+use crate::appstate::vectors;
+
+#[test]
+fn subtract_then_add_matches_go() {
+ let vectors = vectors::load();
+ assert_eq!(vectors.lthash.len(), 2);
+ for vector in vectors.lthash {
+ let subtract: Vec<&[u8]> = vector
+ .subtract
+ .iter()
+ .map(|item| item.0.as_slice())
+ .collect();
+ let add: Vec<&[u8]> = vector.add.iter().map(|item| item.0.as_slice()).collect();
+ let result = WA_PATCH_INTEGRITY
+ .subtract_then_add(&vector.base.0, &subtract, &add)
+ .unwrap();
+ assert_eq!(hex::encode(&result), hex::encode(&vector.result.0));
+
+ // Subtracting what was added gives back the base.
+ let back = WA_PATCH_INTEGRITY
+ .subtract_then_add(&result, &add, &subtract)
+ .unwrap();
+ assert_eq!(back, vector.base.0);
+ }
+}
+
+#[test]
+fn subtract_then_add_in_place_rejects_bases_go_panics_on() {
+ let mut odd = [0; 127];
+ assert_eq!(
+ WA_PATCH_INTEGRITY.subtract_then_add_in_place(&mut odd, &[b"x"], &[b"y"]),
+ Err(LtHashLengthError {
+ base_length: 127,
+ hkdf_size: 128
+ })
+ );
+ let mut long = [0; 130];
+ assert!(
+ WA_PATCH_INTEGRITY
+ .subtract_then_add_in_place(&mut long, &[b"x"], &[b"y"])
+ .is_err()
+ );
+ assert_eq!(long, [0; 130]);
+}
diff --git a/crates/whatsmeow/src/appstate/recovery.rs b/crates/whatsmeow/src/appstate/recovery.rs
new file mode 100644
index 0000000000..09f896d89e
--- /dev/null
+++ b/crates/whatsmeow/src/appstate/recovery.rs
@@ -0,0 +1,158 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+//
+// Ported from whatsmeow appstate/recovery.go (MPL-2.0, Copyright (c) Tulir Asokan)
+
+use std::io::{self, Read};
+
+use flate2::read::MultiGzDecoder;
+use hmac::Hmac;
+use prost::Message;
+use sha2::Sha256;
+
+use super::decode::unmarshal_index;
+use super::hash::{Mutation, concat_and_hmac};
+use super::keys::{GetKeyError, Processor};
+use crate::proto::wa_e2e::peer_data_operation_request_response_message::peer_data_operation_result::SyncDSnapshotFatalRecoveryResponse;
+use crate::proto::wa_server_sync::syncd_mutation::SyncdOperation;
+use crate::proto::wa_syncd_snapshot_recovery::SyncdSnapshotRecovery;
+use crate::store::{AppStateMutationMac, StoreError};
+
+/// Parsing a recovery response failed.
+#[derive(Debug, thiserror::Error)]
+pub enum ParseRecoveryError {
+ /// The gzip stream is invalid. Go reports header errors as "failed to
+ /// start decompressing" and close errors separately; the gzip reader here
+ /// reports both while reading.
+ #[error("failed to decompress: {0}")]
+ Decompress(#[source] io::Error),
+ /// The snapshot isn't a valid protobuf.
+ #[error(transparent)]
+ Unmarshal(#[from] prost::DecodeError),
+}
+
+/// Decodes the collection snapshot of a fatal recovery response from the
+/// primary device, decompressing it if needed.
+pub fn parse_recovery(
+ resp: &SyncDSnapshotFatalRecoveryResponse,
+) -> Result<SyncdSnapshotRecovery, ParseRecoveryError> {
+ let mut data = resp.collection_snapshot.clone().unwrap_or_default();
+ if resp.is_compressed.unwrap_or_default() {
+ let mut decompressed = Vec::new();
+ MultiGzDecoder::new(data.as_slice())
+ .read_to_end(&mut decompressed)
+ .map_err(ParseRecoveryError::Decompress)?;
+ data = decompressed;
+ }
+ Ok(SyncdSnapshotRecovery::decode(data.as_slice())?)
+}
+
+/// Applying a recovery snapshot failed.
+#[derive(Debug, thiserror::Error)]
+pub enum ProcessRecoveryError {
+ /// The LT hash isn't 128 bytes.
+ #[error("invalid lthash length: {0}")]
+ InvalidLtHashLength(usize),
+ /// The key of a mutation couldn't be loaded.
+ #[error("failed to get key {} for mutation #{number}: {source}", hex::encode(.key_id))]
+ MutationKey {
+ /// The key ID.
+ key_id: Vec<u8>,
+ /// The position of the mutation, from 1.
+ number: usize,
+ /// The failure.
+ source: GetKeyError,
+ },
+ /// A mutation's index isn't a JSON list of strings.
+ #[error("failed to unmarshal index for mutation #{number}: {source}")]
+ UnmarshalIndex {
+ /// The position of the mutation, from 1.
+ number: usize,
+ /// The failure.
+ source: serde_json::Error,
+ },
+ /// Deleting the old version failed.
+ #[error("failed to reset app state version in database: {0}")]
+ ResetVersion(#[source] StoreError),
+ /// Storing the new version failed.
+ #[error("failed to update app state version in the database: {0}")]
+ PutVersion(#[source] StoreError),
+ /// Storing the mutation MACs failed.
+ #[error("failed to insert added mutation MACs to the database: {0}")]
+ PutMacs(#[source] StoreError),
+}
+
+impl Processor {
+ /// Replaces the stored state of a collection with a recovery snapshot and
+ /// returns its mutations, all SETs.
+ ///
+ /// Go also returns the mutations when storing fails; this returns just the
+ /// error.
+ pub async fn process_recovery(
+ &self,
+ recovery: &SyncdSnapshotRecovery,
+ ) -> Result<Vec<Mutation>, ProcessRecoveryError> {
+ let lthash = recovery.collection_lthash.as_deref().unwrap_or_default();
+ let lthash = <[u8; 128]>::try_from(lthash)
+ .map_err(|_| ProcessRecoveryError::InvalidLtHashLength(lthash.len()))?;
+ let name = recovery.collection_name.as_deref().unwrap_or_default();
+ let version = recovery
+ .version
+ .as_ref()
+ .and_then(|version| version.version)
+ .unwrap_or_default();
+ let mut macs = Vec::with_capacity(recovery.mutation_records.len());
+ let mut mutations = Vec::with_capacity(recovery.mutation_records.len());
+ for (i, mutation) in recovery.mutation_records.iter().enumerate() {
+ let key_id = mutation.key_id.as_deref().unwrap_or_default();
+ let keys = self.get_app_state_key(key_id).await.map_err(|source| {
+ ProcessRecoveryError::MutationKey {
+ key_id: key_id.to_vec(),
+ number: i + 1,
+ source,
+ }
+ })?;
+ let value = mutation.value.as_ref();
+ let index = value
+ .and_then(|value| value.index.as_deref())
+ .unwrap_or_default();
+ let parsed_index =
+ unmarshal_index(index).map_err(|source| ProcessRecoveryError::UnmarshalIndex {
+ number: i + 1,
+ source,
+ })?;
+ let mac = AppStateMutationMac {
+ index_mac: concat_and_hmac::<Hmac<Sha256>>(&keys.index, &[index]),
+ value_mac: mutation.mac.clone().unwrap_or_default(),
+ };
+ mutations.push(Mutation {
+ key_id: key_id.to_vec(),
+ operation: SyncdOperation::Set as i32,
+ action: value.and_then(|value| value.value.clone()),
+ version: value.and_then(|value| value.version).unwrap_or_default(),
+ index: parsed_index,
+ index_mac: mac.index_mac.clone(),
+ value_mac: mac.value_mac.clone(),
+ patch_version: version,
+ });
+ macs.push(mac);
+ }
+ self.app_state
+ .delete_app_state_version(name)
+ .await
+ .map_err(ProcessRecoveryError::ResetVersion)?;
+ self.app_state
+ .put_app_state_version(name, version, lthash)
+ .await
+ .map_err(ProcessRecoveryError::PutVersion)?;
+ self.app_state
+ .put_app_state_mutation_macs(name, version, &macs)
+ .await
+ .map_err(ProcessRecoveryError::PutMacs)?;
+ Ok(mutations)
+ }
+}
+
+#[cfg(test)]
+mod test;
diff --git a/crates/whatsmeow/src/appstate/recovery/test.rs b/crates/whatsmeow/src/appstate/recovery/test.rs
new file mode 100644
index 0000000000..1e839bf069
--- /dev/null
+++ b/crates/whatsmeow/src/appstate/recovery/test.rs
@@ -0,0 +1,75 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+//! Expected values were produced by whatsmeow's Go code at the pinned revision.
+
+use super::*;
+use crate::appstate::vectors;
+use crate::store::AppStateStore;
+
+#[tokio::test]
+async fn parse_and_process_recovery_match_go() {
+ let vectors = vectors::load();
+ let recovery = vectors.recovery;
+ assert!(recovery.is_compressed);
+ let (store, processor) = vectors::processor_with_keys(&vectors.sequence.keys).await;
+ // A version that the recovery replaces.
+ store
+ .put_app_state_version(&recovery.name, 7, [9; 128])
+ .await
+ .unwrap();
+
+ let parsed = parse_recovery(&SyncDSnapshotFatalRecoveryResponse {
+ collection_snapshot: Some(recovery.collection_snapshot.0.clone()),
+ is_compressed: Some(true),
+ })
+ .unwrap();
+ assert_eq!(parsed.collection_name.as_deref(), Some("regular_low"));
+
+ let mutations = processor.process_recovery(&parsed).await.unwrap();
+ assert_eq!(
+ mutations,
+ recovery
+ .mutations
+ .iter()
+ .map(vectors::MutationVector::to_mutation)
+ .collect::<Vec<_>>()
+ );
+ let (version, hash) = store.get_app_state_version(&recovery.name).await.unwrap();
+ assert_eq!(version, recovery.stored_state.0.version);
+ assert_eq!(hash, recovery.stored_state.0.hash);
+ vectors::assert_lookups(&store, &recovery.name, &recovery.lookups).await;
+
+ // The same snapshot uncompressed.
+ let uncompressed = parse_recovery(&SyncDSnapshotFatalRecoveryResponse {
+ collection_snapshot: Some(parsed.encode_to_vec()),
+ is_compressed: Some(false),
+ })
+ .unwrap();
+ assert_eq!(uncompressed, parsed);
+}
+
+#[tokio::test]
+async fn process_recovery_rejects_an_invalid_lthash_like_go() {
+ let vectors = vectors::load();
+ let (_, processor) = vectors::processor_with_keys(&vectors.sequence.keys).await;
+ let invalid =
+ SyncdSnapshotRecovery::decode(vectors.recovery.invalid_lthash_snapshot.0.as_slice())
+ .unwrap();
+ let error = processor.process_recovery(&invalid).await.unwrap_err();
+ assert_eq!(error.to_string(), vectors.recovery.invalid_lthash_error);
+}
+
+#[test]
+fn parse_recovery_reports_bad_gzip() {
+ let error = parse_recovery(&SyncDSnapshotFatalRecoveryResponse {
+ collection_snapshot: Some(b"not gzip".to_vec()),
+ is_compressed: Some(true),
+ })
+ .unwrap_err();
+ assert!(
+ error.to_string().starts_with("failed to decompress: "),
+ "{error}"
+ );
+}
diff --git a/crates/whatsmeow/src/appstate/vectors.rs b/crates/whatsmeow/src/appstate/vectors.rs
new file mode 100644
index 0000000000..a0857c9dda
--- /dev/null
+++ b/crates/whatsmeow/src/appstate/vectors.rs
@@ -0,0 +1,290 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+//! The test vectors in `testdata/appstate/vectors.json`, written by running
+//! whatsmeow's Go code at the pinned revision (`testdata/generator/appstate`).
+//! Not a port of a Go file.
+
+use std::sync::Arc;
+
+use prost::Message;
+use serde::Deserialize;
+
+use super::hash::{HashState, Mutation};
+use super::keys::{Processor, WaPatchName};
+use crate::proto::wa_server_sync::{SyncdPatch, SyncdSnapshot};
+use crate::proto::wa_sync_action::SyncActionValue;
+use crate::store::{AppStateStore, AppStateSyncKey, AppStateSyncKeyStore, MemoryStore};
+
+/// Bytes written as a hex string.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct Hex(pub Vec<u8>);
+
+impl<'de> Deserialize<'de> for Hex {
+ fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
+ let text = String::deserialize(deserializer)?;
+ hex::decode(text).map(Hex).map_err(serde::de::Error::custom)
+ }
+}
+
+#[derive(Deserialize)]
+pub struct Vectors {
+ pub lthash: Vec<LtHashVector>,
+ pub expanded_keys: Vec<ExpandedKeysVector>,
+ pub snapshot_mac: Vec<SnapshotMacVector>,
+ pub patch_mac: Vec<PatchMacVector>,
+ pub content_mac: Vec<ContentMacVector>,
+ pub index_mac: Vec<IndexMacVector>,
+ pub index_json: Vec<IndexJsonVector>,
+ pub builders: Vec<PatchInfoVector>,
+ pub sequence: SequenceVector,
+ pub decode_errors: Vec<DecodeErrorVector>,
+ pub recovery: RecoveryVector,
+}
+
+#[derive(Deserialize)]
+pub struct LtHashVector {
+ pub base: Hex,
+ pub subtract: Vec<Hex>,
+ pub add: Vec<Hex>,
+ pub result: Hex,
+}
+
+#[derive(Deserialize)]
+pub struct ExpandedKeysVector {
+ pub key_data: Hex,
+ pub index: Hex,
+ pub value_encryption: Hex,
+ pub value_mac: Hex,
+ pub snapshot_mac: Hex,
+ pub patch_mac: Hex,
+}
+
+#[derive(Deserialize)]
+pub struct SnapshotMacVector {
+ pub hash: Hex,
+ pub version: u64,
+ pub name: String,
+ pub key: Hex,
+ pub mac: Hex,
+}
+
+#[derive(Deserialize)]
+pub struct PatchMacVector {
+ pub patch: Hex,
+ pub name: String,
+ pub key: Hex,
+ pub version: u64,
+ pub mac: Hex,
+}
+
+#[derive(Deserialize)]
+pub struct ContentMacVector {
+ pub operation: i32,
+ pub data: Hex,
+ pub key_id: Hex,
+ pub key: Hex,
+ pub mac: Hex,
+}
+
+#[derive(Deserialize)]
+pub struct IndexMacVector {
+ pub key: Hex,
+ pub index: Hex,
+ pub mac: Hex,
+}
+
+#[derive(Deserialize)]
+pub struct IndexJsonVector {
+ pub index: Vec<String>,
+ pub json: String,
+}
+
+#[derive(Deserialize)]
+pub struct PatchInfoVector {
+ #[serde(rename = "type")]
+ pub patch_type: String,
+ pub mutations: Vec<MutationInfoVector>,
+}
+
+#[derive(Deserialize)]
+pub struct MutationInfoVector {
+ pub index: Vec<String>,
+ pub version: i32,
+ pub value: Hex,
+}
+
+#[derive(Deserialize)]
+pub struct KeyVector {
+ pub id: Hex,
+ pub data: Hex,
+}
+
+#[derive(Clone, Copy, Deserialize)]
+#[serde(from = "StateJson")]
+pub struct StateVector(pub HashState);
+
+#[derive(Deserialize)]
+struct StateJson {
+ version: u64,
+ hash: Hex,
+}
+
+impl From<StateJson> for StateVector {
+ fn from(state: StateJson) -> Self {
+ StateVector(HashState {
+ version: state.version,
+ hash: state
+ .hash
+ .0
+ .try_into()
+ .expect("the generator writes 128-byte hashes"),
+ })
+ }
+}
+
+#[derive(Deserialize)]
+pub struct MutationVector {
+ pub key_id: Hex,
+ pub operation: i32,
+ pub action: Option<Hex>,
+ pub version: i32,
+ pub index: Vec<String>,
+ pub index_mac: Hex,
+ pub value_mac: Hex,
+ pub patch_version: u64,
+}
+
+impl MutationVector {
+ pub fn to_mutation(&self) -> Mutation {
+ Mutation {
+ key_id: self.key_id.0.clone(),
+ operation: self.operation,
+ action: self
+ .action
+ .as_ref()
+ .map(|action| SyncActionValue::decode(action.0.as_slice()).unwrap()),
+ version: self.version,
+ index: self.index.clone(),
+ index_mac: self.index_mac.0.clone(),
+ value_mac: self.value_mac.0.clone(),
+ patch_version: self.patch_version,
+ }
+ }
+}
+
+#[derive(Deserialize)]
+pub struct LookupVector {
+ pub index_mac: Hex,
+ pub value_mac: Option<Hex>,
+}
+
+#[derive(Deserialize)]
+pub struct PatchListVector {
+ pub snapshot: Option<Hex>,
+ pub patches: Vec<Hex>,
+}
+
+impl PatchListVector {
+ pub fn to_patch_list(&self, name: &str) -> super::decode::PatchList {
+ super::decode::PatchList {
+ name: WaPatchName::from(name.to_owned()),
+ has_more_patches: false,
+ patches: self
+ .patches
+ .iter()
+ .map(|patch| SyncdPatch::decode(patch.0.as_slice()).unwrap())
+ .collect(),
+ snapshot: self
+ .snapshot
+ .as_ref()
+ .map(|snapshot| SyncdSnapshot::decode(snapshot.0.as_slice()).unwrap()),
+ }
+ }
+}
+
+#[derive(Deserialize)]
+pub struct DecodeStepVector {
+ pub list: PatchListVector,
+ pub initial_state: StateVector,
+ pub mutations: Vec<MutationVector>,
+ pub state: StateVector,
+ pub stored_state: StateVector,
+ pub lookups: Vec<LookupVector>,
+}
+
+#[derive(Deserialize)]
+pub struct SequenceVector {
+ pub name: String,
+ pub keys: Vec<KeyVector>,
+ pub steps: Vec<DecodeStepVector>,
+}
+
+#[derive(Deserialize)]
+pub struct DecodeErrorVector {
+ pub description: String,
+ pub list: PatchListVector,
+ pub initial_state: StateVector,
+ pub error: String,
+ pub key_not_found: bool,
+ pub missing_keys: Vec<Hex>,
+}
+
+#[derive(Deserialize)]
+pub struct RecoveryVector {
+ pub collection_snapshot: Hex,
+ pub is_compressed: bool,
+ pub name: String,
+ pub mutations: Vec<MutationVector>,
+ pub stored_state: StateVector,
+ pub lookups: Vec<LookupVector>,
+ pub invalid_lthash_snapshot: Hex,
+ pub invalid_lthash_error: String,
+}
+
+pub fn load() -> Vectors {
+ serde_json::from_str(include_str!("../../testdata/appstate/vectors.json")).unwrap()
+}
+
+/// A memory store holding the sequence's keys, and a processor on it.
+pub async fn processor_with_keys(keys: &[KeyVector]) -> (Arc<MemoryStore>, Processor) {
+ let store = Arc::new(MemoryStore::default());
+ for key in keys {
+ store
+ .put_app_state_sync_key(
+ &key.id.0,
+ AppStateSyncKey {
+ data: key.data.0.clone(),
+ fingerprint: Vec::new(),
+ timestamp: 0,
+ },
+ )
+ .await
+ .unwrap();
+ }
+ let processor = Processor {
+ key_cache: Default::default(),
+ app_state_keys: store.clone(),
+ app_state: store.clone(),
+ };
+ (store, processor)
+}
+
+/// Checks the stored value MAC of every index MAC.
+pub async fn assert_lookups(store: &MemoryStore, name: &str, lookups: &[LookupVector]) {
+ for lookup in lookups {
+ assert_eq!(
+ store
+ .get_app_state_mutation_mac(name, &lookup.index_mac.0)
+ .await
+ .unwrap(),
+ lookup
+ .value_mac
+ .as_ref()
+ .map(|value_mac| value_mac.0.clone()),
+ "{}",
+ hex::encode(&lookup.index_mac.0)
+ );
+ }
+}
diff --git a/crates/whatsmeow/src/binary.rs b/crates/whatsmeow/src/binary.rs
new file mode 100644
index 0000000000..875d7cbb56
--- /dev/null
+++ b/crates/whatsmeow/src/binary.rs
@@ -0,0 +1,28 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+//
+// Ported from whatsmeow binary/ (MPL-2.0, Copyright (c) Tulir Asokan)
+
+//! Encoding and decoding documents in WhatsApp's binary XML format.
+//!
+//! Not ported: `Node.UnmarshalJSON` (no JSON caller yet) and the deprecated
+//! `binary/proto` aliases (use [`crate::proto`]).
+
+mod attrs;
+mod decoder;
+mod encoder;
+mod errors;
+mod node;
+pub mod token;
+mod unpack;
+mod xml;
+
+pub use attrs::{AttrError, AttrUtility, ErrorList};
+pub use errors::{DecodeError, EncodeError};
+pub use node::{AttributeValue, Attrs, Node, NodeContent, marshal, unmarshal};
+pub use unpack::unpack;
+pub use xml::MAX_BYTES_TO_PRINT_AS_HEX;
+
+#[cfg(test)]
+mod test;
diff --git a/crates/whatsmeow/src/binary/attrs.rs b/crates/whatsmeow/src/binary/attrs.rs
new file mode 100644
index 0000000000..5ef8427815
--- /dev/null
+++ b/crates/whatsmeow/src/binary/attrs.rs
@@ -0,0 +1,314 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+//
+// Ported from whatsmeow binary/attrs.go (MPL-2.0, Copyright (c) Tulir Asokan)
+
+use std::fmt;
+use std::num::ParseIntError;
+
+use chrono::{DateTime, Utc};
+
+use super::node::{AttributeValue, Attrs, Node};
+use crate::types::{EMPTY_JID, Jid};
+
+/// A helper for reading multiple XML attributes and checking for errors
+/// afterwards.
+///
+/// The functions return values directly and collect any decoding errors, which
+/// can then be checked after all necessary attributes are read, instead of
+/// having to check each attribute for errors separately.
+pub struct AttrUtility<'node> {
+ /// The attributes being read.
+ pub attrs: &'node Attrs,
+ /// The errors collected so far.
+ pub errors: Vec<AttrError>,
+}
+
+/// One failed attribute read.
+#[derive(Debug, thiserror::Error, PartialEq, Eq)]
+pub enum AttrError {
+ /// A required JID attribute was missing.
+ #[error("didn't find required JID attribute '{0}'")]
+ MissingJid(String),
+ /// A required attribute was missing.
+ #[error("didn't find required attribute '{0}'")]
+ Missing(String),
+ /// The attribute had a different type than requested.
+ #[error("expected attribute '{key}' to be {expected}, but was {actual}")]
+ WrongType {
+ /// The attribute key.
+ key: String,
+ /// The requested type.
+ expected: &'static str,
+ /// The stored type.
+ actual: &'static str,
+ },
+ /// The attribute wasn't a valid integer.
+ #[error("failed to parse int in attribute '{key}': {source}")]
+ ParseInt {
+ /// The attribute key.
+ key: String,
+ /// The parse failure.
+ source: ParseIntError,
+ },
+ /// The attribute wasn't a valid unsigned integer.
+ #[error("failed to parse uint in attribute '{key}': {source}")]
+ ParseUint {
+ /// The attribute key.
+ key: String,
+ /// The parse failure.
+ source: ParseIntError,
+ },
+ /// The attribute wasn't one of the strings Go's `strconv.ParseBool` accepts.
+ #[error("failed to parse bool in attribute '{key}': invalid syntax {value:?}")]
+ ParseBool {
+ /// The attribute key.
+ key: String,
+ /// The stored value.
+ value: String,
+ },
+}
+
+/// A list of errors that is an error itself.
+#[derive(Debug, PartialEq, Eq)]
+pub struct ErrorList(pub Vec<AttrError>);
+
+impl fmt::Display for ErrorList {
+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
+ formatter.write_str("[")?;
+ for (index, error) in self.0.iter().enumerate() {
+ if index > 0 {
+ formatter.write_str(" ")?;
+ }
+ write!(formatter, "{error}")?;
+ }
+ formatter.write_str("]")
+ }
+}
+
+impl std::error::Error for ErrorList {}
+
+impl Node {
+ /// The [`AttrUtility`] for this node.
+ pub fn attr_getter(&self) -> AttrUtility<'_> {
+ AttrUtility {
+ attrs: &self.attrs,
+ errors: Vec::new(),
+ }
+ }
+}
+
+fn type_name(value: &AttributeValue) -> &'static str {
+ match value {
+ AttributeValue::String(_) => "string",
+ AttributeValue::Jid(_) => "types.JID",
+ }
+}
+
+impl AttrUtility<'_> {
+ /// The JID under the given key, if present and a JID. A missing attribute
+ /// is an error only when `require` is set; a non-JID value always is.
+ pub fn get_jid(&mut self, key: &str, require: bool) -> Option<Jid> {
+ match self.attrs.get(key) {
+ None => {
+ if require {
+ self.errors.push(AttrError::MissingJid(key.to_owned()));
+ }
+ None
+ }
+ Some(AttributeValue::Jid(jid)) => Some(jid.clone()),
+ Some(other) => {
+ self.errors.push(AttrError::WrongType {
+ key: key.to_owned(),
+ expected: "JID",
+ actual: type_name(other),
+ });
+ None
+ }
+ }
+ }
+
+ /// The JID under the given key. A missing attribute isn't an error.
+ pub fn optional_jid(&mut self, key: &str) -> Option<Jid> {
+ self.get_jid(key, false)
+ }
+
+ /// The JID under the given key, or an empty JID. A missing attribute isn't
+ /// an error.
+ pub fn optional_jid_or_empty(&mut self, key: &str) -> Jid {
+ self.get_jid(key, false)
+ .unwrap_or_else(|| EMPTY_JID.clone())
+ }
+
+ /// The JID under the given key. If there's no valid JID under the key, an
+ /// error is stored and an empty JID is returned.
+ pub fn jid(&mut self, key: &str) -> Jid {
+ self.get_jid(key, true).unwrap_or_default()
+ }
+
+ /// The string under the given key, if present and a string. A missing
+ /// attribute is an error only when `require` is set.
+ pub fn get_string(&mut self, key: &str, require: bool) -> Option<String> {
+ match self.attrs.get(key) {
+ None => {
+ if require {
+ self.errors.push(AttrError::Missing(key.to_owned()));
+ }
+ None
+ }
+ Some(AttributeValue::String(value)) => Some(value.clone()),
+ Some(other) => {
+ self.errors.push(AttrError::WrongType {
+ key: key.to_owned(),
+ expected: "string",
+ actual: type_name(other),
+ });
+ None
+ }
+ }
+ }
+
+ /// The base-10 integer under the given key.
+ pub fn get_int64(&mut self, key: &str, require: bool) -> Option<i64> {
+ let value = self.get_string(key, require)?;
+ value
+ .parse()
+ .map_err(|source| {
+ self.errors.push(AttrError::ParseInt {
+ key: key.to_owned(),
+ source,
+ })
+ })
+ .ok()
+ }
+
+ /// The base-10 unsigned integer under the given key. Unlike Rust's parser,
+ /// Go's `strconv.ParseUint` rejects a leading `+`.
+ pub fn get_uint64(&mut self, key: &str, require: bool) -> Option<u64> {
+ let value = self.get_string(key, require)?;
+ let digits = if value.starts_with('+') { "" } else { &value };
+ digits
+ .parse()
+ .map_err(|source| {
+ self.errors.push(AttrError::ParseUint {
+ key: key.to_owned(),
+ source,
+ })
+ })
+ .ok()
+ }
+
+ /// The boolean under the given key, in any form Go's `strconv.ParseBool`
+ /// accepts.
+ pub fn get_bool(&mut self, key: &str, require: bool) -> Option<bool> {
+ let value = self.get_string(key, require)?;
+ match value.as_str() {
+ "1" | "t" | "T" | "TRUE" | "true" | "True" => Some(true),
+ "0" | "f" | "F" | "FALSE" | "false" | "False" => Some(false),
+ _ => {
+ self.errors.push(AttrError::ParseBool {
+ key: key.to_owned(),
+ value,
+ });
+ None
+ }
+ }
+ }
+
+ /// The Unix timestamp in seconds under the given key; `None` when it is
+ /// missing, invalid, or 0 (Go returns the zero `time.Time` for 0).
+ pub fn get_unix_time(&mut self, key: &str, require: bool) -> Option<DateTime<Utc>> {
+ let seconds = self.get_int64(key, require)?;
+ if seconds == 0 {
+ return None;
+ }
+ DateTime::from_timestamp(seconds, 0)
+ }
+
+ /// The Unix timestamp in milliseconds under the given key, like
+ /// [`AttrUtility::get_unix_time`].
+ pub fn get_unix_milli(&mut self, key: &str, require: bool) -> Option<DateTime<Utc>> {
+ let milliseconds = self.get_int64(key, require)?;
+ if milliseconds == 0 {
+ return None;
+ }
+ DateTime::from_timestamp_millis(milliseconds)
+ }
+
+ /// The string under the given key, or an empty string.
+ pub fn optional_string(&mut self, key: &str) -> String {
+ self.get_string(key, false).unwrap_or_default()
+ }
+
+ /// The string under the given key. If there's no valid string under the
+ /// key, an error is stored and an empty string is returned.
+ pub fn string(&mut self, key: &str) -> String {
+ self.get_string(key, true).unwrap_or_default()
+ }
+
+ /// The integer under the given key, or 0.
+ pub fn optional_int(&mut self, key: &str) -> i64 {
+ self.get_int64(key, false).unwrap_or_default()
+ }
+
+ /// The integer under the given key, storing an error if it is missing.
+ pub fn int(&mut self, key: &str) -> i64 {
+ self.get_int64(key, true).unwrap_or_default()
+ }
+
+ /// Same as [`AttrUtility::int`]; Go distinguishes `int` and `int64`.
+ pub fn int64(&mut self, key: &str) -> i64 {
+ self.get_int64(key, true).unwrap_or_default()
+ }
+
+ /// The unsigned integer under the given key, storing an error if it is missing.
+ pub fn uint64(&mut self, key: &str) -> u64 {
+ self.get_uint64(key, true).unwrap_or_default()
+ }
+
+ /// The boolean under the given key, or false.
+ pub fn optional_bool(&mut self, key: &str) -> bool {
+ self.get_bool(key, false).unwrap_or_default()
+ }
+
+ /// The boolean under the given key, storing an error if it is missing.
+ pub fn bool(&mut self, key: &str) -> bool {
+ self.get_bool(key, true).unwrap_or_default()
+ }
+
+ /// The Unix time under the given key; `None` when missing, invalid, or 0.
+ pub fn optional_unix_time(&mut self, key: &str) -> Option<DateTime<Utc>> {
+ self.get_unix_time(key, false)
+ }
+
+ /// Like [`AttrUtility::optional_unix_time`], storing an error if it is missing.
+ pub fn unix_time(&mut self, key: &str) -> Option<DateTime<Utc>> {
+ self.get_unix_time(key, true)
+ }
+
+ /// The Unix millisecond time under the given key; `None` when missing,
+ /// invalid, or 0.
+ pub fn optional_unix_milli(&mut self, key: &str) -> Option<DateTime<Utc>> {
+ self.get_unix_milli(key, false)
+ }
+
+ /// Like [`AttrUtility::optional_unix_milli`], storing an error if it is missing.
+ pub fn unix_milli(&mut self, key: &str) -> Option<DateTime<Utc>> {
+ self.get_unix_milli(key, true)
+ }
+
+ /// Whether no errors were stored.
+ pub fn ok(&self) -> bool {
+ self.errors.is_empty()
+ }
+
+ /// The stored errors as one error, if there are any.
+ pub fn error(self) -> Result<(), ErrorList> {
+ if self.errors.is_empty() {
+ Ok(())
+ } else {
+ Err(ErrorList(self.errors))
+ }
+ }
+}
diff --git a/crates/whatsmeow/src/binary/decoder.rs b/crates/whatsmeow/src/binary/decoder.rs
new file mode 100644
index 0000000000..8ce855832c
--- /dev/null
+++ b/crates/whatsmeow/src/binary/decoder.rs
@@ -0,0 +1,344 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+//
+// Ported from whatsmeow binary/decoder.go (MPL-2.0, Copyright (c) Tulir Asokan)
+
+use super::errors::DecodeError;
+use super::node::{AttributeValue, Attrs, Node, NodeContent};
+use super::token;
+use crate::types::{INTEROP_SERVER, Jid, MESSENGER_SERVER, new_ad_jid, new_jid};
+
+pub(super) struct BinaryDecoder<'data> {
+ data: &'data [u8],
+ index: usize,
+}
+
+/// A value Go's `read` returns as `any`.
+enum Value {
+ Empty,
+ Nodes(Vec<Node>),
+ Bytes(Vec<u8>),
+ String(String),
+ Jid(Jid),
+}
+
+impl Value {
+ fn into_string(self) -> Option<String> {
+ match self {
+ Value::String(value) => Some(value),
+ _ => None,
+ }
+ }
+}
+
+impl<'data> BinaryDecoder<'data> {
+ pub(super) fn new(data: &'data [u8]) -> Self {
+ Self { data, index: 0 }
+ }
+
+ pub(super) fn remaining(&self) -> usize {
+ self.data.len() - self.index
+ }
+
+ fn check_eos(&self, length: usize) -> Result<(), DecodeError> {
+ if self.index + length > self.data.len() {
+ return Err(DecodeError::UnexpectedEof);
+ }
+ Ok(())
+ }
+
+ fn read_byte(&mut self) -> Result<u8, DecodeError> {
+ self.check_eos(1)?;
+ let value = self.data[self.index];
+ self.index += 1;
+ Ok(value)
+ }
+
+ fn read_int_n(&mut self, n: usize) -> Result<usize, DecodeError> {
+ self.check_eos(n)?;
+ let value = self.data[self.index..self.index + n]
+ .iter()
+ .fold(0, |accumulator, byte| {
+ (accumulator << 8) | usize::from(*byte)
+ });
+ self.index += n;
+ Ok(value)
+ }
+
+ fn read_int8(&mut self) -> Result<usize, DecodeError> {
+ self.read_int_n(1)
+ }
+
+ fn read_int16(&mut self) -> Result<u16, DecodeError> {
+ self.check_eos(2)?;
+ let value = u16::from_be_bytes([self.data[self.index], self.data[self.index + 1]]);
+ self.index += 2;
+ Ok(value)
+ }
+
+ fn read_int20(&mut self) -> Result<usize, DecodeError> {
+ self.check_eos(3)?;
+ let value = ((usize::from(self.data[self.index]) & 15) << 16)
+ + (usize::from(self.data[self.index + 1]) << 8)
+ + usize::from(self.data[self.index + 2]);
+ self.index += 3;
+ Ok(value)
+ }
+
+ fn read_int32(&mut self) -> Result<usize, DecodeError> {
+ self.read_int_n(4)
+ }
+
+ fn read_packed8(&mut self, tag: u8) -> Result<String, DecodeError> {
+ let start_byte = self.read_byte()?;
+ let mut build = Vec::with_capacity(usize::from(start_byte & 127) * 2);
+ for _ in 0..(start_byte & 127) {
+ let current_byte = self.read_byte()?;
+ build.push(unpack_byte(tag, (current_byte & 0xf0) >> 4)?);
+ build.push(unpack_byte(tag, current_byte & 0x0f)?);
+ }
+ if start_byte >> 7 != 0 {
+ build.pop();
+ }
+ // Every unpacked byte is ASCII (digits, '-', '.', 'A'-'F' or NUL).
+ Ok(build.into_iter().map(char::from).collect())
+ }
+
+ fn read_list_size(&mut self, tag: u8) -> Result<usize, DecodeError> {
+ match tag {
+ token::LIST_EMPTY => Ok(0),
+ token::LIST_8 => self.read_int8(),
+ token::LIST_16 => self.read_int16().map(usize::from),
+ _ => Err(DecodeError::InvalidListSize {
+ tag,
+ position: self.index,
+ }),
+ }
+ }
+
+ fn read(&mut self, as_string: bool) -> Result<Value, DecodeError> {
+ let tag = self.read_byte()?;
+ match tag {
+ token::LIST_EMPTY => Ok(Value::Empty),
+ token::LIST_8 | token::LIST_16 => self.read_list(tag).map(Value::Nodes),
+ token::BINARY_8 => {
+ let size = self.read_int8()?;
+ self.read_bytes_or_string(size, as_string)
+ }
+ token::BINARY_20 => {
+ let size = self.read_int20()?;
+ self.read_bytes_or_string(size, as_string)
+ }
+ token::BINARY_32 => {
+ let size = self.read_int32()?;
+ self.read_bytes_or_string(size, as_string)
+ }
+ token::DICTIONARY_0
+ | token::DICTIONARY_1
+ | token::DICTIONARY_2
+ | token::DICTIONARY_3 => {
+ let dictionary = usize::from(tag - token::DICTIONARY_0);
+ let index = self.read_int8()?;
+ token::get_double_token(dictionary, index)
+ .map(|value| Value::String(value.to_owned()))
+ .ok_or(DecodeError::InvalidDoubleToken { dictionary, index })
+ }
+ token::FB_JID => self.read_fb_jid().map(Value::Jid),
+ token::INTEROP_JID => self.read_interop_jid().map(Value::Jid),
+ token::JID_PAIR => self.read_jid_pair().map(Value::Jid),
+ token::AD_JID => self.read_ad_jid().map(Value::Jid),
+ token::NIBBLE_8 | token::HEX_8 => self.read_packed8(tag).map(Value::String),
+ _ => match token::SINGLE_BYTE_TOKENS.get(usize::from(tag)) {
+ Some(value) => Ok(Value::String((*value).to_owned())),
+ None => Err(DecodeError::InvalidToken {
+ tag,
+ position: self.index,
+ }),
+ },
+ }
+ }
+
+ fn read_jid_pair(&mut self) -> Result<Jid, DecodeError> {
+ let user = self.read(true)?;
+ let server = self.read(true)?;
+ let Value::String(server) = server else {
+ return Err(DecodeError::InvalidJidType("missing JID server".to_owned()));
+ };
+ match user {
+ Value::Empty => Ok(new_jid("", &server)),
+ Value::String(user) => Ok(new_jid(&user, &server)),
+ _ => Err(DecodeError::InvalidJidType(
+ "JID user is not a string".to_owned(),
+ )),
+ }
+ }
+
+ fn read_interop_jid(&mut self) -> Result<Jid, DecodeError> {
+ let user = self.read_jid_user()?;
+ let device = self.read_int16()?;
+ let integrator = self.read_int16()?;
+ let server = self.read(true)?.into_string();
+ if server.as_deref() != Some(INTEROP_SERVER) {
+ return Err(DecodeError::InvalidJidType(format!(
+ "expected {INTEROP_SERVER:?}, got {server:?}"
+ )));
+ }
+ Ok(Jid {
+ user,
+ raw_agent: 0,
+ device,
+ integrator,
+ server: INTEROP_SERVER.to_owned(),
+ })
+ }
+
+ fn read_fb_jid(&mut self) -> Result<Jid, DecodeError> {
+ let user = self.read_jid_user()?;
+ let device = self.read_int16()?;
+ let server = self.read(true)?.into_string();
+ if server.as_deref() != Some(MESSENGER_SERVER) {
+ return Err(DecodeError::InvalidJidType(format!(
+ "expected {MESSENGER_SERVER:?}, got {server:?}"
+ )));
+ }
+ Ok(Jid {
+ user,
+ raw_agent: 0,
+ device,
+ integrator: 0,
+ server: MESSENGER_SERVER.to_owned(),
+ })
+ }
+
+ fn read_ad_jid(&mut self) -> Result<Jid, DecodeError> {
+ let agent = self.read_byte()?;
+ let device = self.read_byte()?;
+ let user = self.read_jid_user()?;
+ Ok(new_ad_jid(&user, agent, device))
+ }
+
+ /// Go asserts `user.(string)` and panics on anything else.
+ fn read_jid_user(&mut self) -> Result<String, DecodeError> {
+ self.read(true)?
+ .into_string()
+ .ok_or_else(|| DecodeError::InvalidJidType("JID user is not a string".to_owned()))
+ }
+
+ fn read_attributes(&mut self, n: usize) -> Result<Attrs, DecodeError> {
+ let mut attributes = Attrs::new();
+ for _ in 0..n {
+ let Value::String(key) = self.read(true)? else {
+ return Err(DecodeError::NonStringKey {
+ position: self.index,
+ });
+ };
+ match self.read(true)? {
+ Value::String(value) => {
+ attributes.insert(key, AttributeValue::String(value));
+ }
+ Value::Jid(jid) => {
+ attributes.insert(key, AttributeValue::Jid(jid));
+ }
+ // Go stores nil, which reads back like a missing attribute.
+ Value::Empty => {}
+ Value::Nodes(_) | Value::Bytes(_) => {
+ return Err(DecodeError::InvalidAttributeValue {
+ key,
+ position: self.index,
+ });
+ }
+ }
+ }
+ Ok(attributes)
+ }
+
+ fn read_list(&mut self, tag: u8) -> Result<Vec<Node>, DecodeError> {
+ let size = self.read_list_size(tag)?;
+ let mut nodes = Vec::with_capacity(size.min(self.remaining()));
+ for _ in 0..size {
+ nodes.push(self.read_node()?);
+ }
+ Ok(nodes)
+ }
+
+ pub(super) fn read_node(&mut self) -> Result<Node, DecodeError> {
+ let size = self.read_byte()?;
+ let list_size = self.read_list_size(size)?;
+
+ let tag = self.read(true)?.into_string().unwrap_or_default();
+ if list_size == 0 || tag.is_empty() {
+ return Err(DecodeError::InvalidNode);
+ }
+
+ let attrs = self.read_attributes((list_size - 1) >> 1)?;
+ if list_size % 2 == 1 {
+ return Ok(Node {
+ tag,
+ attrs,
+ content: None,
+ });
+ }
+
+ let content = match self.read(false)? {
+ Value::Empty => None,
+ Value::Nodes(nodes) => Some(NodeContent::Nodes(nodes)),
+ Value::Bytes(bytes) => Some(NodeContent::Bytes(bytes)),
+ Value::String(value) => Some(NodeContent::String(value)),
+ Value::Jid(jid) => Some(NodeContent::Jid(jid)),
+ };
+ Ok(Node {
+ tag,
+ attrs,
+ content,
+ })
+ }
+
+ fn read_bytes_or_string(
+ &mut self,
+ length: usize,
+ as_string: bool,
+ ) -> Result<Value, DecodeError> {
+ let data = self.read_raw(length)?;
+ if as_string {
+ // Go converts arbitrary bytes to a string without validation.
+ Ok(Value::String(String::from_utf8_lossy(data).into_owned()))
+ } else {
+ Ok(Value::Bytes(data.to_vec()))
+ }
+ }
+
+ fn read_raw(&mut self, length: usize) -> Result<&'data [u8], DecodeError> {
+ self.check_eos(length)?;
+ let value = &self.data[self.index..self.index + length];
+ self.index += length;
+ Ok(value)
+ }
+}
+
+fn unpack_byte(tag: u8, value: u8) -> Result<u8, DecodeError> {
+ let unpacked = if tag == token::NIBBLE_8 {
+ unpack_nibble(value)
+ } else {
+ unpack_hex(value)
+ };
+ unpacked.ok_or(DecodeError::InvalidPackedValue { tag, value })
+}
+
+fn unpack_nibble(value: u8) -> Option<u8> {
+ match value {
+ 0..=9 => Some(b'0' + value),
+ 10 => Some(b'-'),
+ 11 => Some(b'.'),
+ 15 => Some(0),
+ _ => None,
+ }
+}
+
+fn unpack_hex(value: u8) -> Option<u8> {
+ match value {
+ 0..=9 => Some(b'0' + value),
+ 10..=15 => Some(b'A' + value - 10),
+ _ => None,
+ }
+}
diff --git a/crates/whatsmeow/src/binary/encoder.rs b/crates/whatsmeow/src/binary/encoder.rs
new file mode 100644
index 0000000000..33c8dbd2c9
--- /dev/null
+++ b/crates/whatsmeow/src/binary/encoder.rs
@@ -0,0 +1,286 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+//
+// Ported from whatsmeow binary/encoder.go (MPL-2.0, Copyright (c) Tulir Asokan)
+
+use super::errors::EncodeError;
+use super::node::{AttributeValue, Attrs, Node, NodeContent};
+use super::token;
+use crate::types::{
+ DEFAULT_USER_SERVER, HIDDEN_USER_SERVER, HOSTED_LID_SERVER, HOSTED_SERVER, INTEROP_SERVER, Jid,
+ MESSENGER_SERVER,
+};
+
+const TAG_SIZE: usize = 1;
+const MAX_INT32: usize = 0x7fff_ffff;
+
+pub(super) struct BinaryEncoder {
+ data: Vec<u8>,
+}
+
+/// A value Go's `write(data any)` accepts.
+enum Writable<'value> {
+ Jid(&'value Jid),
+ String(&'value str),
+ Bytes(&'value [u8]),
+ Nodes(&'value [Node]),
+}
+
+impl BinaryEncoder {
+ pub(super) fn new() -> Self {
+ Self { data: vec![0] }
+ }
+
+ pub(super) fn get_data(self) -> Vec<u8> {
+ self.data
+ }
+
+ fn push_byte(&mut self, value: u8) {
+ self.data.push(value);
+ }
+
+ fn push_bytes(&mut self, bytes: &[u8]) {
+ self.data.extend_from_slice(bytes);
+ }
+
+ fn push_int20(&mut self, value: u32) {
+ let [_, high, middle, low] = value.to_be_bytes();
+ self.push_bytes(&[high & 0x0f, middle, low]);
+ }
+
+ fn push_int8(&mut self, value: u8) {
+ self.push_byte(value);
+ }
+
+ fn push_int16(&mut self, value: u16) {
+ self.push_bytes(&value.to_be_bytes());
+ }
+
+ fn push_int32(&mut self, value: u32) {
+ self.push_bytes(&value.to_be_bytes());
+ }
+
+ fn push_string(&mut self, value: &str) {
+ self.push_bytes(value.as_bytes());
+ }
+
+ fn write_byte_length(&mut self, length: usize) -> Result<(), EncodeError> {
+ if let Ok(short) = u8::try_from(length) {
+ self.push_byte(token::BINARY_8);
+ self.push_int8(short);
+ } else if length < (1 << 20) {
+ self.push_byte(token::BINARY_20);
+ self.push_int20(
+ u32::try_from(length).map_err(|_| EncodeError::LengthTooLarge(length))?,
+ );
+ } else if length < MAX_INT32 {
+ self.push_byte(token::BINARY_32);
+ self.push_int32(
+ u32::try_from(length).map_err(|_| EncodeError::LengthTooLarge(length))?,
+ );
+ } else {
+ return Err(EncodeError::LengthTooLarge(length));
+ }
+ Ok(())
+ }
+
+ pub(super) fn write_node(&mut self, node: &Node) -> Result<(), EncodeError> {
+ if node.tag == "0" {
+ self.push_byte(token::LIST_8);
+ self.push_byte(token::LIST_EMPTY);
+ return Ok(());
+ }
+
+ let has_content = usize::from(node.content.is_some());
+ self.write_list_start(2 * count_attributes(&node.attrs) + TAG_SIZE + has_content)?;
+ self.write_string(&node.tag)?;
+ self.write_attributes(&node.attrs)?;
+ match &node.content {
+ Some(NodeContent::Nodes(nodes)) => self.write(Writable::Nodes(nodes)),
+ Some(NodeContent::Bytes(bytes)) => self.write(Writable::Bytes(bytes)),
+ Some(NodeContent::String(value)) => self.write(Writable::String(value)),
+ Some(NodeContent::Jid(jid)) => self.write(Writable::Jid(jid)),
+ None => Ok(()),
+ }
+ }
+
+ fn write(&mut self, data: Writable<'_>) -> Result<(), EncodeError> {
+ match data {
+ Writable::Jid(jid) => self.write_jid(jid),
+ Writable::String(value) => self.write_string(value),
+ Writable::Bytes(bytes) => self.write_bytes(bytes),
+ Writable::Nodes(nodes) => {
+ self.write_list_start(nodes.len())?;
+ for node in nodes {
+ self.write_node(node)?;
+ }
+ Ok(())
+ }
+ }
+ }
+
+ fn write_string(&mut self, data: &str) -> Result<(), EncodeError> {
+ if let Some(token_index) = token::index_of_single_token(data) {
+ self.push_byte(token_index);
+ } else if let Some((dictionary_index, token_index)) =
+ token::index_of_double_byte_token(data)
+ {
+ self.push_byte(token::DICTIONARY_0 + dictionary_index);
+ self.push_byte(token_index);
+ } else if validate_nibble(data) {
+ self.write_packed_bytes(data, token::NIBBLE_8);
+ } else if validate_hex(data) {
+ self.write_packed_bytes(data, token::HEX_8);
+ } else {
+ self.write_string_raw(data)?;
+ }
+ Ok(())
+ }
+
+ fn write_bytes(&mut self, value: &[u8]) -> Result<(), EncodeError> {
+ self.write_byte_length(value.len())?;
+ self.push_bytes(value);
+ Ok(())
+ }
+
+ fn write_string_raw(&mut self, value: &str) -> Result<(), EncodeError> {
+ self.write_byte_length(value.len())?;
+ self.push_string(value);
+ Ok(())
+ }
+
+ fn write_jid(&mut self, jid: &Jid) -> Result<(), EncodeError> {
+ let server = jid.server.as_str();
+ if ((server == DEFAULT_USER_SERVER || server == HIDDEN_USER_SERVER) && jid.device > 0)
+ || server == HOSTED_SERVER
+ || server == HOSTED_LID_SERVER
+ {
+ self.push_byte(token::AD_JID);
+ self.push_byte(jid.actual_agent());
+ self.push_byte(
+ u8::try_from(jid.device).map_err(|_| EncodeError::DeviceOutOfRange(jid.device))?,
+ );
+ self.write_string(&jid.user)?;
+ } else if server == MESSENGER_SERVER {
+ self.push_byte(token::FB_JID);
+ self.write(Writable::String(&jid.user))?;
+ self.push_int16(jid.device);
+ self.write(Writable::String(server))?;
+ } else if server == INTEROP_SERVER {
+ self.push_byte(token::INTEROP_JID);
+ self.write(Writable::String(&jid.user))?;
+ self.push_int16(jid.device);
+ self.push_int16(jid.integrator);
+ self.write(Writable::String(server))?;
+ } else {
+ self.push_byte(token::JID_PAIR);
+ if jid.user.is_empty() {
+ self.push_byte(token::LIST_EMPTY);
+ } else {
+ self.write(Writable::String(&jid.user))?;
+ }
+ self.write(Writable::String(server))?;
+ }
+ Ok(())
+ }
+
+ fn write_attributes(&mut self, attributes: &Attrs) -> Result<(), EncodeError> {
+ for (key, value) in attributes {
+ if value.is_empty_string() {
+ continue;
+ }
+ self.write_string(key)?;
+ match value {
+ AttributeValue::String(value) => self.write(Writable::String(value))?,
+ AttributeValue::Jid(jid) => self.write(Writable::Jid(jid))?,
+ }
+ }
+ Ok(())
+ }
+
+ fn write_list_start(&mut self, list_size: usize) -> Result<(), EncodeError> {
+ if list_size == 0 {
+ self.push_byte(token::LIST_EMPTY);
+ } else if let Ok(short) = u8::try_from(list_size) {
+ self.push_byte(token::LIST_8);
+ self.push_int8(short);
+ } else {
+ self.push_byte(token::LIST_16);
+ self.push_int16(
+ u16::try_from(list_size).map_err(|_| EncodeError::ListTooLarge(list_size))?,
+ );
+ }
+ Ok(())
+ }
+
+ /// Packs a string that [`validate_nibble`] or [`validate_hex`] accepted,
+ /// so it is at most [`token::PACKED_MAX`] bytes of known characters.
+ fn write_packed_bytes(&mut self, value: &str, data_type: u8) {
+ let packer = if data_type == token::NIBBLE_8 {
+ pack_nibble
+ } else {
+ pack_hex
+ };
+ self.push_byte(data_type);
+
+ let bytes = value.as_bytes();
+ // PACKED_MAX (127) halved and rounded up fits in the low seven bits.
+ let mut rounded_length = u8::try_from(bytes.len().div_ceil(2)).unwrap_or(u8::MAX);
+ if !bytes.len().is_multiple_of(2) {
+ rounded_length |= 128;
+ }
+ self.push_byte(rounded_length);
+ let mut pairs = bytes.chunks_exact(2);
+ for pair in pairs.by_ref() {
+ self.push_byte(pack_byte_pair(packer, pair[0], pair[1]));
+ }
+ if let [last] = pairs.remainder() {
+ self.push_byte(pack_byte_pair(packer, *last, 0));
+ }
+ }
+}
+
+fn count_attributes(attributes: &Attrs) -> usize {
+ attributes
+ .values()
+ .filter(|value| !value.is_empty_string())
+ .count()
+}
+
+fn pack_byte_pair(packer: fn(u8) -> u8, part1: u8, part2: u8) -> u8 {
+ (packer(part1) << 4) | packer(part2)
+}
+
+fn validate_nibble(value: &str) -> bool {
+ value.len() <= token::PACKED_MAX
+ && value
+ .bytes()
+ .all(|char| char.is_ascii_digit() || char == b'-' || char == b'.')
+}
+
+/// Only called with characters [`validate_nibble`] accepted, or the 0 padding.
+fn pack_nibble(value: u8) -> u8 {
+ match value {
+ b'-' => 10,
+ b'.' => 11,
+ 0 => 15,
+ _ => value - b'0',
+ }
+}
+
+fn validate_hex(value: &str) -> bool {
+ value.len() <= token::PACKED_MAX
+ && value
+ .bytes()
+ .all(|char| char.is_ascii_digit() || (b'A'..=b'F').contains(&char))
+}
+
+/// Only called with characters [`validate_hex`] accepted, or the 0 padding.
+fn pack_hex(value: u8) -> u8 {
+ match value {
+ b'0'..=b'9' => value - b'0',
+ b'A'..=b'F' => 10 + value - b'A',
+ _ => 15,
+ }
+}
diff --git a/crates/whatsmeow/src/binary/errors.rs b/crates/whatsmeow/src/binary/errors.rs
new file mode 100644
index 0000000000..40f1be08af
--- /dev/null
+++ b/crates/whatsmeow/src/binary/errors.rs
@@ -0,0 +1,96 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+//
+// Ported from whatsmeow binary/errors.go (MPL-2.0, Copyright (c) Tulir Asokan)
+
+/// Errors returned by the binary XML decoder.
+///
+/// Go has sentinel errors (`ErrInvalidType`, `ErrInvalidJIDType`,
+/// `ErrInvalidNode`, `ErrInvalidToken`, `ErrNonStringKey`) wrapped with
+/// formatted context; each wrapping is a variant here. Inputs on which the Go
+/// decoder panics (failed type assertions) are errors too.
+#[derive(Debug, thiserror::Error, PartialEq, Eq)]
+pub enum DecodeError {
+ /// The input ended in the middle of a value (Go's `io.EOF`).
+ #[error("unexpected end of binary XML data")]
+ UnexpectedEof,
+ /// A byte that isn't a known token or type tag.
+ #[error("invalid token with tag {tag} at position {position}")]
+ InvalidToken {
+ /// The tag byte.
+ tag: u8,
+ /// The decoder position after reading it.
+ position: usize,
+ },
+ /// A double-byte token index outside the dictionaries.
+ #[error("index out of double byte token bounds {dictionary}-{index}")]
+ InvalidDoubleToken {
+ /// The dictionary number.
+ dictionary: usize,
+ /// The token index in the dictionary.
+ index: usize,
+ },
+ /// A list size with a tag that isn't a list tag.
+ #[error("readListSize with unknown tag {tag} at position {position}")]
+ InvalidListSize {
+ /// The tag byte.
+ tag: u8,
+ /// The decoder position.
+ position: usize,
+ },
+ /// A nibble or hex packed value that isn't valid for its packing.
+ #[error("invalid packed value {value} for tag {tag}")]
+ InvalidPackedValue {
+ /// The packing tag ([`super::token::NIBBLE_8`] or [`super::token::HEX_8`]).
+ tag: u8,
+ /// The four-bit value.
+ value: u8,
+ },
+ /// A JID with a missing or wrongly typed part.
+ #[error("invalid JID type: {0}")]
+ InvalidJidType(String),
+ /// A node with no tag or an empty list header.
+ #[error("invalid node")]
+ InvalidNode,
+ /// An attribute key that decoded to something other than a string.
+ #[error("non-string key at position {position}")]
+ NonStringKey {
+ /// The decoder position.
+ position: usize,
+ },
+ /// An attribute value that is a list of nodes or raw bytes, which the port
+ /// can't store as an attribute.
+ #[error("unsupported attribute value type for {key:?} at position {position}")]
+ InvalidAttributeValue {
+ /// The attribute key.
+ key: String,
+ /// The decoder position.
+ position: usize,
+ },
+ /// Data after the end of the root node.
+ #[error("{0} leftover bytes after decoding")]
+ LeftoverBytes(usize),
+ /// [`super::unpack`] got no data at all.
+ #[error("no data to unpack")]
+ EmptyPayload,
+ /// [`super::unpack`] couldn't inflate the zlib payload.
+ #[error("failed to decompress zlib payload: {0}")]
+ Decompress(String),
+}
+
+/// Errors returned by the binary XML encoder. Go panics in these cases.
+#[derive(Debug, thiserror::Error, PartialEq, Eq)]
+pub enum EncodeError {
+ /// Binary data at or over `math.MaxInt32` bytes.
+ #[error("length is too large: {0}")]
+ LengthTooLarge(usize),
+ /// A list with more entries than a two-byte length can hold. Go silently
+ /// truncates the length.
+ #[error("list is too large: {0}")]
+ ListTooLarge(usize),
+ /// An AD JID device number that doesn't fit the one-byte device field. Go
+ /// silently truncates it.
+ #[error("device {0} doesn't fit in an AD JID")]
+ DeviceOutOfRange(u16),
+}
diff --git a/crates/whatsmeow/src/binary/node.rs b/crates/whatsmeow/src/binary/node.rs
new file mode 100644
index 0000000000..c0f18a9611
--- /dev/null
+++ b/crates/whatsmeow/src/binary/node.rs
@@ -0,0 +1,190 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+//
+// Ported from whatsmeow binary/node.go (MPL-2.0, Copyright (c) Tulir Asokan)
+
+use std::collections::BTreeMap;
+use std::fmt;
+
+use super::decoder::BinaryDecoder;
+use super::encoder::BinaryEncoder;
+use super::errors::{DecodeError, EncodeError};
+use crate::types::Jid;
+
+/// The attributes of an XML element ([`Node`]).
+///
+/// Go uses an unordered map; a sorted map keeps encoding deterministic, which
+/// WhatsApp doesn't care about either way.
+pub type Attrs = BTreeMap<String, AttributeValue>;
+
+/// The value of one attribute. Go stores `any` here; on the wire every value is
+/// either a string or a JID, so numbers and booleans become strings when they
+/// are put in (as Go's encoder formats them).
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub enum AttributeValue {
+ /// A string value.
+ String(String),
+ /// A JID value.
+ Jid(Jid),
+}
+
+impl AttributeValue {
+ /// Whether Go's encoder would skip the value (it skips `""` and `nil`).
+ pub(super) fn is_empty_string(&self) -> bool {
+ matches!(self, AttributeValue::String(value) if value.is_empty())
+ }
+}
+
+impl fmt::Display for AttributeValue {
+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
+ match self {
+ AttributeValue::String(value) => formatter.write_str(value),
+ AttributeValue::Jid(jid) => jid.fmt(formatter),
+ }
+ }
+}
+
+impl From<String> for AttributeValue {
+ fn from(value: String) -> Self {
+ AttributeValue::String(value)
+ }
+}
+
+impl From<&str> for AttributeValue {
+ fn from(value: &str) -> Self {
+ AttributeValue::String(value.to_owned())
+ }
+}
+
+impl From<Jid> for AttributeValue {
+ fn from(value: Jid) -> Self {
+ AttributeValue::Jid(value)
+ }
+}
+
+impl From<&Jid> for AttributeValue {
+ fn from(value: &Jid) -> Self {
+ AttributeValue::Jid(value.clone())
+ }
+}
+
+impl From<i64> for AttributeValue {
+ fn from(value: i64) -> Self {
+ AttributeValue::String(value.to_string())
+ }
+}
+
+impl From<u64> for AttributeValue {
+ fn from(value: u64) -> Self {
+ AttributeValue::String(value.to_string())
+ }
+}
+
+impl From<i32> for AttributeValue {
+ fn from(value: i32) -> Self {
+ AttributeValue::String(value.to_string())
+ }
+}
+
+impl From<u32> for AttributeValue {
+ fn from(value: u32) -> Self {
+ AttributeValue::String(value.to_string())
+ }
+}
+
+impl From<bool> for AttributeValue {
+ fn from(value: bool) -> Self {
+ AttributeValue::String(value.to_string())
+ }
+}
+
+/// The content inside an element. Go stores `any`: a list of nodes, a byte
+/// array, or (from the decoder) a string or JID token.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub enum NodeContent {
+ /// Child elements.
+ Nodes(Vec<Node>),
+ /// Binary data.
+ Bytes(Vec<u8>),
+ /// A string, encoded like an attribute value.
+ String(String),
+ /// A JID, encoded like an attribute value.
+ Jid(Jid),
+}
+
+/// An XML element.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct Node {
+ /// The tag of the element.
+ pub tag: String,
+ /// The attributes of the element.
+ pub attrs: Attrs,
+ /// The content inside the element.
+ pub content: Option<NodeContent>,
+}
+
+static EMPTY_NODE: Node = Node {
+ tag: String::new(),
+ attrs: BTreeMap::new(),
+ content: None,
+};
+
+impl Node {
+ /// The content of the node as a list of nodes. If the content is not a
+ /// list of nodes, this is empty.
+ pub fn get_children(&self) -> &[Node] {
+ match &self.content {
+ Some(NodeContent::Nodes(children)) => children,
+ _ => &[],
+ }
+ }
+
+ /// The same list as [`Node::get_children`], filtered by tag.
+ pub fn get_children_by_tag<'node>(
+ &'node self,
+ tag: &'node str,
+ ) -> impl Iterator<Item = &'node Node> {
+ self.get_children()
+ .iter()
+ .filter(move |child| child.tag == tag)
+ }
+
+ /// Finds the first child with the given tag. Each provided tag recurses
+ /// in, so this is useful for getting a specific nested element.
+ pub fn get_optional_child_by_tag(&self, tags: &[&str]) -> Option<&Node> {
+ let mut node = self;
+ for tag in tags {
+ node = node.get_children().iter().find(|child| child.tag == *tag)?;
+ }
+ Some(node)
+ }
+
+ /// Like [`Node::get_optional_child_by_tag`], but returns an empty node
+ /// when there's no match, as Go returns the zero `Node`.
+ pub fn get_child_by_tag(&self, tags: &[&str]) -> &Node {
+ self.get_optional_child_by_tag(tags).unwrap_or(&EMPTY_NODE)
+ }
+}
+
+/// Encodes an XML element into WhatsApp's binary XML representation, with the
+/// leading flags byte (0, meaning uncompressed).
+///
+/// Go panics on values it can't encode; the port returns them as errors.
+pub fn marshal(node: &Node) -> Result<Vec<u8>, EncodeError> {
+ let mut encoder = BinaryEncoder::new();
+ encoder.write_node(node)?;
+ Ok(encoder.get_data())
+}
+
+/// Decodes WhatsApp's binary XML representation (without the flags byte; see
+/// [`super::unpack`]) into a node.
+pub fn unmarshal(data: &[u8]) -> Result<Node, DecodeError> {
+ let mut decoder = BinaryDecoder::new(data);
+ let node = decoder.read_node()?;
+ let leftover = decoder.remaining();
+ if leftover != 0 {
+ return Err(DecodeError::LeftoverBytes(leftover));
+ }
+ Ok(node)
+}
diff --git a/crates/whatsmeow/src/binary/test.rs b/crates/whatsmeow/src/binary/test.rs
new file mode 100644
index 0000000000..df660742ed
--- /dev/null
+++ b/crates/whatsmeow/src/binary/test.rs
@@ -0,0 +1,616 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+//! whatsmeow has no tests for the binary package. The expected bytes and XML
+//! strings below were produced by whatsmeow's Go code at the pinned revision
+//! (`binary.Marshal` and `Node.String`), so these tests check the port
+//! against the original byte for byte.
+
+use super::*;
+use crate::types::{
+ DEFAULT_USER_SERVER, GROUP_SERVER, HIDDEN_USER_SERVER, HOSTED_LID_SERVER, HOSTED_SERVER,
+ INTEROP_SERVER, Jid, MESSENGER_SERVER, SERVER_JID, new_jid,
+};
+
+fn hex_bytes(text: &str) -> Vec<u8> {
+ hex::decode(text).expect("test vectors are valid hex")
+}
+
+fn node_with_attribute(tag: &str, key: &str, value: AttributeValue) -> Node {
+ Node {
+ tag: tag.to_owned(),
+ attrs: Attrs::from([(key.to_owned(), value)]),
+ content: None,
+ }
+}
+
+#[test]
+fn marshal_matches_go_for_attribute_encodings() {
+ let cases = [
+ (
+ Node {
+ tag: "iq".to_owned(),
+ ..Node::default()
+ },
+ "00f80119",
+ ),
+ (
+ node_with_attribute("iq", "type", "result".into()),
+ "00f803190414",
+ ),
+ (
+ node_with_attribute("receipt", "class", "read-self".into()),
+ "00f8030715ec00",
+ ),
+ (
+ node_with_attribute("iq", "id", "1234-56.789".into()),
+ "00f8031908ff861234a56b789f",
+ ),
+ (
+ node_with_attribute("iq", "id", "123".into()),
+ "00f8031908ff82123f",
+ ),
+ (
+ node_with_attribute("iq", "id", "3EB0ABCDEF12".into()),
+ "00f8031908fb063eb0abcdef12",
+ ),
+ (
+ node_with_attribute("iq", "id", "hello world".into()),
+ "00f8031908fc0b68656c6c6f20776f726c64",
+ ),
+ (
+ node_with_attribute("iq", "t", 1_700_000_000_i64.into()),
+ "00f803191aff051700000000",
+ ),
+ (
+ node_with_attribute("iq", "x", true.into()),
+ "00f80319fc01789b",
+ ),
+ (node_with_attribute("iq", "x", "".into()), "00f80119"),
+ (
+ Node {
+ tag: "frobnicate".to_owned(),
+ ..Node::default()
+ },
+ "00f801fc0a66726f626e6963617465",
+ ),
+ (
+ Node {
+ tag: "0".to_owned(),
+ ..Node::default()
+ },
+ "00f800",
+ ),
+ ];
+ for (node, expected) in cases {
+ assert_eq!(hex::encode(marshal(&node).unwrap()), expected, "{node}");
+ }
+}
+
+#[test]
+fn marshal_matches_go_for_jid_encodings() {
+ let cases = [
+ (
+ new_jid("1234567890", DEFAULT_USER_SERVER),
+ "00f8031311faff05123456789003",
+ ),
+ (SERVER_JID.clone(), "00f8031911fa0003"),
+ (
+ Jid {
+ user: "1234567890".to_owned(),
+ device: 12,
+ server: DEFAULT_USER_SERVER.to_owned(),
+ ..Jid::default()
+ },
+ "00f8031311f7000cff051234567890",
+ ),
+ (
+ Jid {
+ user: "98765432101234".to_owned(),
+ device: 3,
+ server: HIDDEN_USER_SERVER.to_owned(),
+ ..Jid::default()
+ },
+ "00f8031311f70103ff0798765432101234",
+ ),
+ (
+ Jid {
+ user: "1234567890".to_owned(),
+ device: 99,
+ server: HOSTED_SERVER.to_owned(),
+ ..Jid::default()
+ },
+ "00f8031311f78063ff051234567890",
+ ),
+ (
+ Jid {
+ user: "98765432101234".to_owned(),
+ device: 99,
+ server: HOSTED_LID_SERVER.to_owned(),
+ ..Jid::default()
+ },
+ "00f8031311f78163ff0798765432101234",
+ ),
+ (
+ new_jid("98765432101234", HIDDEN_USER_SERVER),
+ "00f8031311faff079876543210123476",
+ ),
+ (
+ Jid {
+ user: "100001234567890".to_owned(),
+ device: 7,
+ server: MESSENGER_SERVER.to_owned(),
+ ..Jid::default()
+ },
+ "00f8031311f6ff88100001234567890f0007cc",
+ ),
+ (
+ Jid {
+ user: "1234567890".to_owned(),
+ device: 2,
+ integrator: 300,
+ server: INTEROP_SERVER.to_owned(),
+ ..Jid::default()
+ },
+ "00f8031311f5ff0512345678900002012cfc07696e7465726f70",
+ ),
+ (
+ new_jid("120363012345678901", GROUP_SERVER),
+ "00f8031311faff091203630123456789011c",
+ ),
+ ];
+ for (jid, expected) in cases {
+ let tag = if jid == *SERVER_JID { "iq" } else { "message" };
+ let node = node_with_attribute(tag, "to", jid.clone().into());
+ let encoded = marshal(&node).unwrap();
+ assert_eq!(hex::encode(&encoded), expected, "{jid}");
+ assert_eq!(unmarshal(&encoded[1..]).unwrap(), node, "{jid}");
+ }
+}
+
+#[test]
+fn marshal_matches_go_for_content_encodings() {
+ let cases = [
+ (
+ Node {
+ tag: "enc".to_owned(),
+ attrs: Attrs::new(),
+ content: Some(NodeContent::Bytes(vec![0, 1, 2, 3, 0xff])),
+ },
+ "00f8021dfc0500010203ff",
+ ),
+ (
+ Node {
+ tag: "body".to_owned(),
+ attrs: Attrs::new(),
+ content: Some(NodeContent::String("plain text".to_owned())),
+ },
+ "00f802ed75fc0a706c61696e2074657874",
+ ),
+ (
+ Node {
+ tag: "body".to_owned(),
+ attrs: Attrs::new(),
+ content: Some(NodeContent::String("notification".to_owned())),
+ },
+ "00f802ed7509",
+ ),
+ (
+ Node {
+ tag: "body".to_owned(),
+ attrs: Attrs::new(),
+ content: Some(NodeContent::Jid(new_jid("1234567890", DEFAULT_USER_SERVER))),
+ },
+ "00f802ed75faff05123456789003",
+ ),
+ (
+ Node {
+ tag: "iq".to_owned(),
+ attrs: Attrs::from([("id".to_owned(), "abc".into())]),
+ content: Some(NodeContent::Nodes(vec![
+ Node {
+ tag: "ping".to_owned(),
+ ..Node::default()
+ },
+ Node {
+ tag: "list".to_owned(),
+ attrs: Attrs::new(),
+ content: Some(NodeContent::Nodes(vec![Node {
+ tag: "user".to_owned(),
+ attrs: Attrs::from([(
+ "jid".to_owned(),
+ new_jid("1234567890", DEFAULT_USER_SERVER).into(),
+ )]),
+ content: None,
+ }])),
+ },
+ ])),
+ },
+ "00f8041908fc03616263f802f80156f80271f801f8030e0cfaff05123456789003",
+ ),
+ (
+ Node {
+ tag: "iq".to_owned(),
+ attrs: Attrs::new(),
+ content: Some(NodeContent::Nodes(Vec::new())),
+ },
+ "00f8021900",
+ ),
+ ];
+ for (node, expected) in cases {
+ assert_eq!(hex::encode(marshal(&node).unwrap()), expected, "{node}");
+ }
+}
+
+#[test]
+fn marshal_matches_go_for_length_prefixes() {
+ let bytes_300 = marshal(&Node {
+ tag: "enc".to_owned(),
+ attrs: Attrs::new(),
+ content: Some(NodeContent::Bytes(vec![0xab; 300])),
+ })
+ .unwrap();
+ assert_eq!(hex::encode(&bytes_300[..8]), "00f8021dfd00012c");
+ assert_eq!(bytes_300.len(), 8 + 300);
+
+ let bytes_70000 = marshal(&Node {
+ tag: "enc".to_owned(),
+ attrs: Attrs::new(),
+ content: Some(NodeContent::Bytes(vec![1; 70_000])),
+ })
+ .unwrap();
+ assert_eq!(hex::encode(&bytes_70000[..12]), "00f8021dfd01117001010101");
+
+ let bytes_1_mebibyte = marshal(&Node {
+ tag: "enc".to_owned(),
+ attrs: Attrs::new(),
+ content: Some(NodeContent::Bytes(vec![1; 1 << 20])),
+ })
+ .unwrap();
+ assert_eq!(
+ hex::encode(&bytes_1_mebibyte[..12]),
+ "00f8021dfe00100000010101"
+ );
+
+ let list_300 = marshal(&Node {
+ tag: "list".to_owned(),
+ attrs: Attrs::new(),
+ content: Some(NodeContent::Nodes(vec![
+ Node {
+ tag: "item".to_owned(),
+ ..Node::default()
+ };
+ 300
+ ])),
+ })
+ .unwrap();
+ assert_eq!(hex::encode(&list_300[..12]), "00f80271f9012cf8013ff801");
+}
+
+#[test]
+fn marshal_rejects_lists_go_would_truncate() {
+ let node = Node {
+ tag: "list".to_owned(),
+ attrs: Attrs::new(),
+ content: Some(NodeContent::Nodes(vec![Node::default(); 70_000])),
+ };
+ assert_eq!(marshal(&node), Err(EncodeError::ListTooLarge(70_000)));
+
+ let device_too_large = node_with_attribute(
+ "message",
+ "to",
+ Jid {
+ user: "1".to_owned(),
+ device: 300,
+ server: DEFAULT_USER_SERVER.to_owned(),
+ ..Jid::default()
+ }
+ .into(),
+ );
+ assert_eq!(
+ marshal(&device_too_large),
+ Err(EncodeError::DeviceOutOfRange(300))
+ );
+}
+
+#[test]
+fn unmarshal_decodes_go_encodings() {
+ let decoded = unmarshal(&hex_bytes(
+ "f8041908fc03616263f802f80156f80271f801f8030e0cfaff05123456789003",
+ ))
+ .unwrap();
+ assert_eq!(
+ decoded,
+ Node {
+ tag: "iq".to_owned(),
+ attrs: Attrs::from([("id".to_owned(), "abc".into())]),
+ content: Some(NodeContent::Nodes(vec![
+ Node {
+ tag: "ping".to_owned(),
+ ..Node::default()
+ },
+ Node {
+ tag: "list".to_owned(),
+ attrs: Attrs::new(),
+ content: Some(NodeContent::Nodes(vec![Node {
+ tag: "user".to_owned(),
+ attrs: Attrs::from([(
+ "jid".to_owned(),
+ new_jid("1234567890", DEFAULT_USER_SERVER).into(),
+ )]),
+ content: None,
+ }])),
+ },
+ ])),
+ }
+ );
+
+ // Binary content decodes as bytes even when it was encoded from a string,
+ // and packed or token content decodes as a string.
+ assert_eq!(
+ unmarshal(&hex_bytes("f802ed75fc0a706c61696e2074657874"))
+ .unwrap()
+ .content,
+ Some(NodeContent::Bytes(b"plain text".to_vec()))
+ );
+ assert_eq!(
+ unmarshal(&hex_bytes("f802ed7509")).unwrap().content,
+ Some(NodeContent::String("notification".to_owned()))
+ );
+ assert_eq!(
+ unmarshal(&hex_bytes("f8031908ff82123f")).unwrap().attrs,
+ Attrs::from([("id".to_owned(), "123".into())])
+ );
+ assert_eq!(
+ unmarshal(&hex_bytes("f8031908fb063eb0abcdef12"))
+ .unwrap()
+ .attrs,
+ Attrs::from([("id".to_owned(), "3EB0ABCDEF12".into())])
+ );
+ // The double-byte token "read-self" in dictionary 0.
+ assert_eq!(
+ unmarshal(&hex_bytes("f8030715ec00")).unwrap(),
+ node_with_attribute("receipt", "class", "read-self".into())
+ );
+}
+
+#[test]
+fn unmarshal_rejects_malformed_input() {
+ assert_eq!(unmarshal(&[]), Err(DecodeError::UnexpectedEof));
+ // A list header promising three items with only the tag present.
+ assert_eq!(
+ unmarshal(&hex_bytes("f80319")),
+ Err(DecodeError::UnexpectedEof)
+ );
+ assert_eq!(
+ unmarshal(&hex_bytes("f80000")),
+ Err(DecodeError::InvalidNode)
+ );
+ assert_eq!(
+ unmarshal(&hex_bytes("1900")),
+ Err(DecodeError::InvalidListSize {
+ tag: 0x19,
+ position: 1
+ })
+ );
+ // Tag 240 is between the dictionaries and the JID types.
+ assert_eq!(
+ unmarshal(&hex_bytes("f801f0")),
+ Err(DecodeError::InvalidToken {
+ tag: 0xf0,
+ position: 3
+ })
+ );
+ // Nibble value 12 has no meaning.
+ assert_eq!(
+ unmarshal(&hex_bytes("f801ff01c0")),
+ Err(DecodeError::InvalidPackedValue {
+ tag: token::NIBBLE_8,
+ value: 12
+ })
+ );
+ // An attribute key that is a JID.
+ assert_eq!(
+ unmarshal(&hex_bytes("f80319fa0003fa0003")),
+ Err(DecodeError::NonStringKey { position: 6 })
+ );
+ // A messenger JID whose server isn't "msgr".
+ assert!(matches!(
+ unmarshal(&hex_bytes(
+ "f8031311f6ff81100007 03".replace(' ', "").as_str()
+ )),
+ Err(DecodeError::InvalidJidType(_))
+ ));
+ assert_eq!(
+ unmarshal(&hex_bytes("f8011900")),
+ Err(DecodeError::LeftoverBytes(1))
+ );
+}
+
+#[test]
+fn node_string_matches_go() {
+ let iq = Node {
+ tag: "iq".to_owned(),
+ attrs: Attrs::from([
+ ("id".to_owned(), "abc".into()),
+ ("type".to_owned(), "get".into()),
+ ("to".to_owned(), SERVER_JID.clone().into()),
+ ]),
+ content: Some(NodeContent::Nodes(vec![Node {
+ tag: "ping".to_owned(),
+ ..Node::default()
+ }])),
+ };
+ assert_eq!(
+ iq.to_string(),
+ r#"<iq id="abc" to="s.whatsapp.net" type="get"><ping/></iq>"#
+ );
+ assert_eq!(
+ iq.indented_string(),
+ r#"<iq id="abc" to="s.whatsapp.net" type="get"><ping/></iq>"#
+ );
+
+ let bytes = |content: Vec<u8>| Node {
+ tag: "enc".to_owned(),
+ attrs: Attrs::new(),
+ content: Some(NodeContent::Bytes(content)),
+ };
+ assert_eq!(
+ bytes(vec![0, 1, 2, 3, 0xff]).to_string(),
+ "<enc>00010203ff</enc>"
+ );
+ assert_eq!(
+ bytes(vec![0xab; 200]).to_string(),
+ "<enc><!-- 200 bytes --></enc>"
+ );
+ assert_eq!(
+ bytes(b"plain text".to_vec()).to_string(),
+ "<enc>plain text</enc>"
+ );
+ // A newline isn't printable, so the bytes print as hex.
+ assert_eq!(
+ bytes(b"hello\nworld".to_vec()).to_string(),
+ "<enc>68656c6c6f0a776f726c64</enc>"
+ );
+ assert_eq!(
+ bytes(vec![0xab; 100]).indented_string(),
+ "<enc>\n abababababababababababababababababababababababababababababababababababababababab\n abababababababababababababababababababababababababababababababababababababababab\n abababababababababababababababababababab\n</enc>"
+ );
+ assert_eq!(
+ Node {
+ tag: "body".to_owned(),
+ attrs: Attrs::new(),
+ content: Some(NodeContent::String("a\nb".to_owned())),
+ }
+ .to_string(),
+ r"<body>a\nb</body>"
+ );
+ assert_eq!(
+ Node {
+ tag: "message".to_owned(),
+ attrs: Attrs::from([(
+ "to".to_owned(),
+ Jid {
+ user: "1234567890".to_owned(),
+ device: 2,
+ integrator: 300,
+ server: INTEROP_SERVER.to_owned(),
+ ..Jid::default()
+ }
+ .into(),
+ )]),
+ content: None,
+ }
+ .to_string(),
+ r#"<message to="1234567890:2@interop"/>"#
+ );
+}
+
+#[test]
+fn child_lookup_follows_tag_paths() {
+ let node = unmarshal(&hex_bytes(
+ "f8041908fc03616263f802f80156f80271f801f8030e0cfaff05123456789003",
+ ))
+ .unwrap();
+ assert_eq!(node.get_children().len(), 2);
+ assert_eq!(node.get_children_by_tag("ping").count(), 1);
+ let user = node.get_optional_child_by_tag(&["list", "user"]).unwrap();
+ assert_eq!(
+ user.attr_getter().jid("jid"),
+ new_jid("1234567890", DEFAULT_USER_SERVER)
+ );
+ assert_eq!(node.get_optional_child_by_tag(&["list", "nope"]), None);
+ assert_eq!(node.get_child_by_tag(&["nope"]), &Node::default());
+ assert_eq!(node.get_optional_child_by_tag(&[]), Some(&node));
+}
+
+#[test]
+fn attr_utility_collects_errors() {
+ let node = Node {
+ tag: "message".to_owned(),
+ attrs: Attrs::from([
+ (
+ "from".to_owned(),
+ new_jid("1234567890", DEFAULT_USER_SERVER).into(),
+ ),
+ ("t".to_owned(), "1700000000".into()),
+ ("ms".to_owned(), "1700000000123".into()),
+ ("zero".to_owned(), "0".into()),
+ ("offline".to_owned(), "T".into()),
+ ("count".to_owned(), "+5".into()),
+ ("bad".to_owned(), "maybe".into()),
+ ]),
+ content: None,
+ };
+ let mut getter = node.attr_getter();
+ assert_eq!(
+ getter.jid("from"),
+ new_jid("1234567890", DEFAULT_USER_SERVER)
+ );
+ assert_eq!(
+ getter.unix_time("t").map(|time| time.timestamp()),
+ Some(1_700_000_000)
+ );
+ assert_eq!(
+ getter.unix_milli("ms").map(|time| time.timestamp_millis()),
+ Some(1_700_000_000_123)
+ );
+ assert_eq!(getter.get_unix_time("zero", true), None);
+ assert!(getter.bool("offline"));
+ assert_eq!(getter.int("count"), 5);
+ assert!(getter.ok());
+
+ assert_eq!(getter.optional_string("missing"), "");
+ assert_eq!(getter.optional_jid("missing"), None);
+ assert!(getter.ok());
+
+ assert_eq!(getter.uint64("count"), 0);
+ assert_eq!(getter.string("from"), "");
+ assert_eq!(getter.jid("t"), Jid::default());
+ assert!(!getter.optional_bool("bad"));
+ assert_eq!(getter.string("missing"), "");
+ assert_eq!(getter.jid("missing"), Jid::default());
+
+ let errors = getter.error().unwrap_err();
+ assert_eq!(errors.0.len(), 6);
+ assert_eq!(
+ errors.0[1].to_string(),
+ "expected attribute 'from' to be string, but was types.JID"
+ );
+ assert_eq!(
+ errors.0[4].to_string(),
+ "didn't find required attribute 'missing'"
+ );
+ assert_eq!(
+ errors.0[5].to_string(),
+ "didn't find required JID attribute 'missing'"
+ );
+}
+
+#[test]
+fn unpack_inflates_compressed_payloads() {
+ assert_eq!(unpack(&[0, 1, 2, 3]).unwrap(), vec![1, 2, 3]);
+ assert_eq!(
+ unpack(&hex_bytes(
+ "02789c003200cdff77686174736d656f772077686174736d656f772077686174736d656f772077686174736d656f772077686174736d656f77200300044013fc"
+ ))
+ .unwrap(),
+ b"whatsmeow whatsmeow whatsmeow whatsmeow whatsmeow ".to_vec()
+ );
+ assert_eq!(unpack(&[]), Err(DecodeError::EmptyPayload));
+ assert!(matches!(
+ unpack(&[2, 1, 2, 3]),
+ Err(DecodeError::Decompress(_))
+ ));
+}
+
+#[test]
+fn token_lookups_match_go_tables() {
+ assert_eq!(token::index_of_single_token("s.whatsapp.net"), Some(3));
+ assert_eq!(token::index_of_single_token(""), None);
+ assert_eq!(token::index_of_double_byte_token("read-self"), Some((0, 0)));
+ assert_eq!(token::get_double_token(0, 0), Some("read-self"));
+ assert_eq!(token::get_double_token(4, 0), None);
+ assert_eq!(token::get_double_token(3, 256), None);
+}
diff --git a/crates/whatsmeow/src/binary/token.rs b/crates/whatsmeow/src/binary/token.rs
new file mode 100644
index 0000000000..eb992671db
--- /dev/null
+++ b/crates/whatsmeow/src/binary/token.rs
@@ -0,0 +1,1374 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+//
+// Ported from whatsmeow binary/token/token.go (MPL-2.0, Copyright (c) Tulir Asokan)
+
+//! Maps of predefined tokens that WhatsApp's binary XML encoding uses to save
+//! bytes when sending commonly used strings.
+
+use std::collections::HashMap;
+use std::sync::LazyLock;
+
+/// All the currently known single-byte string tokens.
+pub const SINGLE_BYTE_TOKENS: [&str; 236] = [
+ "",
+ "xmlstreamstart",
+ "xmlstreamend",
+ "s.whatsapp.net",
+ "type",
+ "participant",
+ "from",
+ "receipt",
+ "id",
+ "notification",
+ "disappearing_mode",
+ "status",
+ "jid",
+ "broadcast",
+ "user",
+ "devices",
+ "device_hash",
+ "to",
+ "offline",
+ "message",
+ "result",
+ "class",
+ "xmlns",
+ "duration",
+ "notify",
+ "iq",
+ "t",
+ "ack",
+ "g.us",
+ "enc",
+ "urn:xmpp:whatsapp:push",
+ "presence",
+ "config_value",
+ "picture",
+ "verified_name",
+ "config_code",
+ "key-index-list",
+ "contact",
+ "mediatype",
+ "routing_info",
+ "edge_routing",
+ "get",
+ "read",
+ "urn:xmpp:ping",
+ "fallback_hostname",
+ "0",
+ "chatstate",
+ "business_hours_config",
+ "unavailable",
+ "download_buckets",
+ "skmsg",
+ "verified_level",
+ "composing",
+ "handshake",
+ "device-list",
+ "media",
+ "text",
+ "fallback_ip4",
+ "media_conn",
+ "device",
+ "creation",
+ "location",
+ "config",
+ "item",
+ "fallback_ip6",
+ "count",
+ "w:profile:picture",
+ "image",
+ "business",
+ "2",
+ "hostname",
+ "call-creator",
+ "display_name",
+ "relaylatency",
+ "platform",
+ "abprops",
+ "success",
+ "msg",
+ "offline_preview",
+ "prop",
+ "key-index",
+ "v",
+ "day_of_week",
+ "pkmsg",
+ "version",
+ "1",
+ "ping",
+ "w:p",
+ "download",
+ "video",
+ "set",
+ "specific_hours",
+ "props",
+ "primary",
+ "unknown",
+ "hash",
+ "commerce_experience",
+ "last",
+ "subscribe",
+ "max_buckets",
+ "call",
+ "profile",
+ "member_since_text",
+ "close_time",
+ "call-id",
+ "sticker",
+ "mode",
+ "participants",
+ "value",
+ "query",
+ "profile_options",
+ "open_time",
+ "code",
+ "list",
+ "host",
+ "ts",
+ "contacts",
+ "upload",
+ "lid",
+ "preview",
+ "update",
+ "usync",
+ "w:stats",
+ "delivery",
+ "auth_ttl",
+ "context",
+ "fail",
+ "cart_enabled",
+ "appdata",
+ "category",
+ "atn",
+ "direct_connection",
+ "decrypt-fail",
+ "relay_id",
+ "mmg-fallback.whatsapp.net",
+ "target",
+ "available",
+ "name",
+ "last_id",
+ "mmg.whatsapp.net",
+ "categories",
+ "401",
+ "is_new",
+ "index",
+ "tctoken",
+ "ip4",
+ "token_id",
+ "latency",
+ "recipient",
+ "edit",
+ "ip6",
+ "add",
+ "thumbnail-document",
+ "26",
+ "paused",
+ "true",
+ "identity",
+ "stream:error",
+ "key",
+ "sidelist",
+ "background",
+ "audio",
+ "3",
+ "thumbnail-image",
+ "biz-cover-photo",
+ "cat",
+ "gcm",
+ "thumbnail-video",
+ "error",
+ "auth",
+ "deny",
+ "serial",
+ "in",
+ "registration",
+ "thumbnail-link",
+ "remove",
+ "00",
+ "gif",
+ "thumbnail-gif",
+ "tag",
+ "capability",
+ "multicast",
+ "item-not-found",
+ "description",
+ "business_hours",
+ "config_expo_key",
+ "md-app-state",
+ "expiration",
+ "fallback",
+ "ttl",
+ "300",
+ "md-msg-hist",
+ "device_orientation",
+ "out",
+ "w:m",
+ "open_24h",
+ "side_list",
+ "token",
+ "inactive",
+ "01",
+ "document",
+ "te2",
+ "played",
+ "encrypt",
+ "msgr",
+ "hide",
+ "direct_path",
+ "12",
+ "state",
+ "not-authorized",
+ "url",
+ "terminate",
+ "signature",
+ "status-revoke-delay",
+ "02",
+ "te",
+ "linked_accounts",
+ "trusted_contact",
+ "timezone",
+ "ptt",
+ "kyc-id",
+ "privacy_token",
+ "readreceipts",
+ "appointment_only",
+ "address",
+ "expected_ts",
+ "privacy",
+ "7",
+ "android",
+ "interactive",
+ "device-identity",
+ "enabled",
+ "attribute_padding",
+ "1080",
+ "03",
+ "screen_height",
+];
+
+/// All the currently known double-byte string tokens, one list per dictionary.
+pub const DOUBLE_BYTE_TOKENS: [[&str; 256]; 4] = [
+ [
+ "read-self",
+ "active",
+ "fbns",
+ "protocol",
+ "reaction",
+ "screen_width",
+ "heartbeat",
+ "deviceid",
+ "2:47DEQpj8",
+ "uploadfieldstat",
+ "voip_settings",
+ "retry",
+ "priority",
+ "longitude",
+ "conflict",
+ "false",
+ "ig_professional",
+ "replaced",
+ "preaccept",
+ "cover_photo",
+ "uncompressed",
+ "encopt",
+ "ppic",
+ "04",
+ "passive",
+ "status-revoke-drop",
+ "keygen",
+ "540",
+ "offer",
+ "rate",
+ "opus",
+ "latitude",
+ "w:gp2",
+ "ver",
+ "4",
+ "business_profile",
+ "medium",
+ "sender",
+ "prev_v_id",
+ "email",
+ "website",
+ "invited",
+ "sign_credential",
+ "05",
+ "transport",
+ "skey",
+ "reason",
+ "peer_abtest_bucket",
+ "America/Sao_Paulo",
+ "appid",
+ "refresh",
+ "100",
+ "06",
+ "404",
+ "101",
+ "104",
+ "107",
+ "102",
+ "109",
+ "103",
+ "member_add_mode",
+ "105",
+ "transaction-id",
+ "110",
+ "106",
+ "outgoing",
+ "108",
+ "111",
+ "tokens",
+ "followers",
+ "ig_handle",
+ "self_pid",
+ "tue",
+ "dec",
+ "thu",
+ "joinable",
+ "peer_pid",
+ "mon",
+ "features",
+ "wed",
+ "peer_device_presence",
+ "pn",
+ "delete",
+ "07",
+ "fri",
+ "audio_duration",
+ "admin",
+ "connected",
+ "delta",
+ "rcat",
+ "disable",
+ "collection",
+ "08",
+ "480",
+ "sat",
+ "phash",
+ "all",
+ "invite",
+ "accept",
+ "critical_unblock_low",
+ "group_update",
+ "signed_credential",
+ "blinded_credential",
+ "eph_setting",
+ "net",
+ "09",
+ "background_location",
+ "refresh_id",
+ "Asia/Kolkata",
+ "privacy_mode_ts",
+ "account_sync",
+ "voip_payload_type",
+ "service_areas",
+ "acs_public_key",
+ "v_id",
+ "0a",
+ "fallback_class",
+ "relay",
+ "actual_actors",
+ "metadata",
+ "w:biz",
+ "5",
+ "connected-limit",
+ "notice",
+ "0b",
+ "host_storage",
+ "fb_page",
+ "subject",
+ "privatestats",
+ "invis",
+ "groupadd",
+ "010",
+ "note.m4r",
+ "uuid",
+ "0c",
+ "8000",
+ "sun",
+ "372",
+ "1020",
+ "stage",
+ "1200",
+ "720",
+ "canonical",
+ "fb",
+ "011",
+ "video_duration",
+ "0d",
+ "1140",
+ "superadmin",
+ "012",
+ "Opening.m4r",
+ "keystore_attestation",
+ "dleq_proof",
+ "013",
+ "timestamp",
+ "ab_key",
+ "w:sync:app:state",
+ "0e",
+ "vertical",
+ "600",
+ "p_v_id",
+ "6",
+ "likes",
+ "014",
+ "500",
+ "1260",
+ "creator",
+ "0f",
+ "rte",
+ "destination",
+ "group",
+ "group_info",
+ "syncd_anti_tampering_fatal_exception_enabled",
+ "015",
+ "dl_bw",
+ "Asia/Jakarta",
+ "vp8/h.264",
+ "online",
+ "1320",
+ "fb:multiway",
+ "10",
+ "timeout",
+ "016",
+ "nse_retry",
+ "urn:xmpp:whatsapp:dirty",
+ "017",
+ "a_v_id",
+ "web_shops_chat_header_button_enabled",
+ "nse_call",
+ "inactive-upgrade",
+ "none",
+ "web",
+ "groups",
+ "2250",
+ "mms_hot_content_timespan_in_seconds",
+ "contact_blacklist",
+ "nse_read",
+ "suspended_group_deletion_notification",
+ "binary_version",
+ "018",
+ "https://www.whatsapp.com/otp/copy/",
+ "reg_push",
+ "shops_hide_catalog_attachment_entrypoint",
+ "server_sync",
+ ".",
+ "ephemeral_messages_allowed_values",
+ "019",
+ "mms_vcache_aggregation_enabled",
+ "iphone",
+ "America/Argentina/Buenos_Aires",
+ "01a",
+ "mms_vcard_autodownload_size_kb",
+ "nse_ver",
+ "shops_header_dropdown_menu_item",
+ "dhash",
+ "catalog_status",
+ "communities_mvp_new_iqs_serverprop",
+ "blocklist",
+ "default",
+ "11",
+ "ephemeral_messages_enabled",
+ "01b",
+ "original_dimensions",
+ "8",
+ "mms4_media_retry_notification_encryption_enabled",
+ "mms4_server_error_receipt_encryption_enabled",
+ "original_image_url",
+ "sync",
+ "multiway",
+ "420",
+ "companion_enc_static",
+ "shops_profile_drawer_entrypoint",
+ "01c",
+ "vcard_as_document_size_kb",
+ "status_video_max_duration",
+ "request_image_url",
+ "01d",
+ "regular_high",
+ "s_t",
+ "abt",
+ "share_ext_min_preliminary_image_quality",
+ "01e",
+ "32",
+ "syncd_key_rotation_enabled",
+ "data_namespace",
+ "md_downgrade_read_receipts2",
+ "patch",
+ "polltype",
+ "ephemeral_messages_setting",
+ "userrate",
+ "15",
+ "partial_pjpeg_bw_threshold",
+ "played-self",
+ "catalog_exists",
+ "01f",
+ "mute_v2",
+ ],
+ [
+ "reject",
+ "dirty",
+ "announcement",
+ "020",
+ "13",
+ "9",
+ "status_video_max_bitrate",
+ "fb:thrift_iq",
+ "offline_batch",
+ "022",
+ "full",
+ "ctwa_first_business_reply_logging",
+ "h.264",
+ "smax_id",
+ "group_description_length",
+ "https://www.whatsapp.com/otp/code",
+ "status_image_max_edge",
+ "smb_upsell_business_profile_enabled",
+ "021",
+ "web_upgrade_to_md_modal",
+ "14",
+ "023",
+ "s_o",
+ "smaller_video_thumbs_status_enabled",
+ "media_max_autodownload",
+ "960",
+ "blocking_status",
+ "peer_msg",
+ "joinable_group_call_client_version",
+ "group_call_video_maximization_enabled",
+ "return_snapshot",
+ "high",
+ "America/Mexico_City",
+ "entry_point_block_logging_enabled",
+ "pop",
+ "024",
+ "1050",
+ "16",
+ "1380",
+ "one_tap_calling_in_group_chat_size",
+ "regular_low",
+ "inline_joinable_education_enabled",
+ "hq_image_max_edge",
+ "locked",
+ "America/Bogota",
+ "smb_biztools_deeplink_enabled",
+ "status_image_quality",
+ "1088",
+ "025",
+ "payments_upi_intent_transaction_limit",
+ "voip",
+ "w:g2",
+ "027",
+ "md_pin_chat_enabled",
+ "026",
+ "multi_scan_pjpeg_download_enabled",
+ "shops_product_grid",
+ "transaction_id",
+ "ctwa_context_enabled",
+ "20",
+ "fna",
+ "hq_image_quality",
+ "alt_jpeg_doc_detection_quality",
+ "group_call_max_participants",
+ "pkey",
+ "America/Belem",
+ "image_max_kbytes",
+ "web_cart_v1_1_order_message_changes_enabled",
+ "ctwa_context_enterprise_enabled",
+ "urn:xmpp:whatsapp:account",
+ "840",
+ "Asia/Kuala_Lumpur",
+ "max_participants",
+ "video_remux_after_repair_enabled",
+ "stella_addressbook_restriction_type",
+ "660",
+ "900",
+ "780",
+ "context_menu_ios13_enabled",
+ "mute-state",
+ "ref",
+ "payments_request_messages",
+ "029",
+ "frskmsg",
+ "vcard_max_size_kb",
+ "sample_buffer_gif_player_enabled",
+ "match_last_seen",
+ "510",
+ "4983",
+ "video_max_bitrate",
+ "028",
+ "w:comms:chat",
+ "17",
+ "frequently_forwarded_max",
+ "groups_privacy_blacklist",
+ "Asia/Karachi",
+ "02a",
+ "web_download_document_thumb_mms_enabled",
+ "02b",
+ "hist_sync",
+ "biz_block_reasons_version",
+ "1024",
+ "18",
+ "web_is_direct_connection_for_plm_transparent",
+ "view_once_write",
+ "file_max_size",
+ "paid_convo_id",
+ "online_privacy_setting",
+ "video_max_edge",
+ "view_once_read",
+ "enhanced_storage_management",
+ "multi_scan_pjpeg_encoding_enabled",
+ "ctwa_context_forward_enabled",
+ "video_transcode_downgrade_enable",
+ "template_doc_mime_types",
+ "hq_image_bw_threshold",
+ "30",
+ "body",
+ "u_aud_limit_sil_restarts_ctrl",
+ "other",
+ "participating",
+ "w:biz:directory",
+ "1110",
+ "vp8",
+ "4018",
+ "meta",
+ "doc_detection_image_max_edge",
+ "image_quality",
+ "1170",
+ "02c",
+ "smb_upsell_chat_banner_enabled",
+ "key_expiry_time_second",
+ "pid",
+ "stella_interop_enabled",
+ "19",
+ "linked_device_max_count",
+ "md_device_sync_enabled",
+ "02d",
+ "02e",
+ "360",
+ "enhanced_block_enabled",
+ "ephemeral_icon_in_forwarding",
+ "paid_convo_status",
+ "gif_provider",
+ "project_name",
+ "server-error",
+ "canonical_url_validation_enabled",
+ "wallpapers_v2",
+ "syncd_clear_chat_delete_chat_enabled",
+ "medianotify",
+ "02f",
+ "shops_required_tos_version",
+ "vote",
+ "reset_skey_on_id_change",
+ "030",
+ "image_max_edge",
+ "multicast_limit_global",
+ "ul_bw",
+ "21",
+ "25",
+ "5000",
+ "poll",
+ "570",
+ "22",
+ "031",
+ "1280",
+ "WhatsApp",
+ "032",
+ "bloks_shops_enabled",
+ "50",
+ "upload_host_switching_enabled",
+ "web_ctwa_context_compose_enabled",
+ "ptt_forwarded_features_enabled",
+ "unblocked",
+ "partial_pjpeg_enabled",
+ "fbid:devices",
+ "height",
+ "ephemeral_group_query_ts",
+ "group_join_permissions",
+ "order",
+ "033",
+ "alt_jpeg_status_quality",
+ "migrate",
+ "popular-bank",
+ "win_uwp_deprecation_killswitch_enabled",
+ "web_download_status_thumb_mms_enabled",
+ "blocking",
+ "url_text",
+ "035",
+ "web_forwarding_limit_to_groups",
+ "1600",
+ "val",
+ "1000",
+ "syncd_msg_date_enabled",
+ "bank-ref-id",
+ "max_subject",
+ "payments_web_enabled",
+ "web_upload_document_thumb_mms_enabled",
+ "size",
+ "request",
+ "ephemeral",
+ "24",
+ "receipt_agg",
+ "ptt_remember_play_position",
+ "sampling_weight",
+ "enc_rekey",
+ "mute_always",
+ "037",
+ "034",
+ "23",
+ "036",
+ "action",
+ "click_to_chat_qr_enabled",
+ "width",
+ "disabled",
+ "038",
+ "md_blocklist_v2",
+ "played_self_enabled",
+ "web_buttons_message_enabled",
+ "flow_id",
+ "clear",
+ "450",
+ "fbid:thread",
+ "bloks_session_state",
+ "America/Lima",
+ "attachment_picker_refresh",
+ "download_host_switching_enabled",
+ "1792",
+ "u_aud_limit_sil_restarts_test2",
+ "custom_urls",
+ "device_fanout",
+ "optimistic_upload",
+ "2000",
+ "key_cipher_suite",
+ "web_smb_upsell_in_biz_profile_enabled",
+ "e",
+ "039",
+ "siri_post_status_shortcut",
+ "pair-device",
+ "lg",
+ "lc",
+ "stream_attribution_url",
+ "model",
+ "mspjpeg_phash_gen",
+ "catalog_send_all",
+ "new_multi_vcards_ui",
+ "share_biz_vcard_enabled",
+ "-",
+ "clean",
+ "200",
+ "md_blocklist_v2_server",
+ "03b",
+ "03a",
+ "web_md_migration_experience",
+ "ptt_conversation_waveform",
+ "u_aud_limit_sil_restarts_test1",
+ ],
+ [
+ "64",
+ "ptt_playback_speed_enabled",
+ "web_product_list_message_enabled",
+ "paid_convo_ts",
+ "27",
+ "manufacturer",
+ "psp-routing",
+ "grp_uii_cleanup",
+ "ptt_draft_enabled",
+ "03c",
+ "business_initiated",
+ "web_catalog_products_onoff",
+ "web_upload_link_thumb_mms_enabled",
+ "03e",
+ "mediaretry",
+ "35",
+ "hfm_string_changes",
+ "28",
+ "America/Fortaleza",
+ "max_keys",
+ "md_mhfs_days",
+ "streaming_upload_chunk_size",
+ "5541",
+ "040",
+ "03d",
+ "2675",
+ "03f",
+ "...",
+ "512",
+ "mute",
+ "48",
+ "041",
+ "alt_jpeg_quality",
+ "60",
+ "042",
+ "md_smb_quick_reply",
+ "5183",
+ "c",
+ "1343",
+ "40",
+ "1230",
+ "043",
+ "044",
+ "mms_cat_v1_forward_hot_override_enabled",
+ "user_notice",
+ "ptt_waveform_send",
+ "047",
+ "Asia/Calcutta",
+ "250",
+ "md_privacy_v2",
+ "31",
+ "29",
+ "128",
+ "md_messaging_enabled",
+ "046",
+ "crypto",
+ "690",
+ "045",
+ "enc_iv",
+ "75",
+ "failure",
+ "ptt_oot_playback",
+ "AIzaSyDR5yfaG7OG8sMTUj8kfQEb8T9pN8BM6Lk",
+ "w",
+ "048",
+ "2201",
+ "web_large_files_ui",
+ "Asia/Makassar",
+ "812",
+ "status_collapse_muted",
+ "1334",
+ "257",
+ "2HP4dm",
+ "049",
+ "patches",
+ "1290",
+ "43cY6T",
+ "America/Caracas",
+ "web_sticker_maker",
+ "campaign",
+ "ptt_pausable_enabled",
+ "33",
+ "42",
+ "attestation",
+ "biz",
+ "04b",
+ "query_linked",
+ "s",
+ "125",
+ "04a",
+ "810",
+ "availability",
+ "1411",
+ "responsiveness_v2_m1",
+ "catalog_not_created",
+ "34",
+ "America/Santiago",
+ "1465",
+ "enc_p",
+ "04d",
+ "status_info",
+ "04f",
+ "key_version",
+ "..",
+ "04c",
+ "04e",
+ "md_group_notification",
+ "1598",
+ "1215",
+ "web_cart_enabled",
+ "37",
+ "630",
+ "1920",
+ "2394",
+ "-1",
+ "vcard",
+ "38",
+ "elapsed",
+ "36",
+ "828",
+ "peer",
+ "pricing_category",
+ "1245",
+ "invalid",
+ "stella_ios_enabled",
+ "2687",
+ "45",
+ "1528",
+ "39",
+ "u_is_redial_audio_1104_ctrl",
+ "1025",
+ "1455",
+ "58",
+ "2524",
+ "2603",
+ "054",
+ "bsp_system_message_enabled",
+ "web_pip_redesign",
+ "051",
+ "verify_apps",
+ "1974",
+ "1272",
+ "1322",
+ "1755",
+ "052",
+ "70",
+ "050",
+ "1063",
+ "1135",
+ "1361",
+ "80",
+ "1096",
+ "1828",
+ "1851",
+ "1251",
+ "1921",
+ "key_config_id",
+ "1254",
+ "1566",
+ "1252",
+ "2525",
+ "critical_block",
+ "1669",
+ "max_available",
+ "w:auth:backup:token",
+ "product",
+ "2530",
+ "870",
+ "1022",
+ "participant_uuid",
+ "web_cart_on_off",
+ "1255",
+ "1432",
+ "1867",
+ "41",
+ "1415",
+ "1440",
+ "240",
+ "1204",
+ "1608",
+ "1690",
+ "1846",
+ "1483",
+ "1687",
+ "1749",
+ "69",
+ "url_number",
+ "053",
+ "1325",
+ "1040",
+ "365",
+ "59",
+ "Asia/Riyadh",
+ "1177",
+ "test_recommended",
+ "057",
+ "1612",
+ "43",
+ "1061",
+ "1518",
+ "1635",
+ "055",
+ "1034",
+ "1375",
+ "750",
+ "1430",
+ "event_code",
+ "1682",
+ "503",
+ "55",
+ "865",
+ "78",
+ "1309",
+ "1365",
+ "44",
+ "America/Guayaquil",
+ "535",
+ "LIMITED",
+ "1377",
+ "1613",
+ "1420",
+ "1599",
+ "1822",
+ "05a",
+ "1681",
+ "password",
+ "1111",
+ "1214",
+ "1376",
+ "1478",
+ "47",
+ "1082",
+ "4282",
+ "Europe/Istanbul",
+ "1307",
+ "46",
+ "058",
+ "1124",
+ "256",
+ "rate-overlimit",
+ "retail",
+ "u_a_socket_err_fix_succ_test",
+ "1292",
+ "1370",
+ "1388",
+ "520",
+ "861",
+ "psa",
+ "regular",
+ "1181",
+ "1766",
+ "05b",
+ "1183",
+ "1213",
+ "1304",
+ "1537",
+ ],
+ [
+ "1724",
+ "profile_picture",
+ "1071",
+ "1314",
+ "1605",
+ "407",
+ "990",
+ "1710",
+ "746",
+ "pricing_model",
+ "056",
+ "059",
+ "061",
+ "1119",
+ "6027",
+ "65",
+ "877",
+ "1607",
+ "05d",
+ "917",
+ "seen",
+ "1516",
+ "49",
+ "470",
+ "973",
+ "1037",
+ "1350",
+ "1394",
+ "1480",
+ "1796",
+ "keys",
+ "794",
+ "1536",
+ "1594",
+ "2378",
+ "1333",
+ "1524",
+ "1825",
+ "116",
+ "309",
+ "52",
+ "808",
+ "827",
+ "909",
+ "495",
+ "1660",
+ "361",
+ "957",
+ "google",
+ "1357",
+ "1565",
+ "1967",
+ "996",
+ "1775",
+ "586",
+ "736",
+ "1052",
+ "1670",
+ "bank",
+ "177",
+ "1416",
+ "2194",
+ "2222",
+ "1454",
+ "1839",
+ "1275",
+ "53",
+ "997",
+ "1629",
+ "6028",
+ "smba",
+ "1378",
+ "1410",
+ "05c",
+ "1849",
+ "727",
+ "create",
+ "1559",
+ "536",
+ "1106",
+ "1310",
+ "1944",
+ "670",
+ "1297",
+ "1316",
+ "1762",
+ "en",
+ "1148",
+ "1295",
+ "1551",
+ "1853",
+ "1890",
+ "1208",
+ "1784",
+ "7200",
+ "05f",
+ "178",
+ "1283",
+ "1332",
+ "381",
+ "643",
+ "1056",
+ "1238",
+ "2024",
+ "2387",
+ "179",
+ "981",
+ "1547",
+ "1705",
+ "05e",
+ "290",
+ "903",
+ "1069",
+ "1285",
+ "2436",
+ "062",
+ "251",
+ "560",
+ "582",
+ "719",
+ "56",
+ "1700",
+ "2321",
+ "325",
+ "448",
+ "613",
+ "777",
+ "791",
+ "51",
+ "488",
+ "902",
+ "Asia/Almaty",
+ "is_hidden",
+ "1398",
+ "1527",
+ "1893",
+ "1999",
+ "2367",
+ "2642",
+ "237",
+ "busy",
+ "065",
+ "067",
+ "233",
+ "590",
+ "993",
+ "1511",
+ "54",
+ "723",
+ "860",
+ "363",
+ "487",
+ "522",
+ "605",
+ "995",
+ "1321",
+ "1691",
+ "1865",
+ "2447",
+ "2462",
+ "NON_TRANSACTIONAL",
+ "433",
+ "871",
+ "432",
+ "1004",
+ "1207",
+ "2032",
+ "2050",
+ "2379",
+ "2446",
+ "279",
+ "636",
+ "703",
+ "904",
+ "248",
+ "370",
+ "691",
+ "700",
+ "1068",
+ "1655",
+ "2334",
+ "060",
+ "063",
+ "364",
+ "533",
+ "534",
+ "567",
+ "1191",
+ "1210",
+ "1473",
+ "1827",
+ "069",
+ "701",
+ "2531",
+ "514",
+ "prev_dhash",
+ "064",
+ "496",
+ "790",
+ "1046",
+ "1139",
+ "1505",
+ "1521",
+ "1108",
+ "207",
+ "544",
+ "637",
+ "final",
+ "1173",
+ "1293",
+ "1694",
+ "1939",
+ "1951",
+ "1993",
+ "2353",
+ "2515",
+ "504",
+ "601",
+ "857",
+ "modify",
+ "spam_request",
+ "p_121_aa_1101_test4",
+ "866",
+ "1427",
+ "1502",
+ "1638",
+ "1744",
+ "2153",
+ "068",
+ "382",
+ "725",
+ "1704",
+ "1864",
+ "1990",
+ "2003",
+ "Asia/Dubai",
+ "508",
+ "531",
+ "1387",
+ "1474",
+ "1632",
+ "2307",
+ "2386",
+ "819",
+ "2014",
+ "066",
+ "387",
+ "1468",
+ "1706",
+ "2186",
+ "2261",
+ "471",
+ "728",
+ "1147",
+ "1372",
+ "1961",
+ ],
+];
+
+/// The version number of the token lists above.
+/// It's sent when connecting to the websocket so the server knows which tokens are supported.
+pub const DICT_VERSION: u8 = 3;
+
+#[derive(Clone, Copy)]
+struct DoubleByteTokenIndex {
+ dictionary: u8,
+ index: u8,
+}
+
+static MD_SINGLE_BYTE_TOKEN_INDEX: LazyLock<HashMap<&'static str, u8>> = LazyLock::new(|| {
+ (0..=u8::MAX)
+ .zip(SINGLE_BYTE_TOKENS)
+ .filter(|(_, token)| !token.is_empty())
+ .map(|(index, token)| (token, index))
+ .collect()
+});
+
+static MD_DOUBLE_BYTE_TOKEN_INDEX: LazyLock<HashMap<&'static str, DoubleByteTokenIndex>> =
+ LazyLock::new(|| {
+ let mut map = HashMap::with_capacity(256 * DOUBLE_BYTE_TOKENS.len());
+ for (dictionary, tokens) in (0..=u8::MAX).zip(DOUBLE_BYTE_TOKENS) {
+ for (index, token) in (0..=u8::MAX).zip(tokens) {
+ map.insert(token, DoubleByteTokenIndex { dictionary, index });
+ }
+ }
+ map
+ });
+
+/// Gets the string value of the double-byte token at the given index, or
+/// `None` when either index is out of bounds.
+pub fn get_double_token(index1: usize, index2: usize) -> Option<&'static str> {
+ DOUBLE_BYTE_TOKENS.get(index1)?.get(index2).copied()
+}
+
+/// Gets the index of the single-byte token with the given string value.
+pub fn index_of_single_token(token: &str) -> Option<u8> {
+ MD_SINGLE_BYTE_TOKEN_INDEX.get(token).copied()
+}
+
+/// Gets the dictionary and index of the double-byte token with the given string value.
+pub fn index_of_double_byte_token(token: &str) -> Option<(u8, u8)> {
+ MD_DOUBLE_BYTE_TOKEN_INDEX
+ .get(token)
+ .map(|found| (found.dictionary, found.index))
+}
+
+// Type tokens used in the binary XML representation.
+
+/// An empty list, or a missing value.
+pub const LIST_EMPTY: u8 = 0;
+/// First double-byte token dictionary.
+pub const DICTIONARY_0: u8 = 236;
+/// Second double-byte token dictionary.
+pub const DICTIONARY_1: u8 = 237;
+/// Third double-byte token dictionary.
+pub const DICTIONARY_2: u8 = 238;
+/// Fourth double-byte token dictionary.
+pub const DICTIONARY_3: u8 = 239;
+/// An interop JID (user, device, integrator, server).
+pub const INTEROP_JID: u8 = 245;
+/// A Messenger JID (user, device, server).
+pub const FB_JID: u8 = 246;
+/// An AD JID (agent/domain, device, user).
+pub const AD_JID: u8 = 247;
+/// A list with a one-byte length.
+pub const LIST_8: u8 = 248;
+/// A list with a two-byte length.
+pub const LIST_16: u8 = 249;
+/// A regular user@server JID.
+pub const JID_PAIR: u8 = 250;
+/// A hex-packed string.
+pub const HEX_8: u8 = 251;
+/// Binary data with a one-byte length.
+pub const BINARY_8: u8 = 252;
+/// Binary data with a 20-bit length.
+pub const BINARY_20: u8 = 253;
+/// Binary data with a four-byte length.
+pub const BINARY_32: u8 = 254;
+/// A nibble-packed string.
+pub const NIBBLE_8: u8 = 255;
+
+/// The longest string that can be nibble- or hex-packed.
+pub const PACKED_MAX: usize = 127;
+/// The number of values a single byte can hold.
+pub const SINGLE_BYTE_MAX: usize = 256;
diff --git a/crates/whatsmeow/src/binary/unpack.rs b/crates/whatsmeow/src/binary/unpack.rs
new file mode 100644
index 0000000000..5e5ba6de55
--- /dev/null
+++ b/crates/whatsmeow/src/binary/unpack.rs
@@ -0,0 +1,23 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+//
+// Ported from whatsmeow binary/unpack.go (MPL-2.0, Copyright (c) Tulir Asokan)
+
+use super::errors::DecodeError;
+
+/// Unpacks the given decrypted data from the WhatsApp web API.
+///
+/// It checks the first byte to decide whether to uncompress the data with zlib
+/// or just return it as-is (without the first byte). There's no corresponding
+/// pack function because [`super::marshal`] already returns the data with a
+/// leading zero (i.e. not compressed).
+pub fn unpack(data: &[u8]) -> Result<Vec<u8>, DecodeError> {
+ let (&data_type, data) = data.split_first().ok_or(DecodeError::EmptyPayload)?;
+ if 2 & data_type > 0 {
+ miniz_oxide::inflate::decompress_to_vec_zlib(data)
+ .map_err(|error| DecodeError::Decompress(error.to_string()))
+ } else {
+ Ok(data.to_vec())
+ }
+}
diff --git a/crates/whatsmeow/src/binary/xml.rs b/crates/whatsmeow/src/binary/xml.rs
new file mode 100644
index 0000000000..4eaf5f024e
--- /dev/null
+++ b/crates/whatsmeow/src/binary/xml.rs
@@ -0,0 +1,127 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+//
+// Ported from whatsmeow binary/xml.go (MPL-2.0, Copyright (c) Tulir Asokan)
+
+use std::fmt;
+
+use super::node::{Node, NodeContent};
+
+/// Binary content longer than this is printed as a byte count instead of hex.
+pub const MAX_BYTES_TO_PRINT_AS_HEX: usize = 128;
+
+/// The XML representation of the node on one line (Go's `Node.String` with
+/// `IndentXML` off).
+impl fmt::Display for Node {
+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
+ formatter.write_str(&self.xml_string(false))
+ }
+}
+
+impl Node {
+ /// The XML representation of the node with children on their own,
+ /// indented lines (Go's `Node.String` with `IndentXML` on).
+ pub fn indented_string(&self) -> String {
+ self.xml_string(true)
+ }
+
+ fn xml_string(&self, indent: bool) -> String {
+ let content = self.content_string(indent);
+ if content.is_empty() {
+ return format!("<{}{}/>", self.tag, self.attribute_string());
+ }
+ let newline = if content.len() == 1 || !indent {
+ ""
+ } else {
+ "\n"
+ };
+ format!(
+ "<{tag}{attributes}>{newline}{content}{newline}</{tag}>",
+ tag = self.tag,
+ attributes = self.attribute_string(),
+ content = content.join(newline),
+ )
+ }
+
+ fn attribute_string(&self) -> String {
+ if self.attrs.is_empty() {
+ return String::new();
+ }
+ // Go sorts the formatted `key="value"` strings, with an empty first
+ // entry that turns into the leading space.
+ let mut attributes: Vec<String> = std::iter::once(String::new())
+ .chain(
+ self.attrs
+ .iter()
+ .map(|(key, value)| format!("{key}=\"{value}\"")),
+ )
+ .collect();
+ attributes.sort();
+ attributes.join(" ")
+ }
+
+ fn content_string(&self, indent: bool) -> Vec<String> {
+ let mut split = Vec::new();
+ match &self.content {
+ Some(NodeContent::Nodes(children)) => {
+ for child in children {
+ split.extend(child.xml_string(indent).split('\n').map(str::to_owned));
+ }
+ }
+ Some(NodeContent::Bytes(bytes)) => {
+ if let Some(text) = printable(bytes) {
+ if indent {
+ split.extend(text.split('\n').map(str::to_owned));
+ } else {
+ split.push(text.replace('\n', "\\n"));
+ }
+ } else if bytes.len() > MAX_BYTES_TO_PRINT_AS_HEX {
+ split.push(format!("<!-- {} bytes -->", bytes.len()));
+ } else if !indent {
+ split.push(hex::encode(bytes));
+ } else {
+ let hex_data = hex::encode(bytes);
+ split.extend(
+ hex_data
+ .as_bytes()
+ .chunks(80)
+ .map(|line| String::from_utf8_lossy(line).into_owned()),
+ );
+ }
+ }
+ Some(NodeContent::String(text)) => push_text(&mut split, text, indent),
+ Some(NodeContent::Jid(jid)) => push_text(&mut split, &jid.to_string(), indent),
+ None => {}
+ }
+ if split.len() > 1 && indent {
+ for line in &mut split {
+ line.insert_str(0, " ");
+ }
+ }
+ split
+ }
+}
+
+fn push_text(split: &mut Vec<String>, text: &str, indent: bool) {
+ if indent {
+ split.extend(text.split('\n').map(str::to_owned));
+ } else {
+ split.push(text.replace('\n', "\\n"));
+ }
+}
+
+/// The bytes as a string when they are valid UTF-8 made of printable
+/// characters only.
+///
+/// Go uses `unicode.IsPrint` (letters, marks, numbers, punctuation, symbols
+/// and the ASCII space). Rust's standard library has no general-category
+/// lookup, so this approximates it: no control characters and no whitespace
+/// other than the ASCII space. It only affects debug output.
+fn printable(data: &[u8]) -> Option<&str> {
+ let text = std::str::from_utf8(data).ok()?;
+ text.chars()
+ .all(|char| char == ' ' || !(char.is_control() || char.is_whitespace()))
+ .then_some(text)
+ .filter(|text| !text.is_empty())
+}
diff --git a/crates/whatsmeow/src/client.rs b/crates/whatsmeow/src/client.rs
new file mode 100644
index 0000000000..2f0fbb562a
--- /dev/null
+++ b/crates/whatsmeow/src/client.rs
@@ -0,0 +1,1295 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+//
+// Ported from whatsmeow client.go (MPL-2.0, Copyright (c) Tulir Asokan)
+//
+// Deliberate deviations:
+// - Go's public mutable fields (`EnableAutoReconnect`, `SynchronousAck`,
+// `PrePairCallback`, …) are a [`ClientConfig`] passed to [`Client::new`].
+// - The HTTP clients and proxy setters are replaced by [`Dialer`], which opens
+// the websocket (tests dial an in-memory fake server).
+// - Event handlers are async ([`EventHandler`]) so a handler can persist an
+// event before the client acks it (`synchronous_ack`). [`Client::subscribe`]
+// gives a channel of events instead.
+// - `context.Context` parameters are dropped. The per-connection context is a
+// `CancellationToken`; background tasks run on the client's `TaskTracker`.
+// - Logs carry opaque IDs only: no node XML, JIDs or phone numbers.
+// - `handler_queue_loop` handles a `stream:error` it dequeued after the
+// connection ended instead of dropping it (Go drops it, losing the
+// post-pairing 515 reconnect when the socket closes in the same write).
+// - Not ported: Messenger (`MessengerConfig`, `RefreshCAT`), proxies.
+
+//! The WhatsApp web multidevice client.
+
+use std::collections::HashMap;
+use std::panic::AssertUnwindSafe;
+use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU32, AtomicU64, Ordering};
+use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
+use std::time::Duration;
+
+use async_trait::async_trait;
+use chrono::{DateTime, Utc};
+use futures::FutureExt;
+use futures::future::BoxFuture;
+use tokio::sync::{RwLock, mpsc, oneshot, watch};
+use tokio_util::sync::CancellationToken;
+use tokio_util::task::TaskTracker;
+use tracing::Instrument;
+
+use crate::binary::{Attrs, Node, NodeContent, marshal, unmarshal, unpack};
+use crate::errors::ClientError;
+use crate::handshake::do_handshake;
+use crate::pair_code::PairClientType;
+use crate::signal::{CurveSignatures, SignalProtocol};
+use crate::socket::{FrameEvent, FrameSocket, NoiseEvent, NoiseSocket, SocketError, URL};
+use crate::store::{Device, StoreError};
+use crate::types::events::{Disconnected, Event};
+use crate::types::{AddressingMode, DEFAULT_USER_SERVER, HIDDEN_USER_SERVER, Jid};
+use crate::util::keys::new_key_pair;
+
+/// Everything the client needs from a Signal implementation: the protocol
+/// and XEdDSA signatures. Implemented for every type that has both.
+pub trait Signal: SignalProtocol + CurveSignatures {}
+
+impl<Implementation: SignalProtocol + CurveSignatures> Signal for Implementation {}
+
+/// Opens the websocket to WhatsApp.
+///
+/// Object safe (`Arc<dyn Dialer>`), hence `async_trait`.
+#[async_trait]
+pub trait Dialer: Send + Sync {
+ /// Connects and returns the frame socket with its events.
+ async fn dial(&self) -> Result<(FrameSocket, mpsc::Receiver<FrameEvent>), SocketError>;
+}
+
+/// Dials WhatsApp's real websocket endpoint ([`URL`]).
+pub struct WebSocketDialer {
+ /// The URL to dial.
+ pub url: String,
+}
+
+impl Default for WebSocketDialer {
+ fn default() -> Self {
+ WebSocketDialer {
+ url: URL.to_owned(),
+ }
+ }
+}
+
+#[async_trait]
+impl Dialer for WebSocketDialer {
+ async fn dial(&self) -> Result<(FrameSocket, mpsc::Receiver<FrameEvent>), SocketError> {
+ FrameSocket::connect(&self.url).await
+ }
+}
+
+/// Handles events emitted by the client. Returning `false` marks the event
+/// as failed: with `synchronous_ack`, the node isn't acked so the server
+/// redelivers it.
+///
+/// Object safe (`Arc<dyn EventHandler>`), hence `async_trait`.
+#[async_trait]
+pub trait EventHandler: Send + Sync {
+ /// Handles one event.
+ async fn handle(&self, event: &Event) -> bool;
+}
+
+struct FnHandler<Function>(Function);
+
+#[async_trait]
+impl<Function: Fn(&Event) + Send + Sync> EventHandler for FnHandler<Function> {
+ async fn handle(&self, event: &Event) -> bool {
+ (self.0)(event);
+ true
+ }
+}
+
+/// `PrePairCallback`: called with the JID, platform and business name before
+/// pairing completes; returning `false` cancels the pairing.
+pub type PrePairCallback = Arc<dyn Fn(&Jid, &str, &str) -> bool + Send + Sync>;
+
+/// `AutoReconnectHook`: called when an automatic reconnect fails; returning
+/// `false` stops reconnecting.
+pub type AutoReconnectHook = Arc<dyn Fn(&ClientError) -> bool + Send + Sync>;
+
+/// `GetMessageForRetry`: the requester, the chat and the message ID.
+pub type GetMessageForRetry =
+ Arc<dyn Fn(&Jid, &Jid, &str) -> Option<crate::proto::wa_e2e::Message> + Send + Sync>;
+
+/// `PreRetryCallback`: the receipt, message ID, retry count and message.
+pub type PreRetryCallback = Arc<
+ dyn Fn(&crate::types::events::Receipt, &str, i64, &crate::proto::wa_e2e::Message) -> bool
+ + Send
+ + Sync,
+>;
+
+/// The settings Go keeps as public fields on `Client`.
+#[derive(Clone)]
+pub struct ClientConfig {
+ /// Opens the websocket.
+ pub dialer: Arc<dyn Dialer>,
+ /// Reconnect automatically after unexpected disconnects (default true).
+ pub enable_auto_reconnect: bool,
+ /// Retry in the background when the first connection attempt fails.
+ pub initial_auto_reconnect: bool,
+ /// See [`AutoReconnectHook`].
+ pub auto_reconnect_hook: Option<AutoReconnectHook>,
+ /// Only ack nodes after every event handler returned successfully.
+ pub synchronous_ack: bool,
+ /// Don't reconnect after the server's post-login 515 stream error; emit
+ /// [`Event::ManualLoginReconnect`] instead.
+ pub disable_login_auto_reconnect: bool,
+ /// Emit app state events even when re-syncing the whole state.
+ pub emit_app_state_events_on_full_sync: bool,
+ /// Ask the phone for messages that fail to decrypt.
+ pub automatic_message_rerequest_from_phone: bool,
+ /// Don't download history syncs automatically.
+ pub manual_history_sync_download: bool,
+ /// Don't send the history sync receipt when downloading manually.
+ pub disable_manual_history_sync_receipt: bool,
+ /// Delete the stored identity and sessions on untrusted identity errors
+ /// (default true).
+ pub auto_trust_identity: bool,
+ /// Keep sent messages in the store so retry receipts work across restarts.
+ pub use_retry_message_store: bool,
+ /// See [`PrePairCallback`].
+ pub pre_pair_callback: Option<PrePairCallback>,
+ /// Overrides the client type shown on the phone while pairing.
+ pub qr_client_type: Option<PairClientType>,
+ /// The HTTP client for media downloads and uploads (Go's `mediaHTTP`).
+ pub media_http: reqwest::Client,
+ /// Fail [`Client::subscribe_presence`] when there's no privacy token for
+ /// the user instead of subscribing without one.
+ pub error_on_subscribe_presence_without_token: bool,
+ /// Finds a sent message for a retry receipt when it isn't in the recent
+ /// message cache, given the requester, chat and message ID
+ /// (`GetMessageForRetry`).
+ pub get_message_for_retry: Option<GetMessageForRetry>,
+ /// Called before accepting a retry receipt; returning `false` ignores it
+ /// (`PreRetryCallback`).
+ pub pre_retry_callback: Option<PreRetryCallback>,
+ /// Sends media uploads, downloads and deletes to this base URL
+ /// (`scheme://host[:port]`) instead of the hosts the media connection
+ /// names, e.g. a local fake media server in tests. `None` (default) uses
+ /// WhatsApp's hosts. Not in whatsmeow.
+ pub media_base_url: Option<String>,
+ /// Buffer decrypted events in the store so a redelivered ciphertext
+ /// isn't decrypted twice (Go's `EnableDecryptedEventBuffer`).
+ pub enable_decrypted_event_buffer: bool,
+}
+
+impl Default for ClientConfig {
+ fn default() -> Self {
+ ClientConfig {
+ dialer: Arc::new(WebSocketDialer::default()),
+ enable_auto_reconnect: true,
+ initial_auto_reconnect: false,
+ auto_reconnect_hook: None,
+ synchronous_ack: false,
+ disable_login_auto_reconnect: false,
+ emit_app_state_events_on_full_sync: false,
+ automatic_message_rerequest_from_phone: false,
+ manual_history_sync_download: false,
+ disable_manual_history_sync_receipt: false,
+ auto_trust_identity: true,
+ use_retry_message_store: false,
+ pre_pair_callback: None,
+ qr_client_type: None,
+ media_http: reqwest::Client::new(),
+ error_on_subscribe_presence_without_token: false,
+ enable_decrypted_event_buffer: false,
+ media_base_url: None,
+ get_message_for_retry: None,
+ pre_retry_callback: None,
+ }
+ }
+}
+
+/// exsync.Event: a flag tasks can wait on.
+pub(crate) struct EventFlag(watch::Sender<bool>);
+
+impl EventFlag {
+ pub(crate) fn new() -> Self {
+ EventFlag(watch::Sender::new(false))
+ }
+
+ pub(crate) fn set(&self) {
+ self.0.send_replace(true);
+ }
+
+ pub(crate) fn clear(&self) {
+ self.0.send_replace(false);
+ }
+
+ pub(crate) fn is_set(&self) -> bool {
+ *self.0.borrow()
+ }
+
+ /// Waits until the flag is set.
+ pub(crate) async fn wait(&self) {
+ let mut receiver = self.0.subscribe();
+ // The sender lives as long as `self`, so this only returns once set.
+ let _ = receiver.wait_for(|set| *set).await;
+ }
+}
+
+/// The socket and its connection, guarded by Go's `socketLock`.
+#[derive(Default)]
+pub(crate) struct SocketState {
+ pub(crate) socket: Option<Arc<NoiseSocket>>,
+ /// Cancelled when the connection ends (Go's `fs.Context()`).
+ connection: Option<CancellationToken>,
+ /// Resolves when the handler queue loop exits.
+ handler_queue_wait: Option<oneshot::Receiver<()>>,
+}
+
+/// Size of the queue that all incoming XML nodes go through.
+const HANDLER_QUEUE_SIZE: usize = 2048;
+
+/// The tags of the nodes the client handles (Go's `nodeHandlers` keys).
+const NODE_HANDLER_TAGS: &[&str] = &[
+ "message",
+ "status",
+ "appdata",
+ "receipt",
+ "call",
+ "chatstate",
+ "presence",
+ "notification",
+ "success",
+ "failure",
+ "stream:error",
+ "iq",
+ "ib",
+];
+
+/// A user's devices and the hash of the list.
+#[derive(Clone, Debug, Default)]
+pub(crate) struct DeviceCache {
+ pub(crate) devices: Vec<Jid>,
+ #[cfg_attr(
+ not(test),
+ expect(dead_code, reason = "Go keeps it but never reads it either")
+ )]
+ pub(crate) dhash: String,
+}
+
+/// What the send path needs to know about a group (Go's `groupMetaCache`).
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub(crate) struct GroupMetaCache {
+ pub(crate) addressing_mode: AddressingMode,
+ pub(crate) community_announcement_group: bool,
+ pub(crate) read_only: bool,
+ pub(crate) members: Vec<Jid>,
+ pub(crate) admins: Vec<Jid>,
+}
+
+impl GroupMetaCache {
+ /// Whether the sender may send the message: anyone may send in a group
+ /// that isn't read only, and only admins may send anything but
+ /// reactions, poll votes and the like in one that is (`CanSend`; a nil
+ /// cache in Go is `None` at the call site).
+ pub(crate) fn can_send(&self, sender: &Jid, message: &crate::proto::wa_e2e::Message) -> bool {
+ !self.read_only
+ || message.poll_update_message.is_some()
+ || message.reaction_message.is_some()
+ || message.enc_reaction_message.is_some()
+ || message.enc_event_response_message.is_some()
+ || message.question_response_message.is_some()
+ || message.comment_message.is_some()
+ || message.enc_comment_message.is_some()
+ || self.admins.contains(&sender.to_non_ad())
+ }
+}
+
+/// Everything necessary to connect to and interact with the WhatsApp web API.
+pub struct Client {
+ /// The device: keys, identity and stores (Go's `Store`).
+ pub store: RwLock<Device>,
+ pub(crate) signal: Arc<dyn Signal>,
+ pub(crate) config: ClientConfig,
+
+ pub(crate) socket: RwLock<SocketState>,
+ socket_wait: watch::Sender<u64>,
+
+ is_logged_in: AtomicBool,
+ pub(crate) paired: AtomicBool,
+ pub(crate) expected_disconnect: EventFlag,
+ force_auto_reconnect: AtomicBool,
+ last_successful_connect: Mutex<Option<DateTime<Utc>>>,
+ auto_reconnect_errors: AtomicU32,
+
+ pub(crate) send_active_receipts: AtomicU32,
+
+ /// Prekey upload lock with the time of the last upload.
+ pub(crate) upload_pre_keys_lock: tokio::sync::Mutex<Option<tokio::time::Instant>>,
+ /// Set once prekeys were uploaded (Go's `PreKeysUploaded`).
+ pub(crate) pre_keys_uploaded: EventFlag,
+
+ response_waiters: Mutex<HashMap<String, oneshot::Sender<Node>>>,
+
+ event_handlers: std::sync::RwLock<Vec<(u32, Arc<dyn EventHandler>)>>,
+ next_handler_id: AtomicU32,
+
+ /// Go's `groupCache`; held across the group info query when filling it.
+ pub(crate) group_cache: tokio::sync::Mutex<HashMap<Jid, GroupMetaCache>>,
+ pub(crate) user_devices_cache: tokio::sync::Mutex<HashMap<Jid, DeviceCache>>,
+
+ pub(crate) tc_token_sender_ts: Mutex<crate::tctoken::TcTokenSenderTimestamps>,
+ /// The prune lock with the time of the last prune.
+ pub(crate) tc_token_db_prune: tokio::sync::Mutex<Option<tokio::time::Instant>>,
+
+ pub(crate) media_conn_cache: tokio::sync::Mutex<Option<crate::mediaconn::MediaConn>>,
+ pub(crate) phone_linking_cache: Mutex<Option<crate::pair_code::PhoneLinkingCache>>,
+ pub(crate) passkey_state: Mutex<crate::pair_passkey::PasskeyState>,
+ pub(crate) privacy_settings_cache: Mutex<Option<crate::types::PrivacySettings>>,
+
+ /// Built from the device's stores in [`Client::new`] (Go's
+ /// `appStateProc`).
+ pub(crate) app_state_proc: Mutex<Arc<crate::appstate::Processor>>,
+ /// Serializes app state fetches (Go's `appStateSyncLock`).
+ pub(crate) app_state_sync_lock: tokio::sync::Mutex<()>,
+ /// When each missing app state key was last requested, by hex key ID.
+ pub(crate) app_state_key_requests: Mutex<HashMap<String, tokio::time::Instant>>,
+ pub(crate) last_decrypted_buffer_clear: Mutex<Option<tokio::time::Instant>>,
+ pub(crate) history_sync_notifications:
+ mpsc::UnboundedSender<crate::proto::wa_e2e::HistorySyncNotification>,
+ pub(crate) history_sync_notifications_receiver:
+ tokio::sync::Mutex<mpsc::UnboundedReceiver<crate::proto::wa_e2e::HistorySyncNotification>>,
+ pub(crate) history_sync_handler_started: AtomicBool,
+ /// Retry receipts sent per incoming message ID.
+ pub(crate) message_retries: Mutex<HashMap<String, i64>>,
+ /// Pending delayed requests to the phone per message ID.
+ pub(crate) pending_phone_rerequests: Mutex<HashMap<String, CancellationToken>>,
+ pub(crate) recent_messages: Mutex<crate::retry::RecentMessages>,
+ pub(crate) retry_state: Mutex<crate::retry::RetryState>,
+ /// Serializes sends (Go's `messageSendLock`).
+ pub(crate) message_send_lock: tokio::sync::Mutex<()>,
+
+ unique_id: String,
+ id_counter: AtomicU64,
+
+ pub(crate) server_time_offset: AtomicI64,
+
+ pub(crate) tasks: TaskTracker,
+ /// Cancelled when the client is dropped or shut down (Go's
+ /// `BackgroundEventCtx`).
+ pub(crate) background: CancellationToken,
+}
+
+/// Locks a std mutex, ignoring poisoning: every guarded value is replaced
+/// in one step, so a panic can't leave it half-written.
+pub(crate) fn lock<Value>(mutex: &Mutex<Value>) -> MutexGuard<'_, Value> {
+ mutex.lock().unwrap_or_else(PoisonError::into_inner)
+}
+
+impl Client {
+ /// Creates a client for the device (`NewClient`).
+ pub fn new(device: Device, signal: Arc<dyn Signal>, config: ClientConfig) -> Arc<Client> {
+ let unique_id_prefix: [u8; 2] = rand::random();
+ let paired = device.id.is_some();
+ let app_state_proc = Mutex::new(Arc::new(crate::appstate::Processor::new(&device)));
+ let (history_sync_notifications, history_sync_notifications_receiver) =
+ mpsc::unbounded_channel();
+ Arc::new(Client {
+ store: RwLock::new(device),
+ signal,
+ config,
+ socket: RwLock::new(SocketState::default()),
+ socket_wait: watch::Sender::new(0),
+ is_logged_in: AtomicBool::new(false),
+ paired: AtomicBool::new(paired),
+ expected_disconnect: EventFlag::new(),
+ force_auto_reconnect: AtomicBool::new(false),
+ last_successful_connect: Mutex::new(None),
+ auto_reconnect_errors: AtomicU32::new(0),
+ send_active_receipts: AtomicU32::new(0),
+ upload_pre_keys_lock: tokio::sync::Mutex::new(None),
+ pre_keys_uploaded: EventFlag::new(),
+ response_waiters: Mutex::new(HashMap::new()),
+ event_handlers: std::sync::RwLock::new(Vec::new()),
+ next_handler_id: AtomicU32::new(0),
+ group_cache: tokio::sync::Mutex::new(HashMap::new()),
+ user_devices_cache: tokio::sync::Mutex::new(HashMap::new()),
+ tc_token_sender_ts: Mutex::new(Default::default()),
+ tc_token_db_prune: tokio::sync::Mutex::new(None),
+ media_conn_cache: tokio::sync::Mutex::new(None),
+ phone_linking_cache: Mutex::new(None),
+ passkey_state: Mutex::new(Default::default()),
+ privacy_settings_cache: Mutex::new(None),
+ app_state_proc,
+ app_state_sync_lock: tokio::sync::Mutex::new(()),
+ app_state_key_requests: Mutex::new(HashMap::new()),
+ last_decrypted_buffer_clear: Mutex::new(None),
+ history_sync_notifications,
+ history_sync_notifications_receiver: tokio::sync::Mutex::new(
+ history_sync_notifications_receiver,
+ ),
+ history_sync_handler_started: AtomicBool::new(false),
+ message_retries: Mutex::new(HashMap::new()),
+ pending_phone_rerequests: Mutex::new(HashMap::new()),
+ recent_messages: Mutex::new(Default::default()),
+ retry_state: Mutex::new(Default::default()),
+ message_send_lock: tokio::sync::Mutex::new(()),
+ unique_id: format!("{}.{}-", unique_id_prefix[0], unique_id_prefix[1]),
+ id_counter: AtomicU64::new(0),
+ server_time_offset: AtomicI64::new(0),
+ tasks: TaskTracker::new(),
+ background: CancellationToken::new(),
+ })
+ }
+
+ /// The XEdDSA implementation.
+ pub(crate) fn signatures(&self) -> &dyn CurveSignatures {
+ self.signal.as_ref()
+ }
+
+ /// Spawns a background task on the client's tracker.
+ pub(crate) fn spawn<Task>(&self, task: Task)
+ where
+ Task: Future<Output = ()> + Send + 'static,
+ {
+ self.tasks.spawn(task);
+ }
+
+ /// Spawns `dispatch_event` in the background (Go's `go cli.dispatchEvent`).
+ pub(crate) fn spawn_dispatch(self: &Arc<Self>, event: Event) {
+ let client = Arc::clone(self);
+ self.spawn(async move {
+ client.dispatch_event(event).await;
+ });
+ }
+
+ fn notify_socket_waiters(&self) {
+ self.socket_wait.send_modify(|generation| *generation += 1);
+ }
+
+ /// The device's JID, or the empty JID before pairing.
+ pub async fn get_own_id(&self) -> Jid {
+ self.store.read().await.get_jid()
+ }
+
+ /// The device's LID, or the empty JID when unknown.
+ pub async fn get_own_lid(&self) -> Jid {
+ self.store.read().await.get_lid()
+ }
+
+ /// Waits until the client is connected and logged in, the timeout passes,
+ /// or a disconnect is expected.
+ pub async fn wait_for_connection(&self, timeout: Duration) -> bool {
+ let deadline = tokio::time::Instant::now() + timeout;
+ loop {
+ let mut waiter = self.socket_wait.subscribe();
+ {
+ let state = self.socket.read().await;
+ if state
+ .socket
+ .as_ref()
+ .is_some_and(|socket| socket.is_connected())
+ && self.is_logged_in()
+ {
+ return true;
+ }
+ }
+ tokio::select! {
+ _ = waiter.changed() => {}
+ () = tokio::time::sleep_until(deadline) => return false,
+ () = self.expected_disconnect.wait() => return false,
+ }
+ }
+ }
+
+ /// Connects to the WhatsApp web websocket. After connecting, the client
+ /// either logs in with the stored device or emits [`Event::Qr`] to pair a
+ /// new one.
+ #[tracing::instrument(name = "whatsmeow.connect", skip_all, err)]
+ pub async fn connect(self: &Arc<Self>) -> Result<(), ClientError> {
+ let mut state = self.socket.write().await;
+ let result = self.unlocked_connect(&mut state).await;
+ drop(state);
+ if let Err(error) = &result
+ && is_retryable_connect_error(error)
+ && self.config.initial_auto_reconnect
+ && self.config.enable_auto_reconnect
+ {
+ tracing::error!(error = %error, "initial connection failed but reconnecting in background");
+ self.spawn_dispatch(Event::Disconnected(Disconnected));
+ let client = Arc::clone(self);
+ self.spawn(async move { client.auto_reconnect().await });
+ return Ok(());
+ }
+ result
+ }
+
+ async fn connect_inner(self: &Arc<Self>) -> Result<(), ClientError> {
+ let mut state = self.socket.write().await;
+ self.unlocked_connect(&mut state).await
+ }
+
+ /// Boxed with an explicit `Send` bound to break the inference cycle
+ /// through handlers that reconnect (see [`Client::auto_reconnect`]).
+ fn unlocked_connect<'call>(
+ self: &'call Arc<Self>,
+ state: &'call mut SocketState,
+ ) -> BoxFuture<'call, Result<(), ClientError>> {
+ Box::pin(self.unlocked_connect_inner(state))
+ }
+
+ async fn unlocked_connect_inner(
+ self: &Arc<Self>,
+ state: &mut SocketState,
+ ) -> Result<(), ClientError> {
+ if self.store.read().await.deleted {
+ return Err(StoreError::DeviceDeleted.into());
+ }
+ if let Some(socket) = &state.socket {
+ if !socket.is_connected() {
+ self.unlocked_disconnect(state).await;
+ } else {
+ return Err(ClientError::AlreadyConnected);
+ }
+ }
+
+ self.reset_expected_disconnect();
+ let (frame_socket, frames) = self.config.dialer.dial().await?;
+ let (noise_key, client_payload) = {
+ let store = self.store.read().await;
+ let payload = store.get_client_payload().map_err(|error| {
+ ClientError::Other(format!("got invalid client payload: {error}"))
+ });
+ (store.noise_key.clone(), payload)
+ };
+ let client_payload = match client_payload {
+ Ok(payload) => payload,
+ Err(error) => {
+ frame_socket.close(None).await;
+ return Err(error);
+ }
+ };
+ let (noise_socket, noise_events) = match do_handshake(
+ frame_socket.clone(),
+ frames,
+ &new_key_pair(),
+ &noise_key,
+ &client_payload,
+ self.signatures(),
+ )
+ .await
+ {
+ Ok(result) => result,
+ Err(error) => {
+ frame_socket.close(None).await;
+ return Err(error.into());
+ }
+ };
+ let noise_socket = Arc::new(noise_socket);
+ let connection = CancellationToken::new();
+ let (queue_sender, queue_receiver) = mpsc::channel(HANDLER_QUEUE_SIZE);
+ let (close_wait_sender, close_wait_receiver) = oneshot::channel();
+ state.socket = Some(Arc::clone(&noise_socket));
+ state.connection = Some(connection.clone());
+ state.handler_queue_wait = Some(close_wait_receiver);
+
+ let client = Arc::clone(self);
+ let reader_connection = connection.clone();
+ self.spawn(async move {
+ client
+ .read_loop(noise_socket, noise_events, queue_sender, reader_connection)
+ .await;
+ });
+ let client = Arc::clone(self);
+ let keepalive_connection = connection.clone();
+ self.spawn(async move { client.keep_alive_loop(keepalive_connection).await });
+ let client = Arc::clone(self);
+ self.spawn(async move {
+ client
+ .handler_queue_loop(connection, queue_receiver, close_wait_sender)
+ .await;
+ });
+ Ok(())
+ }
+
+ /// Feeds decrypted frames into the node queue and reports the
+ /// disconnect (Go wires these as noise socket callbacks).
+ async fn read_loop(
+ self: Arc<Self>,
+ noise_socket: Arc<NoiseSocket>,
+ mut events: mpsc::Receiver<NoiseEvent>,
+ queue: mpsc::Sender<Node>,
+ connection: CancellationToken,
+ ) {
+ while let Some(event) = events.recv().await {
+ match event {
+ NoiseEvent::Frame(data) => self.handle_frame(&data, &queue),
+ NoiseEvent::Disconnected { remote } => {
+ connection.cancel();
+ self.on_disconnect(&noise_socket, remote).await;
+ return;
+ }
+ }
+ }
+ connection.cancel();
+ }
+
+ /// Whether the client is connected and authenticated.
+ pub fn is_logged_in(&self) -> bool {
+ self.is_logged_in.load(Ordering::SeqCst)
+ }
+
+ pub(crate) fn set_logged_in(&self, logged_in: bool) {
+ self.is_logged_in.store(logged_in, Ordering::SeqCst);
+ }
+
+ async fn on_disconnect(self: &Arc<Self>, noise_socket: &Arc<NoiseSocket>, remote: bool) {
+ noise_socket.stop(false, false).await;
+ let mut state = self.socket.write().await;
+ if state
+ .socket
+ .as_ref()
+ .is_some_and(|current| Arc::ptr_eq(current, noise_socket))
+ {
+ state.socket = None;
+ self.clear_response_waiters(&xml_stream_end_node());
+ if !self.is_expected_disconnect()
+ && (self.force_auto_reconnect.swap(false, Ordering::SeqCst) || remote)
+ {
+ tracing::debug!("emitting Disconnected event");
+ self.spawn_dispatch(Event::Disconnected(Disconnected));
+ let client = Arc::clone(self);
+ self.spawn(async move { client.auto_reconnect().await });
+ } else if remote {
+ tracing::debug!("on_disconnect called, but it was expected, so not emitting event");
+ } else {
+ tracing::debug!("on_disconnect called after manual disconnection");
+ }
+ } else {
+ tracing::debug!("ignoring on_disconnect on different socket");
+ }
+ }
+
+ pub(crate) fn expect_disconnect(&self) {
+ self.force_auto_reconnect.store(false, Ordering::SeqCst);
+ self.expected_disconnect.set();
+ }
+
+ pub(crate) fn reset_expected_disconnect(&self) {
+ self.force_auto_reconnect.store(false, Ordering::SeqCst);
+ self.expected_disconnect.clear();
+ }
+
+ pub(crate) fn is_expected_disconnect(&self) -> bool {
+ self.expected_disconnect.is_set()
+ }
+
+ /// Boxed with an explicit `Send` bound: reconnecting calls back into
+ /// `connect`, whose tasks can start another reconnect, and the compiler
+ /// can't infer `Send` through that cycle.
+ pub(crate) fn auto_reconnect(self: Arc<Self>) -> BoxFuture<'static, ()> {
+ Box::pin(self.auto_reconnect_inner())
+ }
+
+ async fn auto_reconnect_inner(self: Arc<Self>) {
+ if !self.config.enable_auto_reconnect || self.store.read().await.id.is_none() {
+ return;
+ }
+ loop {
+ let errors = self.auto_reconnect_errors.fetch_add(1, Ordering::SeqCst);
+ let delay = Duration::from_secs(u64::from(errors) * 2);
+ tracing::debug!(delay = ?delay, "automatically reconnecting");
+ tokio::select! {
+ () = self.expected_disconnect.wait() => {
+ tracing::debug!("cancelling automatic reconnect due to expected disconnect");
+ return;
+ }
+ () = self.background.cancelled() => {
+ tracing::debug!("cancelling automatic reconnect due to client shutdown");
+ return;
+ }
+ () = tokio::time::sleep(delay) => {}
+ }
+ match self.connect_inner().await {
+ Err(ClientError::AlreadyConnected) => {
+ tracing::debug!(
+ "connect said we're already connected after autoreconnect sleep"
+ );
+ return;
+ }
+ Err(error) => {
+ if self.expected_disconnect.is_set() {
+ tracing::debug!(
+ "autoreconnect failed, but disconnect was expected, not reconnecting"
+ );
+ return;
+ }
+ tracing::error!(error = %error, "error reconnecting after autoreconnect sleep");
+ if let Some(hook) = &self.config.auto_reconnect_hook
+ && !hook(&error)
+ {
+ tracing::debug!("auto reconnect hook returned false, not reconnecting");
+ return;
+ }
+ }
+ Ok(()) => return,
+ }
+ }
+ }
+
+ /// Whether the websocket is connected (not necessarily authenticated).
+ pub async fn is_connected(&self) -> bool {
+ self.socket
+ .read()
+ .await
+ .socket
+ .as_ref()
+ .is_some_and(|socket| socket.is_connected())
+ }
+
+ /// Disconnects from the websocket. Emits no event: [`Event::Disconnected`]
+ /// is only for disconnects caused by the server or the network.
+ pub async fn disconnect(&self) {
+ let mut state = self.socket.write().await;
+ self.expect_disconnect();
+ self.unlocked_disconnect(&mut state).await;
+ drop(state);
+ self.clear_delayed_message_requests();
+ }
+
+ /// Disconnects and forces an automatic reconnect. Does nothing when the
+ /// socket is already disconnected or auto-reconnect is off.
+ pub async fn reset_connection(&self) {
+ let state = self.socket.write().await;
+ self.force_auto_reconnect.store(true, Ordering::SeqCst);
+ if let Some(socket) = &state.socket {
+ socket.stop(true, true).await;
+ self.clear_response_waiters(&xml_stream_end_node());
+ }
+ }
+
+ async fn unlocked_disconnect(&self, state: &mut SocketState) {
+ if let Some(socket) = state.socket.take() {
+ socket.stop(true, false).await;
+ self.clear_response_waiters(&xml_stream_end_node());
+ }
+ if let Some(connection) = state.connection.take() {
+ connection.cancel();
+ }
+ if let Some(wait) = state.handler_queue_wait.take()
+ && tokio::time::timeout(Duration::from_secs(5), wait)
+ .await
+ .is_err()
+ {
+ tracing::warn!("handler queue wait channel not closed after 5 seconds");
+ }
+ }
+
+ /// Asks the server to unlink this device, then disconnects and deletes
+ /// the local device. Emits no event: [`Event::LoggedOut`] is only for
+ /// logouts triggered elsewhere.
+ pub async fn logout(&self) -> Result<(), ClientError> {
+ let own_id = self.get_own_id().await;
+ if own_id.is_empty() {
+ return Err(ClientError::NotLoggedIn);
+ }
+ self.send_iq(crate::request::InfoQuery {
+ namespace: "md",
+ r#type: crate::request::IqType::Set,
+ to: crate::types::SERVER_JID.clone(),
+ content: Some(NodeContent::Nodes(vec![Node {
+ tag: "remove-companion-device".to_owned(),
+ attrs: Attrs::from([
+ ("jid".to_owned(), own_id.into()),
+ ("reason".to_owned(), "user_initiated".into()),
+ ]),
+ content: None,
+ }])),
+ ..Default::default()
+ })
+ .await
+ .map_err(|error| error.wrap("error sending logout request"))?;
+ self.disconnect().await;
+ self.delete_device()
+ .await
+ .map_err(|error| ClientError::from(error).wrap("error deleting data from store"))
+ }
+
+ /// Registers an event handler; returns its ID for
+ /// [`Client::remove_event_handler`].
+ pub fn add_event_handler(&self, handler: Arc<dyn EventHandler>) -> u32 {
+ let id = self.next_handler_id.fetch_add(1, Ordering::SeqCst) + 1;
+ self.event_handlers
+ .write()
+ .unwrap_or_else(PoisonError::into_inner)
+ .push((id, handler));
+ id
+ }
+
+ /// Registers a synchronous event handler function that always succeeds.
+ pub fn add_event_fn<Function>(&self, handler: Function) -> u32
+ where
+ Function: Fn(&Event) + Send + Sync + 'static,
+ {
+ self.add_event_handler(Arc::new(FnHandler(handler)))
+ }
+
+ /// A channel that receives every event from now on.
+ pub fn subscribe(&self) -> mpsc::UnboundedReceiver<Event> {
+ let (sender, receiver) = mpsc::unbounded_channel();
+ self.add_event_fn(move |event| {
+ let _ = sender.send(event.clone());
+ });
+ receiver
+ }
+
+ /// Removes an event handler; returns whether it was found.
+ pub fn remove_event_handler(&self, id: u32) -> bool {
+ let mut handlers = self
+ .event_handlers
+ .write()
+ .unwrap_or_else(PoisonError::into_inner);
+ let before = handlers.len();
+ handlers.retain(|(handler_id, _)| *handler_id != id);
+ handlers.len() != before
+ }
+
+ /// Removes every event handler.
+ pub fn remove_event_handlers(&self) {
+ self.event_handlers
+ .write()
+ .unwrap_or_else(PoisonError::into_inner)
+ .clear();
+ }
+
+ fn handle_frame(self: &Arc<Self>, data: &[u8], queue: &mpsc::Sender<Node>) {
+ let decompressed = match unpack(data) {
+ Ok(decompressed) => decompressed,
+ Err(error) => {
+ tracing::warn!(error = %error, "failed to decompress frame");
+ return;
+ }
+ };
+ let node = match unmarshal(&decompressed) {
+ Ok(node) => node,
+ Err(error) => {
+ tracing::warn!(error = %error, "failed to decode node in frame");
+ return;
+ }
+ };
+ tracing::trace!(tag = %node.tag, "received node");
+ if node.tag == "xmlstreamend" {
+ if !self.is_expected_disconnect() {
+ tracing::warn!("received stream end frame");
+ }
+ } else if self.receive_response(&node) {
+ // handled
+ } else if NODE_HANDLER_TAGS.contains(&node.tag.as_str()) {
+ match queue.try_send(node) {
+ Ok(()) => {}
+ Err(mpsc::error::TrySendError::Full(node)) => {
+ tracing::warn!(
+ "handler queue is full, message ordering is no longer guaranteed"
+ );
+ let queue = queue.clone();
+ self.spawn(async move {
+ let _ = queue.send(node).await;
+ });
+ }
+ Err(mpsc::error::TrySendError::Closed(_)) => {}
+ }
+ } else if node.tag != "ack" {
+ tracing::debug!(tag = %node.tag, "didn't handle WhatsApp node");
+ }
+ }
+
+ async fn handler_queue_loop(
+ self: Arc<Self>,
+ connection: CancellationToken,
+ mut queue: mpsc::Receiver<Node>,
+ close_wait: oneshot::Sender<()>,
+ ) {
+ const SLOW_HANDLER_WARNING: Duration = Duration::from_secs(30);
+ tracing::debug!("starting handler queue loop");
+ 'nodes: loop {
+ let node = tokio::select! {
+ node = queue.recv() => node,
+ () = connection.cancelled() => {
+ tracing::debug!("closing handler queue loop");
+ break;
+ }
+ };
+ let Some(node) = node else { break };
+ if connection.is_cancelled() {
+ // Deviation from Go: the node is already dequeued, so the
+ // drain below wouldn't see it. A stream error (the 515
+ // after pairing) must still be handled or the reconnect
+ // is lost.
+ if node.tag == "stream:error" {
+ tracing::debug!(
+ "handling stream:error node dequeued after the connection ended"
+ );
+ self.handle_stream_error(&node).await;
+ }
+ tracing::debug!("closing handler queue loop before node handling");
+ break;
+ }
+ let tag = node.tag.clone();
+ let client = Arc::clone(&self);
+ let start = tokio::time::Instant::now();
+ let mut handler = self.tasks.spawn(async move {
+ client.handle_node(node).await;
+ let duration = start.elapsed();
+ if duration > Duration::from_secs(5) {
+ tracing::warn!(duration = ?duration, "node handling took long");
+ }
+ });
+ for _ in 0..10 {
+ tokio::select! {
+ _ = &mut handler => continue 'nodes,
+ () = connection.cancelled() => {
+ tracing::warn!(tag = %tag, "closing handler queue loop in the middle of handling a node");
+ break 'nodes;
+ }
+ () = tokio::time::sleep(SLOW_HANDLER_WARNING) => {
+ tracing::warn!(tag = %tag, elapsed = ?start.elapsed(), "node handling is taking long");
+ }
+ }
+ }
+ tracing::warn!(tag = %tag, "continuing handling of node in background as it's taking too long");
+ }
+ // Stream errors are handled even after disconnection so the
+ // appropriate auto-reconnect is done.
+ while let Ok(node) = queue.try_recv() {
+ if node.tag == "stream:error" {
+ tracing::debug!(
+ "handling stream:error node in handler queue loop after context cancellation"
+ );
+ self.handle_stream_error(&node).await;
+ }
+ }
+ let _ = close_wait.send(());
+ }
+
+ /// Dispatches a node to its handler (Go's `nodeHandlers` map).
+ /// Boxed with an explicit `Send` bound to break the inference cycle
+ /// through handlers that reconnect (see [`Client::auto_reconnect`]).
+ fn handle_node(self: Arc<Self>, node: Node) -> BoxFuture<'static, ()> {
+ let span = tracing::info_span!("whatsmeow.handle_node", tag = %node.tag);
+ Box::pin(self.handle_node_inner(node).instrument(span))
+ }
+
+ async fn handle_node_inner(self: Arc<Self>, node: Node) {
+ match node.tag.as_str() {
+ "success" => self.handle_connect_success(&node).await,
+ "failure" => self.handle_connect_failure(&node).await,
+ "stream:error" => self.handle_stream_error(&node).await,
+ "iq" => self.handle_iq(&node).await,
+ "ib" => self.handle_ib(&node).await,
+ "notification" => self.handle_notification(&node).await,
+ "chatstate" => self.handle_chat_state(&node).await,
+ "presence" => self.handle_presence(&node).await,
+ "message" | "appdata" => self.handle_encrypted_message(&node).await,
+ "status" => self.handle_unencrypted_message(&node).await,
+ "receipt" => self.handle_receipt(&node).await,
+ other => self.handle_unported_node(other, &node).await,
+ }
+ }
+
+ /// Calls aren't ported; call nodes are acked so the server doesn't
+ /// redeliver them forever.
+ async fn handle_unported_node(self: &Arc<Self>, tag: &str, node: &Node) {
+ tracing::debug!(tag, "no handler for node yet, acking it");
+ if tag == "call" {
+ self.send_ack(node, 0).await;
+ }
+ }
+
+ /// Marshals and sends a node; returns the marshaled bytes.
+ pub(crate) async fn send_node_and_get_data(&self, node: &Node) -> Result<Vec<u8>, ClientError> {
+ let socket = self.socket.read().await.socket.clone();
+ let Some(socket) = socket else {
+ return Err(ClientError::NotConnected);
+ };
+ let payload = marshal(node)?;
+ tracing::trace!(tag = %node.tag, "sending node");
+ socket.send_frame(&payload).await?;
+ Ok(payload)
+ }
+
+ /// Marshals and sends a node.
+ pub(crate) async fn send_node(&self, node: &Node) -> Result<(), ClientError> {
+ self.send_node_and_get_data(node).await.map(|_| ())
+ }
+
+ /// Sends an event to every handler; returns whether a handler failed.
+ pub(crate) async fn dispatch_event(&self, event: Event) -> bool {
+ let handlers: Vec<Arc<dyn EventHandler>> = self
+ .event_handlers
+ .read()
+ .unwrap_or_else(PoisonError::into_inner)
+ .iter()
+ .map(|(_, handler)| Arc::clone(handler))
+ .collect();
+ for handler in handlers {
+ match AssertUnwindSafe(handler.handle(&event))
+ .catch_unwind()
+ .await
+ {
+ Ok(true) => {}
+ Ok(false) => return true,
+ Err(_) => {
+ tracing::error!("event handler panicked");
+ return false;
+ }
+ }
+ }
+ false
+ }
+
+ /// Parses a history sync `WebMessageInfo` into the [`Event::Message`]
+ /// real-time messages produce (`ParseWebMessage`). An empty `chat_jid`
+ /// is taken from the message key.
+ pub async fn parse_web_message(
+ &self,
+ chat_jid: &Jid,
+ web_message: crate::proto::wa_web::WebMessageInfo,
+ ) -> Result<crate::types::events::Message, ClientError> {
+ use crate::types::{
+ GROUP_SERVER, MessageInfo, MessageSource, NEWSLETTER_SERVER, parse_jid,
+ };
+ let key = web_message.key.clone();
+ let chat_jid = if chat_jid.is_empty() {
+ parse_jid(key.remote_jid.as_deref().unwrap_or_default()).map_err(|error| {
+ ClientError::Other(format!(
+ "no chat JID provided and failed to parse remote JID: {error}"
+ ))
+ })?
+ } else {
+ chat_jid.clone()
+ };
+ let mut info = MessageInfo {
+ source: MessageSource {
+ is_from_me: key.from_me.unwrap_or_default(),
+ is_group: chat_jid.server == GROUP_SERVER,
+ chat: chat_jid.clone(),
+ ..MessageSource::default()
+ },
+ id: key.id.clone().unwrap_or_default(),
+ push_name: web_message.push_name.clone().unwrap_or_default(),
+ timestamp: DateTime::from_timestamp(
+ i64::try_from(web_message.message_timestamp.unwrap_or_default())
+ .unwrap_or_default(),
+ 0,
+ ),
+ ..MessageInfo::default()
+ };
+ let parse_sender = |jid: &str| {
+ parse_jid(jid).map_err(|error| {
+ ClientError::Other(format!(
+ "failed to parse sender of message {}: {error}",
+ info.id
+ ))
+ })
+ };
+ let sender = if info.is_from_me {
+ match web_message
+ .original_self_author_user_jid_string
+ .as_deref()
+ .filter(|jid| !jid.is_empty())
+ {
+ Some(author) => parse_sender(author)?,
+ None => {
+ let own = if info.chat.server == HIDDEN_USER_SERVER {
+ self.get_own_lid().await
+ } else {
+ self.get_own_id().await
+ }
+ .to_non_ad();
+ if own.is_empty() {
+ return Err(ClientError::NotLoggedIn);
+ }
+ own
+ }
+ }
+ } else if chat_jid.server == DEFAULT_USER_SERVER
+ || chat_jid.server == HIDDEN_USER_SERVER
+ || chat_jid.server == NEWSLETTER_SERVER
+ {
+ chat_jid.clone()
+ } else if let Some(participant) =
+ web_message.participant.as_deref().filter(|p| !p.is_empty())
+ {
+ parse_sender(participant)?
+ } else if let Some(participant) = key.participant.as_deref().filter(|p| !p.is_empty()) {
+ parse_sender(participant)?
+ } else {
+ return Err(ClientError::Other(format!(
+ "couldn't find sender of message {}",
+ info.id
+ )));
+ };
+ info.sender = sender;
+ if let Some(parent_key) = web_message
+ .comment_metadata
+ .as_ref()
+ .and_then(|metadata| metadata.comment_parent_key.as_ref())
+ {
+ info.msg_meta_info.thread_message_id = parent_key.id.clone().unwrap_or_default();
+ info.msg_meta_info.thread_message_sender_jid =
+ parse_jid(parent_key.participant.as_deref().unwrap_or_default())
+ .unwrap_or_default();
+ }
+ let mut event = crate::types::events::Message {
+ info,
+ raw_message: web_message.message.clone(),
+ source_web_msg: Some(web_message),
+ ..Default::default()
+ };
+ event.unwrap_raw();
+ if let Some(protocol_message) = event
+ .message
+ .as_ref()
+ .and_then(|message| message.protocol_message.as_ref())
+ && protocol_message.r#type
+ == Some(crate::proto::wa_e2e::protocol_message::Type::MessageEdit as i32)
+ {
+ let edited_id = protocol_message
+ .key
+ .as_ref()
+ .and_then(|key| key.id.clone())
+ .unwrap_or_default();
+ let edited = protocol_message.edited_message.as_deref().cloned();
+ event.info.id = edited_id;
+ event.message = edited;
+ }
+ Ok(event)
+ }
+
+ /// Stores a LID ↔ phone number mapping, in either order.
+ pub async fn store_lid_pn_mapping(&self, first: &Jid, second: &Jid) {
+ let (lid, pn) =
+ if first.server == HIDDEN_USER_SERVER && second.server == DEFAULT_USER_SERVER {
+ (first, second)
+ } else if first.server == DEFAULT_USER_SERVER && second.server == HIDDEN_USER_SERVER {
+ (second, first)
+ } else {
+ return;
+ };
+ let lids = Arc::clone(&self.store.read().await.lids);
+ if let Err(error) = lids.put_lid_mapping(lid, pn).await {
+ tracing::error!(error = %error, "failed to store LID-PN mapping");
+ }
+ }
+
+ fn get_unified_session_id(&self) -> String {
+ const UNIFIED_OFFSET_MILLIS: i64 = 3 * 24 * 60 * 60 * 1000;
+ const WEEK_MILLIS: i64 = 7 * 24 * 60 * 60 * 1000;
+ let offset_millis = self.server_time_offset.load(Ordering::SeqCst) / 1_000_000;
+ let unified = Utc::now().timestamp_millis() + offset_millis + UNIFIED_OFFSET_MILLIS;
+ (unified % WEEK_MILLIS).to_string()
+ }
+
+ pub(crate) async fn send_unified_session(&self) {
+ let node = Node {
+ tag: "ib".to_owned(),
+ attrs: Attrs::new(),
+ content: Some(NodeContent::Nodes(vec![Node {
+ tag: "unified_session".to_owned(),
+ attrs: Attrs::from([("id".to_owned(), self.get_unified_session_id().into())]),
+ content: None,
+ }])),
+ };
+ if let Err(error) = self.send_node(&node).await {
+ tracing::debug!(error = %error, "failed to send unified_session telemetry");
+ }
+ }
+
+ /// Records a successful login.
+ pub(crate) fn mark_connect_success(&self) {
+ *lock(&self.last_successful_connect) = Some(Utc::now());
+ self.auto_reconnect_errors.store(0, Ordering::SeqCst);
+ self.set_logged_in(true);
+ }
+
+ /// When the client last logged in successfully.
+ pub fn last_successful_connect(&self) -> Option<DateTime<Utc>> {
+ *lock(&self.last_successful_connect)
+ }
+
+ /// Wakes [`Client::wait_for_connection`] (Go's `closeSocketWaitChan`).
+ pub(crate) fn close_socket_wait_chan(&self) {
+ self.notify_socket_waiters();
+ }
+
+ /// Generates a request ID (`generateRequestID`).
+ pub(crate) fn generate_request_id(&self) -> String {
+ format!(
+ "{}{}",
+ self.unique_id,
+ self.id_counter.fetch_add(1, Ordering::SeqCst) + 1
+ )
+ }
+
+ pub(crate) fn response_waiters(
+ &self,
+ ) -> MutexGuard<'_, HashMap<String, oneshot::Sender<Node>>> {
+ lock(&self.response_waiters)
+ }
+
+ /// Waits until prekeys were uploaded after pairing (Go's
+ /// `PreKeysUploaded.Wait`).
+ pub async fn wait_pre_keys_uploaded(&self) {
+ self.pre_keys_uploaded.wait().await;
+ }
+
+ /// The app state processor for the device's current stores.
+ pub(crate) fn app_state_processor(&self) -> Arc<crate::appstate::Processor> {
+ Arc::clone(&lock(&self.app_state_proc))
+ }
+
+ /// Deletes the device from its container and points the app state
+ /// processor at the (now failing) stores, so it doesn't keep using the
+ /// deleted device's stores. Go builds the processor once and keeps it.
+ pub(crate) async fn delete_device(&self) -> Result<(), StoreError> {
+ let mut store = self.store.write().await;
+ let result = store.delete().await;
+ *lock(&self.app_state_proc) = Arc::new(crate::appstate::Processor::new(&store));
+ result
+ }
+
+ /// Stops background work: disconnects and waits for the client's tasks.
+ pub async fn shutdown(&self) {
+ self.disconnect().await;
+ self.background.cancel();
+ self.tasks.close();
+ self.tasks.wait().await;
+ }
+}
+
+impl Drop for Client {
+ fn drop(&mut self) {
+ self.background.cancel();
+ }
+}
+
+/// The node waiters receive when the websocket disconnects.
+pub(crate) fn xml_stream_end_node() -> Node {
+ Node {
+ tag: "xmlstreamend".to_owned(),
+ ..Node::default()
+ }
+}
+
+/// Network errors and some HTTP statuses are worth retrying.
+fn is_retryable_connect_error(error: &ClientError) -> bool {
+ match error {
+ ClientError::Socket(SocketError::DialFailed { status_code, .. }) => match status_code {
+ Some(code) => matches!(code, 408 | 500 | 501 | 502 | 503 | 504),
+ None => true,
+ },
+ ClientError::Socket(_) => true,
+ _ => false,
+ }
+}
+
+#[cfg(test)]
+pub(crate) mod test;
diff --git a/crates/whatsmeow/src/client/test.rs b/crates/whatsmeow/src/client/test.rs
new file mode 100644
index 0000000000..1aab2dde86
--- /dev/null
+++ b/crates/whatsmeow/src/client/test.rs
@@ -0,0 +1,711 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+//! The client against the fake WhatsApp server in `testing`: pairing, login,
+//! info queries, prekey upload and the connection lifecycle events.
+
+use std::sync::Arc;
+use std::time::Duration;
+
+use hmac::{Hmac, Mac};
+use prost::Message;
+use sha2::Sha256;
+use tokio::sync::mpsc;
+use tokio_util::sync::CancellationToken;
+
+use super::*;
+use crate::binary::{AttributeValue, NodeContent};
+use crate::proto::wa_adv::{
+ AdvDeviceIdentity, AdvSignedDeviceIdentity, AdvSignedDeviceIdentityHmac,
+};
+use crate::qrchan::QrChannelItem;
+use crate::signal::CurveSignatures;
+use crate::store::{IdentityStore, MemoryStore};
+use crate::testing::{
+ FakeServer, FakeSignal, FakeSignatures, ServerConnection, attr_string, is_iq,
+};
+use crate::types::events::ConnectFailureReason;
+use crate::types::{SERVER_JID, parse_jid};
+use crate::util::keys::new_key_pair;
+
+pub(crate) struct Harness {
+ pub(crate) client: Arc<Client>,
+ pub(crate) server: FakeServer,
+ pub(crate) store: Arc<MemoryStore>,
+ pub(crate) events: mpsc::UnboundedReceiver<Event>,
+}
+
+pub(crate) fn harness_with(
+ paired_as: Option<(&str, &str)>,
+ configure: impl FnOnce(&mut ClientConfig),
+) -> Harness {
+ let store = Arc::new(MemoryStore::default());
+ let mut device = store.new_device(&FakeSignatures);
+ if let Some((jid, lid)) = paired_as {
+ device.id = Some(parse_jid(jid).unwrap());
+ device.lid = parse_jid(lid).unwrap();
+ device.push_name = "Tester".to_owned();
+ }
+ let server = FakeServer::new();
+ let mut config = ClientConfig {
+ dialer: server.dialer(),
+ ..ClientConfig::default()
+ };
+ configure(&mut config);
+ let client = Client::new(device, Arc::new(FakeSignal), config);
+ let events = client.subscribe();
+ Harness {
+ client,
+ server,
+ store,
+ events,
+ }
+}
+
+pub(crate) fn harness(paired_as: Option<(&str, &str)>) -> Harness {
+ harness_with(paired_as, |_| {})
+}
+
+pub(crate) fn node(
+ tag: &str,
+ attrs: &[(&str, AttributeValue)],
+ content: Option<NodeContent>,
+) -> Node {
+ Node {
+ tag: tag.to_owned(),
+ attrs: attrs
+ .iter()
+ .map(|(key, value)| ((*key).to_owned(), value.clone()))
+ .collect(),
+ content,
+ }
+}
+
+pub(crate) fn children(nodes: Vec<Node>) -> Option<NodeContent> {
+ Some(NodeContent::Nodes(nodes))
+}
+
+pub(crate) fn bytes(data: &[u8]) -> Option<NodeContent> {
+ Some(NodeContent::Bytes(data.to_vec()))
+}
+
+pub(crate) fn jid(value: &str) -> AttributeValue {
+ AttributeValue::Jid(parse_jid(value).unwrap())
+}
+
+pub(crate) fn text(value: &str) -> AttributeValue {
+ AttributeValue::String(value.to_owned())
+}
+
+/// Skips keepalive pings and telemetry the tests don't care about.
+pub(crate) fn is_noise(node: &Node) -> bool {
+ is_iq(node, "w:p") || node.tag == "ib"
+}
+
+pub(crate) async fn next_node(connection: &mut ServerConnection) -> Node {
+ connection
+ .recv_node_skipping(is_noise)
+ .await
+ .expect("client sent a node")
+}
+
+pub(crate) async fn next_event(events: &mut mpsc::UnboundedReceiver<Event>) -> Event {
+ tokio::time::timeout(Duration::from_secs(120), events.recv())
+ .await
+ .expect("an event arrives")
+ .expect("the event channel is open")
+}
+
+/// Runs `call` against the fake server and returns the node it sends,
+/// normalized like the Go vectors (`captureNode`): the iq `id` is `ID` and a
+/// usync `sid` is `SID`. An iq gets a 500 error so the call returns.
+pub(crate) async fn capture_request<Call>(connection: &mut ServerConnection, call: Call) -> Node
+where
+ Call: Future + Send + 'static,
+ Call::Output: Send + 'static,
+{
+ let task = tokio::spawn(call);
+ let mut request = next_node(connection).await;
+ if request.tag == "iq" {
+ connection
+ .respond_iq_error(&request, 500, "internal-server-error")
+ .await;
+ request.attrs.insert("id".to_owned(), text("ID"));
+ if let Some(NodeContent::Nodes(children)) = &mut request.content
+ && children.len() == 1
+ && children[0].tag == "usync"
+ {
+ children[0].attrs.insert("sid".to_owned(), text("SID"));
+ }
+ }
+ let _ = task.await;
+ request
+}
+
+/// Answers the post-login requests (prekey count, upload, passive) until the
+/// client reports `Connected`.
+pub(crate) async fn complete_login(
+ connection: &mut ServerConnection,
+ events: &mut mpsc::UnboundedReceiver<Event>,
+ server_pre_key_count: usize,
+) -> Vec<Node> {
+ connection
+ .send_node(&node(
+ "success",
+ &[("t", text("1700000000")), ("lid", jid("9876:5@lid"))],
+ None,
+ ))
+ .await;
+ let mut requests = Vec::new();
+ let mut uploaded = false;
+ loop {
+ tokio::select! {
+ event = next_event(events) => {
+ if matches!(event, Event::Connected(_)) {
+ return requests;
+ }
+ }
+ request = next_node(connection) => {
+ if is_iq(&request, "encrypt") && attr_string(&request, "type") == "get" {
+ let count = if uploaded { 812 } else { server_pre_key_count };
+ connection
+ .respond_iq(&request, vec![node("count", &[("value", text(&count.to_string()))], None)])
+ .await;
+ } else if is_iq(&request, "encrypt") {
+ uploaded = true;
+ connection.respond_iq(&request, vec![]).await;
+ } else if request.tag == "iq" {
+ connection.respond_iq(&request, vec![]).await;
+ }
+ requests.push(request);
+ }
+ }
+ }
+}
+
+/// Logs a paired device in and returns the server side of the connection.
+pub(crate) async fn connect_paired(harness: &mut Harness) -> ServerConnection {
+ harness.client.connect().await.unwrap();
+ let mut connection = harness.server.accept().await.unwrap();
+ complete_login(&mut connection, &mut harness.events, 50).await;
+ connection
+}
+
+struct PrimaryDevice {
+ account_key: crate::util::keys::KeyPair,
+}
+
+impl PrimaryDevice {
+ fn pair_success(&self, device: &Device, request_id: &str) -> Node {
+ let details = AdvDeviceIdentity {
+ raw_id: Some(77),
+ timestamp: Some(1_700_000_000),
+ key_index: Some(3),
+ ..Default::default()
+ }
+ .encode_to_vec();
+ let message = [
+ &crate::pair::ADV_ACCOUNT_SIGNATURE_PREFIX[..],
+ &details,
+ &device.identity_key.public,
+ ]
+ .concat();
+ let signed = AdvSignedDeviceIdentity {
+ details: Some(details),
+ account_signature_key: Some(self.account_key.public.to_vec()),
+ account_signature: Some(
+ FakeSignatures
+ .calculate_signature(&self.account_key.private, &message)
+ .to_vec(),
+ ),
+ device_signature: None,
+ }
+ .encode_to_vec();
+ let mut mac = <Hmac<Sha256> as Mac>::new_from_slice(&device.adv_secret_key).unwrap();
+ mac.update(&signed);
+ let container = AdvSignedDeviceIdentityHmac {
+ details: Some(signed),
+ hmac: Some(mac.finalize().into_bytes().to_vec()),
+ account_type: None,
+ }
+ .encode_to_vec();
+ node(
+ "iq",
+ &[
+ ("from", AttributeValue::Jid(SERVER_JID.clone())),
+ ("id", text(request_id)),
+ ("type", text("set")),
+ ("xmlns", text("md")),
+ ("t", text("1700000000")),
+ ],
+ children(vec![node(
+ "pair-success",
+ &[],
+ children(vec![
+ node("device-identity", &[], bytes(&container)),
+ node(
+ "device",
+ &[
+ ("jid", jid("1234:[email protected]")),
+ ("lid", jid("9876:5@lid")),
+ ],
+ None,
+ ),
+ node("platform", &[("name", text("android"))], None),
+ node("biz", &[("name", text("Shop"))], None),
+ ]),
+ )]),
+ )
+ }
+}
+
+#[tokio::test(start_paused = true)]
+async fn pairing_with_qr_codes_then_logging_in() {
+ let mut harness = harness(None);
+ let mut qr = harness
+ .client
+ .get_qr_channel(CancellationToken::new())
+ .await
+ .unwrap();
+ harness.client.connect().await.unwrap();
+
+ let mut connection = harness.server.accept().await.unwrap();
+ assert!(connection.client_payload.device_pairing_data.is_some());
+ assert_eq!(connection.client_payload.username, None);
+
+ connection
+ .send_node(&node(
+ "iq",
+ &[
+ ("from", AttributeValue::Jid(SERVER_JID.clone())),
+ ("id", text("pair-1")),
+ ("type", text("set")),
+ ("xmlns", text("md")),
+ ],
+ children(vec![node(
+ "pair-device",
+ &[],
+ children(vec![
+ node("ref", &[], bytes(b"2@first")),
+ node("ref", &[], bytes(b"2@second")),
+ ]),
+ )]),
+ ))
+ .await;
+ let ack = next_node(&mut connection).await;
+ assert_eq!(ack.tag, "iq");
+ assert_eq!(attr_string(&ack, "id"), "pair-1");
+ assert_eq!(attr_string(&ack, "type"), "result");
+
+ let Some(QrChannelItem::Code { code, timeout }) = qr.recv().await else {
+ panic!("expected a QR code");
+ };
+ let (noise_public, identity_public, adv_secret) = {
+ let store = harness.client.store.read().await;
+ (
+ store.noise_key.public,
+ store.identity_key.public,
+ store.adv_secret_key.clone(),
+ )
+ };
+ use base64::Engine;
+ let base64 = base64::engine::general_purpose::STANDARD;
+ assert_eq!(
+ code,
+ format!(
+ "https://wa.me/settings/linked_devices#2@first,{},{},{},9",
+ base64.encode(noise_public),
+ base64.encode(identity_public),
+ base64.encode(&adv_secret),
+ )
+ );
+ assert_eq!(timeout, Duration::from_secs(20));
+ let Some(QrChannelItem::Code { code, .. }) = qr.recv().await else {
+ panic!("expected the second QR code after the first expired");
+ };
+ assert!(code.starts_with("https://wa.me/settings/linked_devices#2@second,"));
+
+ let primary = PrimaryDevice {
+ account_key: new_key_pair(),
+ };
+ let pair_success = {
+ let store = harness.client.store.read().await;
+ primary.pair_success(&store, "pair-2")
+ };
+ connection.send_node(&pair_success).await;
+
+ let confirmation = next_node(&mut connection).await;
+ assert_eq!(attr_string(&confirmation, "type"), "result");
+ assert_eq!(attr_string(&confirmation, "id"), "pair-2");
+ let device_identity = confirmation.get_child_by_tag(&["pair-device-sign", "device-identity"]);
+ assert_eq!(attr_string(device_identity, "key-index"), "3");
+ let Some(NodeContent::Bytes(signed)) = &device_identity.content else {
+ panic!("device identity has bytes");
+ };
+ let signed = AdvSignedDeviceIdentity::decode(signed.as_slice()).unwrap();
+ assert_eq!(signed.account_signature_key, None);
+ let message = [
+ &crate::pair::ADV_DEVICE_SIGNATURE_PREFIX[..],
+ signed.details.as_deref().unwrap(),
+ &identity_public,
+ &primary.account_key.public,
+ ]
+ .concat();
+ let identity_private = harness.client.store.read().await.identity_key.private;
+ assert_eq!(
+ signed.device_signature.as_deref(),
+ Some(&FakeSignatures.calculate_signature(&identity_private, &message)[..])
+ );
+
+ loop {
+ match next_event(&mut harness.events).await {
+ Event::PairSuccess(success) => {
+ assert_eq!(success.id.to_string(), "1234:[email protected]");
+ assert_eq!(success.lid.to_string(), "9876:5@lid");
+ assert_eq!(success.platform, "android");
+ assert_eq!(success.business_name, "Shop");
+ break;
+ }
+ Event::Qr(_) => {}
+ other => panic!("unexpected event {other:?}"),
+ }
+ }
+ assert!(matches!(qr.recv().await, Some(QrChannelItem::Success)));
+ assert!(qr.recv().await.is_none());
+ assert_eq!(
+ harness.store.saved_devices(),
+ vec![parse_jid("1234:[email protected]").unwrap()]
+ );
+ assert!(
+ !harness
+ .store
+ .is_trusted_identity("9876_1:0", [1; 32])
+ .await
+ .unwrap(),
+ "the primary device's identity is stored under its LID address"
+ );
+ assert!(
+ harness
+ .store
+ .is_trusted_identity("9876_1:0", primary.account_key.public)
+ .await
+ .unwrap()
+ );
+
+ // The server restarts the stream after pairing; the client logs in.
+ connection
+ .send_node(&node("stream:error", &[("code", text("515"))], None))
+ .await;
+ let mut connection = harness.server.accept().await.unwrap();
+ assert_eq!(connection.client_payload.username, Some(1234));
+ assert_eq!(connection.client_payload.device, Some(5));
+ let requests = complete_login(&mut connection, &mut harness.events, 0).await;
+ let upload = requests
+ .iter()
+ .find(|request| is_iq(request, "encrypt") && attr_string(request, "type") == "set")
+ .expect("the client uploads prekeys");
+ let list = upload.get_child_by_tag(&["list"]);
+ assert_eq!(
+ list.get_children().len(),
+ 812,
+ "the first upload after pairing"
+ );
+ assert!(harness.client.is_logged_in());
+ assert!(requests.iter().any(|request| is_iq(request, "passive")
+ && request.get_optional_child_by_tag(&["active"]).is_some()));
+}
+
+#[tokio::test(start_paused = true)]
+async fn pair_success_with_a_bad_hmac_is_rejected() {
+ let mut harness = harness(None);
+ harness.client.connect().await.unwrap();
+ let mut connection = harness.server.accept().await.unwrap();
+ let mut pair_success = {
+ let store = harness.client.store.read().await;
+ PrimaryDevice {
+ account_key: new_key_pair(),
+ }
+ .pair_success(&store, "pair-3")
+ };
+ let identity = pair_success
+ .get_child_by_tag(&["pair-success", "device-identity"])
+ .clone();
+ let Some(NodeContent::Bytes(container)) = identity.content else {
+ panic!("container bytes");
+ };
+ let mut container = AdvSignedDeviceIdentityHmac::decode(container.as_slice()).unwrap();
+ container.hmac = Some(vec![0; 32]);
+ if let Some(NodeContent::Nodes(children)) = &mut pair_success.content
+ && let Some(NodeContent::Nodes(inner)) = &mut children[0].content
+ {
+ inner[0].content = bytes(&container.encode_to_vec());
+ }
+ connection.send_node(&pair_success).await;
+
+ let error = next_node(&mut connection).await;
+ assert_eq!(attr_string(&error, "type"), "error");
+ let error_child = error.get_child_by_tag(&["error"]);
+ assert_eq!(attr_string(error_child, "code"), "401");
+ assert_eq!(attr_string(error_child, "text"), "hmac-mismatch");
+ loop {
+ if let Event::PairError(pair_error) = next_event(&mut harness.events).await {
+ assert!(matches!(
+ *pair_error.error,
+ ClientError::PairInvalidDeviceIdentityHmac
+ ));
+ break;
+ }
+ }
+ assert!(harness.client.store.read().await.id.is_none());
+}
+
+#[tokio::test(start_paused = true)]
+async fn info_queries_return_results_and_errors() {
+ let mut harness = harness(Some(("1234:[email protected]", "9876:5@lid")));
+ let mut connection = connect_paired(&mut harness).await;
+
+ let client = Arc::clone(&harness.client);
+ let passive = tokio::spawn(async move { client.set_passive(true).await });
+ let request = next_node(&mut connection).await;
+ assert!(is_iq(&request, "passive"));
+ assert_eq!(attr_string(&request, "type"), "set");
+ assert!(request.get_optional_child_by_tag(&["passive"]).is_some());
+ connection
+ .respond_iq_error(&request, 500, "internal-server-error")
+ .await;
+ let error = passive.await.unwrap().unwrap_err();
+ assert_eq!(
+ error.to_string(),
+ "info query returned status 500: internal-server-error"
+ );
+ assert!(error.is(&ClientError::iq_status(
+ crate::errors::IqError::INTERNAL_SERVER_ERROR
+ )));
+
+ let client = Arc::clone(&harness.client);
+ let passive = tokio::spawn(async move { client.set_passive(false).await });
+ let request = next_node(&mut connection).await;
+ connection.respond_iq(&request, vec![]).await;
+ passive.await.unwrap().unwrap();
+
+ let client = Arc::clone(&harness.client);
+ let timed_out = tokio::spawn(async move { client.set_passive(false).await });
+ let _ignored = next_node(&mut connection).await;
+ assert!(matches!(
+ timed_out.await.unwrap(),
+ Err(ClientError::IqTimedOut)
+ ));
+}
+
+#[tokio::test(start_paused = true)]
+async fn a_server_disconnect_interrupts_queries_and_reconnects() {
+ let mut harness = harness(Some(("1234:[email protected]", "9876:5@lid")));
+ let mut connection = connect_paired(&mut harness).await;
+
+ let client = Arc::clone(&harness.client);
+ let passive = tokio::spawn(async move { client.set_passive(true).await });
+ let first = next_node(&mut connection).await;
+ connection.close().await;
+ assert!(matches!(
+ next_event(&mut harness.events).await,
+ Event::Disconnected(_)
+ ));
+
+ // Auto-reconnect logs in again and the query is retried on the new socket.
+ let mut connection = harness.server.accept().await.unwrap();
+ connection
+ .send_node(&node("success", &[("t", text("1700000000"))], None))
+ .await;
+ loop {
+ let request = next_node(&mut connection).await;
+ if attr_string(&request, "id") == attr_string(&first, "id") {
+ connection.respond_iq(&request, vec![]).await;
+ break;
+ }
+ connection
+ .respond_iq(
+ &request,
+ vec![node("count", &[("value", text("50"))], None)],
+ )
+ .await;
+ }
+ passive.await.unwrap().unwrap();
+}
+
+#[tokio::test(start_paused = true)]
+async fn a_logged_out_connect_failure_deletes_the_device() {
+ let mut harness = harness(Some(("1234:[email protected]", "9876:5@lid")));
+ harness.client.connect().await.unwrap();
+ let mut connection = harness.server.accept().await.unwrap();
+ connection
+ .send_node(&node("failure", &[("reason", text("401"))], None))
+ .await;
+ loop {
+ if let Event::LoggedOut(logged_out) = next_event(&mut harness.events).await {
+ assert!(logged_out.on_connect);
+ assert_eq!(logged_out.reason, ConnectFailureReason::LOGGED_OUT);
+ break;
+ }
+ }
+ let store = harness.client.store.read().await;
+ assert!(store.deleted);
+ assert!(store.id.is_none());
+}
+
+#[tokio::test(start_paused = true)]
+async fn qr_codes_run_out_into_a_timeout() {
+ let mut harness = harness(None);
+ let mut qr = harness
+ .client
+ .get_qr_channel(CancellationToken::new())
+ .await
+ .unwrap();
+ harness.client.connect().await.unwrap();
+ let mut connection = harness.server.accept().await.unwrap();
+ connection
+ .send_node(&node(
+ "iq",
+ &[
+ ("from", AttributeValue::Jid(SERVER_JID.clone())),
+ ("id", text("pair-1")),
+ ("type", text("set")),
+ ],
+ children(vec![node(
+ "pair-device",
+ &[],
+ children(vec![node("ref", &[], bytes(b"2@only"))]),
+ )]),
+ ))
+ .await;
+ assert!(matches!(qr.recv().await, Some(QrChannelItem::Code { .. })));
+ assert!(matches!(qr.recv().await, Some(QrChannelItem::Timeout)));
+ assert!(qr.recv().await.is_none());
+ assert!(!harness.client.is_connected().await);
+}
+
+#[tokio::test(start_paused = true)]
+async fn stream_replaced_stops_reconnecting() {
+ let mut harness = harness(Some(("1234:[email protected]", "9876:5@lid")));
+ let connection = connect_paired(&mut harness).await;
+ let mut connection = connection;
+ connection
+ .send_node(&node(
+ "stream:error",
+ &[],
+ children(vec![node("conflict", &[("type", text("replaced"))], None)]),
+ ))
+ .await;
+ loop {
+ if let Event::StreamReplaced(_) = next_event(&mut harness.events).await {
+ break;
+ }
+ }
+ connection.close().await;
+ let more = tokio::time::timeout(Duration::from_secs(60), harness.events.recv()).await;
+ assert!(
+ !matches!(more, Ok(Some(Event::Disconnected(_)))),
+ "a replaced stream is an expected disconnect"
+ );
+ assert!(
+ tokio::time::timeout(Duration::from_secs(60), harness.server.accept())
+ .await
+ .is_err(),
+ "the client doesn't reconnect"
+ );
+}
+
+#[tokio::test(start_paused = true)]
+async fn the_media_connection_is_queried_once_and_cached() {
+ let mut harness = harness(Some(("1234:[email protected]", "9876:5@lid")));
+ let mut connection = connect_paired(&mut harness).await;
+ let client = Arc::clone(&harness.client);
+ let first = tokio::spawn(async move { client.refresh_media_conn(false).await });
+ let request = next_node(&mut connection).await;
+ assert!(is_iq(&request, "w:m"));
+ assert_eq!(attr_string(&request, "type"), "set");
+ connection
+ .respond_iq(
+ &request,
+ vec![node(
+ "media_conn",
+ &[
+ ("auth", text("token")),
+ ("ttl", text("300")),
+ ("auth_ttl", text("60")),
+ ("max_buckets", text("12")),
+ ],
+ children(vec![node(
+ "host",
+ &[("hostname", text("mmg.example"))],
+ None,
+ )]),
+ )],
+ )
+ .await;
+ let media_conn = first.await.unwrap().unwrap();
+ assert_eq!(media_conn.auth, "token");
+ assert_eq!(media_conn.hosts[0].hostname, "mmg.example");
+ let cached = harness.client.refresh_media_conn(false).await.unwrap();
+ assert_eq!(cached, media_conn);
+}
+
+#[tokio::test(start_paused = true)]
+async fn deleting_the_device_resets_the_app_state_processor() {
+ let harness = harness(Some(("1234:[email protected]", "9876:5@lid")));
+ let before = harness.client.app_state_processor();
+ harness.client.delete_device().await.unwrap();
+ let after = harness.client.app_state_processor();
+ assert!(!Arc::ptr_eq(&before, &after));
+ assert!(matches!(
+ after.app_state.get_app_state_version("regular").await,
+ Err(crate::store::StoreError::DeviceDeleted)
+ ));
+}
+
+/// The queue loop must handle a `stream:error` it dequeues after the
+/// connection ended (Go drops it). `tokio::select!` picks either arm when
+/// both are ready, so run it many times: the dropping path would be taken
+/// about half of the time.
+#[tokio::test(start_paused = true)]
+async fn a_stream_error_dequeued_after_the_connection_ended_is_handled() {
+ let mut harness = harness_with(Some(("1234:[email protected]", "9876:5@lid")), |config| {
+ config.disable_login_auto_reconnect = true;
+ });
+ for _ in 0..64 {
+ let (queue_sender, queue_receiver) = mpsc::channel(4);
+ queue_sender
+ .send(node("stream:error", &[("code", text("515"))], None))
+ .await
+ .unwrap();
+ let connection = CancellationToken::new();
+ connection.cancel();
+ let (close_wait, closed) = tokio::sync::oneshot::channel();
+ Arc::clone(&harness.client)
+ .handler_queue_loop(connection, queue_receiver, close_wait)
+ .await;
+ closed.await.unwrap();
+ loop {
+ if let Event::ManualLoginReconnect(_) = next_event(&mut harness.events).await {
+ break;
+ }
+ }
+ }
+}
+
+#[tokio::test(start_paused = true)]
+async fn a_515_followed_by_a_close_still_reconnects_after_pairing() {
+ let mut harness = harness(Some(("1234:[email protected]", "9876:5@lid")));
+ let connection = connect_paired(&mut harness).await;
+ // Pairing expects a disconnect, so only the 515 can trigger the login.
+ harness.client.expect_disconnect();
+ connection
+ .send_node_and_close(&node("stream:error", &[("code", text("515"))], None))
+ .await;
+ let mut connection = tokio::time::timeout(Duration::from_secs(60), harness.server.accept())
+ .await
+ .expect("the client reconnects after the 515")
+ .unwrap();
+ complete_login(&mut connection, &mut harness.events, 50).await;
+ assert!(harness.client.is_logged_in());
+}
diff --git a/crates/whatsmeow/src/connectionevents.rs b/crates/whatsmeow/src/connectionevents.rs
new file mode 100644
index 0000000000..c526376c89
--- /dev/null
+++ b/crates/whatsmeow/src/connectionevents.rs
@@ -0,0 +1,260 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+//
+// Ported from whatsmeow connectionevents.go (MPL-2.0, Copyright (c) Tulir Asokan)
+//
+// Not ported: the Messenger crypto auth token refresh branches (`RefreshCAT`).
+
+//! Handling of the connection lifecycle nodes: `success`, `failure`,
+//! `stream:error` and `ib`.
+
+use std::sync::Arc;
+use std::sync::atomic::Ordering;
+use std::time::Duration;
+
+use chrono::Utc;
+
+use crate::binary::{Node, NodeContent};
+use crate::client::Client;
+use crate::errors::ClientError;
+use crate::prekeys::MIN_PRE_KEY_COUNT;
+use crate::request::{InfoQuery, IqType};
+use crate::store::get_wa_version;
+use crate::types::events::{
+ ClientOutdated, ConnectFailure, ConnectFailureReason, Connected, Event, LoggedOut,
+ ManualLoginReconnect, OfflineSyncCompleted, OfflineSyncPreview, QrScannedWithoutMultidevice,
+ StreamError, StreamReplaced, TempBanReason, TemporaryBan,
+};
+use crate::types::{Jid, SERVER_JID};
+
+impl Client {
+ pub(crate) async fn handle_stream_error(self: &Arc<Self>, node: &Node) {
+ self.set_logged_in(false);
+ self.clear_response_waiters(node);
+ let code = node
+ .attrs
+ .get("code")
+ .map(ToString::to_string)
+ .unwrap_or_default();
+ let conflict_type = node
+ .get_optional_child_by_tag(&["conflict"])
+ .map(|conflict| conflict.attr_getter().optional_string("type"))
+ .unwrap_or_default();
+ if code == "515" {
+ if self.config.disable_login_auto_reconnect {
+ tracing::info!(
+ "got 515 code, but login autoreconnect is disabled, not reconnecting"
+ );
+ self.dispatch_event(Event::ManualLoginReconnect(ManualLoginReconnect))
+ .await;
+ return;
+ }
+ tracing::info!("got 515 code, reconnecting");
+ let client = Arc::clone(self);
+ self.spawn(async move {
+ client.disconnect().await;
+ if let Err(error) = client.connect().await {
+ tracing::error!(error = %error, "failed to reconnect after 515 code");
+ }
+ });
+ } else if code == "401" && conflict_type == "device_removed" {
+ self.expect_disconnect();
+ tracing::info!(
+ "got device removed stream error, sending LoggedOut event and deleting session"
+ );
+ self.spawn_dispatch(Event::LoggedOut(LoggedOut {
+ on_connect: false,
+ reason: ConnectFailureReason::LOGGED_OUT,
+ }));
+ if let Err(error) = self.delete_device().await {
+ tracing::warn!(error = %error, "failed to delete store after device_removed error");
+ }
+ } else if conflict_type == "replaced" {
+ self.expect_disconnect();
+ tracing::info!("got replaced stream error, sending StreamReplaced event");
+ self.spawn_dispatch(Event::StreamReplaced(StreamReplaced));
+ } else if code == "503" {
+ // The server wants to restart; the disconnect is emitted as
+ // Disconnected and auto-reconnect does its thing.
+ tracing::warn!("got 503 stream error, assuming automatic reconnect will handle it");
+ } else {
+ tracing::error!(code = %code, "unknown stream error");
+ self.spawn_dispatch(Event::StreamError(StreamError {
+ code,
+ raw: node.clone(),
+ }));
+ }
+ }
+
+ pub(crate) async fn handle_ib(self: &Arc<Self>, node: &Node) {
+ for child in node.get_children() {
+ let mut attrs = child.attr_getter();
+ match child.tag.as_str() {
+ "downgrade_webclient" => {
+ self.spawn_dispatch(Event::QrScannedWithoutMultidevice(
+ QrScannedWithoutMultidevice,
+ ));
+ }
+ "offline_preview" => {
+ let event = OfflineSyncPreview {
+ total: attrs.int("count"),
+ app_data_changes: attrs.int("appdata"),
+ messages: attrs.int("message"),
+ notifications: attrs.int("notification"),
+ receipts: attrs.int("receipt"),
+ };
+ self.dispatch_event(Event::OfflineSyncPreview(event)).await;
+ }
+ "offline" => {
+ let event = OfflineSyncCompleted {
+ count: attrs.int("count"),
+ };
+ self.dispatch_event(Event::OfflineSyncCompleted(event))
+ .await;
+ }
+ _ => {}
+ }
+ }
+ }
+
+ pub(crate) async fn handle_connect_failure(self: &Arc<Self>, node: &Node) {
+ let mut attrs = node.attr_getter();
+ let reason = ConnectFailureReason(attrs.int("reason"));
+ let message = attrs.optional_string("message");
+ let will_auto_reconnect = reason == ConnectFailureReason::SERVICE_UNAVAILABLE
+ || reason == ConnectFailureReason::INTERNAL_SERVER_ERROR
+ || reason == ConnectFailureReason::CAT_INVALID
+ || reason == ConnectFailureReason::CAT_EXPIRED;
+ if !will_auto_reconnect {
+ // By default, expect a disconnect (i.e. prevent auto-reconnect).
+ self.expect_disconnect();
+ }
+ if reason.0 == 403 {
+ tracing::debug!("got 403 connect failure");
+ }
+ if reason.is_logged_out() {
+ tracing::info!(reason = %reason, "got logged out connect failure, sending LoggedOut event and deleting session");
+ self.spawn_dispatch(Event::LoggedOut(LoggedOut {
+ on_connect: true,
+ reason,
+ }));
+ if let Err(error) = self.delete_device().await {
+ tracing::warn!(error = %error, reason = reason.0, "failed to delete store after failure");
+ }
+ } else if reason == ConnectFailureReason::TEMP_BANNED {
+ tracing::warn!("temporary ban connect failure");
+ self.spawn_dispatch(Event::TemporaryBan(TemporaryBan {
+ code: TempBanReason(attrs.int("code")),
+ expire: Duration::from_secs(u64::try_from(attrs.int("expire")).unwrap_or_default()),
+ }));
+ } else if reason == ConnectFailureReason::CLIENT_OUTDATED {
+ tracing::error!(client_version = %get_wa_version(), "client outdated (405) connect failure");
+ self.spawn_dispatch(Event::ClientOutdated(ClientOutdated));
+ } else if will_auto_reconnect {
+ tracing::warn!(
+ reason = reason.0,
+ "got connect failure, assuming automatic reconnect will handle it"
+ );
+ } else {
+ tracing::warn!(reason = reason.0, "unknown connect failure");
+ self.spawn_dispatch(Event::ConnectFailure(ConnectFailure {
+ reason,
+ message,
+ raw: node.clone(),
+ }));
+ }
+ }
+
+ pub(crate) async fn handle_connect_success(self: &Arc<Self>, node: &Node) {
+ if !self.paired.load(Ordering::SeqCst) {
+ tracing::warn!("received connect success without pairing, ignoring");
+ return;
+ }
+ tracing::info!("successfully authenticated");
+ self.mark_connect_success();
+ let mut attrs = node.attr_getter();
+ let node_lid = attrs.jid("lid");
+ if let Some(server_time) = attrs.unix_time("t") {
+ let now = Utc::now();
+ let rounded = now
+ .with_timezone(&Utc)
+ .timestamp_millis()
+ .saturating_add(500)
+ / 1000;
+ let offset = (server_time.timestamp() - rounded) * 1_000_000_000;
+ self.server_time_offset.store(offset, Ordering::SeqCst);
+ }
+
+ let mut updated_lid = None;
+ {
+ let mut store = self.store.write().await;
+ if !store.lid.is_empty() && !node_lid.is_empty() && store.lid != node_lid {
+ // This should probably never happen, but check just in case.
+ tracing::warn!("stored LID doesn't match one in connect success");
+ store.lid = Jid::default();
+ }
+ if store.lid.is_empty() && !node_lid.is_empty() {
+ store.lid = node_lid;
+ match store.save().await {
+ Err(error) => {
+ tracing::warn!(error = %error, "failed to save device after updating LID");
+ }
+ Ok(()) => tracing::info!("updated LID"),
+ }
+ updated_lid = Some((store.get_lid(), store.get_jid()));
+ }
+ }
+ if let Some((lid, jid)) = updated_lid {
+ self.store_lid_pn_mapping(&lid, &jid).await;
+ }
+ self.delete_expired_privacy_tokens().await;
+ let client = Arc::clone(self);
+ self.spawn(async move {
+ let pre_keys = Arc::clone(&client.store.read().await.pre_keys);
+ match pre_keys.uploaded_pre_key_count().await {
+ Err(error) => {
+ tracing::error!(error = %error, "failed to get number of prekeys in database");
+ }
+ Ok(db_count) => match client.get_server_pre_key_count().await {
+ Err(error) => {
+ tracing::warn!(error = %error, "failed to get number of prekeys on server");
+ }
+ Ok(server_count) => {
+ tracing::debug!(db_count, server_count, "prekey counts");
+ if server_count < MIN_PRE_KEY_COUNT || db_count < MIN_PRE_KEY_COUNT {
+ client
+ .upload_pre_keys(db_count == 0 && server_count == 0)
+ .await;
+ let server_count = client.get_server_pre_key_count().await;
+ tracing::debug!(server_count = ?server_count.ok(), "prekey count after upload");
+ }
+ }
+ },
+ }
+ if let Err(error) = client.set_passive(false).await {
+ tracing::warn!(error = %error, "failed to send post-connect passive IQ");
+ }
+ client.dispatch_event(Event::Connected(Connected)).await;
+ client.close_socket_wait_chan();
+ });
+ }
+
+ /// Tells the server whether this device is passive. The client sends
+ /// `set_passive(false)` itself after connecting.
+ pub async fn set_passive(&self, passive: bool) -> Result<(), ClientError> {
+ let tag = if passive { "passive" } else { "active" };
+ self.send_iq(InfoQuery {
+ namespace: "passive",
+ r#type: IqType::Set,
+ to: SERVER_JID.clone(),
+ content: Some(NodeContent::Nodes(vec![Node {
+ tag: tag.to_owned(),
+ ..Node::default()
+ }])),
+ ..Default::default()
+ })
+ .await
+ .map(|_| ())
+ }
+}
diff --git a/crates/whatsmeow/src/cstoken.rs b/crates/whatsmeow/src/cstoken.rs
new file mode 100644
index 0000000000..5b1a881129
--- /dev/null
+++ b/crates/whatsmeow/src/cstoken.rs
@@ -0,0 +1,70 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+//
+// Ported from whatsmeow cstoken.go (MPL-2.0, Copyright (c) Tulir Asokan)
+
+//! Contact-scoped tokens (`cstoken`), sent instead of a privacy token when
+//! there is none.
+
+use std::sync::Arc;
+
+use hmac::{Hmac, Mac};
+use sha2::Sha256;
+
+use crate::client::Client;
+use crate::types::{DEFAULT_USER_SERVER, HIDDEN_USER_SERVER, Jid, PSA_JID};
+
+/// Whether messages to the JID carry a cstoken.
+pub(crate) fn should_send_cs_token(jid: &Jid) -> bool {
+ let jid = jid.to_non_ad();
+ (jid.server == DEFAULT_USER_SERVER || jid.server == HIDDEN_USER_SERVER)
+ && jid.user != PSA_JID.user
+ && !jid.is_bot()
+}
+
+/// HMAC-SHA256 of the recipient LID string keyed with the salt.
+pub fn cs_token_for(salt: &[u8], recipient_lid: &Jid) -> Vec<u8> {
+ // HMAC accepts keys of any length.
+ let Ok(mut mac) = <Hmac<Sha256> as Mac>::new_from_slice(salt) else {
+ return Vec::new();
+ };
+ mac.update(recipient_lid.to_string().as_bytes());
+ mac.finalize().into_bytes().to_vec()
+}
+
+impl Client {
+ /// The cstoken for a recipient, derived from the NCT salt and their LID;
+ /// `None` when there is no salt or LID.
+ pub(crate) async fn generate_cs_token(&self, jid: &Jid) -> Option<Vec<u8>> {
+ if !should_send_cs_token(jid) {
+ return None;
+ }
+ let (nct_salt, lids) = {
+ let store = self.store.read().await;
+ (Arc::clone(&store.nct_salt), Arc::clone(&store.lids))
+ };
+ let salt = match nct_salt.get_nct_salt().await {
+ Err(error) => {
+ tracing::debug!(error = %error, "failed to load NCT salt for cstoken");
+ return None;
+ }
+ Ok(salt) => salt.filter(|salt| !salt.is_empty())?,
+ };
+ let recipient_lid = match jid.server.as_str() {
+ HIDDEN_USER_SERVER => jid.to_non_ad(),
+ DEFAULT_USER_SERVER => match lids.get_lid_for_pn(&jid.to_non_ad()).await {
+ Err(error) => {
+ tracing::debug!(error = %error, "failed to resolve LID for cstoken");
+ return None;
+ }
+ Ok(lid) => lid.filter(|lid| !lid.is_empty())?.to_non_ad(),
+ },
+ _ => return None,
+ };
+ if recipient_lid.server != HIDDEN_USER_SERVER {
+ return None;
+ }
+ Some(cs_token_for(&salt, &recipient_lid))
+ }
+}
diff --git a/crates/whatsmeow/src/download.rs b/crates/whatsmeow/src/download.rs
new file mode 100644
index 0000000000..65ef6ba1f4
--- /dev/null
+++ b/crates/whatsmeow/src/download.rs
@@ -0,0 +1,815 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+//
+// Ported from whatsmeow download.go (MPL-2.0, Copyright (c) Tulir Asokan)
+//
+// The work happens in free functions taking the media HTTP client
+// ([`MediaHttpClient`]) and an already refreshed [`MediaConn`], so it is
+// testable against local hosts; the `Client` methods at the bottom refresh
+// the media connection (after checking the path, as Go does) and call them.
+// Not wrapped on `Client` yet: `DownloadAny`, `DownloadThumbnail`,
+// `DownloadFB`, `DownloadMediaWithPathToFile` (call the free functions). Not ported: `FetchStickerPack` and the `types.StickerPackItem`
+// implementation (the sticker pack types aren't ported yet). Go's
+// `ErrUnknownMediaType` can't happen: only types with a media type implement
+// the traits. The `DownloadHTTPError` and `Download` sentinels from Go's
+// `errors.go` are [`DownloadError`] variants.
+
+//! Downloading and decrypting attachments.
+
+use std::io;
+use std::time::Duration;
+
+use base64::Engine;
+use base64::engine::general_purpose::URL_SAFE;
+use chrono::{NaiveDateTime, Utc};
+use hmac::{Hmac, Mac};
+use sha2::{Digest, Sha256};
+
+use crate::mediaconn::MediaConn;
+use crate::proto::wa_e2e::{
+ AudioMessage, DocumentMessage, ExtendedTextMessage, HistorySyncNotification, ImageMessage,
+ Message, StickerMessage, StickerPackMessage, VideoMessage,
+};
+use crate::proto::wa_history_sync::StickerMetadata;
+use crate::proto::wa_media_transport::wa_media_transport::Integral;
+use crate::proto::wa_server_sync::ExternalBlobReference;
+use crate::socket::ORIGIN;
+use crate::util::cbcutil::{self, CbcError};
+use crate::util::hkdfutil;
+
+/// How many bytes of the HMAC WhatsApp appends to encrypted media.
+pub(crate) const MEDIA_HMAC_LENGTH: usize = 10;
+
+/// A type of uploaded file on WhatsApp. Its string ([`MediaType::app_info`])
+/// is the HKDF info used to expand the media key.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
+pub enum MediaType {
+ /// Go's `MediaImage`.
+ Image,
+ /// Go's `MediaVideo`.
+ Video,
+ /// Go's `MediaAudio`.
+ Audio,
+ /// Go's `MediaDocument`.
+ Document,
+ /// Go's `MediaHistory`.
+ History,
+ /// Go's `MediaAppState`.
+ AppState,
+ /// Go's `MediaStickerPack`.
+ StickerPack,
+ /// Go's `MediaLinkThumbnail`.
+ LinkThumbnail,
+}
+
+impl MediaType {
+ /// The Go string value, used to generate the encryption keys.
+ pub const fn app_info(self) -> &'static str {
+ match self {
+ MediaType::Image => "WhatsApp Image Keys",
+ MediaType::Video => "WhatsApp Video Keys",
+ MediaType::Audio => "WhatsApp Audio Keys",
+ MediaType::Document => "WhatsApp Document Keys",
+ MediaType::History => "WhatsApp History Keys",
+ MediaType::AppState => "WhatsApp App State Keys",
+ MediaType::StickerPack => "WhatsApp Sticker Pack Keys",
+ MediaType::LinkThumbnail => "WhatsApp Link Thumbnail Keys",
+ }
+ }
+
+ /// The media type's name in upload and download URLs (Go's
+ /// `mediaTypeToMMSType`).
+ pub const fn mms_type(self) -> &'static str {
+ match self {
+ MediaType::Image => "image",
+ MediaType::Audio => "audio",
+ MediaType::Video => "video",
+ MediaType::Document => "document",
+ MediaType::History => "md-msg-hist",
+ MediaType::AppState => "md-app-state",
+ MediaType::StickerPack => "sticker-pack",
+ MediaType::LinkThumbnail => "thumbnail-link",
+ }
+ }
+}
+
+impl std::fmt::Display for MediaType {
+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ formatter.write_str(self.app_info())
+ }
+}
+
+/// A protobuf message that contains attachment info.
+///
+/// All of the downloadable messages inside a [`Message`] implement this
+/// ([`ImageMessage`], [`VideoMessage`], [`AudioMessage`], [`DocumentMessage`],
+/// [`StickerMessage`]). Go's `MediaTypeable` and its `classToMediaType` lookup
+/// are folded into [`DownloadableMessage::get_media_type`]. Unset fields are
+/// `None`, as Go's getters return `nil`. `Sync` so downloads are `Send`
+/// futures.
+pub trait DownloadableMessage: Sync {
+ /// The path of the attachment on the media hosts.
+ fn get_direct_path(&self) -> &str;
+ /// The key the attachment is encrypted with.
+ fn get_media_key(&self) -> Option<&[u8]>;
+ /// SHA-256 of the plaintext.
+ fn get_file_sha256(&self) -> Option<&[u8]>;
+ /// SHA-256 of the ciphertext and its MAC.
+ fn get_file_enc_sha256(&self) -> Option<&[u8]>;
+ /// The media type the keys are expanded with.
+ fn get_media_type(&self) -> MediaType;
+}
+
+/// A protobuf message that contains a thumbnail attachment.
+///
+/// This is primarily meant for link preview thumbnails in
+/// [`ExtendedTextMessage`]. Go's `classToThumbnailMediaType` lookup is
+/// [`DownloadableThumbnail::get_thumbnail_media_type`].
+pub trait DownloadableThumbnail {
+ /// The path of the thumbnail on the media hosts.
+ fn get_thumbnail_direct_path(&self) -> &str;
+ /// SHA-256 of the thumbnail plaintext.
+ fn get_thumbnail_sha256(&self) -> Option<&[u8]>;
+ /// SHA-256 of the thumbnail ciphertext and its MAC.
+ fn get_thumbnail_enc_sha256(&self) -> Option<&[u8]>;
+ /// The key the thumbnail is encrypted with.
+ fn get_media_key(&self) -> Option<&[u8]>;
+ /// The media type the keys are expanded with.
+ fn get_thumbnail_media_type(&self) -> MediaType;
+}
+
+macro_rules! downloadable_message {
+ ($($message:ty => $media_type:expr),* $(,)?) => {$(
+ impl DownloadableMessage for $message {
+ fn get_direct_path(&self) -> &str {
+ self.direct_path.as_deref().unwrap_or_default()
+ }
+
+ fn get_media_key(&self) -> Option<&[u8]> {
+ self.media_key.as_deref()
+ }
+
+ fn get_file_sha256(&self) -> Option<&[u8]> {
+ self.file_sha256.as_deref()
+ }
+
+ fn get_file_enc_sha256(&self) -> Option<&[u8]> {
+ self.file_enc_sha256.as_deref()
+ }
+
+ fn get_media_type(&self) -> MediaType {
+ $media_type
+ }
+ }
+ )*};
+}
+
+downloadable_message! {
+ ImageMessage => MediaType::Image,
+ AudioMessage => MediaType::Audio,
+ VideoMessage => MediaType::Video,
+ DocumentMessage => MediaType::Document,
+ StickerMessage => MediaType::Image,
+ StickerMetadata => MediaType::Image,
+ StickerPackMessage => MediaType::StickerPack,
+ HistorySyncNotification => MediaType::History,
+ ExternalBlobReference => MediaType::AppState,
+}
+
+impl DownloadableThumbnail for ExtendedTextMessage {
+ fn get_thumbnail_direct_path(&self) -> &str {
+ self.thumbnail_direct_path.as_deref().unwrap_or_default()
+ }
+
+ fn get_thumbnail_sha256(&self) -> Option<&[u8]> {
+ self.thumbnail_sha256.as_deref()
+ }
+
+ fn get_thumbnail_enc_sha256(&self) -> Option<&[u8]> {
+ self.thumbnail_enc_sha256.as_deref()
+ }
+
+ fn get_media_key(&self) -> Option<&[u8]> {
+ self.media_key.as_deref()
+ }
+
+ fn get_thumbnail_media_type(&self) -> MediaType {
+ MediaType::LinkThumbnail
+ }
+}
+
+/// The media type corresponding to the given protobuf message.
+pub fn get_media_type(msg: &dyn DownloadableMessage) -> MediaType {
+ msg.get_media_type()
+}
+
+/// A media download, upload or delete failure.
+#[derive(Debug, thiserror::Error)]
+pub enum DownloadError {
+ /// The host answered with a status other than 200 (Go's
+ /// `DownloadHTTPError`; `ErrMediaDownloadFailedWith403`/`404`/`410` are
+ /// this with those codes).
+ #[error("download failed with status code {status_code}")]
+ Http {
+ /// The HTTP status code.
+ status_code: u16,
+ /// The `Retry-After` header, if any.
+ retry_after: Option<String>,
+ },
+ /// The message has no direct path.
+ #[error("no url present")]
+ NoUrlPresent,
+ /// The download is no longer than the MAC.
+ #[error("file too short")]
+ TooShortFile,
+ /// The MAC doesn't match.
+ #[error("invalid media hmac")]
+ InvalidMediaHmac,
+ /// The ciphertext hash doesn't match.
+ #[error("hash of media ciphertext doesn't match")]
+ InvalidMediaEncSha256,
+ /// The plaintext hash doesn't match.
+ #[error("hash of media plaintext doesn't match")]
+ InvalidMediaSha256,
+ /// The hash of unencrypted media doesn't match.
+ #[error("hash of unencrypted media doesn't match")]
+ InvalidUnencryptedMediaSha256,
+ /// [`download_any`] found no attachment.
+ #[error("didn't find any attachments in message")]
+ NothingDownloadableFound,
+ /// The direct path isn't absolute.
+ #[error("media download path does not start with slash: {0}")]
+ PathWithoutSlash(String),
+ /// The expected ciphertext hash isn't 32 bytes.
+ #[error("invalid checksum length: expected 32, got {0}")]
+ InvalidChecksumLength(usize),
+ /// Sending the request or reading the response failed. Go returns the
+ /// `net/http` error as is, and retries it.
+ #[error(transparent)]
+ Transport(reqwest::Error),
+ /// Decrypting failed.
+ #[error("failed to decrypt file: {0}")]
+ Decrypt(#[source] CbcError),
+ /// Reading or writing the output file failed.
+ #[error("{context}: {source}")]
+ Io {
+ /// What was being done.
+ context: &'static str,
+ /// The underlying failure.
+ source: io::Error,
+ },
+ /// Every host failed; this is the last host's error.
+ #[error("failed to download media from last host: {0}")]
+ LastHost(#[source] Box<DownloadError>),
+}
+
+impl DownloadError {
+ /// Whether this is, or wraps, a [`DownloadError::Http`] with the status
+ /// code: Go's `errors.Is(err, ErrMediaDownloadFailedWith404)`.
+ pub fn is_http_status(&self, code: u16) -> bool {
+ match self {
+ DownloadError::Http { status_code, .. } => *status_code == code,
+ DownloadError::LastHost(inner) => inner.is_http_status(code),
+ _ => false,
+ }
+ }
+
+ /// Whether the download loop stops at this error instead of trying the
+ /// next host.
+ pub(crate) fn stops_host_loop(&self) -> bool {
+ matches!(self, DownloadError::InvalidMediaSha256)
+ || self.is_http_status(403)
+ || self.is_http_status(404)
+ || self.is_http_status(410)
+ }
+}
+
+/// The HTTP side of the client's media handling: Go's `Client.mediaHTTP` and
+/// the user agent from `Client.getUserAgent`.
+#[derive(Clone, Debug)]
+pub struct MediaHttpClient {
+ /// The HTTP client.
+ pub client: reqwest::Client,
+ /// The `User-Agent` for downloads; empty sends none.
+ pub user_agent: String,
+ /// Whether the client is a Messenger client (Go's
+ /// `Client.MessengerConfig != nil`); changes the upload URL.
+ pub messenger: bool,
+ /// The URL scheme. Always `https` (Go hardcodes it), unless
+ /// [`MediaHttpClient::with_base_url`] points media at a local server.
+ pub(crate) scheme: String,
+ /// Replaces every media host when set (`host[:port]`), for tests.
+ pub(crate) host_override: Option<String>,
+}
+
+impl MediaHttpClient {
+ /// A media HTTP client using `https`.
+ pub fn new(client: reqwest::Client, user_agent: String, messenger: bool) -> Self {
+ MediaHttpClient {
+ client,
+ user_agent,
+ messenger,
+ scheme: "https".to_owned(),
+ host_override: None,
+ }
+ }
+
+ /// Sends every media request to `base_url` (`scheme://host[:port]`)
+ /// instead of the hosts of the media connection, e.g. a local fake media
+ /// server in tests. Not in whatsmeow.
+ pub fn with_base_url(mut self, base_url: &str) -> Self {
+ match base_url.split_once("://") {
+ Some((scheme, host)) => {
+ self.scheme = scheme.to_owned();
+ self.host_override = Some(host.trim_end_matches('/').to_owned());
+ }
+ None => self.host_override = Some(base_url.trim_end_matches('/').to_owned()),
+ }
+ self
+ }
+
+ /// The host to contact instead of a media connection host.
+ pub(crate) fn host<'host>(&'host self, hostname: &'host str) -> &'host str {
+ self.host_override.as_deref().unwrap_or(hostname)
+ }
+
+ /// The download URL of `direct_path` on one host.
+ pub fn media_download_url(
+ &self,
+ hostname: &str,
+ direct_path: &str,
+ enc_file_hash: Option<&[u8]>,
+ mms_type: &str,
+ ) -> String {
+ // TODO omit hash for unencrypted media? (from Go)
+ format!(
+ "{}://{}{direct_path}&hash={}&mms-type={mms_type}&__wa-mms=",
+ self.scheme,
+ self.host(hostname),
+ URL_SAFE.encode(enc_file_hash.unwrap_or_default()),
+ )
+ }
+}
+
+/// Downloads the first non-empty attachment of the message: the image,
+/// video, audio, document or sticker.
+#[deprecated(
+ note = "find the specific message type you want to download manually and use download instead"
+)]
+pub async fn download_any(
+ http: &MediaHttpClient,
+ media_conn: &MediaConn,
+ msg: Option<&Message>,
+) -> Result<Vec<u8>, DownloadError> {
+ let Some(msg) = msg else {
+ return Err(DownloadError::NothingDownloadableFound);
+ };
+ let downloadable: &(dyn DownloadableMessage + Sync) = if let Some(image) = &msg.image_message {
+ image.as_ref()
+ } else if let Some(video) = &msg.video_message {
+ video.as_ref()
+ } else if let Some(audio) = &msg.audio_message {
+ audio.as_ref()
+ } else if let Some(document) = &msg.document_message {
+ document.as_ref()
+ } else if let Some(sticker) = &msg.sticker_message {
+ sticker.as_ref()
+ } else {
+ return Err(DownloadError::NothingDownloadableFound);
+ };
+ download(http, media_conn, downloadable).await
+}
+
+/// Downloads a thumbnail from a message, primarily link preview thumbnails
+/// in [`ExtendedTextMessage`].
+pub async fn download_thumbnail(
+ http: &MediaHttpClient,
+ media_conn: &MediaConn,
+ msg: &dyn DownloadableThumbnail,
+) -> Result<Vec<u8>, DownloadError> {
+ let media_type = msg.get_thumbnail_media_type();
+ if msg.get_thumbnail_direct_path().is_empty() {
+ return Err(DownloadError::NoUrlPresent);
+ }
+ let enc_sha256 = msg.get_thumbnail_enc_sha256();
+ let mut media_key = msg.get_media_key();
+ // TODO more proper check for unencrypted media? (also Download and DownloadToFile) (from Go)
+ if enc_sha256.is_none() && media_key.is_some() {
+ media_key = None;
+ }
+ download_media_with_path(
+ http,
+ media_conn,
+ msg.get_thumbnail_direct_path(),
+ enc_sha256,
+ msg.get_thumbnail_sha256(),
+ media_key,
+ Some(media_type),
+ media_type.mms_type(),
+ false,
+ )
+ .await
+}
+
+/// Downloads the attachment from the given protobuf message, which is a part
+/// of a [`Message`] (e.g. its `image_message`), not the message itself.
+pub async fn download(
+ http: &MediaHttpClient,
+ media_conn: &MediaConn,
+ msg: &(dyn DownloadableMessage + Sync),
+) -> Result<Vec<u8>, DownloadError> {
+ let media_type = get_media_type(msg);
+ if msg.get_direct_path().is_empty() {
+ return Err(DownloadError::NoUrlPresent);
+ }
+ let enc_sha256 = msg.get_file_enc_sha256();
+ let mut media_key = msg.get_media_key();
+ // TODO more proper check for unencrypted media? (also DownloadToFile) (from Go)
+ if enc_sha256.is_none() && media_key.is_some() {
+ media_key = None;
+ }
+ download_media_with_path(
+ http,
+ media_conn,
+ msg.get_direct_path(),
+ enc_sha256,
+ msg.get_file_sha256(),
+ media_key,
+ Some(media_type),
+ media_type.mms_type(),
+ false,
+ )
+ .await
+}
+
+/// Downloads the attachment of a Messenger media transport.
+pub async fn download_fb(
+ http: &MediaHttpClient,
+ media_conn: &MediaConn,
+ transport: &Integral,
+ media_type: MediaType,
+) -> Result<Vec<u8>, DownloadError> {
+ download_media_with_path(
+ http,
+ media_conn,
+ transport.direct_path.as_deref().unwrap_or_default(),
+ transport.file_enc_sha256.as_deref(),
+ transport.file_sha256.as_deref(),
+ transport.media_key.as_deref(),
+ Some(media_type),
+ media_type.mms_type(),
+ false,
+ )
+ .await
+}
+
+/// Downloads unencrypted media by its path alone, without checking a hash.
+pub async fn download_media_with_only_path(
+ http: &MediaHttpClient,
+ media_conn: &MediaConn,
+ direct_path: &str,
+) -> Result<Vec<u8>, DownloadError> {
+ download_media_with_path(
+ http,
+ media_conn,
+ direct_path,
+ None,
+ None,
+ None,
+ None,
+ "",
+ true,
+ )
+ .await
+}
+
+/// Downloads an attachment by manually specifying the path and encryption
+/// details. Each media host is tried in turn until one succeeds or fails
+/// with a permanent error. `media_type: None` is Go's empty `MediaType`
+/// (only usable for unencrypted media); an empty `mms_type` uses the media
+/// type's. With no hosts this returns an empty download, as Go does.
+#[expect(
+ clippy::too_many_arguments,
+ reason = "mirrors Go's DownloadMediaWithPath"
+)]
+pub async fn download_media_with_path(
+ http: &MediaHttpClient,
+ media_conn: &MediaConn,
+ direct_path: &str,
+ enc_file_hash: Option<&[u8]>,
+ file_hash: Option<&[u8]>,
+ media_key: Option<&[u8]>,
+ media_type: Option<MediaType>,
+ mms_type: &str,
+ allow_no_hash: bool,
+) -> Result<Vec<u8>, DownloadError> {
+ let zero_hash = [0; 32];
+ let file_hash = match file_hash {
+ None if !allow_no_hash => Some(zero_hash.as_slice()),
+ file_hash => file_hash,
+ };
+ if !direct_path.starts_with('/') {
+ return Err(DownloadError::PathWithoutSlash(direct_path.to_owned()));
+ }
+ let mms_type = match (mms_type, media_type) {
+ ("", Some(media_type)) => media_type.mms_type(),
+ (mms_type, _) => mms_type,
+ };
+ let mut data = Vec::new();
+ for (index, host) in media_conn.hosts.iter().enumerate() {
+ let media_url =
+ http.media_download_url(&host.hostname, direct_path, enc_file_hash, mms_type);
+ match download_and_decrypt(
+ http,
+ &media_url,
+ media_key,
+ media_type,
+ enc_file_hash,
+ file_hash,
+ )
+ .await
+ {
+ Ok(downloaded) => {
+ data = downloaded;
+ break;
+ }
+ Err(error) if error.stops_host_loop() => return Err(error),
+ Err(error) if index >= media_conn.hosts.len() - 1 => {
+ return Err(DownloadError::LastHost(Box::new(error)));
+ }
+ Err(error) => {
+ tracing::warn!(%error, "failed to download media, trying with next host");
+ }
+ }
+ }
+ Ok(data)
+}
+
+async fn download_and_decrypt(
+ http: &MediaHttpClient,
+ url: &str,
+ media_key: Option<&[u8]>,
+ app_info: Option<MediaType>,
+ file_enc_sha256: Option<&[u8]>,
+ file_sha256: Option<&[u8]>,
+) -> Result<Vec<u8>, DownloadError> {
+ let keys = get_media_keys(media_key.unwrap_or_default(), app_info);
+ let (ciphertext, mac) =
+ download_possibly_encrypted_media_with_retries(http, url, file_enc_sha256).await?;
+ if media_key.is_none() && file_enc_sha256.is_none() && mac.is_none() {
+ // Unencrypted media, just check the hash and return
+ if let Some(file_sha256) = file_sha256
+ && Sha256::digest(&ciphertext)[..] != *file_sha256
+ {
+ return Err(DownloadError::InvalidUnencryptedMediaSha256);
+ }
+ return Ok(ciphertext);
+ }
+ validate_media(
+ &keys.iv,
+ &ciphertext,
+ &keys.mac_key,
+ mac.as_deref().unwrap_or_default(),
+ )?;
+ let data = cbcutil::decrypt(&keys.cipher_key, &keys.iv, &ciphertext)
+ .map_err(DownloadError::Decrypt)?;
+ if file_sha256 != Some(&Sha256::digest(&data)[..]) {
+ return Err(DownloadError::InvalidMediaSha256);
+ }
+ Ok(data)
+}
+
+/// The keys expanded from a media key.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct MediaKeys {
+ /// The AES-CBC IV.
+ pub iv: [u8; 16],
+ /// The AES-256 key.
+ pub cipher_key: [u8; 32],
+ /// The HMAC-SHA256 key.
+ pub mac_key: [u8; 32],
+ /// The remaining 32 bytes, unused.
+ pub ref_key: [u8; 32],
+}
+
+/// Expands a media key with HKDF-SHA256 into 112 bytes: the IV, cipher key,
+/// MAC key and ref key. `None` is Go's empty `MediaType`.
+pub fn get_media_keys(media_key: &[u8], app_info: Option<MediaType>) -> MediaKeys {
+ let info = app_info.map(MediaType::app_info).unwrap_or_default();
+ let expanded = hkdfutil::sha256(media_key, &[], info.as_bytes(), 112);
+ let mut keys = MediaKeys {
+ iv: [0; 16],
+ cipher_key: [0; 32],
+ mac_key: [0; 32],
+ ref_key: [0; 32],
+ };
+ keys.iv.copy_from_slice(&expanded[..16]);
+ keys.cipher_key.copy_from_slice(&expanded[16..48]);
+ keys.mac_key.copy_from_slice(&expanded[48..80]);
+ keys.ref_key.copy_from_slice(&expanded[80..]);
+ keys
+}
+
+/// Whether a failed download is retried on the same host: network errors
+/// and 502, 503, 504 and 429 responses.
+pub(crate) fn should_retry_media_download(error: &DownloadError) -> bool {
+ match error {
+ DownloadError::Transport(_) => true,
+ DownloadError::Http { status_code, .. } => retry_after_should(*status_code, true),
+ _ => false,
+ }
+}
+
+/// How long to wait before retry `retry_num` (0-based): `Retry-After` if the
+/// error carries a valid one, else `retry_num + 1` seconds.
+pub(crate) fn retry_duration(error: &DownloadError, retry_num: u32) -> Duration {
+ let fallback = Duration::from_secs(u64::from(retry_num) + 1);
+ match error {
+ DownloadError::Http {
+ retry_after: Some(retry_after),
+ ..
+ } => retry_after_parse(retry_after, fallback),
+ _ => fallback,
+ }
+}
+
+async fn download_possibly_encrypted_media_with_retries(
+ http: &MediaHttpClient,
+ url: &str,
+ checksum: Option<&[u8]>,
+) -> Result<(Vec<u8>, Option<Vec<u8>>), DownloadError> {
+ let mut retry_num = 0;
+ loop {
+ let result = match checksum {
+ None => download_media(http, url).await.map(|file| (file, None)),
+ Some(checksum) => download_encrypted_media(http, url, checksum)
+ .await
+ .map(|(file, mac)| (file, Some(mac))),
+ };
+ let error = match result {
+ Err(error) if should_retry_media_download(&error) => error,
+ result => return result,
+ };
+ let retry_duration = retry_duration(&error, retry_num);
+ tracing::warn!(
+ %error,
+ ?retry_duration,
+ "failed to download media due to network error, retrying"
+ );
+ tokio::time::sleep(retry_duration).await;
+ retry_num += 1;
+ if retry_num == 5 {
+ return Err(error);
+ }
+ }
+}
+
+/// Sends the GET for a media download and fails on a non-200 status.
+pub(crate) async fn do_media_download_request(
+ http: &MediaHttpClient,
+ url: &str,
+) -> Result<reqwest::Response, DownloadError> {
+ let mut request = http
+ .client
+ .get(url)
+ .header("Origin", ORIGIN)
+ .header("Referer", format!("{ORIGIN}/"));
+ if !http.user_agent.is_empty() {
+ request = request.header("User-Agent", &http.user_agent);
+ }
+ let response = request.send().await.map_err(DownloadError::Transport)?;
+ if response.status() != reqwest::StatusCode::OK {
+ return Err(DownloadError::Http {
+ status_code: response.status().as_u16(),
+ retry_after: response
+ .headers()
+ .get("Retry-After")
+ .and_then(|value| value.to_str().ok())
+ .map(str::to_owned),
+ });
+ }
+ Ok(response)
+}
+
+async fn download_media(http: &MediaHttpClient, url: &str) -> Result<Vec<u8>, DownloadError> {
+ let response = do_media_download_request(http, url).await?;
+ let data = response.bytes().await.map_err(DownloadError::Transport)?;
+ Ok(data.to_vec())
+}
+
+async fn download_encrypted_media(
+ http: &MediaHttpClient,
+ url: &str,
+ checksum: &[u8],
+) -> Result<(Vec<u8>, Vec<u8>), DownloadError> {
+ if checksum.len() != 32 {
+ return Err(DownloadError::InvalidChecksumLength(checksum.len()));
+ }
+ let mut data = download_media(http, url).await?;
+ if data.len() <= MEDIA_HMAC_LENGTH {
+ return Err(DownloadError::TooShortFile);
+ }
+ if Sha256::digest(&data)[..] != *checksum {
+ return Err(DownloadError::InvalidMediaEncSha256);
+ }
+ let mac = data.split_off(data.len() - MEDIA_HMAC_LENGTH);
+ Ok((data, mac))
+}
+
+/// Checks the media MAC: the first 10 bytes of HMAC-SHA256(iv || file).
+pub fn validate_media(
+ iv: &[u8],
+ file: &[u8],
+ mac_key: &[u8],
+ mac: &[u8],
+) -> Result<(), DownloadError> {
+ let mut hmac = <Hmac<Sha256> as Mac>::new_from_slice(mac_key)
+ .expect("HMAC-SHA256 accepts keys of any length");
+ hmac.update(iv);
+ hmac.update(file);
+ let sum = hmac.finalize().into_bytes();
+ if !constant_time_eq::constant_time_eq(&sum[..MEDIA_HMAC_LENGTH], mac) {
+ return Err(DownloadError::InvalidMediaHmac);
+ }
+ Ok(())
+}
+
+// go.mau.fi/util/retryafter (MPL-2.0), which download.go uses.
+
+/// Whether a request that got this status should be retried.
+fn retry_after_should(status_code: u16, retry_on_rate_limit: bool) -> bool {
+ match status_code {
+ 502..=504 => true,
+ 429 => retry_on_rate_limit,
+ _ => false,
+ }
+}
+
+/// Parses a `Retry-After` header: an HTTP date or a number of seconds. A
+/// date in the past or a negative number is no wait (Go's negative duration
+/// makes the timer fire at once).
+fn retry_after_parse(retry_after: &str, fallback: Duration) -> Duration {
+ if retry_after.is_empty() {
+ return fallback;
+ }
+ if let Ok(date) = NaiveDateTime::parse_from_str(retry_after, "%a, %d %b %Y %H:%M:%S GMT") {
+ return (date.and_utc() - Utc::now()).to_std().unwrap_or_default();
+ }
+ if let Ok(seconds) = retry_after.parse::<i64>() {
+ return Duration::from_secs(u64::try_from(seconds).unwrap_or_default());
+ }
+ fallback
+}
+
+impl crate::client::Client {
+ /// Downloads and decrypts the attachment of a message part (e.g. its
+ /// `image_message`), checking its hashes (`Download`).
+ #[tracing::instrument(name = "whatsmeow.download", skip_all, err)]
+ pub async fn download(
+ &self,
+ msg: &(dyn DownloadableMessage + Sync),
+ ) -> Result<Vec<u8>, crate::errors::ClientError> {
+ if msg.get_direct_path().is_empty() {
+ return Err(DownloadError::NoUrlPresent.into());
+ }
+ let media_conn = self.media_conn_for_transfer().await?;
+ Ok(download(&self.media_http(), &media_conn, msg).await?)
+ }
+
+ /// Downloads media by direct path and keys (`DownloadMediaWithPath`).
+ #[expect(
+ clippy::too_many_arguments,
+ reason = "mirrors Go's DownloadMediaWithPath"
+ )]
+ pub async fn download_media_with_path(
+ &self,
+ direct_path: &str,
+ enc_file_hash: Option<&[u8]>,
+ file_hash: Option<&[u8]>,
+ media_key: Option<&[u8]>,
+ media_type: Option<MediaType>,
+ mms_type: &str,
+ allow_no_hash: bool,
+ ) -> Result<Vec<u8>, crate::errors::ClientError> {
+ if !direct_path.starts_with('/') {
+ return Err(DownloadError::PathWithoutSlash(direct_path.to_owned()).into());
+ }
+ let media_conn = self.media_conn_for_transfer().await?;
+ Ok(download_media_with_path(
+ &self.media_http(),
+ &media_conn,
+ direct_path,
+ enc_file_hash,
+ file_hash,
+ media_key,
+ media_type,
+ mms_type,
+ allow_no_hash,
+ )
+ .await?)
+ }
+}
+
+#[cfg(test)]
+pub(crate) mod test;
diff --git a/crates/whatsmeow/src/download/test.rs b/crates/whatsmeow/src/download/test.rs
new file mode 100644
index 0000000000..644e32c078
--- /dev/null
+++ b/crates/whatsmeow/src/download/test.rs
@@ -0,0 +1,466 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+//! Expected values come from `testdata/media/vectors.json`, written by
+//! `testdata/generator/media` running whatsmeow's Go code: its downloads ran
+//! a real `Client.Download`/`DownloadToFile` against local fake hosts, which
+//! [`FakeHosts`] replays over plain HTTP.
+
+use std::collections::{BTreeMap, VecDeque};
+use std::io::{Read, Seek, SeekFrom};
+use std::sync::{Arc, Mutex};
+
+use axum::Router;
+use axum::body::{Body, to_bytes};
+use axum::extract::{Request, State};
+use axum::response::Response;
+use serde_json::Value;
+
+use super::*;
+use crate::download_to_file::download_to_file;
+use crate::mediaconn::MediaConnHost;
+
+pub(crate) fn vectors() -> Value {
+ serde_json::from_str(include_str!("../../testdata/media/vectors.json")).unwrap()
+}
+
+pub(crate) fn hex_field(value: &Value) -> Option<Vec<u8>> {
+ value.as_str().map(|value| hex::decode(value).unwrap())
+}
+
+/// The user agent the generator's client sends.
+pub(crate) const USER_AGENT: &str = "whatsmeow-rs-test/1.0";
+
+/// One request a fake host received.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub(crate) struct Recorded {
+ pub(crate) host: usize,
+ pub(crate) method: String,
+ pub(crate) request_uri: String,
+ pub(crate) headers: BTreeMap<String, String>,
+ pub(crate) body: Vec<u8>,
+}
+
+impl Recorded {
+ /// The request as the Go generator recorded it.
+ pub(crate) fn from_vector(value: &Value) -> Recorded {
+ Recorded {
+ host: usize::try_from(value["host"].as_u64().unwrap()).unwrap(),
+ method: value["method"].as_str().unwrap().to_owned(),
+ request_uri: value["request_uri"].as_str().unwrap().to_owned(),
+ headers: value["headers"]
+ .as_object()
+ .unwrap()
+ .iter()
+ .map(|(name, value)| (name.clone(), value.as_str().unwrap().to_owned()))
+ .collect(),
+ body: hex_field(&value["body"]).unwrap_or_default(),
+ }
+ }
+}
+
+/// A scripted answer; a `None` body serves the last upload.
+#[derive(Clone, Debug)]
+pub(crate) struct Answer {
+ pub(crate) status: u16,
+ pub(crate) retry_after: Option<String>,
+ pub(crate) body: Option<Vec<u8>>,
+}
+
+#[derive(Default)]
+struct Shared {
+ requests: Mutex<Vec<Recorded>>,
+ uploaded: Mutex<Vec<u8>>,
+ upload_answer: Mutex<String>,
+}
+
+struct Host {
+ index: usize,
+ script: Mutex<VecDeque<Answer>>,
+ shared: Arc<Shared>,
+}
+
+/// Local media hosts on 127.0.0.1. Each answers from its script, consumed in
+/// order with the last answer repeating, like the Go generator's hosts. With
+/// no script, a POST is stored and answered with the upload JSON and a GET
+/// serves the stored upload.
+pub(crate) struct FakeHosts {
+ shared: Arc<Shared>,
+ pub(crate) media_conn: MediaConn,
+}
+
+/// Header names the Go generator recorded.
+const RECORDED_HEADERS: [&str; 5] = [
+ "Origin",
+ "Referer",
+ "User-Agent",
+ "Companion_user_secret",
+ "Content-Length",
+];
+
+async fn serve(State(host): State<Arc<Host>>, request: Request) -> Response {
+ let method = request.method().to_string();
+ let request_uri = request.uri().to_string();
+ let headers = RECORDED_HEADERS
+ .iter()
+ .filter_map(|name| {
+ let value = request.headers().get(*name)?.to_str().ok()?;
+ Some(((*name).to_owned(), value.to_owned()))
+ })
+ .collect();
+ let body = to_bytes(request.into_body(), usize::MAX)
+ .await
+ .unwrap()
+ .to_vec();
+ host.shared.requests.lock().unwrap().push(Recorded {
+ host: host.index,
+ method: method.clone(),
+ request_uri,
+ headers,
+ body: body.clone(),
+ });
+
+ let answer = {
+ let mut script = host.script.lock().unwrap();
+ if script.len() > 1 {
+ script.pop_front()
+ } else {
+ script.front().cloned()
+ }
+ };
+ let answer = answer.unwrap_or_else(|| {
+ if method == "POST" {
+ body.clone_into(&mut host.shared.uploaded.lock().unwrap());
+ Answer {
+ status: 200,
+ retry_after: None,
+ body: Some(host.shared.upload_answer.lock().unwrap().clone().into()),
+ }
+ } else {
+ Answer {
+ status: 200,
+ retry_after: None,
+ body: None,
+ }
+ }
+ });
+ let body = answer
+ .body
+ .unwrap_or_else(|| host.shared.uploaded.lock().unwrap().clone());
+ let mut response = Response::builder().status(answer.status);
+ if let Some(retry_after) = answer.retry_after {
+ response = response.header("Retry-After", retry_after);
+ }
+ response.body(Body::from(body)).unwrap()
+}
+
+impl FakeHosts {
+ pub(crate) async fn start(scripts: Vec<Vec<Answer>>, auth: &str) -> FakeHosts {
+ let shared = Arc::new(Shared::default());
+ let mut hosts = Vec::new();
+ for (index, script) in scripts.into_iter().enumerate() {
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ hosts.push(MediaConnHost {
+ hostname: listener.local_addr().unwrap().to_string(),
+ });
+ let host = Arc::new(Host {
+ index,
+ script: Mutex::new(script.into()),
+ shared: Arc::clone(&shared),
+ });
+ let router = Router::new().fallback(serve).with_state(host);
+ tokio::spawn(async move { axum::serve(listener, router).await.unwrap() });
+ }
+ FakeHosts {
+ shared,
+ media_conn: MediaConn {
+ auth: auth.to_owned(),
+ auth_ttl: 0,
+ ttl: 3600,
+ max_buckets: 0,
+ fetched_at: Utc::now(),
+ hosts,
+ },
+ }
+ }
+
+ /// A media HTTP client that talks plain HTTP to these hosts.
+ pub(crate) fn http() -> MediaHttpClient {
+ MediaHttpClient {
+ scheme: "http".to_owned(),
+ host_override: None,
+ ..MediaHttpClient::new(reqwest::Client::new(), USER_AGENT.to_owned(), false)
+ }
+ }
+
+ pub(crate) fn set_uploaded(&self, body: Vec<u8>) {
+ *self.shared.uploaded.lock().unwrap() = body;
+ }
+
+ pub(crate) fn set_upload_answer(&self, answer: &str) {
+ answer.clone_into(&mut self.shared.upload_answer.lock().unwrap());
+ }
+
+ pub(crate) fn take_requests(&self) -> Vec<Recorded> {
+ std::mem::take(&mut self.shared.requests.lock().unwrap())
+ }
+}
+
+#[test]
+fn media_keys_match_go() {
+ let vectors = vectors();
+ let media_types = [
+ MediaType::Image,
+ MediaType::Video,
+ MediaType::Audio,
+ MediaType::Document,
+ MediaType::History,
+ MediaType::AppState,
+ MediaType::StickerPack,
+ MediaType::LinkThumbnail,
+ ];
+ let cases = vectors["media_keys"].as_array().unwrap();
+ assert_eq!(cases.len(), media_types.len());
+ for (media_type, case) in media_types.into_iter().zip(cases) {
+ assert_eq!(media_type.app_info(), case["media_type"].as_str().unwrap());
+ assert_eq!(media_type.to_string(), media_type.app_info());
+ assert_eq!(media_type.mms_type(), case["mms_type"].as_str().unwrap());
+ let keys = get_media_keys(&hex_field(&case["media_key"]).unwrap(), Some(media_type));
+ assert_eq!(keys.iv.to_vec(), hex_field(&case["iv"]).unwrap());
+ assert_eq!(
+ keys.cipher_key.to_vec(),
+ hex_field(&case["cipher_key"]).unwrap()
+ );
+ assert_eq!(keys.mac_key.to_vec(), hex_field(&case["mac_key"]).unwrap());
+ assert_eq!(keys.ref_key.to_vec(), hex_field(&case["ref_key"]).unwrap());
+ }
+}
+
+#[test]
+fn validate_media_matches_go() {
+ for case in vectors()["validate"].as_array().unwrap() {
+ let result = validate_media(
+ &hex_field(&case["iv"]).unwrap(),
+ &hex_field(&case["file"]).unwrap(),
+ &hex_field(&case["mac_key"]).unwrap(),
+ &hex_field(&case["mac"]).unwrap(),
+ );
+ let error = result
+ .err()
+ .map(|error| error.to_string())
+ .unwrap_or_default();
+ assert_eq!(error, case["error"].as_str().unwrap());
+ }
+}
+
+#[test]
+fn media_types_of_messages() {
+ let image = ImageMessage::default();
+ let sticker = StickerMessage::default();
+ let history = HistorySyncNotification::default();
+ let blob = ExternalBlobReference::default();
+ let pack = StickerPackMessage::default();
+ assert_eq!(get_media_type(&image), MediaType::Image);
+ assert_eq!(get_media_type(&sticker), MediaType::Image);
+ assert_eq!(get_media_type(&history), MediaType::History);
+ assert_eq!(get_media_type(&blob), MediaType::AppState);
+ assert_eq!(get_media_type(&pack), MediaType::StickerPack);
+ assert_eq!(
+ ExtendedTextMessage::default().get_thumbnail_media_type(),
+ MediaType::LinkThumbnail
+ );
+}
+
+#[test]
+fn download_url_matches_go() {
+ let vectors = vectors();
+ let upload = &vectors["upload"];
+ let download = &vectors["downloads"][0];
+ let url = MediaHttpClient::new(reqwest::Client::new(), String::new(), false)
+ .media_download_url(
+ "mmg.whatsapp.net",
+ download["direct_path"].as_str().unwrap(),
+ hex_field(&upload["file_enc_sha256"]).as_deref(),
+ "image",
+ );
+ assert_eq!(
+ url,
+ format!(
+ "https://mmg.whatsapp.net{}",
+ download["requests"][0]["request_uri"].as_str().unwrap()
+ )
+ );
+}
+
+#[test]
+fn retry_after_like_go() {
+ let fallback = Duration::from_secs(3);
+ assert_eq!(retry_after_parse("", fallback), fallback);
+ assert_eq!(retry_after_parse("invalid", fallback), fallback);
+ assert_eq!(retry_after_parse("12", fallback), Duration::from_secs(12));
+ assert_eq!(retry_after_parse("-12", fallback), Duration::ZERO);
+ assert_eq!(
+ retry_after_parse("Mon, 02 Jan 2006 15:04:05 GMT", fallback),
+ Duration::ZERO
+ );
+ let later = (Utc::now() + chrono::TimeDelta::hours(5))
+ .format("%a, %d %b %Y %H:%M:%S GMT")
+ .to_string();
+ let parsed = retry_after_parse(&later, fallback);
+ assert!(parsed > Duration::from_secs(4 * 3600) && parsed <= Duration::from_secs(5 * 3600));
+}
+
+/// A minimal in-memory [`crate::download_to_file::File`].
+#[derive(Default)]
+struct MemoryFile(std::io::Cursor<Vec<u8>>);
+
+impl Read for MemoryFile {
+ fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
+ self.0.read(buffer)
+ }
+}
+
+impl io::Write for MemoryFile {
+ fn write(&mut self, buffer: &[u8]) -> io::Result<usize> {
+ self.0.write(buffer)
+ }
+
+ fn flush(&mut self) -> io::Result<()> {
+ Ok(())
+ }
+}
+
+impl Seek for MemoryFile {
+ fn seek(&mut self, position: SeekFrom) -> io::Result<u64> {
+ self.0.seek(position)
+ }
+}
+
+impl cbcutil::File for MemoryFile {
+ fn truncate(&mut self, size: u64) -> io::Result<()> {
+ self.0.get_mut().truncate(usize::try_from(size).unwrap());
+ Ok(())
+ }
+
+ fn size(&self) -> io::Result<u64> {
+ Ok(self.0.get_ref().len() as u64)
+ }
+}
+
+#[tokio::test]
+async fn downloads_match_go() {
+ let vectors = vectors();
+ let uploaded = hex_field(&vectors["upload"]["requests"][0]["body"]).unwrap();
+ let auth = vectors["auth"].as_str().unwrap();
+ for case in vectors["downloads"].as_array().unwrap() {
+ let name = format!(
+ "{} (to file: {})",
+ case["name"].as_str().unwrap(),
+ case["to_file"]
+ );
+ let scripts = case["responses"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|script| {
+ script
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|answer| Answer {
+ status: u16::try_from(answer["status"].as_u64().unwrap()).unwrap(),
+ retry_after: answer["retry_after"].as_str().map(str::to_owned),
+ body: hex_field(&answer["body"]),
+ })
+ .collect()
+ })
+ .collect();
+ let hosts = FakeHosts::start(scripts, auth).await;
+ hosts.set_uploaded(uploaded.clone());
+ let message = ImageMessage {
+ direct_path: case["direct_path"].as_str().map(str::to_owned),
+ media_key: hex_field(&case["media_key"]),
+ file_sha256: hex_field(&case["file_sha256"]),
+ file_enc_sha256: hex_field(&case["file_enc_sha256"]),
+ ..ImageMessage::default()
+ };
+
+ let result = if case["to_file"].as_bool().unwrap() {
+ let mut file = MemoryFile::default();
+ download_to_file(&FakeHosts::http(), &hosts.media_conn, &message, &mut file)
+ .await
+ .map(|()| file.0.into_inner())
+ } else {
+ download(&FakeHosts::http(), &hosts.media_conn, &message).await
+ };
+
+ match result {
+ Ok(data) => {
+ assert_eq!(case["error"], "", "{name}");
+ assert_eq!(Some(data), hex_field(&case["data"]), "{name}");
+ }
+ Err(error) => assert_eq!(error.to_string(), case["error"], "{name}"),
+ }
+ let expected: Vec<Recorded> = case["requests"]
+ .as_array()
+ .map(|requests| requests.iter().map(Recorded::from_vector).collect())
+ .unwrap_or_default();
+ assert_eq!(hosts.take_requests(), expected, "{name}");
+ }
+}
+
+#[tokio::test]
+async fn not_found_is_the_404_error() {
+ let not_found = Answer {
+ status: 404,
+ retry_after: None,
+ body: Some(Vec::new()),
+ };
+ let hosts = FakeHosts::start(vec![vec![not_found.clone()], vec![not_found]], "auth").await;
+ let message = ImageMessage {
+ direct_path: Some("/v/missing?ccb=1".to_owned()),
+ media_key: Some(vec![1; 32]),
+ file_enc_sha256: Some(vec![2; 32]),
+ file_sha256: Some(vec![3; 32]),
+ ..ImageMessage::default()
+ };
+ let error = download(&FakeHosts::http(), &hosts.media_conn, &message)
+ .await
+ .unwrap_err();
+ assert!(matches!(
+ error,
+ DownloadError::Http {
+ status_code: 404,
+ ..
+ }
+ ));
+ assert!(error.is_http_status(404));
+ assert_eq!(hosts.take_requests().len(), 1);
+}
+
+#[tokio::test]
+async fn download_errors_before_any_request() {
+ let hosts = FakeHosts::start(Vec::new(), "auth").await;
+ let http = FakeHosts::http();
+ let no_path = ImageMessage::default();
+ assert!(matches!(
+ download(&http, &hosts.media_conn, &no_path).await,
+ Err(DownloadError::NoUrlPresent)
+ ));
+ #[expect(deprecated, reason = "download_any is ported as deprecated, as in Go")]
+ let nothing = download_any(&http, &hosts.media_conn, Some(&Message::default())).await;
+ assert!(matches!(
+ nothing,
+ Err(DownloadError::NothingDownloadableFound)
+ ));
+ // No hosts: Go returns no data and no error.
+ let message = ImageMessage {
+ direct_path: Some("/v/x".to_owned()),
+ ..ImageMessage::default()
+ };
+ assert_eq!(
+ download(&http, &hosts.media_conn, &message).await.unwrap(),
+ Vec::<u8>::new()
+ );
+}
diff --git a/crates/whatsmeow/src/download_to_file.rs b/crates/whatsmeow/src/download_to_file.rs
new file mode 100644
index 0000000000..340e398fbe
--- /dev/null
+++ b/crates/whatsmeow/src/download_to_file.rs
@@ -0,0 +1,340 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+//
+// Ported from whatsmeow download-to-file.go (MPL-2.0, Copyright (c) Tulir Asokan)
+//
+// Like `download.rs`, the `Client` methods are free functions taking the
+// media HTTP client and a refreshed media connection. File I/O is blocking,
+// as in Go. Go preallocates `*os.File` outputs with `fallocate`; the port
+// doesn't.
+
+//! Downloading and decrypting attachments into a file.
+
+use std::io::{self, Read, SeekFrom};
+
+use hmac::{Hmac, Mac};
+use sha2::{Digest, Sha256};
+
+use crate::download::{
+ DownloadError, DownloadableMessage, MEDIA_HMAC_LENGTH, MediaHttpClient, MediaType,
+ do_media_download_request, get_media_keys, get_media_type, retry_duration,
+ should_retry_media_download,
+};
+use crate::mediaconn::MediaConn;
+use crate::proto::wa_media_transport::wa_media_transport::Integral;
+use crate::util::cbcutil;
+
+/// A file that can be downloaded into: Go's `File` interface (`io.Reader`,
+/// `io.Writer`, `io.Seeker`, `io.ReaderAt`, `io.WriterAt`, `Truncate`,
+/// `Stat`), expressed with seeking.
+pub use crate::util::cbcutil::File;
+
+fn io_error(context: &'static str) -> impl FnOnce(io::Error) -> DownloadError {
+ move |source| DownloadError::Io { context, source }
+}
+
+/// Downloads the attachment from the given protobuf message into `file`.
+///
+/// This is otherwise identical to [`crate::download::download`].
+pub async fn download_to_file<F: File>(
+ http: &MediaHttpClient,
+ media_conn: &MediaConn,
+ msg: &(dyn DownloadableMessage + Sync),
+ file: &mut F,
+) -> Result<(), DownloadError> {
+ let media_type = get_media_type(msg);
+ if msg.get_direct_path().is_empty() {
+ return Err(DownloadError::NoUrlPresent);
+ }
+ let enc_sha256 = msg.get_file_enc_sha256();
+ let mut media_key = msg.get_media_key();
+ // TODO more proper check for unencrypted media? (also Download) (from Go)
+ if enc_sha256.is_none() && media_key.is_some() {
+ media_key = None;
+ }
+ download_media_with_path_to_file(
+ http,
+ media_conn,
+ msg.get_direct_path(),
+ enc_sha256,
+ msg.get_file_sha256(),
+ media_key,
+ Some(media_type),
+ media_type.mms_type(),
+ false,
+ file,
+ )
+ .await
+}
+
+/// Downloads the attachment of a Messenger media transport into `file`.
+pub async fn download_fb_to_file<F: File>(
+ http: &MediaHttpClient,
+ media_conn: &MediaConn,
+ transport: &Integral,
+ media_type: MediaType,
+ file: &mut F,
+) -> Result<(), DownloadError> {
+ download_media_with_path_to_file(
+ http,
+ media_conn,
+ transport.direct_path.as_deref().unwrap_or_default(),
+ transport.file_enc_sha256.as_deref(),
+ transport.file_sha256.as_deref(),
+ transport.media_key.as_deref(),
+ Some(media_type),
+ media_type.mms_type(),
+ false,
+ file,
+ )
+ .await
+}
+
+/// Downloads unencrypted media by its path alone into `file`, without
+/// checking a hash.
+pub async fn download_media_with_only_path_to_file<F: File>(
+ http: &MediaHttpClient,
+ media_conn: &MediaConn,
+ direct_path: &str,
+ file: &mut F,
+) -> Result<(), DownloadError> {
+ download_media_with_path_to_file(
+ http,
+ media_conn,
+ direct_path,
+ None,
+ None,
+ None,
+ None,
+ "",
+ true,
+ file,
+ )
+ .await
+}
+
+/// Like [`crate::download::download_media_with_path`], but writes into
+/// `file`. Each host's download is written from the file's current position,
+/// as Go does: a host that fails after writing leaves its bytes in front of
+/// the next host's.
+#[expect(
+ clippy::too_many_arguments,
+ reason = "mirrors Go's DownloadMediaWithPathToFile"
+)]
+pub async fn download_media_with_path_to_file<F: File>(
+ http: &MediaHttpClient,
+ media_conn: &MediaConn,
+ direct_path: &str,
+ enc_file_hash: Option<&[u8]>,
+ file_hash: Option<&[u8]>,
+ media_key: Option<&[u8]>,
+ media_type: Option<MediaType>,
+ mms_type: &str,
+ allow_no_hash: bool,
+ file: &mut F,
+) -> Result<(), DownloadError> {
+ let zero_hash = [0; 32];
+ let file_hash = match file_hash {
+ None if !allow_no_hash => Some(zero_hash.as_slice()),
+ file_hash => file_hash,
+ };
+ if !direct_path.starts_with('/') {
+ return Err(DownloadError::PathWithoutSlash(direct_path.to_owned()));
+ }
+ let mms_type = match (mms_type, media_type) {
+ ("", Some(media_type)) => media_type.mms_type(),
+ (mms_type, _) => mms_type,
+ };
+ for (index, host) in media_conn.hosts.iter().enumerate() {
+ let media_url =
+ http.media_download_url(&host.hostname, direct_path, enc_file_hash, mms_type);
+ match download_and_decrypt_to_file(
+ http,
+ &media_url,
+ media_key,
+ media_type,
+ enc_file_hash,
+ file_hash,
+ file,
+ )
+ .await
+ {
+ Ok(()) => return Ok(()),
+ Err(error) if error.stops_host_loop() => return Err(error),
+ Err(error) if index >= media_conn.hosts.len() - 1 => {
+ return Err(DownloadError::LastHost(Box::new(error)));
+ }
+ Err(error) => {
+ tracing::warn!(%error, "failed to download media, trying with next host");
+ }
+ }
+ }
+ Ok(())
+}
+
+async fn download_and_decrypt_to_file<F: File>(
+ http: &MediaHttpClient,
+ url: &str,
+ media_key: Option<&[u8]>,
+ app_info: Option<MediaType>,
+ file_enc_sha256: Option<&[u8]>,
+ file_sha256: Option<&[u8]>,
+ file: &mut F,
+) -> Result<(), DownloadError> {
+ let keys = get_media_keys(media_key.unwrap_or_default(), app_info);
+ let mac =
+ download_possibly_encrypted_media_with_retries_to_file(http, url, file_enc_sha256, file)
+ .await?;
+ if media_key.is_none() && file_enc_sha256.is_none() && mac.is_none() {
+ // Unencrypted media, just check the hash and return
+ let Some(file_sha256) = file_sha256 else {
+ return Ok(());
+ };
+ file.seek(SeekFrom::Start(0))
+ .map_err(io_error("failed to seek to start of file"))?;
+ let hash = hash_file(file).map_err(io_error("failed to hash file"))?;
+ if !constant_time_eq::constant_time_eq(file_sha256, &hash) {
+ return Err(DownloadError::InvalidUnencryptedMediaSha256);
+ }
+ return Ok(());
+ }
+ validate_media_file(
+ file,
+ &keys.iv,
+ &keys.mac_key,
+ mac.as_deref().unwrap_or_default(),
+ )?;
+ file.seek(SeekFrom::Start(0)).map_err(io_error(
+ "failed to seek to start of file after validating mac",
+ ))?;
+ cbcutil::decrypt_file(&keys.cipher_key, &keys.iv, file).map_err(DownloadError::Decrypt)?;
+ file.seek(SeekFrom::Start(0))
+ .map_err(io_error("failed to seek to start of file after decrypting"))?;
+ let hash = hash_file(file).map_err(io_error("failed to hash file"))?;
+ if !constant_time_eq::constant_time_eq(file_sha256.unwrap_or_default(), &hash) {
+ return Err(DownloadError::InvalidMediaSha256);
+ }
+ Ok(())
+}
+
+async fn download_possibly_encrypted_media_with_retries_to_file<F: File>(
+ http: &MediaHttpClient,
+ url: &str,
+ checksum: Option<&[u8]>,
+ file: &mut F,
+) -> Result<Option<Vec<u8>>, DownloadError> {
+ let mut retry_num = 0;
+ loop {
+ let result = match checksum {
+ None => download_media_to_file(http, url, file).await.map(|_| None),
+ Some(checksum) => download_encrypted_media_to_file(http, url, checksum, file)
+ .await
+ .map(Some),
+ };
+ let error = match result {
+ Err(error) if should_retry_media_download(&error) => error,
+ result => return result,
+ };
+ let retry_duration = retry_duration(&error, retry_num);
+ tracing::warn!(
+ %error,
+ ?retry_duration,
+ "failed to download media due to network error, retrying"
+ );
+ file.seek(SeekFrom::Start(0)).map_err(io_error(
+ "failed to seek to start of file to retry download",
+ ))?;
+ tokio::time::sleep(retry_duration).await;
+ retry_num += 1;
+ if retry_num == 5 {
+ return Err(error);
+ }
+ }
+}
+
+/// Streams the download into `file` from its current position, returning the
+/// byte count and SHA-256.
+async fn download_media_to_file<F: File>(
+ http: &MediaHttpClient,
+ url: &str,
+ file: &mut F,
+) -> Result<(u64, [u8; 32]), DownloadError> {
+ let mut response = do_media_download_request(http, url).await?;
+ let mut hasher = Sha256::new();
+ let mut size = 0;
+ while let Some(chunk) = response.chunk().await.map_err(DownloadError::Transport)? {
+ file.write_all(&chunk)
+ .map_err(io_error("failed to write file"))?;
+ hasher.update(&chunk);
+ size += chunk.len() as u64;
+ }
+ Ok((size, hasher.finalize().into()))
+}
+
+async fn download_encrypted_media_to_file<F: File>(
+ http: &MediaHttpClient,
+ url: &str,
+ checksum: &[u8],
+ file: &mut F,
+) -> Result<Vec<u8>, DownloadError> {
+ if checksum.len() != 32 {
+ return Err(DownloadError::InvalidChecksumLength(checksum.len()));
+ }
+ let (size, hash) = download_media_to_file(http, url, file).await?;
+ if size <= MEDIA_HMAC_LENGTH as u64 {
+ return Err(DownloadError::TooShortFile);
+ }
+ if !constant_time_eq::constant_time_eq(checksum, &hash) {
+ return Err(DownloadError::InvalidMediaEncSha256);
+ }
+ // Go's ReadAt: an absolute offset, wherever this download started.
+ let mut mac = vec![0; MEDIA_HMAC_LENGTH];
+ let mac_offset = size - MEDIA_HMAC_LENGTH as u64;
+ file.seek(SeekFrom::Start(mac_offset))
+ .and_then(|_| file.read_exact(&mut mac))
+ .map_err(io_error("failed to read MAC from file"))?;
+ file.truncate(mac_offset)
+ .map_err(io_error("failed to truncate file to remove MAC"))?;
+ Ok(mac)
+}
+
+/// Like [`crate::download::validate_media`], reading the ciphertext from
+/// the start of `file`.
+pub fn validate_media_file(
+ file: &mut impl File,
+ iv: &[u8],
+ mac_key: &[u8],
+ mac: &[u8],
+) -> Result<(), DownloadError> {
+ let mut hmac = <Hmac<Sha256> as Mac>::new_from_slice(mac_key)
+ .expect("HMAC-SHA256 accepts keys of any length");
+ hmac.update(iv);
+ file.seek(SeekFrom::Start(0))
+ .map_err(io_error("failed to seek to start of file"))?;
+ read_chunks(file, |chunk| hmac.update(chunk)).map_err(io_error("failed to hash file"))?;
+ let sum = hmac.finalize().into_bytes();
+ if !constant_time_eq::constant_time_eq(&sum[..MEDIA_HMAC_LENGTH], mac) {
+ return Err(DownloadError::InvalidMediaHmac);
+ }
+ Ok(())
+}
+
+fn hash_file(file: &mut impl Read) -> io::Result<[u8; 32]> {
+ let mut hasher = Sha256::new();
+ read_chunks(file, |chunk| hasher.update(chunk))?;
+ Ok(hasher.finalize().into())
+}
+
+/// Go's `io.Copy` into a hash: feeds everything left in `reader` to `sink`.
+fn read_chunks(reader: &mut impl Read, mut sink: impl FnMut(&[u8])) -> io::Result<()> {
+ let mut buffer = vec![0; 32 * 1024];
+ loop {
+ match reader.read(&mut buffer) {
+ Ok(0) => return Ok(()),
+ Ok(read) => sink(&buffer[..read]),
+ Err(error) if error.kind() == io::ErrorKind::Interrupted => {}
+ Err(error) => return Err(error),
+ }
+ }
+}
diff --git a/crates/whatsmeow/src/errors.rs b/crates/whatsmeow/src/errors.rs
new file mode 100644
index 0000000000..2236797eaf
--- /dev/null
+++ b/crates/whatsmeow/src/errors.rs
@@ -0,0 +1,497 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+//
+// Ported from whatsmeow errors.go (MPL-2.0, Copyright (c) Tulir Asokan)
+//
+// Go returns `error` values compared with `errors.Is`; here every client
+// error is a [`ClientError`] variant. Go's `fmt.Errorf("…: %w", err)`
+// wrapping is [`ClientError::Wrapped`], and [`ClientError::is`] follows the
+// wrap chain like `errors.Is`. The media errors live in `download.rs`.
+
+//! The errors the client returns.
+
+use std::fmt;
+
+use crate::binary::{AttrError, ErrorList, Node};
+use crate::handshake::HandshakeError;
+use crate::signal::SignalError;
+use crate::socket::SocketError;
+use crate::store::StoreError;
+
+/// An error returned by the client.
+#[derive(Debug, thiserror::Error)]
+pub enum ClientError {
+ /// `ErrNoSession`.
+ #[error("can't encrypt message for device: no signal session established")]
+ NoSession,
+ /// `ErrIQTimedOut`.
+ #[error("info query timed out")]
+ IqTimedOut,
+ /// `ErrNotConnected`.
+ #[error("websocket not connected")]
+ NotConnected,
+ /// `ErrNotLoggedIn`.
+ #[error("the store doesn't contain a device JID")]
+ NotLoggedIn,
+ /// `ErrMessageTimedOut`.
+ #[error("timed out waiting for message send response")]
+ MessageTimedOut,
+ /// `ErrAlreadyConnected`.
+ #[error("websocket is already connected")]
+ AlreadyConnected,
+ /// `ErrQRAlreadyConnected`.
+ #[error("GetQRChannel must be called before connecting")]
+ QrAlreadyConnected,
+ /// `ErrQRStoreContainsID`.
+ #[error("GetQRChannel can only be called when there's no user ID in the client's Store")]
+ QrStoreContainsId,
+ /// `ErrNoPushName`.
+ #[error("can't send presence without PushName set")]
+ NoPushName,
+ /// `ErrNoPrivacyToken`.
+ #[error("no privacy token stored")]
+ NoPrivacyToken,
+ /// `ErrAppStateUpdate`.
+ #[error("server returned error updating app state")]
+ AppStateUpdate,
+
+ /// `ErrPairInvalidDeviceIdentityHMAC`.
+ #[error("invalid device identity HMAC in pair success message")]
+ PairInvalidDeviceIdentityHmac,
+ /// `ErrPairInvalidDeviceSignature`.
+ #[error("invalid device signature in pair success message")]
+ PairInvalidDeviceSignature,
+ /// `ErrPairRejectedLocally`.
+ #[error("local PrePairCallback rejected pairing")]
+ PairRejectedLocally,
+ /// `PairProtoError`: pairing failed on a protobuf error.
+ #[error("{message}: {source}")]
+ PairProto {
+ /// What failed.
+ message: String,
+ /// The protobuf error.
+ source: PairProtoSource,
+ },
+ /// `PairDatabaseError`: pairing failed saving the credentials.
+ #[error("{message}: {source}")]
+ PairDatabase {
+ /// What failed.
+ message: String,
+ /// The store error.
+ source: StoreError,
+ },
+
+ /// `ErrNotInGroup`.
+ #[error("you're not participating in that group")]
+ NotInGroup,
+ /// `ErrGroupNotFound`.
+ #[error("that group does not exist")]
+ GroupNotFound,
+ /// `ErrGroupInviteLinkUnauthorized`.
+ #[error("you don't have the permission to get the group's invite link")]
+ GroupInviteLinkUnauthorized,
+ /// `ErrInviteLinkInvalid`.
+ #[error("that group invite link is not valid")]
+ InviteLinkInvalid,
+ /// `ErrInviteLinkRevoked`.
+ #[error("that group invite link has been revoked")]
+ InviteLinkRevoked,
+ /// `ErrProfilePictureUnauthorized`.
+ #[error("the user has hidden their profile picture from you")]
+ ProfilePictureUnauthorized,
+ /// `ErrProfilePictureNotSet`.
+ #[error("that user or group does not have a profile picture")]
+ ProfilePictureNotSet,
+ /// `ErrInvalidImageFormat`.
+ #[error("the given data is not a valid image")]
+ InvalidImageFormat,
+
+ /// `ErrBroadcastListUnsupported`.
+ #[error("sending to non-status broadcast lists is not yet supported")]
+ BroadcastListUnsupported,
+ /// `ErrUnknownServer`.
+ #[error("can't send message to unknown server")]
+ UnknownServer,
+ /// `ErrRecipientADJID`.
+ #[error("message recipient must be a user JID with no device part")]
+ RecipientAdJid,
+ /// `ErrServerReturnedError`.
+ #[error("server returned error")]
+ ServerReturnedError,
+ /// `ErrNoPermissionInGroup`.
+ #[error("no permission to send that message in the group")]
+ NoPermissionInGroup,
+
+ /// `ErrOriginalMessageSecretNotFound`.
+ #[error("original message secret key not found")]
+ OriginalMessageSecretNotFound,
+ /// `ErrNotEncryptedReactionMessage`.
+ #[error("given message isn't an encrypted reaction message")]
+ NotEncryptedReactionMessage,
+ /// `ErrNotEncryptedCommentMessage`.
+ #[error("given message isn't an encrypted comment message")]
+ NotEncryptedCommentMessage,
+ /// `ErrNotPollUpdateMessage`.
+ #[error("given message isn't a poll update message")]
+ NotPollUpdateMessage,
+ /// `ErrMediaNotAvailableOnPhone`.
+ #[error("media no longer available on phone")]
+ MediaNotAvailableOnPhone,
+ /// `ErrUnknownMediaRetryError`.
+ #[error("unknown media retry error")]
+ UnknownMediaRetryError,
+ /// `ErrPhoneNumberTooShort`.
+ #[error("phone number too short")]
+ PhoneNumberTooShort,
+ /// `ErrPhoneNumberIsNotInternational`.
+ #[error("international phone number required (must not start with 0)")]
+ PhoneNumberIsNotInternational,
+ /// `ErrNotSecretEncryptedMessage`.
+ #[error("given message isn't a secret encrypted message")]
+ NotSecretEncryptedMessage,
+
+ /// `IQError`: an info query returned an error.
+ #[error(transparent)]
+ Iq(Box<IqError>),
+ /// `ElementMissingError`: a required XML element is missing.
+ #[error("missing <{tag}> element in {in_}")]
+ ElementMissing {
+ /// The missing tag.
+ tag: String,
+ /// Where it was expected.
+ in_: String,
+ },
+ /// `DisconnectedError`: the websocket disconnected before a response.
+ #[error(transparent)]
+ Disconnected(Box<DisconnectedError>),
+
+ /// A websocket failure.
+ #[error(transparent)]
+ Socket(#[from] SocketError),
+ /// The noise handshake failed.
+ #[error("noise handshake failed: {0}")]
+ Handshake(Box<HandshakeError>),
+ /// A store failure.
+ #[error(transparent)]
+ Store(#[from] StoreError),
+ /// A media download failed.
+ #[error(transparent)]
+ Download(Box<crate::download::DownloadError>),
+ /// A media upload or delete failed.
+ #[error(transparent)]
+ Upload(Box<crate::upload::UploadError>),
+ /// The media connection response didn't parse.
+ #[error(transparent)]
+ MediaConn(#[from] crate::mediaconn::MediaConnError),
+ /// An app state patch list didn't parse.
+ #[error(transparent)]
+ AppStateParse(Box<crate::appstate::ParsePatchListError>),
+ /// App state patches didn't decode or verify. Its
+ /// [`sentinel`](crate::appstate::DecodeError::sentinel) is Go's
+ /// `errors.Is` against the appstate errors.
+ #[error(transparent)]
+ AppStateDecode(Box<crate::appstate::DecodeError>),
+ /// An app state patch couldn't be encoded.
+ #[error(transparent)]
+ AppStateEncode(Box<crate::appstate::EncodeError>),
+ /// A Signal protocol failure.
+ #[error(transparent)]
+ Signal(#[from] SignalError),
+ /// Encoding a node failed.
+ #[error("failed to marshal node: {0}")]
+ Marshal(#[from] crate::binary::EncodeError),
+ /// A protobuf didn't decode.
+ #[error(transparent)]
+ ProtoDecode(#[from] prost::DecodeError),
+ /// Node attributes didn't parse.
+ #[error("{0}")]
+ Attrs(#[from] ErrorList),
+ /// One node attribute didn't parse.
+ #[error(transparent)]
+ Attr(#[from] AttrError),
+ /// An error from another layer, with Go's `fmt.Errorf` message.
+ #[error("{0}")]
+ Other(String),
+ /// Go's `wrappedIQError`: a human readable error (the message) in front
+ /// of the IQ error that caused it. [`ClientError::is`] matches both.
+ #[error("{human}")]
+ WrappedIq {
+ /// The human readable error.
+ human: Box<ClientError>,
+ /// The IQ error.
+ iq: Box<ClientError>,
+ },
+ /// Go's `fmt.Errorf("context: %w", err)`.
+ #[error("{context}: {source}")]
+ Wrapped {
+ /// The context.
+ context: String,
+ /// The wrapped error.
+ source: Box<ClientError>,
+ },
+}
+
+/// The protobuf failure inside a pairing error.
+#[derive(Debug, thiserror::Error)]
+pub enum PairProtoSource {
+ /// Decoding failed.
+ #[error(transparent)]
+ Decode(#[from] prost::DecodeError),
+}
+
+impl From<IqError> for ClientError {
+ fn from(error: IqError) -> Self {
+ ClientError::Iq(Box::new(error))
+ }
+}
+
+impl From<DisconnectedError> for ClientError {
+ fn from(error: DisconnectedError) -> Self {
+ ClientError::Disconnected(Box::new(error))
+ }
+}
+
+impl From<crate::download::DownloadError> for ClientError {
+ fn from(error: crate::download::DownloadError) -> Self {
+ ClientError::Download(Box::new(error))
+ }
+}
+
+impl From<crate::upload::UploadError> for ClientError {
+ fn from(error: crate::upload::UploadError) -> Self {
+ ClientError::Upload(Box::new(error))
+ }
+}
+
+impl From<crate::appstate::ParsePatchListError> for ClientError {
+ fn from(error: crate::appstate::ParsePatchListError) -> Self {
+ ClientError::AppStateParse(Box::new(error))
+ }
+}
+
+impl From<crate::appstate::DecodeError> for ClientError {
+ fn from(error: crate::appstate::DecodeError) -> Self {
+ ClientError::AppStateDecode(Box::new(error))
+ }
+}
+
+impl From<crate::appstate::EncodeError> for ClientError {
+ fn from(error: crate::appstate::EncodeError) -> Self {
+ ClientError::AppStateEncode(Box::new(error))
+ }
+}
+
+impl From<HandshakeError> for ClientError {
+ fn from(error: HandshakeError) -> Self {
+ ClientError::Handshake(Box::new(error))
+ }
+}
+
+impl ClientError {
+ /// An IQ error with just a status, to compare against with
+ /// [`ClientError::is`] (Go's `ErrIQNotFound` and friends).
+ pub fn iq_status(status: (i64, &'static str)) -> ClientError {
+ IqError::from_status(status).into()
+ }
+
+ /// Wraps the error with context, like Go's `fmt.Errorf("context: %w", err)`.
+ pub fn wrap(self, context: impl Into<String>) -> ClientError {
+ ClientError::Wrapped {
+ context: context.into(),
+ source: Box::new(self),
+ }
+ }
+
+ /// The innermost error, unwrapping [`ClientError::Wrapped`] and the IQ
+ /// side of [`ClientError::WrappedIq`] (Go's `Unwrap`).
+ pub fn innermost(&self) -> &ClientError {
+ match self {
+ ClientError::Wrapped { source, .. } => source.innermost(),
+ ClientError::WrappedIq { iq, .. } => iq.innermost(),
+ other => other,
+ }
+ }
+
+ /// Go's `errors.Is` against a sentinel: compares the variant (and the
+ /// code for IQ errors, the action for disconnects) along the wrap chain.
+ pub fn is(&self, target: &ClientError) -> bool {
+ let mut current = self;
+ loop {
+ if current.matches(target) {
+ return true;
+ }
+ match current {
+ ClientError::Wrapped { source, .. } => current = source,
+ ClientError::WrappedIq { human, iq } => {
+ return human.is(target) || iq.is(target);
+ }
+ _ => return false,
+ }
+ }
+ }
+
+ fn matches(&self, target: &ClientError) -> bool {
+ match (self, target) {
+ (ClientError::Iq(error), ClientError::Iq(other)) => error.is(other),
+ (ClientError::Disconnected(error), ClientError::Disconnected(other)) => {
+ error.action == other.action
+ }
+ (ClientError::Wrapped { .. } | ClientError::WrappedIq { .. }, _)
+ | (_, ClientError::Wrapped { .. } | ClientError::WrappedIq { .. }) => false,
+ _ => std::mem::discriminant(self) == std::mem::discriminant(target),
+ }
+ }
+
+ /// Whether this is an IQ error with the given status code.
+ pub fn is_iq_code(&self, code: i64) -> bool {
+ matches!(self.innermost(), ClientError::Iq(error) if error.code == code)
+ }
+}
+
+/// An error returned by an info query (`IQError`).
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct IqError {
+ /// The status code, or 0.
+ pub code: i64,
+ /// The status text.
+ pub text: String,
+ /// The `<error>` node, if any.
+ pub error_node: Option<Node>,
+ /// The whole response.
+ pub raw_node: Option<Node>,
+}
+
+/// `ErrIQBadRequest` and friends: IQ errors to compare against with
+/// [`IqError::is`].
+impl IqError {
+ const fn status(code: i64, text: &'static str) -> (i64, &'static str) {
+ (code, text)
+ }
+
+ /// 400 bad-request.
+ pub const BAD_REQUEST: (i64, &'static str) = Self::status(400, "bad-request");
+ /// 401 not-authorized.
+ pub const NOT_AUTHORIZED: (i64, &'static str) = Self::status(401, "not-authorized");
+ /// 403 forbidden.
+ pub const FORBIDDEN: (i64, &'static str) = Self::status(403, "forbidden");
+ /// 404 item-not-found.
+ pub const NOT_FOUND: (i64, &'static str) = Self::status(404, "item-not-found");
+ /// 405 not-allowed.
+ pub const NOT_ALLOWED: (i64, &'static str) = Self::status(405, "not-allowed");
+ /// 406 not-acceptable.
+ pub const NOT_ACCEPTABLE: (i64, &'static str) = Self::status(406, "not-acceptable");
+ /// 410 gone.
+ pub const GONE: (i64, &'static str) = Self::status(410, "gone");
+ /// 419 resource-limit.
+ pub const RESOURCE_LIMIT: (i64, &'static str) = Self::status(419, "resource-limit");
+ /// 423 locked.
+ pub const LOCKED: (i64, &'static str) = Self::status(423, "locked");
+ /// 429 rate-overlimit.
+ pub const RATE_OVER_LIMIT: (i64, &'static str) = Self::status(429, "rate-overlimit");
+ /// 500 internal-server-error.
+ pub const INTERNAL_SERVER_ERROR: (i64, &'static str) =
+ Self::status(500, "internal-server-error");
+ /// 503 service-unavailable.
+ pub const SERVICE_UNAVAILABLE: (i64, &'static str) = Self::status(503, "service-unavailable");
+ /// 530 partial-server-error.
+ pub const PARTIAL_SERVER_ERROR: (i64, &'static str) = Self::status(530, "partial-server-error");
+
+ /// An IQ error with just a code and text, to compare against.
+ pub fn from_status((code, text): (i64, &'static str)) -> IqError {
+ IqError {
+ code,
+ text: text.to_owned(),
+ ..IqError::default()
+ }
+ }
+
+ /// Go's `IQError.Is`: equal codes and texts, or equal error nodes when
+ /// there is no code.
+ pub fn is(&self, other: &IqError) -> bool {
+ if self.code != 0 && other.code != 0 {
+ other.code == self.code && other.text == self.text
+ } else if let (Some(node), Some(other_node)) = (&self.error_node, &other.error_node) {
+ node.to_string() == other_node.to_string()
+ } else {
+ false
+ }
+ }
+}
+
+impl fmt::Display for IqError {
+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
+ if self.code == 0 {
+ if let Some(error_node) = &self.error_node {
+ write!(formatter, "info query returned unknown error: {error_node}")
+ } else if let Some(raw_node) = &self.raw_node {
+ write!(
+ formatter,
+ "info query returned unexpected response: {raw_node}"
+ )
+ } else {
+ formatter.write_str("unknown info query error")
+ }
+ } else {
+ write!(
+ formatter,
+ "info query returned status {}: {}",
+ self.code, self.text
+ )
+ }
+ }
+}
+
+impl std::error::Error for IqError {}
+
+/// Parses the `<error>` child of an IQ error response.
+pub fn parse_iq_error(node: &Node) -> IqError {
+ let mut error = IqError {
+ raw_node: Some(node.clone()),
+ ..IqError::default()
+ };
+ if let Some(value) = node.get_optional_child_by_tag(&["error"]) {
+ let mut attrs = value.attr_getter();
+ error.code = attrs.optional_int("code");
+ error.text = attrs.optional_string("text");
+ error.error_node = Some(value.clone());
+ }
+ error
+}
+
+/// The websocket disconnected before a request got a response
+/// (`DisconnectedError`).
+#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
+#[error("websocket disconnected before {action} returned response")]
+pub struct DisconnectedError {
+ /// What was waiting for the response.
+ pub action: String,
+ /// The disconnect node.
+ pub node: Option<Node>,
+}
+
+impl DisconnectedError {
+ /// `ErrIQDisconnected`.
+ pub fn iq() -> DisconnectedError {
+ DisconnectedError {
+ action: "info query".to_owned(),
+ node: None,
+ }
+ }
+}
+
+/// `wrapIQError`: puts a human readable error in front of an IQ error.
+pub fn wrap_iq_error(human: ClientError, iq: ClientError) -> ClientError {
+ ClientError::WrappedIq {
+ human: Box::new(human),
+ iq: Box::new(iq),
+ }
+}
+
+/// Shorthand for building [`ClientError::ElementMissing`].
+pub fn element_missing(tag: &str, in_: &str) -> ClientError {
+ ClientError::ElementMissing {
+ tag: tag.to_owned(),
+ in_: in_.to_owned(),
+ }
+}
diff --git a/crates/whatsmeow/src/group.rs b/crates/whatsmeow/src/group.rs
new file mode 100644
index 0000000000..1cd6ad35e1
--- /dev/null
+++ b/crates/whatsmeow/src/group.rs
@@ -0,0 +1,1393 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+//
+// Ported from whatsmeow group.go (MPL-2.0, Copyright (c) Tulir Asokan)
+//
+// Not ported: community administration (`LinkGroup`, `UnlinkGroup`,
+// `GetSubGroups`, `GetLinkedGroupsParticipants`) and the deprecated
+// `SetGroupDescription`. Creating a community or a group inside one works
+// through `ReqCreateGroup`.
+//
+// `parseGroupNode` returns the group along with the attribute errors; here
+// it's a tuple of both. Errors leave out the JIDs and XML Go formats into
+// them, since `err` spans log them.
+
+//! Groups: info, membership and settings.
+
+use std::collections::HashMap;
+use std::sync::Arc;
+
+use crate::binary::{AttrUtility, AttributeValue, Attrs, ErrorList, Node, NodeContent};
+use crate::client::{Client, GroupMetaCache};
+use crate::errors::{ClientError, IqError, element_missing, wrap_iq_error};
+use crate::request::{InfoQuery, IqType};
+use crate::store::{LidMapping, RedactedPhoneEntry};
+use crate::types::events::{GroupInfo as GroupInfoEvent, JoinedGroup};
+use crate::types::{
+ AddressingMode, DEFAULT_USER_SERVER, GROUP_SERVER, GROUP_SERVER_JID, GroupAnnounce,
+ GroupDelete, GroupEphemeral, GroupInfo, GroupLinkChange, GroupLinkChangeType, GroupLinkTarget,
+ GroupLinkedParent, GroupLocked, GroupMemberAddMode, GroupMembershipApprovalMode, GroupName,
+ GroupParent, GroupParticipant, GroupParticipantAddRequest, GroupParticipantRequest, GroupTopic,
+ GroupUnlinkReason, HIDDEN_USER_SERVER, Jid, SERVER_JID, new_jid,
+};
+use crate::user::strip_url_prefix;
+
+/// The prefix of group invite links.
+pub const INVITE_LINK_PREFIX: &str = "https://chat.whatsapp.com/";
+
+/// The request data for [`Client::create_group`].
+#[derive(Clone, Debug, Default)]
+pub struct ReqCreateGroup {
+ /// The group name, up to 25 characters (longer names fail with 406).
+ pub name: String,
+ /// The participants; your own JID is added implicitly.
+ pub participants: Vec<Jid>,
+ /// Disappearing messages.
+ pub ephemeral: GroupEphemeral,
+ /// Whether only admins can send messages.
+ pub announce: GroupAnnounce,
+ /// Whether only admins can edit group info.
+ pub locked: GroupLocked,
+ /// Whether joining needs admin approval.
+ pub membership_approval_mode: GroupMembershipApprovalMode,
+ /// Who can add members (default all members).
+ pub member_add_mode: GroupMemberAddMode,
+ /// Set `is_parent` to create a community; the server creates its
+ /// announcement group.
+ pub parent: GroupParent,
+ /// Set the parent to create a group inside a community.
+ pub linked_parent: GroupLinkedParent,
+}
+
+/// A change to group participants (`ParticipantChange`).
+#[derive(Clone, Copy, Debug, PartialEq, Eq, strum::Display, strum::AsRefStr)]
+pub enum ParticipantChange {
+ /// `add`.
+ #[strum(serialize = "add")]
+ Add,
+ /// `remove`.
+ #[strum(serialize = "remove")]
+ Remove,
+ /// `promote`.
+ #[strum(serialize = "promote")]
+ Promote,
+ /// `demote`.
+ #[strum(serialize = "demote")]
+ Demote,
+}
+
+/// An answer to a join request (`ParticipantRequestChange`).
+#[derive(Clone, Copy, Debug, PartialEq, Eq, strum::Display, strum::AsRefStr)]
+pub enum ParticipantRequestChange {
+ /// `approve`.
+ #[strum(serialize = "approve")]
+ Approve,
+ /// `reject`.
+ #[strum(serialize = "reject")]
+ Reject,
+}
+
+/// A parsed `w:gp2` notification: joining a group or a change to one.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub(crate) enum GroupNotification {
+ Joined(Box<JoinedGroup>),
+ Change(Box<GroupInfoEvent>),
+}
+
+fn node(tag: &str, attrs: Attrs, content: Option<NodeContent>) -> Node {
+ Node {
+ tag: tag.to_owned(),
+ attrs,
+ content,
+ }
+}
+
+fn nodes(children: Vec<Node>) -> Option<NodeContent> {
+ Some(NodeContent::Nodes(children))
+}
+
+fn iq_is(error: &ClientError, status: (i64, &'static str)) -> bool {
+ error.is(&ClientError::iq_status(status))
+}
+
+impl Client {
+ async fn send_group_iq(
+ &self,
+ iq_type: IqType,
+ jid: &Jid,
+ content: Node,
+ ) -> Result<Node, ClientError> {
+ self.send_iq(InfoQuery {
+ namespace: "w:g2",
+ r#type: iq_type,
+ to: jid.clone(),
+ content: nodes(vec![content]),
+ ..InfoQuery::default()
+ })
+ .await
+ }
+
+ /// Creates a group with the given name and participants.
+ #[tracing::instrument(
+ name = "whatsmeow.create_group",
+ skip_all,
+ fields(participants = request.participants.len()),
+ err
+ )]
+ pub async fn create_group(
+ &self,
+ mut request: ReqCreateGroup,
+ ) -> Result<GroupInfo, ClientError> {
+ let mut participant_nodes = Vec::with_capacity(request.participants.len() + 8);
+ let lids = Arc::clone(&self.store.read().await.lids);
+ for participant in &request.participants {
+ let participant = participant.to_non_ad();
+ let mut participant_pn = Jid::default();
+ if participant.server == HIDDEN_USER_SERVER {
+ participant_pn = lids
+ .get_pn_for_lid(&participant)
+ .await
+ .map_err(|error| {
+ ClientError::Other(format!(
+ "failed to get phone number for participant: {error}"
+ ))
+ })?
+ .unwrap_or_default();
+ }
+ let mut attrs = Attrs::from([("jid".to_owned(), (&participant).into())]);
+ if !participant_pn.is_empty() {
+ attrs.insert("phone_number".to_owned(), participant_pn.into());
+ }
+ let token = self.ensure_tc_token(&participant).await.map_err(|error| {
+ ClientError::Other(format!(
+ "failed to get privacy token for participant: {error}"
+ ))
+ })?;
+ let content = token.filter(|token| !token.is_empty()).map(|token| {
+ NodeContent::Nodes(vec![node(
+ "privacy",
+ Attrs::new(),
+ Some(NodeContent::Bytes(token)),
+ )])
+ });
+ participant_nodes.push(node("participant", attrs, content));
+ }
+ // TODO member_share_group_history_mode
+ let member_add_mode = if request.member_add_mode == GroupMemberAddMode::Empty {
+ GroupMemberAddMode::AllMember
+ } else {
+ request.member_add_mode.clone()
+ };
+ participant_nodes.push(node(
+ "member_add_mode",
+ Attrs::new(),
+ Some(NodeContent::String(member_add_mode.as_str().to_owned())),
+ ));
+ if request.parent.is_parent {
+ if request.parent.default_membership_approval_mode.is_empty() {
+ request.parent.default_membership_approval_mode = "request_required".to_owned();
+ }
+ participant_nodes.push(node(
+ "parent",
+ Attrs::from([(
+ "default_membership_approval_mode".to_owned(),
+ request
+ .parent
+ .default_membership_approval_mode
+ .as_str()
+ .into(),
+ )]),
+ None,
+ ));
+ } else if !request.linked_parent.linked_parent_jid.is_empty() {
+ participant_nodes.push(node(
+ "linked_parent",
+ Attrs::from([(
+ "jid".to_owned(),
+ (&request.linked_parent.linked_parent_jid).into(),
+ )]),
+ None,
+ ));
+ }
+ if request.locked.is_locked {
+ participant_nodes.push(node("locked", Attrs::new(), None));
+ }
+ if request.announce.is_announce {
+ participant_nodes.push(node("announcement", Attrs::new(), None));
+ }
+ if request.ephemeral.is_ephemeral {
+ participant_nodes.push(node(
+ "ephemeral",
+ Attrs::from([
+ (
+ "expiration".to_owned(),
+ request.ephemeral.disappearing_timer.into(),
+ ),
+ // TODO what's this?
+ ("trigger".to_owned(), "1".into()),
+ ]),
+ None,
+ ));
+ } else {
+ participant_nodes.push(node(
+ "ephemeral",
+ Attrs::from([("expiration".to_owned(), 0.into())]),
+ None,
+ ));
+ }
+ let approval_state = if request.membership_approval_mode.is_join_approval_required {
+ "on"
+ } else {
+ "off"
+ };
+ participant_nodes.push(node(
+ "membership_approval_mode",
+ Attrs::new(),
+ nodes(vec![node(
+ "group_join",
+ Attrs::from([("state".to_owned(), approval_state.into())]),
+ None,
+ )]),
+ ));
+ let mut create_attrs = Attrs::new();
+ if !request.name.is_empty() {
+ create_attrs.insert("subject".to_owned(), request.name.as_str().into());
+ }
+ let response = self
+ .send_group_iq(
+ IqType::Set,
+ &GROUP_SERVER_JID,
+ node("create", create_attrs, nodes(participant_nodes)),
+ )
+ .await?;
+ let group_node = response
+ .get_optional_child_by_tag(&["group"])
+ .ok_or_else(|| element_missing("group", "response to create group query"))?;
+ let (info, result) = parse_group_node(group_node);
+ result?;
+ Ok(info)
+ }
+
+ /// Leaves the group.
+ #[tracing::instrument(name = "whatsmeow.leave_group", skip_all, err)]
+ pub async fn leave_group(&self, jid: &Jid) -> Result<(), ClientError> {
+ self.send_group_iq(
+ IqType::Set,
+ &GROUP_SERVER_JID,
+ node(
+ "leave",
+ Attrs::new(),
+ nodes(vec![node(
+ "group",
+ Attrs::from([("id".to_owned(), jid.into())]),
+ None,
+ )]),
+ ),
+ )
+ .await
+ .map(|_| ())
+ }
+
+ /// Adds, removes, promotes or demotes members of a group; returns the
+ /// affected participants (with an error code for those that failed).
+ #[tracing::instrument(
+ name = "whatsmeow.update_group_participants",
+ skip_all,
+ fields(action = %action, participants = participant_changes.len()),
+ err
+ )]
+ pub async fn update_group_participants(
+ &self,
+ jid: &Jid,
+ participant_changes: &[Jid],
+ action: ParticipantChange,
+ ) -> Result<Vec<GroupParticipant>, ClientError> {
+ let lids = Arc::clone(&self.store.read().await.lids);
+ let mut content = Vec::with_capacity(participant_changes.len());
+ for participant_jid in participant_changes {
+ let mut attrs = Attrs::from([("jid".to_owned(), participant_jid.into())]);
+ if participant_jid.server == HIDDEN_USER_SERVER && action == ParticipantChange::Add {
+ let pn = lids
+ .get_pn_for_lid(participant_jid)
+ .await
+ .map_err(|error| {
+ ClientError::Other(format!("failed to get phone number for LID: {error}"))
+ })?;
+ if let Some(pn) = pn.filter(|pn| !pn.is_empty()) {
+ attrs.insert("phone_number".to_owned(), pn.into());
+ }
+ }
+ let mut participant_content = None;
+ if action == ParticipantChange::Add {
+ let token = self
+ .ensure_tc_token(participant_jid)
+ .await
+ .map_err(|error| {
+ ClientError::Other(format!(
+ "failed to get privacy token for participant: {error}"
+ ))
+ })?;
+ if let Some(token) = token.filter(|token| !token.is_empty()) {
+ participant_content = nodes(vec![node(
+ "privacy",
+ Attrs::new(),
+ Some(NodeContent::Bytes(token)),
+ )]);
+ }
+ }
+ content.push(node("participant", attrs, participant_content));
+ }
+ let response = self
+ .send_group_iq(
+ IqType::Set,
+ jid,
+ node(action.as_ref(), Attrs::new(), nodes(content)),
+ )
+ .await?;
+ let request_action = response
+ .get_optional_child_by_tag(&[action.as_ref()])
+ .ok_or_else(|| {
+ element_missing(action.as_ref(), "response to group participants update")
+ })?;
+ Ok(request_action
+ .get_children_by_tag("participant")
+ .map(|child| parse_participant(&mut child.attr_getter(), child))
+ .collect())
+ }
+
+ /// Gets the users that asked to join the group.
+ #[tracing::instrument(name = "whatsmeow.get_group_request_participants", skip_all, err)]
+ pub async fn get_group_request_participants(
+ &self,
+ jid: &Jid,
+ ) -> Result<Vec<GroupParticipantRequest>, ClientError> {
+ let response = self
+ .send_group_iq(
+ IqType::Get,
+ jid,
+ node("membership_approval_requests", Attrs::new(), None),
+ )
+ .await?;
+ let request = response
+ .get_optional_child_by_tag(&["membership_approval_requests"])
+ .ok_or_else(|| {
+ element_missing(
+ "membership_approval_requests",
+ "response to group request participants query",
+ )
+ })?;
+ Ok(request
+ .get_children_by_tag("membership_approval_request")
+ .map(|request| GroupParticipantRequest {
+ jid: request.attr_getter().jid("jid"),
+ requested_at: request.attr_getter().unix_time("request_time"),
+ })
+ .collect())
+ }
+
+ /// Approves or rejects requests to join the group.
+ #[tracing::instrument(
+ name = "whatsmeow.update_group_request_participants",
+ skip_all,
+ fields(action = %action, participants = participant_changes.len()),
+ err
+ )]
+ pub async fn update_group_request_participants(
+ &self,
+ jid: &Jid,
+ participant_changes: &[Jid],
+ action: ParticipantRequestChange,
+ ) -> Result<Vec<GroupParticipant>, ClientError> {
+ let content = participant_changes
+ .iter()
+ .map(|participant| {
+ node(
+ "participant",
+ Attrs::from([("jid".to_owned(), participant.into())]),
+ None,
+ )
+ })
+ .collect();
+ let response = self
+ .send_group_iq(
+ IqType::Set,
+ jid,
+ node(
+ "membership_requests_action",
+ Attrs::new(),
+ nodes(vec![node(action.as_ref(), Attrs::new(), nodes(content))]),
+ ),
+ )
+ .await?;
+ let request = response
+ .get_optional_child_by_tag(&["membership_requests_action"])
+ .ok_or_else(|| {
+ element_missing(
+ "membership_requests_action",
+ "response to group request participants update",
+ )
+ })?;
+ let request_action = request
+ .get_optional_child_by_tag(&[action.as_ref()])
+ .ok_or_else(|| {
+ element_missing(
+ action.as_ref(),
+ "response to group request participants update",
+ )
+ })?;
+ Ok(request_action
+ .get_children_by_tag("participant")
+ .map(|child| parse_participant(&mut child.attr_getter(), child))
+ .collect())
+ }
+
+ /// Sets the group's picture (a JPEG; other formats may fail with
+ /// [`ClientError::InvalidImageFormat`]) or removes it with `None`.
+ /// Returns the new picture ID, or `remove`.
+ #[tracing::instrument(name = "whatsmeow.set_group_photo", skip_all, err)]
+ pub async fn set_group_photo(
+ &self,
+ jid: &Jid,
+ avatar: Option<Vec<u8>>,
+ ) -> Result<String, ClientError> {
+ let removing = avatar.is_none();
+ let content = avatar.map(|avatar| {
+ NodeContent::Nodes(vec![node(
+ "picture",
+ Attrs::from([("type".to_owned(), "image".into())]),
+ Some(NodeContent::Bytes(avatar)),
+ )])
+ });
+ let response = match self
+ .send_iq(InfoQuery {
+ namespace: "w:profile:picture",
+ r#type: IqType::Set,
+ to: SERVER_JID.clone(),
+ target: jid.clone(),
+ content,
+ ..InfoQuery::default()
+ })
+ .await
+ {
+ Err(error) if iq_is(&error, IqError::NOT_ACCEPTABLE) => {
+ return Err(wrap_iq_error(ClientError::InvalidImageFormat, error));
+ }
+ result => result?,
+ };
+ if removing {
+ return Ok("remove".to_owned());
+ }
+ match response.get_child_by_tag(&["picture"]).attrs.get("id") {
+ Some(AttributeValue::String(id)) => Ok(id.clone()),
+ _ => Err(ClientError::Other(
+ "didn't find picture ID in response".to_owned(),
+ )),
+ }
+ }
+
+ /// Sets the group's name (subject).
+ #[tracing::instrument(name = "whatsmeow.set_group_name", skip_all, err)]
+ pub async fn set_group_name(&self, jid: &Jid, name: &str) -> Result<(), ClientError> {
+ self.send_group_iq(
+ IqType::Set,
+ jid,
+ node(
+ "subject",
+ Attrs::new(),
+ Some(NodeContent::Bytes(name.as_bytes().to_vec())),
+ ),
+ )
+ .await
+ .map(|_| ())
+ }
+
+ /// Sets the group's topic (description); an empty topic deletes it.
+ ///
+ /// Without `previous_id`, the current topic ID is fetched with
+ /// [`Client::get_group_info`]; without `new_id`, one is generated with
+ /// [`Client::generate_message_id`].
+ #[tracing::instrument(name = "whatsmeow.set_group_topic", skip_all, err)]
+ pub async fn set_group_topic(
+ &self,
+ jid: &Jid,
+ previous_id: &str,
+ new_id: &str,
+ topic: &str,
+ ) -> Result<(), ClientError> {
+ let previous_id = if previous_id.is_empty() {
+ let old_info = self.get_group_info(jid).await.map_err(|error| {
+ ClientError::Other(format!(
+ "failed to get old group info to update topic: {error}"
+ ))
+ })?;
+ old_info.topic.topic_id
+ } else {
+ previous_id.to_owned()
+ };
+ let new_id = if new_id.is_empty() {
+ self.generate_message_id().await
+ } else {
+ new_id.to_owned()
+ };
+ let mut attrs = Attrs::from([("id".to_owned(), new_id.into())]);
+ if !previous_id.is_empty() {
+ attrs.insert("prev".to_owned(), previous_id.into());
+ }
+ let content = if topic.is_empty() {
+ attrs.insert("delete".to_owned(), "true".into());
+ None
+ } else {
+ nodes(vec![node(
+ "body",
+ Attrs::new(),
+ Some(NodeContent::Bytes(topic.as_bytes().to_vec())),
+ )])
+ };
+ self.send_group_iq(IqType::Set, jid, node("description", attrs, content))
+ .await
+ .map(|_| ())
+ }
+
+ /// Sets whether only admins can edit group info.
+ #[tracing::instrument(name = "whatsmeow.set_group_locked", skip_all, err)]
+ pub async fn set_group_locked(&self, jid: &Jid, locked: bool) -> Result<(), ClientError> {
+ let tag = if locked { "locked" } else { "unlocked" };
+ self.send_group_iq(IqType::Set, jid, node(tag, Attrs::new(), None))
+ .await
+ .map(|_| ())
+ }
+
+ /// Sets whether only admins can send messages.
+ #[tracing::instrument(name = "whatsmeow.set_group_announce", skip_all, err)]
+ pub async fn set_group_announce(&self, jid: &Jid, announce: bool) -> Result<(), ClientError> {
+ let tag = if announce {
+ "announcement"
+ } else {
+ "not_announcement"
+ };
+ self.send_group_iq(IqType::Set, jid, node(tag, Attrs::new(), None))
+ .await
+ .map(|_| ())
+ }
+
+ /// Gets the group's invite link; `reset` revokes the old link and makes a
+ /// new one.
+ #[tracing::instrument(name = "whatsmeow.get_group_invite_link", skip_all, fields(reset), err)]
+ pub async fn get_group_invite_link(
+ &self,
+ jid: &Jid,
+ reset: bool,
+ ) -> Result<String, ClientError> {
+ let iq_type = if reset { IqType::Set } else { IqType::Get };
+ let response = match self
+ .send_group_iq(iq_type, jid, node("invite", Attrs::new(), None))
+ .await
+ {
+ Err(error) if iq_is(&error, IqError::NOT_AUTHORIZED) => {
+ return Err(wrap_iq_error(
+ ClientError::GroupInviteLinkUnauthorized,
+ error,
+ ));
+ }
+ Err(error) if iq_is(&error, IqError::NOT_FOUND) => {
+ return Err(wrap_iq_error(ClientError::GroupNotFound, error));
+ }
+ Err(error) if iq_is(&error, IqError::FORBIDDEN) => {
+ return Err(wrap_iq_error(ClientError::NotInGroup, error));
+ }
+ result => result?,
+ };
+ match response.get_child_by_tag(&["invite"]).attrs.get("code") {
+ Some(AttributeValue::String(code)) => Ok(format!("{INVITE_LINK_PREFIX}{code}")),
+ _ => Err(ClientError::Other(
+ "didn't find invite code in response".to_owned(),
+ )),
+ }
+ }
+
+ /// Gets the group info from an invite message (not an invite link; see
+ /// [`Client::get_group_info_from_link`]).
+ #[tracing::instrument(name = "whatsmeow.get_group_info_from_invite", skip_all, err)]
+ pub async fn get_group_info_from_invite(
+ &self,
+ jid: &Jid,
+ inviter: &Jid,
+ code: &str,
+ expiration: i64,
+ ) -> Result<GroupInfo, ClientError> {
+ let response = self
+ .send_group_iq(
+ IqType::Get,
+ jid,
+ node(
+ "query",
+ Attrs::new(),
+ nodes(vec![node(
+ "add_request",
+ Attrs::from([
+ ("code".to_owned(), code.into()),
+ ("expiration".to_owned(), expiration.into()),
+ ("admin".to_owned(), inviter.into()),
+ ]),
+ None,
+ )]),
+ ),
+ )
+ .await?;
+ let group_node = response
+ .get_optional_child_by_tag(&["group"])
+ .ok_or_else(|| element_missing("group", "response to invite group info query"))?;
+ let (info, result) = parse_group_node(group_node);
+ result?;
+ Ok(info)
+ }
+
+ /// Joins a group with an invite message (not an invite link; see
+ /// [`Client::join_group_with_link`]).
+ #[tracing::instrument(name = "whatsmeow.join_group_with_invite", skip_all, err)]
+ pub async fn join_group_with_invite(
+ &self,
+ jid: &Jid,
+ inviter: &Jid,
+ code: &str,
+ expiration: i64,
+ ) -> Result<(), ClientError> {
+ self.send_group_iq(
+ IqType::Set,
+ jid,
+ node(
+ "accept",
+ Attrs::from([
+ ("code".to_owned(), code.into()),
+ ("expiration".to_owned(), expiration.into()),
+ ("admin".to_owned(), inviter.into()),
+ ]),
+ None,
+ ),
+ )
+ .await
+ .map(|_| ())
+ }
+
+ /// Resolves an invite link (or just its code) to the group's info
+ /// without joining.
+ #[tracing::instrument(name = "whatsmeow.get_group_info_from_link", skip_all, err)]
+ pub async fn get_group_info_from_link(&self, code: &str) -> Result<GroupInfo, ClientError> {
+ let response = self.send_invite_link_iq(IqType::Get, code).await?;
+ let group_node = response
+ .get_optional_child_by_tag(&["group"])
+ .ok_or_else(|| element_missing("group", "response to group link info query"))?;
+ let (info, result) = parse_group_node(group_node);
+ result?;
+ Ok(info)
+ }
+
+ /// Joins a group with an invite link (or just its code). Returns the
+ /// group, or the JID of the pending membership request when joining
+ /// needs approval.
+ #[tracing::instrument(name = "whatsmeow.join_group_with_link", skip_all, err)]
+ pub async fn join_group_with_link(&self, code: &str) -> Result<Jid, ClientError> {
+ let response = self.send_invite_link_iq(IqType::Set, code).await?;
+ if let Some(membership_request) =
+ response.get_optional_child_by_tag(&["membership_approval_request"])
+ {
+ return Ok(membership_request.attr_getter().jid("jid"));
+ }
+ let group_node = response
+ .get_optional_child_by_tag(&["group"])
+ .ok_or_else(|| element_missing("group", "response to group link join query"))?;
+ Ok(group_node.attr_getter().jid("jid"))
+ }
+
+ async fn send_invite_link_iq(&self, iq_type: IqType, code: &str) -> Result<Node, ClientError> {
+ match self
+ .send_group_iq(
+ iq_type,
+ &GROUP_SERVER_JID,
+ node(
+ "invite",
+ Attrs::from([(
+ "code".to_owned(),
+ strip_url_prefix(code, &[INVITE_LINK_PREFIX]).into(),
+ )]),
+ None,
+ ),
+ )
+ .await
+ {
+ Err(error) if iq_is(&error, IqError::GONE) => {
+ Err(wrap_iq_error(ClientError::InviteLinkRevoked, error))
+ }
+ Err(error) if iq_is(&error, IqError::NOT_ACCEPTABLE) => {
+ Err(wrap_iq_error(ClientError::InviteLinkInvalid, error))
+ }
+ result => result,
+ }
+ }
+
+ /// Lists the groups the user participates in, with participants and
+ /// descriptions; caches them and stores the LID mappings and redacted
+ /// phones they carry. Groups whose attributes don't fully parse are
+ /// returned anyway, like Go.
+ #[tracing::instrument(
+ name = "whatsmeow.get_joined_groups",
+ skip_all,
+ fields(groups = tracing::field::Empty),
+ err
+ )]
+ pub async fn get_joined_groups(&self) -> Result<Vec<GroupInfo>, ClientError> {
+ let response = self
+ .send_group_iq(
+ IqType::Get,
+ &GROUP_SERVER_JID,
+ node(
+ "participating",
+ Attrs::new(),
+ nodes(vec![
+ node("participants", Attrs::new(), None),
+ node("description", Attrs::new(), None),
+ ]),
+ ),
+ )
+ .await?;
+ let groups = response
+ .get_optional_child_by_tag(&["groups"])
+ .ok_or_else(|| element_missing("groups", "response to group list query"))?;
+ let children = groups.get_children();
+ let mut infos = Vec::with_capacity(children.len());
+ let mut all_lid_pairs = Vec::new();
+ let mut all_redacted_phones = Vec::new();
+ for child in children {
+ if child.tag != "group" {
+ tracing::debug!(tag = %child.tag, "unexpected child in group list response");
+ continue;
+ }
+ let (parsed, result) = parse_group_node(child);
+ if let Err(error) = result {
+ tracing::warn!(error = %error, "error parsing group");
+ }
+ let (lid_pairs, redacted_phones) = self.cache_group_info(&parsed, None).await;
+ all_lid_pairs.extend(lid_pairs);
+ all_redacted_phones.extend(redacted_phones);
+ infos.push(parsed);
+ }
+ tracing::Span::current().record("groups", infos.len());
+ let (lids, contacts) = {
+ let store = self.store.read().await;
+ (Arc::clone(&store.lids), Arc::clone(&store.contacts))
+ };
+ if let Err(error) = lids.put_many_lid_mappings(&all_lid_pairs).await {
+ tracing::warn!(error = %error, "failed to store LID mappings from joined groups");
+ }
+ if let Err(error) = contacts
+ .put_many_redacted_phones(&all_redacted_phones)
+ .await
+ {
+ tracing::warn!(error = %error, "failed to store redacted phones from joined groups");
+ }
+ Ok(infos)
+ }
+
+ /// Gets a group's info from the server and caches it, storing the LID
+ /// mappings and redacted phones of its participants.
+ #[tracing::instrument(name = "whatsmeow.get_group_info", skip_all, err)]
+ pub async fn get_group_info(&self, jid: &Jid) -> Result<GroupInfo, ClientError> {
+ self.get_group_info_inner(jid, None).await
+ }
+
+ /// Caches what the send path needs to know about the group. With
+ /// `locked_cache`, the caller already holds the cache lock (Go's
+ /// `lock == false`). Returns the participants' LID mappings (one per
+ /// participant, empty for those without both, as Go) and redacted phones.
+ pub(crate) async fn cache_group_info(
+ &self,
+ group_info: &GroupInfo,
+ locked_cache: Option<&mut HashMap<Jid, GroupMetaCache>>,
+ ) -> (Vec<LidMapping>, Vec<RedactedPhoneEntry>) {
+ let mut participants = Vec::with_capacity(group_info.participants.len());
+ let mut lid_pairs = Vec::with_capacity(group_info.participants.len());
+ let mut redacted_phones = Vec::new();
+ let mut admins = Vec::new();
+ for participant in &group_info.participants {
+ participants.push(participant.jid.clone());
+ if participant.is_admin || participant.is_super_admin {
+ admins.push(participant.jid.clone());
+ }
+ if !participant.phone_number.is_empty() && !participant.lid.is_empty() {
+ lid_pairs.push(LidMapping {
+ lid: participant.lid.clone(),
+ pn: participant.phone_number.clone(),
+ });
+ } else {
+ lid_pairs.push(LidMapping {
+ lid: Jid::default(),
+ pn: Jid::default(),
+ });
+ }
+ if !participant.display_name.is_empty() && !participant.lid.is_empty() {
+ redacted_phones.push(RedactedPhoneEntry {
+ jid: participant.lid.clone(),
+ redacted_phone: participant.display_name.clone(),
+ });
+ }
+ }
+ let meta = GroupMetaCache {
+ addressing_mode: group_info.addressing_mode.clone(),
+ read_only: group_info.announce.is_announce,
+ community_announcement_group: group_info.announce.is_announce
+ && group_info.is_default_sub.is_default_sub_group,
+ members: participants,
+ admins,
+ };
+ match locked_cache {
+ Some(cache) => {
+ cache.insert(group_info.jid.clone(), meta);
+ }
+ None => {
+ self.group_cache
+ .lock()
+ .await
+ .insert(group_info.jid.clone(), meta);
+ }
+ }
+ (lid_pairs, redacted_phones)
+ }
+
+ /// Go's `getGroupInfo`: `locked_cache` is the cache when the caller
+ /// already holds its lock.
+ pub(crate) async fn get_group_info_inner(
+ &self,
+ jid: &Jid,
+ locked_cache: Option<&mut HashMap<Jid, GroupMetaCache>>,
+ ) -> Result<GroupInfo, ClientError> {
+ let response = match self
+ .send_group_iq(
+ IqType::Get,
+ jid,
+ node(
+ "query",
+ Attrs::from([("request".to_owned(), "interactive".into())]),
+ None,
+ ),
+ )
+ .await
+ {
+ Err(error) if iq_is(&error, IqError::NOT_FOUND) => {
+ return Err(wrap_iq_error(ClientError::GroupNotFound, error));
+ }
+ Err(error) if iq_is(&error, IqError::FORBIDDEN) => {
+ return Err(wrap_iq_error(ClientError::NotInGroup, error));
+ }
+ result => result?,
+ };
+ let group_node = response
+ .get_optional_child_by_tag(&["group"])
+ .ok_or_else(|| element_missing("groups", "response to group info query"))?;
+ let (group_info, result) = parse_group_node(group_node);
+ result?;
+ let (lid_pairs, redacted_phones) = self.cache_group_info(&group_info, locked_cache).await;
+ let (lids, contacts) = {
+ let store = self.store.read().await;
+ (Arc::clone(&store.lids), Arc::clone(&store.contacts))
+ };
+ if let Err(error) = lids.put_many_lid_mappings(&lid_pairs).await {
+ tracing::warn!(error = %error, "failed to store LID mappings for group members");
+ }
+ if let Err(error) = contacts.put_many_redacted_phones(&redacted_phones).await {
+ tracing::warn!(error = %error, "failed to store redacted phones for group members");
+ }
+ Ok(group_info)
+ }
+
+ /// The cached group metadata, fetching the group info when it isn't
+ /// cached. The cache lock is held across the query, like Go.
+ pub(crate) async fn get_cached_group_data(
+ &self,
+ jid: &Jid,
+ ) -> Result<GroupMetaCache, ClientError> {
+ let mut cache = self.group_cache.lock().await;
+ if let Some(cached) = cache.get(jid) {
+ return Ok(cached.clone());
+ }
+ self.get_group_info_inner(jid, Some(&mut cache)).await?;
+ // `cache_group_info` just inserted it.
+ Ok(cache.get(jid).cloned().unwrap_or_default())
+ }
+
+ async fn parse_group_create(
+ &self,
+ parent_node: &Node,
+ node: &Node,
+ ) -> Result<(JoinedGroup, Vec<LidMapping>, Vec<RedactedPhoneEntry>), ClientError> {
+ let group_node = node.get_optional_child_by_tag(&["group"]).ok_or_else(|| {
+ ClientError::Other("group create notification didn't contain group info".to_owned())
+ })?;
+ let mut parent_attrs = parent_node.attr_getter();
+ let mut attrs = node.attr_getter();
+ let (mut info, result) = parse_group_node(group_node);
+ result.map_err(|error| {
+ ClientError::from(error).wrap("failed to parse group info in create notification")
+ })?;
+ if info.addressing_mode == AddressingMode::Empty {
+ info.addressing_mode =
+ AddressingMode::from(parent_attrs.optional_string("addressing_mode"));
+ }
+ let (lid_pairs, redacted_phones) = self.cache_group_info(&info, None).await;
+ let event = JoinedGroup {
+ reason: attrs.optional_string("reason"),
+ create_key: attrs.optional_string("key"),
+ r#type: attrs.optional_string("type"),
+ sender: parent_attrs.optional_jid("participant"),
+ sender_pn: parent_attrs.optional_jid("participant_pn"),
+ notify: parent_attrs.optional_string("notify"),
+ group_info: info,
+ };
+ Ok((event, lid_pairs, redacted_phones))
+ }
+
+ async fn update_group_participant_cache(&self, event: &GroupInfoEvent) {
+ // TODO can the addressing mode change here?
+ if event.join.is_empty()
+ && event.leave.is_empty()
+ && event.promote.is_empty()
+ && event.demote.is_empty()
+ && event.announce.is_none()
+ {
+ return;
+ }
+ let mut cache = self.group_cache.lock().await;
+ let Some(cached) = cache.get_mut(&event.jid) else {
+ return;
+ };
+ if let Some(announce) = &event.announce {
+ cached.read_only = announce.is_announce;
+ }
+ for jid in &event.join {
+ if !cached.members.contains(jid) {
+ cached.members.push(jid.clone());
+ }
+ }
+ for jid in &event.leave {
+ fast_delete_item(&mut cached.members, jid);
+ fast_delete_item(&mut cached.admins, jid);
+ }
+ for jid in &event.promote {
+ if !cached.admins.contains(jid) {
+ cached.admins.push(jid.clone());
+ }
+ }
+ for jid in &event.demote {
+ fast_delete_item(&mut cached.admins, jid);
+ }
+ }
+
+ /// Parses a `w:gp2` notification: a lone `<create>` is joining a group,
+ /// anything else a change, which also updates the participant cache.
+ pub(crate) async fn parse_group_notification(
+ &self,
+ node: &Node,
+ ) -> Result<(GroupNotification, Vec<LidMapping>, Vec<RedactedPhoneEntry>), ClientError> {
+ let children = node.get_children();
+ if children.len() == 1 && children[0].tag == "create" {
+ let (event, lid_pairs, redacted_phones) =
+ self.parse_group_create(node, &children[0]).await?;
+ Ok((
+ GroupNotification::Joined(Box::new(event)),
+ lid_pairs,
+ redacted_phones,
+ ))
+ } else {
+ let (group_change, lid_pairs) = parse_group_change(node)?;
+ self.update_group_participant_cache(&group_change).await;
+ Ok((
+ GroupNotification::Change(Box::new(group_change)),
+ lid_pairs,
+ Vec::new(),
+ ))
+ }
+ }
+
+ /// Turns join approval on or off.
+ #[tracing::instrument(name = "whatsmeow.set_group_join_approval_mode", skip_all, err)]
+ pub async fn set_group_join_approval_mode(
+ &self,
+ jid: &Jid,
+ mode: bool,
+ ) -> Result<(), ClientError> {
+ let state = if mode { "on" } else { "off" };
+ self.send_group_iq(
+ IqType::Set,
+ jid,
+ node(
+ "membership_approval_mode",
+ Attrs::new(),
+ nodes(vec![node(
+ "group_join",
+ Attrs::from([("state".to_owned(), state.into())]),
+ None,
+ )]),
+ ),
+ )
+ .await
+ .map(|_| ())
+ }
+
+ /// Sets who can add members: [`GroupMemberAddMode::Admin`] or
+ /// [`GroupMemberAddMode::AllMember`].
+ #[tracing::instrument(name = "whatsmeow.set_group_member_add_mode", skip_all, err)]
+ pub async fn set_group_member_add_mode(
+ &self,
+ jid: &Jid,
+ mode: GroupMemberAddMode,
+ ) -> Result<(), ClientError> {
+ if mode != GroupMemberAddMode::Admin && mode != GroupMemberAddMode::AllMember {
+ return Err(ClientError::Other(
+ "invalid mode, must be 'admin_add' or 'all_member_add'".to_owned(),
+ ));
+ }
+ self.send_group_iq(
+ IqType::Set,
+ jid,
+ node(
+ "member_add_mode",
+ Attrs::new(),
+ Some(NodeContent::Bytes(mode.as_str().as_bytes().to_vec())),
+ ),
+ )
+ .await
+ .map(|_| ())
+ }
+}
+
+/// `exslices.FastDeleteItem`: removes the first match by swapping in the last
+/// element.
+fn fast_delete_item(items: &mut Vec<Jid>, item: &Jid) {
+ if let Some(index) = items.iter().position(|existing| existing == item) {
+ items.swap_remove(index);
+ }
+}
+
+/// Parses a `<participant>`. Attribute errors land in `attrs`, which the
+/// caller owns (Go passes the caller's `AttrUtility`).
+pub(crate) fn parse_participant(attrs: &mut AttrUtility<'_>, child: &Node) -> GroupParticipant {
+ let participant_type = attrs.optional_string("type");
+ let mut participant = GroupParticipant {
+ is_admin: participant_type == "admin" || participant_type == "superadmin",
+ is_super_admin: participant_type == "superadmin",
+ jid: attrs.jid("jid"),
+ display_name: attrs.optional_string("display_name"),
+ ..GroupParticipant::default()
+ };
+ if participant.jid.server == HIDDEN_USER_SERVER {
+ participant.lid = participant.jid.clone();
+ participant.phone_number = attrs.optional_jid_or_empty("phone_number");
+ } else if participant.jid.server == DEFAULT_USER_SERVER {
+ participant.phone_number = participant.jid.clone();
+ participant.lid = attrs.optional_jid_or_empty("lid");
+ }
+ let error_code = attrs.optional_int("error");
+ if error_code != 0 {
+ participant.error = error_code;
+ if let Some(add_request) = child.get_optional_child_by_tag(&["add_request"]) {
+ let mut add_attrs = add_request.attr_getter();
+ participant.add_request = Some(GroupParticipantAddRequest {
+ code: add_attrs.string("code"),
+ expiration: add_attrs.unix_time("expiration"),
+ });
+ }
+ }
+ participant
+}
+
+/// Parses a `<group>` node. The group comes back even when its attributes
+/// didn't fully parse, with the errors next to it.
+pub(crate) fn parse_group_node(group_node: &Node) -> (GroupInfo, Result<(), ErrorList>) {
+ let mut group = GroupInfo::default();
+ let mut attrs = group_node.attr_getter();
+
+ group.jid = new_jid(&attrs.string("id"), GROUP_SERVER);
+ group.owner_jid = attrs.optional_jid_or_empty("creator");
+ group.owner_pn = attrs.optional_jid_or_empty("creator_pn");
+
+ group.name.name = attrs.optional_string("subject");
+ group.name.name_set_at = attrs.optional_unix_time("s_t");
+ group.name.name_set_by = attrs.optional_jid_or_empty("s_o");
+ group.name.name_set_by_pn = attrs.optional_jid_or_empty("s_o_pn");
+
+ group.group_created = attrs.optional_unix_time("creation");
+ group.creator_country_code = attrs.optional_string("creator_country_code");
+
+ group.announce.announce_version_id = attrs.optional_string("a_v_id");
+ group.participant_version_id = attrs.optional_string("p_v_id");
+ group.participant_count = attrs.optional_int("size");
+ group.addressing_mode = AddressingMode::from(attrs.optional_string("addressing_mode"));
+
+ for child in group_node.get_children() {
+ let mut child_attrs = child.attr_getter();
+ match child.tag.as_str() {
+ "participant" => group
+ .participants
+ .push(parse_participant(&mut child_attrs, child)),
+ "description" => {
+ if let Some(body) = child.get_optional_child_by_tag(&["body"]) {
+ group.topic.topic = match &body.content {
+ Some(NodeContent::Bytes(topic)) => {
+ String::from_utf8_lossy(topic).into_owned()
+ }
+ _ => String::new(),
+ };
+ group.topic.topic_id = child_attrs.string("id");
+ group.topic.topic_set_by = child_attrs.optional_jid_or_empty("participant");
+ // TODO confirm field name
+ group.topic.topic_set_by_pn =
+ child_attrs.optional_jid_or_empty("participant_pn");
+ group.topic.topic_set_at = child_attrs.unix_time("t");
+ }
+ }
+ "announcement" => group.announce.is_announce = true,
+ "locked" => group.locked.is_locked = true,
+ "ephemeral" => {
+ group.ephemeral.is_ephemeral = true;
+ group.ephemeral.disappearing_timer = child_attrs.uint64("expiration") as u32;
+ }
+ "member_add_mode" => {
+ group.member_add_mode = match &child.content {
+ Some(NodeContent::Bytes(mode)) => {
+ GroupMemberAddMode::from(String::from_utf8_lossy(mode).as_ref())
+ }
+ _ => GroupMemberAddMode::Empty,
+ };
+ }
+ "linked_parent" => group.linked_parent.linked_parent_jid = child_attrs.jid("jid"),
+ "default_sub_group" => group.is_default_sub.is_default_sub_group = true,
+ "parent" => {
+ group.parent.is_parent = true;
+ group.parent.default_membership_approval_mode =
+ child_attrs.optional_string("default_membership_approval_mode");
+ }
+ "incognito" => group.incognito.is_incognito = true,
+ "membership_approval_mode" => {
+ group.membership_approval_mode.is_join_approval_required = true;
+ }
+ "suspended" => group.suspended = true,
+ other => tracing::debug!(tag = other, "unknown element in group node"),
+ }
+ if !child_attrs.ok() {
+ tracing::warn!(tag = %child.tag, errors = ?child_attrs.errors, "possibly failed to parse element in group node");
+ }
+ }
+ (group, attrs.error())
+}
+
+/// Parses a linked group (`<group>` in link changes and subgroup lists).
+pub(crate) fn parse_group_link_target_node(
+ group_node: &Node,
+) -> Result<GroupLinkTarget, ErrorList> {
+ let mut attrs = group_node.attr_getter();
+ let mut jid = attrs.optional_jid_or_empty("jid");
+ if jid.is_empty() {
+ jid = new_jid(&attrs.string("id"), GROUP_SERVER);
+ }
+ let target = GroupLinkTarget {
+ jid,
+ name: GroupName {
+ name: attrs.optional_string("subject"),
+ name_set_at: attrs.optional_unix_time("s_t"),
+ ..GroupName::default()
+ },
+ is_default_sub: crate::types::GroupIsDefaultSub {
+ is_default_sub_group: group_node.get_child_by_tag(&["default_sub_group"]).tag
+ == "default_sub_group",
+ },
+ };
+ attrs.error()?;
+ Ok(target)
+}
+
+/// The JIDs of the `<participant>` children, with the LID mappings their
+/// `phone_number` / `lid` attributes give.
+pub(crate) fn parse_participant_list(node: &Node) -> (Vec<Jid>, Vec<LidMapping>) {
+ let children = node.get_children();
+ let mut participants = Vec::with_capacity(children.len());
+ let mut lid_pairs = Vec::new();
+ for child in children {
+ let Some(AttributeValue::Jid(jid)) = child.attrs.get("jid") else {
+ continue;
+ };
+ if child.tag != "participant" {
+ continue;
+ }
+ participants.push(jid.clone());
+ if jid.server == HIDDEN_USER_SERVER {
+ if let Some(AttributeValue::Jid(phone_number)) = child.attrs.get("phone_number")
+ && !phone_number.is_empty()
+ {
+ lid_pairs.push(LidMapping {
+ lid: jid.clone(),
+ pn: phone_number.clone(),
+ });
+ }
+ } else if jid.server == DEFAULT_USER_SERVER
+ && let Some(AttributeValue::Jid(lid)) = child.attrs.get("lid")
+ && !lid.is_empty()
+ {
+ lid_pairs.push(LidMapping {
+ lid: lid.clone(),
+ pn: jid.clone(),
+ });
+ }
+ }
+ (participants, lid_pairs)
+}
+
+/// Parses a group change notification. The LID mappings are those of the
+/// last participant list in it, as in Go.
+pub(crate) fn parse_group_change(
+ node: &Node,
+) -> Result<(GroupInfoEvent, Vec<LidMapping>), ClientError> {
+ let mut event = GroupInfoEvent::default();
+ let mut attrs = node.attr_getter();
+ event.jid = attrs.jid("from");
+ event.notify = attrs.optional_string("notify");
+ event.sender = attrs.optional_jid("participant");
+ event.sender_pn = attrs.optional_jid("participant_pn");
+ event.timestamp = attrs.unix_time("t");
+ attrs.error().map_err(|error| {
+ ClientError::from(error).wrap("group change doesn't contain required attributes")
+ })?;
+
+ let mut lid_pairs = Vec::new();
+ for child in node.get_children() {
+ let mut child_attrs = child.attr_getter();
+ if matches!(child.tag.as_str(), "add" | "remove" | "promote" | "demote") {
+ event.prev_participant_version_id = child_attrs.optional_string("prev_v_id");
+ event.participant_version_id = child_attrs.optional_string("v_id");
+ }
+ match child.tag.as_str() {
+ "add" => {
+ event.join_reason = child_attrs.optional_string("reason");
+ (event.join, lid_pairs) = parse_participant_list(child);
+ }
+ "remove" => (event.leave, lid_pairs) = parse_participant_list(child),
+ "promote" => (event.promote, lid_pairs) = parse_participant_list(child),
+ "demote" => (event.demote, lid_pairs) = parse_participant_list(child),
+ "locked" => event.locked = Some(GroupLocked { is_locked: true }),
+ "unlocked" => event.locked = Some(GroupLocked { is_locked: false }),
+ "delete" => {
+ event.delete = Some(GroupDelete {
+ deleted: true,
+ delete_reason: child_attrs.optional_string("reason"),
+ });
+ }
+ "subject" => {
+ event.name = Some(GroupName {
+ name: child_attrs.string("subject"),
+ name_set_at: child_attrs.unix_time("s_t"),
+ name_set_by: child_attrs.optional_jid_or_empty("s_o"),
+ name_set_by_pn: child_attrs.optional_jid_or_empty("s_o_pn"),
+ });
+ }
+ "description" => {
+ let is_delete = child.get_optional_child_by_tag(&["delete"]).is_some();
+ let mut topic = String::new();
+ if !is_delete {
+ let Some(NodeContent::Bytes(topic_bytes)) =
+ &child.get_child_by_tag(&["body"]).content
+ else {
+ return Err(ClientError::Other(
+ "group change description has unexpected body".to_owned(),
+ ));
+ };
+ topic = String::from_utf8_lossy(topic_bytes).into_owned();
+ }
+ event.topic = Some(GroupTopic {
+ topic,
+ topic_id: child_attrs.string("id"),
+ topic_set_at: event.timestamp,
+ topic_set_by: event.sender.clone().unwrap_or_default(),
+ topic_deleted: is_delete,
+ ..GroupTopic::default()
+ });
+ }
+ "announcement" => {
+ event.announce = Some(GroupAnnounce {
+ is_announce: true,
+ announce_version_id: child_attrs.string("v_id"),
+ });
+ }
+ "not_announcement" => {
+ event.announce = Some(GroupAnnounce {
+ is_announce: false,
+ announce_version_id: child_attrs.string("v_id"),
+ });
+ }
+ "invite" => {
+ event.new_invite_link = Some(format!(
+ "{INVITE_LINK_PREFIX}{}",
+ child_attrs.string("code")
+ ));
+ }
+ "ephemeral" => {
+ event.ephemeral = Some(GroupEphemeral {
+ is_ephemeral: true,
+ disappearing_timer: child_attrs.uint64("expiration") as u32,
+ });
+ }
+ "not_ephemeral" => {
+ event.ephemeral = Some(GroupEphemeral {
+ is_ephemeral: false,
+ disappearing_timer: 0,
+ });
+ }
+ "link" => {
+ let r#type = GroupLinkChangeType::from(child_attrs.string("link_type"));
+ let group_node = child
+ .get_optional_child_by_tag(&["group"])
+ .ok_or_else(|| element_missing("group", "group link"))?;
+ let group = parse_group_link_target_node(group_node).map_err(|error| {
+ ClientError::from(error).wrap("failed to parse group link node in group change")
+ })?;
+ event.link = Some(GroupLinkChange {
+ r#type,
+ group,
+ ..GroupLinkChange::default()
+ });
+ }
+ "unlink" => {
+ let r#type = GroupLinkChangeType::from(child_attrs.string("unlink_type"));
+ let unlink_reason = GroupUnlinkReason::from(child_attrs.string("unlink_reason"));
+ let group_node = child
+ .get_optional_child_by_tag(&["group"])
+ .ok_or_else(|| element_missing("group", "group unlink"))?;
+ let group = parse_group_link_target_node(group_node).map_err(|error| {
+ ClientError::from(error)
+ .wrap("failed to parse group unlink node in group change")
+ })?;
+ event.unlink = Some(GroupLinkChange {
+ r#type,
+ unlink_reason,
+ group,
+ });
+ }
+ "membership_approval_mode" => {
+ event.membership_approval_mode = Some(GroupMembershipApprovalMode {
+ is_join_approval_required: true,
+ });
+ }
+ "suspended" => event.suspended = true,
+ "unsuspended" => event.unsuspended = true,
+ _ => event.unknown_changes.push(child.clone()),
+ }
+ if let Err(error) = child_attrs.error() {
+ return Err(ClientError::from(error).wrap(format!(
+ "group change {} element doesn't contain required attributes",
+ child.tag
+ )));
+ }
+ }
+ Ok((event, lid_pairs))
+}
+
+#[cfg(test)]
+mod test;
diff --git a/crates/whatsmeow/src/group/test.rs b/crates/whatsmeow/src/group/test.rs
new file mode 100644
index 0000000000..36d1410cdb
--- /dev/null
+++ b/crates/whatsmeow/src/group/test.rs
@@ -0,0 +1,774 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+//! Group parsing and requests against whatsmeow's own output
+//! (`testdata/group.json`, see `testdata/generator`), and the group calls
+//! and `w:gp2` notifications against the fake server.
+
+use std::sync::Arc;
+use std::time::Duration;
+
+use chrono::{DateTime, Utc};
+use serde_json::{Value, json};
+
+use super::*;
+use crate::binary::AttributeValue;
+use crate::client::test::{
+ capture_request, children, connect_paired, harness, jid, next_event, next_node, node, text,
+};
+use crate::store::{ContactStore, LidStore};
+use crate::testing::{attr_string, is_iq};
+use crate::types::events::Event;
+use crate::types::parse_jid;
+use crate::vectors::Vectors;
+
+const OWN: (&str, &str) = ("1234:[email protected]", "9876:5@lid");
+
+fn unix(time: Option<DateTime<Utc>>) -> i64 {
+ time.map_or(0, |time| time.timestamp())
+}
+
+fn jid_strings(jids: &[Jid]) -> Vec<String> {
+ jids.iter().map(ToString::to_string).collect()
+}
+
+fn lid_pair_strings(pairs: &[LidMapping]) -> Value {
+ json!(
+ pairs
+ .iter()
+ .map(|pair| [pair.lid.to_string(), pair.pn.to_string()])
+ .collect::<Vec<_>>()
+ )
+}
+
+fn redacted_strings(entries: &[RedactedPhoneEntry]) -> Value {
+ json!(
+ entries
+ .iter()
+ .map(|entry| [entry.jid.to_string(), entry.redacted_phone.clone()])
+ .collect::<Vec<_>>()
+ )
+}
+
+fn participant_vector(participant: &GroupParticipant) -> Value {
+ json!({
+ "jid": participant.jid.to_string(),
+ "phone_number": participant.phone_number.to_string(),
+ "lid": participant.lid.to_string(),
+ "is_admin": participant.is_admin,
+ "is_super_admin": participant.is_super_admin,
+ "display_name": participant.display_name,
+ "error": participant.error,
+ "add_request": participant.add_request.as_ref().map(|request| json!({
+ "code": request.code,
+ "expiration": unix(request.expiration),
+ })),
+ })
+}
+
+fn group_info_vector(group: &GroupInfo) -> Value {
+ json!({
+ "jid": group.jid.to_string(),
+ "owner_jid": group.owner_jid.to_string(),
+ "owner_pn": group.owner_pn.to_string(),
+ "name": group.name.name,
+ "name_set_at": unix(group.name.name_set_at),
+ "name_set_by": group.name.name_set_by.to_string(),
+ "name_set_by_pn": group.name.name_set_by_pn.to_string(),
+ "topic": group.topic.topic,
+ "topic_id": group.topic.topic_id,
+ "topic_set_at": unix(group.topic.topic_set_at),
+ "topic_set_by": group.topic.topic_set_by.to_string(),
+ "topic_set_by_pn": group.topic.topic_set_by_pn.to_string(),
+ "topic_deleted": group.topic.topic_deleted,
+ "is_locked": group.locked.is_locked,
+ "is_announce": group.announce.is_announce,
+ "announce_version_id": group.announce.announce_version_id,
+ "is_ephemeral": group.ephemeral.is_ephemeral,
+ "disappearing_timer": group.ephemeral.disappearing_timer,
+ "is_incognito": group.incognito.is_incognito,
+ "is_parent": group.parent.is_parent,
+ "default_membership_approval_mode": group.parent.default_membership_approval_mode,
+ "linked_parent_jid": group.linked_parent.linked_parent_jid.to_string(),
+ "is_default_sub_group": group.is_default_sub.is_default_sub_group,
+ "is_join_approval_required": group.membership_approval_mode.is_join_approval_required,
+ "addressing_mode": group.addressing_mode.as_str(),
+ "group_created": unix(group.group_created),
+ "creator_country_code": group.creator_country_code,
+ "participant_version_id": group.participant_version_id,
+ "participants": group.participants.iter().map(participant_vector).collect::<Vec<_>>(),
+ "participant_count": group.participant_count,
+ "member_add_mode": group.member_add_mode.as_str(),
+ "suspended": group.suspended,
+ })
+}
+
+fn link_change_vector(change: Option<&GroupLinkChange>) -> Value {
+ match change {
+ None => Value::Null,
+ Some(change) => json!({
+ "type": change.r#type.as_str(),
+ "unlink_reason": change.unlink_reason.as_str(),
+ "group": {
+ "jid": change.group.jid.to_string(),
+ "name": change.group.name.name,
+ "name_set_at": unix(change.group.name.name_set_at),
+ "is_default_sub_group": change.group.is_default_sub.is_default_sub_group,
+ },
+ }),
+ }
+}
+
+fn group_change_vector(event: &GroupInfoEvent) -> Value {
+ json!({
+ "jid": event.jid.to_string(),
+ "notify": event.notify,
+ "sender": event.sender.as_ref().map(ToString::to_string),
+ "sender_pn": event.sender_pn.as_ref().map(ToString::to_string),
+ "timestamp": unix(event.timestamp),
+ "name": event.name.as_ref().map(|name| json!({
+ "name": name.name,
+ "name_set_at": unix(name.name_set_at),
+ "name_set_by": name.name_set_by.to_string(),
+ "name_set_by_pn": name.name_set_by_pn.to_string(),
+ })),
+ "topic": event.topic.as_ref().map(|topic| json!({
+ "topic": topic.topic,
+ "topic_id": topic.topic_id,
+ "topic_set_at": unix(topic.topic_set_at),
+ "topic_set_by": topic.topic_set_by.to_string(),
+ "topic_deleted": topic.topic_deleted,
+ })),
+ "locked": event.locked.as_ref().map(|locked| locked.is_locked),
+ "announce": event.announce.as_ref().map(|announce| json!({
+ "is_announce": announce.is_announce,
+ "announce_version_id": announce.announce_version_id,
+ })),
+ "ephemeral": event.ephemeral.as_ref().map(|ephemeral| json!({
+ "is_ephemeral": ephemeral.is_ephemeral,
+ "disappearing_timer": ephemeral.disappearing_timer,
+ })),
+ "membership_approval_mode": event
+ .membership_approval_mode
+ .as_ref()
+ .map(|mode| mode.is_join_approval_required),
+ "delete": event.delete.as_ref().map(|delete| json!({
+ "deleted": delete.deleted,
+ "delete_reason": delete.delete_reason,
+ })),
+ "link": link_change_vector(event.link.as_ref()),
+ "unlink": link_change_vector(event.unlink.as_ref()),
+ "new_invite_link": event.new_invite_link,
+ "prev_participant_version_id": event.prev_participant_version_id,
+ "participant_version_id": event.participant_version_id,
+ "join_reason": event.join_reason,
+ "join": jid_strings(&event.join),
+ "leave": jid_strings(&event.leave),
+ "promote": jid_strings(&event.promote),
+ "demote": jid_strings(&event.demote),
+ "suspended": event.suspended,
+ "unsuspended": event.unsuspended,
+ "unknown_changes": event.unknown_changes.iter().map(|change| change.tag.clone()).collect::<Vec<_>>(),
+ })
+}
+
+fn group_jid() -> Jid {
+ parse_jid("[email protected]").unwrap()
+}
+
+#[tokio::test]
+async fn group_nodes_and_notifications_parse_like_go() {
+ let vectors = Vectors::load("group.json");
+ let harness = harness(Some(OWN));
+ let client = &harness.client;
+
+ let (parsed, result) = parse_group_node(&vectors.node("group_node"));
+ result.unwrap();
+ assert_eq!(group_info_vector(&parsed), *vectors.value("group_info"));
+ let (lid_pairs, redacted_phones) = client.cache_group_info(&parsed, None).await;
+ assert_eq!(
+ lid_pair_strings(&lid_pairs),
+ *vectors.value("group_lid_pairs")
+ );
+ assert_eq!(
+ redacted_strings(&redacted_phones),
+ *vectors.value("group_redacted_phones")
+ );
+
+ let (broken, result) = parse_group_node(&vectors.node("broken_group_node"));
+ assert_eq!(
+ group_info_vector(&broken),
+ *vectors.value("broken_group_info")
+ );
+ assert_eq!(
+ result.unwrap_err().to_string(),
+ vectors.string("broken_group_error")
+ );
+
+ let Value::Array(changes) = vectors.value("group_changes") else {
+ panic!("group_changes is a list");
+ };
+ for change in changes {
+ let notification = node_from_hex(&change["node"]);
+ let (event, lid_pairs, redacted_phones) = client
+ .parse_group_notification(&notification)
+ .await
+ .unwrap();
+ let GroupNotification::Change(event) = event else {
+ panic!("expected a group change");
+ };
+ assert_eq!(group_change_vector(&event), change["event"]);
+ assert_eq!(lid_pair_strings(&lid_pairs), change["lid_pairs"]);
+ assert!(redacted_phones.is_empty());
+ }
+ let cached = client
+ .group_cache
+ .lock()
+ .await
+ .get(&group_jid())
+ .cloned()
+ .unwrap();
+ assert_eq!(
+ json!({
+ "addressing_mode": cached.addressing_mode.as_str(),
+ "community_announcement_group": cached.community_announcement_group,
+ "read_only": cached.read_only,
+ "members": jid_strings(&cached.members),
+ "admins": jid_strings(&cached.admins),
+ }),
+ *vectors.value("cached_after_changes")
+ );
+
+ let (event, lid_pairs, redacted_phones) = client
+ .parse_group_notification(&vectors.node("create_node"))
+ .await
+ .unwrap();
+ let GroupNotification::Joined(joined) = event else {
+ panic!("expected a joined group");
+ };
+ assert_eq!(
+ json!({
+ "reason": joined.reason,
+ "type": joined.r#type,
+ "create_key": joined.create_key,
+ "sender": joined.sender.as_ref().map(ToString::to_string),
+ "sender_pn": joined.sender_pn.as_ref().map(ToString::to_string),
+ "notify": joined.notify,
+ "group_info": group_info_vector(&joined.group_info),
+ }),
+ *vectors.value("joined_group")
+ );
+ assert_eq!(
+ lid_pair_strings(&lid_pairs),
+ *vectors.value("joined_lid_pairs")
+ );
+ assert_eq!(
+ redacted_strings(&redacted_phones),
+ *vectors.value("joined_redacted_phones")
+ );
+
+ let Value::Array(failures) = vectors.value("group_change_failures") else {
+ panic!("group_change_failures is a list");
+ };
+ for failure in failures {
+ let error = client
+ .parse_group_notification(&node_from_hex(&failure["node"]))
+ .await
+ .unwrap_err();
+ assert_eq!(error.to_string(), failure["error"]);
+ }
+}
+
+fn node_from_hex(value: &Value) -> Node {
+ let data = hex::decode(value.as_str().unwrap()).unwrap();
+ crate::binary::unmarshal(&crate::binary::unpack(&data).unwrap()).unwrap()
+}
+
+#[tokio::test(start_paused = true)]
+async fn group_requests_match_go() {
+ let vectors = Vectors::load("group.json");
+ let requests = vectors.value("requests");
+ let mut harness = harness(Some(OWN));
+ let mut connection = connect_paired(&mut harness).await;
+ // Leaked so the spawned calls can borrow them.
+ let group: &'static Jid = Box::leak(Box::new(group_jid()));
+ let parent: &'static Jid = Box::leak(Box::new(parse_jid("[email protected]").unwrap()));
+ let inviter: &'static Jid = Box::leak(Box::new(parse_jid("[email protected]").unwrap()));
+ let lid: &'static Jid = Box::leak(Box::new(parse_jid("5555@lid").unwrap()));
+ let pn: &'static Jid = Box::leak(Box::new(parse_jid("[email protected]").unwrap()));
+
+ macro_rules! check {
+ ($key:literal, |$client:ident| $call:expr) => {{
+ let $client = Arc::clone(&harness.client);
+ let request = capture_request(&mut connection, async move {
+ let _ = $call;
+ })
+ .await;
+ assert_eq!(request, node_from_hex(&requests[$key]), $key);
+ }};
+ }
+
+ check!("get_joined_groups", |client| client
+ .get_joined_groups()
+ .await);
+ check!("get_group_info", |client| client
+ .get_group_info(group)
+ .await);
+ check!("create_group", |client| client
+ .create_group(ReqCreateGroup {
+ name: "Team".to_owned(),
+ participants: vec![pn.clone(), parse_jid("5555:2@lid").unwrap()],
+ ephemeral: GroupEphemeral {
+ is_ephemeral: true,
+ disappearing_timer: 604_800,
+ },
+ announce: GroupAnnounce {
+ is_announce: true,
+ ..GroupAnnounce::default()
+ },
+ locked: GroupLocked { is_locked: true },
+ membership_approval_mode: GroupMembershipApprovalMode {
+ is_join_approval_required: true,
+ },
+ member_add_mode: GroupMemberAddMode::Admin,
+ linked_parent: GroupLinkedParent {
+ linked_parent_jid: parent.clone(),
+ },
+ ..ReqCreateGroup::default()
+ })
+ .await);
+ check!("create_community", |client| client
+ .create_group(ReqCreateGroup {
+ name: "Community".to_owned(),
+ parent: GroupParent {
+ is_parent: true,
+ ..GroupParent::default()
+ },
+ ..ReqCreateGroup::default()
+ })
+ .await);
+ check!("leave_group", |client| client.leave_group(group).await);
+ check!("add_participants", |client| client
+ .update_group_participants(group, &[lid.clone(), pn.clone()], ParticipantChange::Add)
+ .await);
+ check!("demote_participants", |client| client
+ .update_group_participants(group, std::slice::from_ref(lid), ParticipantChange::Demote)
+ .await);
+ check!("get_request_participants", |client| client
+ .get_group_request_participants(group)
+ .await);
+ check!("approve_request_participants", |client| client
+ .update_group_request_participants(
+ group,
+ std::slice::from_ref(lid),
+ ParticipantRequestChange::Approve
+ )
+ .await);
+ check!("set_group_photo", |client| client
+ .set_group_photo(group, Some(vec![0xff, 0xd8]))
+ .await);
+ check!("remove_group_photo", |client| client
+ .set_group_photo(group, None)
+ .await);
+ check!("set_group_name", |client| client
+ .set_group_name(group, "New name")
+ .await);
+ check!("set_group_topic", |client| client
+ .set_group_topic(group, "prev1", "new1", "Topic")
+ .await);
+ check!("delete_group_topic", |client| client
+ .set_group_topic(group, "prev1", "new2", "")
+ .await);
+ check!("set_group_locked", |client| client
+ .set_group_locked(group, true)
+ .await);
+ check!("set_group_unlocked", |client| client
+ .set_group_locked(group, false)
+ .await);
+ check!("set_group_announce", |client| client
+ .set_group_announce(group, true)
+ .await);
+ check!("set_group_not_announce", |client| client
+ .set_group_announce(group, false)
+ .await);
+ check!("reset_invite_link", |client| client
+ .get_group_invite_link(group, true)
+ .await);
+ check!("get_invite_link", |client| client
+ .get_group_invite_link(group, false)
+ .await);
+ check!("info_from_invite", |client| client
+ .get_group_info_from_invite(group, inviter, "code1", 1_700_000_000)
+ .await);
+ check!("join_with_invite", |client| client
+ .join_group_with_invite(group, inviter, "code1", 1_700_000_000)
+ .await);
+ check!("info_from_link", |client| client
+ .get_group_info_from_link("https://chat.whatsapp.com/AbC?x=1")
+ .await);
+ check!("join_with_link", |client| client
+ .join_group_with_link("AbC")
+ .await);
+ check!("join_approval_mode", |client| client
+ .set_group_join_approval_mode(group, true)
+ .await);
+ check!("member_add_mode", |client| client
+ .set_group_member_add_mode(group, GroupMemberAddMode::Admin)
+ .await);
+}
+
+fn group_response(id: &str, participants: Vec<Node>) -> Node {
+ node(
+ "group",
+ &[
+ ("id", text(id)),
+ ("subject", text("Team")),
+ ("addressing_mode", text("lid")),
+ ],
+ children(participants),
+ )
+}
+
+fn participant(attrs: &[(&str, AttributeValue)]) -> Node {
+ node("participant", attrs, None)
+}
+
+#[tokio::test(start_paused = true)]
+async fn joined_groups_are_parsed_cached_and_their_mappings_stored() {
+ let mut harness = harness(Some(OWN));
+ let mut connection = connect_paired(&mut harness).await;
+ let client = Arc::clone(&harness.client);
+ let call = tokio::spawn(async move { client.get_joined_groups().await });
+
+ let request = next_node(&mut connection).await;
+ assert!(is_iq(&request, "w:g2"));
+ assert_eq!(attr_string(&request, "type"), "get");
+ assert_eq!(attr_string(&request, "to"), "g.us");
+ let participating = request.get_child_by_tag(&["participating"]);
+ let tags: Vec<&str> = participating
+ .get_children()
+ .iter()
+ .map(|child| child.tag.as_str())
+ .collect();
+ assert_eq!(tags, ["participants", "description"]);
+
+ connection
+ .respond_iq(
+ &request,
+ vec![node(
+ "groups",
+ &[],
+ children(vec![
+ group_response(
+ "111",
+ vec![
+ participant(&[
+ ("jid", jid("1111@lid")),
+ ("type", text("admin")),
+ ("phone_number", jid("[email protected]")),
+ ]),
+ participant(&[
+ ("jid", jid("2222@lid")),
+ ("display_name", text("+1∙∙22")),
+ ]),
+ ],
+ ),
+ node("unexpected", &[], None),
+ group_response("222", vec![]),
+ ]),
+ )],
+ )
+ .await;
+ let groups = call.await.unwrap().unwrap();
+ assert_eq!(groups.len(), 2);
+ assert_eq!(groups[0].jid.to_string(), "[email protected]");
+ assert_eq!(groups[0].name.name, "Team");
+ assert_eq!(groups[0].participants.len(), 2);
+ assert!(groups[0].participants[0].is_admin);
+ assert_eq!(
+ groups[0].participants[0].phone_number.to_string(),
+ );
+ assert_eq!(groups[1].jid.to_string(), "[email protected]");
+
+ assert_eq!(
+ harness
+ .store
+ .get_pn_for_lid(&parse_jid("1111@lid").unwrap())
+ .await
+ .unwrap()
+ .map(|pn| pn.to_string()),
+ Some("[email protected]".to_owned())
+ );
+ let contact = harness
+ .store
+ .get_contact(&parse_jid("2222@lid").unwrap())
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(contact.redacted_phone, "+1∙∙22");
+ let cache = harness.client.group_cache.lock().await;
+ let cached = cache.get(&parse_jid("[email protected]").unwrap()).unwrap();
+ assert_eq!(cached.addressing_mode, AddressingMode::Lid);
+ assert_eq!(jid_strings(&cached.admins), ["1111@lid"]);
+ assert_eq!(jid_strings(&cached.members), ["1111@lid", "2222@lid"]);
+ assert!(cache.contains_key(&parse_jid("[email protected]").unwrap()));
+}
+
+#[tokio::test(start_paused = true)]
+async fn group_info_is_fetched_once_for_the_cache_and_errors_are_mapped() {
+ let mut harness = harness(Some(OWN));
+ let mut connection = connect_paired(&mut harness).await;
+ let group = group_jid();
+
+ let client = Arc::clone(&harness.client);
+ let lookup = group.clone();
+ let first = tokio::spawn(async move { client.get_cached_group_data(&lookup).await });
+ let request = next_node(&mut connection).await;
+ assert!(is_iq(&request, "w:g2"));
+ assert_eq!(attr_string(&request, "to"), group.to_string());
+ assert_eq!(
+ attr_string(request.get_child_by_tag(&["query"]), "request"),
+ "interactive"
+ );
+ connection
+ .respond_iq(
+ &request,
+ vec![{
+ let mut group_node = group_response(
+ "120363001234567890",
+ vec![
+ participant(&[("jid", jid("1111@lid")), ("type", text("superadmin"))]),
+ participant(&[("jid", jid("2222@lid"))]),
+ ],
+ );
+ if let Some(NodeContent::Nodes(nodes)) = &mut group_node.content {
+ nodes.push(node("announcement", &[], None));
+ }
+ group_node
+ }],
+ )
+ .await;
+ let cached = first.await.unwrap().unwrap();
+ assert!(cached.read_only);
+ assert_eq!(jid_strings(&cached.admins), ["1111@lid"]);
+
+ // The second lookup is served from the cache.
+ assert_eq!(
+ harness.client.get_cached_group_data(&group).await.unwrap(),
+ cached
+ );
+ let nothing = tokio::time::timeout(Duration::from_secs(5), next_node(&mut connection)).await;
+ assert!(nothing.is_err(), "a cached lookup sends nothing");
+
+ let client = Arc::clone(&harness.client);
+ let lookup = group.clone();
+ let missing = tokio::spawn(async move { client.get_group_info(&lookup).await });
+ let request = next_node(&mut connection).await;
+ assert!(is_iq(&request, "w:g2"));
+ connection
+ .respond_iq_error(&request, 404, "item-not-found")
+ .await;
+ let error = missing.await.unwrap().unwrap_err();
+ assert_eq!(error.to_string(), "that group does not exist");
+ assert!(error.is(&ClientError::GroupNotFound));
+ assert!(error.is(&ClientError::iq_status(IqError::NOT_FOUND)));
+}
+
+async fn next_group_event(harness: &mut crate::client::test::Harness) -> Event {
+ loop {
+ let event = next_event(&mut harness.events).await;
+ if matches!(event, Event::GroupInfo(_) | Event::JoinedGroup(_)) {
+ return event;
+ }
+ }
+}
+
+#[tokio::test(start_paused = true)]
+async fn group_notifications_emit_events_and_update_the_participant_cache() {
+ let mut harness = harness(Some(OWN));
+ let mut connection = connect_paired(&mut harness).await;
+ let group = group_jid();
+ harness
+ .client
+ .cache_group_info(
+ &GroupInfo {
+ jid: group.clone(),
+ participants: vec![
+ GroupParticipant {
+ jid: parse_jid("1111@lid").unwrap(),
+ is_admin: true,
+ ..GroupParticipant::default()
+ },
+ GroupParticipant {
+ jid: parse_jid("2222@lid").unwrap(),
+ ..GroupParticipant::default()
+ },
+ ],
+ ..GroupInfo::default()
+ },
+ None,
+ )
+ .await;
+
+ connection
+ .send_node(&node(
+ "notification",
+ &[
+ ("id", text("n1")),
+ ("type", text("w:gp2")),
+ ("from", AttributeValue::Jid(group.clone())),
+ ("t", text("1700000100")),
+ ("participant", jid("1111@lid")),
+ ],
+ children(vec![
+ node(
+ "add",
+ &[("v_id", text("2"))],
+ children(vec![participant(&[
+ ("jid", jid("3333@lid")),
+ ("phone_number", jid("[email protected]")),
+ ])]),
+ ),
+ node(
+ "remove",
+ &[],
+ children(vec![participant(&[("jid", jid("1111@lid"))])]),
+ ),
+ node(
+ "promote",
+ &[("v_id", text("4"))],
+ children(vec![participant(&[("jid", jid("2222@lid"))])]),
+ ),
+ ]),
+ ))
+ .await;
+ let Event::GroupInfo(event) = next_group_event(&mut harness).await else {
+ panic!("expected a group change");
+ };
+ assert_eq!(event.jid, group);
+ assert_eq!(jid_strings(&event.join), ["3333@lid"]);
+ assert_eq!(jid_strings(&event.leave), ["1111@lid"]);
+ assert_eq!(jid_strings(&event.promote), ["2222@lid"]);
+ // Each participant change overwrites the versions, as in Go.
+ assert_eq!(event.participant_version_id, "4");
+ let ack = next_node(&mut connection).await;
+ assert_eq!(ack.tag, "ack");
+ assert_eq!(attr_string(&ack, "class"), "notification");
+ assert_eq!(attr_string(&ack, "id"), "n1");
+
+ let cached = harness
+ .client
+ .group_cache
+ .lock()
+ .await
+ .get(&group)
+ .cloned()
+ .unwrap();
+ // Removal swaps the last member in (Go's `FastDeleteItem`).
+ assert_eq!(jid_strings(&cached.members), ["3333@lid", "2222@lid"]);
+ assert_eq!(jid_strings(&cached.admins), ["2222@lid"]);
+ // The last participant list's mappings are stored (the promote has
+ // none, so the add's are dropped, as in Go).
+ assert_eq!(
+ harness
+ .store
+ .get_pn_for_lid(&parse_jid("3333@lid").unwrap())
+ .await
+ .unwrap(),
+ None
+ );
+
+ connection
+ .send_node(&node(
+ "notification",
+ &[
+ ("id", text("n2")),
+ ("type", text("w:gp2")),
+ ("from", jid("[email protected]")),
+ ("t", text("1700000200")),
+ ("participant", jid("1111@lid")),
+ ],
+ children(vec![node(
+ "create",
+ &[("type", text("new"))],
+ children(vec![node(
+ "group",
+ &[
+ ("id", text("120363007777777777")),
+ ("subject", text("Fresh")),
+ ],
+ children(vec![participant(&[
+ ("jid", jid("1111@lid")),
+ ("phone_number", jid("[email protected]")),
+ ])]),
+ )]),
+ )]),
+ ))
+ .await;
+ let Event::JoinedGroup(joined) = next_group_event(&mut harness).await else {
+ panic!("expected a joined group");
+ };
+ assert_eq!(joined.r#type, "new");
+ assert_eq!(joined.group_info.name.name, "Fresh");
+ assert_eq!(
+ joined.sender.as_ref().map(ToString::to_string),
+ Some("1111@lid".to_owned())
+ );
+ assert!(
+ harness
+ .client
+ .group_cache
+ .lock()
+ .await
+ .contains_key(&parse_jid("[email protected]").unwrap())
+ );
+ assert_eq!(
+ harness
+ .store
+ .get_pn_for_lid(&parse_jid("1111@lid").unwrap())
+ .await
+ .unwrap()
+ .map(|pn| pn.to_string()),
+ Some("[email protected]".to_owned())
+ );
+}
+
+#[tokio::test(start_paused = true)]
+async fn a_failing_handler_leaves_the_group_notification_unacked() {
+ let mut harness = crate::client::test::harness_with(Some(OWN), |config| {
+ config.synchronous_ack = true;
+ });
+ harness
+ .client
+ .add_event_handler(Arc::new(RejectGroupEvents));
+ let mut connection = connect_paired(&mut harness).await;
+ connection
+ .send_node(&node(
+ "notification",
+ &[
+ ("id", text("n3")),
+ ("type", text("w:gp2")),
+ ("from", AttributeValue::Jid(group_jid())),
+ ("t", text("1700000100")),
+ ],
+ children(vec![node("locked", &[], None)]),
+ ))
+ .await;
+ assert!(matches!(
+ next_group_event(&mut harness).await,
+ Event::GroupInfo(_)
+ ));
+ let next = tokio::time::timeout(Duration::from_secs(5), next_node(&mut connection)).await;
+ assert!(next.is_err(), "the notification isn't acked");
+}
+
+struct RejectGroupEvents;
+
+#[async_trait::async_trait]
+impl crate::client::EventHandler for RejectGroupEvents {
+ async fn handle(&self, event: &Event) -> bool {
+ !matches!(event, Event::GroupInfo(_))
+ }
+}
diff --git a/crates/whatsmeow/src/handshake.rs b/crates/whatsmeow/src/handshake.rs
new file mode 100644
index 0000000000..a8b064fdc8
--- /dev/null
+++ b/crates/whatsmeow/src/handshake.rs
@@ -0,0 +1,347 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+//
+// Ported from whatsmeow handshake.go (MPL-2.0, Copyright (c) Tulir Asokan)
+//
+// Go's `doHandshake` is a `Client` method that also wires the frame handler
+// into the client's node queue. Until the client is ported, it is a function
+// taking the client's inputs and returning the noise socket with its events.
+
+//! The noise handshake that opens every connection, and the verification of
+//! the server's certificate chain.
+
+use std::time::Duration;
+
+use chrono::{DateTime, Utc};
+use prost::Message;
+use tokio::sync::mpsc;
+
+use crate::proto::wa_cert::CertChain;
+use crate::proto::wa_cert::cert_chain::noise_certificate::Details;
+use crate::proto::wa_wa6::{ClientPayload, HandshakeMessage, handshake_message};
+use crate::signal::CurveSignatures;
+use crate::socket::{
+ FrameEvent, FrameSocket, NOISE_START_PATTERN, NoiseEvent, NoiseHandshake, NoiseHandshakeError,
+ NoiseSocket, SocketError,
+};
+use crate::util::gcmutil::GcmError;
+use crate::util::keys::KeyPair;
+
+/// How long to wait for the server's handshake response.
+pub const NOISE_HANDSHAKE_RESPONSE_TIMEOUT: Duration = Duration::from_secs(20);
+/// The issuer serial of the intermediate certificate.
+pub const WA_CERT_ISSUER_SERIAL: u32 = 0;
+/// WhatsApp's root key that signs the intermediate noise certificate.
+pub const WA_CERT_PUB_KEY: [u8; 32] = [
+ 0x14, 0x23, 0x75, 0x57, 0x4d, 0xa, 0x58, 0x71, 0x66, 0xaa, 0xe7, 0x1e, 0xbe, 0x51, 0x64, 0x37,
+ 0xc4, 0xa2, 0x8b, 0x73, 0xe3, 0x69, 0x5c, 0x6c, 0xe1, 0xf7, 0xf9, 0x54, 0x5d, 0xa8, 0xee, 0x6b,
+];
+
+/// Why the handshake failed. The messages match whatsmeow's.
+#[derive(Debug, thiserror::Error)]
+pub enum HandshakeError {
+ /// Starting or mixing the handshake failed.
+ #[error("noise handshake failed: {0}")]
+ Noise(#[from] NoiseHandshakeError),
+ /// Sending a handshake frame failed.
+ #[error("failed to send handshake message: {0}")]
+ Send(#[source] SocketError),
+ /// No response within [`NOISE_HANDSHAKE_RESPONSE_TIMEOUT`].
+ #[error("timed out waiting for handshake response")]
+ Timeout,
+ /// The socket closed before the server answered.
+ #[error("socket closed while waiting for handshake response")]
+ Disconnected,
+ /// The response wasn't a handshake message.
+ #[error("failed to unmarshal handshake response: {0}")]
+ Unmarshal(#[source] prost::DecodeError),
+ /// The server hello lacked a part.
+ #[error("missing parts of handshake response")]
+ MissingParts,
+ /// The server's static key didn't decrypt.
+ #[error("failed to decrypt server static ciphertext: {0}")]
+ DecryptStatic(#[source] GcmError),
+ /// The server's static key wasn't 32 bytes.
+ #[error("unexpected length of server static plaintext {0} (expected 32)")]
+ StaticLength(usize),
+ /// The certificate didn't decrypt.
+ #[error("failed to decrypt noise certificate ciphertext: {0}")]
+ DecryptCertificate(#[source] GcmError),
+ /// The certificate didn't verify.
+ #[error("failed to verify server cert: {0}")]
+ Certificate(#[from] CertificateError),
+}
+
+/// Why the server's noise certificate didn't verify.
+#[derive(Debug, thiserror::Error, PartialEq)]
+pub enum CertificateError {
+ /// The chain or its details didn't parse.
+ #[error("failed to unmarshal noise certificate: {0}")]
+ Unmarshal(#[source] prost::DecodeError),
+ /// A certificate lacked details or a signature.
+ #[error("missing parts of noise certificate")]
+ MissingParts,
+ /// The intermediate signature wasn't 64 bytes.
+ #[error("unexpected length of intermediate cert signature {0} (expected 64)")]
+ IntermediateSignatureLength(usize),
+ /// The leaf signature wasn't 64 bytes.
+ #[error("unexpected length of leaf cert signature {0} (expected 64)")]
+ LeafSignatureLength(usize),
+ /// WhatsApp's root key didn't sign the intermediate certificate.
+ #[error("failed to verify intermediate cert signature")]
+ IntermediateSignature,
+ /// The intermediate certificate has another issuer.
+ #[error("unexpected intermediate issuer serial {0} (expected {WA_CERT_ISSUER_SERIAL})")]
+ IntermediateIssuer(u32),
+ /// The intermediate key wasn't 32 bytes.
+ #[error("unexpected length of intermediate cert key {0} (expected 32)")]
+ IntermediateKeyLength(usize),
+ /// The intermediate key didn't sign the leaf certificate. Go reports this
+ /// with the intermediate message too.
+ #[error("failed to verify intermediate cert signature")]
+ LeafSignature,
+ /// The leaf wasn't issued by the intermediate.
+ #[error("unexpected leaf issuer serial {got} (expected {expected})")]
+ LeafIssuer {
+ /// The leaf's issuer serial.
+ got: u32,
+ /// The intermediate's serial.
+ expected: u32,
+ },
+ /// The leaf key isn't the server's static key.
+ #[error("cert key doesn't match decrypted static")]
+ KeyMismatch,
+ /// A certificate isn't valid at the current time.
+ #[error("{which} cert {reason}")]
+ Validity {
+ /// "intermediate" or "leaf".
+ which: &'static str,
+ /// Not valid yet or expired.
+ reason: ValidityError,
+ },
+}
+
+/// Why a certificate isn't valid now.
+#[derive(Debug, thiserror::Error, PartialEq, Eq)]
+pub enum ValidityError {
+ /// Before the certificate's start.
+ #[error("certificate not valid yet (current time {now} is before {not_before})")]
+ NotYetValid {
+ /// The current time.
+ now: DateTime<Utc>,
+ /// The certificate's start.
+ not_before: DateTime<Utc>,
+ },
+ /// After the certificate's end.
+ #[error("certificate expired (current time {now} is after {not_after})")]
+ Expired {
+ /// The current time.
+ now: DateTime<Utc>,
+ /// The certificate's end.
+ not_after: DateTime<Utc>,
+ },
+}
+
+/// Runs the `Noise_XX_25519_AESGCM_SHA256` handshake for the WhatsApp web
+/// API over a freshly connected frame socket, sending `client_payload` as the
+/// final message. On success, frames go through the returned noise socket.
+pub async fn do_handshake(
+ frame_socket: FrameSocket,
+ mut frames: mpsc::Receiver<FrameEvent>,
+ ephemeral_key_pair: &KeyPair,
+ noise_key: &KeyPair,
+ client_payload: &ClientPayload,
+ signatures: &dyn CurveSignatures,
+) -> Result<(NoiseSocket, mpsc::Receiver<NoiseEvent>), HandshakeError> {
+ let header = frame_socket.header().await.unwrap_or_default();
+ let mut handshake = NoiseHandshake::start(NOISE_START_PATTERN, &header)?;
+ handshake.authenticate(&ephemeral_key_pair.public);
+ let data = HandshakeMessage {
+ client_hello: Some(handshake_message::ClientHello {
+ ephemeral: Some(ephemeral_key_pair.public.to_vec()),
+ ..Default::default()
+ }),
+ ..Default::default()
+ }
+ .encode_to_vec();
+ frame_socket
+ .send_frame(&data)
+ .await
+ .map_err(HandshakeError::Send)?;
+
+ let response = match tokio::time::timeout(NOISE_HANDSHAKE_RESPONSE_TIMEOUT, frames.recv()).await
+ {
+ Err(_) => return Err(HandshakeError::Timeout),
+ Ok(Some(FrameEvent::Frame(response))) => response,
+ Ok(Some(FrameEvent::Disconnected { .. }) | None) => {
+ return Err(HandshakeError::Disconnected);
+ }
+ };
+ let handshake_response =
+ HandshakeMessage::decode(response.as_slice()).map_err(HandshakeError::Unmarshal)?;
+ let server_hello = handshake_response.server_hello.unwrap_or_default();
+ let (Some(server_ephemeral), Some(server_static_ciphertext), Some(certificate_ciphertext)) = (
+ server_hello.ephemeral,
+ server_hello.r#static,
+ server_hello.payload,
+ ) else {
+ return Err(HandshakeError::MissingParts);
+ };
+ let server_ephemeral: [u8; 32] = server_ephemeral
+ .try_into()
+ .map_err(|_| HandshakeError::MissingParts)?;
+
+ handshake.authenticate(&server_ephemeral);
+ handshake.mix_shared_secret_into_key(ephemeral_key_pair.private, server_ephemeral)?;
+
+ let static_decrypted = handshake
+ .decrypt(&server_static_ciphertext)
+ .map_err(HandshakeError::DecryptStatic)?;
+ let static_decrypted: [u8; 32] = static_decrypted
+ .try_into()
+ .map_err(|wrong: Vec<u8>| HandshakeError::StaticLength(wrong.len()))?;
+ handshake.mix_shared_secret_into_key(ephemeral_key_pair.private, static_decrypted)?;
+
+ let certificate_decrypted = handshake
+ .decrypt(&certificate_ciphertext)
+ .map_err(HandshakeError::DecryptCertificate)?;
+ verify_server_cert(&certificate_decrypted, &static_decrypted, signatures)?;
+
+ let encrypted_public_key = handshake.encrypt(&noise_key.public)?;
+ handshake.mix_shared_secret_into_key(noise_key.private, server_ephemeral)?;
+
+ let encrypted_client_finish_payload = handshake.encrypt(&client_payload.encode_to_vec())?;
+ let data = HandshakeMessage {
+ client_finish: Some(handshake_message::ClientFinish {
+ r#static: Some(encrypted_public_key),
+ payload: Some(encrypted_client_finish_payload),
+ ..Default::default()
+ }),
+ ..Default::default()
+ }
+ .encode_to_vec();
+ frame_socket
+ .send_frame(&data)
+ .await
+ .map_err(HandshakeError::Send)?;
+
+ Ok(handshake.finish(frame_socket, frames)?)
+}
+
+/// Checks that `now` is within the certificate's validity.
+fn check_cert_validity(details: &Details, now: DateTime<Utc>) -> Result<(), ValidityError> {
+ let seconds = |value: Option<u64>| {
+ DateTime::from_timestamp(
+ i64::try_from(value.unwrap_or_default()).unwrap_or(i64::MAX),
+ 0,
+ )
+ .unwrap_or(DateTime::<Utc>::MAX_UTC)
+ };
+ let not_before = seconds(details.not_before);
+ let not_after = seconds(details.not_after);
+ if now < not_before {
+ return Err(ValidityError::NotYetValid { now, not_before });
+ }
+ if now > not_after {
+ return Err(ValidityError::Expired { now, not_after });
+ }
+ Ok(())
+}
+
+/// Verifies the server's certificate chain: WhatsApp's root key signs the
+/// intermediate, the intermediate signs the leaf, and the leaf key is the
+/// static key the server used in the handshake.
+pub fn verify_server_cert(
+ certificate_decrypted: &[u8],
+ static_decrypted: &[u8; 32],
+ signatures: &dyn CurveSignatures,
+) -> Result<(), CertificateError> {
+ verify_server_cert_at(
+ certificate_decrypted,
+ static_decrypted,
+ signatures,
+ Utc::now(),
+ )
+}
+
+fn verify_server_cert_at(
+ certificate_decrypted: &[u8],
+ static_decrypted: &[u8; 32],
+ signatures: &dyn CurveSignatures,
+ now: DateTime<Utc>,
+) -> Result<(), CertificateError> {
+ let certificate_chain =
+ CertChain::decode(certificate_decrypted).map_err(CertificateError::Unmarshal)?;
+ let intermediate = certificate_chain.intermediate.unwrap_or_default();
+ let leaf = certificate_chain.leaf.unwrap_or_default();
+ let (
+ Some(intermediate_details_raw),
+ Some(intermediate_signature),
+ Some(leaf_details_raw),
+ Some(leaf_signature),
+ ) = (
+ intermediate.details,
+ intermediate.signature,
+ leaf.details,
+ leaf.signature,
+ )
+ else {
+ return Err(CertificateError::MissingParts);
+ };
+ let intermediate_signature: [u8; 64] = intermediate_signature
+ .try_into()
+ .map_err(|wrong: Vec<u8>| CertificateError::IntermediateSignatureLength(wrong.len()))?;
+ let leaf_signature: [u8; 64] = leaf_signature
+ .try_into()
+ .map_err(|wrong: Vec<u8>| CertificateError::LeafSignatureLength(wrong.len()))?;
+
+ if !signatures.verify_signature(
+ &WA_CERT_PUB_KEY,
+ &intermediate_details_raw,
+ &intermediate_signature,
+ ) {
+ return Err(CertificateError::IntermediateSignature);
+ }
+ let intermediate_details = Details::decode(intermediate_details_raw.as_slice())
+ .map_err(CertificateError::Unmarshal)?;
+ let intermediate_issuer = intermediate_details.issuer_serial.unwrap_or_default();
+ if intermediate_issuer != WA_CERT_ISSUER_SERIAL {
+ return Err(CertificateError::IntermediateIssuer(intermediate_issuer));
+ }
+ let intermediate_key = intermediate_details.key.clone().unwrap_or_default();
+ let intermediate_key: [u8; 32] = intermediate_key
+ .try_into()
+ .map_err(|wrong: Vec<u8>| CertificateError::IntermediateKeyLength(wrong.len()))?;
+ if !signatures.verify_signature(&intermediate_key, &leaf_details_raw, &leaf_signature) {
+ return Err(CertificateError::LeafSignature);
+ }
+ check_cert_validity(&intermediate_details, now).map_err(|reason| {
+ CertificateError::Validity {
+ which: "intermediate",
+ reason,
+ }
+ })?;
+
+ let leaf_details =
+ Details::decode(leaf_details_raw.as_slice()).map_err(CertificateError::Unmarshal)?;
+ let expected_issuer = intermediate_details.serial.unwrap_or_default();
+ let leaf_issuer = leaf_details.issuer_serial.unwrap_or_default();
+ if leaf_issuer != expected_issuer {
+ return Err(CertificateError::LeafIssuer {
+ got: leaf_issuer,
+ expected: expected_issuer,
+ });
+ }
+ let leaf_key = leaf_details.key.clone().unwrap_or_default();
+ if !constant_time_eq::constant_time_eq(&leaf_key, static_decrypted) {
+ return Err(CertificateError::KeyMismatch);
+ }
+ check_cert_validity(&leaf_details, now).map_err(|reason| CertificateError::Validity {
+ which: "leaf",
+ reason,
+ })
+}
+
+#[cfg(test)]
+mod test;
diff --git a/crates/whatsmeow/src/handshake/test.rs b/crates/whatsmeow/src/handshake/test.rs
new file mode 100644
index 0000000000..b0f8a63a80
--- /dev/null
+++ b/crates/whatsmeow/src/handshake/test.rs
@@ -0,0 +1,292 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+//! The handshake runs against a fake WhatsApp server over an in-memory
+//! websocket. Signatures are faked: libsignal's XEdDSA is behind the
+//! `CurveSignatures` boundary.
+
+use futures::{SinkExt, StreamExt};
+use sha2::{Digest, Sha256};
+use tokio_tungstenite::WebSocketStream;
+use tokio_tungstenite::tungstenite::Message as WebSocketMessage;
+use tokio_tungstenite::tungstenite::protocol::Role;
+
+use super::*;
+use crate::proto::wa_cert::cert_chain::NoiseCertificate;
+use crate::socket::WA_CONN_HEADER;
+use crate::util::gcmutil;
+use crate::util::keys::new_key_pair_from_private_key;
+
+/// A stand-in signature scheme: the signature is SHA-256 of the key and the
+/// message, twice.
+struct FakeSignatures;
+
+fn fake_signature(public_key: &[u8; 32], message: &[u8]) -> [u8; 64] {
+ let digest: [u8; 32] = Sha256::new()
+ .chain_update(public_key)
+ .chain_update(message)
+ .finalize()
+ .into();
+ let mut signature = [0; 64];
+ signature[..32].copy_from_slice(&digest);
+ signature[32..].copy_from_slice(&digest);
+ signature
+}
+
+impl CurveSignatures for FakeSignatures {
+ fn calculate_signature(&self, _: &[u8; 32], _: &[u8]) -> [u8; 64] {
+ [0; 64]
+ }
+
+ fn verify_signature(
+ &self,
+ public_key: &[u8; 32],
+ message: &[u8],
+ signature: &[u8; 64],
+ ) -> bool {
+ fake_signature(public_key, message) == *signature
+ }
+}
+
+const INTERMEDIATE_KEY: [u8; 32] = [0x42; 32];
+
+fn fixed_private_key(start: u8) -> [u8; 32] {
+ std::array::from_fn(|index| start + u8::try_from(index).unwrap())
+}
+
+fn certificate_chain(leaf_key: &[u8; 32], not_after: u64) -> Vec<u8> {
+ let intermediate_details = Details {
+ serial: Some(7),
+ issuer_serial: Some(WA_CERT_ISSUER_SERIAL),
+ key: Some(INTERMEDIATE_KEY.to_vec()),
+ not_before: Some(1_600_000_000),
+ not_after: Some(not_after),
+ }
+ .encode_to_vec();
+ let leaf_details = Details {
+ serial: Some(8),
+ issuer_serial: Some(7),
+ key: Some(leaf_key.to_vec()),
+ not_before: Some(1_600_000_000),
+ not_after: Some(not_after),
+ }
+ .encode_to_vec();
+ CertChain {
+ intermediate: Some(NoiseCertificate {
+ signature: Some(fake_signature(&WA_CERT_PUB_KEY, &intermediate_details).to_vec()),
+ details: Some(intermediate_details),
+ }),
+ leaf: Some(NoiseCertificate {
+ signature: Some(fake_signature(&INTERMEDIATE_KEY, &leaf_details).to_vec()),
+ details: Some(leaf_details),
+ }),
+ }
+ .encode_to_vec()
+}
+
+fn frame(data: &[u8]) -> WebSocketMessage {
+ let length = u32::try_from(data.len()).unwrap().to_be_bytes();
+ let mut message = length[1..].to_vec();
+ message.extend_from_slice(data);
+ WebSocketMessage::Binary(message.into())
+}
+
+async fn read_frame(server: &mut WebSocketStream<tokio::io::DuplexStream>, skip: usize) -> Vec<u8> {
+ let Some(Ok(WebSocketMessage::Binary(data))) = server.next().await else {
+ panic!("expected a binary message");
+ };
+ data[skip + 3..].to_vec()
+}
+
+#[tokio::test]
+async fn handshake_with_a_fake_server_establishes_the_noise_socket() {
+ let (client, server) = tokio::io::duplex(1 << 16);
+ let client = WebSocketStream::from_raw_socket(client, Role::Client, None).await;
+ let mut server = WebSocketStream::from_raw_socket(server, Role::Server, None).await;
+ let (frame_socket, frames) = FrameSocket::from_websocket(client);
+
+ let client_ephemeral = new_key_pair_from_private_key(fixed_private_key(0x10));
+ let noise_key = new_key_pair_from_private_key(fixed_private_key(0x90));
+ let client_payload = ClientPayload {
+ username: Some(1_234_567_890),
+ device: Some(7),
+ ..Default::default()
+ };
+
+ let server_task = tokio::spawn(async move {
+ let server_ephemeral = new_key_pair_from_private_key(fixed_private_key(0x50));
+ let server_static = new_key_pair_from_private_key(fixed_private_key(0x70));
+
+ let hello = HandshakeMessage::decode(read_frame(&mut server, 4).await.as_slice()).unwrap();
+ let client_ephemeral: [u8; 32] = hello
+ .client_hello
+ .unwrap()
+ .ephemeral
+ .unwrap()
+ .try_into()
+ .unwrap();
+
+ let mut handshake = NoiseHandshake::start(NOISE_START_PATTERN, &WA_CONN_HEADER).unwrap();
+ handshake.authenticate(&client_ephemeral);
+ handshake.authenticate(&server_ephemeral.public);
+ handshake
+ .mix_shared_secret_into_key(server_ephemeral.private, client_ephemeral)
+ .unwrap();
+ let static_ciphertext = handshake.encrypt(&server_static.public).unwrap();
+ handshake
+ .mix_shared_secret_into_key(server_static.private, client_ephemeral)
+ .unwrap();
+ let certificate_ciphertext = handshake
+ .encrypt(&certificate_chain(&server_static.public, 4_000_000_000))
+ .unwrap();
+ let server_hello = HandshakeMessage {
+ server_hello: Some(handshake_message::ServerHello {
+ ephemeral: Some(server_ephemeral.public.to_vec()),
+ r#static: Some(static_ciphertext),
+ payload: Some(certificate_ciphertext),
+ ..Default::default()
+ }),
+ ..Default::default()
+ };
+ server
+ .send(frame(&server_hello.encode_to_vec()))
+ .await
+ .unwrap();
+
+ let finish = HandshakeMessage::decode(read_frame(&mut server, 0).await.as_slice())
+ .unwrap()
+ .client_finish
+ .unwrap();
+ let client_static: [u8; 32] = handshake
+ .decrypt(&finish.r#static.unwrap())
+ .unwrap()
+ .try_into()
+ .unwrap();
+ handshake
+ .mix_shared_secret_into_key(server_ephemeral.private, client_static)
+ .unwrap();
+ let payload = ClientPayload::decode(
+ handshake
+ .decrypt(&finish.payload.unwrap())
+ .unwrap()
+ .as_slice(),
+ )
+ .unwrap();
+ let (client_write, client_read) = handshake.transport_keys();
+
+ let first_transport_frame = read_frame(&mut server, 0).await;
+ let plaintext = gcmutil::decrypt(
+ &client_write,
+ &crate::socket::generate_iv(0),
+ &first_transport_frame,
+ &[],
+ )
+ .unwrap();
+ let reply =
+ gcmutil::encrypt(&client_read, &crate::socket::generate_iv(0), b"pong", &[]).unwrap();
+ server.send(frame(&reply)).await.unwrap();
+ (client_static, payload, plaintext, server)
+ });
+
+ let (noise_socket, mut events) = do_handshake(
+ frame_socket,
+ frames,
+ &client_ephemeral,
+ &noise_key,
+ &client_payload,
+ &FakeSignatures,
+ )
+ .await
+ .unwrap();
+ noise_socket.send_frame(b"ping").await.unwrap();
+ assert_eq!(
+ events.recv().await,
+ Some(NoiseEvent::Frame(b"pong".to_vec()))
+ );
+
+ let (client_static, payload, plaintext, _server) = server_task.await.unwrap();
+ assert_eq!(client_static, noise_key.public);
+ assert_eq!(payload, client_payload);
+ assert_eq!(plaintext, b"ping");
+}
+
+#[tokio::test]
+async fn handshake_fails_when_the_server_hangs_up() {
+ let (client, server) = tokio::io::duplex(1 << 16);
+ let client = WebSocketStream::from_raw_socket(client, Role::Client, None).await;
+ let mut server = WebSocketStream::from_raw_socket(server, Role::Server, None).await;
+ let (frame_socket, frames) = FrameSocket::from_websocket(client);
+ let server_task = tokio::spawn(async move {
+ read_frame(&mut server, 4).await;
+ server.close(None).await.unwrap();
+ });
+
+ let result = do_handshake(
+ frame_socket,
+ frames,
+ &new_key_pair_from_private_key(fixed_private_key(0x10)),
+ &new_key_pair_from_private_key(fixed_private_key(0x90)),
+ &ClientPayload::default(),
+ &FakeSignatures,
+ )
+ .await;
+ assert!(matches!(result, Err(HandshakeError::Disconnected)));
+ server_task.await.unwrap();
+}
+
+#[test]
+fn certificate_chain_checks_match_go() {
+ let static_key = [9; 32];
+ let now = DateTime::from_timestamp(1_700_000_000, 0).unwrap();
+ assert_eq!(
+ verify_server_cert_at(
+ &certificate_chain(&static_key, 4_000_000_000),
+ &static_key,
+ &FakeSignatures,
+ now
+ ),
+ Ok(())
+ );
+ assert_eq!(
+ verify_server_cert_at(
+ &certificate_chain(&[8; 32], 4_000_000_000),
+ &static_key,
+ &FakeSignatures,
+ now
+ ),
+ Err(CertificateError::KeyMismatch)
+ );
+ assert_eq!(
+ verify_server_cert_at(
+ &certificate_chain(&static_key, 1_650_000_000),
+ &static_key,
+ &FakeSignatures,
+ now
+ )
+ .unwrap_err()
+ .to_string(),
+ "intermediate cert certificate expired (current time 2023-11-14 22:13:20 UTC is after 2022-04-15 05:20:00 UTC)"
+ );
+
+ let mut tampered =
+ CertChain::decode(certificate_chain(&static_key, 4_000_000_000).as_slice()).unwrap();
+ if let Some(intermediate) = tampered.intermediate.as_mut() {
+ intermediate.signature = Some(vec![0; 64]);
+ }
+ assert_eq!(
+ verify_server_cert_at(&tampered.encode_to_vec(), &static_key, &FakeSignatures, now),
+ Err(CertificateError::IntermediateSignature)
+ );
+ if let Some(intermediate) = tampered.intermediate.as_mut() {
+ intermediate.signature = Some(vec![0; 63]);
+ }
+ assert_eq!(
+ verify_server_cert_at(&tampered.encode_to_vec(), &static_key, &FakeSignatures, now),
+ Err(CertificateError::IntermediateSignatureLength(63))
+ );
+ assert_eq!(
+ verify_server_cert_at(&[], &static_key, &FakeSignatures, now),
+ Err(CertificateError::MissingParts)
+ );
+}
diff --git a/crates/whatsmeow/src/keepalive.rs b/crates/whatsmeow/src/keepalive.rs
new file mode 100644
index 0000000000..752024e1a5
--- /dev/null
+++ b/crates/whatsmeow/src/keepalive.rs
@@ -0,0 +1,102 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+//
+// Ported from whatsmeow keepalive.go (MPL-2.0, Copyright (c) Tulir Asokan)
+//
+// Go keeps the durations in package variables so callers can change them;
+// here they are constants.
+
+//! Websocket keepalive pings.
+
+use std::sync::Arc;
+use std::time::Duration;
+
+use chrono::Utc;
+use rand::Rng;
+use tokio_util::sync::CancellationToken;
+
+use crate::client::Client;
+use crate::request::{InfoQuery, IqType};
+use crate::types::SERVER_JID;
+use crate::types::events::{Event, KeepAliveRestored, KeepAliveTimeout};
+
+/// How long to wait for a response to a keepalive ping.
+pub const KEEP_ALIVE_RESPONSE_DEADLINE: Duration = Duration::from_secs(10);
+/// The minimum interval between keepalive pings.
+pub const KEEP_ALIVE_INTERVAL_MIN: Duration = Duration::from_secs(20);
+/// The maximum interval between keepalive pings.
+pub const KEEP_ALIVE_INTERVAL_MAX: Duration = Duration::from_secs(30);
+/// How long keepalives may fail before forcing a reconnect.
+pub const KEEP_ALIVE_MAX_FAIL_TIME: Duration = Duration::from_secs(3 * 60);
+
+impl Client {
+ pub(crate) async fn keep_alive_loop(self: Arc<Self>, connection: CancellationToken) {
+ let mut last_success = Utc::now();
+ let mut error_count = 0;
+ loop {
+ let interval = rand::rng().random_range(
+ KEEP_ALIVE_INTERVAL_MIN.as_millis()..KEEP_ALIVE_INTERVAL_MAX.as_millis(),
+ );
+ let interval = Duration::from_millis(u64::try_from(interval).unwrap_or(u64::MAX));
+ tokio::select! {
+ () = tokio::time::sleep(interval) => {}
+ () = connection.cancelled() => return,
+ }
+ let (is_success, should_continue) = self.send_keep_alive(&connection).await;
+ if !should_continue {
+ return;
+ } else if !is_success {
+ error_count += 1;
+ self.spawn_dispatch(Event::KeepAliveTimeout(KeepAliveTimeout {
+ error_count,
+ last_success,
+ }));
+ let since_success = (Utc::now() - last_success).to_std().unwrap_or_default();
+ if self.config.enable_auto_reconnect && since_success > KEEP_ALIVE_MAX_FAIL_TIME {
+ tracing::debug!("forcing reconnect due to keepalive failure");
+ self.disconnect().await;
+ self.reset_expected_disconnect();
+ let client = Arc::clone(&self);
+ self.spawn(async move { client.auto_reconnect().await });
+ }
+ } else {
+ if error_count > 0 {
+ error_count = 0;
+ self.spawn_dispatch(Event::KeepAliveRestored(KeepAliveRestored));
+ }
+ last_success = Utc::now();
+ }
+ }
+ }
+
+ /// Sends one ping; returns (is success, should continue).
+ async fn send_keep_alive(&self, connection: &CancellationToken) -> (bool, bool) {
+ let response = self
+ .send_iq_async(InfoQuery {
+ namespace: "w:p",
+ r#type: IqType::Get,
+ to: SERVER_JID.clone(),
+ ..Default::default()
+ })
+ .await;
+ if connection.is_cancelled() {
+ return (false, false);
+ }
+ let response = match response {
+ Ok(response) => response,
+ Err(error) => {
+ tracing::warn!(error = %error, "failed to send keepalive");
+ return (false, true);
+ }
+ };
+ tokio::select! {
+ _ = response => (true, true),
+ () = tokio::time::sleep(KEEP_ALIVE_RESPONSE_DEADLINE) => {
+ tracing::warn!("keepalive timed out");
+ (false, true)
+ }
+ () = connection.cancelled() => (false, false),
+ }
+ }
+}
diff --git a/crates/whatsmeow/src/lib.rs b/crates/whatsmeow/src/lib.rs
new file mode 100644
index 0000000000..e5ff7d85d1
--- /dev/null
+++ b/crates/whatsmeow/src/lib.rs
@@ -0,0 +1,59 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+//! A Rust port of [whatsmeow](https://github.com/tulir/whatsmeow), the Go
+//! library for the WhatsApp web multidevice API.
+//!
+//! Each module mirrors the Go package of the same name, and each file in it
+//! the Go file of the same name. Top-level Go files (`client.go`,
+//! `send.go`, …) are top-level modules whose `impl Client` blocks add the
+//! methods Go defines on `*Client`. [`signal`] is the exception: it is the
+//! boundary implemented by the separate `whatsmeow_signal` crate.
+#![deny(missing_docs)]
+
+pub mod appstate;
+pub mod binary;
+pub mod client;
+mod connectionevents;
+mod cstoken;
+pub mod download;
+pub mod download_to_file;
+pub mod errors;
+pub mod group;
+pub mod handshake;
+mod keepalive;
+pub mod mediaconn;
+pub mod mediaretry;
+mod message;
+pub mod msgsecret;
+mod notification;
+pub mod pair;
+pub mod pair_code;
+pub mod pair_passkey;
+pub mod prekeys;
+pub mod presence;
+mod privacysettings;
+pub use whatsmeow_proto as proto;
+pub mod qrchan;
+pub mod receipt;
+pub mod request;
+mod retry;
+pub mod send;
+pub mod signal;
+pub mod socket;
+pub mod store;
+mod tctoken;
+#[cfg(any(test, feature = "testing"))]
+pub mod testing;
+pub mod types;
+pub mod upload;
+pub mod user;
+pub mod util;
+#[cfg(test)]
+mod vectors;
+
+pub use client::{Client, ClientConfig, Dialer, EventHandler, Signal, WebSocketDialer};
+pub use errors::ClientError;
+pub use qrchan::QrChannelItem;
+pub use types::events::Event;
diff --git a/crates/whatsmeow/src/mediaconn.rs b/crates/whatsmeow/src/mediaconn.rs
new file mode 100644
index 0000000000..9fd5f33cc9
--- /dev/null
+++ b/crates/whatsmeow/src/mediaconn.rs
@@ -0,0 +1,197 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+//
+// Ported from whatsmeow mediaconn.go (MPL-2.0, Copyright (c) Tulir Asokan)
+//
+// `Client.refreshMediaConn` is split into pure parts, tested alone: the cache
+// check ([`media_conn_needs_refresh`]), the request ([`build_media_conn_iq`])
+// and the response parsing ([`parse_media_conn`]).
+
+//! The media hosts and upload auth token WhatsApp hands out over an IQ.
+
+use chrono::{DateTime, TimeDelta, Utc};
+
+use crate::binary::{ErrorList, Node, NodeContent};
+use crate::client::Client;
+use crate::errors::ClientError;
+use crate::request::{InfoQuery, IqType};
+use crate::types::SERVER_JID;
+
+/// The namespace of the media connection IQ.
+pub const MEDIA_CONN_NAMESPACE: &str = "w:m";
+/// The type of the media connection IQ.
+pub const MEDIA_CONN_IQ_TYPE: &str = "set";
+
+/// A single host to download media from.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct MediaConnHost {
+ /// The host name, used as the URL host.
+ pub hostname: String,
+}
+
+/// The WhatsApp servers attachments can be uploaded to and downloaded from.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct MediaConn {
+ /// The upload auth token.
+ pub auth: String,
+ /// How long `auth` is valid, in seconds.
+ pub auth_ttl: i64,
+ /// How long this media connection is valid, in seconds.
+ pub ttl: i64,
+ /// The `max_buckets` attribute.
+ pub max_buckets: i64,
+ /// When the media connection was fetched.
+ pub fetched_at: DateTime<Utc>,
+ /// The hosts, in the order to try them.
+ pub hosts: Vec<MediaConnHost>,
+}
+
+impl MediaConn {
+ /// When the media connection expires.
+ pub fn expiry(&self) -> DateTime<Utc> {
+ self.fetched_at + TimeDelta::seconds(self.ttl)
+ }
+}
+
+/// An unexpected media connection IQ response.
+#[derive(Debug, thiserror::Error, PartialEq, Eq)]
+pub enum MediaConnError {
+ /// The response's first child isn't `<media_conn>`.
+ #[error("failed to query media connections: unexpected child tag")]
+ UnexpectedChildTag,
+ /// The `<media_conn>` attributes didn't parse.
+ #[error("failed to parse media connections: {0}")]
+ InvalidAttributes(ErrorList),
+ /// A `<host>` had no `hostname`. Go prints the (empty) `<media_conn>`
+ /// errors here; the port prints the host's.
+ #[error("failed to parse media connection host: {0}")]
+ InvalidHost(ErrorList),
+}
+
+/// Whether the cached media connection must be fetched again: there is none,
+/// a refresh is forced, or it has expired at `now`. This is the condition in
+/// Go's `Client.refreshMediaConn`, which then queries and caches a new one.
+pub fn media_conn_needs_refresh(
+ cache: Option<&MediaConn>,
+ force: bool,
+ now: DateTime<Utc>,
+) -> bool {
+ match cache {
+ None => true,
+ Some(media_conn) => force || now > media_conn.expiry(),
+ }
+}
+
+/// The content of the media connection IQ: one empty `<media_conn>`.
+pub fn media_conn_query_content() -> Vec<Node> {
+ vec![Node {
+ tag: "media_conn".to_owned(),
+ ..Node::default()
+ }]
+}
+
+/// The whole IQ `Client.queryMediaConn` sends, as Go's `sendIQ` builds it from
+/// the info query: `<iq id=… xmlns="w:m" type="set" to="s.whatsapp.net">`
+/// around [`media_conn_query_content`].
+pub fn build_media_conn_iq(id: &str) -> Node {
+ let mut node = Node {
+ tag: "iq".to_owned(),
+ content: Some(NodeContent::Nodes(media_conn_query_content())),
+ ..Node::default()
+ };
+ node.attrs.insert("id".to_owned(), id.into());
+ node.attrs
+ .insert("xmlns".to_owned(), MEDIA_CONN_NAMESPACE.into());
+ node.attrs
+ .insert("type".to_owned(), MEDIA_CONN_IQ_TYPE.into());
+ node.attrs.insert("to".to_owned(), (&*SERVER_JID).into());
+ node
+}
+
+/// Parses the media connection IQ response, stamping it as fetched now.
+/// Children of `<media_conn>` other than `<host>` are logged and skipped.
+pub fn parse_media_conn(resp: &Node) -> Result<MediaConn, MediaConnError> {
+ let resp_mc = match resp.get_children().first() {
+ Some(child) if child.tag == "media_conn" => child,
+ _ => return Err(MediaConnError::UnexpectedChildTag),
+ };
+ let fetched_at = Utc::now();
+ let mut ag = resp_mc.attr_getter();
+ let auth = ag.string("auth");
+ let ttl = ag.int("ttl");
+ let auth_ttl = ag.int("auth_ttl");
+ let max_buckets = ag.int("max_buckets");
+ ag.error().map_err(MediaConnError::InvalidAttributes)?;
+ let mut hosts = Vec::new();
+ for child in resp_mc.get_children() {
+ if child.tag != "host" {
+ tracing::warn!(node = %child, "unexpected child in media_conn element");
+ continue;
+ }
+ let mut cag = child.attr_getter();
+ hosts.push(MediaConnHost {
+ hostname: cag.string("hostname"),
+ });
+ cag.error().map_err(MediaConnError::InvalidHost)?;
+ }
+ Ok(MediaConn {
+ auth,
+ auth_ttl,
+ ttl,
+ max_buckets,
+ fetched_at,
+ hosts,
+ })
+}
+
+impl Client {
+ /// The cached media connection, fetched again when missing, expired or
+ /// `force`d (`refreshMediaConn`).
+ pub(crate) async fn refresh_media_conn(&self, force: bool) -> Result<MediaConn, ClientError> {
+ let mut cache = self.media_conn_cache.lock().await;
+ if media_conn_needs_refresh(cache.as_ref(), force, Utc::now()) {
+ *cache = Some(self.query_media_conn().await?);
+ }
+ cache
+ .clone()
+ .ok_or_else(|| ClientError::Other("media connection cache is empty".to_owned()))
+ }
+
+ async fn query_media_conn(&self) -> Result<MediaConn, ClientError> {
+ let response = self
+ .send_iq(InfoQuery {
+ namespace: MEDIA_CONN_NAMESPACE,
+ r#type: IqType::Set,
+ to: SERVER_JID.clone(),
+ content: Some(NodeContent::Nodes(media_conn_query_content())),
+ ..Default::default()
+ })
+ .await
+ .map_err(|error| error.wrap("failed to query media connections"))?;
+ Ok(parse_media_conn(&response)?)
+ }
+
+ /// The media connection for a download or upload, with Go's error context.
+ pub(crate) async fn media_conn_for_transfer(&self) -> Result<MediaConn, ClientError> {
+ self.refresh_media_conn(false)
+ .await
+ .map_err(|error| error.wrap("failed to refresh media connections"))
+ }
+
+ /// The HTTP side of media transfers.
+ pub(crate) fn media_http(&self) -> crate::download::MediaHttpClient {
+ let http = crate::download::MediaHttpClient::new(
+ self.config.media_http.clone(),
+ String::new(),
+ false,
+ );
+ match &self.config.media_base_url {
+ Some(base_url) => http.with_base_url(base_url),
+ None => http,
+ }
+ }
+}
+
+#[cfg(test)]
+mod test;
diff --git a/crates/whatsmeow/src/mediaconn/test.rs b/crates/whatsmeow/src/mediaconn/test.rs
new file mode 100644
index 0000000000..b0e1286e5d
--- /dev/null
+++ b/crates/whatsmeow/src/mediaconn/test.rs
@@ -0,0 +1,131 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+//! Expected values come from `testdata/media/vectors.json`, written by
+//! `testdata/generator/media` running whatsmeow's Go code.
+
+use chrono::TimeZone;
+use serde_json::Value;
+
+use super::*;
+use crate::binary::{marshal, unmarshal};
+
+fn vectors() -> Value {
+ serde_json::from_str(include_str!("../../testdata/media/vectors.json")).unwrap()
+}
+
+fn hex_field(value: &Value) -> Vec<u8> {
+ hex::decode(value.as_str().unwrap()).unwrap()
+}
+
+#[test]
+fn parses_go_media_conn_response() {
+ let vector = &vectors()["media_conn"];
+ // Go's Marshal prepends the uncompressed flag byte.
+ let response = unmarshal(&hex_field(&vector["response"])[1..]).unwrap();
+
+ let before = Utc::now();
+ let media_conn = parse_media_conn(&response).unwrap();
+
+ assert_eq!(media_conn.auth, vector["auth"].as_str().unwrap());
+ assert_eq!(media_conn.ttl, vector["ttl"].as_i64().unwrap());
+ assert_eq!(media_conn.auth_ttl, vector["auth_ttl"].as_i64().unwrap());
+ assert_eq!(
+ media_conn.max_buckets,
+ vector["max_buckets"].as_i64().unwrap()
+ );
+ let hostnames: Vec<&str> = vector["hosts"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|host| host["hostname"].as_str().unwrap())
+ .collect();
+ assert_eq!(
+ media_conn
+ .hosts
+ .iter()
+ .map(|host| host.hostname.as_str())
+ .collect::<Vec<_>>(),
+ hostnames
+ );
+ assert!(media_conn.fetched_at >= before && media_conn.fetched_at <= Utc::now());
+}
+
+#[test]
+fn builds_go_media_conn_request() {
+ let vector = &vectors()["media_conn"];
+ // Go encodes attributes in map order, so compare the decoded node.
+ let request = unmarshal(&hex_field(&vector["request"])[1..]).unwrap();
+ assert_eq!(build_media_conn_iq("1234.5678-2"), request);
+ assert_eq!(
+ unmarshal(&marshal(&request).unwrap()[1..]).unwrap(),
+ request
+ );
+}
+
+#[test]
+fn rejects_unexpected_responses() {
+ let empty = Node {
+ tag: "iq".to_owned(),
+ ..Node::default()
+ };
+ assert_eq!(
+ parse_media_conn(&empty).unwrap_err().to_string(),
+ "failed to query media connections: unexpected child tag"
+ );
+
+ let mut response = build_media_conn_iq("1");
+ let error = parse_media_conn(&response).unwrap_err();
+ assert_eq!(
+ error.to_string(),
+ "failed to parse media connections: [didn't find required attribute 'auth' \
+ didn't find required attribute 'ttl' didn't find required attribute 'auth_ttl' \
+ didn't find required attribute 'max_buckets']"
+ );
+
+ let Some(NodeContent::Nodes(children)) = &mut response.content else {
+ unreachable!()
+ };
+ for (key, value) in [
+ ("auth", "a"),
+ ("ttl", "1"),
+ ("auth_ttl", "2"),
+ ("max_buckets", "3"),
+ ] {
+ children[0].attrs.insert(key.to_owned(), value.into());
+ }
+ children[0].content = Some(NodeContent::Nodes(vec![Node {
+ tag: "host".to_owned(),
+ ..Node::default()
+ }]));
+ assert_eq!(
+ parse_media_conn(&response).unwrap_err(),
+ MediaConnError::InvalidHost(ErrorList(vec![crate::binary::AttrError::Missing(
+ "hostname".to_owned()
+ )]))
+ );
+}
+
+#[test]
+fn expiry_and_refresh() {
+ let media_conn = MediaConn {
+ auth: String::new(),
+ auth_ttl: 0,
+ ttl: 300,
+ max_buckets: 0,
+ fetched_at: Utc.with_ymd_and_hms(2026, 1, 1, 0, 0, 0).unwrap(),
+ hosts: Vec::new(),
+ };
+ let expiry = Utc.with_ymd_and_hms(2026, 1, 1, 0, 5, 0).unwrap();
+ assert_eq!(media_conn.expiry(), expiry);
+
+ assert!(media_conn_needs_refresh(None, false, expiry));
+ assert!(!media_conn_needs_refresh(Some(&media_conn), false, expiry));
+ assert!(media_conn_needs_refresh(Some(&media_conn), true, expiry));
+ assert!(media_conn_needs_refresh(
+ Some(&media_conn),
+ false,
+ expiry + TimeDelta::nanoseconds(1)
+ ));
+}
diff --git a/crates/whatsmeow/src/mediaretry.rs b/crates/whatsmeow/src/mediaretry.rs
new file mode 100644
index 0000000000..f55f140386
--- /dev/null
+++ b/crates/whatsmeow/src/mediaretry.rs
@@ -0,0 +1,192 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+//
+// Ported from whatsmeow mediaretry.go (MPL-2.0, Copyright (c) Tulir Asokan)
+//
+// `encryptMediaRetryReceipt` takes its IV as a parameter
+// ([`encrypt_media_retry_receipt_with`]) so tests can compare with Go.
+
+//! Asking the sender's phone to re-upload media that is gone from the
+//! server (404/410 on download).
+
+use prost::Message;
+
+use crate::binary::{Attrs, Node, NodeContent};
+use crate::client::Client;
+use crate::errors::{ClientError, element_missing};
+use crate::proto::wa_mms_retry::{MediaRetryNotification, ServerErrorReceipt};
+use crate::types::MessageInfo;
+use crate::types::events::{Event, MediaRetry, MediaRetryError};
+use crate::util::gcmutil;
+use crate::util::hkdfutil;
+
+/// The key that encrypts media retry receipts and notifications.
+pub fn get_media_retry_key(media_key: &[u8]) -> Vec<u8> {
+ hkdfutil::sha256(media_key, &[], b"WhatsApp Media Retry Notification", 32)
+}
+
+/// The encrypted `ServerErrorReceipt` for a message, with the given IV.
+pub fn encrypt_media_retry_receipt_with(
+ message_id: &str,
+ media_key: &[u8],
+ iv: &[u8; 12],
+) -> Result<Vec<u8>, ClientError> {
+ let plaintext = ServerErrorReceipt {
+ stanza_id: Some(message_id.to_owned()),
+ }
+ .encode_to_vec();
+ gcmutil::encrypt(
+ &get_media_retry_key(media_key),
+ iv,
+ &plaintext,
+ message_id.as_bytes(),
+ )
+ .map_err(|error| ClientError::Other(format!("failed to encrypt retry receipt: {error}")))
+}
+
+/// Decrypts a media retry answer with the media key
+/// (`DecryptMediaRetryNotification`). On success the notification holds the
+/// new direct path.
+pub fn decrypt_media_retry_notification(
+ event: &MediaRetry,
+ media_key: &[u8],
+) -> Result<MediaRetryNotification, ClientError> {
+ if let Some(error) = event.error
+ && event.ciphertext.is_empty()
+ {
+ if error.code == 2 {
+ return Err(ClientError::MediaNotAvailableOnPhone);
+ }
+ return Err(ClientError::Other(format!(
+ "{} (code: {})",
+ ClientError::UnknownMediaRetryError,
+ error.code
+ )));
+ }
+ let plaintext = gcmutil::decrypt(
+ &get_media_retry_key(media_key),
+ &event.iv,
+ &event.ciphertext,
+ event.message_id.as_bytes(),
+ )
+ .map_err(|error| ClientError::Other(format!("failed to decrypt notification: {error}")))?;
+ MediaRetryNotification::decode(plaintext.as_slice()).map_err(|error| {
+ ClientError::Other(format!(
+ "failed to unmarshal notification (invalid encryption key?): {error}"
+ ))
+ })
+}
+
+fn child_bytes(node: &Node, tags: &[&str]) -> Option<Vec<u8>> {
+ match &node.get_optional_child_by_tag(tags)?.content {
+ Some(NodeContent::Bytes(bytes)) => Some(bytes.clone()),
+ _ => None,
+ }
+}
+
+/// Parses a `mediaretry` notification.
+pub fn parse_media_retry_notification(node: &Node) -> Result<MediaRetry, ClientError> {
+ let mut attrs = node.attr_getter();
+ let mut event = MediaRetry {
+ timestamp: attrs.unix_time("t"),
+ message_id: attrs.string("id"),
+ ..MediaRetry::default()
+ };
+ attrs.error()?;
+ let rmr = node
+ .get_optional_child_by_tag(&["rmr"])
+ .ok_or_else(|| element_missing("rmr", "retry notification"))?;
+ let mut rmr_attrs = rmr.attr_getter();
+ event.chat_id = rmr_attrs.jid("jid");
+ event.from_me = rmr_attrs.bool("from_me");
+ event.sender_id = rmr_attrs.optional_jid_or_empty("participant");
+ rmr_attrs
+ .error()
+ .map_err(|error| ClientError::Other(format!("missing attributes in <rmr> tag: {error}")))?;
+ if let Some(error_node) = node.get_optional_child_by_tag(&["error"]) {
+ event.error = Some(MediaRetryError {
+ code: error_node.attr_getter().int("code"),
+ });
+ return Ok(event);
+ }
+ event.ciphertext = child_bytes(node, &["encrypt", "enc_p"])
+ .ok_or_else(|| element_missing("enc_p", "retry notification"))?;
+ event.iv = child_bytes(node, &["encrypt", "enc_iv"])
+ .ok_or_else(|| element_missing("enc_iv", "retry notification"))?;
+ Ok(event)
+}
+
+fn bytes_node(tag: &str, content: Vec<u8>) -> Node {
+ Node {
+ tag: tag.to_owned(),
+ attrs: Attrs::new(),
+ content: Some(NodeContent::Bytes(content)),
+ }
+}
+
+impl Client {
+ /// Asks the phone to re-upload the media of a message
+ /// (`SendMediaRetryReceipt`); the answer arrives as [`Event::MediaRetry`].
+ /// Use it when a download fails with 404 or 410.
+ #[tracing::instrument(name = "whatsmeow.media_retry.send", skip_all, err)]
+ pub async fn send_media_retry_receipt(
+ &self,
+ message: &MessageInfo,
+ media_key: &[u8],
+ ) -> Result<(), ClientError> {
+ let iv: [u8; 12] = rand::random();
+ let ciphertext = encrypt_media_retry_receipt_with(&message.id, media_key, &iv)
+ .map_err(|error| error.wrap("failed to prepare encrypted retry receipt"))?;
+ let own_id = self.get_own_id().await.to_non_ad();
+ if own_id.is_empty() {
+ return Err(ClientError::NotLoggedIn);
+ }
+ let mut rmr_attrs = Attrs::from([
+ ("jid".to_owned(), message.chat.clone().into()),
+ ("from_me".to_owned(), message.is_from_me.into()),
+ ]);
+ if message.is_group {
+ rmr_attrs.insert("participant".to_owned(), message.sender.clone().into());
+ }
+ self.send_node(&Node {
+ tag: "receipt".to_owned(),
+ attrs: Attrs::from([
+ ("id".to_owned(), message.id.clone().into()),
+ ("to".to_owned(), own_id.into()),
+ ("type".to_owned(), "server-error".into()),
+ ]),
+ content: Some(NodeContent::Nodes(vec![
+ Node {
+ tag: "encrypt".to_owned(),
+ attrs: Attrs::new(),
+ content: Some(NodeContent::Nodes(vec![
+ bytes_node("enc_p", ciphertext),
+ bytes_node("enc_iv", iv.to_vec()),
+ ])),
+ },
+ Node {
+ tag: "rmr".to_owned(),
+ attrs: rmr_attrs,
+ content: None,
+ },
+ ])),
+ })
+ .await
+ }
+
+ pub(crate) async fn handle_media_retry_notification(&self, node: &Node) {
+ match parse_media_retry_notification(node) {
+ Err(error) => {
+ tracing::warn!(error = %error, "failed to parse media retry notification")
+ }
+ Ok(event) => {
+ self.dispatch_event(Event::MediaRetry(Box::new(event)))
+ .await;
+ }
+ }
+ }
+}
+
+#[cfg(test)]
+mod test;
diff --git a/crates/whatsmeow/src/mediaretry/test.rs b/crates/whatsmeow/src/mediaretry/test.rs
new file mode 100644
index 0000000000..ad3377695c
--- /dev/null
+++ b/crates/whatsmeow/src/mediaretry/test.rs
@@ -0,0 +1,132 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+//! Media retry receipts and notifications against whatsmeow's output.
+
+use super::*;
+use crate::client::test::{capture_request, connect_paired, harness, next_event};
+use crate::proto::wa_mms_retry::{ServerErrorReceipt, media_retry_notification::ResultType};
+use crate::types::parse_jid;
+use crate::vectors::Vectors;
+
+#[test]
+fn receipts_encrypt_and_notifications_parse_like_go() {
+ let vectors = Vectors::load("pairing_media.json");
+ let media_key = vectors.bytes("media_key");
+ let iv: [u8; 12] = vectors.bytes("media_retry_receipt_iv").try_into().unwrap();
+ assert_eq!(
+ encrypt_media_retry_receipt_with("MSGID1", &media_key, &iv).unwrap(),
+ vectors.bytes("media_retry_receipt_ciphertext")
+ );
+ let event = parse_media_retry_notification(&vectors.node("media_retry_notification")).unwrap();
+ assert_eq!(
+ event.chat_id.to_string(),
+ vectors.string("media_retry_chat")
+ );
+ assert_eq!(
+ event.sender_id.to_string(),
+ vectors.string("media_retry_sender")
+ );
+ assert_eq!(event.message_id, "MSGID1");
+ // The notification carries the receipt ciphertext; it decrypts as a
+ // ServerErrorReceipt, proving key and AD match.
+ let plaintext = gcmutil::decrypt(
+ &get_media_retry_key(&media_key),
+ &event.iv,
+ &event.ciphertext,
+ b"MSGID1",
+ )
+ .unwrap();
+ assert_eq!(
+ ServerErrorReceipt::decode(plaintext.as_slice())
+ .unwrap()
+ .stanza_id
+ .as_deref(),
+ Some("MSGID1")
+ );
+ let error = MediaRetry {
+ message_id: "MSGID1".to_owned(),
+ error: Some(MediaRetryError { code: 2 }),
+ ..MediaRetry::default()
+ };
+ assert_eq!(
+ decrypt_media_retry_notification(&error, &media_key)
+ .unwrap_err()
+ .to_string(),
+ vectors.string("media_retry_error_2")
+ );
+}
+
+#[test]
+fn a_successful_retry_notification_decrypts_to_the_new_path() {
+ let media_key = [5; 32];
+ let notification = MediaRetryNotification {
+ stanza_id: Some("M2".to_owned()),
+ direct_path: Some("/v/new".to_owned()),
+ result: Some(ResultType::Success as i32),
+ ..Default::default()
+ };
+ let iv = [6; 12];
+ let ciphertext = gcmutil::encrypt(
+ &get_media_retry_key(&media_key),
+ &iv,
+ &notification.encode_to_vec(),
+ b"M2",
+ )
+ .unwrap();
+ let event = MediaRetry {
+ ciphertext,
+ iv: iv.to_vec(),
+ message_id: "M2".to_owned(),
+ ..MediaRetry::default()
+ };
+ assert_eq!(
+ decrypt_media_retry_notification(&event, &media_key)
+ .unwrap()
+ .direct_path
+ .as_deref(),
+ Some("/v/new")
+ );
+}
+
+#[tokio::test(start_paused = true)]
+async fn the_retry_receipt_and_notification_match_go() {
+ let vectors = Vectors::load("pairing_media.json");
+ let mut harness = harness(Some(("1234:[email protected]", "9876:5@lid")));
+ let mut connection = connect_paired(&mut harness).await;
+ let info = MessageInfo {
+ source: crate::types::MessageSource {
+ chat: parse_jid("[email protected]").unwrap(),
+ sender: parse_jid("777@lid").unwrap(),
+ is_group: true,
+ ..Default::default()
+ },
+ id: "MSGID1".to_owned(),
+ ..Default::default()
+ };
+ let client = std::sync::Arc::clone(&harness.client);
+ let media_key = vectors.bytes("media_key");
+ let mut sent = capture_request(&mut connection, async move {
+ client.send_media_retry_receipt(&info, &media_key).await
+ })
+ .await;
+ let mut expected = vectors.node("media_retry_send");
+ // The IV is random on both sides.
+ for node in [&mut sent, &mut expected] {
+ if let Some(NodeContent::Nodes(children)) = &mut node.content {
+ children[0].content = None;
+ }
+ }
+ assert_eq!(sent, expected);
+
+ connection
+ .send_node(&vectors.node("media_retry_notification"))
+ .await;
+ loop {
+ if let Event::MediaRetry(retry) = next_event(&mut harness.events).await {
+ assert_eq!(retry.message_id, "MSGID1");
+ break;
+ }
+ }
+}
diff --git a/crates/whatsmeow/src/message.rs b/crates/whatsmeow/src/message.rs
new file mode 100644
index 0000000000..dde3f3d9d7
--- /dev/null
+++ b/crates/whatsmeow/src/message.rs
@@ -0,0 +1,1497 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+//
+// Ported from whatsmeow message.go (MPL-2.0, Copyright (c) Tulir Asokan)
+//
+// Deviations:
+// - libsignal calls go through `crate::signal::SignalProtocol` with the
+// device as its store; Go's `sessionlessSignalStore` is
+// [`SessionlessSignalStore`].
+// - Go recovers from panics in `decryptMessages` and acks; Rust handlers
+// don't panic (a panicking task is logged by the runtime).
+// - Not ported: bot (`msmsg`) and Armadillo (`v="3"`) messages, newsletter
+// plaintext messages, `SendHistorySyncServerErrorReceipt` (media retry
+// isn't ported). They are acked and logged.
+
+//! Receiving messages: parsing, decrypting and dispatching them, and the
+//! protocol messages (history sync, sender keys, app state keys) inside.
+
+use std::io::Read;
+use std::sync::Arc;
+use std::sync::atomic::Ordering;
+
+use async_trait::async_trait;
+use chrono::{DateTime, Utc};
+use prost::Message as _;
+use sha2::{Digest, Sha256};
+
+use crate::binary::{Node, NodeContent};
+use crate::client::Client;
+use crate::download::MediaType;
+use crate::errors::ClientError;
+use crate::proto::wa_e2e::{self, PeerDataOperationRequestType};
+use crate::proto::wa_history_sync::{self, history_sync::HistorySyncType};
+use crate::proto::wa_lid_migration_sync_payload::LidMigrationMappingSyncPayload;
+use crate::proto::wa_web::WebMessageInfo;
+use crate::receipt::{NACK_INVALID_PROTOBUF, NACK_PARSING_ERROR, NACK_UNRECOGNIZED_STANZA};
+use crate::signal::{SenderKeyName, SignalAddress, SignalError, SignalProtocolStore};
+use crate::store::{LidMapping, MessageSecretInsert, PrivacyToken, StoreError};
+use crate::types::events::{
+ DecryptFailMode, Event, HistorySync, IdentityChange, Message, UnavailableType,
+ UndecryptableMessage,
+};
+use crate::types::{
+ AddressingMode, BROADCAST_SERVER, BotEditType, BroadcastRecipient, DEFAULT_USER_SERVER,
+ EditAttribute, GROUP_SERVER, HIDDEN_USER_SERVER, HOSTED_LID_SERVER, HOSTED_SERVER, Jid,
+ LEGACY_USER_SERVER, MessageInfo, MessageSource, MsgBotInfo, MsgMetaInfo, NEWSLETTER_SERVER,
+ ReceiptType, parse_jid,
+};
+use crate::user::parse_verified_name_content;
+
+/// Why decrypting one `<enc>` failed.
+#[derive(Debug, thiserror::Error)]
+pub(crate) enum DecryptError {
+ /// The decrypted event buffer already handled this ciphertext
+ /// (`ErrEventAlreadyProcessed`).
+ #[error("event was already processed at {0}")]
+ AlreadyProcessed(DateTime<Utc>),
+ /// libsignal failed.
+ #[error("{context}: {source}")]
+ Signal {
+ /// What was being decrypted.
+ context: &'static str,
+ /// The failure.
+ source: SignalError,
+ },
+ /// The store failed.
+ #[error("{context}: {source}")]
+ Store {
+ /// What failed.
+ context: &'static str,
+ /// The failure.
+ source: StoreError,
+ },
+ /// Anything else.
+ #[error("{0}")]
+ Other(String),
+}
+
+impl DecryptError {
+ fn signal(&self) -> Option<&SignalError> {
+ match self {
+ DecryptError::Signal { source, .. } => Some(source),
+ _ => None,
+ }
+ }
+}
+
+/// The device's Signal store, but sessions from stateless prekey messages
+/// aren't stored (`sessionlessSignalStore`).
+struct SessionlessSignalStore<'store>(&'store dyn SignalProtocolStore);
+
+#[async_trait]
+impl SignalProtocolStore for SessionlessSignalStore<'_> {
+ fn get_identity_key_pair(&self) -> ([u8; 32], [u8; 32]) {
+ self.0.get_identity_key_pair()
+ }
+ fn get_local_registration_id(&self) -> u32 {
+ self.0.get_local_registration_id()
+ }
+ async fn save_identity(
+ &self,
+ address: &SignalAddress,
+ key: [u8; 32],
+ ) -> Result<(), StoreError> {
+ self.0.save_identity(address, key).await
+ }
+ async fn is_trusted_identity(
+ &self,
+ address: &SignalAddress,
+ key: [u8; 32],
+ ) -> Result<bool, StoreError> {
+ self.0.is_trusted_identity(address, key).await
+ }
+ async fn load_pre_key(&self, id: u32) -> Result<Option<([u8; 32], [u8; 32])>, StoreError> {
+ self.0.load_pre_key(id).await
+ }
+ async fn remove_pre_key(&self, id: u32) -> Result<(), StoreError> {
+ self.0.remove_pre_key(id).await
+ }
+ async fn load_session(&self, address: &SignalAddress) -> Result<Option<Vec<u8>>, StoreError> {
+ self.0.load_session(address).await
+ }
+ async fn store_session(&self, _: &SignalAddress, _: Vec<u8>) -> Result<(), StoreError> {
+ Ok(())
+ }
+ async fn contains_session(&self, address: &SignalAddress) -> Result<bool, StoreError> {
+ self.0.contains_session(address).await
+ }
+ fn load_signed_pre_key(&self, id: u32) -> Option<([u8; 32], [u8; 32], [u8; 64])> {
+ self.0.load_signed_pre_key(id)
+ }
+ async fn store_sender_key(
+ &self,
+ name: &SenderKeyName,
+ record: Vec<u8>,
+ ) -> Result<(), StoreError> {
+ self.0.store_sender_key(name, record).await
+ }
+ async fn load_sender_key(&self, name: &SenderKeyName) -> Result<Option<Vec<u8>>, StoreError> {
+ self.0.load_sender_key(name).await
+ }
+}
+
+fn bytes_of(node: &Node) -> Option<&[u8]> {
+ match &node.content {
+ Some(NodeContent::Bytes(bytes)) => Some(bytes),
+ _ => None,
+ }
+}
+
+impl Client {
+ pub(crate) async fn handle_encrypted_message(self: &Arc<Self>, node: &Node) {
+ let mut info = match self.parse_message_info(node).await {
+ Ok(info) => info,
+ Err(error) => {
+ tracing::warn!(error = %error, "failed to parse message");
+ self.send_ack(node, NACK_PARSING_ERROR).await;
+ return;
+ }
+ };
+ if !info.sender_alt.is_empty() {
+ self.store_lid_pn_mapping(&info.sender_alt, &info.sender)
+ .await;
+ } else if !info.recipient_alt.is_empty() {
+ self.store_lid_pn_mapping(&info.recipient_alt, &info.chat)
+ .await;
+ }
+ if let Some(name) = info
+ .verified_name
+ .as_ref()
+ .and_then(|verified| verified.details.as_ref())
+ .and_then(|details| details.verified_name.clone())
+ .filter(|name| !name.is_empty())
+ {
+ let client = Arc::clone(self);
+ let info = info.clone();
+ self.spawn(async move {
+ client
+ .update_business_name(&info.sender, &info.sender_alt, Some(&info), &name)
+ .await;
+ });
+ }
+ if !info.push_name.is_empty() && info.push_name != "-" {
+ let client = Arc::clone(self);
+ let info = info.clone();
+ self.spawn(async move {
+ client
+ .update_push_name(&info.sender, &info.sender_alt, &info, &info.push_name)
+ .await;
+ });
+ }
+ if info.sender.server == NEWSLETTER_SERVER {
+ tracing::debug!("newsletters aren't ported, acking newsletter message");
+ self.send_ack(node, 0).await;
+ } else {
+ self.decrypt_messages(&mut info, node).await;
+ }
+ }
+
+ pub(crate) async fn handle_unencrypted_message(self: &Arc<Self>, node: &Node) {
+ match self.parse_message_info(node).await {
+ Err(error) => {
+ tracing::warn!(error = %error, "failed to parse message");
+ self.send_ack(node, NACK_PARSING_ERROR).await;
+ }
+ // Newsletter statuses aren't ported; everything else is acked
+ // as Go does.
+ Ok(_) => self.send_ack(node, 0).await,
+ }
+ }
+
+ /// Who sent a message or receipt and in which chat.
+ pub(crate) async fn parse_message_source(
+ &self,
+ node: &Node,
+ require_participant: bool,
+ ) -> Result<MessageSource, ClientError> {
+ let client_id = self.get_own_id().await;
+ let client_lid = self.get_own_lid().await;
+ if client_id.is_empty() {
+ return Err(ClientError::NotLoggedIn);
+ }
+ let mut source = MessageSource::default();
+ let mut attrs = node.attr_getter();
+ let mut from = attrs.jid("from");
+ source.addressing_mode = AddressingMode::from(attrs.optional_string("addressing_mode"));
+ if from.server == GROUP_SERVER || from.server == BROADCAST_SERVER {
+ source.is_group = true;
+ source.chat = from.clone();
+ source.sender = if require_participant {
+ attrs.jid("participant")
+ } else {
+ attrs.optional_jid_or_empty("participant")
+ };
+ source.sender_alt = attrs.optional_jid_or_empty("participant_pn");
+ if source.sender_alt.is_empty() && source.addressing_mode != AddressingMode::Lid {
+ source.sender_alt = attrs.optional_jid_or_empty("participant_lid");
+ }
+ if source.sender.user == client_id.user || source.sender.user == client_lid.user {
+ source.is_from_me = true;
+ }
+ if from.server == BROADCAST_SERVER {
+ source.broadcast_list_owner = attrs.optional_jid_or_empty("recipient");
+ if let Some(participants) = node.get_optional_child_by_tag(&["participants"])
+ && source.is_from_me
+ {
+ for child in participants.get_children() {
+ if child.tag != "to" {
+ continue;
+ }
+ let mut child_attrs = child.attr_getter();
+ let main_jid = child_attrs.jid("jid");
+ let recipient = if main_jid.server == HIDDEN_USER_SERVER {
+ BroadcastRecipient {
+ lid: main_jid,
+ pn: child_attrs.optional_jid_or_empty("peer_recipient_pn"),
+ }
+ } else {
+ BroadcastRecipient {
+ lid: child_attrs.optional_jid_or_empty("peer_recipient_lid"),
+ pn: main_jid,
+ }
+ };
+ source.broadcast_recipients.push(recipient);
+ }
+ }
+ }
+ } else if from.server == NEWSLETTER_SERVER {
+ source.chat = from.clone();
+ source.sender = from;
+ } else if from.user == client_id.user || from.user == client_lid.user {
+ if from.server == HOSTED_SERVER {
+ from.server = DEFAULT_USER_SERVER.to_owned();
+ } else if from.server == HOSTED_LID_SERVER {
+ from.server = HIDDEN_USER_SERVER.to_owned();
+ }
+ source.is_from_me = true;
+ source.sender = from.clone();
+ source.chat = attrs
+ .optional_jid("recipient")
+ .unwrap_or_else(|| from.to_non_ad());
+ source.recipient_alt = if source.chat.server == HIDDEN_USER_SERVER
+ || source.chat.server == HOSTED_LID_SERVER
+ {
+ attrs.optional_jid_or_empty("peer_recipient_pn")
+ } else {
+ attrs.optional_jid_or_empty("peer_recipient_lid")
+ };
+ } else if from.is_bot() {
+ source.sender = from.clone();
+ let meta = node.get_child_by_tag(&["meta"]);
+ let mut meta_attrs = meta.attr_getter();
+ source.chat = match meta_attrs.optional_jid("target_chat_jid") {
+ Some(target_chat) => target_chat.to_non_ad(),
+ None => from,
+ };
+ meta_attrs.error()?;
+ } else {
+ if from.server == HOSTED_SERVER {
+ from.server = DEFAULT_USER_SERVER.to_owned();
+ } else if from.server == HOSTED_LID_SERVER {
+ from.server = HIDDEN_USER_SERVER.to_owned();
+ }
+ source.chat = from.to_non_ad();
+ source.sender = from;
+ source.sender_alt = if source.sender.server == HIDDEN_USER_SERVER
+ || source.chat.server == HOSTED_LID_SERVER
+ {
+ attrs.optional_jid_or_empty("sender_pn")
+ } else {
+ attrs.optional_jid_or_empty("sender_lid")
+ };
+ }
+ if !source.sender_alt.is_empty() && source.sender_alt.device == 0 {
+ source.sender_alt.device = source.sender.device;
+ }
+ attrs.error()?;
+ Ok(source)
+ }
+
+ /// The parsed `<message>` attributes and metadata children.
+ pub(crate) async fn parse_message_info(&self, node: &Node) -> Result<MessageInfo, ClientError> {
+ let mut info = MessageInfo {
+ source: self.parse_message_source(node, true).await?,
+ ..MessageInfo::default()
+ };
+ let mut attrs = node.attr_getter();
+ info.id = attrs.string("id");
+ info.server_id = attrs.optional_int("server_id");
+ info.timestamp = attrs.unix_time("t");
+ info.push_name = attrs.optional_string("notify");
+ info.category = attrs.optional_string("category");
+ info.r#type = attrs.optional_string("type");
+ info.edit = EditAttribute::from(attrs.optional_string("edit"));
+ attrs.error()?;
+
+ for child in node.get_children() {
+ match child.tag.as_str() {
+ "multicast" => info.multicast = true,
+ "verified_name" => match parse_verified_name_content(child) {
+ Ok(verified_name) => info.verified_name = verified_name,
+ Err(error) => {
+ tracing::warn!(error = %error, "failed to parse verified_name node")
+ }
+ },
+ "bot" => match parse_msg_bot_info(child) {
+ Ok(bot_info) => info.msg_bot_info = bot_info,
+ Err(error) => tracing::warn!(error = %error, "failed to parse <bot> node"),
+ },
+ "meta" => match parse_msg_meta_info(child) {
+ Ok(meta_info) => info.msg_meta_info = meta_info,
+ Err(error) => tracing::warn!(error = %error, "failed to parse <meta> node"),
+ },
+ "franking" | "trace" => {}
+ _ => {
+ if let Some(media_type) = child.attr_getter().get_string("mediatype", false) {
+ info.media_type = media_type;
+ }
+ }
+ }
+ }
+ Ok(info)
+ }
+
+ async fn migrate_session_store(&self, pn: &Jid, lid: &Jid) {
+ let sessions = Arc::clone(&self.store.read().await.sessions);
+ if let Err(error) = sessions.migrate_pn_to_lid(pn, lid).await {
+ tracing::error!(error = %error, "failed to migrate signal store from phone number to LID");
+ }
+ }
+
+ #[tracing::instrument(
+ name = "whatsmeow.receive_message",
+ skip_all,
+ fields(message_id = %info.id, is_group = info.is_group, enc_count)
+ )]
+ async fn decrypt_messages(self: &Arc<Self>, info: &mut MessageInfo, node: &Node) {
+ if let Some(unavailable) = node.get_optional_child_by_tag(&["unavailable"])
+ && node.get_children_by_tag("enc").next().is_none()
+ {
+ let unavailable_type = UnavailableType::from(unavailable.attr_getter().string("type"));
+ tracing::warn!(unavailable_type = %unavailable_type, "unavailable message");
+ let client = Arc::clone(self);
+ let ack_info = info.clone();
+ let ack_node = node.clone();
+ self.background_if_async_ack(async move {
+ client.immediate_request_message_from_phone(&ack_info).await;
+ client.send_ack(&ack_node, 0).await;
+ })
+ .await;
+ self.dispatch_event(Event::UndecryptableMessage(UndecryptableMessage {
+ info: info.clone(),
+ is_unavailable: true,
+ unavailable_type,
+ decrypt_fail_mode: DecryptFailMode::Show,
+ }))
+ .await;
+ return;
+ }
+
+ tracing::Span::current().record("enc_count", node.get_children_by_tag("enc").count());
+ let mut contains_direct_msg = false;
+ let mut sender_encryption_jid = info.sender.clone();
+ if info.sender.server == DEFAULT_USER_SERVER && !info.sender.is_bot() {
+ if info.sender_alt.server == HIDDEN_USER_SERVER {
+ sender_encryption_jid = info.sender_alt.clone();
+ self.migrate_session_store(&info.sender, &info.sender_alt)
+ .await;
+ } else {
+ let lids = Arc::clone(&self.store.read().await.lids);
+ match lids.get_lid_for_pn(&info.sender).await {
+ Err(error) => tracing::error!(error = %error, "failed to get LID for sender"),
+ Ok(Some(lid)) if !lid.is_empty() => {
+ self.migrate_session_store(&info.sender, &lid).await;
+ sender_encryption_jid = lid.clone();
+ info.sender_alt = lid;
+ }
+ Ok(_) => tracing::warn!("no LID found for sender"),
+ }
+ }
+ }
+ let mut recognized_stanza = false;
+ let mut protobuf_failed = false;
+ for child in node.get_children() {
+ if child.tag != "enc" {
+ continue;
+ }
+ recognized_stanza = true;
+ let mut attrs = child.attr_getter();
+ let Some(enc_type) = attrs.get_string("type", false) else {
+ continue;
+ };
+ let result = if enc_type == "pkmsg" || enc_type == "msg" {
+ contains_direct_msg = true;
+ self.decrypt_dm(
+ child,
+ &sender_encryption_jid,
+ enc_type == "pkmsg",
+ info.timestamp,
+ )
+ .await
+ } else if info.is_group && enc_type == "skmsg" {
+ self.decrypt_group_msg(child, &sender_encryption_jid, &info.chat, info.timestamp)
+ .await
+ } else {
+ tracing::warn!(enc_type = %enc_type, "unhandled encrypted message type");
+ continue;
+ };
+ let (decrypted, ciphertext_hash) = match result {
+ Err(DecryptError::AlreadyProcessed(_)) => {
+ tracing::debug!("ignoring already processed message");
+ continue;
+ }
+ Err(error) if matches!(error.signal(), Some(SignalError::OldCounter)) => {
+ tracing::warn!(error = %error, "ignoring message with old counter");
+ continue;
+ }
+ Err(error) => {
+ tracing::warn!(error = %error, enc_type = %enc_type, "error decrypting message");
+ let is_unavailable = enc_type == "skmsg"
+ && !contains_direct_msg
+ && matches!(error.signal(), Some(SignalError::NoSenderKeyForUser));
+ if self.config.synchronous_ack {
+ self.send_retry_receipt(node, info, is_unavailable).await;
+ self.send_ack(node, 0).await;
+ } else {
+ let client = Arc::clone(self);
+ let retry_node = node.clone();
+ let retry_info = info.clone();
+ self.spawn(async move {
+ client
+ .send_retry_receipt(&retry_node, &retry_info, is_unavailable)
+ .await;
+ client.send_ack(&retry_node, 0).await;
+ });
+ }
+ self.dispatch_event(Event::UndecryptableMessage(UndecryptableMessage {
+ info: info.clone(),
+ is_unavailable,
+ unavailable_type: UnavailableType::Unknown,
+ decrypt_fail_mode: DecryptFailMode::from(
+ attrs.optional_string("decrypt-fail"),
+ ),
+ }))
+ .await;
+ return;
+ }
+ Ok(decrypted) => decrypted,
+ };
+ let retry_count = attrs.optional_int("count");
+ self.cancel_delayed_request_from_phone(&info.id);
+
+ let handler_failed = match attrs.int("v") {
+ 2 => match wa_e2e::Message::decode(decrypted.as_slice()) {
+ Err(error) => {
+ tracing::warn!(error = %error, "error unmarshaling decrypted message");
+ protobuf_failed = true;
+ continue;
+ }
+ Ok(message) => {
+ protobuf_failed = false;
+ self.handle_decrypted_message(info, message, retry_count)
+ .await
+ }
+ },
+ 3 => {
+ tracing::warn!("armadillo (v3) messages aren't ported");
+ false
+ }
+ version => {
+ tracing::warn!(version, "unknown version in decrypted message");
+ false
+ }
+ };
+ if handler_failed {
+ tracing::warn!("handler for message failed");
+ return;
+ }
+ if let Some(ciphertext_hash) = ciphertext_hash {
+ let event_buffer = Arc::clone(&self.store.read().await.event_buffer);
+ if let Err(error) = event_buffer
+ .clear_buffered_event_plaintext(ciphertext_hash)
+ .await
+ {
+ tracing::error!(error = %error, "failed to clear buffered event plaintext");
+ }
+ self.maybe_delete_old_buffered_hashes(event_buffer).await;
+ }
+ }
+ let client = Arc::clone(self);
+ let receipt_info = info.clone();
+ let receipt_node = node.clone();
+ self.background_if_async_ack(async move {
+ if !recognized_stanza {
+ client
+ .send_ack(&receipt_node, NACK_UNRECOGNIZED_STANZA)
+ .await;
+ } else if protobuf_failed {
+ client.send_ack(&receipt_node, NACK_INVALID_PROTOBUF).await;
+ } else {
+ client
+ .send_message_receipt(&receipt_info, &receipt_node)
+ .await;
+ }
+ })
+ .await;
+ }
+
+ async fn maybe_delete_old_buffered_hashes(
+ &self,
+ event_buffer: Arc<dyn crate::store::EventBuffer>,
+ ) {
+ const CLEAR_INTERVAL: std::time::Duration = std::time::Duration::from_secs(12 * 60 * 60);
+ let mut last_clear = crate::client::lock(&self.last_decrypted_buffer_clear);
+ if last_clear.is_some_and(|last| last.elapsed() < CLEAR_INTERVAL) {
+ return;
+ }
+ *last_clear = Some(tokio::time::Instant::now());
+ drop(last_clear);
+ self.spawn(async move {
+ if let Err(error) = event_buffer.delete_old_buffered_hashes().await {
+ tracing::error!(error = %error, "failed to delete old buffered hashes");
+ }
+ });
+ }
+
+ /// Deletes a peer's identity and session after an untrusted identity
+ /// error, and emits an implicit [`Event::IdentityChange`].
+ async fn clear_untrusted_identity(self: &Arc<Self>, target: &Jid) -> Result<(), ClientError> {
+ let (identities, sessions) = {
+ let store = self.store.read().await;
+ (Arc::clone(&store.identities), Arc::clone(&store.sessions))
+ };
+ let address = target.signal_address().to_string();
+ identities
+ .delete_identity(&address)
+ .await
+ .map_err(|error| ClientError::from(error).wrap("failed to delete identity"))?;
+ sessions
+ .delete_session(&address)
+ .await
+ .map_err(|error| ClientError::from(error).wrap("failed to delete session"))?;
+ self.spawn_dispatch(Event::IdentityChange(IdentityChange {
+ jid: target.clone(),
+ timestamp: Some(Utc::now()),
+ implicit: true,
+ }));
+ Ok(())
+ }
+
+ /// Decrypts through the decrypted event buffer when it's enabled, so a
+ /// redelivered ciphertext isn't decrypted twice. Returns the plaintext
+ /// and the ciphertext hash (when buffering).
+ async fn buffered_decrypt<'call, Decrypt>(
+ &'call self,
+ ciphertext: &[u8],
+ server_timestamp: Option<DateTime<Utc>>,
+ decrypt: Decrypt,
+ extra_hash_data: &[&str],
+ ) -> Result<(Vec<u8>, Option<[u8; 32]>), DecryptError>
+ where
+ Decrypt: Future<Output = Result<Vec<u8>, DecryptError>> + Send + 'call,
+ {
+ if !self.config.enable_decrypted_event_buffer {
+ return decrypt.await.map(|plaintext| (plaintext, None));
+ }
+ let mut hasher = Sha256::new();
+ hasher.update(ciphertext);
+ for part in extra_hash_data {
+ hasher.update([0]);
+ hasher.update(part.as_bytes());
+ }
+ hasher.update([0, 0]);
+ let ciphertext_hash: [u8; 32] = hasher.finalize().into();
+ let event_buffer = Arc::clone(&self.store.read().await.event_buffer);
+ let buffered = event_buffer
+ .get_buffered_event(ciphertext_hash)
+ .await
+ .map_err(|source| DecryptError::Store {
+ context: "failed to get buffered event",
+ source,
+ })?;
+ if let Some(buffered) = buffered {
+ if buffered.plaintext.is_empty() {
+ tracing::debug!("returning event already processed error");
+ return Err(DecryptError::AlreadyProcessed(buffered.insert_time));
+ }
+ tracing::debug!("returning previously decrypted plaintext");
+ return Ok((buffered.plaintext, Some(ciphertext_hash)));
+ }
+ let plaintext = std::sync::Mutex::new(None);
+ let decrypt_error = std::sync::Mutex::new(None);
+ let transaction_event_buffer = Arc::clone(&event_buffer);
+ let body = async {
+ match decrypt.await {
+ Ok(decrypted) => {
+ transaction_event_buffer
+ .put_buffered_event(
+ ciphertext_hash,
+ decrypted.clone(),
+ server_timestamp.unwrap_or_default(),
+ )
+ .await?;
+ *crate::client::lock(&plaintext) = Some(decrypted);
+ Ok(())
+ }
+ Err(error) => {
+ *crate::client::lock(&decrypt_error) = Some(error);
+ Err(StoreError::InvalidArgument("decryption failed".to_owned()))
+ }
+ }
+ };
+ let result = event_buffer.do_decryption_txn(Box::pin(body)).await;
+ if let Some(error) = crate::client::lock(&decrypt_error).take() {
+ return Err(error);
+ }
+ result.map_err(|source| DecryptError::Store {
+ context: "failed to save decrypted event to buffer",
+ source,
+ })?;
+ let plaintext = crate::client::lock(&plaintext)
+ .take()
+ .ok_or_else(|| DecryptError::Other("decryption produced no plaintext".to_owned()))?;
+ tracing::debug!("successfully decrypted and saved event");
+ Ok((plaintext, Some(ciphertext_hash)))
+ }
+
+ async fn decrypt_dm(
+ self: &Arc<Self>,
+ child: &Node,
+ from: &Jid,
+ is_pre_key: bool,
+ server_timestamp: Option<DateTime<Utc>>,
+ ) -> Result<(Vec<u8>, Option<[u8; 32]>), DecryptError> {
+ let content = bytes_of(child)
+ .ok_or_else(|| DecryptError::Other("message content is not a byte slice".to_owned()))?;
+ let address = from.signal_address();
+ let stateless = is_pre_key && child.attr_getter().optional_string("state") == "false";
+ if stateless {
+ tracing::debug!("not storing session from stateless prekey message");
+ }
+ let (plaintext, ciphertext_hash) = if is_pre_key {
+ let decrypt = async {
+ let result = self
+ .decrypt_pre_key_once(&address, content, stateless)
+ .await;
+ match result {
+ Err(SignalError::UntrustedIdentity) if self.config.auto_trust_identity => {
+ tracing::warn!("untrusted identity while decrypting prekey message, clearing stored identity and retrying");
+ self.clear_untrusted_identity(from).await.map_err(|error| {
+ DecryptError::Other(format!("failed to clear untrusted identity: {error}"))
+ })?;
+ self.decrypt_pre_key_once(&address, content, stateless).await
+ }
+ other => other,
+ }
+ .map_err(|source| DecryptError::Signal {
+ context: "failed to decrypt prekey message",
+ source,
+ })
+ };
+ self.buffered_decrypt(
+ content,
+ server_timestamp,
+ decrypt,
+ &["prekey", &from.to_string()],
+ )
+ .await?
+ } else {
+ let decrypt = async {
+ let store = self.store.read().await;
+ let signal_store = store.signal_store(None);
+ self.signal
+ .decrypt_message(&signal_store, &address, content)
+ .await
+ .map_err(|source| DecryptError::Signal {
+ context: "failed to decrypt normal message",
+ source,
+ })
+ };
+ self.buffered_decrypt(
+ content,
+ server_timestamp,
+ decrypt,
+ &["normal", &from.to_string()],
+ )
+ .await?
+ };
+ let plaintext = unpad_message(plaintext, child.attr_getter().int("v"))
+ .map_err(|error| DecryptError::Other(format!("failed to unpad message: {error}")))?;
+ Ok((plaintext, ciphertext_hash))
+ }
+
+ async fn decrypt_pre_key_once(
+ &self,
+ address: &SignalAddress,
+ content: &[u8],
+ stateless: bool,
+ ) -> Result<Vec<u8>, SignalError> {
+ let store = self.store.read().await;
+ let signal_store = store.signal_store(None);
+ if stateless {
+ let sessionless = SessionlessSignalStore(&signal_store);
+ self.signal
+ .decrypt_pre_key_message(&sessionless, address, content)
+ .await
+ } else {
+ self.signal
+ .decrypt_pre_key_message(&signal_store, address, content)
+ .await
+ }
+ }
+
+ async fn decrypt_group_msg(
+ &self,
+ child: &Node,
+ from: &Jid,
+ chat: &Jid,
+ server_timestamp: Option<DateTime<Utc>>,
+ ) -> Result<(Vec<u8>, Option<[u8; 32]>), DecryptError> {
+ let content = bytes_of(child)
+ .ok_or_else(|| DecryptError::Other("message content is not a byte slice".to_owned()))?;
+ let sender_key_name = SenderKeyName {
+ group_id: chat.to_string(),
+ sender: from.signal_address(),
+ };
+ let decrypt = async {
+ let store = self.store.read().await;
+ let signal_store = store.signal_store(None);
+ self.signal
+ .group_decrypt(&signal_store, &sender_key_name, content)
+ .await
+ .map_err(|source| DecryptError::Signal {
+ context: "failed to decrypt group message",
+ source,
+ })
+ };
+ let (plaintext, ciphertext_hash) = self
+ .buffered_decrypt(
+ content,
+ server_timestamp,
+ decrypt,
+ &["senderkey", &chat.to_string(), &from.to_string()],
+ )
+ .await?;
+ let plaintext =
+ unpad_message(plaintext, child.attr_getter().int("v")).map_err(DecryptError::Other)?;
+ Ok((plaintext, ciphertext_hash))
+ }
+
+ async fn handle_sender_key_distribution_message(
+ &self,
+ chat: &Jid,
+ from: &Jid,
+ axolotl_skdm: &[u8],
+ ) {
+ let sender_key_name = SenderKeyName {
+ group_id: chat.to_string(),
+ sender: from.signal_address(),
+ };
+ let store = self.store.read().await;
+ let signal_store = store.signal_store(None);
+ match self
+ .signal
+ .process_sender_key_distribution_message(&signal_store, &sender_key_name, axolotl_skdm)
+ .await
+ {
+ Err(error) => {
+ tracing::error!(error = %error, "failed to process sender key distribution message")
+ }
+ Ok(()) => tracing::debug!("processed sender key distribution message"),
+ }
+ }
+
+ /// Boxed with an explicit `Send` bound: the loop restarts itself.
+ fn handle_history_sync_notification_loop(
+ self: Arc<Self>,
+ ) -> futures::future::BoxFuture<'static, ()> {
+ Box::pin(self.history_sync_notification_loop_inner())
+ }
+
+ async fn history_sync_notification_loop_inner(self: Arc<Self>) {
+ const IDLE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(60);
+ loop {
+ let notification = {
+ let mut receiver = self.history_sync_notifications_receiver.lock().await;
+ tokio::select! {
+ notification = receiver.recv() => notification,
+ () = tokio::time::sleep(IDLE_TIMEOUT) => None,
+ () = self.background.cancelled() => None,
+ }
+ };
+ let Some(notification) = notification else {
+ break;
+ };
+ match self.download_history_sync(&notification, false).await {
+ Err(error) => tracing::error!(error = %error, "failed to download history sync"),
+ Ok(blob) => {
+ self.dispatch_event(Event::HistorySync(Box::new(HistorySync {
+ data: blob,
+ notification: notification.clone(),
+ })))
+ .await;
+ if let Err(error) = self
+ .delete_media(
+ MediaType::History,
+ notification.direct_path.as_deref().unwrap_or_default(),
+ notification.file_enc_sha256.as_deref().unwrap_or_default(),
+ notification.enc_handle.as_deref().unwrap_or_default(),
+ )
+ .await
+ {
+ tracing::warn!(error = %error, "failed to delete history sync media from server");
+ }
+ }
+ }
+ }
+ self.history_sync_handler_started
+ .store(false, Ordering::SeqCst);
+ // Something may have been queued between the loop stopping and the
+ // flag being cleared; restart if so.
+ if !self
+ .history_sync_notifications_receiver
+ .lock()
+ .await
+ .is_empty()
+ && self
+ .history_sync_handler_started
+ .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
+ .is_ok()
+ {
+ tracing::warn!(
+ "new history sync notifications appeared after loop stopped, restarting loop"
+ );
+ let client = Arc::clone(&self);
+ self.spawn(client.handle_history_sync_notification_loop());
+ }
+ }
+
+ /// Downloads and decodes the history sync blob of a notification. Call
+ /// this yourself only with `manual_history_sync_download`; otherwise the
+ /// client does and emits [`Event::HistorySync`].
+ #[tracing::instrument(name = "whatsmeow.history_sync.download", skip_all, err)]
+ pub async fn download_history_sync(
+ self: &Arc<Self>,
+ notification: &wa_e2e::HistorySyncNotification,
+ synchronous_storage: bool,
+ ) -> Result<wa_history_sync::HistorySync, ClientError> {
+ let data = match &notification.initial_hist_bootstrap_inline_payload {
+ Some(inline) => inline.clone(),
+ None => self
+ .download(notification)
+ .await
+ .map_err(|error| error.wrap("failed to download"))?,
+ };
+ let mut raw_data = Vec::new();
+ flate2::read::ZlibDecoder::new(data.as_slice())
+ .read_to_end(&mut raw_data)
+ .map_err(|error| ClientError::Other(format!("failed to decompress: {error}")))?;
+ let history_sync = wa_history_sync::HistorySync::decode(raw_data.as_slice())
+ .map_err(|error| ClientError::Other(format!("failed to unmarshal: {error}")))?;
+ tracing::debug!(
+ sync_type = history_sync.sync_type,
+ chunk_order = history_sync.chunk_order,
+ progress = history_sync.progress,
+ conversations = history_sync.conversations.len(),
+ "received history sync"
+ );
+ if synchronous_storage {
+ self.store_history_sync_side_data(&history_sync).await;
+ } else {
+ let client = Arc::clone(self);
+ let history_sync = history_sync.clone();
+ self.spawn(async move { client.store_history_sync_side_data(&history_sync).await });
+ }
+ Ok(history_sync)
+ }
+
+ async fn store_history_sync_side_data(&self, history_sync: &wa_history_sync::HistorySync) {
+ if let Some(salt) = history_sync
+ .nct_salt
+ .as_ref()
+ .filter(|salt| !salt.is_empty())
+ {
+ let nct_salt = Arc::clone(&self.store.read().await.nct_salt);
+ match nct_salt.put_nct_salt(salt.clone()).await {
+ Err(error) => {
+ tracing::warn!(error = %error, "failed to store NCT salt from history sync")
+ }
+ Ok(()) => tracing::debug!("stored new NCT salt"),
+ }
+ }
+ if !history_sync.phone_number_to_lid_mappings.is_empty() {
+ self.store_historical_pn_lid_mappings(&history_sync.phone_number_to_lid_mappings)
+ .await;
+ }
+ if history_sync.sync_type == HistorySyncType::PushName as i32 {
+ self.handle_historical_push_names(&history_sync.pushnames)
+ .await;
+ } else if !history_sync.conversations.is_empty() {
+ self.store_historical_message_secrets(&history_sync.conversations)
+ .await;
+ }
+ if let Some(settings) = &history_sync.global_settings {
+ self.store_global_settings(settings).await;
+ }
+ if let Some(nonce) = &history_sync.companion_meta_nonce {
+ self.store_companion_meta_nonce(nonce).await;
+ }
+ }
+
+ async fn handle_placeholder_resend_response(
+ &self,
+ message: &wa_e2e::PeerDataOperationRequestResponseMessage,
+ ) -> bool {
+ let request_id = message.stanza_id.clone().unwrap_or_default();
+ let parts = &message.peer_data_operation_result;
+ tracing::debug!(
+ items = parts.len(),
+ "handling response to placeholder resend request"
+ );
+ let mut ok = true;
+ for (index, part) in parts.iter().enumerate() {
+ let Some(response) = &part.placeholder_message_resend_response else {
+ tracing::warn!(
+ item = index + 1,
+ "missing response in placeholder resend item"
+ );
+ continue;
+ };
+ let web_message = match WebMessageInfo::decode(
+ response
+ .web_message_info_bytes
+ .as_deref()
+ .unwrap_or_default(),
+ ) {
+ Ok(web_message) => web_message,
+ Err(error) => {
+ tracing::warn!(error = %error, item = index + 1, "failed to unmarshal web message in placeholder resend item");
+ continue;
+ }
+ };
+ match self.parse_web_message(&Jid::default(), web_message).await {
+ Err(error) => {
+ tracing::warn!(error = %error, item = index + 1, "failed to parse web message info in placeholder resend item");
+ }
+ Ok(mut event) => {
+ event.unavailable_request_id = request_id.clone();
+ ok = !self.dispatch_event(Event::Message(Box::new(event))).await && ok;
+ }
+ }
+ }
+ ok
+ }
+
+ async fn handle_protocol_message(
+ self: &Arc<Self>,
+ info: &MessageInfo,
+ message: &wa_e2e::Message,
+ ) -> bool {
+ let mut ok = true;
+ let Some(protocol_message) = &message.protocol_message else {
+ return ok;
+ };
+ if !info.is_from_me {
+ return ok;
+ }
+
+ if let Some(notification) = &protocol_message.history_sync_notification {
+ if !self.config.manual_history_sync_download {
+ let _ = self.history_sync_notifications.send(notification.clone());
+ if self
+ .history_sync_handler_started
+ .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
+ .is_ok()
+ {
+ let client = Arc::clone(self);
+ self.spawn(client.handle_history_sync_notification_loop());
+ }
+ }
+ if !(self.config.manual_history_sync_download
+ && self.config.disable_manual_history_sync_receipt)
+ {
+ let client = Arc::clone(self);
+ let id = info.id.clone();
+ self.spawn(async move {
+ if let Err(error) = client
+ .send_protocol_message_receipt(&id, ReceiptType::HistorySync)
+ .await
+ {
+ tracing::warn!(error = %error, "failed to send acknowledgement for protocol message");
+ }
+ });
+ }
+ }
+
+ if let Some(lid_sync) = &protocol_message.lid_migration_mapping_sync_message {
+ self.store_lid_sync_message(
+ lid_sync
+ .encoded_mapping_payload
+ .as_deref()
+ .unwrap_or_default(),
+ )
+ .await;
+ }
+
+ if info.sender.device == 0
+ && let Some(response) = &protocol_message.peer_data_operation_request_response_message
+ {
+ let request_type = response.peer_data_operation_request_type;
+ if request_type == Some(PeerDataOperationRequestType::PlaceholderMessageResend as i32) {
+ ok = self.handle_placeholder_resend_response(response).await && ok;
+ } else if request_type
+ == Some(PeerDataOperationRequestType::CompanionSyncdSnapshotFatalRecovery as i32)
+ {
+ tracing::debug!("app state recovery responses are handled with app state sync");
+ }
+ }
+
+ if let Some(key_share) = &protocol_message.app_state_sync_key_share {
+ let client = Arc::clone(self);
+ let key_share = key_share.clone();
+ self.spawn(async move { client.handle_app_state_sync_key_share(&key_share).await });
+ }
+
+ if info.category == "peer" {
+ let client = Arc::clone(self);
+ let id = info.id.clone();
+ self.spawn(async move {
+ if let Err(error) = client
+ .send_protocol_message_receipt(&id, ReceiptType::PeerMsg)
+ .await
+ {
+ tracing::warn!(error = %error, "failed to send acknowledgement for protocol message");
+ }
+ });
+ }
+ ok
+ }
+
+ async fn process_protocol_parts(
+ self: &Arc<Self>,
+ info: &MessageInfo,
+ message: &wa_e2e::Message,
+ ) -> bool {
+ let mut ok = true;
+ self.store_message_secret(info, message).await;
+ // Hopefully sender key distribution messages and protocol messages
+ // can't be inside ephemeral messages.
+ let message = message
+ .device_sent_message
+ .as_ref()
+ .and_then(|device_sent| device_sent.message.as_deref())
+ .unwrap_or(message);
+ if let Some(skdm) = &message.sender_key_distribution_message {
+ if !info.is_group {
+ tracing::warn!("got sender key distribution message in non-group chat");
+ } else {
+ let mut encryption_identity = &info.sender;
+ if encryption_identity.server == DEFAULT_USER_SERVER
+ && info.sender_alt.server == HIDDEN_USER_SERVER
+ {
+ encryption_identity = &info.sender_alt;
+ }
+ self.handle_sender_key_distribution_message(
+ &info.chat,
+ encryption_identity,
+ skdm.axolotl_sender_key_distribution_message
+ .as_deref()
+ .unwrap_or_default(),
+ )
+ .await;
+ }
+ }
+ // Edits are protocol messages too, but wrapped in EditedMessage,
+ // which is only unwrapped after this, so they don't trigger here.
+ if message.protocol_message.is_some() {
+ ok = self.handle_protocol_message(info, message).await && ok;
+ }
+ ok
+ }
+
+ async fn store_message_secret(&self, info: &MessageInfo, message: &wa_e2e::Message) {
+ let Some(secret) = message
+ .message_context_info
+ .as_ref()
+ .and_then(|context| context.message_secret.as_ref())
+ .filter(|secret| !secret.is_empty())
+ else {
+ return;
+ };
+ let mut target_chat = info.chat.clone();
+ let device_sent = message
+ .device_sent_message
+ .as_ref()
+ .and_then(|device_sent| device_sent.message.as_deref())
+ .unwrap_or(message);
+ if let Some(target_chat_jid) = device_sent
+ .root_secret_distribute_message
+ .as_ref()
+ .and_then(|root| root.chat_jid.as_deref())
+ .filter(|jid| !jid.is_empty())
+ && info.is_from_me
+ {
+ match parse_jid(target_chat_jid) {
+ Ok(jid) => target_chat = jid,
+ Err(error) => {
+ tracing::warn!(error = %error, "failed to parse chat JID from root secret distribute message");
+ return;
+ }
+ }
+ }
+ let msg_secrets = Arc::clone(&self.store.read().await.msg_secrets);
+ match msg_secrets
+ .put_message_secret(&target_chat, &info.sender, &info.id, secret.clone())
+ .await
+ {
+ Err(error) => tracing::error!(error = %error, "failed to store message secret key"),
+ Ok(()) => tracing::debug!("stored message secret key"),
+ }
+ }
+
+ async fn store_historical_message_secrets(
+ &self,
+ conversations: &[wa_history_sync::Conversation],
+ ) {
+ let own_id = self.get_own_id().await.to_non_ad();
+ if own_id.is_empty() {
+ return;
+ }
+ let (lids, msg_secrets, privacy_tokens) = {
+ let store = self.store.read().await;
+ (
+ Arc::clone(&store.lids),
+ Arc::clone(&store.msg_secrets),
+ Arc::clone(&store.privacy_tokens),
+ )
+ };
+ let mut secrets = Vec::new();
+ let mut tokens = Vec::new();
+ for conversation in conversations {
+ let chat_jid = parse_jid(&conversation.id).unwrap_or_default();
+ if chat_jid.is_empty() {
+ continue;
+ }
+ let user_jid = if chat_jid.server == HIDDEN_USER_SERVER {
+ chat_jid.clone()
+ } else if chat_jid.server == DEFAULT_USER_SERVER {
+ // Privacy token lookups check LIDs and phone numbers, so a
+ // phone number is better than nothing.
+ lids.get_lid_for_pn(&chat_jid)
+ .await
+ .ok()
+ .flatten()
+ .filter(|lid| !lid.is_empty())
+ .unwrap_or_else(|| chat_jid.clone())
+ } else {
+ Jid::default()
+ };
+ if !user_jid.is_empty()
+ && let Some(token) = &conversation.tc_token
+ {
+ let seconds = |value: Option<u64>| {
+ DateTime::from_timestamp(
+ i64::try_from(value.unwrap_or_default()).unwrap_or_default(),
+ 0,
+ )
+ .unwrap_or_default()
+ };
+ tokens.push(PrivacyToken {
+ user: user_jid,
+ token: token.clone(),
+ timestamp: seconds(conversation.tc_token_timestamp),
+ sender_timestamp: Some(seconds(conversation.tc_token_sender_timestamp)),
+ });
+ }
+ for history_message in &conversation.messages {
+ let Some(web_message) = &history_message.message else {
+ continue;
+ };
+ let Some(secret) = &web_message.message_secret else {
+ continue;
+ };
+ let key = web_message.key.clone();
+ let sender_jid = if key.from_me.unwrap_or_default() {
+ own_id.clone()
+ } else if chat_jid.server == DEFAULT_USER_SERVER
+ || chat_jid.server == HIDDEN_USER_SERVER
+ {
+ chat_jid.clone()
+ } else if let Some(participant) =
+ key.participant.as_deref().filter(|p| !p.is_empty())
+ {
+ parse_jid(participant).unwrap_or_default()
+ } else if let Some(participant) =
+ web_message.participant.as_deref().filter(|p| !p.is_empty())
+ {
+ parse_jid(participant).unwrap_or_default()
+ } else {
+ Jid::default()
+ };
+ let id = key.id.unwrap_or_default();
+ if sender_jid.is_empty() || id.is_empty() {
+ continue;
+ }
+ secrets.push(MessageSecretInsert {
+ chat: chat_jid.clone(),
+ sender: sender_jid,
+ id,
+ secret: secret.clone(),
+ });
+ }
+ }
+ if !secrets.is_empty() {
+ match msg_secrets.put_message_secrets(&secrets).await {
+ Err(error) => {
+ tracing::error!(error = %error, "failed to store message secret keys in history sync")
+ }
+ Ok(()) => tracing::info!(
+ count = secrets.len(),
+ "stored message secret keys from history sync"
+ ),
+ }
+ }
+ if !tokens.is_empty() {
+ match privacy_tokens.put_privacy_tokens(&tokens).await {
+ Err(error) => {
+ tracing::error!(error = %error, "failed to store privacy tokens in history sync")
+ }
+ Ok(()) => tracing::info!(
+ count = tokens.len(),
+ "stored privacy tokens from history sync"
+ ),
+ }
+ }
+ }
+
+ async fn store_lid_sync_message(&self, payload: &[u8]) {
+ let decoded = match LidMigrationMappingSyncPayload::decode(payload) {
+ Ok(decoded) => decoded,
+ Err(error) => {
+ tracing::error!(error = %error, "failed to unmarshal LID migration mapping sync payload");
+ return;
+ }
+ };
+ let migration_timestamp = decoded.chat_db_migration_timestamp.unwrap_or_default();
+ self.save_lid_migration_timestamp(i64::try_from(migration_timestamp).unwrap_or_default())
+ .await;
+ let pairs: Vec<LidMapping> = decoded
+ .pn_to_lid_mappings
+ .iter()
+ .map(|mapping| LidMapping {
+ lid: crate::types::new_jid(&mapping.assigned_lid.to_string(), HIDDEN_USER_SERVER),
+ pn: crate::types::new_jid(&mapping.pn.to_string(), DEFAULT_USER_SERVER),
+ })
+ .collect();
+ let lids = Arc::clone(&self.store.read().await.lids);
+ match lids.put_many_lid_mappings(&pairs).await {
+ Err(error) => {
+ tracing::error!(error = %error, pair_count = pairs.len(), "failed to store phone number to LID mappings from sync message")
+ }
+ Ok(()) => tracing::debug!(
+ pair_count = pairs.len(),
+ "stored PN-LID mappings from sync message"
+ ),
+ }
+ }
+
+ async fn save_lid_migration_timestamp(&self, timestamp: i64) {
+ let mut store = self.store.write().await;
+ if store.lid_migration_timestamp == 0 && timestamp > 0 {
+ store.lid_migration_timestamp = timestamp;
+ match store.save().await {
+ Err(error) => {
+ tracing::error!(error = %error, "failed to save chat DB LID migration timestamp")
+ }
+ Ok(()) => tracing::debug!(timestamp, "saved chat DB LID migration timestamp"),
+ }
+ }
+ }
+
+ async fn store_global_settings(&self, settings: &wa_history_sync::GlobalSettings) {
+ self.save_lid_migration_timestamp(
+ settings.chat_db_lid_migration_timestamp.unwrap_or_default(),
+ )
+ .await;
+ }
+
+ async fn store_companion_meta_nonce(&self, nonce: &str) {
+ let mut store = self.store.write().await;
+ if !nonce.is_empty() && nonce != store.companion_meta_nonce {
+ store.companion_meta_nonce = nonce.to_owned();
+ match store.save().await {
+ Err(error) => {
+ tracing::error!(error = %error, "failed to save companion meta nonce")
+ }
+ Ok(()) => tracing::debug!("saved companion meta nonce"),
+ }
+ }
+ }
+
+ async fn store_historical_pn_lid_mappings(
+ &self,
+ mappings: &[wa_history_sync::PhoneNumberToLidMapping],
+ ) {
+ let mut pairs = Vec::with_capacity(mappings.len());
+ for mapping in mappings {
+ let mut pn = match parse_jid(mapping.pn_jid.as_deref().unwrap_or_default()) {
+ Ok(pn) => pn,
+ Err(error) => {
+ tracing::error!(error = %error, "failed to parse phone number from history sync");
+ continue;
+ }
+ };
+ if pn.server == LEGACY_USER_SERVER {
+ pn.server = DEFAULT_USER_SERVER.to_owned();
+ }
+ let lid = match parse_jid(mapping.lid_jid.as_deref().unwrap_or_default()) {
+ Ok(lid) => lid,
+ Err(error) => {
+ tracing::error!(error = %error, "failed to parse LID from history sync");
+ continue;
+ }
+ };
+ pairs.push(LidMapping { lid, pn });
+ }
+ let lids = Arc::clone(&self.store.read().await.lids);
+ match lids.put_many_lid_mappings(&pairs).await {
+ Err(error) => {
+ tracing::error!(error = %error, pair_count = pairs.len(), "failed to store phone number to LID mappings from history sync")
+ }
+ Ok(()) => tracing::debug!(
+ pair_count = pairs.len(),
+ "stored PN-LID mappings from history sync"
+ ),
+ }
+ }
+
+ /// Handles a decrypted message; returns whether a handler failed.
+ async fn handle_decrypted_message(
+ self: &Arc<Self>,
+ info: &MessageInfo,
+ message: wa_e2e::Message,
+ retry_count: i64,
+ ) -> bool {
+ if !self.process_protocol_parts(info, &message).await {
+ return false;
+ }
+ let mut event = Message {
+ info: info.clone(),
+ raw_message: Some(message),
+ retry_count,
+ ..Message::default()
+ };
+ event.unwrap_raw();
+ self.dispatch_event(Event::Message(Box::new(event))).await
+ }
+
+ /// Sends a receipt for a protocol message back to the phone.
+ pub async fn send_protocol_message_receipt(
+ &self,
+ id: &str,
+ message_type: ReceiptType,
+ ) -> Result<(), ClientError> {
+ if id.is_empty() {
+ return Ok(());
+ }
+ let node = Node {
+ tag: "receipt".to_owned(),
+ attrs: crate::binary::Attrs::from([
+ ("id".to_owned(), id.into()),
+ ("type".to_owned(), message_type.as_str().into()),
+ ("to".to_owned(), self.get_own_id().await.to_non_ad().into()),
+ ]),
+ content: None,
+ };
+ self.send_node(&node).await
+ }
+}
+
+/// Parses a `<bot>` node. Like Go, it reads the `<bot>` child of the node it
+/// is given, and the message parser passes the `<bot>` node itself.
+fn parse_msg_bot_info(node: &Node) -> Result<MsgBotInfo, ClientError> {
+ let bot_node = node.get_child_by_tag(&["bot"]);
+ let mut attrs = bot_node.attr_getter();
+ let mut bot_info = MsgBotInfo {
+ edit_type: BotEditType::from(attrs.optional_string("edit")),
+ ..MsgBotInfo::default()
+ };
+ if matches!(
+ bot_info.edit_type,
+ BotEditType::Inner | BotEditType::Last | BotEditType::Full
+ ) {
+ bot_info.edit_target_id = attrs.optional_string("edit_target_id");
+ bot_info.edit_sender_timestamp_ms = attrs.unix_milli("sender_timestamp_ms");
+ }
+ bot_info.client_thread_id = attrs.optional_string("client_thread_id");
+ attrs.error()?;
+ Ok(bot_info)
+}
+
+/// Parses a `<meta>` node; reads the `<meta>` child like `parse_msg_bot_info`.
+fn parse_msg_meta_info(node: &Node) -> Result<MsgMetaInfo, ClientError> {
+ let meta_node = node.get_child_by_tag(&["meta"]);
+ let mut attrs = meta_node.attr_getter();
+ let meta_info = MsgMetaInfo {
+ target_id: attrs.optional_string("target_id"),
+ target_sender: attrs.optional_jid_or_empty("target_sender_jid"),
+ target_chat: attrs.optional_jid_or_empty("target_chat_jid"),
+ deprecated_lid_session: attrs.get_bool("deprecated_lid_session", false),
+ thread_message_id: attrs.optional_string("thread_msg_id"),
+ thread_message_sender_jid: attrs.optional_jid_or_empty("thread_msg_sender_jid"),
+ };
+ attrs.error()?;
+ Ok(meta_info)
+}
+
+fn is_valid_padding(plaintext: &[u8]) -> bool {
+ let Some(&last_byte) = plaintext.last() else {
+ return false;
+ };
+ let padding = usize::from(last_byte);
+ padding <= plaintext.len()
+ && plaintext[plaintext.len() - padding..]
+ .iter()
+ .all(|&byte| byte == last_byte)
+}
+
+/// Removes the random padding of a decrypted message; version 3 messages
+/// aren't padded.
+pub fn unpad_message(mut plaintext: Vec<u8>, version: i64) -> Result<Vec<u8>, String> {
+ if version == 3 {
+ return Ok(plaintext);
+ }
+ let Some(&last_byte) = plaintext.last() else {
+ return Err("plaintext is empty".to_owned());
+ };
+ if !is_valid_padding(&plaintext) {
+ return Err("plaintext doesn't have expected padding".to_owned());
+ }
+ plaintext.truncate(plaintext.len() - usize::from(last_byte));
+ Ok(plaintext)
+}
+
+/// Appends 1–15 bytes of padding, each the padding length.
+pub fn pad_message(mut plaintext: Vec<u8>) -> Vec<u8> {
+ let mut pad = rand::random::<u8>() & 0xf;
+ if pad == 0 {
+ pad = 0xf;
+ }
+ plaintext.extend(std::iter::repeat_n(pad, usize::from(pad)));
+ plaintext
+}
+
+#[cfg(test)]
+mod test;
diff --git a/crates/whatsmeow/src/message/test.rs b/crates/whatsmeow/src/message/test.rs
new file mode 100644
index 0000000000..6670495a27
--- /dev/null
+++ b/crates/whatsmeow/src/message/test.rs
@@ -0,0 +1,393 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+//! The receive path against the fake server, with the fake Signal
+//! implementation: decrypting 1:1 and group messages, receipts, retry
+//! receipts for undecryptable messages, and history sync notifications.
+
+use std::io::Write as _;
+
+use prost::Message as _;
+
+use super::*;
+use crate::client::test::{
+ bytes, children, connect_paired, harness, jid, next_event, next_node, node, text,
+};
+use crate::store::{IdentityStore, SenderKeyStore};
+use crate::testing::{
+ attr_string, fake_direct_ciphertext, fake_group_ciphertext,
+ fake_sender_key_distribution_message,
+};
+
+const OWN_JID: &str = "1234:[email protected]";
+const OWN_LID: &str = "9876:5@lid";
+const PEER: &str = "[email protected]";
+const PEER_IDENTITY: [u8; 32] = [0x33; 32];
+
+fn enc(kind: &str, ciphertext: Vec<u8>) -> Node {
+ node(
+ "enc",
+ &[("v", text("2")), ("type", text(kind))],
+ bytes(&ciphertext),
+ )
+}
+
+fn text_message(body: &str) -> wa_e2e::Message {
+ wa_e2e::Message {
+ conversation: Some(body.to_owned()),
+ ..Default::default()
+ }
+}
+
+async fn next_message(events: &mut tokio::sync::mpsc::UnboundedReceiver<Event>) -> Message {
+ loop {
+ if let Event::Message(message) = next_event(events).await {
+ return *message;
+ }
+ }
+}
+
+#[test]
+fn padding_round_trips_and_rejects_bad_padding() {
+ let padded = pad_message(b"hello".to_vec());
+ assert!(padded.len() > 5 && padded.len() <= 20);
+ assert_eq!(unpad_message(padded, 2).unwrap(), b"hello");
+ assert_eq!(
+ unpad_message(b"abc\x02\x01".to_vec(), 2).unwrap(),
+ b"abc\x02"
+ );
+ assert_eq!(
+ unpad_message(b"abc\x03\x02".to_vec(), 2).unwrap_err(),
+ "plaintext doesn't have expected padding"
+ );
+ assert_eq!(
+ unpad_message(Vec::new(), 2).unwrap_err(),
+ "plaintext is empty"
+ );
+ assert_eq!(unpad_message(b"raw".to_vec(), 3).unwrap(), b"raw");
+}
+
+#[tokio::test(start_paused = true)]
+async fn a_direct_message_is_decrypted_dispatched_and_receipted() {
+ let mut harness = harness(Some((OWN_JID, OWN_LID)));
+ let mut connection = connect_paired(&mut harness).await;
+ let ciphertext = fake_direct_ciphertext(
+ &PEER_IDENTITY,
+ &pad_message(text_message("hello there").encode_to_vec()),
+ );
+ connection
+ .send_node(&node(
+ "message",
+ &[
+ ("from", jid(PEER)),
+ ("id", text("MSG1")),
+ ("t", text("1700000100")),
+ ("type", text("text")),
+ ("notify", text("Peer")),
+ ],
+ children(vec![enc("pkmsg", ciphertext)]),
+ ))
+ .await;
+
+ let message = next_message(&mut harness.events).await;
+ assert_eq!(message.info.id, "MSG1");
+ assert_eq!(message.info.chat.to_string(), PEER);
+ assert_eq!(message.info.sender.to_string(), PEER);
+ assert!(!message.info.is_from_me);
+ assert_eq!(message.info.push_name, "Peer");
+ assert_eq!(
+ message.message.unwrap().conversation.as_deref(),
+ Some("hello there")
+ );
+
+ let receipt = next_node(&mut connection).await;
+ assert_eq!(receipt.tag, "receipt");
+ assert_eq!(attr_string(&receipt, "id"), "MSG1");
+ assert_eq!(attr_string(&receipt, "to"), PEER);
+ assert_eq!(attr_string(&receipt, "type"), "inactive");
+ assert!(
+ harness
+ .store
+ .is_trusted_identity("5550001:0", PEER_IDENTITY)
+ .await
+ .unwrap(),
+ "decrypting the prekey message stored the sender's identity"
+ );
+}
+
+#[tokio::test(start_paused = true)]
+async fn group_messages_need_the_sender_key_and_ask_for_a_retry_without_it() {
+ let mut harness = harness(Some((OWN_JID, OWN_LID)));
+ let mut connection = connect_paired(&mut harness).await;
+ let group = "[email protected]";
+
+ // No sender key yet: the client sends a retry receipt and reports the
+ // message as undecryptable.
+ connection
+ .send_node(&node(
+ "message",
+ &[
+ ("from", jid(group)),
+ ("participant", jid(PEER)),
+ ("id", text("G1")),
+ ("t", text("1700000200")),
+ ("type", text("text")),
+ ],
+ children(vec![enc(
+ "skmsg",
+ fake_group_ciphertext(&pad_message(text_message("lost").encode_to_vec())),
+ )]),
+ ))
+ .await;
+ loop {
+ if let Event::UndecryptableMessage(undecryptable) = next_event(&mut harness.events).await {
+ assert_eq!(undecryptable.info.id, "G1");
+ assert!(undecryptable.is_unavailable);
+ break;
+ }
+ }
+ let mut retry = next_node(&mut connection).await;
+ if retry.tag == "ack" {
+ retry = next_node(&mut connection).await;
+ }
+ assert_eq!(retry.tag, "receipt");
+ assert_eq!(attr_string(&retry, "type"), "retry");
+ assert_eq!(attr_string(&retry, "participant"), PEER);
+ let retry_child = retry.get_child_by_tag(&["retry"]);
+ assert_eq!(attr_string(retry_child, "count"), "1");
+ assert_eq!(attr_string(retry_child, "id"), "G1");
+ assert!(
+ retry.get_optional_child_by_tag(&["keys"]).is_some(),
+ "a missing sender key forces our identity into the first retry"
+ );
+
+ // The resend carries the sender key distribution message 1:1 and the
+ // group ciphertext.
+ let sender_key_name = SenderKeyName {
+ group_id: group.to_owned(),
+ sender: parse_jid(PEER).unwrap().signal_address(),
+ };
+ let skdm_message = wa_e2e::Message {
+ sender_key_distribution_message: Some(wa_e2e::SenderKeyDistributionMessage {
+ group_id: Some(group.to_owned()),
+ axolotl_sender_key_distribution_message: Some(fake_sender_key_distribution_message(
+ &sender_key_name,
+ )),
+ }),
+ ..Default::default()
+ };
+ connection
+ .send_node(&node(
+ "message",
+ &[
+ ("from", jid(group)),
+ ("participant", jid(PEER)),
+ ("id", text("G1")),
+ ("t", text("1700000200")),
+ ("type", text("text")),
+ ],
+ children(vec![
+ enc(
+ "pkmsg",
+ fake_direct_ciphertext(
+ &PEER_IDENTITY,
+ &pad_message(skdm_message.encode_to_vec()),
+ ),
+ ),
+ enc(
+ "skmsg",
+ fake_group_ciphertext(&pad_message(text_message("found").encode_to_vec())),
+ ),
+ ]),
+ ))
+ .await;
+ let first = next_message(&mut harness.events).await;
+ assert!(
+ first
+ .message
+ .unwrap()
+ .sender_key_distribution_message
+ .is_some()
+ );
+ let second = next_message(&mut harness.events).await;
+ assert_eq!(second.info.chat.to_string(), group);
+ assert_eq!(second.info.sender.to_string(), PEER);
+ assert!(second.info.is_group);
+ assert_eq!(
+ second.message.unwrap().conversation.as_deref(),
+ Some("found")
+ );
+ assert!(
+ harness
+ .store
+ .get_sender_key(group, "5550001:0")
+ .await
+ .unwrap()
+ .is_some()
+ );
+}
+
+#[tokio::test(start_paused = true)]
+async fn an_unparseable_message_is_nacked() {
+ let mut harness = harness(Some((OWN_JID, OWN_LID)));
+ let mut connection = connect_paired(&mut harness).await;
+ connection
+ .send_node(&node("message", &[("id", text("BAD"))], None))
+ .await;
+ let ack = next_node(&mut connection).await;
+ assert_eq!(ack.tag, "ack");
+ assert_eq!(attr_string(&ack, "error"), "487");
+}
+
+#[tokio::test(start_paused = true)]
+async fn receipts_are_parsed_and_acked() {
+ let mut harness = harness(Some((OWN_JID, OWN_LID)));
+ let mut connection = connect_paired(&mut harness).await;
+ connection
+ .send_node(&node(
+ "receipt",
+ &[
+ ("from", jid(PEER)),
+ ("id", text("OUT1")),
+ ("t", text("1700000300")),
+ ("type", text("read")),
+ ],
+ children(vec![node(
+ "list",
+ &[],
+ children(vec![node("item", &[("id", text("OUT2"))], None)]),
+ )]),
+ ))
+ .await;
+ loop {
+ if let Event::Receipt(receipt) = next_event(&mut harness.events).await {
+ assert_eq!(
+ receipt.message_ids,
+ vec!["OUT1".to_owned(), "OUT2".to_owned()]
+ );
+ assert_eq!(receipt.r#type, ReceiptType::Read);
+ assert_eq!(receipt.source.chat.to_string(), PEER);
+ break;
+ }
+ }
+ let ack = next_node(&mut connection).await;
+ assert_eq!(ack.tag, "ack");
+ assert_eq!(attr_string(&ack, "class"), "receipt");
+ assert_eq!(attr_string(&ack, "type"), "read");
+ assert_eq!(attr_string(&ack, "id"), "OUT1");
+}
+
+#[tokio::test(start_paused = true)]
+async fn a_history_sync_notification_from_the_phone_is_downloaded_and_dispatched() {
+ let mut harness = harness(Some((OWN_JID, OWN_LID)));
+ let mut connection = connect_paired(&mut harness).await;
+ let history = wa_history_sync::HistorySync {
+ sync_type: HistorySyncType::InitialBootstrap as i32,
+ conversations: vec![wa_history_sync::Conversation {
+ id: "[email protected]".to_owned(),
+ ..Default::default()
+ }],
+ phone_number_to_lid_mappings: vec![wa_history_sync::PhoneNumberToLidMapping {
+ pn_jid: Some(PEER.to_owned()),
+ lid_jid: Some("777@lid".to_owned()),
+ }],
+ ..Default::default()
+ };
+ let mut compressed =
+ flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default());
+ compressed.write_all(&history.encode_to_vec()).unwrap();
+ let notification = wa_e2e::Message {
+ protocol_message: Some(Box::new(wa_e2e::ProtocolMessage {
+ r#type: Some(wa_e2e::protocol_message::Type::HistorySyncNotification as i32),
+ history_sync_notification: Some(wa_e2e::HistorySyncNotification {
+ initial_hist_bootstrap_inline_payload: Some(compressed.finish().unwrap()),
+ ..Default::default()
+ }),
+ ..Default::default()
+ })),
+ ..Default::default()
+ };
+ let own_identity = harness.client.store.read().await.identity_key.public;
+ connection
+ .send_node(&node(
+ "message",
+ &[
+ ("from", jid("1234:[email protected]")),
+ ("id", text("HS1")),
+ ("t", text("1700000400")),
+ ("type", text("text")),
+ ("category", text("peer")),
+ ],
+ children(vec![enc(
+ "pkmsg",
+ fake_direct_ciphertext(&own_identity, &pad_message(notification.encode_to_vec())),
+ )]),
+ ))
+ .await;
+ loop {
+ if let Event::HistorySync(history_sync) = next_event(&mut harness.events).await {
+ assert_eq!(history_sync.data.conversations.len(), 1);
+ break;
+ }
+ }
+ let mut receipt_types = Vec::new();
+ while receipt_types.len() < 3 {
+ let receipt = next_node(&mut connection).await;
+ if receipt.tag == "receipt" {
+ receipt_types.push(attr_string(&receipt, "type"));
+ }
+ }
+ receipt_types.sort();
+ assert_eq!(receipt_types, vec!["hist_sync", "peer_msg", "sender"]);
+ let lid = harness
+ .client
+ .store
+ .read()
+ .await
+ .lids
+ .get_lid_for_pn(&parse_jid(PEER).unwrap())
+ .await
+ .unwrap();
+ assert_eq!(lid.unwrap().to_string(), "777@lid");
+}
+
+#[tokio::test(start_paused = true)]
+async fn message_sources_parse_like_go() {
+ let harness = harness(Some((OWN_JID, OWN_LID)));
+ let vectors = crate::vectors::Vectors::load("message.json");
+ for case in vectors.value("sources").as_array().unwrap() {
+ let data = hex::decode(case["node"].as_str().unwrap()).unwrap();
+ let node = crate::binary::unmarshal(&crate::binary::unpack(&data).unwrap()).unwrap();
+ let info = harness.client.parse_message_info(&node).await.unwrap();
+ assert_eq!(info.chat.to_string(), case["chat"].as_str().unwrap());
+ assert_eq!(info.sender.to_string(), case["sender"].as_str().unwrap());
+ assert_eq!(info.is_from_me, case["from_me"].as_bool().unwrap());
+ assert_eq!(info.is_group, case["group"].as_bool().unwrap());
+ assert_eq!(
+ info.addressing_mode.as_str(),
+ case["addressing_mode"].as_str().unwrap()
+ );
+ assert_eq!(
+ info.sender_alt.to_string(),
+ case["sender_alt"].as_str().unwrap()
+ );
+ assert_eq!(
+ info.recipient_alt.to_string(),
+ case["recipient_alt"].as_str().unwrap()
+ );
+ assert_eq!(info.id, case["id"].as_str().unwrap());
+ assert_eq!(
+ info.timestamp.unwrap().timestamp(),
+ case["t"].as_i64().unwrap()
+ );
+ assert_eq!(info.push_name, case["push_name"].as_str().unwrap());
+ assert_eq!(info.r#type, case["type"].as_str().unwrap());
+ assert_eq!(info.edit.as_str(), case["edit"].as_str().unwrap());
+ assert_eq!(info.media_type, case["media_type"].as_str().unwrap());
+ }
+ assert_eq!(
+ hex::decode(vectors.string("unpadded")).unwrap(),
+ unpad_message(b"abc\x03\x03\x03".to_vec(), 2).unwrap()
+ );
+}
diff --git a/crates/whatsmeow/src/msgsecret.rs b/crates/whatsmeow/src/msgsecret.rs
new file mode 100644
index 0000000000..f83c5e9c6e
--- /dev/null
+++ b/crates/whatsmeow/src/msgsecret.rs
@@ -0,0 +1,536 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+//
+// Ported from whatsmeow msgsecret.go (MPL-2.0, Copyright (c) Tulir Asokan)
+//
+// Not ported: WASA and bot messages (`encryptWASAMessage`,
+// `decryptBotMessage`), which the port skips. The encrypt functions take
+// their IV through `encrypt_msg_secret_with` so tests can compare with Go.
+
+//! Message secrets: the per-message keys that encrypt reactions, comments,
+//! poll votes and edits to an earlier message.
+
+use std::sync::Arc;
+
+use chrono::Utc;
+use prost::Message as _;
+use sha2::{Digest, Sha256};
+
+use crate::client::Client;
+use crate::errors::ClientError;
+use crate::proto::wa_common::MessageKey;
+use crate::proto::wa_e2e::{
+ self, EncCommentMessage, EncReactionMessage, PollEncValue, PollUpdateMessage, PollVoteMessage,
+ ReactionMessage, poll_creation_message, secret_encrypted_message,
+};
+use crate::types::events::Message;
+use crate::types::{DEFAULT_USER_SERVER, HIDDEN_USER_SERVER, Jid, MessageInfo, parse_jid};
+use crate::util::gcmutil::{self, GcmError};
+use crate::util::hkdfutil;
+
+/// The use case a message secret key is derived for (`MsgSecretType`).
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum MsgSecretType {
+ /// A poll vote.
+ PollVote,
+ /// An encrypted reaction.
+ Reaction,
+ /// An encrypted comment.
+ Comment,
+ /// A report token.
+ ReportToken,
+ /// An event response.
+ EventResponse,
+ /// An event edit.
+ EventEdit,
+ /// A message edit.
+ MessageEdit,
+ /// A poll edit.
+ PollEdit,
+ /// A poll option added.
+ PollAddOption,
+ /// A bot message.
+ BotMessage,
+ /// No use case (Go's `""`, used for bot messages).
+ Empty,
+}
+
+impl MsgSecretType {
+ /// The string mixed into the key.
+ pub fn as_str(self) -> &'static str {
+ match self {
+ MsgSecretType::PollVote => "Poll Vote",
+ MsgSecretType::Reaction => "Enc Reaction",
+ MsgSecretType::Comment => "Enc Comment",
+ MsgSecretType::ReportToken => "Report Token",
+ MsgSecretType::EventResponse => "Event Response",
+ MsgSecretType::EventEdit => "Event Edit",
+ MsgSecretType::MessageEdit => "Message Edit",
+ MsgSecretType::PollEdit => "Poll Edit",
+ MsgSecretType::PollAddOption => "Poll Add Option",
+ MsgSecretType::BotMessage => "Bot Message",
+ MsgSecretType::Empty => "",
+ }
+ }
+}
+
+/// The key and additional data for one use of an original message's secret.
+pub fn generate_msg_secret_key(
+ modification_type: MsgSecretType,
+ modification_sender: &Jid,
+ original_message_id: &str,
+ original_message_sender: &Jid,
+ original_message_secret: &[u8],
+) -> (Vec<u8>, Vec<u8>) {
+ let original_sender = original_message_sender.to_non_ad().to_string();
+ let modification_sender = modification_sender.to_non_ad().to_string();
+ let use_case_secret = [
+ original_message_id.as_bytes(),
+ original_sender.as_bytes(),
+ modification_sender.as_bytes(),
+ modification_type.as_str().as_bytes(),
+ ]
+ .concat();
+ let secret_key = hkdfutil::sha256(original_message_secret, &[], &use_case_secret, 32);
+ let additional_data = match modification_type {
+ MsgSecretType::PollVote | MsgSecretType::EventResponse | MsgSecretType::Empty => {
+ format!("{original_message_id}\x00{modification_sender}").into_bytes()
+ }
+ _ => Vec::new(),
+ };
+ (secret_key, additional_data)
+}
+
+fn get_orig_sender_from_key(message: &Message, key: &MessageKey) -> Result<Jid, ClientError> {
+ let chat_server = message.info.chat.server.as_str();
+ if key.from_me.unwrap_or_default() {
+ Ok(message.info.sender.clone())
+ } else if chat_server == DEFAULT_USER_SERVER || chat_server == HIDDEN_USER_SERVER {
+ let remote_jid = key.remote_jid.as_deref().unwrap_or_default();
+ parse_jid(remote_jid).map_err(|error| {
+ ClientError::Other(format!(
+ "failed to parse JID of original message sender: {error}"
+ ))
+ })
+ } else {
+ let participant = key.participant.as_deref().unwrap_or_default();
+ let sender = parse_jid(participant).map_err(|error| error.to_string());
+ match sender {
+ Ok(sender)
+ if sender.server == DEFAULT_USER_SERVER || sender.server == HIDDEN_USER_SERVER =>
+ {
+ Ok(sender)
+ }
+ Ok(_) => Err(ClientError::Other(
+ "failed to parse JID of original message sender: unexpected server".to_owned(),
+ )),
+ Err(error) => Err(ClientError::Other(format!(
+ "failed to parse JID of original message sender: {error}"
+ ))),
+ }
+ }
+}
+
+/// `SHA-256` of each poll option name (`HashPollOptions`).
+pub fn hash_poll_options(option_names: &[String]) -> Vec<Vec<u8>> {
+ option_names
+ .iter()
+ .map(|option| Sha256::digest(option.as_bytes()).to_vec())
+ .collect()
+}
+
+/// A new poll; the message secret is what voters encrypt with
+/// (`BuildPollCreation`).
+pub fn build_poll_creation(
+ name: &str,
+ option_names: &[String],
+ selectable_option_count: i64,
+) -> wa_e2e::Message {
+ let selectable = if selectable_option_count < 0
+ || selectable_option_count > i64::try_from(option_names.len()).unwrap_or(i64::MAX)
+ {
+ 0
+ } else {
+ selectable_option_count
+ };
+ wa_e2e::Message {
+ poll_creation_message: Some(Box::new(wa_e2e::PollCreationMessage {
+ name: Some(name.to_owned()),
+ options: option_names
+ .iter()
+ .map(|option| poll_creation_message::Option {
+ option_name: Some(option.clone()),
+ ..Default::default()
+ })
+ .collect(),
+ selectable_options_count: Some(u32::try_from(selectable).unwrap_or_default()),
+ ..Default::default()
+ })),
+ message_context_info: Some(wa_e2e::MessageContextInfo {
+ message_secret: Some(rand::random::<[u8; 32]>().to_vec()),
+ ..Default::default()
+ }),
+ ..Default::default()
+ }
+}
+
+/// The key of the message an info describes (`getKeyFromInfo`).
+pub fn get_key_from_info(info: &MessageInfo) -> MessageKey {
+ MessageKey {
+ remote_jid: Some(info.chat.to_string()),
+ from_me: Some(info.is_from_me),
+ id: Some(info.id.clone()),
+ participant: info.is_group.then(|| info.sender.to_string()),
+ }
+}
+
+impl Client {
+ async fn decrypt_msg_secret(
+ &self,
+ message: &Message,
+ use_case: MsgSecretType,
+ enc_iv: &[u8],
+ enc_payload: &[u8],
+ original_key: &MessageKey,
+ ) -> Result<Vec<u8>, ClientError> {
+ let original_sender = get_orig_sender_from_key(message, original_key)?;
+ let original_id = original_key.id.clone().unwrap_or_default();
+ let msg_secrets = Arc::clone(&self.store.read().await.msg_secrets);
+ let (base_key, stored_original_sender) = msg_secrets
+ .get_message_secret(&message.info.chat, &original_sender, &original_id)
+ .await
+ .map_err(|error| {
+ ClientError::from(error).wrap("failed to get original message secret key")
+ })?
+ .ok_or(ClientError::OriginalMessageSecretNotFound)?;
+ let (secret_key, additional_data) = generate_msg_secret_key(
+ use_case,
+ &message.info.sender,
+ &original_id,
+ &original_sender,
+ &base_key,
+ );
+ match gcmutil::decrypt(&secret_key, enc_iv, enc_payload, &additional_data) {
+ Ok(plaintext) => {
+ tracing::debug!("decrypted message secret without hack");
+ Ok(plaintext)
+ }
+ Err(GcmError::Authentication) if original_sender != stored_original_sender => {
+ let (secret_key, additional_data) = generate_msg_secret_key(
+ use_case,
+ &message.info.sender,
+ &original_id,
+ &stored_original_sender,
+ &base_key,
+ );
+ let plaintext =
+ gcmutil::decrypt(&secret_key, enc_iv, enc_payload, &additional_data).map_err(
+ |error| {
+ ClientError::Other(format!("failed to decrypt secret message: {error}"))
+ },
+ )?;
+ tracing::debug!("decrypted message secret with orig sender hack");
+ Ok(plaintext)
+ }
+ Err(error) => Err(ClientError::Other(format!(
+ "failed to decrypt secret message: {error}"
+ ))),
+ }
+ }
+
+ /// Encrypts with an original message's secret; returns (ciphertext, IV).
+ async fn encrypt_msg_secret(
+ &self,
+ own_id: &Jid,
+ chat: &Jid,
+ original_sender: &Jid,
+ original_message_id: &str,
+ use_case: MsgSecretType,
+ plaintext: &[u8],
+ ) -> Result<(Vec<u8>, Vec<u8>), ClientError> {
+ if own_id.is_empty() {
+ return Err(ClientError::NotLoggedIn);
+ }
+ let msg_secrets = Arc::clone(&self.store.read().await.msg_secrets);
+ let (base_key, stored_original_sender) = msg_secrets
+ .get_message_secret(chat, original_sender, &original_message_id.to_owned())
+ .await
+ .map_err(|error| {
+ ClientError::from(error).wrap("failed to get original message secret key")
+ })?
+ .ok_or(ClientError::OriginalMessageSecretNotFound)?;
+ let iv: [u8; 12] = rand::random();
+ let ciphertext = encrypt_msg_secret_with(
+ own_id,
+ &stored_original_sender,
+ original_message_id,
+ use_case,
+ &base_key,
+ &iv,
+ plaintext,
+ )?;
+ Ok((ciphertext, iv.to_vec()))
+ }
+
+ /// Decrypts an encrypted reaction (`DecryptReaction`).
+ pub async fn decrypt_reaction(
+ &self,
+ reaction: &Message,
+ ) -> Result<ReactionMessage, ClientError> {
+ let encrypted = reaction
+ .message
+ .as_ref()
+ .and_then(|message| message.enc_reaction_message.as_ref())
+ .ok_or(ClientError::NotEncryptedReactionMessage)?;
+ let plaintext = self
+ .decrypt_msg_secret(
+ reaction,
+ MsgSecretType::Reaction,
+ encrypted.enc_iv.as_deref().unwrap_or_default(),
+ encrypted.enc_payload.as_deref().unwrap_or_default(),
+ &encrypted.target_message_key.clone().unwrap_or_default(),
+ )
+ .await
+ .map_err(|error| error.wrap("failed to decrypt reaction"))?;
+ ReactionMessage::decode(plaintext.as_slice()).map_err(|error| {
+ ClientError::Other(format!("failed to decode reaction protobuf: {error}"))
+ })
+ }
+
+ /// Decrypts an encrypted comment (`DecryptComment`).
+ pub async fn decrypt_comment(&self, comment: &Message) -> Result<wa_e2e::Message, ClientError> {
+ let encrypted = comment
+ .message
+ .as_ref()
+ .and_then(|message| message.enc_comment_message.as_ref())
+ .ok_or(ClientError::NotEncryptedCommentMessage)?;
+ let plaintext = self
+ .decrypt_msg_secret(
+ comment,
+ MsgSecretType::Comment,
+ encrypted.enc_iv.as_deref().unwrap_or_default(),
+ encrypted.enc_payload.as_deref().unwrap_or_default(),
+ &encrypted.target_message_key.clone().unwrap_or_default(),
+ )
+ .await
+ .map_err(|error| error.wrap("failed to decrypt comment"))?;
+ wa_e2e::Message::decode(plaintext.as_slice()).map_err(|error| {
+ ClientError::Other(format!("failed to decode comment protobuf: {error}"))
+ })
+ }
+
+ /// Decrypts a poll vote (`DecryptPollVote`).
+ pub async fn decrypt_poll_vote(&self, vote: &Message) -> Result<PollVoteMessage, ClientError> {
+ let poll_update = vote
+ .message
+ .as_ref()
+ .and_then(|message| message.poll_update_message.as_ref())
+ .ok_or(ClientError::NotPollUpdateMessage)?;
+ let encrypted = poll_update.vote.clone().unwrap_or_default();
+ let plaintext = self
+ .decrypt_msg_secret(
+ vote,
+ MsgSecretType::PollVote,
+ encrypted.enc_iv.as_deref().unwrap_or_default(),
+ encrypted.enc_payload.as_deref().unwrap_or_default(),
+ &poll_update
+ .poll_creation_message_key
+ .clone()
+ .unwrap_or_default(),
+ )
+ .await
+ .map_err(|error| error.wrap("failed to decrypt poll vote"))?;
+ PollVoteMessage::decode(plaintext.as_slice()).map_err(|error| {
+ ClientError::Other(format!("failed to decode poll vote protobuf: {error}"))
+ })
+ }
+
+ /// Decrypts a message or poll edit sent as a secret encrypted message
+ /// (`DecryptSecretEncryptedMessage`).
+ pub async fn decrypt_secret_encrypted_message(
+ &self,
+ event: &Message,
+ ) -> Result<wa_e2e::Message, ClientError> {
+ let encrypted = event
+ .message
+ .as_ref()
+ .and_then(|message| message.secret_encrypted_message.as_ref())
+ .ok_or(ClientError::NotSecretEncryptedMessage)?;
+ let secret_enc_type = encrypted.secret_enc_type.unwrap_or_default();
+ let secret_type = match secret_encrypted_message::SecretEncType::try_from(secret_enc_type) {
+ Ok(secret_encrypted_message::SecretEncType::EventEdit) => MsgSecretType::EventEdit,
+ Ok(
+ secret_encrypted_message::SecretEncType::PollEdit
+ | secret_encrypted_message::SecretEncType::PollAddOption,
+ ) => MsgSecretType::PollEdit,
+ Ok(secret_encrypted_message::SecretEncType::MessageEdit) => MsgSecretType::MessageEdit,
+ other => {
+ return Err(ClientError::Other(format!(
+ "unsupported secret enc type: {}",
+ other
+ .map(|kind| kind.as_str_name().to_owned())
+ .unwrap_or_else(|_| secret_enc_type.to_string())
+ )));
+ }
+ };
+ let plaintext = self
+ .decrypt_msg_secret(
+ event,
+ secret_type,
+ encrypted.enc_iv.as_deref().unwrap_or_default(),
+ encrypted.enc_payload.as_deref().unwrap_or_default(),
+ &encrypted.target_message_key.clone().unwrap_or_default(),
+ )
+ .await?;
+ let mut message = wa_e2e::Message::decode(plaintext.as_slice()).map_err(|error| {
+ ClientError::Other(format!("failed to decode message protobuf: {error}"))
+ })?;
+ if message.message_context_info.is_none() {
+ message.message_context_info = event
+ .message
+ .as_ref()
+ .and_then(|outer| outer.message_context_info.clone());
+ }
+ Ok(message)
+ }
+
+ /// A vote for options of a poll (`BuildPollVote`).
+ pub async fn build_poll_vote(
+ &self,
+ poll_info: &MessageInfo,
+ option_names: &[String],
+ ) -> Result<wa_e2e::Message, ClientError> {
+ let poll_update = self
+ .encrypt_poll_vote(
+ poll_info,
+ &PollVoteMessage {
+ selected_options: hash_poll_options(option_names),
+ },
+ )
+ .await?;
+ Ok(wa_e2e::Message {
+ poll_update_message: Some(poll_update),
+ ..Default::default()
+ })
+ }
+
+ /// Encrypts a poll vote (`EncryptPollVote`).
+ pub async fn encrypt_poll_vote(
+ &self,
+ poll_info: &MessageInfo,
+ vote: &PollVoteMessage,
+ ) -> Result<PollUpdateMessage, ClientError> {
+ let own_id = if poll_info.sender.server == DEFAULT_USER_SERVER {
+ self.get_own_id().await
+ } else {
+ self.get_own_lid().await
+ };
+ let (ciphertext, iv) = self
+ .encrypt_msg_secret(
+ &own_id,
+ &poll_info.chat,
+ &poll_info.sender,
+ &poll_info.id,
+ MsgSecretType::PollVote,
+ &vote.encode_to_vec(),
+ )
+ .await
+ .map_err(|error| error.wrap("failed to encrypt poll vote"))?;
+ Ok(PollUpdateMessage {
+ poll_creation_message_key: Some(get_key_from_info(poll_info)),
+ vote: Some(PollEncValue {
+ enc_payload: Some(ciphertext),
+ enc_iv: Some(iv),
+ }),
+ sender_timestamp_ms: Some(Utc::now().timestamp_millis()),
+ ..Default::default()
+ })
+ }
+
+ /// Encrypts a comment on a message (`EncryptComment`).
+ pub async fn encrypt_comment(
+ &self,
+ root_message_info: &MessageInfo,
+ comment: &wa_e2e::Message,
+ ) -> Result<wa_e2e::Message, ClientError> {
+ let own_lid = self.get_own_lid().await;
+ let (ciphertext, iv) = self
+ .encrypt_msg_secret(
+ &own_lid,
+ &root_message_info.chat,
+ &root_message_info.sender,
+ &root_message_info.id,
+ MsgSecretType::Comment,
+ &comment.encode_to_vec(),
+ )
+ .await
+ .map_err(|error| error.wrap("failed to encrypt comment"))?;
+ Ok(wa_e2e::Message {
+ enc_comment_message: Some(EncCommentMessage {
+ target_message_key: Some(MessageKey {
+ remote_jid: Some(root_message_info.chat.to_string()),
+ participant: Some(root_message_info.sender.to_non_ad().to_string()),
+ from_me: Some(root_message_info.is_from_me),
+ id: Some(root_message_info.id.clone()),
+ }),
+ enc_payload: Some(ciphertext),
+ enc_iv: Some(iv),
+ }),
+ ..Default::default()
+ })
+ }
+
+ /// Encrypts a reaction to a message (`EncryptReaction`); the reaction's
+ /// key becomes the target key.
+ pub async fn encrypt_reaction(
+ &self,
+ root_message_info: &MessageInfo,
+ mut reaction: ReactionMessage,
+ ) -> Result<EncReactionMessage, ClientError> {
+ let reaction_key = reaction.key.take();
+ let own_lid = self.get_own_lid().await;
+ let (ciphertext, iv) = self
+ .encrypt_msg_secret(
+ &own_lid,
+ &root_message_info.chat,
+ &root_message_info.sender,
+ &root_message_info.id,
+ MsgSecretType::Reaction,
+ &reaction.encode_to_vec(),
+ )
+ .await
+ .map_err(|error| error.wrap("failed to encrypt reaction"))?;
+ Ok(EncReactionMessage {
+ target_message_key: reaction_key,
+ enc_payload: Some(ciphertext),
+ enc_iv: Some(iv),
+ })
+ }
+}
+
+/// Encrypts with the secret of an original message and a given IV, as
+/// `encryptMsgSecret` does after loading the secret. `original_sender` is
+/// the sender the secret was stored under.
+pub fn encrypt_msg_secret_with(
+ own_id: &Jid,
+ original_sender: &Jid,
+ original_message_id: &str,
+ use_case: MsgSecretType,
+ base_key: &[u8],
+ iv: &[u8; 12],
+ plaintext: &[u8],
+) -> Result<Vec<u8>, ClientError> {
+ let (secret_key, additional_data) = generate_msg_secret_key(
+ use_case,
+ own_id,
+ original_message_id,
+ original_sender,
+ base_key,
+ );
+ gcmutil::encrypt(&secret_key, iv, plaintext, &additional_data)
+ .map_err(|error| ClientError::Other(format!("failed to encrypt secret message: {error}")))
+}
+
+#[cfg(test)]
+mod test;
diff --git a/crates/whatsmeow/src/msgsecret/test.rs b/crates/whatsmeow/src/msgsecret/test.rs
new file mode 100644
index 0000000000..55ff4eae1e
--- /dev/null
+++ b/crates/whatsmeow/src/msgsecret/test.rs
@@ -0,0 +1,106 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+//! Message secret keys against whatsmeow's output, and an encrypted
+//! reaction round trip through the store.
+
+use super::*;
+use crate::client::test::harness;
+use crate::store::MsgSecretStore;
+use crate::types::MessageSource;
+use crate::vectors::Vectors;
+
+#[test]
+fn secret_keys_match_go() {
+ let vectors = Vectors::load("pairing_media.json");
+ let secret = vectors.bytes("msg_secret");
+ let sender = parse_jid("9876:5@lid").unwrap();
+ let original_sender = parse_jid("777:2@lid").unwrap();
+ for (use_case, name) in [
+ (MsgSecretType::Reaction, "Enc Reaction"),
+ (MsgSecretType::PollVote, "Poll Vote"),
+ (MsgSecretType::MessageEdit, "Message Edit"),
+ ] {
+ let (key, additional) =
+ generate_msg_secret_key(use_case, &sender, "ORIG1", &original_sender, &secret);
+ assert_eq!(key, vectors.bytes(&format!("msg_secret_key_{name}")));
+ assert_eq!(additional, vectors.bytes(&format!("msg_secret_ad_{name}")));
+ }
+ let hashes: Vec<String> = hash_poll_options(&["yes".to_owned(), "no".to_owned()])
+ .iter()
+ .map(hex::encode)
+ .collect();
+ let expected: Vec<String> = vectors
+ .value("poll_option_hashes")
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|value| value.as_str().unwrap().to_owned())
+ .collect();
+ assert_eq!(hashes, expected);
+}
+
+#[tokio::test(start_paused = true)]
+async fn an_encrypted_reaction_decrypts_for_the_other_side() {
+ let harness = harness(Some(("1234:[email protected]", "9876:5@lid")));
+ let group = parse_jid("[email protected]").unwrap();
+ let author = parse_jid("777@lid").unwrap();
+ harness
+ .store
+ .put_message_secret(&group, &author, &"ORIG1".to_owned(), vec![9; 32])
+ .await
+ .unwrap();
+ let root = MessageInfo {
+ source: MessageSource {
+ chat: group.clone(),
+ sender: author.clone(),
+ is_group: true,
+ ..Default::default()
+ },
+ id: "ORIG1".to_owned(),
+ ..Default::default()
+ };
+ let key = MessageKey {
+ remote_jid: Some(group.to_string()),
+ from_me: Some(false),
+ id: Some("ORIG1".to_owned()),
+ participant: Some(author.to_string()),
+ };
+ let encrypted = harness
+ .client
+ .encrypt_reaction(
+ &root,
+ ReactionMessage {
+ key: Some(key),
+ text: Some("👍".to_owned()),
+ ..Default::default()
+ },
+ )
+ .await
+ .unwrap();
+ // Received in the group from our LID: decrypting finds the same secret.
+ let received = Message {
+ info: MessageInfo {
+ source: MessageSource {
+ chat: group,
+ sender: parse_jid("9876:5@lid").unwrap(),
+ is_group: true,
+ ..Default::default()
+ },
+ id: "R1".to_owned(),
+ ..Default::default()
+ },
+ message: Some(wa_e2e::Message {
+ enc_reaction_message: Some(encrypted),
+ ..Default::default()
+ }),
+ ..Default::default()
+ };
+ let reaction = harness.client.decrypt_reaction(&received).await.unwrap();
+ assert_eq!(reaction.text.as_deref(), Some("👍"));
+ assert!(matches!(
+ harness.client.decrypt_comment(&received).await,
+ Err(ClientError::NotEncryptedCommentMessage)
+ ));
+}
diff --git a/crates/whatsmeow/src/notification.rs b/crates/whatsmeow/src/notification.rs
new file mode 100644
index 0000000000..db4239ab3c
--- /dev/null
+++ b/crates/whatsmeow/src/notification.rs
@@ -0,0 +1,445 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+//
+// Ported from whatsmeow notification.go (MPL-2.0, Copyright (c) Tulir Asokan)
+//
+// Not ported: the newsletter, mex and FB device list notifications (features
+// the port skips).
+
+//! Handling of `<notification>` nodes.
+
+use std::sync::Arc;
+
+use crate::binary::{Node, NodeContent};
+use crate::client::Client;
+use crate::group::GroupNotification;
+use crate::send::participant_list_hash_v2;
+use crate::store::PrivacyToken;
+use crate::types::events::{
+ Blocklist, BlocklistAction, BlocklistChange, BlocklistChangeAction, Event, IdentityChange,
+ Picture, UserAbout,
+};
+use crate::types::{Jid, SERVER_JID};
+
+impl Client {
+ async fn handle_encrypt_notification(self: &Arc<Self>, node: &Node) {
+ let from = node.attr_getter().jid("from");
+ if from == *SERVER_JID {
+ let count = node.get_child_by_tag(&["count"]);
+ let mut attrs = count.attr_getter();
+ let otks_left = attrs.int("value");
+ if !attrs.ok() {
+ tracing::warn!("didn't get number of OTKs left in encryption notification");
+ return;
+ }
+ tracing::info!(otks_left, "got prekey count from server");
+ if otks_left < crate::prekeys::MIN_PRE_KEY_COUNT as i64 {
+ self.upload_pre_keys(false).await;
+ }
+ } else if node.get_optional_child_by_tag(&["identity"]).is_some() {
+ tracing::debug!(
+ "got identity change, deleting all identities/sessions for that number"
+ );
+ let (identities, sessions, privacy_tokens) = {
+ let store = self.store.read().await;
+ (
+ Arc::clone(&store.identities),
+ Arc::clone(&store.sessions),
+ Arc::clone(&store.privacy_tokens),
+ )
+ };
+ if let Err(error) = identities.delete_all_identities(&from.user).await {
+ tracing::warn!(error = %error, "failed to delete all identities from store after identity change");
+ }
+ if let Err(error) = sessions.delete_all_sessions(&from.user).await {
+ tracing::warn!(error = %error, "failed to delete all sessions from store after identity change");
+ }
+ let timestamp = node.attr_getter().unix_time("t");
+ let storage_lid = self.resolve_tc_token_storage_lid(&from).await;
+ let stored_sender_timestamp = match privacy_tokens.get_privacy_token(&storage_lid).await
+ {
+ Ok(token) => token.and_then(|token| token.sender_timestamp),
+ Err(error) => {
+ tracing::debug!(error = %error, "failed to load tctoken for identity change re-issue");
+ None
+ }
+ };
+ if self.validate_and_set_tc_token_sender_ts(&storage_lid, stored_sender_timestamp)
+ && let Some(sender_timestamp) = self.get_tc_token_sender_ts(&storage_lid)
+ {
+ tracing::debug!("identity changed, re-issuing tctoken");
+ let client = Arc::clone(self);
+ self.spawn(async move {
+ client
+ .issue_privacy_token_and_save(storage_lid, sender_timestamp)
+ .await;
+ });
+ }
+ self.dispatch_event(Event::IdentityChange(IdentityChange {
+ jid: from,
+ timestamp,
+ implicit: false,
+ }))
+ .await;
+ } else {
+ tracing::debug!("got unknown encryption notification from server");
+ }
+ }
+
+ async fn handle_picture_notification(&self, node: &Node) {
+ let timestamp = node.attr_getter().unix_time("t");
+ for child in node.get_children() {
+ let mut attrs = child.attr_getter();
+ let mut event = Picture {
+ timestamp,
+ jid: attrs.jid("jid"),
+ author: attrs.optional_jid_or_empty("author"),
+ ..Picture::default()
+ };
+ match child.tag.as_str() {
+ "delete" => event.remove = true,
+ // Sometimes there's a hash and no ID on "set".
+ "add" | "set" => event.picture_id = attrs.string("id"),
+ _ => continue,
+ }
+ if !attrs.ok() {
+ tracing::debug!(error = ?attrs.error().err(), "ignoring picture change notification with unexpected attributes");
+ continue;
+ }
+ self.dispatch_event(Event::Picture(event)).await;
+ }
+ }
+
+ async fn handle_device_notification(&self, node: &Node) {
+ let mut cache = self.user_devices_cache.lock().await;
+ let mut attrs = node.attr_getter();
+ let from = attrs.jid("from");
+ let from_lid = attrs.optional_jid("lid");
+ if let Some(from_lid) = &from_lid {
+ self.store_lid_pn_mapping(from_lid, &from).await;
+ }
+ let Some(mut cached) = cache.get(&from).cloned() else {
+ tracing::debug!("no device list cached, ignoring device list notification");
+ return;
+ };
+ let mut cached_lid = from_lid
+ .as_ref()
+ .and_then(|lid| cache.get(lid).cloned())
+ .unwrap_or_default();
+ for child in node.get_children() {
+ let mut child_attrs = child.attr_getter();
+ let device_hash = child_attrs.string("device_hash");
+ let device_lid_hash = child_attrs.optional_string("device_lid_hash");
+ let device_child = child.get_child_by_tag(&["device"]);
+ let mut device_attrs = device_child.attr_getter();
+ let changed_device_jid = device_attrs.jid("jid");
+ let changed_device_lid = device_attrs.optional_jid("lid");
+ match child.tag.as_str() {
+ "add" => {
+ cached.devices.push(changed_device_jid);
+ if let Some(lid) = &changed_device_lid {
+ cached_lid.devices.push(lid.clone());
+ }
+ }
+ "remove" => {
+ cached
+ .devices
+ .retain(|existing| *existing != changed_device_jid);
+ if let Some(lid) = &changed_device_lid {
+ cached_lid.devices.retain(|existing| existing != lid);
+ }
+ }
+ "update" => {
+ // The exact meaning of "update" is unknown; clear the
+ // device list cache to be safe.
+ tracing::debug!("device list updated, dropping cached devices");
+ cache.remove(&from);
+ continue;
+ }
+ other => {
+ tracing::debug!(tag = other, "unknown device list change tag");
+ continue;
+ }
+ }
+ if participant_list_hash_v2(&cached.devices) == device_hash {
+ tracing::debug!(tag = %child.tag, "device list hash changed, new hash matches");
+ cache.insert(from.clone(), cached.clone());
+ } else {
+ tracing::warn!(tag = %child.tag, "device list hash changed, new hash doesn't match");
+ cache.remove(&from);
+ }
+ if let (Some(from_lid), Some(_)) = (&from_lid, &changed_device_lid)
+ && !device_lid_hash.is_empty()
+ {
+ if participant_list_hash_v2(&cached_lid.devices) == device_lid_hash {
+ tracing::debug!(tag = %child.tag, "LID device list hash changed, new hash matches");
+ cache.insert(from_lid.clone(), cached_lid.clone());
+ } else {
+ tracing::warn!(tag = %child.tag, "LID device list hash changed, new hash doesn't match");
+ cache.remove(from_lid);
+ }
+ }
+ }
+ }
+
+ async fn handle_own_devices_notification(&self, node: &Node, from_jid: &Jid) {
+ let mut cache = self.user_devices_cache.lock().await;
+ let own_lid = self.get_own_lid().await.to_non_ad();
+ let own_id = self.get_own_id().await.to_non_ad();
+ if own_id.is_empty() {
+ tracing::debug!("ignoring own device change notification, session was deleted");
+ return;
+ }
+ let from_jid_plain = from_jid.to_non_ad();
+ let alt_jid = if from_jid_plain == own_id {
+ own_lid.clone()
+ } else if from_jid_plain == own_lid {
+ own_id.clone()
+ } else {
+ tracing::warn!("unexpected own device notification sender");
+ return;
+ };
+ let expected_new_hash = node.attr_getter().string("dhash");
+ let mut new_device_list = Vec::new();
+ let mut alt_device_list = Vec::new();
+ for child in node.get_children() {
+ let jid = child.attr_getter().jid("jid");
+ if child.tag == "device" && !jid.is_empty() {
+ let mut alt_device_jid = alt_jid.clone();
+ alt_device_jid.device = jid.device;
+ new_device_list.push(jid);
+ alt_device_list.push(alt_device_jid);
+ }
+ }
+ let new_hash = participant_list_hash_v2(&new_device_list);
+ if new_hash != expected_new_hash {
+ tracing::debug!(
+ "received own device list change notification, but the hash didn't match"
+ );
+ cache.remove(&own_id);
+ cache.remove(&own_lid);
+ } else {
+ tracing::debug!("received own device list change notification");
+ let alt_hash = participant_list_hash_v2(&alt_device_list);
+ cache.insert(
+ from_jid_plain,
+ crate::client::DeviceCache {
+ devices: new_device_list,
+ dhash: expected_new_hash,
+ },
+ );
+ cache.insert(
+ alt_jid,
+ crate::client::DeviceCache {
+ devices: alt_device_list,
+ dhash: alt_hash,
+ },
+ );
+ }
+ }
+
+ async fn handle_blocklist(&self, node: &Node) {
+ let mut attrs = node.attr_getter();
+ let mut event = Blocklist {
+ action: BlocklistAction::from(attrs.optional_string("action")),
+ d_hash: attrs.string("dhash"),
+ prev_d_hash: attrs.optional_string("prev_dhash"),
+ changes: Vec::new(),
+ };
+ for child in node.get_children() {
+ let mut child_attrs = child.attr_getter();
+ let change = BlocklistChange {
+ jid: child_attrs.jid("jid"),
+ action: BlocklistChangeAction::from(child_attrs.string("action")),
+ };
+ if !child_attrs.ok() {
+ tracing::warn!("unexpected data in blocklist event child");
+ continue;
+ }
+ event.changes.push(change);
+ }
+ self.dispatch_event(Event::Blocklist(event)).await;
+ }
+
+ async fn handle_account_sync_notification(self: &Arc<Self>, node: &Node) {
+ for child in node.get_children() {
+ match child.tag.as_str() {
+ "privacy" => self.handle_privacy_settings_notification(child).await,
+ "devices" => {
+ let from = node.attr_getter().jid("from");
+ self.handle_own_devices_notification(child, &from).await;
+ }
+ "picture" => {
+ let event = Picture {
+ timestamp: node.attr_getter().unix_time("t"),
+ jid: self.get_own_id().await.to_non_ad(),
+ ..Picture::default()
+ };
+ self.dispatch_event(Event::Picture(event)).await;
+ }
+ "blocklist" => self.handle_blocklist(child).await,
+ other => tracing::debug!(tag = other, "unhandled account sync item"),
+ }
+ }
+ }
+
+ async fn handle_privacy_token_notification(&self, node: &Node) {
+ if self.get_own_id().await.is_empty() {
+ tracing::debug!("ignoring privacy token notification, session was deleted");
+ return;
+ }
+ let tokens = node.get_child_by_tag(&["tokens"]);
+ if tokens.tag != "tokens" {
+ tracing::warn!("privacy_token notification didn't contain <tokens> tag");
+ return;
+ }
+ let mut parent_attrs = node.attr_getter();
+ let sender = parent_attrs.jid("from").to_non_ad();
+ let mut sender_lid = parent_attrs.optional_jid_or_empty("sender_lid").to_non_ad();
+ if !parent_attrs.ok() {
+ tracing::warn!("privacy_token notification didn't have a sender");
+ return;
+ }
+ if sender_lid.is_empty() {
+ sender_lid = self.resolve_tc_token_storage_lid(&sender).await;
+ }
+ let privacy_tokens = Arc::clone(&self.store.read().await.privacy_tokens);
+ for child in tokens.get_children() {
+ let mut attrs = child.attr_getter();
+ if child.tag != "token" {
+ tracing::warn!(tag = %child.tag, "privacy_token notification contained unexpected tag");
+ continue;
+ }
+ let token_type = attrs.string("type");
+ if token_type != "trusted_contact" {
+ tracing::warn!(token_type = %token_type, "privacy_token notification contained unexpected token type");
+ continue;
+ }
+ let Some(NodeContent::Bytes(token)) = &child.content else {
+ tracing::warn!("privacy_token notification contained non-binary token");
+ continue;
+ };
+ let timestamp = attrs.unix_time("t");
+ if !attrs.ok() {
+ tracing::warn!("privacy_token notification is missing some fields");
+ }
+ let result = privacy_tokens
+ .put_privacy_tokens(&[PrivacyToken {
+ user: sender_lid.clone(),
+ token: token.clone(),
+ timestamp: timestamp.unwrap_or_default(),
+ sender_timestamp: None,
+ }])
+ .await;
+ match result {
+ Err(error) => tracing::error!(error = %error, "failed to save privacy token"),
+ Ok(()) => tracing::debug!("received privacy token"),
+ }
+ }
+ }
+
+ async fn handle_status_notification(&self, node: &Node) {
+ let mut attrs = node.attr_getter();
+ let Some(child) = node.get_optional_child_by_tag(&["set"]) else {
+ tracing::debug!("status notification did not contain child with tag 'set'");
+ return;
+ };
+ let Some(NodeContent::Bytes(status)) = &child.content else {
+ tracing::warn!("set status notification has unexpected content");
+ return;
+ };
+ let event = UserAbout {
+ jid: attrs.jid("from"),
+ timestamp: attrs.unix_time("t"),
+ status: String::from_utf8_lossy(status).into_owned(),
+ };
+ self.dispatch_event(Event::UserAbout(event)).await;
+ }
+
+ /// Emits the group event of a `w:gp2` notification after storing the
+ /// LID mappings and redacted phones it carries; returns whether a
+ /// handler failed (so the notification isn't acked).
+ async fn handle_group_notification(&self, node: &Node) -> bool {
+ let (event, lid_pairs, redacted_phones) = match self.parse_group_notification(node).await {
+ Ok(parsed) => parsed,
+ Err(error) => {
+ tracing::error!(error = %error, "failed to parse group notification");
+ return false;
+ }
+ };
+ let (lids, contacts) = {
+ let store = self.store.read().await;
+ (Arc::clone(&store.lids), Arc::clone(&store.contacts))
+ };
+ if let Err(error) = lids.put_many_lid_mappings(&lid_pairs).await {
+ tracing::error!(error = %error, "failed to store LID mappings from group notification");
+ }
+ if let Err(error) = contacts.put_many_redacted_phones(&redacted_phones).await {
+ tracing::warn!(error = %error, "failed to store redacted phones from group notification");
+ }
+ self.dispatch_event(match event {
+ GroupNotification::Joined(joined) => Event::JoinedGroup(joined),
+ GroupNotification::Change(change) => Event::GroupInfo(change),
+ })
+ .await
+ }
+
+ pub(crate) async fn handle_notification(self: &Arc<Self>, node: &Node) {
+ let mut cancelled = false;
+ let ack = self.maybe_deferred_ack(node);
+ let mut attrs = node.attr_getter();
+ let notification_type = attrs.string("type");
+ if attrs.ok() {
+ match notification_type.as_str() {
+ "encrypt" => {
+ let client = Arc::clone(self);
+ let node = node.clone();
+ self.spawn(async move { client.handle_encrypt_notification(&node).await });
+ }
+ "server_sync" => {
+ let client = Arc::clone(self);
+ let node = node.clone();
+ self.spawn(async move { client.handle_app_state_notification(&node).await });
+ }
+ "account_sync" => {
+ let client = Arc::clone(self);
+ let node = node.clone();
+ self.spawn(async move { client.handle_account_sync_notification(&node).await });
+ }
+ "devices" => self.handle_device_notification(node).await,
+ "w:gp2" => cancelled = self.handle_group_notification(node).await,
+ "picture" => self.handle_picture_notification(node).await,
+ "privacy_token" => self.handle_privacy_token_notification(node).await,
+ "status" => self.handle_status_notification(node).await,
+ "mediaretry" => self.handle_media_retry_notification(node).await,
+ "link_code_companion_reg" => {
+ let client = Arc::clone(self);
+ self.spawn(client.try_handle_code_pair_notification(node.clone()));
+ }
+ "passkey_prologue_request" => self.handle_passkey_notification(node).await,
+ "crsc_continuation" => {
+ let client = Arc::clone(self);
+ self.spawn(client.try_handle_passkey_continuation_notification(node.clone()));
+ }
+ "companion_reg_refresh" => {
+ let refresh = node
+ .get_optional_child_by_tag(&["companion_reg_refresh"])
+ .is_some();
+ let rotate_qr = node
+ .get_optional_child_by_tag(&["pair-device-rotate-qr"])
+ .is_some();
+ if refresh || rotate_qr {
+ self.rotate_adv_secret().await;
+ } else {
+ tracing::debug!("unrecognized companion reg refresh notification");
+ }
+ }
+ // Other types: business, disappearing_mode, server, pay, psa,
+ // and the ones the port skips.
+ other => tracing::debug!(notification_type = other, "unhandled notification"),
+ }
+ }
+ self.finish_deferred_ack(ack, cancelled).await;
+ }
+}
diff --git a/crates/whatsmeow/src/pair.rs b/crates/whatsmeow/src/pair.rs
new file mode 100644
index 0000000000..597eded4ce
--- /dev/null
+++ b/crates/whatsmeow/src/pair.rs
@@ -0,0 +1,512 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+//
+// Ported from whatsmeow pair.go (MPL-2.0, Copyright (c) Tulir Asokan)
+//
+// `makeQRData` and `getQRClientType` take the client's inputs as parameters
+// ([`make_qr_data`], [`get_qr_client_type`]) so they are testable alone.
+
+//! QR code pairing.
+
+use std::sync::Arc;
+use std::sync::atomic::Ordering;
+
+use base64::Engine;
+use base64::engine::general_purpose::STANDARD;
+use hmac::{Hmac, Mac};
+use prost::Message;
+use sha2::Sha256;
+
+use crate::binary::{Attrs, Node, NodeContent};
+use crate::client::Client;
+use crate::errors::ClientError;
+use crate::pair_code::PairClientType;
+use crate::proto::wa_adv::{
+ AdvDeviceIdentity, AdvEncryptionType, AdvSignedDeviceIdentity, AdvSignedDeviceIdentityHmac,
+};
+use crate::proto::wa_companion_reg::ClientPairingProps;
+use crate::proto::wa_companion_reg::device_props::PlatformType;
+use crate::proto::wa_wa6::client_payload::user_agent::Platform;
+use crate::signal::CurveSignatures;
+use crate::store::{Device, base_client_payload, device_props};
+use crate::types::events::{Event, PairError, PairSuccess, Qr, RotateAdvSecret};
+use crate::types::{Jid, SERVER_JID};
+use crate::util::keys::KeyPair;
+
+/// The prefix of the message the primary device's account key signs.
+pub const ADV_ACCOUNT_SIGNATURE_PREFIX: [u8; 2] = [6, 0];
+/// The prefix of the message the companion's identity key signs.
+pub const ADV_DEVICE_SIGNATURE_PREFIX: [u8; 2] = [6, 1];
+/// [`ADV_ACCOUNT_SIGNATURE_PREFIX`] for hosted accounts.
+pub const ADV_HOSTED_ACCOUNT_SIGNATURE_PREFIX: [u8; 2] = [6, 5];
+/// [`ADV_DEVICE_SIGNATURE_PREFIX`] for hosted accounts.
+pub const ADV_HOSTED_DEVICE_SIGNATURE_PREFIX: [u8; 2] = [6, 6];
+
+/// The client type the QR code announces: the override if set, else derived
+/// from the device props platform, else from the user agent platform. Go
+/// reads the override from `Client.QRClientType`.
+pub fn get_qr_client_type(client_type_override: Option<PairClientType>) -> PairClientType {
+ if let Some(client_type) = client_type_override {
+ return client_type;
+ }
+ let platform_type = device_props()
+ .platform_type
+ .and_then(|value| PlatformType::try_from(value).ok());
+ match platform_type {
+ Some(PlatformType::Chrome) => return PairClientType::Chrome,
+ Some(PlatformType::Firefox) => return PairClientType::Firefox,
+ Some(PlatformType::Edge) => return PairClientType::Edge,
+ Some(PlatformType::Ie) => return PairClientType::Ie,
+ Some(PlatformType::Opera) => return PairClientType::Opera,
+ Some(PlatformType::Safari) => return PairClientType::Safari,
+ Some(PlatformType::Uwp) => return PairClientType::Uwp,
+ Some(PlatformType::AndroidPhone) => return PairClientType::Android,
+ _ => {}
+ }
+ let platform = base_client_payload()
+ .user_agent
+ .and_then(|user_agent| user_agent.platform)
+ .and_then(|value| Platform::try_from(value).ok());
+ match platform {
+ Some(Platform::Web) => PairClientType::OtherWebClient,
+ Some(Platform::Macos) => PairClientType::MacOs,
+ _ => PairClientType::Unknown,
+ }
+}
+
+/// The contents of one pairing QR code: a link carrying the server's
+/// reference, the device's noise and identity keys, its ADV secret, and the
+/// client type. Go's `Client.makeQRData` reads the keys from `Client.Store`.
+pub fn make_qr_data(store: &Device, reference: &[u8], client_type: PairClientType) -> String {
+ format!(
+ "https://wa.me/settings/linked_devices#{},{},{},{},{}",
+ String::from_utf8_lossy(reference),
+ STANDARD.encode(store.noise_key.public),
+ STANDARD.encode(store.identity_key.public),
+ STANDARD.encode(&store.adv_secret_key),
+ client_type,
+ )
+}
+
+/// Concatenates byte slices.
+pub fn concat_bytes(data: &[&[u8]]) -> Vec<u8> {
+ data.concat()
+}
+
+/// Whether the primary device's account key signed this device's identity
+/// details and identity key.
+pub fn verify_account_signature(
+ device_identity: &AdvSignedDeviceIdentity,
+ identity_key: &KeyPair,
+ is_hosted: bool,
+ signatures: &dyn CurveSignatures,
+) -> bool {
+ let (Some(signature_key), Some(signature)) = (
+ device_identity.account_signature_key.as_deref(),
+ device_identity.account_signature.as_deref(),
+ ) else {
+ return false;
+ };
+ let (Ok(signature_key), Ok(signature)) = (
+ <&[u8; 32]>::try_from(signature_key),
+ <&[u8; 64]>::try_from(signature),
+ ) else {
+ return false;
+ };
+ let prefix = if is_hosted {
+ ADV_HOSTED_ACCOUNT_SIGNATURE_PREFIX
+ } else {
+ ADV_ACCOUNT_SIGNATURE_PREFIX
+ };
+ let message = concat_bytes(&[
+ &prefix,
+ device_identity.details.as_deref().unwrap_or_default(),
+ &identity_key.public,
+ ]);
+ signatures.verify_signature(signature_key, &message, signature)
+}
+
+/// This device's signature over its identity details, identity key and the
+/// account key, sent back to confirm the pairing.
+pub fn generate_device_signature(
+ device_identity: &AdvSignedDeviceIdentity,
+ identity_key: &KeyPair,
+ signatures: &dyn CurveSignatures,
+) -> [u8; 64] {
+ let message = concat_bytes(&[
+ &ADV_DEVICE_SIGNATURE_PREFIX,
+ device_identity.details.as_deref().unwrap_or_default(),
+ &identity_key.public,
+ device_identity
+ .account_signature_key
+ .as_deref()
+ .unwrap_or_default(),
+ ]);
+ signatures.calculate_signature(&identity_key.private, &message)
+}
+
+fn bytes_content(node: &Node) -> Vec<u8> {
+ match &node.content {
+ Some(NodeContent::Bytes(bytes)) => bytes.clone(),
+ _ => Vec::new(),
+ }
+}
+
+fn string_attr(node: &Node, key: &str) -> String {
+ match node.attrs.get(key) {
+ Some(crate::binary::AttributeValue::String(value)) => value.clone(),
+ _ => String::new(),
+ }
+}
+
+fn jid_attr(node: &Node, key: &str) -> Jid {
+ match node.attrs.get(key) {
+ Some(crate::binary::AttributeValue::Jid(value)) => value.clone(),
+ _ => Jid::default(),
+ }
+}
+
+impl Client {
+ pub(crate) async fn handle_iq(self: &Arc<Self>, node: &Node) {
+ let children = node.get_children();
+ let from_server = matches!(
+ node.attrs.get("from"),
+ Some(crate::binary::AttributeValue::Jid(from)) if *from == *SERVER_JID
+ );
+ if children.len() != 1 || !from_server {
+ return;
+ }
+ match children[0].tag.as_str() {
+ "pair-device" => self.handle_pair_device(node).await,
+ "pair-success" => self.handle_pair_success(node).await,
+ _ => {}
+ }
+ }
+
+ async fn handle_pair_device(self: &Arc<Self>, node: &Node) {
+ self.paired.store(false, Ordering::SeqCst);
+ let pair_device = node.get_child_by_tag(&["pair-device"]);
+ let mut attrs = Attrs::from([("type".to_owned(), "result".into())]);
+ if let Some(from) = node.attrs.get("from") {
+ attrs.insert("to".to_owned(), from.clone());
+ }
+ if let Some(id) = node.attrs.get("id") {
+ attrs.insert("id".to_owned(), id.clone());
+ }
+ let ack = Node {
+ tag: "iq".to_owned(),
+ attrs,
+ content: None,
+ };
+ if let Err(error) = self.send_node(&ack).await {
+ tracing::warn!(error = %error, "failed to send acknowledgement for pair-device request");
+ }
+
+ let client_type = get_qr_client_type(self.config.qr_client_type);
+ let mut codes = Vec::with_capacity(pair_device.get_children().len());
+ {
+ let store = self.store.read().await;
+ for (index, child) in pair_device.get_children().iter().enumerate() {
+ if child.tag != "ref" {
+ tracing::warn!(tag = %child.tag, index, "pair-device node contains unexpected child tag");
+ continue;
+ }
+ let Some(NodeContent::Bytes(content)) = &child.content else {
+ tracing::warn!(
+ index,
+ "pair-device node contains unexpected child content type"
+ );
+ continue;
+ };
+ codes.push(make_qr_data(&store, content, client_type));
+ }
+ }
+ self.dispatch_event(Event::Qr(Qr { codes })).await;
+ }
+
+ /// Replaces the ADV secret, for `companion_reg_refresh` notifications.
+ pub(crate) async fn rotate_adv_secret(self: &Arc<Self>) {
+ let new_secret: [u8; 32] = rand::random();
+ let old_secret = {
+ let mut store = self.store.write().await;
+ std::mem::replace(&mut store.adv_secret_key, new_secret.to_vec())
+ };
+ self.dispatch_event(Event::RotateAdvSecret(RotateAdvSecret {
+ old_secret: STANDARD.encode(old_secret),
+ new_secret: STANDARD.encode(new_secret),
+ }))
+ .await;
+ }
+
+ async fn handle_pair_success(self: &Arc<Self>, node: &Node) {
+ if let Some(server_time) = node.attr_getter().unix_time("t") {
+ let offset = (server_time.timestamp() - chrono::Utc::now().timestamp()) * 1_000_000_000;
+ self.server_time_offset.store(offset, Ordering::SeqCst);
+ }
+ let id = string_attr(node, "id");
+ let pair_success = node.get_child_by_tag(&["pair-success"]);
+
+ let device_identity_bytes =
+ bytes_content(pair_success.get_child_by_tag(&["device-identity"]));
+ let business_name = string_attr(pair_success.get_child_by_tag(&["biz"]), "name");
+ let jid = jid_attr(pair_success.get_child_by_tag(&["device"]), "jid");
+ let lid = jid_attr(pair_success.get_child_by_tag(&["device"]), "lid");
+ let platform = string_attr(pair_success.get_child_by_tag(&["platform"]), "name");
+ let client_props_bytes = bytes_content(pair_success.get_child_by_tag(&["client-props"]));
+ let props =
+ ClientPairingProps::decode(client_props_bytes.as_slice()).unwrap_or_else(|error| {
+ tracing::warn!(error = %error, "failed to parse client pairing props");
+ ClientPairingProps::default()
+ });
+
+ let client = Arc::clone(self);
+ self.spawn(async move {
+ let result = client
+ .handle_pair(
+ &device_identity_bytes,
+ &id,
+ &business_name,
+ &platform,
+ &jid,
+ &lid,
+ )
+ .await;
+ match result {
+ Err(error) => {
+ tracing::error!(error = %error, "failed to pair device");
+ client.disconnect().await;
+ client
+ .dispatch_event(Event::PairError(PairError {
+ id: jid,
+ lid,
+ business_name,
+ platform,
+ props,
+ error: Arc::new(error),
+ }))
+ .await;
+ }
+ Ok(()) => {
+ tracing::info!("successfully paired");
+ let unified = Arc::clone(&client);
+ client.spawn(async move { unified.send_unified_session().await });
+ client
+ .dispatch_event(Event::PairSuccess(PairSuccess {
+ id: jid,
+ lid,
+ business_name,
+ platform,
+ props,
+ }))
+ .await;
+ }
+ }
+ });
+ }
+
+ #[tracing::instrument(name = "whatsmeow.pair", skip_all, err)]
+ async fn handle_pair(
+ &self,
+ device_identity_bytes: &[u8],
+ request_id: &str,
+ business_name: &str,
+ platform: &str,
+ jid: &Jid,
+ lid: &Jid,
+ ) -> Result<(), ClientError> {
+ let container = match AdvSignedDeviceIdentityHmac::decode(device_identity_bytes) {
+ Ok(container) => container,
+ Err(error) => {
+ self.send_pair_error(request_id, 500, "internal-error")
+ .await;
+ return Err(ClientError::PairProto {
+ message: "failed to parse device identity container in pair success message"
+ .to_owned(),
+ source: error.into(),
+ });
+ }
+ };
+
+ let (adv_secret_key, identity_key) = {
+ let store = self.store.read().await;
+ (store.adv_secret_key.clone(), store.identity_key.clone())
+ };
+ // HMAC accepts keys of any length.
+ let mut mac = <Hmac<Sha256> as Mac>::new_from_slice(&adv_secret_key)
+ .map_err(|error| ClientError::Other(error.to_string()))?;
+ if container.account_type == Some(AdvEncryptionType::Hosted as i32) {
+ mac.update(&ADV_HOSTED_ACCOUNT_SIGNATURE_PREFIX);
+ }
+ mac.update(container.details.as_deref().unwrap_or_default());
+ if mac
+ .verify_slice(container.hmac.as_deref().unwrap_or_default())
+ .is_err()
+ {
+ tracing::warn!("invalid HMAC from pair success message");
+ self.send_pair_error(request_id, 401, "hmac-mismatch").await;
+ return Err(ClientError::PairInvalidDeviceIdentityHmac);
+ }
+
+ let mut device_identity =
+ match AdvSignedDeviceIdentity::decode(container.details.as_deref().unwrap_or_default())
+ {
+ Ok(identity) => identity,
+ Err(error) => {
+ self.send_pair_error(request_id, 500, "internal-error")
+ .await;
+ return Err(ClientError::PairProto {
+ message: "failed to parse signed device identity in pair success message"
+ .to_owned(),
+ source: error.into(),
+ });
+ }
+ };
+
+ let device_identity_details =
+ match AdvDeviceIdentity::decode(device_identity.details.as_deref().unwrap_or_default())
+ {
+ Ok(details) => details,
+ Err(error) => {
+ self.send_pair_error(request_id, 500, "internal-error")
+ .await;
+ return Err(ClientError::PairProto {
+ message: "failed to parse device identity details in pair success message"
+ .to_owned(),
+ source: error.into(),
+ });
+ }
+ };
+
+ let is_hosted =
+ device_identity_details.device_type == Some(AdvEncryptionType::Hosted as i32);
+ if !verify_account_signature(
+ &device_identity,
+ &identity_key,
+ is_hosted,
+ self.signatures(),
+ ) {
+ self.send_pair_error(request_id, 401, "signature-mismatch")
+ .await;
+ return Err(ClientError::PairInvalidDeviceSignature);
+ }
+
+ device_identity.device_signature = Some(
+ generate_device_signature(&device_identity, &identity_key, self.signatures()).to_vec(),
+ );
+
+ if let Some(callback) = &self.config.pre_pair_callback
+ && !callback(jid, platform, business_name)
+ {
+ self.send_pair_error(request_id, 500, "internal-error")
+ .await;
+ return Err(ClientError::PairRejectedLocally);
+ }
+
+ let mut main_device_lid = lid.clone();
+ main_device_lid.device = 0;
+ let Ok(main_device_identity) = <[u8; 32]>::try_from(
+ device_identity
+ .account_signature_key
+ .as_deref()
+ .unwrap_or_default(),
+ ) else {
+ // verify_account_signature already checked the length.
+ return Err(ClientError::PairInvalidDeviceSignature);
+ };
+ let account = device_identity.clone();
+ device_identity.account_signature_key = None;
+ let self_signed_device_identity = device_identity.encode_to_vec();
+
+ let identities = {
+ let mut store = self.store.write().await;
+ store.account = Some(account);
+ store.id = Some(jid.clone());
+ store.lid = lid.clone();
+ store.business_name = business_name.to_owned();
+ store.platform = platform.to_owned();
+ if let Err(error) = store.save().await {
+ drop(store);
+ self.send_pair_error(request_id, 500, "internal-error")
+ .await;
+ return Err(ClientError::PairDatabase {
+ message: "failed to save device store".to_owned(),
+ source: error,
+ });
+ }
+ Arc::clone(&store.identities)
+ };
+ self.store_lid_pn_mapping(lid, jid).await;
+ if let Err(error) = identities
+ .put_identity(
+ &main_device_lid.signal_address().to_string(),
+ main_device_identity,
+ )
+ .await
+ {
+ let _ = self.delete_device().await;
+ self.send_pair_error(request_id, 500, "internal-error")
+ .await;
+ return Err(ClientError::PairDatabase {
+ message: "failed to store main device identity".to_owned(),
+ source: error,
+ });
+ }
+
+ // Expect a disconnect after this and don't dispatch the usual
+ // Disconnected event.
+ self.expect_disconnect();
+ self.paired.store(true, Ordering::SeqCst);
+
+ let confirmation = Node {
+ tag: "iq".to_owned(),
+ attrs: Attrs::from([
+ ("to".to_owned(), SERVER_JID.clone().into()),
+ ("type".to_owned(), "result".into()),
+ ("id".to_owned(), request_id.into()),
+ ]),
+ content: Some(NodeContent::Nodes(vec![Node {
+ tag: "pair-device-sign".to_owned(),
+ attrs: Attrs::new(),
+ content: Some(NodeContent::Nodes(vec![Node {
+ tag: "device-identity".to_owned(),
+ attrs: Attrs::from([(
+ "key-index".to_owned(),
+ device_identity_details.key_index.unwrap_or_default().into(),
+ )]),
+ content: Some(NodeContent::Bytes(self_signed_device_identity)),
+ }])),
+ }])),
+ };
+ if let Err(error) = self.send_node(&confirmation).await {
+ let _ = self.delete_device().await;
+ return Err(error.wrap("failed to send pairing confirmation"));
+ }
+ Ok(())
+ }
+
+ async fn send_pair_error(&self, id: &str, code: i64, text: &str) {
+ let node = Node {
+ tag: "iq".to_owned(),
+ attrs: Attrs::from([
+ ("to".to_owned(), SERVER_JID.clone().into()),
+ ("type".to_owned(), "error".into()),
+ ("id".to_owned(), id.into()),
+ ]),
+ content: Some(NodeContent::Nodes(vec![Node {
+ tag: "error".to_owned(),
+ attrs: Attrs::from([
+ ("code".to_owned(), code.into()),
+ ("text".to_owned(), text.into()),
+ ]),
+ content: None,
+ }])),
+ };
+ if let Err(error) = self.send_node(&node).await {
+ tracing::error!(error = %error, "failed to send pair error node");
+ }
+ }
+}
+
+#[cfg(test)]
+mod test;
diff --git a/crates/whatsmeow/src/pair/test.rs b/crates/whatsmeow/src/pair/test.rs
new file mode 100644
index 0000000000..efc2e6c40d
--- /dev/null
+++ b/crates/whatsmeow/src/pair/test.rs
@@ -0,0 +1,136 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+//! The QR string was produced by whatsmeow's Go code at the pinned revision
+//! with the same keys.
+
+use std::sync::{Arc, Mutex};
+
+use super::*;
+use crate::store::MemoryStore;
+use crate::util::keys::new_key_pair_from_private_key;
+
+/// Records the messages it signs or verifies; accepts only `[7; 64]`.
+#[derive(Default)]
+struct RecordingSignatures {
+ messages: Mutex<Vec<(Vec<u8>, Vec<u8>)>>,
+}
+
+impl CurveSignatures for RecordingSignatures {
+ fn calculate_signature(&self, private_key: &[u8; 32], message: &[u8]) -> [u8; 64] {
+ self.messages
+ .lock()
+ .unwrap()
+ .push((private_key.to_vec(), message.to_vec()));
+ [7; 64]
+ }
+
+ fn verify_signature(
+ &self,
+ public_key: &[u8; 32],
+ message: &[u8],
+ signature: &[u8; 64],
+ ) -> bool {
+ self.messages
+ .lock()
+ .unwrap()
+ .push((public_key.to_vec(), message.to_vec()));
+ *signature == [7; 64]
+ }
+}
+
+fn fixed_private_key(start: u8) -> [u8; 32] {
+ std::array::from_fn(|index| start + u8::try_from(index).unwrap())
+}
+
+#[test]
+fn qr_data_matches_go() {
+ let mut device = Arc::new(MemoryStore::default()).new_device(&RecordingSignatures::default());
+ device.noise_key = new_key_pair_from_private_key(fixed_private_key(0x90));
+ device.identity_key = new_key_pair_from_private_key(fixed_private_key(0x20));
+ device.adv_secret_key = (0xa0..0xc0).collect();
+
+ let client_type = get_qr_client_type(None);
+ assert_eq!(client_type, PairClientType::OtherWebClient);
+ assert_eq!(
+ make_qr_data(&device, b"2@abcDEF+/==", client_type),
+ "https://wa.me/settings/linked_devices#2@abcDEF+/==,n9etbc/0KY3T+W1bGyr5EKBTWxSI1/j6uzSamCiAthU=,NYBy1jZYgNGu6jKa35EhODhR7SGijjt16WXQ0s0WYlQ=,oKGio6SlpqeoqaqrrK2ur7CxsrO0tba3uLm6u7y9vr8=,9"
+ );
+ assert_eq!(
+ get_qr_client_type(Some(PairClientType::MacOs)).to_string(),
+ "c"
+ );
+}
+
+#[test]
+fn account_signature_covers_prefix_details_and_identity_key() {
+ let identity_key = new_key_pair_from_private_key(fixed_private_key(0x20));
+ let device_identity = AdvSignedDeviceIdentity {
+ details: Some(b"details".to_vec()),
+ account_signature_key: Some(vec![3; 32]),
+ account_signature: Some(vec![7; 64]),
+ device_signature: None,
+ };
+ let signatures = RecordingSignatures::default();
+ assert!(verify_account_signature(
+ &device_identity,
+ &identity_key,
+ false,
+ &signatures
+ ));
+ assert!(verify_account_signature(
+ &device_identity,
+ &identity_key,
+ true,
+ &signatures
+ ));
+ let messages = signatures.messages.into_inner().unwrap();
+ assert_eq!(messages[0].0, vec![3; 32]);
+ assert_eq!(
+ messages[0].1,
+ [&[6, 0][..], b"details", &identity_key.public].concat()
+ );
+ assert_eq!(
+ messages[1].1,
+ [&[6, 5][..], b"details", &identity_key.public].concat()
+ );
+
+ let short_signature = AdvSignedDeviceIdentity {
+ account_signature: Some(vec![7; 63]),
+ ..device_identity
+ };
+ assert!(!verify_account_signature(
+ &short_signature,
+ &identity_key,
+ false,
+ &RecordingSignatures::default()
+ ));
+}
+
+#[test]
+fn device_signature_covers_the_account_key_too() {
+ let identity_key = new_key_pair_from_private_key(fixed_private_key(0x20));
+ let device_identity = AdvSignedDeviceIdentity {
+ details: Some(b"details".to_vec()),
+ account_signature_key: Some(vec![3; 32]),
+ account_signature: Some(vec![7; 64]),
+ device_signature: None,
+ };
+ let signatures = RecordingSignatures::default();
+ assert_eq!(
+ generate_device_signature(&device_identity, &identity_key, &signatures),
+ [7; 64]
+ );
+ let messages = signatures.messages.into_inner().unwrap();
+ assert_eq!(messages[0].0, identity_key.private.to_vec());
+ assert_eq!(
+ messages[0].1,
+ [&[6, 1][..], b"details", &identity_key.public, &[3; 32]].concat()
+ );
+}
+
+#[test]
+fn concat_bytes_matches_go() {
+ assert_eq!(concat_bytes(&[&[1, 2], &[], &[3]]), vec![1, 2, 3]);
+}
diff --git a/crates/whatsmeow/src/pair_code.rs b/crates/whatsmeow/src/pair_code.rs
new file mode 100644
index 0000000000..7fe5a9861e
--- /dev/null
+++ b/crates/whatsmeow/src/pair_code.rs
@@ -0,0 +1,435 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+//
+// Ported from whatsmeow pair-code.go (MPL-2.0, Copyright (c) Tulir Asokan)
+//
+// The randomness of `generateCompanionEphemeralKey` and the notification
+// handler is passed in by the `_with` functions so tests can compare with Go.
+// PBKDF2-HMAC-SHA256, AES-CTR and the linking base32 alphabet are small local
+// helpers (Go uses `x/crypto/pbkdf2`, `crypto/cipher` and `encoding/base32`).
+
+//! Pairing by phone number link code.
+
+use std::sync::Arc;
+
+use aes::Aes256;
+use aes::cipher::{BlockEncrypt, KeyInit};
+use hmac::{Hmac, Mac};
+use sha2::Sha256;
+
+use crate::binary::{Attrs, Node, NodeContent};
+use crate::client::{Client, lock};
+use crate::errors::{ClientError, element_missing};
+use crate::request::{InfoQuery, IqType};
+use crate::types::{DEFAULT_USER_SERVER, Jid, SERVER_JID, new_jid};
+use crate::util::gcmutil;
+use crate::util::hkdfutil;
+use crate::util::keys::{KeyPair, new_key_pair};
+
+/// The alphabet of pairing codes (Crockford-like, without 0, I, O, U).
+pub const LINKING_BASE32_ALPHABET: &[u8; 32] = b"123456789ABCDEFGHJKLMNPQRSTVWXYZ";
+/// PBKDF2 iterations for the link code key (Go's `2<<16`).
+const LINK_CODE_PBKDF2_ROUNDS: u32 = 2 << 16;
+
+/// The type of client shown on the phone when pairing, the last field of the
+/// QR code.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, strum::Display, strum::EnumString, strum::AsRefStr)]
+pub enum PairClientType {
+ /// An unknown client.
+ #[strum(serialize = "0")]
+ Unknown,
+ /// Chrome.
+ #[strum(serialize = "1")]
+ Chrome,
+ /// Edge.
+ #[strum(serialize = "2")]
+ Edge,
+ /// Firefox.
+ #[strum(serialize = "3")]
+ Firefox,
+ /// Internet Explorer.
+ #[strum(serialize = "4")]
+ Ie,
+ /// Opera.
+ #[strum(serialize = "5")]
+ Opera,
+ /// Safari.
+ #[strum(serialize = "6")]
+ Safari,
+ /// Electron.
+ #[strum(serialize = "7")]
+ Electron,
+ /// The Windows app.
+ #[strum(serialize = "8")]
+ Uwp,
+ /// Another web client.
+ #[strum(serialize = "9")]
+ OtherWebClient,
+ /// The macOS app.
+ #[strum(serialize = "c")]
+ MacOs,
+ /// Android.
+ #[strum(serialize = "e")]
+ Android,
+}
+
+/// Base32 with the linking alphabet, without padding.
+pub fn linking_base32(data: &[u8]) -> String {
+ let mut output = String::new();
+ let mut buffer: u32 = 0;
+ let mut bits = 0;
+ for &byte in data {
+ buffer = (buffer << 8) | u32::from(byte);
+ bits += 8;
+ while bits >= 5 {
+ bits -= 5;
+ output.push(char::from(
+ LINKING_BASE32_ALPHABET[((buffer >> bits) & 31) as usize],
+ ));
+ }
+ }
+ if bits > 0 {
+ output.push(char::from(
+ LINKING_BASE32_ALPHABET[((buffer << (5 - bits)) & 31) as usize],
+ ));
+ }
+ output
+}
+
+/// PBKDF2-HMAC-SHA256 with a 32-byte output.
+pub(crate) fn pbkdf2_sha256(password: &[u8], salt: &[u8], rounds: u32) -> [u8; 32] {
+ let mac = <Hmac<Sha256> as Mac>::new_from_slice(password).unwrap_or_else(|_| {
+ // HMAC accepts keys of any length.
+ <Hmac<Sha256> as Mac>::new_from_slice(&[]).unwrap_or_else(|_| unreachable!())
+ });
+ let mut first = mac.clone();
+ first.update(salt);
+ first.update(&1_u32.to_be_bytes());
+ let mut block: [u8; 32] = first.finalize().into_bytes().into();
+ let mut output = block;
+ for _ in 1..rounds {
+ let mut next = mac.clone();
+ next.update(&block);
+ block = next.finalize().into_bytes().into();
+ for (out, byte) in output.iter_mut().zip(block) {
+ *out ^= byte;
+ }
+ }
+ output
+}
+
+/// AES-256-CTR with a 128-bit big-endian counter starting at `iv`, as Go's
+/// `cipher.NewCTR`.
+pub(crate) fn aes_ctr(key: &[u8; 32], iv: &[u8; 16], data: &[u8]) -> Vec<u8> {
+ let cipher = Aes256::new(key.into());
+ let mut counter = u128::from_be_bytes(*iv);
+ let mut output = Vec::with_capacity(data.len());
+ for chunk in data.chunks(16) {
+ let mut block = counter.to_be_bytes().into();
+ cipher.encrypt_block(&mut block);
+ output.extend(chunk.iter().zip(block.iter()).map(|(byte, key)| byte ^ key));
+ counter = counter.wrapping_add(1);
+ }
+ output
+}
+
+fn link_code_key(linking_code: &str, salt: &[u8]) -> [u8; 32] {
+ pbkdf2_sha256(linking_code.as_bytes(), salt, LINK_CODE_PBKDF2_ROUNDS)
+}
+
+/// The companion's ephemeral key for code pairing: the public key encrypted
+/// with a key derived from the linking code, prefixed with the salt and IV
+/// (80 bytes), and the encoded linking code. `generateCompanionEphemeralKey`
+/// with its randomness passed in.
+pub fn generate_companion_ephemeral_key_with(
+ key_pair: &KeyPair,
+ salt: &[u8; 32],
+ iv: &[u8; 16],
+ linking_code: &[u8; 5],
+) -> (Vec<u8>, String) {
+ let encoded_linking_code = linking_base32(linking_code);
+ let key = link_code_key(&encoded_linking_code, salt);
+ let encrypted_public = aes_ctr(&key, iv, &key_pair.public);
+ let ephemeral_key = [&salt[..], &iv[..], &encrypted_public].concat();
+ (ephemeral_key, encoded_linking_code)
+}
+
+/// The pending code pairing (`phoneLinkingCache`).
+#[derive(Clone)]
+pub(crate) struct PhoneLinkingCache {
+ jid: Jid,
+ key_pair: KeyPair,
+ linking_code: String,
+ pairing_ref: String,
+}
+
+/// The `companion_finish` key bundle and ADV secret of a code pairing,
+/// computed from the primary device's wrapped ephemeral key and identity
+/// (the crypto of `handleCodePairNotification`, with its randomness passed
+/// in). Returns (wrapped key bundle, ADV secret).
+#[expect(
+ clippy::too_many_arguments,
+ reason = "the inputs of Go's computation, made explicit"
+)]
+pub fn code_pair_key_bundle_with(
+ linking_code: &str,
+ ephemeral_key_pair: &KeyPair,
+ identity_key_pair: &KeyPair,
+ wrapped_primary_ephemeral_public: &[u8],
+ primary_identity_public: &[u8],
+ adv_secret_random: &[u8; 32],
+ key_bundle_salt: &[u8; 32],
+ key_bundle_nonce: &[u8; 12],
+) -> Result<(Vec<u8>, Vec<u8>), ClientError> {
+ if wrapped_primary_ephemeral_public.len() < 80 {
+ return Err(ClientError::Other(format!(
+ "unexpected length of link_code_pairing_wrapped_primary_ephemeral_pub: {}",
+ wrapped_primary_ephemeral_public.len()
+ )));
+ }
+ let primary_salt = &wrapped_primary_ephemeral_public[0..32];
+ let primary_iv: [u8; 16] = wrapped_primary_ephemeral_public[32..48]
+ .try_into()
+ .map_err(|_| ClientError::Other("invalid primary IV".to_owned()))?;
+ let primary_encrypted_public = &wrapped_primary_ephemeral_public[48..80];
+ let key = link_code_key(linking_code, primary_salt);
+ let primary_public: [u8; 32] = aes_ctr(&key, &primary_iv, primary_encrypted_public)
+ .try_into()
+ .map_err(|_| ClientError::Other("invalid primary ephemeral key".to_owned()))?;
+ let ephemeral_shared_secret =
+ x25519(ephemeral_key_pair.private, primary_public).map_err(|error| {
+ ClientError::Other(format!(
+ "failed to compute ephemeral shared secret: {error}"
+ ))
+ })?;
+
+ let key_bundle_encryption_key = hkdfutil::sha256(
+ &ephemeral_shared_secret,
+ key_bundle_salt,
+ b"link_code_pairing_key_bundle_encryption_key",
+ 32,
+ );
+ let plaintext_key_bundle = [
+ &identity_key_pair.public[..],
+ primary_identity_public,
+ &adv_secret_random[..],
+ ]
+ .concat();
+ let encrypted_key_bundle = gcmutil::encrypt(
+ &key_bundle_encryption_key,
+ key_bundle_nonce,
+ &plaintext_key_bundle,
+ &[],
+ )
+ .map_err(|error| ClientError::Other(format!("failed to encrypt key bundle: {error}")))?;
+ let wrapped_key_bundle = [
+ &key_bundle_salt[..],
+ &key_bundle_nonce[..],
+ &encrypted_key_bundle,
+ ]
+ .concat();
+
+ let primary_identity: [u8; 32] = primary_identity_public.try_into().map_err(|_| {
+ ClientError::Other(
+ "failed to compute identity shared key: bad public key length".to_owned(),
+ )
+ })?;
+ let identity_shared_key =
+ x25519(identity_key_pair.private, primary_identity).map_err(|error| {
+ ClientError::Other(format!("failed to compute identity shared key: {error}"))
+ })?;
+ let adv_secret_input = [
+ &ephemeral_shared_secret[..],
+ &identity_shared_key[..],
+ &adv_secret_random[..],
+ ]
+ .concat();
+ let adv_secret = hkdfutil::sha256(&adv_secret_input, &[], b"adv_secret", 32);
+ Ok((wrapped_key_bundle, adv_secret))
+}
+
+/// X25519 that rejects low-order points like Go's `curve25519.X25519`.
+fn x25519(private: [u8; 32], public: [u8; 32]) -> Result<[u8; 32], &'static str> {
+ let shared = x25519_dalek::x25519(private, public);
+ if shared == [0; 32] {
+ return Err("bad input point: low order point");
+ }
+ Ok(shared)
+}
+
+fn bytes_node(tag: &str, content: Vec<u8>) -> Node {
+ Node {
+ tag: tag.to_owned(),
+ attrs: Attrs::new(),
+ content: Some(NodeContent::Bytes(content)),
+ }
+}
+
+fn node_bytes<'node>(node: &'node Node, tag: &str) -> Option<&'node [u8]> {
+ match &node.get_optional_child_by_tag(&[tag])?.content {
+ Some(NodeContent::Bytes(bytes)) => Some(bytes),
+ _ => None,
+ }
+}
+
+impl Client {
+ /// Starts pairing with a code the user types on their phone instead of
+ /// scanning a QR code; returns the code as `ABCD-EFGH` (`PairPhone`).
+ ///
+ /// Connect first and wait for the first QR event. The display name must
+ /// look like `Browser (OS)`.
+ #[tracing::instrument(name = "whatsmeow.pair_phone", skip_all, err)]
+ pub async fn pair_phone(
+ &self,
+ phone: &str,
+ show_push_notification: bool,
+ client_type: PairClientType,
+ client_display_name: &str,
+ ) -> Result<String, ClientError> {
+ let key_pair = new_key_pair();
+ let (ephemeral_key, encoded_linking_code) = generate_companion_ephemeral_key_with(
+ &key_pair,
+ &rand::random(),
+ &rand::random(),
+ &rand::random(),
+ );
+ let phone: String = phone.chars().filter(char::is_ascii_digit).collect();
+ if phone.len() <= 6 {
+ return Err(ClientError::PhoneNumberTooShort);
+ } else if phone.starts_with('0') {
+ return Err(ClientError::PhoneNumberIsNotInternational);
+ }
+ let jid = new_jid(&phone, DEFAULT_USER_SERVER);
+ let noise_public = self.store.read().await.noise_key.public;
+ let response = self
+ .send_iq(InfoQuery {
+ namespace: "md",
+ r#type: IqType::Set,
+ to: SERVER_JID.clone(),
+ content: Some(NodeContent::Nodes(vec![Node {
+ tag: "link_code_companion_reg".to_owned(),
+ attrs: Attrs::from([
+ ("jid".to_owned(), jid.clone().into()),
+ ("stage".to_owned(), "companion_hello".into()),
+ (
+ "should_show_push_notification".to_owned(),
+ show_push_notification.into(),
+ ),
+ ]),
+ content: Some(NodeContent::Nodes(vec![
+ bytes_node(
+ "link_code_pairing_wrapped_companion_ephemeral_pub",
+ ephemeral_key,
+ ),
+ bytes_node("companion_server_auth_key_pub", noise_public.to_vec()),
+ Node {
+ tag: "companion_platform_id".to_owned(),
+ attrs: Attrs::new(),
+ content: Some(NodeContent::String(client_type.to_string())),
+ },
+ Node {
+ tag: "companion_platform_display".to_owned(),
+ attrs: Attrs::new(),
+ content: Some(NodeContent::String(client_display_name.to_owned())),
+ },
+ bytes_node("link_code_pairing_nonce", vec![0]),
+ ])),
+ }])),
+ ..Default::default()
+ })
+ .await?;
+ let pairing_ref = response
+ .get_optional_child_by_tag(&["link_code_companion_reg", "link_code_pairing_ref"])
+ .ok_or_else(|| {
+ element_missing("link_code_pairing_ref", "code link registration response")
+ })?;
+ let Some(NodeContent::Bytes(pairing_ref)) = &pairing_ref.content else {
+ return Err(ClientError::Other(
+ "unexpected type in content of link_code_pairing_ref tag".to_owned(),
+ ));
+ };
+ *lock(&self.phone_linking_cache) = Some(PhoneLinkingCache {
+ jid,
+ key_pair,
+ linking_code: encoded_linking_code.clone(),
+ pairing_ref: String::from_utf8_lossy(pairing_ref).into_owned(),
+ });
+ Ok(format!(
+ "{}-{}",
+ &encoded_linking_code[..4],
+ &encoded_linking_code[4..]
+ ))
+ }
+
+ pub(crate) async fn try_handle_code_pair_notification(self: Arc<Self>, parent: Node) {
+ if let Err(error) = self.handle_code_pair_notification(&parent).await {
+ tracing::error!(error = %error, "failed to handle code pair notification");
+ }
+ }
+
+ async fn handle_code_pair_notification(&self, parent: &Node) -> Result<(), ClientError> {
+ let node = parent
+ .get_optional_child_by_tag(&["link_code_companion_reg"])
+ .ok_or_else(|| element_missing("link_code_companion_reg", "notification"))?;
+ let link_cache = lock(&self.phone_linking_cache).clone().ok_or_else(|| {
+ ClientError::Other(
+ "received code pair notification without a pending pairing".to_owned(),
+ )
+ })?;
+ self.paired
+ .store(false, std::sync::atomic::Ordering::SeqCst);
+ let pairing_ref = node_bytes(node, "link_code_pairing_ref").unwrap_or_default();
+ if pairing_ref != link_cache.pairing_ref.as_bytes() {
+ return Err(ClientError::Other(
+ "pairing ref mismatch in code pair notification".to_owned(),
+ ));
+ }
+ let wrapped_primary_ephemeral_public =
+ node_bytes(node, "link_code_pairing_wrapped_primary_ephemeral_pub").ok_or_else(
+ || {
+ element_missing(
+ "link_code_pairing_wrapped_primary_ephemeral_pub",
+ "notification",
+ )
+ },
+ )?;
+ let primary_identity_public = node_bytes(node, "primary_identity_pub")
+ .ok_or_else(|| element_missing("primary_identity_pub", "notification"))?;
+ let identity_key = self.store.read().await.identity_key.clone();
+ let (wrapped_key_bundle, adv_secret) = code_pair_key_bundle_with(
+ &link_cache.linking_code,
+ &link_cache.key_pair,
+ &identity_key,
+ wrapped_primary_ephemeral_public,
+ primary_identity_public,
+ &rand::random(),
+ &rand::random(),
+ &rand::random(),
+ )?;
+ self.store.write().await.adv_secret_key = adv_secret;
+ self.send_iq(InfoQuery {
+ namespace: "md",
+ r#type: IqType::Set,
+ to: SERVER_JID.clone(),
+ content: Some(NodeContent::Nodes(vec![Node {
+ tag: "link_code_companion_reg".to_owned(),
+ attrs: Attrs::from([
+ ("jid".to_owned(), link_cache.jid.clone().into()),
+ ("stage".to_owned(), "companion_finish".into()),
+ ]),
+ content: Some(NodeContent::Nodes(vec![
+ bytes_node("link_code_pairing_wrapped_key_bundle", wrapped_key_bundle),
+ bytes_node("companion_identity_public", identity_key.public.to_vec()),
+ bytes_node("link_code_pairing_ref", pairing_ref.to_vec()),
+ ])),
+ }])),
+ ..Default::default()
+ })
+ .await
+ .map(|_| ())
+ }
+}
+
+#[cfg(test)]
+mod test;
diff --git a/crates/whatsmeow/src/pair_code/test.rs b/crates/whatsmeow/src/pair_code/test.rs
new file mode 100644
index 0000000000..6e7ac6966e
--- /dev/null
+++ b/crates/whatsmeow/src/pair_code/test.rs
@@ -0,0 +1,260 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+//! Code pairing against whatsmeow's own output
+//! (`testdata/generator/inpackage/pairing_media_vectors_test.go`) and the
+//! fake server.
+
+use std::sync::Arc;
+
+use super::*;
+use crate::client::test::{bytes, children, connect_paired, harness, next_node, node, text};
+use crate::testing::{attr_string, is_iq};
+use crate::util::keys::new_key_pair_from_private_key;
+use crate::vectors::Vectors;
+
+fn array<const N: usize>(data: Vec<u8>) -> [u8; N] {
+ data.try_into().unwrap()
+}
+
+#[test]
+fn companion_ephemeral_keys_match_go() {
+ let vectors = Vectors::load("pairing_media.json");
+ let key_pair = new_key_pair_from_private_key(array(vectors.bytes("companion_private")));
+ let ephemeral_key = vectors.bytes("companion_ephemeral_key");
+ let (computed, code) = generate_companion_ephemeral_key_with(
+ &key_pair,
+ &array(ephemeral_key[..32].to_vec()),
+ &array(ephemeral_key[32..48].to_vec()),
+ &array(vectors.bytes("companion_linking_code_bytes")),
+ );
+ assert_eq!(code, vectors.string("companion_linking_code"));
+ assert_eq!(computed, ephemeral_key);
+}
+
+#[test]
+fn the_key_bundle_and_adv_secret_match_go() {
+ let vectors = Vectors::load("pairing_media.json");
+ let notification = vectors.node("code_pair_notification");
+ let registration = notification.get_child_by_tag(&["link_code_companion_reg"]);
+ let wrapped_primary = node_bytes(
+ registration,
+ "link_code_pairing_wrapped_primary_ephemeral_pub",
+ )
+ .unwrap();
+ let finish = vectors.node("code_pair_finish");
+ let wrapped_bundle = node_bytes(
+ finish.get_child_by_tag(&["link_code_companion_reg"]),
+ "link_code_pairing_wrapped_key_bundle",
+ )
+ .unwrap()
+ .to_vec();
+ let identity =
+ new_key_pair_from_private_key(array(vectors.bytes("code_pair_identity_private")));
+ let ephemeral = new_key_pair_from_private_key(array(vectors.bytes("companion_private")));
+
+ // Recover Go's random ADV input by decrypting its bundle, then check the
+ // Rust computation reproduces the bundle and the ADV secret exactly.
+ let primary_public: [u8; 32] = array(aes_ctr(
+ &link_code_key(
+ &vectors.string("companion_linking_code"),
+ &wrapped_primary[..32],
+ ),
+ &array(wrapped_primary[32..48].to_vec()),
+ &wrapped_primary[48..80],
+ ));
+ let shared = x25519(ephemeral.private, primary_public).unwrap();
+ let bundle_key = hkdfutil::sha256(
+ &shared,
+ &wrapped_bundle[..32],
+ b"link_code_pairing_key_bundle_encryption_key",
+ 32,
+ );
+ let plaintext = gcmutil::decrypt(
+ &bundle_key,
+ &wrapped_bundle[32..44],
+ &wrapped_bundle[44..],
+ &[],
+ )
+ .unwrap();
+ let (computed_bundle, adv_secret) = code_pair_key_bundle_with(
+ &vectors.string("companion_linking_code"),
+ &ephemeral,
+ &identity,
+ wrapped_primary,
+ &vectors.bytes("code_pair_primary_identity"),
+ &array(plaintext[64..].to_vec()),
+ &array(wrapped_bundle[..32].to_vec()),
+ &array(wrapped_bundle[32..44].to_vec()),
+ )
+ .unwrap();
+ assert_eq!(computed_bundle, wrapped_bundle);
+ assert_eq!(adv_secret, vectors.bytes("code_pair_adv_secret"));
+ assert_eq!(&plaintext[..32], &identity.public);
+}
+
+#[test]
+fn linking_base32_matches_the_alphabet() {
+ assert_eq!(linking_base32(&[0, 0, 0, 0, 0]), "11111111");
+ assert_eq!(linking_base32(&[0xff; 5]), "ZZZZZZZZ");
+}
+
+#[tokio::test(start_paused = true)]
+async fn pairing_with_a_phone_number_code() {
+ let mut harness = harness(None);
+ harness.client.connect().await.unwrap();
+ let mut connection = harness.server.accept().await.unwrap();
+
+ let client = Arc::clone(&harness.client);
+ let pair = tokio::spawn(async move {
+ client
+ .pair_phone(
+ "+1 (555) 000-1111",
+ true,
+ PairClientType::Chrome,
+ "Chrome (Linux)",
+ )
+ .await
+ });
+ let hello = next_node(&mut connection).await;
+ assert!(is_iq(&hello, "md"));
+ let registration = hello.get_child_by_tag(&["link_code_companion_reg"]);
+ assert_eq!(attr_string(registration, "stage"), "companion_hello");
+ assert_eq!(
+ attr_string(registration, "jid"),
+ );
+ assert_eq!(
+ attr_string(registration, "should_show_push_notification"),
+ "true"
+ );
+ let wrapped_companion = node_bytes(
+ registration,
+ "link_code_pairing_wrapped_companion_ephemeral_pub",
+ )
+ .unwrap()
+ .to_vec();
+ connection
+ .respond_iq(
+ &hello,
+ vec![node(
+ "link_code_companion_reg",
+ &[],
+ children(vec![node("link_code_pairing_ref", &[], bytes(b"REF9"))]),
+ )],
+ )
+ .await;
+ let code = pair.await.unwrap().unwrap();
+ assert_eq!(code.len(), 9);
+ let linking_code = code.replace('-', "");
+
+ // The phone decrypts the companion key with the code and answers with
+ // its own wrapped ephemeral key.
+ let companion_public: [u8; 32] = array(aes_ctr(
+ &link_code_key(&linking_code, &wrapped_companion[..32]),
+ &array(wrapped_companion[32..48].to_vec()),
+ &wrapped_companion[48..80],
+ ));
+ let primary_ephemeral = new_key_pair();
+ let primary_identity = new_key_pair();
+ let salt = [3; 32];
+ let iv = [4; 16];
+ let wrapped_primary = [
+ &salt[..],
+ &iv[..],
+ &aes_ctr(
+ &link_code_key(&linking_code, &salt),
+ &iv,
+ &primary_ephemeral.public,
+ ),
+ ]
+ .concat();
+ connection
+ .send_node(&node(
+ "notification",
+ &[
+ (
+ "from",
+ crate::binary::AttributeValue::Jid(SERVER_JID.clone()),
+ ),
+ ("id", text("N1")),
+ ("type", text("link_code_companion_reg")),
+ ],
+ children(vec![node(
+ "link_code_companion_reg",
+ &[],
+ children(vec![
+ node("link_code_pairing_ref", &[], bytes(b"REF9")),
+ node(
+ "link_code_pairing_wrapped_primary_ephemeral_pub",
+ &[],
+ bytes(&wrapped_primary),
+ ),
+ node("primary_identity_pub", &[], bytes(&primary_identity.public)),
+ ]),
+ )]),
+ ))
+ .await;
+ let finish = loop {
+ let request = next_node(&mut connection).await;
+ if is_iq(&request, "md") {
+ break request;
+ }
+ };
+ let registration = finish.get_child_by_tag(&["link_code_companion_reg"]);
+ assert_eq!(attr_string(registration, "stage"), "companion_finish");
+ let wrapped_bundle = node_bytes(registration, "link_code_pairing_wrapped_key_bundle").unwrap();
+ let shared = x25519(primary_ephemeral.private, companion_public).unwrap();
+ let bundle_key = hkdfutil::sha256(
+ &shared,
+ &wrapped_bundle[..32],
+ b"link_code_pairing_key_bundle_encryption_key",
+ 32,
+ );
+ let plaintext = gcmutil::decrypt(
+ &bundle_key,
+ &wrapped_bundle[32..44],
+ &wrapped_bundle[44..],
+ &[],
+ )
+ .unwrap();
+ let identity_public = harness.client.store.read().await.identity_key.public;
+ assert_eq!(&plaintext[..32], &identity_public);
+ assert_eq!(&plaintext[32..64], &primary_identity.public);
+ // The phone derives the same ADV secret the client stored.
+ let identity_shared = x25519(primary_identity.private, identity_public).unwrap();
+ let adv_secret = hkdfutil::sha256(
+ &[&shared[..], &identity_shared[..], &plaintext[64..]].concat(),
+ &[],
+ b"adv_secret",
+ 32,
+ );
+ assert_eq!(harness.client.store.read().await.adv_secret_key, adv_secret);
+ connection.respond_iq(&finish, vec![]).await;
+ let _ = connect_paired;
+}
+
+#[tokio::test(start_paused = true)]
+async fn short_and_local_phone_numbers_are_rejected() {
+ let harness = harness(None);
+ assert!(matches!(
+ harness
+ .client
+ .pair_phone("12345", false, PairClientType::Chrome, "Chrome (Linux)")
+ .await,
+ Err(ClientError::PhoneNumberTooShort)
+ ));
+ assert!(matches!(
+ harness
+ .client
+ .pair_phone(
+ "0555000111",
+ false,
+ PairClientType::Chrome,
+ "Chrome (Linux)"
+ )
+ .await,
+ Err(ClientError::PhoneNumberIsNotInternational)
+ ));
+}
diff --git a/crates/whatsmeow/src/pair_passkey.rs b/crates/whatsmeow/src/pair_passkey.rs
new file mode 100644
index 0000000000..4beb763734
--- /dev/null
+++ b/crates/whatsmeow/src/pair_passkey.rs
@@ -0,0 +1,491 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+//
+// Ported from whatsmeow pair-passkey.go (MPL-2.0, Copyright (c) Tulir Asokan)
+//
+// The key derivations take their randomness and inputs as parameters
+// (`prologue_with`, `passkey_confirmation_code`, …) so tests can compare
+// with Go.
+
+//! Pairing that the phone protects with a passkey: the server asks for a
+//! WebAuthn assertion, then both sides agree on a short confirmation code.
+
+use std::sync::Arc;
+use std::time::Duration;
+
+use hmac::{Hmac, Mac};
+use prost::Message;
+use sha2::{Digest, Sha256};
+
+use crate::binary::{AttributeValue, Attrs, Node, NodeContent};
+use crate::client::{Client, lock};
+use crate::errors::{ClientError, element_missing};
+use crate::pair_code::linking_base32;
+use crate::proto::wa_companion_reg::{
+ CompanionCommitment, CompanionEphemeralIdentity, EncryptedPairingRequest, PairingRequest,
+ PrimaryEphemeralIdentity, ProloguePayload,
+};
+use crate::request::{InfoQuery, IqType};
+use crate::store::device_props;
+use crate::types::events::{Event, PairPasskeyConfirmation, PairPasskeyError, PairPasskeyRequest};
+use crate::types::{SERVER_JID, WebAuthnPublicKey, WebAuthnResponse};
+use crate::util::gcmutil;
+use crate::util::hkdfutil;
+use crate::util::keys::{KeyPair, new_key_pair};
+
+/// How long the passkey handoff key stays valid.
+const PASSKEY_HANDOFF_KEY_LIFETIME: Duration = Duration::from_secs(5 * 60);
+
+/// The state of a passkey pairing between the response and the confirmation
+/// (`passkeyLinkingCache`).
+#[derive(Clone)]
+pub(crate) struct PasskeyLinkingCache {
+ key_pair: KeyPair,
+ companion_nonce: Vec<u8>,
+ pairing_ref: String,
+ device_type: i32,
+ encryption_key: Option<Vec<u8>>,
+}
+
+/// The HMAC key proving the pairing handoff (`passkeyHandoffKey`).
+#[derive(Clone)]
+pub(crate) struct PasskeyHandoffKey {
+ hmac: Vec<u8>,
+ created: tokio::time::Instant,
+}
+
+impl PasskeyHandoffKey {
+ fn valid(&self) -> bool {
+ self.created.elapsed() < PASSKEY_HANDOFF_KEY_LIFETIME
+ }
+}
+
+/// The passkey state the client keeps.
+#[derive(Default)]
+pub(crate) struct PasskeyState {
+ pub(crate) linking: Option<PasskeyLinkingCache>,
+ pub(crate) handoff_key: Option<PasskeyHandoffKey>,
+ pub(crate) skip_handoff_ux: bool,
+}
+
+/// The handoff HMAC key derived from the ADV secret.
+pub fn passkey_handoff_hmac_key(adv_secret: &[u8]) -> Vec<u8> {
+ hkdfutil::sha256(adv_secret, &[], b"shortcake-passkey-handoff-v1", 32)
+}
+
+/// The serialized `ProloguePayload` committing to the companion's ephemeral
+/// identity and nonce.
+pub fn prologue_with(
+ ephemeral_public: &[u8; 32],
+ device_type: i32,
+ companion_ref: &str,
+ companion_nonce: &[u8],
+) -> Vec<u8> {
+ let identity = CompanionEphemeralIdentity {
+ public_key: Some(ephemeral_public.to_vec()),
+ device_type: Some(device_type),
+ r#ref: Some(companion_ref.to_owned()),
+ }
+ .encode_to_vec();
+ let commitment: [u8; 32] = Sha256::new()
+ .chain_update(&identity)
+ .chain_update(companion_nonce)
+ .finalize()
+ .into();
+ ProloguePayload {
+ companion_ephemeral_identity: Some(identity),
+ commitment: Some(CompanionCommitment {
+ hash: Some(commitment.to_vec()),
+ }),
+ }
+ .encode_to_vec()
+}
+
+/// HMAC-SHA256 of the prologue with the handoff key.
+pub fn pairing_handoff_proof(handoff_key: &[u8], prologue: &[u8]) -> Vec<u8> {
+ // HMAC accepts keys of any length.
+ let Ok(mut mac) = <Hmac<Sha256> as Mac>::new_from_slice(handoff_key) else {
+ return Vec::new();
+ };
+ mac.update(prologue);
+ mac.finalize().into_bytes().to_vec()
+}
+
+/// The pairing encryption key and the confirmation code (`ABCD-EFGH`) from
+/// the primary device's ephemeral identity.
+pub fn passkey_confirmation_code(
+ companion_private: [u8; 32],
+ companion_nonce: &[u8],
+ device_type: i32,
+ pairing_ref: &str,
+ primary_public: &[u8; 32],
+ primary_nonce: &[u8],
+) -> Result<(Vec<u8>, String), ClientError> {
+ let shared_secret = x25519_dalek::x25519(companion_private, *primary_public);
+ if shared_secret == [0; 32] {
+ return Err(ClientError::Other(
+ "failed to compute shared secret: bad input point: low order point".to_owned(),
+ ));
+ }
+ let salt = format!("Companion Pairing {device_type} with ref {pairing_ref}");
+ let encryption_key = hkdfutil::sha256(
+ &shared_secret,
+ salt.as_bytes(),
+ b"Pairing Information Encryption Key",
+ 32,
+ );
+ let digest: [u8; 32] = Sha256::new()
+ .chain_update(companion_nonce)
+ .chain_update(primary_public)
+ .finalize()
+ .into();
+ let code_bytes: Vec<u8> = primary_nonce
+ .iter()
+ .zip(digest)
+ .take(5)
+ .map(|(nonce, digest)| nonce ^ digest)
+ .collect();
+ let encoded = linking_base32(&code_bytes);
+ Ok((
+ encryption_key,
+ format!("{}-{}", &encoded[..4], &encoded[4..]),
+ ))
+}
+
+fn bytes_node(tag: &str, content: Vec<u8>) -> Node {
+ Node {
+ tag: tag.to_owned(),
+ attrs: Attrs::new(),
+ content: Some(NodeContent::Bytes(content)),
+ }
+}
+
+fn from_server(node: &Node) -> bool {
+ matches!(node.attrs.get("from"), Some(AttributeValue::Jid(from)) if *from == *SERVER_JID)
+}
+
+/// Parses the WebAuthn options in a `passkey_prologue_request` notification
+/// or the `passkey_request_options` IQ response.
+pub fn parse_passkey_notification(node: &Node) -> Result<WebAuthnPublicKey, ClientError> {
+ let options = node
+ .get_optional_child_by_tag(&["passkey_request_options"])
+ .ok_or_else(|| element_missing("passkey_request_options", "passkey notification"))?;
+ let Some(NodeContent::Bytes(content)) = &options.content else {
+ return Err(ClientError::Other(
+ "unexpected content type for <passkey_request_options> node".to_owned(),
+ ));
+ };
+ serde_json::from_slice(content).map_err(|error| {
+ ClientError::Other(format!(
+ "failed to unmarshal <passkey_request_options> content: {error}"
+ ))
+ })
+}
+
+/// Parses the primary device's ephemeral identity in a continuation
+/// notification.
+pub fn parse_passkey_continuation_notification(
+ node: &Node,
+) -> Result<PrimaryEphemeralIdentity, ClientError> {
+ let identity = node
+ .get_optional_child_by_tag(&["primary_ephemeral_identity"])
+ .ok_or_else(|| {
+ element_missing(
+ "primary_ephemeral_identity",
+ "passkey continuation notification",
+ )
+ })?;
+ let Some(NodeContent::Bytes(content)) = &identity.content else {
+ return Err(ClientError::Other(
+ "unexpected content type for <primary_ephemeral_identity> node".to_owned(),
+ ));
+ };
+ let identity = PrimaryEphemeralIdentity::decode(content.as_slice()).map_err(|error| {
+ ClientError::Other(format!(
+ "failed to unmarshal primary ephemeral identity: {error}"
+ ))
+ })?;
+ let public_key_length = identity.public_key.as_deref().unwrap_or_default().len();
+ let nonce_length = identity.nonce.as_deref().unwrap_or_default().len();
+ if public_key_length != 32 {
+ return Err(ClientError::Other(format!(
+ "unexpected public key length {public_key_length} primary ephemeral identity"
+ )));
+ } else if nonce_length != 32 {
+ return Err(ClientError::Other(format!(
+ "unexpected nonce length {nonce_length} primary ephemeral identity"
+ )));
+ }
+ Ok(identity)
+}
+
+impl Client {
+ pub(crate) async fn handle_passkey_notification(self: &Arc<Self>, node: &Node) {
+ if !from_server(node) {
+ tracing::warn!("ignoring passkey notification from non-server JID");
+ return;
+ }
+ let public_key = match parse_passkey_notification(node) {
+ Ok(public_key) => public_key,
+ Err(error) => {
+ tracing::warn!(error = %error, "failed to parse passkey notification");
+ match self.get_passkey_request_options().await {
+ Ok(public_key) => {
+ tracing::debug!(
+ "fetched passkey options after failing to parse notification"
+ );
+ public_key
+ }
+ Err(second_error) => {
+ tracing::warn!(error = %second_error, "failed to fetch passkey options");
+ self.dispatch_event(Event::PairPasskeyError(PairPasskeyError {
+ error: Arc::new(ClientError::Other(format!(
+ "failed to parse passkey notification: {error} (fetching key also failed: {second_error})"
+ ))),
+ continuation: false,
+ }))
+ .await;
+ return;
+ }
+ }
+ }
+ };
+ let new_secret: [u8; 32] = rand::random();
+ let old_secret = {
+ let mut store = self.store.write().await;
+ std::mem::replace(&mut store.adv_secret_key, new_secret.to_vec())
+ };
+ lock(&self.passkey_state).handoff_key = Some(PasskeyHandoffKey {
+ hmac: passkey_handoff_hmac_key(&old_secret),
+ created: tokio::time::Instant::now(),
+ });
+ self.dispatch_event(Event::PairPasskeyRequest(Box::new(PairPasskeyRequest {
+ public_key,
+ })))
+ .await;
+ }
+
+ /// Sends the authenticator's answer to an [`Event::PairPasskeyRequest`]
+ /// (`SendPasskeyResponse`).
+ #[tracing::instrument(name = "whatsmeow.pair.passkey_response", skip_all, err)]
+ pub async fn send_passkey_response(
+ &self,
+ passkey_response: &WebAuthnResponse,
+ ) -> Result<(), ClientError> {
+ let marshaled_response = serde_json::to_vec(passkey_response).map_err(|error| {
+ ClientError::Other(format!("failed to marshal WebAuthnResponse: {error}"))
+ })?;
+ let companion_ref = self
+ .get_companion_ref()
+ .await
+ .map_err(|error| error.wrap("failed to get companion ref"))?;
+ let key_pair = new_key_pair();
+ let companion_nonce: [u8; 32] = rand::random();
+ let device_type = device_props().platform_type.unwrap_or_default();
+ let prologue = prologue_with(
+ &key_pair.public,
+ device_type,
+ &companion_ref,
+ &companion_nonce,
+ );
+ let handoff_key = {
+ let mut state = lock(&self.passkey_state);
+ state.linking = Some(PasskeyLinkingCache {
+ key_pair,
+ companion_nonce: companion_nonce.to_vec(),
+ pairing_ref: companion_ref,
+ device_type,
+ encryption_key: None,
+ });
+ let handoff_key = state.handoff_key.clone().filter(PasskeyHandoffKey::valid);
+ state.skip_handoff_ux = handoff_key.is_some();
+ handoff_key
+ };
+ let mut content = vec![
+ bytes_node("credential_id", passkey_response.raw_id.0.clone()),
+ bytes_node("webauthn_assertion", marshaled_response),
+ bytes_node("prologue_payload", prologue.clone()),
+ ];
+ if let Some(handoff_key) = handoff_key {
+ content.push(bytes_node(
+ "pairing_handoff_proof",
+ pairing_handoff_proof(&handoff_key.hmac, &prologue),
+ ));
+ }
+ self.send_iq(InfoQuery {
+ namespace: "md",
+ r#type: IqType::Set,
+ to: SERVER_JID.clone(),
+ content: Some(NodeContent::Nodes(vec![Node {
+ tag: "passkey_prologue".to_owned(),
+ attrs: Attrs::new(),
+ content: Some(NodeContent::Nodes(content)),
+ }])),
+ ..Default::default()
+ })
+ .await
+ .map_err(|error| error.wrap("failed to send passkey response"))?;
+ lock(&self.passkey_state).handoff_key = None;
+ Ok(())
+ }
+
+ pub(crate) async fn try_handle_passkey_continuation_notification(self: Arc<Self>, node: Node) {
+ if !from_server(&node) {
+ tracing::warn!("ignoring passkey continuation notification from non-server JID");
+ return;
+ }
+ if let Err(error) = self.handle_passkey_continuation_notification(&node).await {
+ tracing::warn!(error = %error, "failed to handle passkey continuation notification");
+ self.dispatch_event(Event::PairPasskeyError(PairPasskeyError {
+ error: Arc::new(error),
+ continuation: true,
+ }))
+ .await;
+ }
+ }
+
+ async fn handle_passkey_continuation_notification(
+ &self,
+ node: &Node,
+ ) -> Result<(), ClientError> {
+ let cache = lock(&self.passkey_state).linking.clone().ok_or_else(|| {
+ ClientError::Other(
+ "received passkey continuation notification without a linking cache".to_owned(),
+ )
+ })?;
+ let primary = parse_passkey_continuation_notification(node)
+ .map_err(|error| error.wrap("failed to parse passkey continuation notification"))?;
+ let primary_public: [u8; 32] = primary
+ .public_key
+ .as_deref()
+ .unwrap_or_default()
+ .try_into()
+ .map_err(|_| ClientError::Other("bad primary public key".to_owned()))?;
+ self.send_iq(InfoQuery {
+ namespace: "md",
+ r#type: IqType::Set,
+ to: SERVER_JID.clone(),
+ content: Some(NodeContent::Nodes(vec![bytes_node(
+ "companion_nonce",
+ cache.companion_nonce.clone(),
+ )])),
+ ..Default::default()
+ })
+ .await
+ .map_err(|error| error.wrap("failed to send companion nonce"))?;
+ let (encryption_key, code) = passkey_confirmation_code(
+ cache.key_pair.private,
+ &cache.companion_nonce,
+ cache.device_type,
+ &cache.pairing_ref,
+ &primary_public,
+ primary.nonce.as_deref().unwrap_or_default(),
+ )?;
+ let skip_handoff_ux = {
+ let mut state = lock(&self.passkey_state);
+ if let Some(linking) = state.linking.as_mut() {
+ linking.encryption_key = Some(encryption_key);
+ }
+ state.skip_handoff_ux
+ };
+ self.dispatch_event(Event::PairPasskeyConfirmation(PairPasskeyConfirmation {
+ code,
+ skip_handoff_ux,
+ }))
+ .await;
+ Ok(())
+ }
+
+ /// Confirms that the code of [`Event::PairPasskeyConfirmation`] was shown
+ /// and accepted, finishing the pairing (`SendPasskeyConfirmation`).
+ #[tracing::instrument(name = "whatsmeow.pair.passkey_confirmation", skip_all, err)]
+ pub async fn send_passkey_confirmation(&self) -> Result<(), ClientError> {
+ let encryption_key = {
+ let state = lock(&self.passkey_state);
+ let cache = state.linking.as_ref().ok_or_else(|| {
+ ClientError::Other("no passkey linking cache available".to_owned())
+ })?;
+ cache.encryption_key.clone().ok_or_else(|| {
+ ClientError::Other(
+ "passkey linking cache does not have an encryption key yet".to_owned(),
+ )
+ })?
+ };
+ let request = {
+ let store = self.store.read().await;
+ PairingRequest {
+ companion_public_key: Some(store.noise_key.public.to_vec()),
+ companion_identity_key: Some(store.identity_key.public.to_vec()),
+ adv_secret: Some(store.adv_secret_key.clone()),
+ }
+ .encode_to_vec()
+ };
+ let iv: [u8; 12] = rand::random();
+ let encrypted_request =
+ gcmutil::encrypt(&encryption_key, &iv, &request, &[]).map_err(|error| {
+ ClientError::Other(format!("failed to encrypt PairingRequest: {error}"))
+ })?;
+ let wrapped_request = EncryptedPairingRequest {
+ encrypted_payload: Some(encrypted_request),
+ iv: Some(iv.to_vec()),
+ }
+ .encode_to_vec();
+ self.send_iq(InfoQuery {
+ namespace: "md",
+ r#type: IqType::Set,
+ to: SERVER_JID.clone(),
+ content: Some(NodeContent::Nodes(vec![bytes_node(
+ "encrypted_pairing_request",
+ wrapped_request,
+ )])),
+ ..Default::default()
+ })
+ .await?;
+ lock(&self.passkey_state).linking = None;
+ Ok(())
+ }
+
+ async fn get_companion_ref(&self) -> Result<String, ClientError> {
+ let response = self
+ .send_iq(InfoQuery {
+ namespace: "md",
+ r#type: IqType::Get,
+ to: SERVER_JID.clone(),
+ content: Some(NodeContent::Nodes(vec![Node {
+ tag: "ref".to_owned(),
+ ..Node::default()
+ }])),
+ ..Default::default()
+ })
+ .await?;
+ let reference = response
+ .get_optional_child_by_tag(&["ref"])
+ .ok_or_else(|| element_missing("ref", "get ref response"))?;
+ match &reference.content {
+ Some(NodeContent::Bytes(bytes)) => Ok(String::from_utf8_lossy(bytes).into_owned()),
+ _ => Err(ClientError::Other(
+ "unexpected content type for <ref> node".to_owned(),
+ )),
+ }
+ }
+
+ async fn get_passkey_request_options(&self) -> Result<WebAuthnPublicKey, ClientError> {
+ let response = self
+ .send_iq(InfoQuery {
+ namespace: "md",
+ r#type: IqType::Get,
+ to: SERVER_JID.clone(),
+ content: Some(NodeContent::Nodes(vec![Node {
+ tag: "passkey_request_options".to_owned(),
+ ..Node::default()
+ }])),
+ ..Default::default()
+ })
+ .await?;
+ parse_passkey_notification(&response)
+ }
+}
+
+#[cfg(test)]
+mod test;
diff --git a/crates/whatsmeow/src/pair_passkey/test.rs b/crates/whatsmeow/src/pair_passkey/test.rs
new file mode 100644
index 0000000000..be5f4214b8
--- /dev/null
+++ b/crates/whatsmeow/src/pair_passkey/test.rs
@@ -0,0 +1,206 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+//! Passkey pairing on the fake server, with the server and phone side of
+//! the key agreement computed independently in the test.
+
+use std::sync::Arc;
+
+use super::*;
+use crate::client::test::{bytes, children, harness, next_event, next_node, node, text};
+use crate::testing::{attr_string, is_iq};
+use crate::types::UnpaddedUrlBytes;
+
+fn child_bytes(node: &Node, tag: &str) -> Vec<u8> {
+ match &node.get_child_by_tag(&[tag]).content {
+ Some(NodeContent::Bytes(bytes)) => bytes.clone(),
+ _ => panic!("<{tag}> has bytes"),
+ }
+}
+
+#[test]
+fn webauthn_json_round_trips_with_go_field_names() {
+ let json = r#"{"challenge":"AAEC","timeout":60000,"rpId":"whatsapp.com","allowCredentials":[{"id":"_wAB","type":"public-key","transports":["hybrid"]}],"userVerification":"preferred","extensions":{"appid":"x"}}"#;
+ let options: WebAuthnPublicKey = serde_json::from_str(json).unwrap();
+ assert_eq!(options.challenge.0, [0, 1, 2]);
+ assert_eq!(options.allow_credentials[0].id.0, [255, 0, 1]);
+ let response = WebAuthnResponse {
+ id: "_wAB".to_owned(),
+ raw_id: UnpaddedUrlBytes(vec![255, 0, 1]),
+ r#type: "public-key".to_owned(),
+ response: Default::default(),
+ };
+ assert_eq!(
+ serde_json::to_string(&response).unwrap(),
+ r#"{"id":"_wAB","rawId":"_wAB","type":"public-key","response":{"clientDataJSON":"","authenticatorData":"","signature":"","userHandle":null}}"#
+ );
+}
+
+#[tokio::test(start_paused = true)]
+async fn pairing_with_a_passkey_and_confirmation_code() {
+ let mut harness = harness(None);
+ harness.client.connect().await.unwrap();
+ let mut connection = harness.server.accept().await.unwrap();
+ let old_adv_secret = harness.client.store.read().await.adv_secret_key.clone();
+
+ let options = br#"{"challenge":"AAEC","timeout":60000,"rpId":"whatsapp.com","allowCredentials":[],"userVerification":"required","extensions":{}}"#;
+ connection
+ .send_node(&node(
+ "notification",
+ &[
+ ("from", AttributeValue::Jid(SERVER_JID.clone())),
+ ("id", text("N1")),
+ ("type", text("passkey_prologue_request")),
+ ],
+ children(vec![node("passkey_request_options", &[], bytes(options))]),
+ ))
+ .await;
+ let request = loop {
+ if let Event::PairPasskeyRequest(request) = next_event(&mut harness.events).await {
+ break request;
+ }
+ };
+ assert_eq!(request.public_key.relying_party_id, "whatsapp.com");
+ assert_ne!(
+ harness.client.store.read().await.adv_secret_key,
+ old_adv_secret
+ );
+
+ let client = Arc::clone(&harness.client);
+ let response = tokio::spawn(async move {
+ client
+ .send_passkey_response(&WebAuthnResponse {
+ id: "_wAB".to_owned(),
+ raw_id: UnpaddedUrlBytes(vec![255, 0, 1]),
+ r#type: "public-key".to_owned(),
+ response: Default::default(),
+ })
+ .await
+ });
+ let ref_query = loop {
+ let request = next_node(&mut connection).await;
+ if is_iq(&request, "md") {
+ break request;
+ }
+ };
+ assert_eq!(attr_string(&ref_query, "type"), "get");
+ connection
+ .respond_iq(&ref_query, vec![node("ref", &[], bytes(b"2@companionref"))])
+ .await;
+ let prologue_iq = next_node(&mut connection).await;
+ let prologue_node = prologue_iq.get_child_by_tag(&["passkey_prologue"]);
+ assert_eq!(child_bytes(prologue_node, "credential_id"), [255, 0, 1]);
+ let prologue = child_bytes(prologue_node, "prologue_payload");
+ assert_eq!(
+ child_bytes(prologue_node, "pairing_handoff_proof"),
+ pairing_handoff_proof(&passkey_handoff_hmac_key(&old_adv_secret), &prologue)
+ );
+ let payload = ProloguePayload::decode(prologue.as_slice()).unwrap();
+ let identity = CompanionEphemeralIdentity::decode(
+ payload.companion_ephemeral_identity.as_deref().unwrap(),
+ )
+ .unwrap();
+ assert_eq!(identity.r#ref.as_deref(), Some("2@companionref"));
+ connection.respond_iq(&prologue_iq, vec![]).await;
+ response.await.unwrap().unwrap();
+
+ // The phone answers with its ephemeral identity.
+ let primary = new_key_pair();
+ let primary_nonce = [8; 32];
+ connection
+ .send_node(&node(
+ "notification",
+ &[
+ ("from", AttributeValue::Jid(SERVER_JID.clone())),
+ ("id", text("N2")),
+ ("type", text("crsc_continuation")),
+ ],
+ children(vec![node(
+ "primary_ephemeral_identity",
+ &[],
+ bytes(
+ &PrimaryEphemeralIdentity {
+ public_key: Some(primary.public.to_vec()),
+ nonce: Some(primary_nonce.to_vec()),
+ }
+ .encode_to_vec(),
+ ),
+ )]),
+ ))
+ .await;
+ let nonce_iq = loop {
+ let request = next_node(&mut connection).await;
+ if is_iq(&request, "md") {
+ break request;
+ }
+ };
+ let companion_nonce = child_bytes(&nonce_iq, "companion_nonce");
+ assert_eq!(
+ payload.commitment.unwrap().hash.unwrap(),
+ Sha256::new()
+ .chain_update(payload.companion_ephemeral_identity.as_deref().unwrap())
+ .chain_update(&companion_nonce)
+ .finalize()
+ .to_vec()
+ );
+ connection.respond_iq(&nonce_iq, vec![]).await;
+ let confirmation = loop {
+ if let Event::PairPasskeyConfirmation(confirmation) = next_event(&mut harness.events).await
+ {
+ break confirmation;
+ }
+ };
+ assert!(confirmation.skip_handoff_ux);
+ // The phone computes the same key from its side of the agreement and
+ // the same code from the nonces.
+ let companion_public: [u8; 32] = identity.public_key.unwrap().try_into().unwrap();
+ let shared = x25519_dalek::x25519(primary.private, companion_public);
+ let encryption_key = hkdfutil::sha256(
+ &shared,
+ format!(
+ "Companion Pairing {} with ref 2@companionref",
+ identity.device_type.unwrap_or_default()
+ )
+ .as_bytes(),
+ b"Pairing Information Encryption Key",
+ 32,
+ );
+ let digest = Sha256::new()
+ .chain_update(&companion_nonce)
+ .chain_update(primary.public)
+ .finalize();
+ let code_bytes: Vec<u8> = (0..5)
+ .map(|index| primary_nonce[index] ^ digest[index])
+ .collect();
+ let code = linking_base32(&code_bytes);
+ assert_eq!(confirmation.code, format!("{}-{}", &code[..4], &code[4..]));
+
+ let client = Arc::clone(&harness.client);
+ let confirm = tokio::spawn(async move { client.send_passkey_confirmation().await });
+ let pairing_iq = next_node(&mut connection).await;
+ let wrapped = EncryptedPairingRequest::decode(
+ child_bytes(&pairing_iq, "encrypted_pairing_request").as_slice(),
+ )
+ .unwrap();
+ let request = PairingRequest::decode(
+ gcmutil::decrypt(
+ &encryption_key,
+ wrapped.iv.as_deref().unwrap(),
+ wrapped.encrypted_payload.as_deref().unwrap(),
+ &[],
+ )
+ .unwrap()
+ .as_slice(),
+ )
+ .unwrap();
+ let store = harness.client.store.read().await;
+ assert_eq!(
+ request.companion_public_key.unwrap(),
+ store.noise_key.public
+ );
+ assert_eq!(request.adv_secret.unwrap(), store.adv_secret_key);
+ drop(store);
+ connection.respond_iq(&pairing_iq, vec![]).await;
+ confirm.await.unwrap().unwrap();
+}
diff --git a/crates/whatsmeow/src/prekeys.rs b/crates/whatsmeow/src/prekeys.rs
new file mode 100644
index 0000000000..cc45408a98
--- /dev/null
+++ b/crates/whatsmeow/src/prekeys.rs
@@ -0,0 +1,362 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+//
+// Ported from whatsmeow prekeys.go (MPL-2.0, Copyright (c) Tulir Asokan)
+//
+// Go's `nodeToPreKey` fills a `keys.PreKey` with only the public half; here
+// a received prekey is its own [`ReceivedPreKey`], since a local `PreKey`
+// always has its private key.
+
+//! Uploading this device's prekeys and fetching other devices' prekey bundles.
+
+use std::collections::HashMap;
+use std::time::Duration;
+
+use crate::binary::{Node, NodeContent};
+use crate::client::Client;
+use crate::errors::ClientError;
+use crate::request::{InfoQuery, IqType};
+use crate::signal::{DJB_TYPE, PreKeyBundle};
+use crate::types::{Jid, SERVER_JID};
+use crate::util::keys::PreKey;
+
+/// How many prekeys the client uploads in one batch.
+pub const WANTED_PRE_KEY_COUNT: u32 = 50;
+/// How many prekeys the initial upload after pairing contains.
+pub const INITIAL_PRE_KEY_COUNT: u32 = 812;
+/// Below this many prekeys on the server, the client uploads a new batch.
+pub const MIN_PRE_KEY_COUNT: usize = 5;
+
+/// A prekey from another device's bundle.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct ReceivedPreKey {
+ /// The prekey ID.
+ pub key_id: u32,
+ /// The public key.
+ pub public: [u8; 32],
+ /// The signature, for signed prekeys.
+ pub signature: Option<[u8; 64]>,
+}
+
+/// The result of fetching one device's prekey bundle (`preKeyResp`).
+pub(crate) type PreKeyResponse = Result<PreKeyBundle, ClientError>;
+
+impl Client {
+ /// How many prekeys the server has left for this device.
+ pub(crate) async fn get_server_pre_key_count(&self) -> Result<usize, ClientError> {
+ let response = self
+ .send_iq(InfoQuery {
+ namespace: "encrypt",
+ r#type: IqType::Get,
+ to: SERVER_JID.clone(),
+ content: Some(NodeContent::Nodes(vec![Node {
+ tag: "count".to_owned(),
+ ..Node::default()
+ }])),
+ ..Default::default()
+ })
+ .await
+ .map_err(|error| error.wrap("failed to get prekey count on server"))?;
+ let count = response.get_child_by_tag(&["count"]);
+ let mut attrs = count.attr_getter();
+ let value = attrs.int("value");
+ attrs.error()?;
+ Ok(usize::try_from(value).unwrap_or_default())
+ }
+
+ /// Uploads a batch of prekeys (812 on the first upload after pairing).
+ pub(crate) async fn upload_pre_keys(&self, initial_upload: bool) {
+ let mut last_upload = self.upload_pre_keys_lock.lock().await;
+ if let Some(last) = *last_upload
+ && last + Duration::from_secs(10 * 60) > tokio::time::Instant::now()
+ {
+ let server_count = self.get_server_pre_key_count().await.unwrap_or_default();
+ if server_count >= usize::try_from(WANTED_PRE_KEY_COUNT).unwrap_or(usize::MAX) {
+ tracing::debug!("canceling prekey upload request due to likely race condition");
+ return;
+ }
+ }
+ let (registration_id, identity_public, signed_pre_key, pre_key_store) = {
+ let store = self.store.read().await;
+ (
+ store.registration_id,
+ store.identity_key.public,
+ store.signed_pre_key.clone(),
+ std::sync::Arc::clone(&store.pre_keys),
+ )
+ };
+ let wanted_count = if initial_upload {
+ INITIAL_PRE_KEY_COUNT
+ } else {
+ WANTED_PRE_KEY_COUNT
+ };
+ let pre_keys = match pre_key_store.get_or_gen_pre_keys(wanted_count).await {
+ Ok(pre_keys) => pre_keys,
+ Err(error) => {
+ tracing::error!(error = %error, "failed to get prekeys to upload");
+ return;
+ }
+ };
+ let Some(last_key_id) = pre_keys.last().map(|key| key.key_id) else {
+ tracing::error!("prekey store returned no prekeys to upload");
+ return;
+ };
+ tracing::info!(count = pre_keys.len(), "uploading new prekeys to server");
+ let result = self
+ .send_iq(InfoQuery {
+ namespace: "encrypt",
+ r#type: IqType::Set,
+ to: SERVER_JID.clone(),
+ content: Some(NodeContent::Nodes(vec![
+ bytes_node("registration", registration_id.to_be_bytes().to_vec()),
+ bytes_node("type", vec![DJB_TYPE]),
+ bytes_node("identity", identity_public.to_vec()),
+ Node {
+ tag: "list".to_owned(),
+ content: Some(NodeContent::Nodes(pre_keys_to_nodes(&pre_keys))),
+ ..Node::default()
+ },
+ pre_key_to_node(&signed_pre_key),
+ ])),
+ ..Default::default()
+ })
+ .await;
+ if let Err(error) = result {
+ tracing::error!(error = %error, "failed to send request to upload prekeys");
+ return;
+ }
+ tracing::debug!("got response to uploading prekeys");
+ if let Err(error) = pre_key_store.mark_pre_keys_as_uploaded(last_key_id).await {
+ tracing::warn!(error = %error, "failed to mark prekeys as uploaded");
+ return;
+ }
+ *last_upload = Some(tokio::time::Instant::now());
+ self.pre_keys_uploaded.set();
+ }
+
+ /// Fetches prekey bundles, logging and skipping failures
+ /// (`fetchPreKeysNoError`).
+ pub(crate) async fn fetch_pre_keys_no_error(
+ &self,
+ retry_devices: &[Jid],
+ ) -> HashMap<Jid, PreKeyBundle> {
+ if retry_devices.is_empty() {
+ return HashMap::new();
+ }
+ let responses = match self.fetch_pre_keys(retry_devices).await {
+ Ok(responses) => responses,
+ Err(error) => {
+ tracing::warn!(error = %error, count = retry_devices.len(), "failed to fetch prekeys for devices with no existing session");
+ return HashMap::new();
+ }
+ };
+ let mut bundles = HashMap::with_capacity(retry_devices.len());
+ for (jid, response) in responses {
+ match response {
+ Ok(bundle) => {
+ bundles.insert(jid, bundle);
+ }
+ Err(error) => tracing::warn!(error = %error, "failed to fetch prekey for device"),
+ }
+ }
+ bundles
+ }
+
+ /// Fetches the prekey bundles of devices.
+ pub(crate) async fn fetch_pre_keys(
+ &self,
+ users: &[Jid],
+ ) -> Result<HashMap<Jid, PreKeyResponse>, ClientError> {
+ let requests = users
+ .iter()
+ .map(|user| Node {
+ tag: "user".to_owned(),
+ attrs: crate::binary::Attrs::from([
+ ("jid".to_owned(), user.into()),
+ ("reason".to_owned(), "identity".into()),
+ ]),
+ content: None,
+ })
+ .collect();
+ let response = self
+ .send_iq(InfoQuery {
+ namespace: "encrypt",
+ r#type: IqType::Get,
+ to: SERVER_JID.clone(),
+ content: Some(NodeContent::Nodes(vec![Node {
+ tag: "key".to_owned(),
+ content: Some(NodeContent::Nodes(requests)),
+ ..Node::default()
+ }])),
+ ..Default::default()
+ })
+ .await
+ .map_err(|error| error.wrap("failed to send prekey request"))?;
+ if response.get_children().is_empty() {
+ return Err(ClientError::Other(
+ "got empty response to prekey request".to_owned(),
+ ));
+ }
+ let list = response.get_child_by_tag(&["list"]);
+ let mut responses = HashMap::new();
+ for child in list.get_children() {
+ if child.tag != "user" {
+ continue;
+ }
+ let jid = child.attr_getter().jid("jid");
+ let bundle = node_to_pre_key_bundle(u32::from(jid.device), child);
+ responses.insert(jid, bundle);
+ }
+ Ok(responses)
+ }
+}
+
+fn bytes_node(tag: &str, content: Vec<u8>) -> Node {
+ Node {
+ tag: tag.to_owned(),
+ content: Some(NodeContent::Bytes(content)),
+ ..Node::default()
+ }
+}
+
+/// The `<key>` (or `<skey>` for signed prekeys) node of a prekey.
+pub fn pre_key_to_node(key: &PreKey) -> Node {
+ let key_id = key.key_id.to_be_bytes();
+ let mut children = vec![
+ bytes_node("id", key_id[1..].to_vec()),
+ bytes_node("value", key.key_pair.public.to_vec()),
+ ];
+ let tag = match key.signature {
+ Some(signature) => {
+ children.push(bytes_node("signature", signature.to_vec()));
+ "skey"
+ }
+ None => "key",
+ };
+ Node {
+ tag: tag.to_owned(),
+ content: Some(NodeContent::Nodes(children)),
+ ..Node::default()
+ }
+}
+
+fn node_bytes<'node>(node: &'node Node, tag: &str) -> Option<&'node [u8]> {
+ match &node.get_optional_child_by_tag(&[tag])?.content {
+ Some(NodeContent::Bytes(bytes)) => Some(bytes),
+ _ => None,
+ }
+}
+
+/// Parses a `<user>` node of a prekey response into a bundle.
+pub fn node_to_pre_key_bundle(device_id: u32, node: &Node) -> Result<PreKeyBundle, ClientError> {
+ if let Some(error_node) = node.get_optional_child_by_tag(&["error"]) {
+ return Err(ClientError::Other(format!(
+ "got error getting prekeys: {error_node}"
+ )));
+ }
+ let registration_id = node_bytes(node, "registration")
+ .and_then(|bytes| <[u8; 4]>::try_from(bytes).ok())
+ .map(u32::from_be_bytes)
+ .ok_or_else(|| {
+ ClientError::Other("invalid registration ID in prekey response".to_owned())
+ })?;
+
+ let keys_node = node.get_optional_child_by_tag(&["keys"]).unwrap_or(node);
+
+ let identity_key = node_bytes(keys_node, "identity")
+ .and_then(|bytes| <[u8; 32]>::try_from(bytes).ok())
+ .ok_or_else(|| ClientError::Other("invalid identity key in prekey response".to_owned()))?;
+
+ let pre_key = match keys_node.get_optional_child_by_tag(&["key"]) {
+ Some(pre_key_node) => Some(node_to_pre_key(pre_key_node).map_err(|error| {
+ ClientError::Other(format!("invalid prekey in prekey response: {error}"))
+ })?),
+ None => None,
+ };
+ let signed_pre_key =
+ node_to_pre_key(keys_node.get_child_by_tag(&["skey"])).map_err(|error| {
+ ClientError::Other(format!("invalid signed prekey in prekey response: {error}"))
+ })?;
+ let signed_pre_key_signature = signed_pre_key.signature.ok_or_else(|| {
+ ClientError::Other("invalid signed prekey in prekey response: missing signature".to_owned())
+ })?;
+
+ Ok(PreKeyBundle {
+ registration_id,
+ device_id,
+ pre_key: pre_key.map(|key| (key.key_id, key.public)),
+ signed_pre_key_id: signed_pre_key.key_id,
+ signed_pre_key_public: signed_pre_key.public,
+ signed_pre_key_signature,
+ identity_key,
+ })
+}
+
+/// Parses a `<key>` or `<skey>` node.
+pub fn node_to_pre_key(node: &Node) -> Result<ReceivedPreKey, String> {
+ let id = node.get_child_by_tag(&["id"]);
+ let key_id = if id.tag != "id" {
+ return Err("prekey node doesn't contain ID tag".to_owned());
+ } else {
+ match &id.content {
+ Some(NodeContent::Bytes(bytes)) if bytes.len() == 3 => {
+ u32::from_be_bytes([0, bytes[0], bytes[1], bytes[2]])
+ }
+ Some(NodeContent::Bytes(bytes)) => {
+ return Err(format!(
+ "prekey ID has unexpected number of bytes ({}, expected 3)",
+ bytes.len()
+ ));
+ }
+ _ => return Err("prekey ID has unexpected content".to_owned()),
+ }
+ };
+ let value = node.get_child_by_tag(&["value"]);
+ let public = if value.tag != "value" {
+ return Err("prekey node doesn't contain value tag".to_owned());
+ } else {
+ match &value.content {
+ Some(NodeContent::Bytes(bytes)) => {
+ <[u8; 32]>::try_from(bytes.as_slice()).map_err(|_| {
+ format!(
+ "prekey value has unexpected number of bytes ({}, expected 32)",
+ bytes.len()
+ )
+ })?
+ }
+ _ => return Err("prekey value has unexpected content".to_owned()),
+ }
+ };
+ let mut signature = None;
+ if node.tag == "skey" {
+ let signature_node = node.get_child_by_tag(&["signature"]);
+ if signature_node.tag != "signature" {
+ return Err("prekey node doesn't contain signature tag".to_owned());
+ }
+ signature = Some(match &signature_node.content {
+ Some(NodeContent::Bytes(bytes)) => {
+ <[u8; 64]>::try_from(bytes.as_slice()).map_err(|_| {
+ format!(
+ "prekey signature has unexpected number of bytes ({}, expected 64)",
+ bytes.len()
+ )
+ })?
+ }
+ _ => return Err("prekey signature has unexpected content".to_owned()),
+ });
+ }
+ Ok(ReceivedPreKey {
+ key_id,
+ public,
+ signature,
+ })
+}
+
+/// The `<key>` nodes of many prekeys.
+pub fn pre_keys_to_nodes(pre_keys: &[PreKey]) -> Vec<Node> {
+ pre_keys.iter().map(pre_key_to_node).collect()
+}
+
+#[cfg(test)]
+mod test;
diff --git a/crates/whatsmeow/src/prekeys/test.rs b/crates/whatsmeow/src/prekeys/test.rs
new file mode 100644
index 0000000000..82bb2f0582
--- /dev/null
+++ b/crates/whatsmeow/src/prekeys/test.rs
@@ -0,0 +1,106 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+//! Expected bytes come from whatsmeow's `preKeyToNode` and
+//! `nodeToPreKeyBundle` (see `testdata/generator`).
+
+use super::*;
+use crate::binary::marshal;
+use crate::util::keys::new_key_pair_from_private_key;
+use crate::vectors::Vectors;
+
+fn fixed_private_key(start: u8) -> [u8; 32] {
+ std::array::from_fn(|index| start.wrapping_add(u8::try_from(index).unwrap()))
+}
+
+#[test]
+fn pre_key_nodes_match_go() {
+ let vectors = Vectors::load("prekeys.json");
+ let pre_key = PreKey {
+ key_pair: new_key_pair_from_private_key(fixed_private_key(0x30)),
+ key_id: 0x01_02_03,
+ signature: None,
+ };
+ assert_eq!(
+ hex::encode(marshal(&pre_key_to_node(&pre_key)).unwrap()),
+ vectors.string("pre_key_node")
+ );
+ let signed_pre_key = PreKey {
+ key_pair: new_key_pair_from_private_key(fixed_private_key(0x50)),
+ key_id: 1,
+ signature: Some([0x77; 64]),
+ };
+ assert_eq!(
+ hex::encode(marshal(&pre_key_to_node(&signed_pre_key)).unwrap()),
+ vectors.string("signed_pre_key_node")
+ );
+}
+
+#[test]
+fn pre_key_bundles_parse_like_go() {
+ let vectors = Vectors::load("prekeys.json");
+ let user = vectors.node("bundle_user_node");
+ let bundle = node_to_pre_key_bundle(7, &user).unwrap();
+ assert_eq!(
+ bundle.registration_id,
+ vectors.u64("bundle_registration_id") as u32
+ );
+ assert_eq!(bundle.device_id, 7);
+ assert_eq!(
+ bundle.pre_key,
+ Some((
+ vectors.u64("bundle_pre_key_id") as u32,
+ vectors.bytes("bundle_pre_key_public").try_into().unwrap()
+ ))
+ );
+ assert_eq!(
+ bundle.signed_pre_key_id,
+ vectors.u64("bundle_signed_pre_key_id") as u32
+ );
+ assert_eq!(
+ bundle.signed_pre_key_public.to_vec(),
+ vectors.bytes("bundle_signed_pre_key_public")
+ );
+ assert_eq!(
+ bundle.signed_pre_key_signature.to_vec(),
+ vectors.bytes("bundle_signed_pre_key_signature")
+ );
+ assert_eq!(
+ bundle.identity_key.to_vec(),
+ vectors.bytes("bundle_identity_key")
+ );
+
+ let without_pre_key = vectors.node("bundle_without_pre_key_node");
+ assert_eq!(
+ node_to_pre_key_bundle(7, &without_pre_key).unwrap().pre_key,
+ None
+ );
+
+ let error = vectors.node("bundle_error_node");
+ assert_eq!(
+ node_to_pre_key_bundle(7, &error).unwrap_err().to_string(),
+ vectors.string("bundle_error_message")
+ );
+}
+
+#[test]
+fn received_pre_keys_reject_bad_lengths() {
+ let key = pre_key_to_node(&PreKey {
+ key_pair: new_key_pair_from_private_key(fixed_private_key(1)),
+ key_id: 9,
+ signature: None,
+ });
+ let parsed = node_to_pre_key(&key).unwrap();
+ assert_eq!(parsed.key_id, 9);
+ assert_eq!(parsed.signature, None);
+
+ let mut short = key.clone();
+ if let Some(NodeContent::Nodes(children)) = &mut short.content {
+ children[0].content = Some(NodeContent::Bytes(vec![1, 2]));
+ }
+ assert_eq!(
+ node_to_pre_key(&short).unwrap_err(),
+ "prekey ID has unexpected number of bytes (2, expected 3)"
+ );
+}
diff --git a/crates/whatsmeow/src/presence.rs b/crates/whatsmeow/src/presence.rs
new file mode 100644
index 0000000000..00fb1a3692
--- /dev/null
+++ b/crates/whatsmeow/src/presence.rs
@@ -0,0 +1,182 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+//
+// Ported from whatsmeow presence.go (MPL-2.0, Copyright (c) Tulir Asokan)
+//
+// Messenger (`MessengerConfig`) isn't ported, so presences always carry the
+// push name.
+
+//! Online presence and typing notifications.
+
+use std::sync::Arc;
+use std::sync::atomic::Ordering;
+
+use crate::binary::{Attrs, Node, NodeContent};
+use crate::client::Client;
+use crate::errors::ClientError;
+use crate::types::events::{ChatPresence as ChatPresenceEvent, Event, Presence as PresenceEvent};
+use crate::types::{ChatPresence, ChatPresenceMedia, Jid, Presence};
+
+impl Client {
+ pub(crate) async fn handle_chat_state(&self, node: &Node) {
+ let source = match self.parse_message_source(node, true).await {
+ Ok(source) => source,
+ Err(error) => {
+ tracing::warn!(error = %error, "failed to parse chat state update");
+ return;
+ }
+ };
+ let children = node.get_children();
+ if children.len() != 1 {
+ tracing::warn!(
+ children = children.len(),
+ "failed to parse chat state update: unexpected number of children in element"
+ );
+ return;
+ }
+ let child = &children[0];
+ let presence = ChatPresence::from(child.tag.as_str());
+ if presence != ChatPresence::Composing && presence != ChatPresence::Paused {
+ tracing::warn!(state = %child.tag, "unrecognized chat presence state");
+ }
+ let media = ChatPresenceMedia::from(child.attr_getter().optional_string("media"));
+ self.dispatch_event(Event::ChatPresence(ChatPresenceEvent {
+ source,
+ state: presence,
+ media,
+ }))
+ .await;
+ }
+
+ pub(crate) async fn handle_presence(&self, node: &Node) {
+ let mut attrs = node.attr_getter();
+ let from = attrs.jid("from");
+ let presence_type = attrs.optional_string("type");
+ let unavailable = presence_type == "unavailable";
+ if !unavailable && !presence_type.is_empty() {
+ tracing::debug!(presence_type = %presence_type, "unrecognized presence type in presence event");
+ }
+ let last_seen = attrs.optional_string("last");
+ let last_seen = if !last_seen.is_empty() && last_seen != "deny" {
+ attrs.unix_time("last")
+ } else {
+ None
+ };
+ if !attrs.ok() {
+ tracing::warn!(error = ?attrs.error().err(), "error parsing presence event");
+ return;
+ }
+ self.dispatch_event(Event::Presence(PresenceEvent {
+ from,
+ unavailable,
+ last_seen,
+ }))
+ .await;
+ }
+
+ /// Updates the user's presence status on WhatsApp.
+ ///
+ /// Call this at least once after connecting so that the server has your
+ /// push name; otherwise other users see "-" as the name.
+ #[tracing::instrument(name = "whatsmeow.send_presence", skip_all, fields(state = %state), err)]
+ pub async fn send_presence(self: &Arc<Self>, state: Presence) -> Result<(), ClientError> {
+ let push_name = self.store.read().await.push_name.clone();
+ if push_name.is_empty() {
+ return Err(ClientError::NoPushName);
+ }
+ if state == Presence::Available {
+ let client = Arc::clone(self);
+ self.spawn(async move { client.send_unified_session().await });
+ let _ = self.send_active_receipts.compare_exchange(
+ 0,
+ 1,
+ Ordering::SeqCst,
+ Ordering::SeqCst,
+ );
+ } else {
+ let _ = self.send_active_receipts.compare_exchange(
+ 1,
+ 0,
+ Ordering::SeqCst,
+ Ordering::SeqCst,
+ );
+ }
+ self.send_node(&Node {
+ tag: "presence".to_owned(),
+ attrs: Attrs::from([
+ ("type".to_owned(), state.as_str().into()),
+ ("name".to_owned(), push_name.into()),
+ ]),
+ content: None,
+ })
+ .await
+ }
+
+ /// Asks the WhatsApp servers to send presence updates of a specific user
+ /// to this client, as [`Event::Presence`].
+ ///
+ /// The servers seem to require you to be online to receive presences, so
+ /// call [`Client::send_presence`] with [`Presence::Available`] first.
+ ///
+ /// Without a privacy token for the user this subscribes anyway, or returns
+ /// [`ClientError::NoPrivacyToken`] with
+ /// `error_on_subscribe_presence_without_token` (Go appends the JID to the
+ /// message; the port leaves it out of errors).
+ #[tracing::instrument(name = "whatsmeow.subscribe_presence", skip_all, err)]
+ pub async fn subscribe_presence(&self, jid: &Jid) -> Result<(), ClientError> {
+ let privacy_token = self
+ .ensure_tc_token(jid)
+ .await
+ .map_err(|error| error.wrap("failed to get privacy token"))?;
+ if privacy_token.is_none() {
+ if self.config.error_on_subscribe_presence_without_token {
+ return Err(ClientError::NoPrivacyToken);
+ }
+ tracing::debug!("trying to subscribe to presence without privacy token");
+ }
+ self.send_node(&Node {
+ tag: "presence".to_owned(),
+ attrs: Attrs::from([
+ ("type".to_owned(), "subscribe".into()),
+ ("to".to_owned(), jid.into()),
+ ]),
+ content: privacy_token.map(|token| {
+ NodeContent::Nodes(vec![Node {
+ tag: "tctoken".to_owned(),
+ attrs: Attrs::new(),
+ content: Some(NodeContent::Bytes(token)),
+ }])
+ }),
+ })
+ .await
+ }
+
+ /// Updates the user's typing status in a chat. `media` can say the user
+ /// is recording a voice message rather than typing text.
+ #[tracing::instrument(name = "whatsmeow.send_chat_presence", skip_all, fields(state = %state), err)]
+ pub async fn send_chat_presence(
+ &self,
+ jid: &Jid,
+ state: ChatPresence,
+ media: ChatPresenceMedia,
+ ) -> Result<(), ClientError> {
+ let mut attrs = Attrs::new();
+ if state == ChatPresence::Composing && !media.as_str().is_empty() {
+ attrs.insert("media".to_owned(), media.as_str().into());
+ }
+ self.send_node(&Node {
+ tag: "chatstate".to_owned(),
+ attrs: Attrs::from([("to".to_owned(), jid.into())]),
+ content: Some(NodeContent::Nodes(vec![Node {
+ tag: state.as_str().to_owned(),
+ attrs,
+ content: None,
+ }])),
+ })
+ .await
+ }
+}
+
+#[cfg(test)]
+mod test;
diff --git a/crates/whatsmeow/src/presence/test.rs b/crates/whatsmeow/src/presence/test.rs
new file mode 100644
index 0000000000..25b3619478
--- /dev/null
+++ b/crates/whatsmeow/src/presence/test.rs
@@ -0,0 +1,202 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+//! Presence nodes against whatsmeow's own output (`testdata/presence.json`,
+//! see `testdata/generator`), and incoming presences and chat states against
+//! the fake server.
+
+use std::sync::Arc;
+
+use super::*;
+use crate::binary::AttributeValue;
+use crate::client::test::{
+ capture_request, children, connect_paired, harness, jid, next_event, node, text,
+};
+use crate::types::parse_jid;
+use crate::vectors::Vectors;
+
+const OWN: (&str, &str) = ("1234:[email protected]", "9876:5@lid");
+
+#[tokio::test(start_paused = true)]
+async fn presence_nodes_match_go() {
+ let vectors = Vectors::load("presence.json");
+ let requests = vectors.value("requests");
+ let mut harness = harness(Some(OWN));
+ let mut connection = connect_paired(&mut harness).await;
+ let to = parse_jid("[email protected]").unwrap();
+
+ let expected = |key: &str| {
+ let data = hex::decode(requests[key].as_str().unwrap()).unwrap();
+ crate::binary::unmarshal(&crate::binary::unpack(&data).unwrap()).unwrap()
+ };
+ let client = Arc::clone(&harness.client);
+ let request = capture_request(&mut connection, async move {
+ client.send_presence(Presence::Unavailable).await
+ })
+ .await;
+ assert_eq!(request, expected("unavailable"));
+ let client = Arc::clone(&harness.client);
+ let target = to.clone();
+ let request = capture_request(&mut connection, async move {
+ client.subscribe_presence(&target).await
+ })
+ .await;
+ assert_eq!(request, expected("subscribe"));
+ let client = Arc::clone(&harness.client);
+ let target = to.clone();
+ let request = capture_request(&mut connection, async move {
+ client
+ .send_chat_presence(&target, ChatPresence::Composing, ChatPresenceMedia::Audio)
+ .await
+ })
+ .await;
+ assert_eq!(request, expected("composing_audio"));
+ let client = Arc::clone(&harness.client);
+ let request = capture_request(&mut connection, async move {
+ client
+ .send_chat_presence(&to, ChatPresence::Paused, ChatPresenceMedia::Audio)
+ .await
+ })
+ .await;
+ assert_eq!(request, expected("paused"));
+}
+
+#[tokio::test(start_paused = true)]
+async fn presence_needs_a_push_name_and_can_require_a_privacy_token() {
+ let mut harness = crate::client::test::harness_with(Some(OWN), |config| {
+ config.error_on_subscribe_presence_without_token = true;
+ });
+ let _connection = connect_paired(&mut harness).await;
+ let error = harness
+ .client
+ .subscribe_presence(&parse_jid("[email protected]").unwrap())
+ .await
+ .unwrap_err();
+ assert!(matches!(error, ClientError::NoPrivacyToken));
+
+ harness.client.store.write().await.push_name.clear();
+ let error = harness
+ .client
+ .send_presence(Presence::Available)
+ .await
+ .unwrap_err();
+ assert!(matches!(error, ClientError::NoPushName));
+}
+
+async fn next_presence_event(events: &mut tokio::sync::mpsc::UnboundedReceiver<Event>) -> Event {
+ loop {
+ let event = next_event(events).await;
+ if matches!(event, Event::Presence(_) | Event::ChatPresence(_)) {
+ return event;
+ }
+ }
+}
+
+#[tokio::test(start_paused = true)]
+async fn incoming_presences_and_chat_states_become_events() {
+ let mut harness = harness(Some(OWN));
+ let mut connection = connect_paired(&mut harness).await;
+
+ connection
+ .send_node(&node(
+ "presence",
+ &[
+ ("from", jid("[email protected]")),
+ ("type", text("unavailable")),
+ ("last", text("1700000000")),
+ ],
+ None,
+ ))
+ .await;
+ let Event::Presence(presence) = next_presence_event(&mut harness.events).await else {
+ panic!("expected a presence");
+ };
+ assert_eq!(presence.from.to_string(), "[email protected]");
+ assert!(presence.unavailable);
+ assert_eq!(
+ presence.last_seen.map(|time| time.timestamp()),
+ Some(1_700_000_000)
+ );
+
+ connection
+ .send_node(&node(
+ "presence",
+ &[("from", jid("6666@lid")), ("last", text("deny"))],
+ None,
+ ))
+ .await;
+ let Event::Presence(presence) = next_presence_event(&mut harness.events).await else {
+ panic!("expected a presence");
+ };
+ assert!(!presence.unavailable);
+ assert_eq!(presence.last_seen, None);
+
+ connection
+ .send_node(&node(
+ "chatstate",
+ &[
+ ("from", jid("[email protected]")),
+ ("participant", jid("6666@lid")),
+ ("participant_pn", jid("[email protected]")),
+ ],
+ children(vec![node("composing", &[("media", text("audio"))], None)]),
+ ))
+ .await;
+ let Event::ChatPresence(chat_presence) = next_presence_event(&mut harness.events).await else {
+ panic!("expected a chat presence");
+ };
+ assert_eq!(chat_presence.state, ChatPresence::Composing);
+ assert_eq!(chat_presence.media, ChatPresenceMedia::Audio);
+ assert!(chat_presence.source.is_group);
+ assert_eq!(
+ chat_presence.source.chat.to_string(),
+ );
+ assert_eq!(chat_presence.source.sender.to_string(), "6666@lid");
+ assert_eq!(
+ chat_presence.source.sender_alt.to_string(),
+ );
+
+ // A direct chat state from one of our own other devices.
+ connection
+ .send_node(&node(
+ "chatstate",
+ &[
+ (
+ "from",
+ AttributeValue::Jid(parse_jid("1234:[email protected]").unwrap()),
+ ),
+ ("recipient", jid("[email protected]")),
+ ],
+ children(vec![node("paused", &[], None)]),
+ ))
+ .await;
+ let Event::ChatPresence(chat_presence) = next_presence_event(&mut harness.events).await else {
+ panic!("expected a chat presence");
+ };
+ assert_eq!(chat_presence.state, ChatPresence::Paused);
+ assert!(chat_presence.source.is_from_me);
+ assert_eq!(chat_presence.source.chat.to_string(), "[email protected]");
+
+ // A chat state without exactly one child is dropped.
+ connection
+ .send_node(&node(
+ "chatstate",
+ &[("from", jid("[email protected]"))],
+ None,
+ ))
+ .await;
+ connection
+ .send_node(&node(
+ "presence",
+ &[("from", jid("[email protected]"))],
+ None,
+ ))
+ .await;
+ let Event::Presence(presence) = next_presence_event(&mut harness.events).await else {
+ panic!("the dropped chat state emits nothing");
+ };
+ assert_eq!(presence.from.to_string(), "[email protected]");
+}
diff --git a/crates/whatsmeow/src/privacysettings.rs b/crates/whatsmeow/src/privacysettings.rs
new file mode 100644
index 0000000000..65693496b5
--- /dev/null
+++ b/crates/whatsmeow/src/privacysettings.rs
@@ -0,0 +1,201 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+//
+// Ported from whatsmeow privacysettings.go (MPL-2.0, Copyright (c) Tulir Asokan)
+
+//! The user's privacy settings: fetching, caching and changing them.
+
+use std::sync::Arc;
+use std::time::Duration;
+
+use crate::binary::{Attrs, Node, NodeContent};
+use crate::client::{Client, lock};
+use crate::errors::{ClientError, element_missing};
+use crate::request::{InfoQuery, IqType};
+use crate::types::events::{Event, PrivacySettings as PrivacySettingsEvent};
+use crate::types::{PrivacySetting, PrivacySettingType, PrivacySettings, SERVER_JID};
+
+fn privacy_query(content: Vec<Node>) -> Option<NodeContent> {
+ Some(NodeContent::Nodes(vec![Node {
+ tag: "privacy".to_owned(),
+ attrs: Attrs::new(),
+ content: (!content.is_empty()).then_some(NodeContent::Nodes(content)),
+ }]))
+}
+
+/// Applies the `<category>` children of a `<privacy>` node to the settings
+/// and returns which ones changed.
+pub fn parse_privacy_settings(
+ privacy_node: &Node,
+ settings: &mut PrivacySettings,
+) -> PrivacySettingsEvent {
+ let mut event = PrivacySettingsEvent::default();
+ for child in privacy_node.get_children() {
+ if child.tag != "category" {
+ continue;
+ }
+ let mut attrs = child.attr_getter();
+ let name = PrivacySettingType::from(attrs.string("name"));
+ let value = PrivacySetting::from(attrs.string("value"));
+ match name {
+ PrivacySettingType::GroupAdd => {
+ settings.group_add = value;
+ event.group_add_changed = true;
+ }
+ PrivacySettingType::LastSeen => {
+ settings.last_seen = value;
+ event.last_seen_changed = true;
+ }
+ PrivacySettingType::Status => {
+ settings.status = value;
+ event.status_changed = true;
+ }
+ PrivacySettingType::Profile => {
+ settings.profile = value;
+ event.profile_changed = true;
+ }
+ PrivacySettingType::ReadReceipts => {
+ settings.read_receipts = value;
+ event.read_receipts_changed = true;
+ }
+ PrivacySettingType::Online => {
+ settings.online = value;
+ event.online_changed = true;
+ }
+ PrivacySettingType::CallAdd => {
+ settings.call_add = value;
+ event.call_add_changed = true;
+ }
+ PrivacySettingType::Messages => {
+ settings.messages = value;
+ event.messages_changed = true;
+ }
+ PrivacySettingType::Defense => {
+ settings.defense = value;
+ event.defense_changed = true;
+ }
+ PrivacySettingType::Stickers => {
+ settings.stickers = value;
+ event.stickers_changed = true;
+ }
+ PrivacySettingType::Other(_) => {}
+ }
+ }
+ event
+}
+
+impl Client {
+ /// The privacy settings, from the cache or the server
+ /// (`TryFetchPrivacySettings`).
+ #[tracing::instrument(name = "whatsmeow.privacy.fetch", skip_all, err)]
+ pub async fn try_fetch_privacy_settings(
+ &self,
+ ignore_cache: bool,
+ ) -> Result<PrivacySettings, ClientError> {
+ if !ignore_cache && let Some(settings) = lock(&self.privacy_settings_cache).clone() {
+ return Ok(settings);
+ }
+ let response = self
+ .send_iq(InfoQuery {
+ namespace: "privacy",
+ r#type: IqType::Get,
+ to: SERVER_JID.clone(),
+ content: privacy_query(Vec::new()),
+ ..Default::default()
+ })
+ .await?;
+ let privacy_node = response
+ .get_optional_child_by_tag(&["privacy"])
+ .ok_or_else(|| element_missing("privacy", "response to privacy settings query"))?;
+ let mut settings = PrivacySettings::default();
+ parse_privacy_settings(privacy_node, &mut settings);
+ *lock(&self.privacy_settings_cache) = Some(settings.clone());
+ Ok(settings)
+ }
+
+ /// The privacy settings, or the defaults if fetching fails (the error is
+ /// logged) (`GetPrivacySettings`).
+ pub async fn get_privacy_settings(&self) -> PrivacySettings {
+ self.try_fetch_privacy_settings(false)
+ .await
+ .inspect_err(
+ |error| tracing::error!(error = %error, "failed to fetch privacy settings"),
+ )
+ .unwrap_or_default()
+ }
+
+ /// Changes one privacy setting and returns the updated settings
+ /// (`SetPrivacySetting`).
+ pub async fn set_privacy_setting(
+ &self,
+ name: PrivacySettingType,
+ value: PrivacySetting,
+ ) -> Result<PrivacySettings, ClientError> {
+ let mut settings = self.try_fetch_privacy_settings(false).await?;
+ self.send_iq(InfoQuery {
+ namespace: "privacy",
+ r#type: IqType::Set,
+ to: SERVER_JID.clone(),
+ content: privacy_query(vec![Node {
+ tag: "category".to_owned(),
+ attrs: Attrs::from([
+ ("name".to_owned(), name.as_str().into()),
+ ("value".to_owned(), value.as_str().into()),
+ ]),
+ content: None,
+ }]),
+ ..Default::default()
+ })
+ .await?;
+ match name {
+ PrivacySettingType::GroupAdd => settings.group_add = value,
+ PrivacySettingType::LastSeen => settings.last_seen = value,
+ PrivacySettingType::Status => settings.status = value,
+ PrivacySettingType::Profile => settings.profile = value,
+ PrivacySettingType::ReadReceipts => settings.read_receipts = value,
+ PrivacySettingType::Online => settings.online = value,
+ PrivacySettingType::CallAdd => settings.call_add = value,
+ _ => {}
+ }
+ *lock(&self.privacy_settings_cache) = Some(settings.clone());
+ Ok(settings)
+ }
+
+ /// Sets the default disappearing message timer.
+ pub async fn set_default_disappearing_timer(&self, timer: Duration) -> Result<(), ClientError> {
+ self.send_iq(InfoQuery {
+ namespace: "disappearing_mode",
+ r#type: IqType::Set,
+ to: SERVER_JID.clone(),
+ content: Some(NodeContent::Nodes(vec![Node {
+ tag: "disappearing_mode".to_owned(),
+ attrs: Attrs::from([("duration".to_owned(), timer.as_secs().to_string().into())]),
+ content: None,
+ }])),
+ ..Default::default()
+ })
+ .await
+ .map(|_| ())
+ }
+
+ pub(crate) async fn handle_privacy_settings_notification(
+ self: &Arc<Self>,
+ privacy_node: &Node,
+ ) {
+ tracing::debug!("parsing privacy settings change notification");
+ let mut settings = match self.try_fetch_privacy_settings(false).await {
+ Ok(settings) => settings,
+ Err(error) => {
+ tracing::error!(error = %error, "failed to fetch privacy settings when handling change");
+ return;
+ }
+ };
+ let event = parse_privacy_settings(privacy_node, &mut settings);
+ *lock(&self.privacy_settings_cache) = Some(settings.clone());
+ self.dispatch_event(Event::PrivacySettings(event)).await;
+ }
+}
+
+#[cfg(test)]
+mod test;
diff --git a/crates/whatsmeow/src/privacysettings/test.rs b/crates/whatsmeow/src/privacysettings/test.rs
new file mode 100644
index 0000000000..db772e102d
--- /dev/null
+++ b/crates/whatsmeow/src/privacysettings/test.rs
@@ -0,0 +1,94 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+//! Privacy settings parsing against whatsmeow's output, and the fetch and
+//! cache on the fake server.
+
+use std::sync::Arc;
+
+use super::*;
+use crate::client::test::{connect_paired, harness, next_node, node, text};
+use crate::testing::is_iq;
+use crate::types::ReceiptType;
+use crate::vectors::Vectors;
+
+#[test]
+fn settings_parse_like_go() {
+ let vectors = Vectors::load("pairing_media.json");
+ let mut settings = PrivacySettings::default();
+ let event = parse_privacy_settings(&vectors.node("privacy_node"), &mut settings);
+ assert_eq!(
+ settings.read_receipts.as_str(),
+ vectors.string("privacy_read_receipts")
+ );
+ assert_eq!(
+ settings.last_seen.as_str(),
+ vectors.string("privacy_last_seen")
+ );
+ let changed: Vec<bool> = vectors
+ .value("privacy_changed")
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|value| value.as_bool().unwrap())
+ .collect();
+ assert_eq!(
+ changed,
+ [
+ event.read_receipts_changed,
+ event.last_seen_changed,
+ event.group_add_changed
+ ]
+ );
+}
+
+#[tokio::test(start_paused = true)]
+async fn read_receipts_follow_the_fetched_setting() {
+ let mut harness = harness(Some(("1234:[email protected]", "9876:5@lid")));
+ let mut connection = connect_paired(&mut harness).await;
+ let client = Arc::clone(&harness.client);
+ let mark = tokio::spawn(async move {
+ client
+ .mark_read(
+ &["M1".to_owned()],
+ chrono::Utc::now(),
+ &crate::types::parse_jid("[email protected]").unwrap(),
+ &crate::types::Jid::default(),
+ None,
+ )
+ .await
+ });
+ let query = next_node(&mut connection).await;
+ assert!(is_iq(&query, "privacy"));
+ connection
+ .respond_iq(
+ &query,
+ vec![node(
+ "privacy",
+ &[],
+ Some(NodeContent::Nodes(vec![node(
+ "category",
+ &[("name", text("readreceipts")), ("value", text("none"))],
+ None,
+ )])),
+ )],
+ )
+ .await;
+ let receipt = next_node(&mut connection).await;
+ assert_eq!(
+ crate::testing::attr_string(&receipt, "type"),
+ ReceiptType::ReadSelf.as_str()
+ );
+ mark.await.unwrap().unwrap();
+ // Cached now: no second query.
+ assert_eq!(
+ harness
+ .client
+ .try_fetch_privacy_settings(false)
+ .await
+ .unwrap()
+ .read_receipts,
+ PrivacySetting::None
+ );
+}
diff --git a/crates/whatsmeow/src/qrchan.rs b/crates/whatsmeow/src/qrchan.rs
new file mode 100644
index 0000000000..1e0c7d43a8
--- /dev/null
+++ b/crates/whatsmeow/src/qrchan.rs
@@ -0,0 +1,310 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+//
+// Ported from whatsmeow qrchan.go (MPL-2.0, Copyright (c) Tulir Asokan)
+//
+// Go's `QRChannelItem` with an `Event` string is the [`QrChannelItem`] enum.
+
+//! A channel of QR codes that rotates them until pairing ends.
+
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::{Arc, Mutex, Weak};
+use std::time::Duration;
+
+use async_trait::async_trait;
+use tokio::sync::mpsc;
+use tokio_util::sync::CancellationToken;
+
+use crate::client::{Client, EventHandler, lock};
+use crate::errors::ClientError;
+use crate::types::events::{Event, RotateAdvSecret};
+
+/// One item of the QR channel.
+#[derive(Clone, Debug)]
+pub enum QrChannelItem {
+ /// A new QR code to show until `timeout` passes.
+ Code {
+ /// The QR code contents.
+ code: String,
+ /// When the next code replaces it.
+ timeout: Duration,
+ },
+ /// Pairing failed.
+ Error(Arc<ClientError>),
+ /// Pairing succeeded (`QRChannelSuccess`).
+ Success,
+ /// The codes ran out or the server disconnected before pairing
+ /// (`QRChannelTimeout`).
+ Timeout,
+ /// An unexpected connection event: the device was probably paired before
+ /// the channel was set up (`QRChannelErrUnexpectedEvent`).
+ ErrUnexpectedEvent,
+ /// The client is outdated (`QRChannelClientOutdated`).
+ ClientOutdated,
+ /// The code was scanned by a phone without multidevice
+ /// (`QRChannelScannedWithoutMultidevice`).
+ ScannedWithoutMultidevice,
+ /// Pairing needs a passkey (`passkey-request`); answer with
+ /// `Client::send_passkey_response`.
+ PasskeyRequest(Box<crate::types::events::PairPasskeyRequest>),
+ /// Show the code and call `Client::send_passkey_confirmation`
+ /// (`passkey-confirmation`).
+ PasskeyConfirmation(crate::types::events::PairPasskeyConfirmation),
+}
+
+impl QrChannelItem {
+ /// Go's `Event` string of the item.
+ pub fn event(&self) -> &'static str {
+ match self {
+ QrChannelItem::Code { .. } => "code",
+ QrChannelItem::Error(_) => "error",
+ QrChannelItem::Success => "success",
+ QrChannelItem::Timeout => "timeout",
+ QrChannelItem::ErrUnexpectedEvent => "err-unexpected-state",
+ QrChannelItem::ClientOutdated => "err-client-outdated",
+ QrChannelItem::ScannedWithoutMultidevice => "err-scanned-without-multidevice",
+ QrChannelItem::PasskeyRequest(_) => "passkey-request",
+ QrChannelItem::PasskeyConfirmation(_) => "passkey-confirmation",
+ }
+ }
+}
+
+const QR_CHANNEL_SIZE: usize = 8;
+
+struct QrChannel {
+ client: Weak<Client>,
+ handler_id: Mutex<u32>,
+ closed: AtomicBool,
+ output: Mutex<Option<mpsc::Sender<QrChannelItem>>>,
+ stop_qrs: CancellationToken,
+ rotate_adv: mpsc::Sender<RotateAdvSecret>,
+ rotate_adv_receiver: tokio::sync::Mutex<Option<mpsc::Receiver<RotateAdvSecret>>>,
+ cancel: CancellationToken,
+}
+
+impl QrChannel {
+ /// Marks the channel closed; returns whether it was open.
+ fn close(&self) -> bool {
+ !self.closed.swap(true, Ordering::SeqCst)
+ }
+
+ fn output(&self) -> Option<mpsc::Sender<QrChannelItem>> {
+ lock(&self.output).clone()
+ }
+
+ fn close_output(&self) {
+ lock(&self.output).take();
+ }
+
+ async fn send(&self, item: QrChannelItem) {
+ if let Some(output) = self.output() {
+ let _ = output.send(item).await;
+ }
+ }
+
+ /// Removes the handler in the background (Go does it in a goroutine to
+ /// avoid a deadlock on the handler lock).
+ fn remove_handler(&self, client: &Client) {
+ client.remove_event_handler(*lock(&self.handler_id));
+ }
+
+ async fn emit_qrs(self: Arc<Self>, mut codes: Vec<String>) {
+ let Some(client) = self.client.upgrade() else {
+ return;
+ };
+ let mut rotate_adv = self.rotate_adv_receiver.lock().await.take();
+ loop {
+ if codes.is_empty() {
+ if self.close() {
+ tracing::debug!(
+ "ran out of QR codes, closing channel with timeout and disconnecting client"
+ );
+ self.send(QrChannelItem::Timeout).await;
+ self.close_output();
+ self.remove_handler(&client);
+ client.disconnect().await;
+ } else {
+ tracing::debug!("ran out of QR codes, but channel is already closed");
+ }
+ return;
+ } else if self.closed.load(Ordering::SeqCst) {
+ tracing::debug!("QR code channel is closed, exiting QR emitter");
+ return;
+ }
+ let timeout = if codes.len() == 6 {
+ Duration::from_secs(60)
+ } else {
+ Duration::from_secs(20)
+ };
+ let next_code = codes.remove(0);
+ let accepted = self.output().is_some_and(|output| {
+ output
+ .try_send(QrChannelItem::Code {
+ code: next_code.clone(),
+ timeout,
+ })
+ .is_ok()
+ });
+ if !accepted {
+ tracing::debug!("output channel didn't accept code, exiting QR emitter");
+ if self.close() {
+ self.close_output();
+ self.remove_handler(&client);
+ client.disconnect().await;
+ }
+ return;
+ }
+ let rotation = async {
+ match rotate_adv.as_mut() {
+ Some(receiver) => receiver.recv().await,
+ None => std::future::pending().await,
+ }
+ };
+ tokio::select! {
+ () = tokio::time::sleep(timeout) => {}
+ () = self.stop_qrs.cancelled() => {
+ tracing::debug!("got signal to stop QR emitter");
+ return;
+ }
+ () = client.expected_disconnect.wait() => {
+ tracing::debug!("client is expected to disconnect, stopping QR emitter");
+ return;
+ }
+ Some(rotation) = rotation => {
+ tracing::debug!("rotating ADV secrets in remaining QR codes");
+ let mut new_codes = Vec::with_capacity(codes.len() + 1);
+ new_codes.push(next_code.replacen(&rotation.old_secret, &rotation.new_secret, 1));
+ for code in &codes {
+ new_codes.push(code.replacen(&rotation.old_secret, &rotation.new_secret, 1));
+ }
+ codes = new_codes;
+ }
+ () = self.cancel.cancelled() => {
+ tracing::debug!("context is done, stopping QR emitter");
+ if self.close() {
+ self.close_output();
+ self.remove_handler(&client);
+ client.disconnect().await;
+ }
+ }
+ }
+ }
+ }
+}
+
+#[async_trait]
+impl EventHandler for Arc<QrChannel> {
+ async fn handle(&self, event: &Event) -> bool {
+ if self.closed.load(Ordering::SeqCst) {
+ tracing::debug!("dropping event, QR channel is closed");
+ return true;
+ }
+ let output = match event {
+ Event::Qr(qr) => {
+ tracing::debug!("received QR code event, starting to emit codes to channel");
+ let channel = Arc::clone(self);
+ let codes = qr.codes.clone();
+ if let Some(client) = self.client.upgrade() {
+ client.spawn(channel.emit_qrs(codes));
+ }
+ return true;
+ }
+ Event::RotateAdvSecret(rotation) => {
+ if self.rotate_adv.try_send(rotation.clone()).is_err() {
+ tracing::warn!("rotate ADV channel didn't accept event");
+ }
+ return true;
+ }
+ Event::QrScannedWithoutMultidevice(_) => {
+ tracing::debug!("QR code scanned without multidevice enabled");
+ self.send(QrChannelItem::ScannedWithoutMultidevice).await;
+ return true;
+ }
+ Event::PairPasskeyRequest(request) => {
+ self.send(QrChannelItem::PasskeyRequest(request.clone()))
+ .await;
+ return true;
+ }
+ Event::PairPasskeyConfirmation(confirmation) => {
+ if confirmation.skip_handoff_ux {
+ tracing::debug!("sending automatic passkey confirmation");
+ if let Some(client) = self.client.upgrade()
+ && let Err(error) = client.send_passkey_confirmation().await
+ {
+ self.send(QrChannelItem::Error(Arc::new(ClientError::Other(format!(
+ "failed to send passkey confirmation automatically: {error}"
+ )))))
+ .await;
+ }
+ } else {
+ self.send(QrChannelItem::PasskeyConfirmation(confirmation.clone()))
+ .await;
+ }
+ return true;
+ }
+ Event::PairPasskeyError(error) => {
+ self.send(QrChannelItem::Error(Arc::clone(&error.error)))
+ .await;
+ return true;
+ }
+ Event::ClientOutdated(_) => QrChannelItem::ClientOutdated,
+ Event::PairSuccess(_) => QrChannelItem::Success,
+ Event::PairError(error) => QrChannelItem::Error(Arc::clone(&error.error)),
+ Event::Disconnected(_) => QrChannelItem::Timeout,
+ Event::Connected(_)
+ | Event::ConnectFailure(_)
+ | Event::LoggedOut(_)
+ | Event::TemporaryBan(_) => QrChannelItem::ErrUnexpectedEvent,
+ _ => return true,
+ };
+ self.stop_qrs.cancel();
+ if self.close() {
+ tracing::debug!(status = output.event(), "closing QR channel");
+ self.send(output).await;
+ self.close_output();
+ } else {
+ tracing::debug!(
+ status = output.event(),
+ "got status, but QR channel is already closed"
+ );
+ }
+ if let Some(client) = self.client.upgrade() {
+ self.remove_handler(&client);
+ }
+ true
+ }
+}
+
+impl Client {
+ /// A channel that emits a new QR code whenever the previous one expires.
+ ///
+ /// Must be called before [`Client::connect`]. The last item is a final
+ /// status (success, timeout or an error); the channel closes after it.
+ /// Cancelling `cancel` stops the codes and disconnects.
+ pub async fn get_qr_channel(
+ self: &Arc<Self>,
+ cancel: CancellationToken,
+ ) -> Result<mpsc::Receiver<QrChannelItem>, ClientError> {
+ if self.is_connected().await {
+ return Err(ClientError::QrAlreadyConnected);
+ } else if self.store.read().await.id.is_some() {
+ return Err(ClientError::QrStoreContainsId);
+ }
+ let (output, receiver) = mpsc::channel(QR_CHANNEL_SIZE);
+ let (rotate_adv, rotate_adv_receiver) = mpsc::channel(4);
+ let channel = Arc::new(QrChannel {
+ client: Arc::downgrade(self),
+ handler_id: Mutex::new(0),
+ closed: AtomicBool::new(false),
+ output: Mutex::new(Some(output)),
+ stop_qrs: CancellationToken::new(),
+ rotate_adv,
+ rotate_adv_receiver: tokio::sync::Mutex::new(Some(rotate_adv_receiver)),
+ cancel,
+ });
+ let handler_id = self.add_event_handler(Arc::new(Arc::clone(&channel)));
+ *lock(&channel.handler_id) = handler_id;
+ Ok(receiver)
+ }
+}
diff --git a/crates/whatsmeow/src/receipt.rs b/crates/whatsmeow/src/receipt.rs
new file mode 100644
index 0000000000..277d49aa7a
--- /dev/null
+++ b/crates/whatsmeow/src/receipt.rs
@@ -0,0 +1,346 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+//
+// Ported from whatsmeow receipt.go (MPL-2.0, Copyright (c) Tulir Asokan)
+//
+// Go's `maybeDeferredAck` returns a closure to `defer`; here it returns a
+// [`DeferredAck`] the handler finishes with `finish_deferred_ack`.
+
+//! Receipts: receiving them, sending acks and sending read receipts.
+
+use std::sync::Arc;
+use std::sync::atomic::Ordering;
+
+use chrono::{DateTime, Utc};
+
+use crate::binary::{AttributeValue, Attrs, Node, NodeContent};
+use crate::client::Client;
+use crate::errors::{ClientError, element_missing};
+use crate::types::events::{Event, Receipt};
+use crate::types::{
+ DEFAULT_USER_SERVER, HIDDEN_USER_SERVER, Jid, MESSENGER_SERVER, MessageInfo, NEWSLETTER_SERVER,
+ PrivacySetting, ReceiptType,
+};
+
+/// The stanza couldn't be parsed.
+pub const NACK_PARSING_ERROR: i64 = 487;
+/// Unrecognized stanza.
+pub const NACK_UNRECOGNIZED_STANZA: i64 = 488;
+/// Unrecognized stanza class.
+pub const NACK_UNRECOGNIZED_STANZA_CLASS: i64 = 489;
+/// Unrecognized stanza type.
+pub const NACK_UNRECOGNIZED_STANZA_TYPE: i64 = 490;
+/// The protobuf didn't decode.
+pub const NACK_INVALID_PROTOBUF: i64 = 491;
+/// Invalid hosted companion stanza.
+pub const NACK_INVALID_HOSTED_COMPANION_STANZA: i64 = 493;
+/// The message secret is missing.
+pub const NACK_MISSING_MESSAGE_SECRET: i64 = 495;
+/// The Signal counter is old (already decrypted).
+pub const NACK_SIGNAL_ERROR_OLD_COUNTER: i64 = 496;
+/// The message was deleted on the peer.
+pub const NACK_MESSAGE_DELETED_ON_PEER: i64 = 499;
+/// An unhandled error.
+pub const NACK_UNHANDLED_ERROR: i64 = 500;
+/// Admin revokes aren't supported.
+pub const NACK_UNSUPPORTED_ADMIN_REVOKE: i64 = 550;
+/// LID groups aren't supported.
+pub const NACK_UNSUPPORTED_LID_GROUP: i64 = 551;
+/// A database operation failed.
+pub const NACK_DB_OPERATION_FAILED: i64 = 552;
+
+/// An ack that is sent when the handler finishes (with `synchronous_ack`)
+/// or was already sent in the background.
+/// The attributes every receipt for a node starts with.
+pub(crate) fn build_base_receipt(id: &str, node: &Node) -> Attrs {
+ let mut attrs = Attrs::from([("id".to_owned(), id.into())]);
+ if let Some(from) = node.attrs.get("from") {
+ attrs.insert("to".to_owned(), from.clone());
+ }
+ if let Some(recipient) = node.attrs.get("recipient") {
+ attrs.insert("recipient".to_owned(), recipient.clone());
+ }
+ if let Some(participant) = node.attrs.get("participant") {
+ attrs.insert("participant".to_owned(), participant.clone());
+ }
+ attrs
+}
+
+#[must_use = "finish the ack with Client::finish_deferred_ack"]
+pub(crate) struct DeferredAck {
+ node: Option<Node>,
+}
+
+impl Client {
+ pub(crate) async fn handle_receipt(self: &Arc<Self>, node: &Node) {
+ match self.parse_receipt(node).await {
+ Err(error) => {
+ tracing::warn!(error = %error, "failed to parse receipt");
+ let client = Arc::clone(self);
+ let node = node.clone();
+ self.spawn(async move { client.send_ack(&node, NACK_PARSING_ERROR).await });
+ }
+ Ok((receipt, Some(participants))) => {
+ let ack = self.maybe_deferred_ack(node);
+ let mut cancelled = false;
+ for participants_node in &participants {
+ cancelled = self
+ .handle_grouped_receipt(receipt.clone(), participants_node)
+ .await;
+ }
+ self.finish_deferred_ack(ack, cancelled).await;
+ }
+ Ok((receipt, None)) => {
+ if receipt.r#type == ReceiptType::Retry {
+ // The retry receipt handler acks by itself.
+ let client = Arc::clone(self);
+ let retry_receipt = receipt.clone();
+ let retry_node = node.clone();
+ self.background_if_async_ack(async move {
+ client
+ .try_handle_retry_receipt(&retry_receipt, &retry_node)
+ .await;
+ })
+ .await;
+ self.dispatch_event(Event::Receipt(receipt)).await;
+ } else {
+ let ack = self.maybe_deferred_ack(node);
+ let cancelled = self.dispatch_event(Event::Receipt(receipt)).await;
+ self.finish_deferred_ack(ack, cancelled).await;
+ }
+ }
+ }
+ }
+
+ async fn handle_grouped_receipt(&self, partial_receipt: Receipt, participants: &Node) -> bool {
+ let mut cancelled = false;
+ let mut participants_attrs = participants.attr_getter();
+ let mut partial_receipt = partial_receipt;
+ partial_receipt.message_ids = vec![participants_attrs.string("key")];
+ for child in participants.get_children() {
+ if child.tag != "user" {
+ tracing::warn!(tag = %child.tag, "unexpected node in grouped receipt participants");
+ continue;
+ }
+ let mut attrs = child.attr_getter();
+ let mut receipt = partial_receipt.clone();
+ receipt.timestamp = attrs.unix_time("t");
+ receipt.source.sender = attrs.jid("jid");
+ if !attrs.ok() {
+ tracing::warn!("failed to parse user node in grouped receipt");
+ continue;
+ }
+ cancelled = self.dispatch_event(Event::Receipt(receipt)).await || cancelled;
+ }
+ cancelled
+ }
+
+ /// Parses a `<receipt>`; grouped receipts return their `<participants>`
+ /// nodes too.
+ pub(crate) async fn parse_receipt(
+ &self,
+ node: &Node,
+ ) -> Result<(Receipt, Option<Vec<Node>>), ClientError> {
+ let source = self.parse_message_source(node, false).await?;
+ let mut attrs = node.attr_getter();
+ let mut receipt = Receipt {
+ timestamp: attrs.unix_time("t"),
+ r#type: ReceiptType::from(attrs.optional_string("type")),
+ message_sender: attrs.optional_jid_or_empty("recipient"),
+ source,
+ ..Receipt::default()
+ };
+ if receipt.source.is_group && receipt.source.sender.is_empty() {
+ let participants: Vec<Node> =
+ node.get_children_by_tag("participants").cloned().collect();
+ if participants.is_empty() {
+ return Err(element_missing("participants", "grouped receipt"));
+ }
+ return Ok((receipt, Some(participants)));
+ }
+ let main_message_id = attrs.string("id");
+ attrs.error().map_err(|error| {
+ ClientError::Other(format!("failed to parse read receipt attrs: {error}"))
+ })?;
+ let children = node.get_children();
+ if children.len() == 1 && children[0].tag == "list" {
+ receipt.message_ids = vec![main_message_id];
+ for item in children[0].get_children() {
+ if let Some(AttributeValue::String(id)) = item.attrs.get("id")
+ && item.tag == "item"
+ {
+ receipt.message_ids.push(id.clone());
+ }
+ }
+ } else {
+ receipt.message_ids = vec![main_message_id];
+ }
+ Ok((receipt, None))
+ }
+
+ /// Sends a read receipt (or `played` with `receipt_type`) for messages
+ /// one sender sent in a chat. `sender` is needed in groups.
+ #[tracing::instrument(name = "whatsmeow.mark_read", skip_all, fields(count = ids.len()), err)]
+ pub async fn mark_read(
+ &self,
+ ids: &[String],
+ timestamp: DateTime<Utc>,
+ chat: &Jid,
+ sender: &Jid,
+ receipt_type: Option<ReceiptType>,
+ ) -> Result<(), ClientError> {
+ let Some(first_id) = ids.first() else {
+ return Err(ClientError::Other("no message IDs specified".to_owned()));
+ };
+ let receipt_type = receipt_type.unwrap_or(ReceiptType::Read);
+ let mut attrs = Attrs::from([
+ ("id".to_owned(), first_id.clone().into()),
+ ("type".to_owned(), receipt_type.as_str().into()),
+ ("to".to_owned(), chat.into()),
+ ("t".to_owned(), timestamp.timestamp().into()),
+ ]);
+ if (chat.server == NEWSLETTER_SERVER
+ || self.get_privacy_settings().await.read_receipts == PrivacySetting::None)
+ && receipt_type == ReceiptType::Read
+ {
+ attrs.insert("type".to_owned(), ReceiptType::ReadSelf.as_str().into());
+ }
+ if !sender.is_empty()
+ && chat.server != DEFAULT_USER_SERVER
+ && chat.server != HIDDEN_USER_SERVER
+ && chat.server != MESSENGER_SERVER
+ {
+ attrs.insert("participant".to_owned(), sender.to_non_ad().into());
+ }
+ let content = (ids.len() > 1).then(|| {
+ NodeContent::Nodes(vec![Node {
+ tag: "list".to_owned(),
+ attrs: Attrs::new(),
+ content: Some(NodeContent::Nodes(
+ ids[1..]
+ .iter()
+ .map(|id| Node {
+ tag: "item".to_owned(),
+ attrs: Attrs::from([("id".to_owned(), id.clone().into())]),
+ content: None,
+ })
+ .collect(),
+ )),
+ }])
+ });
+ self.send_node(&Node {
+ tag: "receipt".to_owned(),
+ attrs,
+ content,
+ })
+ .await
+ }
+
+ /// Forces normal delivery receipts even when the client isn't marked
+ /// online (`SetForceActiveDeliveryReceipts`).
+ pub fn set_force_active_delivery_receipts(&self, active: bool) {
+ self.send_active_receipts
+ .store(if active { 2 } else { 0 }, Ordering::SeqCst);
+ }
+
+ pub(crate) async fn send_message_receipt(&self, info: &MessageInfo, node: &Node) {
+ let mut attrs = build_base_receipt(&info.id, node);
+ if info.is_from_me {
+ let receipt_type = if info.r#type == "peer_msg" {
+ ReceiptType::PeerMsg
+ } else {
+ ReceiptType::Sender
+ };
+ attrs.insert("type".to_owned(), receipt_type.as_str().into());
+ } else if self.send_active_receipts.load(Ordering::SeqCst) == 0 {
+ attrs.insert("type".to_owned(), ReceiptType::Inactive.as_str().into());
+ }
+ let receipt = Node {
+ tag: "receipt".to_owned(),
+ attrs,
+ content: None,
+ };
+ if let Err(error) = self.send_node(&receipt).await {
+ tracing::warn!(error = %error, "failed to send receipt");
+ }
+ }
+
+ /// Runs the closure now with `synchronous_ack`, else in the background.
+ pub(crate) async fn background_if_async_ack<Task>(&self, task: Task)
+ where
+ Task: Future<Output = ()> + Send + 'static,
+ {
+ if self.config.synchronous_ack {
+ task.await;
+ } else {
+ self.spawn(task);
+ }
+ }
+
+ /// Acks the node in the background now, or defers the ack until the
+ /// handler finishes when `synchronous_ack` is set.
+ pub(crate) fn maybe_deferred_ack(self: &Arc<Self>, node: &Node) -> DeferredAck {
+ if self.config.synchronous_ack {
+ DeferredAck {
+ node: Some(node.clone()),
+ }
+ } else {
+ let client = Arc::clone(self);
+ let node = node.clone();
+ self.spawn(async move { client.send_ack(&node, 0).await });
+ DeferredAck { node: None }
+ }
+ }
+
+ /// Sends a deferred ack, unless the event was cancelled (a handler failed).
+ pub(crate) async fn finish_deferred_ack(&self, ack: DeferredAck, cancelled: bool) {
+ let Some(node) = ack.node else {
+ return;
+ };
+ if cancelled || self.background.is_cancelled() {
+ tracing::debug!(cancelled, tag = %node.tag, "not sending ack for node");
+ return;
+ }
+ self.send_ack(&node, 0).await;
+ }
+
+ /// Acks (or with a nonzero `error`, nacks) a node.
+ pub(crate) async fn send_ack(&self, node: &Node, error: i64) {
+ let mut attrs = Attrs::from([("class".to_owned(), node.tag.clone().into())]);
+ if let Some(id) = node.attrs.get("id") {
+ attrs.insert("id".to_owned(), id.clone());
+ }
+ if let Some(from) = node.attrs.get("from") {
+ attrs.insert("to".to_owned(), from.clone());
+ }
+ if let Some(participant) = node.attrs.get("participant") {
+ attrs.insert("participant".to_owned(), participant.clone());
+ }
+ if let Some(recipient) = node.attrs.get("recipient") {
+ // Go maps bot recipients through `types.BotJIDMap` here; bots
+ // aren't ported.
+ attrs.insert("recipient".to_owned(), recipient.clone());
+ }
+ if let Some(receipt_type) = node.attrs.get("type")
+ && node.tag != "message"
+ {
+ attrs.insert("type".to_owned(), receipt_type.clone());
+ }
+ if error != 0 {
+ attrs.insert("error".to_owned(), error.into());
+ }
+ let ack = Node {
+ tag: "ack".to_owned(),
+ attrs,
+ content: None,
+ };
+ if let Err(send_error) = self.send_node(&ack).await {
+ let id = match node.attrs.get("id") {
+ Some(AttributeValue::String(id)) => id.clone(),
+ _ => String::new(),
+ };
+ tracing::warn!(error = %send_error, tag = %node.tag, id = %id, "failed to send acknowledgement");
+ }
+ }
+}
diff --git a/crates/whatsmeow/src/request.rs b/crates/whatsmeow/src/request.rs
new file mode 100644
index 0000000000..3adbde3796
--- /dev/null
+++ b/crates/whatsmeow/src/request.rs
@@ -0,0 +1,272 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+//
+// Ported from whatsmeow request.go (MPL-2.0, Copyright (c) Tulir Asokan)
+//
+// Go's response channels are `oneshot`s: a dropped sender is Go's closed
+// channel and is reported as a disconnect.
+
+//! Info queries (`<iq>`) and waiting for their responses.
+
+use std::time::Duration;
+
+use tokio::sync::oneshot;
+
+use crate::binary::{Attrs, Node, NodeContent};
+use crate::client::Client;
+use crate::errors::{ClientError, DisconnectedError, IqError, parse_iq_error};
+use crate::types::Jid;
+
+/// The type of an info query.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, strum::Display, strum::AsRefStr)]
+pub enum IqType {
+ /// `set`.
+ #[strum(serialize = "set")]
+ Set,
+ /// `get`.
+ #[default]
+ #[strum(serialize = "get")]
+ Get,
+}
+
+/// An info query to send (`infoQuery`).
+#[derive(Clone, Debug, Default)]
+pub(crate) struct InfoQuery {
+ pub(crate) namespace: &'static str,
+ pub(crate) r#type: IqType,
+ pub(crate) to: Jid,
+ pub(crate) target: Jid,
+ pub(crate) id: String,
+ pub(crate) smax_id: String,
+ pub(crate) content: Option<NodeContent>,
+ /// Zero means [`DEFAULT_REQUEST_TIMEOUT`].
+ pub(crate) timeout: Duration,
+ pub(crate) no_retry: bool,
+}
+
+/// How long [`Client::send_iq`] waits for a response by default.
+pub const DEFAULT_REQUEST_TIMEOUT: Duration = Duration::from_secs(75);
+
+/// Whether the node signals a disconnect rather than a response.
+pub(crate) fn is_disconnect_node(node: &Node) -> bool {
+ node.tag == "xmlstreamend" || node.tag == "stream:error"
+}
+
+/// Whether the disconnect is an auth error that shouldn't be retried.
+pub(crate) fn is_auth_error_disconnect(node: &Node) -> bool {
+ if node.tag != "stream:error" {
+ return false;
+ }
+ let code = node.attrs.get("code").map(ToString::to_string);
+ let conflict_type = node
+ .get_optional_child_by_tag(&["conflict"])
+ .map(|conflict| conflict.attr_getter().optional_string("type"))
+ .unwrap_or_default();
+ code.as_deref() == Some("401")
+ || conflict_type == "replaced"
+ || conflict_type == "device_removed"
+}
+
+impl Client {
+ /// Sends the node to every response waiter and forgets them.
+ pub(crate) fn clear_response_waiters(&self, node: &Node) {
+ let waiters = std::mem::take(&mut *self.response_waiters());
+ for (_, waiter) in waiters {
+ let _ = waiter.send(node.clone());
+ }
+ }
+
+ pub(crate) fn wait_response(&self, request_id: &str) -> oneshot::Receiver<Node> {
+ let (sender, receiver) = oneshot::channel();
+ self.response_waiters()
+ .insert(request_id.to_owned(), sender);
+ receiver
+ }
+
+ pub(crate) fn cancel_response(&self, request_id: &str) {
+ self.response_waiters().remove(request_id);
+ }
+
+ /// Hands an `iq` or `ack` to its waiter; returns whether one was waiting.
+ pub(crate) fn receive_response(&self, data: &Node) -> bool {
+ let Some(crate::binary::AttributeValue::String(id)) = data.attrs.get("id") else {
+ return false;
+ };
+ if data.tag != "iq" && data.tag != "ack" {
+ return false;
+ }
+ let Some(waiter) = self.response_waiters().remove(id) else {
+ return false;
+ };
+ let _ = waiter.send(data.clone());
+ true
+ }
+
+ async fn send_iq_async_and_get_data(
+ &self,
+ query: &mut InfoQuery,
+ ) -> Result<(oneshot::Receiver<Node>, Vec<u8>), ClientError> {
+ if query.id.is_empty() {
+ query.id = self.generate_request_id();
+ }
+ let waiter = self.wait_response(&query.id);
+ let mut attrs = Attrs::from([
+ ("id".to_owned(), query.id.clone().into()),
+ ("xmlns".to_owned(), query.namespace.into()),
+ ("type".to_owned(), query.r#type.as_ref().into()),
+ ]);
+ if !query.smax_id.is_empty() {
+ attrs.insert("smax_id".to_owned(), query.smax_id.clone().into());
+ }
+ if !query.to.is_empty() {
+ attrs.insert("to".to_owned(), query.to.clone().into());
+ }
+ if !query.target.is_empty() {
+ attrs.insert("target".to_owned(), query.target.clone().into());
+ }
+ let node = Node {
+ tag: "iq".to_owned(),
+ attrs,
+ content: query.content.clone(),
+ };
+ match self.send_node_and_get_data(&node).await {
+ Ok(data) => Ok((waiter, data)),
+ Err(error) => {
+ self.cancel_response(&query.id);
+ Err(error)
+ }
+ }
+ }
+
+ /// Sends an info query without waiting for the response.
+ pub(crate) async fn send_iq_async(
+ &self,
+ mut query: InfoQuery,
+ ) -> Result<oneshot::Receiver<Node>, ClientError> {
+ self.send_iq_async_and_get_data(&mut query)
+ .await
+ .map(|(waiter, _)| waiter)
+ }
+
+ /// Sends an info query and waits for the response; an error response is
+ /// an [`IqError`]. A disconnect before the response retries once after
+ /// reconnecting, unless `no_retry` is set.
+ #[tracing::instrument(
+ name = "whatsmeow.iq",
+ skip_all,
+ fields(xmlns = query.namespace, iq_type = %query.r#type),
+ err
+ )]
+ pub(crate) async fn send_iq(&self, mut query: InfoQuery) -> Result<Node, ClientError> {
+ if query.timeout.is_zero() {
+ query.timeout = DEFAULT_REQUEST_TIMEOUT;
+ }
+ let (waiter, data) = self.send_iq_async_and_get_data(&mut query).await?;
+ let response = match tokio::time::timeout(query.timeout, waiter).await {
+ Err(_) => {
+ self.cancel_response(&query.id);
+ return Err(ClientError::IqTimedOut);
+ }
+ Ok(Err(_)) => crate::client::xml_stream_end_node(),
+ Ok(Ok(response)) => response,
+ };
+ let response = if is_disconnect_node(&response) {
+ if query.no_retry {
+ return Err(DisconnectedError {
+ action: "info query".to_owned(),
+ node: Some(response),
+ }
+ .into());
+ }
+ self.retry_frame("info query", &query.id, &data, response, query.timeout)
+ .await?
+ } else {
+ response
+ };
+ let response_type = response.attrs.get("type").map(ToString::to_string);
+ if response.tag != "iq"
+ || (response_type.as_deref() != Some("result")
+ && response_type.as_deref() != Some("error"))
+ {
+ return Err(IqError {
+ raw_node: Some(response),
+ ..IqError::default()
+ }
+ .into());
+ } else if response_type.as_deref() == Some("error") {
+ return Err(parse_iq_error(&response).into());
+ }
+ Ok(response)
+ }
+
+ pub(crate) async fn retry_frame(
+ &self,
+ request_type: &str,
+ id: &str,
+ data: &[u8],
+ original_response: Node,
+ timeout: Duration,
+ ) -> Result<Node, ClientError> {
+ if is_auth_error_disconnect(&original_response) {
+ tracing::debug!(
+ request_type,
+ "request was interrupted by an auth error disconnect, not retrying"
+ );
+ return Err(DisconnectedError {
+ action: request_type.to_owned(),
+ node: Some(original_response),
+ }
+ .into());
+ }
+ tracing::debug!(
+ request_type,
+ "request was interrupted by websocket disconnection, waiting for reconnect to retry"
+ );
+ if !self.wait_for_connection(Duration::from_secs(5)).await {
+ tracing::debug!(
+ request_type,
+ "websocket didn't reconnect within 5 seconds of failed request"
+ );
+ return Err(DisconnectedError {
+ action: request_type.to_owned(),
+ node: Some(original_response),
+ }
+ .into());
+ }
+ let socket = self.socket.read().await.socket.clone();
+ let Some(socket) = socket else {
+ return Err(ClientError::NotConnected);
+ };
+ let waiter = self.wait_response(id);
+ if let Err(error) = socket.send_frame(data).await {
+ self.cancel_response(id);
+ return Err(error.into());
+ }
+ let response = if timeout.is_zero() {
+ waiter
+ .await
+ .unwrap_or_else(|_| crate::client::xml_stream_end_node())
+ } else {
+ match tokio::time::timeout(timeout, waiter).await {
+ Err(_) => {
+ self.cancel_response(id);
+ return Err(ClientError::IqTimedOut);
+ }
+ Ok(response) => response.unwrap_or_else(|_| crate::client::xml_stream_end_node()),
+ }
+ };
+ if is_disconnect_node(&response) {
+ tracing::debug!(
+ request_type,
+ "retried request was interrupted by websocket disconnection, not retrying anymore"
+ );
+ return Err(DisconnectedError {
+ action: format!("{request_type} (retry)"),
+ node: Some(response),
+ }
+ .into());
+ }
+ Ok(response)
+ }
+}
diff --git a/crates/whatsmeow/src/retry.rs b/crates/whatsmeow/src/retry.rs
new file mode 100644
index 0000000000..dde318a026
--- /dev/null
+++ b/crates/whatsmeow/src/retry.rs
@@ -0,0 +1,579 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+//
+// Ported from whatsmeow retry.go (MPL-2.0, Copyright (c) Tulir Asokan)
+
+//! Retry receipts: asking senders to resend messages that didn't decrypt,
+//! and resending our messages when others ask.
+
+use std::collections::HashMap;
+use std::sync::Arc;
+use std::time::Duration;
+
+use chrono::Utc;
+use prost::Message as _;
+
+use crate::binary::{AttributeValue, Attrs, Node, NodeContent};
+use crate::client::{Client, lock};
+use crate::errors::{ClientError, element_missing};
+use crate::prekeys::pre_key_to_node;
+use crate::proto::wa_e2e;
+use crate::signal::DJB_TYPE;
+use crate::signal::SenderKeyName;
+use crate::types::events::Receipt;
+use crate::types::{DEFAULT_USER_SERVER, HIDDEN_USER_SERVER, Jid, MessageId, MessageInfo};
+
+/// How many sent messages are kept in memory for retry receipts.
+pub const RECENT_MESSAGES_SIZE: usize = 256;
+
+const RECREATE_SESSION_TIMEOUT: Duration = Duration::from_secs(60 * 60);
+const RETRY_STORE_CLEAR_INTERVAL: Duration = Duration::from_secs(12 * 60 * 60);
+
+/// The recently sent messages, a ring of [`RECENT_MESSAGES_SIZE`] (Go's
+/// `recentMessagesMap` and `recentMessagesList`). Only WhatsApp messages;
+/// Messenger (`fb`) messages aren't ported.
+pub(crate) struct RecentMessages {
+ map: HashMap<(Jid, MessageId), wa_e2e::Message>,
+ list: Vec<Option<(Jid, MessageId)>>,
+ pointer: usize,
+}
+
+impl Default for RecentMessages {
+ fn default() -> Self {
+ RecentMessages {
+ map: HashMap::new(),
+ list: vec![None; RECENT_MESSAGES_SIZE],
+ pointer: 0,
+ }
+ }
+}
+
+/// Retry bookkeeping guarded by one lock: per-device session recreation
+/// times and per-(device, message) incoming retry counts.
+#[derive(Default)]
+pub(crate) struct RetryState {
+ session_recreate_history: HashMap<Jid, tokio::time::Instant>,
+ incoming_retry_request_counter: HashMap<(Jid, MessageId), u32>,
+ last_retry_store_clear: Option<tokio::time::Instant>,
+}
+
+/// How long to wait for the sender to resend a message before asking the
+/// phone (`RequestFromPhoneDelay`), with `automatic_message_rerequest_from_phone`.
+pub const REQUEST_FROM_PHONE_DELAY: Duration = Duration::from_secs(5);
+
+impl Client {
+ /// Remembers a sent message for retry receipts, in the store too with
+ /// `use_retry_message_store`.
+ pub(crate) async fn add_recent_message(
+ &self,
+ to: &Jid,
+ id: &str,
+ message: &wa_e2e::Message,
+ ) -> Result<(), ClientError> {
+ if self.config.use_retry_message_store {
+ let event_buffer = Arc::clone(&self.store.read().await.event_buffer);
+ event_buffer
+ .add_outgoing_event(to, &id.to_owned(), "wa", message.encode_to_vec())
+ .await
+ .map_err(|error| {
+ ClientError::from(error).wrap("failed to add message to retry store")
+ })?;
+ let clear = {
+ let mut state = lock(&self.retry_state);
+ let clear = state
+ .last_retry_store_clear
+ .is_none_or(|last| last.elapsed() > RETRY_STORE_CLEAR_INTERVAL);
+ if clear {
+ state.last_retry_store_clear = Some(tokio::time::Instant::now());
+ }
+ clear
+ };
+ if clear {
+ event_buffer
+ .delete_old_outgoing_events()
+ .await
+ .map_err(|error| {
+ ClientError::from(error)
+ .wrap("failed to clear old messages from retry store")
+ })?;
+ }
+ }
+ let mut recent = lock(&self.recent_messages);
+ let key = (to.clone(), id.to_owned());
+ let pointer = recent.pointer;
+ if let Some(old) = recent.list[pointer].take() {
+ recent.map.remove(&old);
+ }
+ recent.map.insert(key.clone(), message.clone());
+ recent.list[pointer] = Some(key);
+ recent.pointer = (pointer + 1) % RECENT_MESSAGES_SIZE;
+ Ok(())
+ }
+
+ fn get_recent_message(&self, to: &Jid, id: &str) -> Option<wa_e2e::Message> {
+ lock(&self.recent_messages)
+ .map
+ .get(&(to.clone(), id.to_owned()))
+ .cloned()
+ }
+
+ async fn get_message_for_retry(
+ &self,
+ receipt: &Receipt,
+ message_id: &str,
+ ) -> Result<Option<wa_e2e::Message>, ClientError> {
+ if let Some(message) = self.get_recent_message(&receipt.source.chat, message_id) {
+ tracing::debug!("found message in local cache to accept retry receipt");
+ return Ok(Some(message));
+ }
+ let lids = Arc::clone(&self.store.read().await.lids);
+ let alt_chat = match receipt.source.chat.server.as_str() {
+ DEFAULT_USER_SERVER => lids.get_lid_for_pn(&receipt.source.chat).await,
+ HIDDEN_USER_SERVER => lids.get_pn_for_lid(&receipt.source.chat).await,
+ _ => Ok(None),
+ }
+ .map_err(|error| ClientError::from(error).wrap("failed to get alternate JID"))?
+ .unwrap_or_default();
+ if !alt_chat.is_empty()
+ && let Some(message) = self.get_recent_message(&alt_chat, message_id)
+ {
+ tracing::debug!(
+ "found message in local cache with alternate chat JID to accept retry receipt"
+ );
+ return Ok(Some(message));
+ }
+ if self.config.use_retry_message_store {
+ let event_buffer = Arc::clone(&self.store.read().await.event_buffer);
+ let stored = event_buffer
+ .get_outgoing_event(&receipt.source.chat, &alt_chat, &message_id.to_owned())
+ .await
+ .map_err(|error| {
+ ClientError::from(error).wrap("failed to get message from retry store")
+ })?;
+ return match stored {
+ None => Ok(None),
+ Some((format, buffer)) if format == "wa" => {
+ wa_e2e::Message::decode(buffer.as_slice())
+ .map(Some)
+ .map_err(|error| {
+ ClientError::Other(format!(
+ "failed to unmarshal payload in retry store: {error}"
+ ))
+ })
+ }
+ Some((format, _)) => Err(ClientError::Other(format!(
+ "failed to unmarshal payload in retry store: unknown format in retry store: {format}"
+ ))),
+ };
+ }
+ if let Some(callback) = &self.config.get_message_for_retry
+ && let Some(message) =
+ callback(&receipt.source.sender, &receipt.source.chat, message_id)
+ {
+ tracing::debug!("found message in get_message_for_retry to accept retry receipt");
+ return Ok(Some(message));
+ }
+ Ok(None)
+ }
+
+ async fn should_recreate_session(&self, retry_count: i64, jid: &Jid) -> Option<&'static str> {
+ let contains = {
+ let store = self.store.read().await;
+ store
+ .sessions
+ .has_session(&jid.signal_address().to_string())
+ .await
+ };
+ let mut state = lock(&self.retry_state);
+ match contains {
+ Err(_) => return None,
+ Ok(false) => {
+ state
+ .session_recreate_history
+ .insert(jid.clone(), tokio::time::Instant::now());
+ return Some("we don't have a Signal session with them");
+ }
+ Ok(true) if retry_count < 2 => return None,
+ Ok(true) => {}
+ }
+ let recreate = state
+ .session_recreate_history
+ .get(jid)
+ .is_none_or(|previous| previous.elapsed() > RECREATE_SESSION_TIMEOUT);
+ if recreate {
+ state
+ .session_recreate_history
+ .insert(jid.clone(), tokio::time::Instant::now());
+ Some("retry count > 1 and over an hour since last recreation")
+ } else {
+ None
+ }
+ }
+
+ /// Resends one of our messages to a device that couldn't decrypt it.
+ #[tracing::instrument(name = "whatsmeow.handle_retry_receipt", skip_all, err)]
+ async fn handle_retry_receipt(
+ self: &Arc<Self>,
+ receipt: &Receipt,
+ node: &Node,
+ ) -> Result<(), ClientError> {
+ let retry_child = node
+ .get_optional_child_by_tag(&["retry"])
+ .ok_or_else(|| element_missing("retry", "retry receipt"))?;
+ let mut attrs = retry_child.attr_getter();
+ let message_id = attrs.string("id");
+ let timestamp = attrs.unix_time("t");
+ let retry_count = attrs.int("count");
+ attrs.error()?;
+ let Some(mut message) = self.get_message_for_retry(receipt, &message_id).await? else {
+ return Err(ClientError::Other(format!(
+ "couldn't find message {message_id}"
+ )));
+ };
+
+ let internal_counter = {
+ let mut state = lock(&self.retry_state);
+ let counter = state
+ .incoming_retry_request_counter
+ .entry((receipt.source.sender.clone(), message_id.clone()))
+ .or_default();
+ *counter += 1;
+ *counter
+ };
+ if internal_counter >= 10 {
+ tracing::warn!(
+ internal_counter,
+ "dropping retry request: internal retry counter is too high"
+ );
+ return Ok(());
+ }
+
+ if receipt.source.is_group {
+ let sender_key_name = SenderKeyName {
+ group_id: receipt.source.chat.to_string(),
+ sender: self.get_own_lid().await.signal_address(),
+ };
+ let skdm = {
+ let store = self.store.read().await;
+ let signal_store = store.signal_store(None);
+ self.signal
+ .create_sender_key_distribution_message(&signal_store, &sender_key_name)
+ .await
+ };
+ match skdm {
+ Err(error) => {
+ tracing::warn!(error = %error, "failed to create sender key distribution message to include in retry")
+ }
+ Ok(skdm) => {
+ message.sender_key_distribution_message =
+ Some(wa_e2e::SenderKeyDistributionMessage {
+ group_id: Some(receipt.source.chat.to_string()),
+ axolotl_sender_key_distribution_message: Some(skdm),
+ });
+ }
+ }
+ } else if receipt.source.is_from_me {
+ message = wa_e2e::Message {
+ device_sent_message: Some(Box::new(wa_e2e::DeviceSentMessage {
+ destination_jid: Some(receipt.source.chat.to_string()),
+ message: Some(Box::new(message)),
+ phash: None,
+ })),
+ ..Default::default()
+ };
+ }
+
+ if let Some(callback) = &self.config.pre_retry_callback
+ && !callback(receipt, &message_id, retry_count, &message)
+ {
+ tracing::debug!("cancelled retry receipt in pre_retry_callback");
+ return Ok(());
+ }
+
+ let plaintext = message.encode_to_vec();
+ let bundle = if node.get_optional_child_by_tag(&["keys"]).is_some() {
+ Some(
+ crate::prekeys::node_to_pre_key_bundle(
+ u32::from(receipt.source.sender.device),
+ node,
+ )
+ .map_err(|error| error.wrap("failed to read prekey bundle in retry receipt"))?,
+ )
+ } else if let Some(reason) = self
+ .should_recreate_session(retry_count, &receipt.source.sender)
+ .await
+ {
+ tracing::debug!(
+ reason,
+ "fetching prekeys for retry receipt with no prekey bundle"
+ );
+ let mut keys = self
+ .fetch_pre_keys(std::slice::from_ref(&receipt.source.sender))
+ .await?;
+ let response_count = keys.len();
+ match keys.remove(&receipt.source.sender) {
+ Some(Ok(bundle)) => Some(bundle),
+ Some(Err(error)) => return Err(error.wrap("failed to fetch prekeys")),
+ None => {
+ return Err(ClientError::Other(format!(
+ "didn't get prekey bundle for the sender (response size: {response_count})"
+ )));
+ }
+ }
+ } else {
+ None
+ };
+ let mut enc_attrs = Attrs::new();
+ let media_type = crate::send::get_media_type_from_message(&message);
+ if !media_type.is_empty() {
+ enc_attrs.insert("mediatype".to_owned(), media_type.into());
+ }
+ let message_type = crate::send::get_type_from_message(&message);
+ let mut encryption_identity = receipt.source.sender.clone();
+ if receipt.source.sender.server == DEFAULT_USER_SERVER {
+ let lids = Arc::clone(&self.store.read().await.lids);
+ match lids.get_lid_for_pn(&receipt.source.sender).await {
+ Err(error) => tracing::warn!(error = %error, "failed to get LID for retry sender"),
+ Ok(Some(lid)) if !lid.is_empty() => {
+ let sessions = Arc::clone(&self.store.read().await.sessions);
+ if let Err(error) = sessions
+ .migrate_pn_to_lid(&receipt.source.sender, &lid)
+ .await
+ {
+ tracing::error!(error = %error, "failed to migrate signal store from phone number to LID");
+ }
+ encryption_identity = lid;
+ }
+ Ok(_) => {}
+ }
+ }
+ let (mut encrypted, include_device_identity) = self
+ .encrypt_message_for_device(
+ &plaintext,
+ &encryption_identity,
+ bundle.as_ref(),
+ &enc_attrs,
+ None,
+ None,
+ )
+ .await
+ .map_err(|error| error.wrap("failed to encrypt message for retry"))?;
+ encrypted
+ .attrs
+ .insert("count".to_owned(), retry_count.into());
+
+ let mut message_attrs = Attrs::from([
+ ("type".to_owned(), message_type.into()),
+ ("id".to_owned(), message_id.clone().into()),
+ (
+ "t".to_owned(),
+ timestamp.unwrap_or_else(Utc::now).timestamp().into(),
+ ),
+ ]);
+ if let Some(from) = node.attrs.get("from") {
+ message_attrs.insert("to".to_owned(), from.clone());
+ }
+ if !receipt.source.is_group {
+ message_attrs.insert("device_fanout".to_owned(), false.into());
+ }
+ for key in ["participant", "recipient", "edit"] {
+ if let Some(value) = node.attrs.get(key) {
+ message_attrs.insert(key.to_owned(), value.clone());
+ }
+ }
+ let content = self
+ .get_message_content(
+ encrypted,
+ &message,
+ &message_attrs,
+ include_device_identity,
+ &crate::send::NodeExtraParams::default(),
+ )
+ .await;
+ self.send_node(&Node {
+ tag: "message".to_owned(),
+ attrs: message_attrs,
+ content: Some(NodeContent::Nodes(content)),
+ })
+ .await
+ .map_err(|error| error.wrap("failed to send retry message"))?;
+ tracing::debug!(retry_count, "sent retry");
+ Ok(())
+ }
+
+ pub(crate) fn cancel_delayed_request_from_phone(&self, message_id: &str) {
+ if !self.config.automatic_message_rerequest_from_phone {
+ return;
+ }
+ if let Some(cancel) = lock(&self.pending_phone_rerequests).get(message_id) {
+ cancel.cancel();
+ }
+ }
+
+ async fn delayed_request_message_from_phone(self: Arc<Self>, info: MessageInfo) {
+ if !self.config.automatic_message_rerequest_from_phone {
+ return;
+ }
+ let cancel = {
+ let mut pending = lock(&self.pending_phone_rerequests);
+ if pending.contains_key(&info.id) {
+ return;
+ }
+ let cancel = self.background.child_token();
+ pending.insert(info.id.clone(), cancel.clone());
+ cancel
+ };
+ tokio::select! {
+ () = tokio::time::sleep(REQUEST_FROM_PHONE_DELAY) => {
+ self.immediate_request_message_from_phone(&info).await;
+ }
+ () = cancel.cancelled() => {
+ tracing::debug!("cancelled delayed request for message from phone");
+ }
+ }
+ lock(&self.pending_phone_rerequests).remove(&info.id);
+ }
+
+ /// Asks the primary device to resend a message this device couldn't
+ /// decrypt.
+ pub(crate) async fn immediate_request_message_from_phone(self: &Arc<Self>, info: &MessageInfo) {
+ let request = self.build_unavailable_message_request(&info.chat, &info.sender, &info.id);
+ match self.send_peer_message(request).await {
+ Err(error) => {
+ tracing::warn!(error = %error, "failed to send request for unavailable message to phone")
+ }
+ Ok(_) => tracing::debug!("requested message from phone"),
+ }
+ }
+
+ pub(crate) fn clear_delayed_message_requests(&self) {
+ for cancel in lock(&self.pending_phone_rerequests).values() {
+ cancel.cancel();
+ }
+ }
+
+ /// Sends a retry receipt for an incoming message that didn't decrypt.
+ pub(crate) async fn send_retry_receipt(
+ self: &Arc<Self>,
+ node: &Node,
+ info: &MessageInfo,
+ force_include_identity: bool,
+ ) {
+ let id = match node.attrs.get("id") {
+ Some(AttributeValue::String(id)) => id.clone(),
+ _ => String::new(),
+ };
+ let children = node.get_children();
+ let retry_count_in_message = if children.len() == 1 && children[0].tag == "enc" {
+ children[0].attr_getter().optional_int("count")
+ } else {
+ 0
+ };
+ let retry_count = {
+ let mut retries = lock(&self.message_retries);
+ let count = retries.entry(id.clone()).or_default();
+ *count += 1;
+ // If this is a retry response and we restarted in between, take
+ // the count from the message.
+ if *count == 1 && retry_count_in_message > 0 {
+ *count = retry_count_in_message + 1;
+ }
+ *count
+ };
+ if retry_count >= 5 {
+ tracing::warn!("not sending any more retry receipts");
+ return;
+ }
+ if retry_count == 1 {
+ if self.config.synchronous_ack {
+ self.immediate_request_message_from_phone(info).await;
+ } else {
+ let client = Arc::clone(self);
+ let info = info.clone();
+ self.spawn(client.delayed_request_message_from_phone(info));
+ }
+ }
+
+ let (registration_id, identity_public, signed_pre_key, account, pre_keys) = {
+ let store = self.store.read().await;
+ (
+ store.registration_id,
+ store.identity_key.public,
+ store.signed_pre_key.clone(),
+ store.account.clone(),
+ Arc::clone(&store.pre_keys),
+ )
+ };
+ let mut attrs = crate::receipt::build_base_receipt(&info.id, node);
+ attrs.insert("type".to_owned(), "retry".into());
+ if info.r#type == "peer_msg" && info.is_from_me {
+ attrs.insert("category".to_owned(), "peer".into());
+ }
+ let mut retry_attrs = Attrs::from([
+ ("count".to_owned(), retry_count.into()),
+ ("id".to_owned(), id.clone().into()),
+ ("v".to_owned(), 1_i64.into()),
+ ]);
+ if let Some(timestamp) = node.attrs.get("t") {
+ retry_attrs.insert("t".to_owned(), timestamp.clone());
+ }
+ let mut content = vec![
+ Node {
+ tag: "retry".to_owned(),
+ attrs: retry_attrs,
+ content: None,
+ },
+ Node {
+ tag: "registration".to_owned(),
+ attrs: Attrs::new(),
+ content: Some(NodeContent::Bytes(registration_id.to_be_bytes().to_vec())),
+ },
+ ];
+ if retry_count > 1 || force_include_identity {
+ match pre_keys.gen_one_pre_key().await {
+ Err(error) => {
+ tracing::error!(error = %error, "failed to get prekey for retry receipt")
+ }
+ Ok(key) => {
+ let device_identity = account.unwrap_or_default().encode_to_vec();
+ let bytes = |tag: &str, data: Vec<u8>| Node {
+ tag: tag.to_owned(),
+ attrs: Attrs::new(),
+ content: Some(NodeContent::Bytes(data)),
+ };
+ content.push(Node {
+ tag: "keys".to_owned(),
+ attrs: Attrs::new(),
+ content: Some(NodeContent::Nodes(vec![
+ bytes("type", vec![DJB_TYPE]),
+ bytes("identity", identity_public.to_vec()),
+ pre_key_to_node(&key),
+ pre_key_to_node(&signed_pre_key),
+ bytes("device-identity", device_identity),
+ ])),
+ });
+ }
+ }
+ }
+ let payload = Node {
+ tag: "receipt".to_owned(),
+ attrs,
+ content: Some(NodeContent::Nodes(content)),
+ };
+ if let Err(error) = self.send_node(&payload).await {
+ tracing::error!(error = %error, "failed to send retry receipt");
+ }
+ }
+
+ /// Handles a retry receipt for one of our messages; acks it afterwards.
+ pub(crate) async fn try_handle_retry_receipt(self: &Arc<Self>, receipt: &Receipt, node: &Node) {
+ let ack = self.maybe_deferred_ack(node);
+ let mut cancelled = false;
+ if let Err(error) = self.handle_retry_receipt(receipt, node).await {
+ tracing::error!(error = %error, "failed to handle retry receipt");
+ cancelled = matches!(error.innermost(), ClientError::NotConnected);
+ }
+ self.finish_deferred_ack(ack, cancelled).await;
+ }
+}
diff --git a/crates/whatsmeow/src/send.rs b/crates/whatsmeow/src/send.rs
new file mode 100644
index 0000000000..2457933664
--- /dev/null
+++ b/crates/whatsmeow/src/send.rs
@@ -0,0 +1,1415 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+//
+// Ported from whatsmeow send.go (MPL-2.0, Copyright (c) Tulir Asokan)
+//
+// Deviations:
+// - Go's variadic `SendRequestExtra` is an explicit [`SendRequestExtra`]
+// argument; `MessageDebugTimings` is not ported (each phase is a span).
+// - Not ported: newsletters, bots (inline bot mode, Muse/WASA encryption),
+// broadcast lists (`ErrBroadcastListUnsupported`), reporting tokens,
+// `SetDisappearingTimer` for groups.
+
+//! Sending messages: 1:1 and group fan-out, peer messages to our own
+//! devices, and builders for revokes, reactions, edits and requests.
+
+use std::collections::HashMap;
+use std::sync::Arc;
+use std::time::Duration;
+
+use base64::Engine;
+use base64::engine::general_purpose::STANDARD_NO_PAD;
+use chrono::{DateTime, Utc};
+use prost::Message as _;
+use sha2::{Digest, Sha256};
+use tracing::Instrument;
+
+use crate::binary::{AttributeValue, Attrs, Node, NodeContent};
+use crate::client::Client;
+use crate::errors::ClientError;
+use crate::message::pad_message;
+use crate::proto::wa_common::MessageKey;
+use crate::proto::wa_e2e::{
+ self, KeepType, PeerDataOperationRequestType, peer_data_operation_request_message,
+ protocol_message,
+};
+use crate::request::{DEFAULT_REQUEST_TIMEOUT, is_disconnect_node};
+use crate::signal::{CiphertextType, PreKeyBundle, SignalError};
+use crate::store::SessionCache;
+use crate::types::events::DecryptFailMode;
+use crate::types::{
+ AddressingMode, BOT_SERVER, BROADCAST_SERVER, DEFAULT_USER_SERVER, EditAttribute, GROUP_SERVER,
+ HIDDEN_USER_SERVER, HOSTED_LID_SERVER, HOSTED_SERVER, Jid, MESSENGER_SERVER, MessageId,
+ MessageInfo, MessageServerId, MsgMetaInfo, NEWSLETTER_SERVER,
+};
+
+/// The prefix of message IDs WhatsApp web generates.
+pub const WEB_MESSAGE_ID_PREFIX: &str = "3EB0";
+
+/// How long a message can be edited after it was sent.
+pub const EDIT_WINDOW: Duration = Duration::from_secs(20 * 60);
+
+/// The reaction text that removes a reaction.
+pub const REMOVE_REACTION_TEXT: &str = "";
+
+/// What [`Client::send_message`] returns once the server acked the message.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct SendResponse {
+ /// The message timestamp returned by the server.
+ pub timestamp: Option<DateTime<Utc>>,
+ /// The ID of the sent message.
+ pub id: MessageId,
+ /// The server ID (newsletters only).
+ pub server_id: MessageServerId,
+ /// The identity the message was sent with (LID or phone number).
+ pub sender: Jid,
+ /// The chat the message was actually sent to.
+ pub chat: Jid,
+}
+
+/// The optional parameters of [`Client::send_message`].
+#[derive(Clone, Debug, Default)]
+pub struct SendRequestExtra {
+ /// The message ID; a new one is generated when empty.
+ pub id: MessageId,
+ /// Send as a peer message to our own devices (protocol messages such as
+ /// app state key requests).
+ pub peer: bool,
+ /// How long to wait for the server's ack; zero means
+ /// [`DEFAULT_REQUEST_TIMEOUT`], `None` waits forever.
+ pub timeout: Option<Duration>,
+ /// The `<meta>` node attributes (threads).
+ pub meta: Option<MsgMetaInfo>,
+ /// Extra nodes to append to the message node; use only if you know what
+ /// you are doing.
+ pub additional_nodes: Vec<Node>,
+ /// Refuse to send to read-only groups where we aren't admin.
+ pub check_permissions: bool,
+ /// Don't resend the message after reconnecting when the websocket drops
+ /// before the server acked it; return a disconnect error instead, so the
+ /// caller can record the outcome as unknown. Not in whatsmeow: #8304
+ /// carried this as a patch (`NoDisconnectRetry`).
+ pub no_disconnect_retry: bool,
+}
+
+/// Extra parts of the message node (`nodeExtraParams`).
+#[derive(Clone, Debug, Default)]
+pub(crate) struct NodeExtraParams {
+ pub(crate) meta_node: Option<Node>,
+ pub(crate) additional_nodes: Vec<Node>,
+ pub(crate) addressing_mode: Option<AddressingMode>,
+ pub(crate) peer_recipient_pn: Jid,
+}
+
+fn bytes_node(tag: &str, data: Vec<u8>) -> Node {
+ Node {
+ tag: tag.to_owned(),
+ attrs: Attrs::new(),
+ content: Some(NodeContent::Bytes(data)),
+ }
+}
+
+impl Client {
+ /// A new message ID: `3EB0` and a hash of the time, our user and random
+ /// bytes, as WhatsApp web does.
+ pub async fn generate_message_id(&self) -> MessageId {
+ let own_id = self.get_own_id().await;
+ generate_message_id_with(&own_id, Utc::now().timestamp(), &rand::random::<[u8; 16]>())
+ }
+
+ /// Sends a message and waits for the server's ack.
+ ///
+ /// `to` is a user (phone number or LID, no device) or a group. Media must
+ /// be uploaded first with [`Client::upload`].
+ #[tracing::instrument(
+ name = "whatsmeow.send_message",
+ skip_all,
+ fields(message_id, is_group = to.server == GROUP_SERVER, peer = extra.peer),
+ err
+ )]
+ pub async fn send_message(
+ self: &Arc<Self>,
+ to: &Jid,
+ mut message: wa_e2e::Message,
+ extra: SendRequestExtra,
+ ) -> Result<SendResponse, ClientError> {
+ let mut to = to.clone();
+ if to.device > 0 && !extra.peer {
+ return Err(ClientError::RecipientAdJid);
+ }
+ let mut own_id = self.get_own_id().await;
+ if own_id.is_empty() {
+ return Err(ClientError::NotLoggedIn);
+ }
+ let id = if extra.id.is_empty() {
+ self.generate_message_id().await
+ } else {
+ extra.id.clone()
+ };
+ tracing::Span::current().record("message_id", id.as_str());
+ let mut response = SendResponse {
+ id: id.clone(),
+ ..SendResponse::default()
+ };
+
+ let mut extra_params = NodeExtraParams::default();
+ let mut group_participants = Vec::new();
+ let mut cached_group = None;
+ if to.server == GROUP_SERVER {
+ let cached = self
+ .get_cached_group_data(&to)
+ .await
+ .map_err(|error| error.wrap("failed to get group members"))?;
+ group_participants = cached.members.clone();
+ // whatsmeow notes this is fairly hacky: the identity a message is
+ // sent with follows the group's addressing mode.
+ if cached.addressing_mode == AddressingMode::Lid {
+ own_id = self.get_own_lid().await;
+ extra_params.addressing_mode = Some(AddressingMode::Lid);
+ } else if cached.community_announcement_group && extra.meta.is_some() {
+ own_id = self.get_own_lid().await;
+ extra_params.addressing_mode = Some(AddressingMode::Pn);
+ }
+ cached_group = Some(cached);
+ } else if to.server == BROADCAST_SERVER {
+ return Err(ClientError::BroadcastListUnsupported);
+ } else if to.server == HIDDEN_USER_SERVER {
+ own_id = self.get_own_lid().await;
+ let lids = Arc::clone(&self.store.read().await.lids);
+ match lids.get_pn_for_lid(&to).await {
+ Ok(pn) => extra_params.peer_recipient_pn = pn.unwrap_or_default(),
+ Err(error) => {
+ tracing::warn!(error = %error, "failed to get peer recipient phone number")
+ }
+ }
+ } else if to.server == DEFAULT_USER_SERVER && !extra.peer {
+ let lids = Arc::clone(&self.store.read().await.lids);
+ let mut to_lid = lids
+ .get_lid_for_pn(&to)
+ .await
+ .map_err(|error| {
+ ClientError::from(error).wrap("failed to get LID for phone number")
+ })?
+ .unwrap_or_default();
+ if to_lid.is_empty() {
+ tracing::debug!("LID for recipient not found, fetching user info");
+ let info = self
+ .get_user_info(std::slice::from_ref(&to))
+ .await
+ .map_err(|error| error.wrap("failed to get user info to fill LID cache"))?;
+ to_lid = info
+ .get(&to)
+ .map(|info| info.lid.clone())
+ .unwrap_or_default();
+ if to_lid.is_empty() {
+ return Err(ClientError::Other(
+ "no LID found for recipient from server".to_owned(),
+ ));
+ }
+ }
+ extra_params.peer_recipient_pn = to.clone();
+ to = to_lid;
+ own_id = self.get_own_lid().await;
+ }
+ if let Some(meta) = &extra.meta {
+ let mut attrs = Attrs::new();
+ if let Some(deprecated) = meta.deprecated_lid_session {
+ attrs.insert("deprecated_lid_session".to_owned(), deprecated.into());
+ }
+ if !meta.thread_message_id.is_empty() {
+ attrs.insert(
+ "thread_msg_id".to_owned(),
+ meta.thread_message_id.clone().into(),
+ );
+ attrs.insert(
+ "thread_msg_sender_jid".to_owned(),
+ meta.thread_message_sender_jid.clone().into(),
+ );
+ }
+ extra_params.meta_node = Some(Node {
+ tag: "meta".to_owned(),
+ attrs,
+ content: None,
+ });
+ }
+ extra_params.additional_nodes = extra.additional_nodes.clone();
+
+ response.sender = own_id.clone();
+ response.chat = to.clone();
+
+ // Sending several messages at once can cause weird issues and makes
+ // retries unsafe; it also protects the session prefetching.
+ let _send_lock = self
+ .message_send_lock
+ .lock()
+ .instrument(tracing::info_span!("whatsmeow.send_message.queue"))
+ .await;
+
+ // Peer message retries aren't implemented.
+ if !extra.peer {
+ self.add_recent_message(&to, &id, &message).await?;
+ }
+ if let Some(secret) = message
+ .message_context_info
+ .as_ref()
+ .and_then(|context| context.message_secret.clone())
+ {
+ let msg_secrets = Arc::clone(&self.store.read().await.msg_secrets);
+ match msg_secrets
+ .put_message_secret(&to, &own_id, &id, secret)
+ .await
+ {
+ Err(error) => {
+ tracing::warn!(error = %error, "failed to store message secret key for outgoing message")
+ }
+ Ok(()) => tracing::debug!("stored message secret key for outgoing message"),
+ }
+ }
+ if extra.check_permissions
+ && let Some(cached) = &cached_group
+ && !cached.can_send(&own_id, &message)
+ {
+ return Err(ClientError::NoPermissionInGroup);
+ }
+
+ let waiter = self.wait_response(&id);
+ let sent = match to.server.as_str() {
+ GROUP_SERVER => {
+ self.send_group(
+ &own_id,
+ &to,
+ &group_participants,
+ &id,
+ &message,
+ extra_params,
+ )
+ .await
+ }
+ DEFAULT_USER_SERVER | BOT_SERVER | HIDDEN_USER_SERVER => {
+ if extra.peer {
+ self.send_peer_message_node(&to, &id, &mut message)
+ .await
+ .map(|data| (String::new(), data))
+ } else {
+ self.send_dm(&own_id, &to, &id, &message, extra_params)
+ .await
+ }
+ }
+ NEWSLETTER_SERVER => Err(ClientError::Other("newsletters aren't ported".to_owned())),
+ other => Err(ClientError::Other(format!(
+ "{} {other}",
+ ClientError::UnknownServer
+ ))),
+ };
+ let (phash, data) = match sent {
+ Ok(sent) => sent,
+ Err(error) => {
+ self.cancel_response(&id);
+ return Err(error);
+ }
+ };
+ let timeout = extra.timeout.map(|timeout| {
+ if timeout.is_zero() {
+ DEFAULT_REQUEST_TIMEOUT
+ } else {
+ timeout
+ }
+ });
+ let ack = async {
+ match timeout {
+ Some(timeout) => tokio::time::timeout(timeout, waiter).await.ok(),
+ None => Some(waiter.await),
+ }
+ }
+ .instrument(tracing::info_span!("whatsmeow.send_message.wait_ack"))
+ .await;
+ let response_node = match ack {
+ None => {
+ self.cancel_response(&id);
+ return Err(ClientError::MessageTimedOut);
+ }
+ Some(Err(_)) => crate::client::xml_stream_end_node(),
+ Some(Ok(node)) => node,
+ };
+ let response_node = if is_disconnect_node(&response_node) && extra.no_disconnect_retry {
+ return Err(crate::errors::DisconnectedError {
+ action: "message send".to_owned(),
+ node: Some(response_node),
+ }
+ .into());
+ } else if is_disconnect_node(&response_node) {
+ self.retry_frame("message send", &id, &data, response_node, Duration::ZERO)
+ .await?
+ } else {
+ response_node
+ };
+ let mut attrs = response_node.attr_getter();
+ response.server_id = attrs.optional_int("server_id");
+ response.timestamp = attrs.unix_time("t");
+ let error_code = attrs.int("error");
+ let expected_phash = attrs.optional_string("phash");
+ if !expected_phash.is_empty() && phash != expected_phash {
+ tracing::warn!(
+ "server returned a different participant list hash, some devices may not have received the message"
+ );
+ match to.server.as_str() {
+ GROUP_SERVER => {
+ self.group_cache.lock().await.remove(&to);
+ }
+ DEFAULT_USER_SERVER | HIDDEN_USER_SERVER | BOT_SERVER | HOSTED_SERVER
+ | HOSTED_LID_SERVER => {
+ self.user_devices_cache.lock().await.remove(&to);
+ }
+ _ => {}
+ }
+ }
+ if error_code != 0 {
+ return Err(ClientError::Other(format!(
+ "{} {error_code}",
+ ClientError::ServerReturnedError
+ )));
+ }
+ Ok(response)
+ }
+
+ /// Sends a protocol message to our own devices (app state key requests,
+ /// requests to the phone).
+ pub async fn send_peer_message(
+ self: &Arc<Self>,
+ message: wa_e2e::Message,
+ ) -> Result<SendResponse, ClientError> {
+ let own_id = self.get_own_id().await.to_non_ad();
+ if own_id.is_empty() {
+ return Err(ClientError::NotLoggedIn);
+ }
+ self.send_message(
+ &own_id,
+ message,
+ SendRequestExtra {
+ peer: true,
+ timeout: Some(Duration::ZERO),
+ ..SendRequestExtra::default()
+ },
+ )
+ .await
+ }
+
+ /// A key referring to an earlier message, for replies, revokes and
+ /// reactions.
+ pub async fn build_message_key(&self, chat: &Jid, sender: &Jid, id: &str) -> MessageKey {
+ let own_id = self.get_own_id().await;
+ let own_lid = self.get_own_lid().await;
+ build_message_key_with(&own_id, &own_lid, chat, sender, id)
+ }
+
+ /// A message deleting an earlier message for everyone. Pass an empty
+ /// `sender` for our own messages, or the sender as group admin.
+ pub async fn build_revoke(&self, chat: &Jid, sender: &Jid, id: &str) -> wa_e2e::Message {
+ wa_e2e::Message {
+ protocol_message: Some(Box::new(wa_e2e::ProtocolMessage {
+ r#type: Some(protocol_message::Type::Revoke as i32),
+ key: Some(self.build_message_key(chat, sender, id).await),
+ ..Default::default()
+ })),
+ ..Default::default()
+ }
+ }
+
+ /// A reaction to an earlier message; an empty reaction removes it.
+ pub async fn build_reaction(
+ &self,
+ chat: &Jid,
+ sender: &Jid,
+ id: &str,
+ reaction: &str,
+ ) -> wa_e2e::Message {
+ wa_e2e::Message {
+ reaction_message: Some(wa_e2e::ReactionMessage {
+ key: Some(self.build_message_key(chat, sender, id).await),
+ text: Some(reaction.to_owned()),
+ sender_timestamp_ms: Some(Utc::now().timestamp_millis()),
+ ..Default::default()
+ }),
+ ..Default::default()
+ }
+ }
+
+ /// A request asking our primary device to resend a message this device
+ /// couldn't decrypt; send it with [`Client::send_peer_message`].
+ pub fn build_unavailable_message_request(
+ &self,
+ chat: &Jid,
+ sender: &Jid,
+ id: &str,
+ ) -> wa_e2e::Message {
+ let own = self.own_ids_now();
+ wa_e2e::Message {
+ protocol_message: Some(Box::new(wa_e2e::ProtocolMessage {
+ r#type: Some(protocol_message::Type::PeerDataOperationRequestMessage as i32),
+ peer_data_operation_request_message: Some(
+ wa_e2e::PeerDataOperationRequestMessage {
+ peer_data_operation_request_type: Some(
+ PeerDataOperationRequestType::PlaceholderMessageResend as i32,
+ ),
+ placeholder_message_resend_request: vec![
+ peer_data_operation_request_message::PlaceholderMessageResendRequest {
+ message_key: Some(build_message_key_with(
+ &own.0, &own.1, chat, sender, id,
+ )),
+ },
+ ],
+ ..Default::default()
+ },
+ ),
+ ..Default::default()
+ })),
+ ..Default::default()
+ }
+ }
+
+ /// A request for `count` messages before the given one from our primary
+ /// device; the answer comes as an on-demand [`crate::Event::HistorySync`].
+ pub fn build_history_sync_request(
+ &self,
+ last_known_message_info: &MessageInfo,
+ count: i32,
+ ) -> wa_e2e::Message {
+ wa_e2e::Message {
+ protocol_message: Some(Box::new(wa_e2e::ProtocolMessage {
+ r#type: Some(protocol_message::Type::PeerDataOperationRequestMessage as i32),
+ peer_data_operation_request_message: Some(
+ wa_e2e::PeerDataOperationRequestMessage {
+ peer_data_operation_request_type: Some(
+ PeerDataOperationRequestType::HistorySyncOnDemand as i32,
+ ),
+ history_sync_on_demand_request: Some(
+ peer_data_operation_request_message::HistorySyncOnDemandRequest {
+ chat_jid: Some(last_known_message_info.chat.to_string()),
+ oldest_msg_id: Some(last_known_message_info.id.clone()),
+ oldest_msg_from_me: Some(last_known_message_info.is_from_me),
+ on_demand_msg_count: Some(count),
+ // Despite the name, this holds seconds.
+ oldest_msg_timestamp_ms: last_known_message_info
+ .timestamp
+ .map(|timestamp| timestamp.timestamp()),
+ ..Default::default()
+ },
+ ),
+ ..Default::default()
+ },
+ ),
+ ..Default::default()
+ })),
+ ..Default::default()
+ }
+ }
+
+ async fn send_group(
+ self: &Arc<Self>,
+ own_id: &Jid,
+ to: &Jid,
+ participants: &[Jid],
+ id: &str,
+ message: &wa_e2e::Message,
+ extra_params: NodeExtraParams,
+ ) -> Result<(String, Vec<u8>), ClientError> {
+ let (plaintext, _) = marshal_message(to, message);
+ let own_lid = self.get_own_lid().await;
+ let sender_key_name = crate::signal::SenderKeyName {
+ group_id: to.to_string(),
+ sender: own_lid.signal_address(),
+ };
+ let (skd_plaintext, ciphertext) = async {
+ let store = self.store.read().await;
+ let signal_store = store.signal_store(None);
+ let skdm = self
+ .signal
+ .create_sender_key_distribution_message(&signal_store, &sender_key_name)
+ .await
+ .map_err(|error| {
+ ClientError::from(error).wrap(
+ "failed to create sender key distribution message to send group message",
+ )
+ })?;
+ let skd_message = wa_e2e::Message {
+ sender_key_distribution_message: Some(wa_e2e::SenderKeyDistributionMessage {
+ group_id: Some(to.to_string()),
+ axolotl_sender_key_distribution_message: Some(skdm),
+ }),
+ ..Default::default()
+ };
+ let ciphertext = self
+ .signal
+ .group_encrypt(
+ &signal_store,
+ &sender_key_name,
+ &pad_message(plaintext.clone()),
+ )
+ .await
+ .map_err(|error| {
+ ClientError::from(error).wrap("failed to encrypt group message")
+ })?;
+ Ok::<_, ClientError>((skd_message.encode_to_vec(), ciphertext))
+ }
+ .instrument(tracing::info_span!("whatsmeow.send_message.group_encrypt"))
+ .await?;
+
+ let (mut node, all_devices) = self
+ .prepare_message_node(
+ to,
+ id,
+ message,
+ participants,
+ &skd_plaintext,
+ None,
+ &extra_params,
+ )
+ .await?;
+ let phash = participant_list_hash_v2(&all_devices);
+ node.attrs.insert("phash".to_owned(), phash.clone().into());
+ let mut sk_attrs = Attrs::from([
+ ("v".to_owned(), "2".into()),
+ ("type".to_owned(), "skmsg".into()),
+ ]);
+ let media_type = get_media_type_from_message(message);
+ if !media_type.is_empty() {
+ sk_attrs.insert("mediatype".to_owned(), media_type.into());
+ }
+ push_child(
+ &mut node,
+ Node {
+ tag: "enc".to_owned(),
+ attrs: sk_attrs,
+ content: Some(NodeContent::Bytes(ciphertext)),
+ },
+ );
+ let _ = own_id;
+ let data = self
+ .send_node_and_get_data(&node)
+ .instrument(tracing::info_span!("whatsmeow.send_message.send"))
+ .await
+ .map_err(|error| error.wrap("failed to send message node"))?;
+ Ok((phash, data))
+ }
+
+ async fn send_peer_message_node(
+ self: &Arc<Self>,
+ to: &Jid,
+ id: &str,
+ message: &mut wa_e2e::Message,
+ ) -> Result<Vec<u8>, ClientError> {
+ let node = self.prepare_peer_message_node(to, id, message).await?;
+ self.send_node_and_get_data(&node)
+ .await
+ .map_err(|error| error.wrap("failed to send message node"))
+ }
+
+ async fn send_dm(
+ self: &Arc<Self>,
+ own_id: &Jid,
+ to: &Jid,
+ id: &str,
+ message: &wa_e2e::Message,
+ extra_params: NodeExtraParams,
+ ) -> Result<(String, Vec<u8>), ClientError> {
+ let (message_plaintext, device_sent_plaintext) = marshal_message(to, message);
+ let (mut node, all_devices) = self
+ .prepare_message_node(
+ to,
+ id,
+ message,
+ &[to.clone(), own_id.to_non_ad()],
+ &message_plaintext,
+ device_sent_plaintext.as_deref(),
+ &extra_params,
+ )
+ .await?;
+ let phash = participant_list_hash_v2(&all_devices);
+
+ let tc_token = self.ensure_tc_token(to).await.unwrap_or_else(|error| {
+ tracing::warn!(error = %error, "failed to get privacy token");
+ None
+ });
+ if let Some(token) = tc_token.filter(|token| !token.is_empty()) {
+ push_child(&mut node, bytes_node("tctoken", token));
+ } else if let Some(cs_token) = self.generate_cs_token(to).await {
+ push_child(&mut node, bytes_node("cstoken", cs_token));
+ }
+
+ let data = self
+ .send_node_and_get_data(&node)
+ .instrument(tracing::info_span!("whatsmeow.send_message.send"))
+ .await
+ .map_err(|error| error.wrap("failed to send message node"))?;
+
+ let storage_jid = self.resolve_tc_token_storage_lid(to).await;
+ if crate::tctoken::should_send_tc_token_in_chat_action(to)
+ && crate::tctoken::should_send_new_tc_token(self.get_tc_token_sender_ts(&storage_jid))
+ {
+ let client = Arc::clone(self);
+ self.spawn(async move {
+ client
+ .issue_privacy_token_and_save(storage_jid, Utc::now())
+ .await;
+ });
+ }
+ Ok((phash, data))
+ }
+
+ async fn prepare_peer_message_node(
+ self: &Arc<Self>,
+ to: &Jid,
+ id: &str,
+ message: &wa_e2e::Message,
+ ) -> Result<Node, ClientError> {
+ let mut attrs = Attrs::from([
+ ("id".to_owned(), id.into()),
+ ("type".to_owned(), "text".into()),
+ ("category".to_owned(), "peer".into()),
+ ("to".to_owned(), to.into()),
+ ]);
+ let protocol = message.protocol_message.as_deref();
+ if protocol.and_then(|protocol| protocol.r#type)
+ == Some(protocol_message::Type::AppStateSyncKeyRequest as i32)
+ {
+ attrs.insert("push_priority".to_owned(), "high".into());
+ } else if protocol
+ .and_then(|protocol| protocol.peer_data_operation_request_message.as_ref())
+ .and_then(|request| request.peer_data_operation_request_type)
+ == Some(PeerDataOperationRequestType::HistorySyncOnDemand as i32)
+ {
+ attrs.insert("push_priority".to_owned(), "high_force".into());
+ attrs.insert("privacy_sensitive".to_owned(), "1".into());
+ }
+ let plaintext = message.encode_to_vec();
+ let mut encryption_identity = to.clone();
+ if to.server == DEFAULT_USER_SERVER {
+ let lids = Arc::clone(&self.store.read().await.lids);
+ encryption_identity = lids
+ .get_lid_for_pn(to)
+ .await
+ .map_err(|error| {
+ ClientError::from(error).wrap("failed to get LID for phone number")
+ })?
+ .unwrap_or_default();
+ }
+ let (encrypted, is_pre_key) = self
+ .encrypt_message_for_device(
+ &plaintext,
+ &encryption_identity,
+ None,
+ &Attrs::new(),
+ None,
+ None,
+ )
+ .await
+ .map_err(|error| error.wrap("failed to encrypt peer message"))?;
+ let mut content = vec![
+ Node {
+ tag: "meta".to_owned(),
+ attrs: Attrs::from([("appdata".to_owned(), "default".into())]),
+ content: None,
+ },
+ encrypted,
+ ];
+ if is_pre_key {
+ content.push(self.make_device_identity_node().await);
+ }
+ Ok(Node {
+ tag: "message".to_owned(),
+ attrs,
+ content: Some(NodeContent::Nodes(content)),
+ })
+ }
+
+ /// The children of a message node after the encrypted part.
+ pub(crate) async fn get_message_content(
+ &self,
+ base_node: Node,
+ message: &wa_e2e::Message,
+ message_attrs: &Attrs,
+ include_identity: bool,
+ extra_params: &NodeExtraParams,
+ ) -> Vec<Node> {
+ let mut content = vec![base_node];
+ if include_identity {
+ content.push(self.make_device_identity_node().await);
+ }
+ if matches!(message_attrs.get("type"), Some(AttributeValue::String(kind)) if kind == "poll")
+ {
+ let poll_type = if message.poll_update_message.is_some() {
+ "vote"
+ } else {
+ "creation"
+ };
+ content.push(Node {
+ tag: "meta".to_owned(),
+ attrs: Attrs::from([("polltype".to_owned(), poll_type.into())]),
+ content: None,
+ });
+ }
+ if let Some(meta_node) = &extra_params.meta_node {
+ content.push(meta_node.clone());
+ }
+ content.extend(extra_params.additional_nodes.iter().cloned());
+ let button_type = get_button_type_from_message(message);
+ if !button_type.is_empty() {
+ content.push(Node {
+ tag: "biz".to_owned(),
+ attrs: Attrs::new(),
+ content: Some(NodeContent::Nodes(vec![Node {
+ tag: button_type.to_owned(),
+ attrs: get_button_attributes(message),
+ content: None,
+ }])),
+ });
+ }
+ content
+ }
+
+ #[expect(clippy::too_many_arguments, reason = "mirrors Go's prepareMessageNode")]
+ async fn prepare_message_node(
+ self: &Arc<Self>,
+ to: &Jid,
+ id: &str,
+ message: &wa_e2e::Message,
+ participants: &[Jid],
+ plaintext: &[u8],
+ device_sent_plaintext: Option<&[u8]>,
+ extra_params: &NodeExtraParams,
+ ) -> Result<(Node, Vec<Jid>), ClientError> {
+ let mut all_devices = self
+ .get_user_devices(participants)
+ .instrument(tracing::info_span!("whatsmeow.send_message.get_devices"))
+ .await
+ .map_err(|error| error.wrap("failed to get device list"))?;
+ if to.server == GROUP_SERVER {
+ all_devices
+ .retain(|jid| jid.server != HOSTED_SERVER && jid.server != HOSTED_LID_SERVER);
+ }
+ let message_type = get_type_from_message(message);
+ let mut enc_attrs = Attrs::new();
+ // Only 1:1 messages (with a device sent plaintext) carry the media type.
+ let enc_media_type = get_media_type_from_message(message);
+ if device_sent_plaintext.is_some() && !enc_media_type.is_empty() {
+ enc_attrs.insert("mediatype".to_owned(), enc_media_type.into());
+ }
+ let mut attrs = Attrs::from([
+ ("id".to_owned(), id.into()),
+ ("type".to_owned(), message_type.into()),
+ ("to".to_owned(), to.into()),
+ ]);
+ if !extra_params.peer_recipient_pn.is_empty() {
+ attrs.insert(
+ "peer_recipient_pn".to_owned(),
+ extra_params.peer_recipient_pn.clone().into(),
+ );
+ }
+ if let Some(addressing_mode) = &extra_params.addressing_mode {
+ attrs.insert(
+ "addressing_mode".to_owned(),
+ addressing_mode.as_str().into(),
+ );
+ }
+ let edit = get_edit_attribute(message);
+ if edit != EditAttribute::Empty {
+ attrs.insert("edit".to_owned(), edit.as_str().into());
+ enc_attrs.insert(
+ "decrypt-fail".to_owned(),
+ DecryptFailMode::Hide.as_str().into(),
+ );
+ }
+ if message_type == "reaction" || message.poll_update_message.is_some() {
+ enc_attrs.insert(
+ "decrypt-fail".to_owned(),
+ DecryptFailMode::Hide.as_str().into(),
+ );
+ }
+ let (participant_nodes, include_identity) = self
+ .encrypt_message_for_devices(
+ &all_devices,
+ id,
+ plaintext,
+ device_sent_plaintext,
+ &enc_attrs,
+ )
+ .instrument(tracing::info_span!(
+ "whatsmeow.send_message.peer_encrypt",
+ devices = all_devices.len()
+ ))
+ .await?;
+ let participant_node = Node {
+ tag: "participants".to_owned(),
+ attrs: Attrs::new(),
+ content: Some(NodeContent::Nodes(participant_nodes)),
+ };
+ let content = self
+ .get_message_content(
+ participant_node,
+ message,
+ &attrs,
+ include_identity,
+ extra_params,
+ )
+ .await;
+ Ok((
+ Node {
+ tag: "message".to_owned(),
+ attrs,
+ content: Some(NodeContent::Nodes(content)),
+ },
+ all_devices,
+ ))
+ }
+
+ /// The `<device-identity>` node with our account signature.
+ pub(crate) async fn make_device_identity_node(&self) -> Node {
+ let account = self.store.read().await.account.clone().unwrap_or_default();
+ bytes_node("device-identity", account.encode_to_vec())
+ }
+
+ async fn encrypt_message_for_devices(
+ self: &Arc<Self>,
+ all_devices: &[Jid],
+ id: &str,
+ message_plaintext: &[u8],
+ device_sent_plaintext: Option<&[u8]>,
+ enc_attrs: &Attrs,
+ ) -> Result<(Vec<Node>, bool), ClientError> {
+ let own_jid = self.get_own_id().await;
+ let own_lid = self.get_own_lid().await;
+ let mut include_identity = false;
+ let mut participant_nodes = Vec::with_capacity(all_devices.len());
+
+ let pn_devices: Vec<Jid> = all_devices
+ .iter()
+ .filter(|jid| jid.server == DEFAULT_USER_SERVER)
+ .cloned()
+ .collect();
+ let lids = Arc::clone(&self.store.read().await.lids);
+ let lid_mappings = lids
+ .get_many_lids_for_pns(&pn_devices)
+ .await
+ .map_err(|error| ClientError::from(error).wrap("failed to fetch LID mappings"))?;
+
+ let mut encryption_identities = HashMap::with_capacity(all_devices.len());
+ let mut session_address_to_jid = HashMap::with_capacity(all_devices.len());
+ let mut session_addresses = Vec::with_capacity(all_devices.len());
+ for jid in all_devices {
+ if *jid == own_jid || *jid == own_lid {
+ continue;
+ }
+ let mut encryption_identity = jid.clone();
+ if jid.server == DEFAULT_USER_SERVER
+ && let Some(lid_for_pn) = lid_mappings.get(jid).filter(|lid| !lid.is_empty())
+ {
+ self.migrate_session_store_for_send(jid, lid_for_pn).await;
+ encryption_identity = lid_for_pn.clone();
+ }
+ let address = encryption_identity.signal_address().to_string();
+ encryption_identities.insert(jid.clone(), encryption_identity);
+ session_addresses.push(address.clone());
+ session_address_to_jid.insert(address, jid.clone());
+ }
+
+ let (existing_sessions, cache) = self
+ .store
+ .read()
+ .await
+ .with_cached_sessions(&session_addresses)
+ .await
+ .map_err(|error| ClientError::from(error).wrap("failed to prefetch sessions"))?;
+ let retry_devices: Vec<Jid> = existing_sessions
+ .iter()
+ .filter(|(_, exists)| !**exists)
+ .filter_map(|(address, _)| session_address_to_jid.get(address).cloned())
+ .collect();
+ let bundles = self.fetch_pre_keys_no_error(&retry_devices).await;
+
+ for jid in all_devices {
+ if *jid == own_jid || *jid == own_lid {
+ continue;
+ }
+ let plaintext = match device_sent_plaintext {
+ Some(device_sent) if jid.user == own_jid.user || jid.user == own_lid.user => {
+ device_sent
+ }
+ _ => message_plaintext,
+ };
+ let Some(encryption_identity) = encryption_identities.get(jid) else {
+ continue;
+ };
+ let result = self
+ .encrypt_message_for_device(
+ plaintext,
+ encryption_identity,
+ bundles.get(jid),
+ enc_attrs,
+ Some(&existing_sessions),
+ cache.as_ref(),
+ )
+ .await;
+ match result {
+ Err(error) => {
+ tracing::warn!(error = %error, message_id = id, "failed to encrypt message for a device");
+ continue;
+ }
+ Ok((encrypted, is_pre_key)) => {
+ participant_nodes.push(Node {
+ tag: "to".to_owned(),
+ attrs: Attrs::from([("jid".to_owned(), jid.into())]),
+ content: Some(NodeContent::Nodes(vec![encrypted])),
+ });
+ include_identity |= is_pre_key;
+ }
+ }
+ }
+ if let Some(cache) = &cache {
+ self.store
+ .read()
+ .await
+ .put_cached_sessions(cache)
+ .await
+ .map_err(|error| ClientError::from(error).wrap("failed to save cached sessions"))?;
+ }
+ Ok((participant_nodes, include_identity))
+ }
+
+ async fn migrate_session_store_for_send(&self, pn: &Jid, lid: &Jid) {
+ let sessions = Arc::clone(&self.store.read().await.sessions);
+ if let Err(error) = sessions.migrate_pn_to_lid(pn, lid).await {
+ tracing::error!(error = %error, "failed to migrate signal store from phone number to LID");
+ }
+ }
+
+ /// Encrypts a padded plaintext for one device, starting a session from
+ /// the bundle when there is one. Returns the `<enc>` node and whether it
+ /// is a prekey message (which needs our device identity alongside).
+ pub(crate) async fn encrypt_message_for_device(
+ self: &Arc<Self>,
+ plaintext: &[u8],
+ to: &Jid,
+ bundle: Option<&PreKeyBundle>,
+ extra_attrs: &Attrs,
+ existing_sessions: Option<&HashMap<String, bool>>,
+ cache: Option<&SessionCache>,
+ ) -> Result<(Node, bool), ClientError> {
+ let address = to.signal_address();
+ if let Some(bundle) = bundle {
+ tracing::debug!("processing prekey bundle");
+ let mut result = self.process_bundle_once(&address, bundle, cache).await;
+ if self.config.auto_trust_identity
+ && matches!(result, Err(SignalError::UntrustedIdentity))
+ {
+ tracing::warn!(
+ "untrusted identity while processing prekey bundle, clearing stored identity and retrying"
+ );
+ self.clear_untrusted_identity_for_send(to)
+ .await
+ .map_err(|error| error.wrap("failed to clear untrusted identity"))?;
+ result = self.process_bundle_once(&address, bundle, cache).await;
+ }
+ result.map_err(|error| {
+ ClientError::from(error).wrap("failed to process prekey bundle")
+ })?;
+ } else {
+ let session_exists =
+ match existing_sessions.and_then(|sessions| sessions.get(&address.to_string())) {
+ Some(exists) => *exists,
+ None => {
+ let store = self.store.read().await;
+ store.sessions.has_session(&address.to_string()).await?
+ }
+ };
+ if !session_exists {
+ return Err(ClientError::NoSession.wrap(format!("with {address}")));
+ }
+ }
+ let ciphertext = {
+ let store = self.store.read().await;
+ let signal_store = store.signal_store(cache);
+ self.signal
+ .encrypt(&signal_store, &address, &pad_message(plaintext.to_vec()))
+ .await
+ .map_err(|error| ClientError::from(error).wrap("cipher encryption failed"))?
+ };
+ let mut attrs = Attrs::from([
+ ("v".to_owned(), "2".into()),
+ ("type".to_owned(), "msg".into()),
+ ]);
+ if ciphertext.kind == CiphertextType::PreKey {
+ attrs.insert("type".to_owned(), "pkmsg".into());
+ }
+ for (key, value) in extra_attrs {
+ attrs.insert(key.clone(), value.clone());
+ }
+ let include_device_identity =
+ matches!(attrs.get("type"), Some(AttributeValue::String(kind)) if kind == "pkmsg");
+ Ok((
+ Node {
+ tag: "enc".to_owned(),
+ attrs,
+ content: Some(NodeContent::Bytes(ciphertext.serialized)),
+ },
+ include_device_identity,
+ ))
+ }
+
+ async fn process_bundle_once(
+ &self,
+ address: &crate::signal::SignalAddress,
+ bundle: &PreKeyBundle,
+ cache: Option<&SessionCache>,
+ ) -> Result<(), SignalError> {
+ let store = self.store.read().await;
+ let signal_store = store.signal_store(cache);
+ self.signal
+ .process_bundle(&signal_store, address, bundle)
+ .await
+ }
+
+ async fn clear_untrusted_identity_for_send(
+ self: &Arc<Self>,
+ target: &Jid,
+ ) -> Result<(), ClientError> {
+ let (identities, sessions) = {
+ let store = self.store.read().await;
+ (Arc::clone(&store.identities), Arc::clone(&store.sessions))
+ };
+ let address = target.signal_address().to_string();
+ identities
+ .delete_identity(&address)
+ .await
+ .map_err(|error| ClientError::from(error).wrap("failed to delete identity"))?;
+ sessions
+ .delete_session(&address)
+ .await
+ .map_err(|error| ClientError::from(error).wrap("failed to delete session"))?;
+ self.spawn_dispatch(crate::Event::IdentityChange(
+ crate::types::events::IdentityChange {
+ jid: target.clone(),
+ timestamp: Some(Utc::now()),
+ implicit: true,
+ },
+ ));
+ Ok(())
+ }
+
+ /// Our JID and LID without awaiting the store lock, for the synchronous
+ /// builders; empty if the store is being written.
+ fn own_ids_now(&self) -> (Jid, Jid) {
+ match self.store.try_read() {
+ Ok(store) => (store.get_jid(), store.get_lid()),
+ Err(_) => (Jid::default(), Jid::default()),
+ }
+ }
+}
+
+fn push_child(node: &mut Node, child: Node) {
+ match &mut node.content {
+ Some(NodeContent::Nodes(children)) => children.push(child),
+ _ => node.content = Some(NodeContent::Nodes(vec![child])),
+ }
+}
+
+/// `GenerateMessageID` with its inputs as parameters, for tests.
+pub fn generate_message_id_with(own_id: &Jid, unix_seconds: i64, random: &[u8; 16]) -> MessageId {
+ let mut data = Vec::with_capacity(8 + 20 + 16);
+ data.extend_from_slice(
+ &u64::try_from(unix_seconds)
+ .unwrap_or_default()
+ .to_be_bytes(),
+ );
+ if !own_id.is_empty() {
+ data.extend_from_slice(own_id.user.as_bytes());
+ data.extend_from_slice(b"@c.us");
+ }
+ data.extend_from_slice(random);
+ let hash = Sha256::digest(&data);
+ format!("{WEB_MESSAGE_ID_PREFIX}{}", hex::encode_upper(&hash[..9]))
+}
+
+/// `BuildMessageKey` with our JIDs as parameters.
+pub fn build_message_key_with(
+ own_id: &Jid,
+ own_lid: &Jid,
+ chat: &Jid,
+ sender: &Jid,
+ id: &str,
+) -> MessageKey {
+ let mut key = MessageKey {
+ from_me: Some(true),
+ id: Some(id.to_owned()),
+ remote_jid: Some(chat.to_string()),
+ participant: None,
+ };
+ if !sender.is_empty() && sender.user != own_id.user && sender.user != own_lid.user {
+ key.from_me = Some(false);
+ if chat.server != DEFAULT_USER_SERVER
+ && chat.server != HIDDEN_USER_SERVER
+ && chat.server != MESSENGER_SERVER
+ {
+ key.participant = Some(sender.to_non_ad().to_string());
+ }
+ }
+ key
+}
+
+/// An edit replacing an earlier message's content.
+pub fn build_edit(chat: &Jid, id: &str, new_content: wa_e2e::Message) -> wa_e2e::Message {
+ wa_e2e::Message {
+ edited_message: Some(Box::new(wa_e2e::FutureProofMessage {
+ message: Some(Box::new(wa_e2e::Message {
+ protocol_message: Some(Box::new(wa_e2e::ProtocolMessage {
+ key: Some(MessageKey {
+ from_me: Some(true),
+ id: Some(id.to_owned()),
+ remote_jid: Some(chat.to_string()),
+ participant: None,
+ }),
+ r#type: Some(protocol_message::Type::MessageEdit as i32),
+ edited_message: Some(Box::new(new_content)),
+ timestamp_ms: Some(Utc::now().timestamp_millis()),
+ ..Default::default()
+ })),
+ ..Default::default()
+ })),
+ })),
+ ..Default::default()
+ }
+}
+
+/// The participant hash of a device list: `2:` and the base64 of the first
+/// six bytes of SHA-256 over the sorted AD strings.
+pub fn participant_list_hash_v2(participants: &[Jid]) -> String {
+ let mut participant_strings: Vec<String> = participants.iter().map(Jid::ad_string).collect();
+ participant_strings.sort();
+ let hash = Sha256::digest(participant_strings.concat().as_bytes());
+ format!("2:{}", STANDARD_NO_PAD.encode(&hash[..6]))
+}
+
+/// The protobuf of a message, and for chats other than groups the
+/// `DeviceSentMessage` our other devices get.
+pub(crate) fn marshal_message(to: &Jid, message: &wa_e2e::Message) -> (Vec<u8>, Option<Vec<u8>>) {
+ let plaintext = message.encode_to_vec();
+ let device_sent = (to.server != GROUP_SERVER && to.server != NEWSLETTER_SERVER).then(|| {
+ wa_e2e::Message {
+ device_sent_message: Some(Box::new(wa_e2e::DeviceSentMessage {
+ destination_jid: Some(to.to_string()),
+ message: Some(Box::new(message.clone())),
+ phash: None,
+ })),
+ message_context_info: message.message_context_info.clone(),
+ ..Default::default()
+ }
+ .encode_to_vec()
+ });
+ (plaintext, device_sent)
+}
+
+fn inner(wrapper: Option<&wa_e2e::FutureProofMessage>) -> Option<&wa_e2e::Message> {
+ wrapper.and_then(|wrapper| wrapper.message.as_deref())
+}
+
+fn unwrapped(message: &wa_e2e::Message) -> Option<&wa_e2e::Message> {
+ if message.view_once_message.is_some() {
+ return inner(message.view_once_message.as_deref());
+ }
+ if message.view_once_message_v2.is_some() {
+ return inner(message.view_once_message_v2.as_deref());
+ }
+ if message.view_once_message_v2_extension.is_some() {
+ return inner(message.view_once_message_v2_extension.as_deref());
+ }
+ if message.lottie_sticker_message.is_some() {
+ return inner(message.lottie_sticker_message.as_deref());
+ }
+ if message.ephemeral_message.is_some() {
+ return inner(message.ephemeral_message.as_deref());
+ }
+ if message.document_with_caption_message.is_some() {
+ return inner(message.document_with_caption_message.as_deref());
+ }
+ None
+}
+
+fn is_wrapper(message: &wa_e2e::Message) -> bool {
+ message.view_once_message.is_some()
+ || message.view_once_message_v2.is_some()
+ || message.view_once_message_v2_extension.is_some()
+ || message.lottie_sticker_message.is_some()
+ || message.ephemeral_message.is_some()
+ || message.document_with_caption_message.is_some()
+}
+
+/// The `type` attribute of a message node.
+pub fn get_type_from_message(message: &wa_e2e::Message) -> &'static str {
+ if is_wrapper(message) {
+ return unwrapped(message).map_or("text", get_type_from_message);
+ }
+ if message.reaction_message.is_some() || message.enc_reaction_message.is_some() {
+ "reaction"
+ } else if message.poll_creation_message.is_some() || message.poll_update_message.is_some() {
+ "poll"
+ } else if !get_media_type_from_message(message).is_empty() {
+ "media"
+ } else {
+ "text"
+ }
+}
+
+/// The `mediatype` attribute of a message node, empty for non-media.
+pub fn get_media_type_from_message(message: &wa_e2e::Message) -> &'static str {
+ if is_wrapper(message) {
+ return unwrapped(message).map_or("", get_media_type_from_message);
+ }
+ if message
+ .extended_text_message
+ .as_ref()
+ .is_some_and(|text| text.title.is_some())
+ {
+ "url"
+ } else if message.image_message.is_some() {
+ "image"
+ } else if message.sticker_message.is_some() {
+ "sticker"
+ } else if message.document_message.is_some() {
+ "document"
+ } else if let Some(audio) = &message.audio_message {
+ if audio.ptt.unwrap_or_default() {
+ "ptt"
+ } else {
+ "audio"
+ }
+ } else if let Some(video) = &message.video_message {
+ if video.gif_playback.unwrap_or_default() {
+ "gif"
+ } else {
+ "video"
+ }
+ } else if message.contact_message.is_some() {
+ "vcard"
+ } else if message.contacts_array_message.is_some() {
+ "contact_array"
+ } else if message.list_message.is_some() {
+ "list"
+ } else if message.list_response_message.is_some() {
+ "list_response"
+ } else if message.buttons_response_message.is_some() {
+ "buttons_response"
+ } else if message.order_message.is_some() {
+ "order"
+ } else if message.product_message.is_some() {
+ "product"
+ } else if message.interactive_response_message.is_some() {
+ "native_flow_response"
+ } else {
+ ""
+ }
+}
+
+fn get_button_type_from_message(message: &wa_e2e::Message) -> &'static str {
+ if message.view_once_message.is_some() {
+ return inner(message.view_once_message.as_deref())
+ .map_or("", get_button_type_from_message);
+ }
+ if message.view_once_message_v2.is_some() {
+ return inner(message.view_once_message_v2.as_deref())
+ .map_or("", get_button_type_from_message);
+ }
+ if message.ephemeral_message.is_some() {
+ return inner(message.ephemeral_message.as_deref())
+ .map_or("", get_button_type_from_message);
+ }
+ if message.buttons_message.is_some() {
+ "buttons"
+ } else if message.buttons_response_message.is_some() {
+ "buttons_response"
+ } else if message.list_message.is_some() {
+ "list"
+ } else if message.list_response_message.is_some() {
+ "list_response"
+ } else if message.interactive_response_message.is_some() {
+ "interactive_response"
+ } else {
+ ""
+ }
+}
+
+fn get_button_attributes(message: &wa_e2e::Message) -> Attrs {
+ if message.view_once_message.is_some() {
+ return inner(message.view_once_message.as_deref())
+ .map_or_else(Attrs::new, get_button_attributes);
+ }
+ if message.view_once_message_v2.is_some() {
+ return inner(message.view_once_message_v2.as_deref())
+ .map_or_else(Attrs::new, get_button_attributes);
+ }
+ if message.ephemeral_message.is_some() {
+ return inner(message.ephemeral_message.as_deref())
+ .map_or_else(Attrs::new, get_button_attributes);
+ }
+ if message.template_message.is_some() {
+ return Attrs::new();
+ }
+ match &message.list_message {
+ Some(list) => {
+ let list_type =
+ wa_e2e::list_message::ListType::try_from(list.list_type.unwrap_or_default())
+ .map(|list_type| list_type.as_str_name().to_lowercase())
+ .unwrap_or_default();
+ Attrs::from([
+ ("v".to_owned(), "2".into()),
+ ("type".to_owned(), list_type.into()),
+ ])
+ }
+ None => Attrs::new(),
+ }
+}
+
+/// The `edit` attribute of a message node.
+pub fn get_edit_attribute(message: &wa_e2e::Message) -> EditAttribute {
+ if let Some(edited) = inner(message.edited_message.as_deref()) {
+ return get_edit_attribute(edited);
+ }
+ if let Some(protocol) = message.protocol_message.as_deref()
+ && let Some(key) = &protocol.key
+ {
+ let protocol_type = protocol.r#type;
+ if protocol_type == Some(protocol_message::Type::Revoke as i32) {
+ return if key.from_me.unwrap_or_default() {
+ EditAttribute::SenderRevoke
+ } else {
+ EditAttribute::AdminRevoke
+ };
+ }
+ if protocol_type == Some(protocol_message::Type::MessageEdit as i32)
+ && protocol.edited_message.is_some()
+ {
+ return EditAttribute::MessageEdit;
+ }
+ return EditAttribute::Empty;
+ }
+ if message.reaction_message.as_ref().is_some_and(|reaction| {
+ reaction.text.as_deref().unwrap_or_default() == REMOVE_REACTION_TEXT
+ }) {
+ return EditAttribute::SenderRevoke;
+ }
+ if message.keep_in_chat_message.as_ref().is_some_and(|keep| {
+ keep.key
+ .as_ref()
+ .and_then(|key| key.from_me)
+ .unwrap_or_default()
+ && keep.keep_type == Some(KeepType::UndoKeepForAll as i32)
+ }) {
+ return EditAttribute::SenderRevoke;
+ }
+ if message.pin_in_chat_message.is_some() {
+ return EditAttribute::PinInChat;
+ }
+ EditAttribute::Empty
+}
+
+#[cfg(test)]
+mod test;
diff --git a/crates/whatsmeow/src/send/test.rs b/crates/whatsmeow/src/send/test.rs
new file mode 100644
index 0000000000..0cd065eff3
--- /dev/null
+++ b/crates/whatsmeow/src/send/test.rs
@@ -0,0 +1,543 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+//! Message type attributes, marshaling and participant hashes match
+//! whatsmeow's (see `testdata/generator/inpackage/message_vectors_test.go`).
+
+use super::*;
+use crate::types::parse_jid;
+use crate::vectors::Vectors;
+
+#[test]
+fn message_attributes_and_marshaling_match_go() {
+ let vectors = Vectors::load("message.json");
+ let to = parse_jid("777@lid").unwrap();
+ let cases = vectors.value("types").as_array().unwrap();
+ assert_eq!(cases.len(), 11);
+ for case in cases {
+ let raw = hex::decode(case["message"].as_str().unwrap()).unwrap();
+ let message = wa_e2e::Message::decode(raw.as_slice()).unwrap();
+ assert_eq!(message.encode_to_vec(), raw, "Rust encodes like Go");
+ assert_eq!(
+ get_type_from_message(&message),
+ case["type"].as_str().unwrap()
+ );
+ assert_eq!(
+ get_media_type_from_message(&message),
+ case["media_type"].as_str().unwrap()
+ );
+ assert_eq!(
+ get_edit_attribute(&message).as_str(),
+ case["edit"].as_str().unwrap()
+ );
+ let (plaintext, device_sent) = marshal_message(&to, &message);
+ assert_eq!(hex::encode(plaintext), case["plaintext"].as_str().unwrap());
+ assert_eq!(
+ hex::encode(device_sent.unwrap_or_default()),
+ case["device_sent_plaintext"].as_str().unwrap()
+ );
+ }
+}
+
+#[test]
+fn participant_hashes_match_go() {
+ let vectors = Vectors::load("message.json");
+ for case in vectors.value("hashes").as_array().unwrap() {
+ let jids: Vec<Jid> = case["jids"]
+ .as_array()
+ .map(|jids| {
+ jids.iter()
+ .map(|jid| parse_jid(jid.as_str().unwrap()).unwrap())
+ .collect()
+ })
+ .unwrap_or_default();
+ assert_eq!(
+ participant_list_hash_v2(&jids),
+ case["hash"].as_str().unwrap()
+ );
+ }
+}
+
+#[test]
+fn builders_match_go() {
+ let vectors = Vectors::load("message.json");
+ let own = parse_jid("1234:[email protected]").unwrap();
+ let own_lid = parse_jid("9876:5@lid").unwrap();
+ let group = parse_jid("[email protected]").unwrap();
+ let sender = parse_jid("777@lid").unwrap();
+ let request = wa_e2e::Message {
+ protocol_message: Some(Box::new(wa_e2e::ProtocolMessage {
+ r#type: Some(protocol_message::Type::PeerDataOperationRequestMessage as i32),
+ peer_data_operation_request_message: Some(wa_e2e::PeerDataOperationRequestMessage {
+ peer_data_operation_request_type: Some(
+ PeerDataOperationRequestType::PlaceholderMessageResend as i32,
+ ),
+ placeholder_message_resend_request: vec![
+ peer_data_operation_request_message::PlaceholderMessageResendRequest {
+ message_key: Some(build_message_key_with(
+ &own, &own_lid, &group, &sender, "LOST",
+ )),
+ },
+ ],
+ ..Default::default()
+ }),
+ ..Default::default()
+ })),
+ ..Default::default()
+ };
+ assert_eq!(
+ hex::encode(request.encode_to_vec()),
+ vectors.string("unavailable_req")
+ );
+}
+
+#[test]
+fn message_ids_look_like_whatsapp_web_ids() {
+ let own = parse_jid("1234:[email protected]").unwrap();
+ let id = generate_message_id_with(&own, 1_700_000_000, &[7; 16]);
+ assert_eq!(id.len(), 4 + 18);
+ assert!(id.starts_with(WEB_MESSAGE_ID_PREFIX));
+ assert_eq!(id, id.to_uppercase());
+}
+
+mod fake_server {
+ use std::sync::Arc;
+
+ use crate::binary::{AttributeValue, Node, NodeContent};
+ use crate::client::test::{
+ bytes, children, connect_paired, harness, jid, next_event, next_node, node, text,
+ };
+ use crate::prekeys::pre_key_to_node;
+ use crate::proto::wa_e2e;
+ use crate::send::SendRequestExtra;
+ use crate::testing::{ServerConnection, attr_string, is_iq};
+ use crate::types::events::Event;
+ use crate::types::{SERVER_JID, parse_jid};
+ use crate::util::keys::{new_key_pair, new_pre_key};
+
+ const OWN: (&str, &str) = ("1234:[email protected]", "9876:5@lid");
+ const GROUP: &str = "[email protected]";
+
+ fn usync_devices(users: &[(&str, &[&str])]) -> Node {
+ node(
+ "usync",
+ &[],
+ children(vec![node(
+ "list",
+ &[],
+ children(
+ users
+ .iter()
+ .map(|(user, devices)| {
+ node(
+ "user",
+ &[("jid", jid(user))],
+ children(vec![node(
+ "devices",
+ &[],
+ children(vec![node(
+ "device-list",
+ &[],
+ children(
+ devices
+ .iter()
+ .map(|id| node("device", &[("id", text(id))], None))
+ .collect(),
+ ),
+ )]),
+ )]),
+ )
+ })
+ .collect(),
+ ),
+ )]),
+ )
+ }
+
+ fn bundle_user(device: &str) -> Node {
+ let identity = new_key_pair();
+ let mut signed = new_pre_key(1);
+ signed.signature = Some([9; 64]);
+ node(
+ "user",
+ &[("jid", jid(device))],
+ children(vec![
+ node("registration", &[], bytes(&7_u32.to_be_bytes())),
+ node("type", &[], bytes(&[5])),
+ node("identity", &[], bytes(&identity.public)),
+ pre_key_to_node(&new_pre_key(42)),
+ pre_key_to_node(&signed),
+ ]),
+ )
+ }
+
+ fn requested_users(request: &Node) -> Vec<String> {
+ request
+ .get_child_by_tag(&["key"])
+ .get_children()
+ .iter()
+ .map(|user| attr_string(user, "jid"))
+ .collect()
+ }
+
+ /// Answers group info, usync and prekey requests until the message node
+ /// arrives, and returns it.
+ async fn serve_until_message(
+ connection: &mut ServerConnection,
+ devices: &[(&str, &[&str])],
+ ) -> Node {
+ loop {
+ let request = next_node(connection).await;
+ if request.tag == "message" {
+ return request;
+ }
+ if is_iq(&request, "w:g2") {
+ connection
+ .respond_iq(
+ &request,
+ vec![node(
+ "group",
+ &[
+ ("id", text("120363001234567890")),
+ ("subject", text("Team")),
+ ("addressing_mode", text("lid")),
+ ],
+ children(vec![
+ node(
+ "participant",
+ &[("jid", jid("1111@lid")), ("type", text("admin"))],
+ None,
+ ),
+ node("participant", &[("jid", jid("2222@lid"))], None),
+ node("participant", &[("jid", jid("9876@lid"))], None),
+ ]),
+ )],
+ )
+ .await;
+ } else if is_iq(&request, "usync") {
+ connection
+ .respond_iq(&request, vec![usync_devices(devices)])
+ .await;
+ } else if is_iq(&request, "encrypt") {
+ let users = requested_users(&request);
+ connection
+ .respond_iq(
+ &request,
+ vec![node(
+ "list",
+ &[],
+ children(users.iter().map(|user| bundle_user(user)).collect()),
+ )],
+ )
+ .await;
+ } else if request.tag == "iq" {
+ connection.respond_iq(&request, vec![]).await;
+ }
+ }
+ }
+
+ fn ack_for(message: &Node) -> Node {
+ let mut attrs = vec![
+ ("class", text("message")),
+ ("id", AttributeValue::String(attr_string(message, "id"))),
+ ("t", text("1700000500")),
+ ("from", AttributeValue::Jid(SERVER_JID.clone())),
+ ];
+ let phash = attr_string(message, "phash");
+ if !phash.is_empty() {
+ attrs.push(("phash", AttributeValue::String(phash)));
+ }
+ node("ack", &attrs, None)
+ }
+
+ fn enc_children(to: &Node) -> Vec<&Node> {
+ to.get_children()
+ .iter()
+ .filter(|child| child.tag == "enc")
+ .collect()
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn a_group_message_fans_out_to_every_device_with_the_sender_key() {
+ let mut harness = harness(Some(OWN));
+ let mut connection = connect_paired(&mut harness).await;
+ let client = Arc::clone(&harness.client);
+ let send = tokio::spawn(async move {
+ client
+ .send_message(
+ &parse_jid(GROUP).unwrap(),
+ wa_e2e::Message {
+ conversation: Some("hello group".to_owned()),
+ ..Default::default()
+ },
+ SendRequestExtra::default(),
+ )
+ .await
+ });
+ let message = serve_until_message(
+ &mut connection,
+ &[
+ ("1111@lid", &["0"]),
+ ("2222@lid", &["0", "3"]),
+ ("9876@lid", &["0", "5"]),
+ ],
+ )
+ .await;
+ assert_eq!(attr_string(&message, "to"), GROUP);
+ assert_eq!(attr_string(&message, "type"), "text");
+ assert_eq!(attr_string(&message, "addressing_mode"), "lid");
+ let participants = message.get_child_by_tag(&["participants"]);
+ let mut recipients: Vec<String> = participants
+ .get_children()
+ .iter()
+ .map(|to| attr_string(to, "jid"))
+ .collect();
+ recipients.sort();
+ assert_eq!(
+ recipients,
+ ["1111@lid", "2222:3@lid", "2222@lid", "9876@lid"]
+ );
+ for to in participants.get_children() {
+ let encs = enc_children(to);
+ assert_eq!(encs.len(), 1);
+ assert_eq!(attr_string(encs[0], "type"), "pkmsg");
+ }
+ assert!(
+ message
+ .get_optional_child_by_tag(&["device-identity"])
+ .is_some()
+ );
+ let skmsg = message
+ .get_children()
+ .iter()
+ .find(|child| child.tag == "enc")
+ .expect("group ciphertext");
+ assert_eq!(attr_string(skmsg, "type"), "skmsg");
+ let Some(NodeContent::Bytes(ciphertext)) = &skmsg.content else {
+ panic!("skmsg has bytes");
+ };
+ let padded = ciphertext
+ .strip_prefix(b"FAKEG")
+ .expect("fake group ciphertext");
+ let plaintext = crate::message::unpad_message(padded.to_vec(), 2).unwrap();
+ assert_eq!(
+ wa_e2e::Message::decode_from(&plaintext)
+ .conversation
+ .as_deref(),
+ Some("hello group")
+ );
+ assert!(attr_string(&message, "phash").starts_with("2:"));
+
+ connection.send_node(&ack_for(&message)).await;
+ let response = send.await.unwrap().unwrap();
+ assert_eq!(response.chat.to_string(), GROUP);
+ assert_eq!(response.sender.to_string(), OWN.1);
+ assert_eq!(response.timestamp.unwrap().timestamp(), 1_700_000_500);
+
+ // The sessions now exist, so a second send needs no prekeys.
+ let client = Arc::clone(&harness.client);
+ let send = tokio::spawn(async move {
+ client
+ .send_message(
+ &parse_jid(GROUP).unwrap(),
+ wa_e2e::Message {
+ conversation: Some("again".to_owned()),
+ ..Default::default()
+ },
+ SendRequestExtra::default(),
+ )
+ .await
+ });
+ let message = next_node(&mut connection).await;
+ assert_eq!(message.tag, "message", "group info and devices are cached");
+ connection.send_node(&ack_for(&message)).await;
+ send.await.unwrap().unwrap();
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn a_direct_message_goes_to_the_lid_and_our_other_devices() {
+ let mut harness = harness(Some(OWN));
+ harness
+ .client
+ .store_lid_pn_mapping(
+ &parse_jid("777@lid").unwrap(),
+ &parse_jid("[email protected]").unwrap(),
+ )
+ .await;
+ let mut connection = connect_paired(&mut harness).await;
+ let client = Arc::clone(&harness.client);
+ let send = tokio::spawn(async move {
+ client
+ .send_message(
+ &parse_jid("[email protected]").unwrap(),
+ wa_e2e::Message {
+ conversation: Some("hi".to_owned()),
+ ..Default::default()
+ },
+ SendRequestExtra {
+ id: "3EB0FIXED".to_owned(),
+ ..SendRequestExtra::default()
+ },
+ )
+ .await
+ });
+ let message = serve_until_message(
+ &mut connection,
+ &[("777@lid", &["0"]), ("9876@lid", &["0", "5", "7"])],
+ )
+ .await;
+ assert_eq!(attr_string(&message, "id"), "3EB0FIXED");
+ assert_eq!(attr_string(&message, "to"), "777@lid");
+ assert_eq!(
+ attr_string(&message, "peer_recipient_pn"),
+ );
+ let mut recipients: Vec<String> = message
+ .get_child_by_tag(&["participants"])
+ .get_children()
+ .iter()
+ .map(|to| attr_string(to, "jid"))
+ .collect();
+ recipients.sort();
+ assert_eq!(recipients, ["777@lid", "9876:7@lid", "9876@lid"]);
+ connection.send_node(&ack_for(&message)).await;
+ let response = send.await.unwrap().unwrap();
+ assert_eq!(response.id, "3EB0FIXED");
+ assert_eq!(response.chat.to_string(), "777@lid");
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn a_retry_receipt_resends_the_message_to_that_device() {
+ let mut harness = harness(Some(OWN));
+ harness
+ .client
+ .store_lid_pn_mapping(
+ &parse_jid("777@lid").unwrap(),
+ &parse_jid("[email protected]").unwrap(),
+ )
+ .await;
+ let mut connection = connect_paired(&mut harness).await;
+ let client = Arc::clone(&harness.client);
+ let send = tokio::spawn(async move {
+ client
+ .send_message(
+ &parse_jid("777@lid").unwrap(),
+ wa_e2e::Message {
+ conversation: Some("retry me".to_owned()),
+ ..Default::default()
+ },
+ SendRequestExtra {
+ id: "3EB0RETRY".to_owned(),
+ ..SendRequestExtra::default()
+ },
+ )
+ .await
+ });
+ let message = serve_until_message(
+ &mut connection,
+ &[("777@lid", &["0"]), ("9876@lid", &["0", "5"])],
+ )
+ .await;
+ connection.send_node(&ack_for(&message)).await;
+ send.await.unwrap().unwrap();
+
+ connection
+ .send_node(&node(
+ "receipt",
+ &[
+ ("from", jid("777@lid")),
+ ("id", text("3EB0RETRY")),
+ ("t", text("1700000600")),
+ ("type", text("retry")),
+ ],
+ children(vec![
+ node(
+ "retry",
+ &[
+ ("id", text("3EB0RETRY")),
+ ("t", text("1700000500")),
+ ("count", text("1")),
+ ("v", text("1")),
+ ],
+ None,
+ ),
+ node("registration", &[], bytes(&7_u32.to_be_bytes())),
+ ]),
+ ))
+ .await;
+ let mut resend = None;
+ let mut acked = false;
+ while resend.is_none() || !acked {
+ let next = next_node(&mut connection).await;
+ match next.tag.as_str() {
+ "message" => resend = Some(next),
+ "ack" => {
+ assert_eq!(attr_string(&next, "class"), "receipt");
+ acked = true;
+ }
+ _ => {}
+ }
+ }
+ let resend = resend.unwrap();
+ assert_eq!(attr_string(&resend, "id"), "3EB0RETRY");
+ assert_eq!(attr_string(&resend, "to"), "777@lid");
+ assert_eq!(attr_string(&resend, "device_fanout"), "false");
+ let enc = resend.get_child_by_tag(&["enc"]);
+ assert_eq!(attr_string(enc, "count"), "1");
+ loop {
+ if let Event::Receipt(receipt) = next_event(&mut harness.events).await {
+ assert_eq!(receipt.message_ids, ["3EB0RETRY"]);
+ break;
+ }
+ }
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn a_send_without_disconnect_retry_fails_instead_of_resending() {
+ let mut harness = harness(Some(OWN));
+ let mut connection = connect_paired(&mut harness).await;
+ let client = Arc::clone(&harness.client);
+ let send = tokio::spawn(async move {
+ client
+ .send_message(
+ &parse_jid("777@lid").unwrap(),
+ wa_e2e::Message {
+ conversation: Some("once".to_owned()),
+ ..Default::default()
+ },
+ SendRequestExtra {
+ no_disconnect_retry: true,
+ ..SendRequestExtra::default()
+ },
+ )
+ .await
+ });
+ let _message = serve_until_message(
+ &mut connection,
+ &[("777@lid", &["0"]), ("9876@lid", &["0", "5"])],
+ )
+ .await;
+ connection.close().await;
+ let error = send.await.unwrap().unwrap_err();
+ assert!(
+ matches!(error, crate::errors::ClientError::Disconnected(_)),
+ "{error}"
+ );
+ loop {
+ if let Event::Disconnected(_) = next_event(&mut harness.events).await {
+ break;
+ }
+ }
+ }
+
+ trait DecodeFrom {
+ fn decode_from(data: &[u8]) -> Self;
+ }
+
+ impl DecodeFrom for wa_e2e::Message {
+ fn decode_from(data: &[u8]) -> Self {
+ prost::Message::decode(data).unwrap()
+ }
+ }
+}
diff --git a/crates/whatsmeow/src/signal.rs b/crates/whatsmeow/src/signal.rs
new file mode 100644
index 0000000000..30aa01741c
--- /dev/null
+++ b/crates/whatsmeow/src/signal.rs
@@ -0,0 +1,254 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+//! The boundary to the Signal protocol.
+//!
+//! whatsmeow delegates the Signal protocol to `go.mau.fi/libsignal`, which is
+//! GPL-3.0. This module is not a port of anything: it names the libsignal
+//! types and operations whatsmeow uses, as seen from whatsmeow's own call
+//! sites, so the rest of the port can be written against them. No
+//! implementation ships with the crate; see `AGENTS.md` for the pending
+//! licensing decision.
+//!
+//! Session and sender key records are opaque bytes here: whatsmeow only ever
+//! stores them, so their format belongs to whichever implementation is chosen.
+
+use std::fmt;
+
+use async_trait::async_trait;
+
+use crate::store::StoreError;
+
+/// The address of one device's Signal session: a name (the JID user, plus the
+/// domain type for non-default domains) and a device number.
+#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
+pub struct SignalAddress {
+ /// The user part, e.g. `12345` or `12345_1` for a LID.
+ pub name: String,
+ /// The device number.
+ pub device_id: u32,
+}
+
+impl SignalAddress {
+ /// Creates a new address.
+ pub fn new(name: String, device_id: u32) -> Self {
+ Self { name, device_id }
+ }
+}
+
+/// `name:device`, the form whatsmeow uses as the key of sessions and
+/// identities in its stores (its SQL matches them with `LIKE user || ':%'`).
+impl fmt::Display for SignalAddress {
+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
+ write!(formatter, "{}:{}", self.name, self.device_id)
+ }
+}
+
+/// The key type byte libsignal prefixes Curve25519 public keys with
+/// (`ecc.DjbType`).
+pub const DJB_TYPE: u8 = 5;
+
+/// Curve25519 signatures (XEdDSA): libsignal's `ecc.CalculateSignature` and
+/// `ecc.VerifySignature`. whatsmeow uses them to sign prekeys and pairing
+/// messages and to verify the server's noise certificate.
+pub trait CurveSignatures: Send + Sync {
+ /// Signs `message` with a Curve25519 private key.
+ fn calculate_signature(&self, private_key: &[u8; 32], message: &[u8]) -> [u8; 64];
+
+ /// Whether `signature` is a valid signature of `message` by a Curve25519
+ /// public key.
+ fn verify_signature(&self, public_key: &[u8; 32], message: &[u8], signature: &[u8; 64])
+ -> bool;
+}
+
+/// A sender's sender key in a group: libsignal's `protocol.SenderKeyName`.
+#[derive(Clone, Debug, PartialEq, Eq, Hash)]
+pub struct SenderKeyName {
+ /// The group JID as a string.
+ pub group_id: String,
+ /// The sending device.
+ pub sender: SignalAddress,
+}
+
+/// Another device's keys for starting a session: libsignal's `prekey.Bundle`,
+/// as whatsmeow builds it from a prekey response.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct PreKeyBundle {
+ /// The device's registration ID.
+ pub registration_id: u32,
+ /// The device number.
+ pub device_id: u32,
+ /// The one-time prekey, if the server had one left.
+ pub pre_key: Option<(u32, [u8; 32])>,
+ /// The signed prekey ID.
+ pub signed_pre_key_id: u32,
+ /// The signed prekey.
+ pub signed_pre_key_public: [u8; 32],
+ /// The identity key's signature of the signed prekey.
+ pub signed_pre_key_signature: [u8; 64],
+ /// The identity key.
+ pub identity_key: [u8; 32],
+}
+
+/// The two kinds of one-to-one ciphertext.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum CiphertextType {
+ /// A message that also sets up the session (`pkmsg`).
+ PreKey,
+ /// A message in an established session (`msg`).
+ Whisper,
+}
+
+/// An encrypted one-to-one message.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct CiphertextMessage {
+ /// Which kind of message it is.
+ pub kind: CiphertextType,
+ /// The serialized message.
+ pub serialized: Vec<u8>,
+}
+
+/// Signal protocol failures whatsmeow distinguishes.
+#[derive(Debug, thiserror::Error)]
+pub enum SignalError {
+ /// The peer's identity key changed (`signalerror.ErrUntrustedIdentity`).
+ #[error("untrusted identity")]
+ UntrustedIdentity,
+ /// The message was already decrypted (`signalerror.ErrOldCounter`).
+ #[error("old counter")]
+ OldCounter,
+ /// There is no sender key for the sender (`signalerror.ErrNoSenderKeyForUser`).
+ #[error("no sender key for user")]
+ NoSenderKeyForUser,
+ /// The store failed.
+ #[error(transparent)]
+ Store(#[from] StoreError),
+ /// Any other protocol failure.
+ #[error("signal protocol error: {0:?}")]
+ Internal(rootcause::Report),
+}
+
+/// The storage libsignal reads and writes while encrypting and decrypting:
+/// the methods whatsmeow's `store.Device` implements in `store/signal.go`.
+///
+/// Object safe (`&dyn SignalProtocolStore`), hence `async_trait`.
+#[async_trait]
+pub trait SignalProtocolStore: Send + Sync {
+ /// The local identity keypair as (public, private).
+ fn get_identity_key_pair(&self) -> ([u8; 32], [u8; 32]);
+ /// The local registration ID.
+ fn get_local_registration_id(&self) -> u32;
+ /// Remembers a peer's identity key.
+ async fn save_identity(
+ &self,
+ address: &SignalAddress,
+ identity_key: [u8; 32],
+ ) -> Result<(), StoreError>;
+ /// Whether a peer's identity key is the trusted one.
+ async fn is_trusted_identity(
+ &self,
+ address: &SignalAddress,
+ identity_key: [u8; 32],
+ ) -> Result<bool, StoreError>;
+ /// A one-time prekey as (public, private).
+ async fn load_pre_key(&self, id: u32) -> Result<Option<([u8; 32], [u8; 32])>, StoreError>;
+ /// Removes a used one-time prekey.
+ async fn remove_pre_key(&self, id: u32) -> Result<(), StoreError>;
+ /// The serialized session record, or `None` for a new session.
+ async fn load_session(&self, address: &SignalAddress) -> Result<Option<Vec<u8>>, StoreError>;
+ /// Stores a serialized session record.
+ async fn store_session(
+ &self,
+ address: &SignalAddress,
+ record: Vec<u8>,
+ ) -> Result<(), StoreError>;
+ /// Whether there is a session with the address.
+ async fn contains_session(&self, address: &SignalAddress) -> Result<bool, StoreError>;
+ /// The signed prekey as (public, private, signature), if the ID matches.
+ fn load_signed_pre_key(&self, id: u32) -> Option<([u8; 32], [u8; 32], [u8; 64])>;
+ /// Stores a serialized sender key record.
+ async fn store_sender_key(
+ &self,
+ name: &SenderKeyName,
+ record: Vec<u8>,
+ ) -> Result<(), StoreError>;
+ /// The serialized sender key record, or `None` for a new one.
+ async fn load_sender_key(&self, name: &SenderKeyName) -> Result<Option<Vec<u8>>, StoreError>;
+}
+
+/// The Signal protocol operations whatsmeow runs: libsignal's session builder
+/// and cipher, and group session builder and cipher.
+///
+/// Object safe so a client can hold `Arc<dyn SignalProtocol>`, hence
+/// `async_trait`.
+#[async_trait]
+pub trait SignalProtocol: Send + Sync {
+ /// Starts a session from another device's prekey bundle
+ /// (`session.Builder.ProcessBundle`).
+ async fn process_bundle(
+ &self,
+ store: &dyn SignalProtocolStore,
+ address: &SignalAddress,
+ bundle: &PreKeyBundle,
+ ) -> Result<(), SignalError>;
+
+ /// Encrypts a padded plaintext for a device (`session.Cipher.Encrypt`).
+ async fn encrypt(
+ &self,
+ store: &dyn SignalProtocolStore,
+ address: &SignalAddress,
+ plaintext: &[u8],
+ ) -> Result<CiphertextMessage, SignalError>;
+
+ /// Decrypts a `pkmsg`, setting up the session
+ /// (`session.Cipher.DecryptMessage` of a `PreKeySignalMessage`).
+ async fn decrypt_pre_key_message(
+ &self,
+ store: &dyn SignalProtocolStore,
+ address: &SignalAddress,
+ ciphertext: &[u8],
+ ) -> Result<Vec<u8>, SignalError>;
+
+ /// Decrypts a `msg` in an established session
+ /// (`session.Cipher.Decrypt` of a `SignalMessage`).
+ async fn decrypt_message(
+ &self,
+ store: &dyn SignalProtocolStore,
+ address: &SignalAddress,
+ ciphertext: &[u8],
+ ) -> Result<Vec<u8>, SignalError>;
+
+ /// Creates (or reuses) the local sender key for a group and returns the
+ /// serialized distribution message (`groups.SessionBuilder.Create`).
+ async fn create_sender_key_distribution_message(
+ &self,
+ store: &dyn SignalProtocolStore,
+ name: &SenderKeyName,
+ ) -> Result<Vec<u8>, SignalError>;
+
+ /// Stores another device's sender key from its serialized distribution
+ /// message (`groups.SessionBuilder.Process`).
+ async fn process_sender_key_distribution_message(
+ &self,
+ store: &dyn SignalProtocolStore,
+ name: &SenderKeyName,
+ message: &[u8],
+ ) -> Result<(), SignalError>;
+
+ /// Encrypts a padded plaintext for a group (`groups.GroupCipher.Encrypt`).
+ async fn group_encrypt(
+ &self,
+ store: &dyn SignalProtocolStore,
+ name: &SenderKeyName,
+ plaintext: &[u8],
+ ) -> Result<Vec<u8>, SignalError>;
+
+ /// Decrypts a `skmsg` (`groups.GroupCipher.Decrypt`).
+ async fn group_decrypt(
+ &self,
+ store: &dyn SignalProtocolStore,
+ name: &SenderKeyName,
+ ciphertext: &[u8],
+ ) -> Result<Vec<u8>, SignalError>;
+}
diff --git a/crates/whatsmeow/src/socket.rs b/crates/whatsmeow/src/socket.rs
new file mode 100644
index 0000000000..3e9f827f87
--- /dev/null
+++ b/crates/whatsmeow/src/socket.rs
@@ -0,0 +1,25 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+//
+// Ported from whatsmeow socket/ (MPL-2.0, Copyright (c) Tulir Asokan)
+
+//! A subset of the Noise protocol framework on top of websockets, as used by
+//! WhatsApp.
+//!
+//! Go hands frames to callbacks (`Frames` channel plus `OnDisconnect` on the
+//! frame socket, `FrameHandler` plus `DisconnectHandler` on the noise
+//! socket); the port delivers each as one event receiver instead.
+//!
+//! Not ported: `dialopts_js.go` (the WebAssembly build).
+
+mod constants;
+mod dialopts;
+mod framesocket;
+mod noisehandshake;
+mod noisesocket;
+
+pub use constants::*;
+pub use framesocket::{FrameAssembler, FrameEvent, FrameSocket};
+pub use noisehandshake::{NoiseHandshake, NoiseHandshakeError};
+pub use noisesocket::{NoiseEvent, NoiseSocket, generate_iv};
diff --git a/crates/whatsmeow/src/socket/constants.rs b/crates/whatsmeow/src/socket/constants.rs
new file mode 100644
index 0000000000..0b685f3a13
--- /dev/null
+++ b/crates/whatsmeow/src/socket/constants.rs
@@ -0,0 +1,56 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+//
+// Ported from whatsmeow socket/constants.go (MPL-2.0, Copyright (c) Tulir Asokan)
+
+use crate::binary::token;
+
+/// The Origin header for all WhatsApp websocket connections.
+pub const ORIGIN: &str = "https://web.whatsapp.com";
+/// The websocket URL for the multidevice protocol.
+pub const URL: &str = "wss://web.whatsapp.com/ws/chat";
+
+/// The Noise protocol name, padded to 32 bytes so it is used as the initial
+/// hash directly.
+pub const NOISE_START_PATTERN: &[u8] = b"Noise_XX_25519_AESGCM_SHA256\x00\x00\x00\x00";
+
+/// The magic value in the connection header.
+pub const WA_MAGIC_VALUE: u8 = 6;
+
+/// The header sent before the first frame of a connection.
+pub const WA_CONN_HEADER: [u8; 4] = [b'W', b'A', WA_MAGIC_VALUE, token::DICT_VERSION];
+
+/// Frames must be shorter than this.
+pub const FRAME_MAX_SIZE: usize = 1 << 24;
+/// The length of the big-endian frame length prefix.
+pub const FRAME_LENGTH_SIZE: usize = 3;
+
+/// Errors from the frame and noise sockets.
+#[derive(Debug, thiserror::Error)]
+pub enum SocketError {
+ /// The frame is [`FRAME_MAX_SIZE`] bytes or larger.
+ #[error("frame too large (got {length} bytes, max {FRAME_MAX_SIZE} bytes)")]
+ FrameTooLarge {
+ /// The frame length.
+ length: usize,
+ },
+ /// The socket isn't connected.
+ #[error("frame socket is closed")]
+ SocketClosed,
+ /// Dialing the websocket failed. Go wraps the HTTP status code in
+ /// `ErrWithStatusCode` when there was a response.
+ #[error("failed to dial whatsapp web websocket (status {status_code:?}): {source}")]
+ DialFailed {
+ /// The HTTP status of the failed upgrade, if the server answered.
+ status_code: Option<u16>,
+ /// The websocket error.
+ source: Box<tokio_tungstenite::tungstenite::Error>,
+ },
+ /// Writing to the websocket failed.
+ #[error("failed to write to websocket: {0}")]
+ Write(#[source] Box<tokio_tungstenite::tungstenite::Error>),
+ /// Encrypting a frame failed.
+ #[error("failed to encrypt frame: {0}")]
+ Encrypt(#[from] crate::util::gcmutil::GcmError),
+}
diff --git a/crates/whatsmeow/src/socket/dialopts.rs b/crates/whatsmeow/src/socket/dialopts.rs
new file mode 100644
index 0000000000..68f1c4fc2e
--- /dev/null
+++ b/crates/whatsmeow/src/socket/dialopts.rs
@@ -0,0 +1,35 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+//
+// Ported from whatsmeow socket/dialopts.go and the headers in
+// socket/framesocket.go (MPL-2.0, Copyright (c) Tulir Asokan)
+
+use tokio_tungstenite::tungstenite::client::IntoClientRequest;
+use tokio_tungstenite::tungstenite::handshake::client::Request;
+use tokio_tungstenite::tungstenite::http::HeaderValue;
+use tokio_tungstenite::tungstenite::protocol::WebSocketConfig;
+
+use super::constants::{FRAME_MAX_SIZE, ORIGIN, SocketError};
+
+/// The upgrade request for `url` with the headers whatsmeow sends.
+pub(super) fn make_dial_request(url: &str) -> Result<Request, SocketError> {
+ let mut request = url
+ .into_client_request()
+ .map_err(|error| SocketError::DialFailed {
+ status_code: None,
+ source: Box::new(error),
+ })?;
+ let headers = request.headers_mut();
+ headers.insert("Origin", HeaderValue::from_static(ORIGIN));
+ headers.insert("Cache-Control", HeaderValue::from_static("no-cache"));
+ headers.insert("Pragma", HeaderValue::from_static("no-cache"));
+ Ok(request)
+}
+
+/// Go sets the read limit to [`FRAME_MAX_SIZE`].
+pub(super) fn websocket_config() -> WebSocketConfig {
+ WebSocketConfig::default()
+ .max_message_size(Some(FRAME_MAX_SIZE))
+ .max_frame_size(Some(FRAME_MAX_SIZE))
+}
diff --git a/crates/whatsmeow/src/socket/framesocket.rs b/crates/whatsmeow/src/socket/framesocket.rs
new file mode 100644
index 0000000000..7a341297cc
--- /dev/null
+++ b/crates/whatsmeow/src/socket/framesocket.rs
@@ -0,0 +1,332 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+//
+// Ported from whatsmeow socket/framesocket.go (MPL-2.0, Copyright (c) Tulir Asokan)
+
+use std::pin::Pin;
+use std::sync::Arc;
+use std::sync::atomic::{AtomicBool, Ordering};
+
+use futures::stream::{SplitSink, SplitStream};
+use futures::{Sink, SinkExt, Stream, StreamExt};
+use tokio::io::{AsyncRead, AsyncWrite};
+use tokio::sync::{Mutex, mpsc};
+use tokio_tungstenite::WebSocketStream;
+use tokio_tungstenite::tungstenite::protocol::CloseFrame;
+use tokio_tungstenite::tungstenite::protocol::frame::coding::CloseCode;
+use tokio_tungstenite::tungstenite::{self, Message};
+use tokio_util::sync::CancellationToken;
+use tokio_util::task::TaskTracker;
+
+use super::constants::{FRAME_LENGTH_SIZE, FRAME_MAX_SIZE, SocketError, WA_CONN_HEADER};
+use super::dialopts::make_dial_request;
+
+/// How many received frames may wait for the consumer. Go's channel is
+/// unbuffered; one slot keeps the same backpressure on the read pump.
+const FRAME_QUEUE_SIZE: usize = 1;
+
+type BoxedSink = Pin<Box<dyn Sink<Message, Error = tungstenite::Error> + Send>>;
+type BoxedStream = Pin<Box<dyn Stream<Item = Result<Message, tungstenite::Error>> + Send>>;
+
+/// What the read pump delivers: Go's `Frames` channel and `OnDisconnect`
+/// callback as one stream of events.
+#[derive(Debug, PartialEq, Eq)]
+pub enum FrameEvent {
+ /// One complete frame, without its length prefix.
+ Frame(Vec<u8>),
+ /// The socket closed. `remote` is true when the connection dropped or was
+ /// force closed rather than closed with a status code.
+ Disconnected {
+ /// Whether the close wasn't a clean local close.
+ remote: bool,
+ },
+}
+
+struct WriteState {
+ sink: Option<BoxedSink>,
+ /// The connection header, sent once in front of the first frame.
+ header: Option<Vec<u8>>,
+}
+
+struct Shared {
+ write: Mutex<WriteState>,
+ connected: AtomicBool,
+ closed: AtomicBool,
+ cancel: CancellationToken,
+ tasks: TaskTracker,
+ events: mpsc::Sender<FrameEvent>,
+}
+
+/// A websocket that carries WhatsApp's length-prefixed frames.
+///
+/// Go's `FrameSocket` is created unconnected and then dialed; here
+/// [`FrameSocket::connect`] does both and returns the event receiver with the
+/// socket. Cloning gives another handle to the same connection.
+#[derive(Clone)]
+pub struct FrameSocket {
+ shared: Arc<Shared>,
+}
+
+impl FrameSocket {
+ /// Dials the WhatsApp websocket at `url` with the Origin and no-cache
+ /// headers whatsmeow sends.
+ ///
+ /// Go negotiates permessage-deflate; tungstenite doesn't support it, so
+ /// the port connects uncompressed.
+ pub async fn connect(
+ url: &str,
+ ) -> Result<(FrameSocket, mpsc::Receiver<FrameEvent>), SocketError> {
+ tracing::debug!(url, "dialing websocket");
+ let request = make_dial_request(url)?;
+ let (stream, _response) = tokio_tungstenite::connect_async_with_config(
+ request,
+ Some(super::dialopts::websocket_config()),
+ false,
+ )
+ .await
+ .map_err(|error| {
+ let status_code = match &error {
+ tungstenite::Error::Http(response) => Some(response.status().as_u16()),
+ _ => None,
+ };
+ SocketError::DialFailed {
+ status_code,
+ source: Box::new(error),
+ }
+ })?;
+ Ok(Self::from_websocket(stream))
+ }
+
+ /// Runs the frame protocol over an established websocket, such as an
+ /// in-memory one in tests.
+ pub fn from_websocket<Transport>(
+ stream: WebSocketStream<Transport>,
+ ) -> (FrameSocket, mpsc::Receiver<FrameEvent>)
+ where
+ Transport: AsyncRead + AsyncWrite + Unpin + Send + 'static,
+ {
+ let (sink, stream): (SplitSink<_, Message>, SplitStream<_>) = stream.split();
+ let (events, receiver) = mpsc::channel(FRAME_QUEUE_SIZE);
+ let socket = FrameSocket {
+ shared: Arc::new(Shared {
+ write: Mutex::new(WriteState {
+ sink: Some(Box::pin(sink)),
+ header: Some(WA_CONN_HEADER.to_vec()),
+ }),
+ connected: AtomicBool::new(true),
+ closed: AtomicBool::new(false),
+ cancel: CancellationToken::new(),
+ tasks: TaskTracker::new(),
+ events,
+ }),
+ };
+ let pump = socket.clone();
+ socket
+ .shared
+ .tasks
+ .spawn(async move { pump.read_pump(Box::pin(stream)).await });
+ socket.shared.tasks.close();
+ (socket, receiver)
+ }
+
+ /// The connection header that hasn't been sent yet, if any. The noise
+ /// handshake mixes it into its hash before the first frame goes out.
+ pub async fn header(&self) -> Option<Vec<u8>> {
+ self.shared.write.lock().await.header.clone()
+ }
+
+ /// Whether the websocket is open.
+ pub fn is_connected(&self) -> bool {
+ self.shared.connected.load(Ordering::SeqCst)
+ }
+
+ /// Closes the websocket. With a close code, a close frame is sent and the
+ /// disconnect counts as local; without one, the connection is dropped and
+ /// the disconnect counts as remote, like Go's `Close(0)`. Only the first
+ /// close emits [`FrameEvent::Disconnected`].
+ pub async fn close(&self, code: Option<CloseCode>) {
+ if !self.shared.connected.swap(false, Ordering::SeqCst) {
+ return;
+ }
+ self.shared.closed.store(true, Ordering::SeqCst);
+ let sink = self.shared.write.lock().await.sink.take();
+ if let Some(mut sink) = sink {
+ let result = match code {
+ Some(code) => {
+ sink.send(Message::Close(Some(CloseFrame {
+ code,
+ reason: "".into(),
+ })))
+ .await
+ }
+ None => sink.close().await,
+ };
+ if let Err(error) = result {
+ tracing::warn!(error = %error, "error sending close to websocket");
+ }
+ }
+ self.shared.cancel.cancel();
+ // Go calls OnDisconnect in a new goroutine, so a consumer that closes
+ // the socket while handling a frame doesn't deadlock.
+ let events = self.shared.events.clone();
+ let remote = code.is_none();
+ self.shared.tasks.spawn(async move {
+ // The receiver may already be gone, which is fine.
+ let _ = events.send(FrameEvent::Disconnected { remote }).await;
+ });
+ }
+
+ /// Sends one frame, prefixed with its length and, the first time, with
+ /// the connection header.
+ pub async fn send_frame(&self, data: &[u8]) -> Result<(), SocketError> {
+ let mut write = self.shared.write.lock().await;
+ let data_length = data.len();
+ if data_length >= FRAME_MAX_SIZE {
+ return Err(SocketError::FrameTooLarge {
+ length: data_length,
+ });
+ }
+ let header = write.header.take().unwrap_or_default();
+ let Some(sink) = write.sink.as_mut() else {
+ write.header = Some(header).filter(|header| !header.is_empty());
+ return Err(SocketError::SocketClosed);
+ };
+
+ let mut whole_frame = Vec::with_capacity(header.len() + FRAME_LENGTH_SIZE + data_length);
+ whole_frame.extend_from_slice(&header);
+ let [_, high, middle, low] = u32::try_from(data_length)
+ .map_err(|_| SocketError::FrameTooLarge {
+ length: data_length,
+ })?
+ .to_be_bytes();
+ whole_frame.extend_from_slice(&[high, middle, low]);
+ whole_frame.extend_from_slice(data);
+ sink.send(Message::Binary(whole_frame.into()))
+ .await
+ .map_err(|error| SocketError::Write(Box::new(error)))
+ }
+
+ async fn read_pump(&self, mut stream: BoxedStream) {
+ tracing::debug!("frame websocket read pump starting");
+ let mut assembler = FrameAssembler::default();
+ 'pump: loop {
+ let message = tokio::select! {
+ () = self.shared.cancel.cancelled() => break,
+ message = stream.next() => message,
+ };
+ match message {
+ Some(Ok(Message::Binary(data))) => {
+ for frame in assembler.process_data(&data) {
+ if self
+ .shared
+ .events
+ .send(FrameEvent::Frame(frame))
+ .await
+ .is_err()
+ {
+ // Nobody consumes frames anymore.
+ break 'pump;
+ }
+ }
+ }
+ Some(Ok(Message::Close(_))) | None => break,
+ Some(Ok(Message::Ping(_) | Message::Pong(_) | Message::Frame(_))) => {}
+ Some(Ok(Message::Text(_))) => {
+ tracing::warn!("got unexpected websocket text message");
+ }
+ Some(Err(error)) => {
+ if !self.shared.closed.load(Ordering::SeqCst) {
+ tracing::error!(error = %error, "error reading from websocket");
+ }
+ break;
+ }
+ }
+ }
+ tracing::debug!("frame websocket read pump exiting");
+ self.close(None).await;
+ }
+}
+
+/// Reassembles length-prefixed frames from websocket messages, which may
+/// split or batch them (Go keeps this state on `FrameSocket`).
+#[derive(Default)]
+pub struct FrameAssembler {
+ incoming_length: usize,
+ received_length: usize,
+ incoming: Option<Vec<u8>>,
+ partial_header: Option<Vec<u8>>,
+}
+
+impl FrameAssembler {
+ /// Feeds one websocket message in and returns the frames it completed.
+ pub fn process_data(&mut self, message: &[u8]) -> Vec<Vec<u8>> {
+ let mut frames = Vec::new();
+ // A partial header is only ever left at the end of a message, so it
+ // is joined with the start of the next one.
+ let joined;
+ let mut message = match self.partial_header.take() {
+ Some(mut partial_header) => {
+ partial_header.extend_from_slice(message);
+ joined = partial_header;
+ joined.as_slice()
+ }
+ None => message,
+ };
+ while !message.is_empty() {
+ match self.incoming.as_mut() {
+ None => {
+ if message.len() >= FRAME_LENGTH_SIZE {
+ let length = (usize::from(message[0]) << 16)
+ + (usize::from(message[1]) << 8)
+ + usize::from(message[2]);
+ self.incoming_length = length;
+ message = &message[FRAME_LENGTH_SIZE..];
+ self.received_length = message.len();
+ if message.len() >= length {
+ frames.push(message[..length].to_vec());
+ message = &message[length..];
+ self.frame_complete();
+ } else {
+ let mut incoming = vec![0; length];
+ incoming[..message.len()].copy_from_slice(message);
+ self.incoming = Some(incoming);
+ message = &[];
+ }
+ } else {
+ tracing::warn!("received partial header (report if this happens often)");
+ self.partial_header = Some(message.to_vec());
+ message = &[];
+ }
+ }
+ Some(incoming) => {
+ let missing = self.incoming_length - self.received_length;
+ if message.len() >= missing {
+ incoming[self.received_length..].copy_from_slice(&message[..missing]);
+ message = &message[missing..];
+ if let Some(frame) = self.incoming.take() {
+ frames.push(frame);
+ }
+ self.frame_complete();
+ } else {
+ incoming[self.received_length..self.received_length + message.len()]
+ .copy_from_slice(message);
+ self.received_length += message.len();
+ message = &[];
+ }
+ }
+ }
+ }
+ frames
+ }
+
+ fn frame_complete(&mut self) {
+ self.incoming = None;
+ self.partial_header = None;
+ self.incoming_length = 0;
+ self.received_length = 0;
+ }
+}
+
+#[cfg(test)]
+mod test;
diff --git a/crates/whatsmeow/src/socket/framesocket/test.rs b/crates/whatsmeow/src/socket/framesocket/test.rs
new file mode 100644
index 0000000000..ce4815d13b
--- /dev/null
+++ b/crates/whatsmeow/src/socket/framesocket/test.rs
@@ -0,0 +1,138 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+use futures::{SinkExt, StreamExt};
+use tokio_tungstenite::WebSocketStream;
+use tokio_tungstenite::tungstenite::Message;
+use tokio_tungstenite::tungstenite::protocol::Role;
+use tokio_tungstenite::tungstenite::protocol::frame::coding::CloseCode;
+
+use super::*;
+
+#[test]
+fn process_data_splits_batched_frames() {
+ let mut assembler = FrameAssembler::default();
+ let frames = assembler.process_data(&[0, 0, 2, b'h', b'i', 0, 0, 0, 0, 0, 1, b'!']);
+ assert_eq!(frames, vec![b"hi".to_vec(), Vec::new(), b"!".to_vec()]);
+}
+
+#[test]
+fn process_data_joins_frames_split_across_messages() {
+ let mut assembler = FrameAssembler::default();
+ assert_eq!(
+ assembler.process_data(&[0, 0, 5, b'w', b'h']),
+ Vec::<Vec<u8>>::new()
+ );
+ assert_eq!(assembler.process_data(b"a"), Vec::<Vec<u8>>::new());
+ assert_eq!(
+ assembler.process_data(&[b't', b's', 0, 0, 1, b'x']),
+ vec![b"whats".to_vec(), b"x".to_vec()]
+ );
+}
+
+#[test]
+fn process_data_keeps_a_partial_length_prefix() {
+ let mut assembler = FrameAssembler::default();
+ assert_eq!(assembler.process_data(&[0, 0]), Vec::<Vec<u8>>::new());
+ assert_eq!(
+ assembler.process_data(&[3, b'a', b'b']),
+ Vec::<Vec<u8>>::new()
+ );
+ assert_eq!(assembler.process_data(b"c"), vec![b"abc".to_vec()]);
+}
+
+async fn connected_pair() -> (
+ FrameSocket,
+ mpsc::Receiver<FrameEvent>,
+ WebSocketStream<tokio::io::DuplexStream>,
+) {
+ let (client, server) = tokio::io::duplex(1 << 16);
+ let client = WebSocketStream::from_raw_socket(client, Role::Client, None).await;
+ let server = WebSocketStream::from_raw_socket(server, Role::Server, None).await;
+ let (socket, events) = FrameSocket::from_websocket(client);
+ (socket, events, server)
+}
+
+#[tokio::test]
+async fn send_frame_prefixes_the_header_once_and_the_length_always() {
+ let (socket, _events, mut server) = connected_pair().await;
+ assert_eq!(socket.header().await, Some(b"WA\x06\x03".to_vec()));
+
+ socket.send_frame(b"first").await.unwrap();
+ socket.send_frame(b"second").await.unwrap();
+
+ assert_eq!(
+ server.next().await.unwrap().unwrap(),
+ Message::Binary(b"WA\x06\x03\x00\x00\x05first".to_vec().into())
+ );
+ assert_eq!(
+ server.next().await.unwrap().unwrap(),
+ Message::Binary(b"\x00\x00\x06second".to_vec().into())
+ );
+ assert_eq!(socket.header().await, None);
+}
+
+#[tokio::test]
+async fn received_messages_become_frame_events() {
+ let (_socket, mut events, mut server) = connected_pair().await;
+ server
+ .send(Message::Binary(b"\x00\x00\x03abc\x00\x00".to_vec().into()))
+ .await
+ .unwrap();
+ server
+ .send(Message::Binary(b"\x02de".to_vec().into()))
+ .await
+ .unwrap();
+
+ assert_eq!(
+ events.recv().await,
+ Some(FrameEvent::Frame(b"abc".to_vec()))
+ );
+ assert_eq!(events.recv().await, Some(FrameEvent::Frame(b"de".to_vec())));
+}
+
+#[tokio::test]
+async fn remote_close_is_a_remote_disconnect() {
+ let (socket, mut events, mut server) = connected_pair().await;
+ server.close(None).await.unwrap();
+
+ assert_eq!(
+ events.recv().await,
+ Some(FrameEvent::Disconnected { remote: true })
+ );
+ assert!(!socket.is_connected());
+ assert!(matches!(
+ socket.send_frame(b"late").await,
+ Err(SocketError::SocketClosed)
+ ));
+}
+
+#[tokio::test]
+async fn local_close_with_a_code_is_a_local_disconnect_once() {
+ let (socket, mut events, mut server) = connected_pair().await;
+ socket.close(Some(CloseCode::Normal)).await;
+ socket.close(Some(CloseCode::Normal)).await;
+
+ assert!(matches!(
+ server.next().await,
+ Some(Ok(Message::Close(Some(frame)))) if frame.code == CloseCode::Normal
+ ));
+ assert_eq!(
+ events.recv().await,
+ Some(FrameEvent::Disconnected { remote: false })
+ );
+ drop(socket);
+ assert_eq!(events.recv().await, None);
+}
+
+#[tokio::test]
+async fn send_frame_rejects_oversized_frames() {
+ let (socket, _events, _server) = connected_pair().await;
+ assert!(matches!(
+ socket.send_frame(&vec![0; FRAME_MAX_SIZE]).await,
+ Err(SocketError::FrameTooLarge {
+ length: FRAME_MAX_SIZE
+ })
+ ));
+}
diff --git a/crates/whatsmeow/src/socket/noisehandshake.rs b/crates/whatsmeow/src/socket/noisehandshake.rs
new file mode 100644
index 0000000000..2e13733fa3
--- /dev/null
+++ b/crates/whatsmeow/src/socket/noisehandshake.rs
@@ -0,0 +1,156 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+//
+// Ported from whatsmeow socket/noisehandshake.go (MPL-2.0, Copyright (c) Tulir Asokan)
+
+use aes_gcm::Aes256Gcm;
+use hkdf::Hkdf;
+use sha2::{Digest, Sha256};
+use tokio::sync::mpsc;
+
+use super::framesocket::{FrameEvent, FrameSocket};
+use super::noisesocket::{NoiseEvent, NoiseSocket, generate_iv, new_noise_socket};
+use crate::util::gcmutil::{self, GcmError};
+
+/// Errors while mixing keys during the handshake.
+#[derive(Debug, thiserror::Error, PartialEq, Eq)]
+pub enum NoiseHandshakeError {
+ /// The peer's public key is a low-order point, so the shared secret is 0.
+ #[error("failed to do x25519 scalar multiplication: low order point")]
+ LowOrderPoint,
+ /// Creating a cipher or encrypting failed.
+ #[error(transparent)]
+ Cipher(#[from] GcmError),
+}
+
+/// The handshake state of the `Noise_XX_25519_AESGCM_SHA256` protocol.
+pub struct NoiseHandshake {
+ hash: [u8; 32],
+ salt: [u8; 32],
+ key: Aes256Gcm,
+ counter: u32,
+}
+
+fn sha256_slice(data: &[&[u8]]) -> [u8; 32] {
+ let mut hasher = Sha256::new();
+ for part in data {
+ hasher.update(part);
+ }
+ hasher.finalize().into()
+}
+
+impl NoiseHandshake {
+ /// Starts a handshake: Go's `NewNoiseHandshake` followed by `Start`.
+ ///
+ /// A 32-byte pattern is the initial hash itself; anything else is hashed.
+ /// The connection header is then mixed into the hash.
+ pub fn start(pattern: &[u8], header: &[u8]) -> Result<Self, NoiseHandshakeError> {
+ let hash = match <[u8; 32]>::try_from(pattern) {
+ Ok(hash) => hash,
+ Err(_) => sha256_slice(&[pattern]),
+ };
+ let mut handshake = Self {
+ hash,
+ salt: hash,
+ key: gcmutil::prepare(&hash)?,
+ counter: 0,
+ };
+ handshake.authenticate(header);
+ Ok(handshake)
+ }
+
+ /// Mixes data into the handshake hash.
+ pub fn authenticate(&mut self, data: &[u8]) {
+ self.hash = sha256_slice(&[&self.hash, data]);
+ }
+
+ fn post_increment_counter(&mut self) -> u32 {
+ let count = self.counter;
+ self.counter = self.counter.wrapping_add(1);
+ count
+ }
+
+ /// Encrypts a handshake payload with the hash as associated data, and
+ /// mixes the ciphertext into the hash.
+ pub fn encrypt(&mut self, plaintext: &[u8]) -> Result<Vec<u8>, NoiseHandshakeError> {
+ let iv = generate_iv(self.post_increment_counter());
+ let ciphertext = gcmutil::seal(&self.key, &iv, plaintext, &self.hash)?;
+ self.authenticate(&ciphertext);
+ Ok(ciphertext)
+ }
+
+ /// Decrypts a handshake payload, mixing the ciphertext into the hash when
+ /// it authenticates.
+ pub fn decrypt(&mut self, ciphertext: &[u8]) -> Result<Vec<u8>, GcmError> {
+ let iv = generate_iv(self.post_increment_counter());
+ let plaintext = gcmutil::open(&self.key, &iv, ciphertext, &self.hash)?;
+ self.authenticate(ciphertext);
+ Ok(plaintext)
+ }
+
+ /// Derives the transport keys and starts the encrypted socket over the
+ /// frame socket's events. The returned receiver yields decrypted frames
+ /// and the disconnect, which Go delivers to a frame handler and a
+ /// disconnect handler.
+ pub fn finish(
+ self,
+ frame_socket: FrameSocket,
+ frames: mpsc::Receiver<FrameEvent>,
+ ) -> Result<(NoiseSocket, mpsc::Receiver<NoiseEvent>), NoiseHandshakeError> {
+ let (write, read) = extract_and_expand(&self.salt, &[]);
+ let write_key = gcmutil::prepare(&write)?;
+ let read_key = gcmutil::prepare(&read)?;
+ Ok(new_noise_socket(frame_socket, frames, write_key, read_key))
+ }
+
+ /// Mixes the X25519 shared secret of a private and a public key into the
+ /// cipher key.
+ pub fn mix_shared_secret_into_key(
+ &mut self,
+ private: [u8; 32],
+ public: [u8; 32],
+ ) -> Result<(), NoiseHandshakeError> {
+ let secret = x25519_dalek::x25519(private, public);
+ // Go's curve25519.X25519 rejects low-order points this way.
+ if secret == [0; 32] {
+ return Err(NoiseHandshakeError::LowOrderPoint);
+ }
+ self.mix_into_key(&secret)
+ }
+
+ /// Derives a new salt and cipher key from the current salt and `data`,
+ /// resetting the nonce counter.
+ pub fn mix_into_key(&mut self, data: &[u8]) -> Result<(), NoiseHandshakeError> {
+ self.counter = 0;
+ let (write, read) = extract_and_expand(&self.salt, data);
+ self.salt = write;
+ self.key = gcmutil::prepare(&read)?;
+ Ok(())
+ }
+}
+
+impl NoiseHandshake {
+ /// The (initiator write, initiator read) transport keys, for tests that
+ /// play the responder.
+ #[cfg(any(test, feature = "testing"))]
+ pub fn transport_keys(&self) -> ([u8; 32], [u8; 32]) {
+ extract_and_expand(&self.salt, &[])
+ }
+}
+
+/// HKDF-SHA256 of `data` with `salt`, split into two 32-byte keys.
+fn extract_and_expand(salt: &[u8], data: &[u8]) -> ([u8; 32], [u8; 32]) {
+ let mut output = [0; 64];
+ Hkdf::<Sha256>::new(Some(salt), data)
+ .expand(&[], &mut output)
+ .expect("HKDF-SHA256 can expand 64 bytes");
+ let mut write = [0; 32];
+ let mut read = [0; 32];
+ write.copy_from_slice(&output[..32]);
+ read.copy_from_slice(&output[32..]);
+ (write, read)
+}
+
+#[cfg(test)]
+mod test;
diff --git a/crates/whatsmeow/src/socket/noisehandshake/test.rs b/crates/whatsmeow/src/socket/noisehandshake/test.rs
new file mode 100644
index 0000000000..3437f2b33d
--- /dev/null
+++ b/crates/whatsmeow/src/socket/noisehandshake/test.rs
@@ -0,0 +1,131 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+//! The ciphertexts below were produced by whatsmeow's Go `NoiseHandshake` at
+//! the pinned revision, with the same fixed keys.
+
+use super::*;
+use crate::socket::{NOISE_START_PATTERN, WA_CONN_HEADER};
+use crate::util::keys::new_key_pair_from_private_key;
+
+fn fixed_private_key(start: u8) -> [u8; 32] {
+ std::array::from_fn(|index| start + u8::try_from(index).unwrap())
+}
+
+#[test]
+fn handshake_operations_match_go() {
+ let client = new_key_pair_from_private_key(fixed_private_key(0x10));
+ let server = new_key_pair_from_private_key(fixed_private_key(0x50));
+ let noise = new_key_pair_from_private_key(fixed_private_key(0x90));
+ assert_eq!(
+ hex::encode(server.public),
+ "392d174a38b3b1beafaf1fe824870841c5fa531bc6eafdb6402c124664488c1c"
+ );
+
+ let mut handshake = NoiseHandshake::start(NOISE_START_PATTERN, &WA_CONN_HEADER).unwrap();
+ handshake.authenticate(&client.public);
+ handshake.authenticate(&server.public);
+ handshake
+ .mix_shared_secret_into_key(client.private, server.public)
+ .unwrap();
+ assert_eq!(
+ hex::encode(handshake.encrypt(b"first").unwrap()),
+ "dfe67f8ad4a53540f16673a4667d76cc7a53bcacef"
+ );
+ assert_eq!(
+ hex::encode(handshake.encrypt(b"second").unwrap()),
+ "93e26bf20321b4d5f5c6cc314fca95950325fee98ea6"
+ );
+ handshake
+ .mix_shared_secret_into_key(noise.private, server.public)
+ .unwrap();
+ assert_eq!(
+ hex::encode(handshake.encrypt(b"third").unwrap()),
+ "214324a0b83628dcb1ac495714baf780f574140b10"
+ );
+}
+
+#[test]
+fn mixing_rejects_low_order_points() {
+ let client = new_key_pair_from_private_key(fixed_private_key(0x10));
+ let mut handshake = NoiseHandshake::start(NOISE_START_PATTERN, &WA_CONN_HEADER).unwrap();
+ assert_eq!(
+ handshake.mix_shared_secret_into_key(client.private, [0; 32]),
+ Err(NoiseHandshakeError::LowOrderPoint)
+ );
+}
+
+#[test]
+fn both_sides_of_an_xx_handshake_agree() {
+ let client_ephemeral = new_key_pair_from_private_key(fixed_private_key(0x10));
+ let client_static = new_key_pair_from_private_key(fixed_private_key(0x90));
+ let server_ephemeral = new_key_pair_from_private_key(fixed_private_key(0x50));
+ let server_static = new_key_pair_from_private_key(fixed_private_key(0x70));
+
+ let mut client = NoiseHandshake::start(NOISE_START_PATTERN, &WA_CONN_HEADER).unwrap();
+ let mut server = NoiseHandshake::start(NOISE_START_PATTERN, &WA_CONN_HEADER).unwrap();
+
+ // -> e
+ client.authenticate(&client_ephemeral.public);
+ server.authenticate(&client_ephemeral.public);
+ // <- e, ee, s, es
+ server.authenticate(&server_ephemeral.public);
+ server
+ .mix_shared_secret_into_key(server_ephemeral.private, client_ephemeral.public)
+ .unwrap();
+ let static_ciphertext = server.encrypt(&server_static.public).unwrap();
+ server
+ .mix_shared_secret_into_key(server_static.private, client_ephemeral.public)
+ .unwrap();
+ let payload_ciphertext = server.encrypt(b"certificate").unwrap();
+
+ client.authenticate(&server_ephemeral.public);
+ client
+ .mix_shared_secret_into_key(client_ephemeral.private, server_ephemeral.public)
+ .unwrap();
+ assert_eq!(
+ client.decrypt(&static_ciphertext).unwrap(),
+ server_static.public
+ );
+ client
+ .mix_shared_secret_into_key(client_ephemeral.private, server_static.public)
+ .unwrap();
+ assert_eq!(client.decrypt(&payload_ciphertext).unwrap(), b"certificate");
+
+ // -> s, se
+ let client_static_ciphertext = client.encrypt(&client_static.public).unwrap();
+ client
+ .mix_shared_secret_into_key(client_static.private, server_ephemeral.public)
+ .unwrap();
+ let client_payload_ciphertext = client.encrypt(b"client payload").unwrap();
+
+ assert_eq!(
+ server.decrypt(&client_static_ciphertext).unwrap(),
+ client_static.public
+ );
+ server
+ .mix_shared_secret_into_key(server_ephemeral.private, client_static.public)
+ .unwrap();
+ assert_eq!(
+ server.decrypt(&client_payload_ciphertext).unwrap(),
+ b"client payload"
+ );
+
+ assert_eq!(client.hash, server.hash);
+ assert_eq!(
+ extract_and_expand(&client.salt, &[]),
+ extract_and_expand(&server.salt, &[])
+ );
+}
+
+#[test]
+fn tampered_ciphertext_doesnt_change_the_hash() {
+ let mut sender = NoiseHandshake::start(NOISE_START_PATTERN, &WA_CONN_HEADER).unwrap();
+ let mut receiver = NoiseHandshake::start(NOISE_START_PATTERN, &WA_CONN_HEADER).unwrap();
+ let mut ciphertext = sender.encrypt(b"payload").unwrap();
+ ciphertext[0] ^= 1;
+ let hash_before = receiver.hash;
+ assert_eq!(receiver.decrypt(&ciphertext), Err(GcmError::Authentication));
+ assert_eq!(receiver.hash, hash_before);
+}
diff --git a/crates/whatsmeow/src/socket/noisesocket.rs b/crates/whatsmeow/src/socket/noisesocket.rs
new file mode 100644
index 0000000000..6469f28fd6
--- /dev/null
+++ b/crates/whatsmeow/src/socket/noisesocket.rs
@@ -0,0 +1,177 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+//
+// Ported from whatsmeow socket/noisesocket.go (MPL-2.0, Copyright (c) Tulir Asokan)
+
+use std::sync::Arc;
+use std::sync::atomic::{AtomicBool, Ordering};
+
+use aes_gcm::Aes256Gcm;
+use tokio::sync::{Mutex, mpsc};
+use tokio_tungstenite::tungstenite::protocol::frame::coding::CloseCode;
+use tokio_util::sync::CancellationToken;
+use tokio_util::task::TaskTracker;
+
+use super::constants::SocketError;
+use super::framesocket::{FrameEvent, FrameSocket};
+use crate::util::gcmutil;
+
+/// How many decrypted frames may wait for the consumer.
+const NOISE_EVENT_QUEUE_SIZE: usize = 1;
+
+/// What an established noise socket delivers: Go's `FrameHandler` and
+/// `DisconnectHandler` callbacks as one stream of events.
+#[derive(Debug, PartialEq, Eq)]
+pub enum NoiseEvent {
+ /// One decrypted frame.
+ Frame(Vec<u8>),
+ /// The underlying socket closed.
+ Disconnected {
+ /// Whether the close wasn't a clean local close.
+ remote: bool,
+ },
+}
+
+struct WriteState {
+ key: Aes256Gcm,
+ counter: u32,
+}
+
+/// The transport after the noise handshake: every frame is encrypted with
+/// AES-256-GCM, with a per-direction counter as the nonce.
+pub struct NoiseSocket {
+ frame_socket: FrameSocket,
+ write: Mutex<WriteState>,
+ destroyed: AtomicBool,
+ allow_on_disconnect: Arc<AtomicBool>,
+ stop_consumer: CancellationToken,
+ tasks: TaskTracker,
+}
+
+/// The 12-byte nonce for a counter: zeros followed by the big-endian counter.
+pub fn generate_iv(count: u32) -> [u8; 12] {
+ let mut iv = [0; 12];
+ iv[8..].copy_from_slice(&count.to_be_bytes());
+ iv
+}
+
+pub(super) fn new_noise_socket(
+ frame_socket: FrameSocket,
+ frames: mpsc::Receiver<FrameEvent>,
+ write_key: Aes256Gcm,
+ read_key: Aes256Gcm,
+) -> (NoiseSocket, mpsc::Receiver<NoiseEvent>) {
+ let (events, receiver) = mpsc::channel(NOISE_EVENT_QUEUE_SIZE);
+ let socket = NoiseSocket {
+ frame_socket,
+ write: Mutex::new(WriteState {
+ key: write_key,
+ counter: 0,
+ }),
+ destroyed: AtomicBool::new(false),
+ allow_on_disconnect: Arc::new(AtomicBool::new(true)),
+ stop_consumer: CancellationToken::new(),
+ tasks: TaskTracker::new(),
+ };
+ socket.tasks.spawn(consume_frames(
+ frames,
+ events,
+ read_key,
+ socket.stop_consumer.clone(),
+ Arc::clone(&socket.allow_on_disconnect),
+ ));
+ socket.tasks.close();
+ (socket, receiver)
+}
+
+/// Decrypts frames in order until stopped. A frame that doesn't decrypt is
+/// logged and skipped; the read counter still advances, as in Go.
+async fn consume_frames(
+ mut frames: mpsc::Receiver<FrameEvent>,
+ events: mpsc::Sender<NoiseEvent>,
+ read_key: Aes256Gcm,
+ stop: CancellationToken,
+ allow_on_disconnect: Arc<AtomicBool>,
+) {
+ let mut read_counter: u32 = 0;
+ loop {
+ let event = tokio::select! {
+ () = stop.cancelled() => break,
+ event = frames.recv() => event,
+ };
+ match event {
+ Some(FrameEvent::Frame(ciphertext)) => {
+ let plaintext =
+ gcmutil::open(&read_key, &generate_iv(read_counter), &ciphertext, &[]);
+ read_counter = read_counter.wrapping_add(1);
+ match plaintext {
+ Ok(plaintext) => {
+ if events.send(NoiseEvent::Frame(plaintext)).await.is_err() {
+ return;
+ }
+ }
+ Err(error) => tracing::warn!(error = %error, "failed to decrypt frame"),
+ }
+ }
+ Some(FrameEvent::Disconnected { remote }) => {
+ // The receiver may already be gone, which is fine.
+ let _ = events.send(NoiseEvent::Disconnected { remote }).await;
+ return;
+ }
+ None => return,
+ }
+ }
+ // Stopped: Go still runs the disconnect handler when it is allowed to.
+ if !allow_on_disconnect.load(Ordering::SeqCst) {
+ return;
+ }
+ while let Some(event) = frames.recv().await {
+ if let FrameEvent::Disconnected { remote } = event {
+ let _ = events.send(NoiseEvent::Disconnected { remote }).await;
+ return;
+ }
+ }
+}
+
+impl NoiseSocket {
+ /// Stops delivering frames. With `disconnect`, the websocket is closed
+ /// normally; with `allow_on_disconnect`, the disconnect is still
+ /// delivered. Only the first call has an effect.
+ pub async fn stop(&self, disconnect: bool, allow_on_disconnect: bool) {
+ if self
+ .destroyed
+ .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
+ .is_err()
+ {
+ return;
+ }
+ self.allow_on_disconnect
+ .store(allow_on_disconnect, Ordering::SeqCst);
+ self.stop_consumer.cancel();
+ if disconnect {
+ self.frame_socket.close(Some(CloseCode::Normal)).await;
+ }
+ }
+
+ /// Encrypts and sends one frame.
+ ///
+ /// The write lock is held until the frame is handed to the websocket, so
+ /// frames go out in counter order. Dropping the future mid-send leaves the
+ /// counter ahead of the server, which breaks the connection, as a
+ /// cancelled context does in Go.
+ pub async fn send_frame(&self, plaintext: &[u8]) -> Result<(), SocketError> {
+ let mut write = self.write.lock().await;
+ let ciphertext = gcmutil::seal(&write.key, &generate_iv(write.counter), plaintext, &[])?;
+ write.counter = write.counter.wrapping_add(1);
+ self.frame_socket.send_frame(&ciphertext).await
+ }
+
+ /// Whether the underlying websocket is open.
+ pub fn is_connected(&self) -> bool {
+ self.frame_socket.is_connected()
+ }
+}
+
+#[cfg(test)]
+mod test;
diff --git a/crates/whatsmeow/src/socket/noisesocket/test.rs b/crates/whatsmeow/src/socket/noisesocket/test.rs
new file mode 100644
index 0000000000..468c07b0e7
--- /dev/null
+++ b/crates/whatsmeow/src/socket/noisesocket/test.rs
@@ -0,0 +1,117 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+use futures::{SinkExt, StreamExt};
+use tokio_tungstenite::WebSocketStream;
+use tokio_tungstenite::tungstenite::Message;
+use tokio_tungstenite::tungstenite::protocol::Role;
+
+use super::*;
+use crate::util::gcmutil::prepare;
+
+const CLIENT_WRITE_KEY: [u8; 32] = [1; 32];
+const CLIENT_READ_KEY: [u8; 32] = [2; 32];
+
+async fn connected_noise_socket() -> (
+ NoiseSocket,
+ mpsc::Receiver<NoiseEvent>,
+ WebSocketStream<tokio::io::DuplexStream>,
+) {
+ let (client, server) = tokio::io::duplex(1 << 16);
+ let client = WebSocketStream::from_raw_socket(client, Role::Client, None).await;
+ let server = WebSocketStream::from_raw_socket(server, Role::Server, None).await;
+ let (frame_socket, frames) = FrameSocket::from_websocket(client);
+ let (socket, events) = new_noise_socket(
+ frame_socket,
+ frames,
+ prepare(&CLIENT_WRITE_KEY).unwrap(),
+ prepare(&CLIENT_READ_KEY).unwrap(),
+ );
+ (socket, events, server)
+}
+
+#[test]
+fn generate_iv_puts_the_counter_at_the_end() {
+ assert_eq!(
+ generate_iv(0x0102_0304),
+ [0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4]
+ );
+}
+
+#[tokio::test]
+async fn send_frame_encrypts_with_an_incrementing_counter() {
+ let (socket, _events, mut server) = connected_noise_socket().await;
+ socket.send_frame(b"one").await.unwrap();
+ socket.send_frame(b"two").await.unwrap();
+
+ let key = prepare(&CLIENT_WRITE_KEY).unwrap();
+ let Some(Ok(Message::Binary(first))) = server.next().await else {
+ panic!("expected a binary message");
+ };
+ assert_eq!(first[..4], *b"WA\x06\x03");
+ assert_eq!(
+ gcmutil::open(&key, &generate_iv(0), &first[7..], &[]).unwrap(),
+ b"one"
+ );
+ let Some(Ok(Message::Binary(second))) = server.next().await else {
+ panic!("expected a binary message");
+ };
+ assert_eq!(
+ gcmutil::open(&key, &generate_iv(1), &second[3..], &[]).unwrap(),
+ b"two"
+ );
+}
+
+#[tokio::test]
+async fn received_frames_are_decrypted_and_bad_ones_skipped() {
+ let (_socket, mut events, mut server) = connected_noise_socket().await;
+ let key = prepare(&CLIENT_READ_KEY).unwrap();
+ let first = gcmutil::seal(&key, &generate_iv(0), b"hello", &[]).unwrap();
+ // Encrypted with the wrong counter, so it fails and is skipped.
+ let bad = gcmutil::seal(&key, &generate_iv(0), b"bad", &[]).unwrap();
+ let third = gcmutil::seal(&key, &generate_iv(2), b"world", &[]).unwrap();
+ for ciphertext in [first, bad, third] {
+ let mut message = vec![0, 0, u8::try_from(ciphertext.len()).unwrap()];
+ message.extend_from_slice(&ciphertext);
+ server.send(Message::Binary(message.into())).await.unwrap();
+ }
+
+ assert_eq!(
+ events.recv().await,
+ Some(NoiseEvent::Frame(b"hello".to_vec()))
+ );
+ assert_eq!(
+ events.recv().await,
+ Some(NoiseEvent::Frame(b"world".to_vec()))
+ );
+}
+
+#[tokio::test]
+async fn stop_with_disconnect_still_reports_the_disconnect_when_allowed() {
+ let (socket, mut events, _server) = connected_noise_socket().await;
+ socket.stop(true, true).await;
+ assert_eq!(
+ events.recv().await,
+ Some(NoiseEvent::Disconnected { remote: false })
+ );
+ assert!(!socket.is_connected());
+}
+
+#[tokio::test]
+async fn stop_without_on_disconnect_reports_nothing() {
+ let (socket, mut events, _server) = connected_noise_socket().await;
+ socket.stop(true, false).await;
+ drop(socket);
+ assert_eq!(events.recv().await, None);
+}
+
+#[tokio::test]
+async fn remote_disconnect_is_forwarded() {
+ let (_socket, mut events, mut server) = connected_noise_socket().await;
+ server.close(None).await.unwrap();
+ assert_eq!(
+ events.recv().await,
+ Some(NoiseEvent::Disconnected { remote: true })
+ );
+}
diff --git a/crates/whatsmeow/src/store.rs b/crates/whatsmeow/src/store.rs
new file mode 100644
index 0000000000..5e8e53deab
--- /dev/null
+++ b/crates/whatsmeow/src/store.rs
@@ -0,0 +1,28 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+//
+// Ported from whatsmeow store/ (MPL-2.0, Copyright (c) Tulir Asokan)
+
+//! Interfaces for storing data needed for WhatsApp multidevice.
+//!
+//! Not ported: `store/sqlstore`. [`MemoryStore`] is an in-memory
+//! implementation for tests, not a port.
+
+mod clientpayload;
+mod memorystore;
+mod noop;
+mod sessioncache;
+mod signal;
+#[expect(
+ clippy::module_inception,
+ reason = "mirrors whatsmeow's store/store.go"
+)]
+mod store;
+
+pub use clientpayload::*;
+pub use memorystore::MemoryStore;
+pub use noop::{NoopError, NoopStore};
+pub use sessioncache::{SessionCache, SessionCacheEntry};
+pub use signal::DeviceSignalStore;
+pub use store::*;
diff --git a/crates/whatsmeow/src/store/clientpayload.rs b/crates/whatsmeow/src/store/clientpayload.rs
new file mode 100644
index 0000000000..cf8f3b7beb
--- /dev/null
+++ b/crates/whatsmeow/src/store/clientpayload.rs
@@ -0,0 +1,274 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+//
+// Ported from whatsmeow store/clientpayload.go (MPL-2.0, Copyright (c) Tulir Asokan)
+//
+// Go keeps `BaseClientPayload` and `DeviceProps` as mutable package
+// variables that `SetWAVersion` and `SetOSInfo` edit. The port keeps the two
+// settings in locks and builds both messages from them on demand.
+
+use std::fmt;
+use std::num::ParseIntError;
+use std::sync::{PoisonError, RwLock};
+
+use md5::{Digest, Md5};
+use prost::Message;
+
+use super::store::Device;
+use crate::proto::wa_companion_reg::{DeviceProps, device_props};
+use crate::proto::wa_wa6::ClientPayload;
+use crate::proto::wa_wa6::client_payload::{
+ ConnectReason, ConnectType, DevicePairingRegistrationData, UserAgent, WebInfo, user_agent,
+ web_info,
+};
+use crate::signal::DJB_TYPE;
+
+/// A WhatsApp web version number.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
+pub struct WaVersionContainer(pub [u32; 3]);
+
+/// Why [`parse_version`] failed. The messages match whatsmeow's.
+#[derive(Debug, thiserror::Error, PartialEq, Eq)]
+pub enum ParseVersionError {
+ /// Not three parts.
+ #[error("'{0}' doesn't contain three dot-separated parts")]
+ WrongPartCount(String),
+ /// A part isn't a number.
+ #[error("{position} part of '{version}' is not a number: {source}")]
+ NotANumber {
+ /// "first", "second" or "third".
+ position: &'static str,
+ /// The whole version string.
+ version: String,
+ /// The parse failure.
+ source: ParseIntError,
+ },
+}
+
+/// Parses a version string (three dot-separated numbers).
+pub fn parse_version(version: &str) -> Result<WaVersionContainer, ParseVersionError> {
+ let parts: Vec<&str> = version.split('.').collect();
+ let [first, second, third] = parts.as_slice() else {
+ return Err(ParseVersionError::WrongPartCount(version.to_owned()));
+ };
+ let parse = |part: &str, position| {
+ part.parse::<u32>()
+ .map_err(|source| ParseVersionError::NotANumber {
+ position,
+ version: version.to_owned(),
+ source,
+ })
+ };
+ Ok(WaVersionContainer([
+ parse(first, "first")?,
+ parse(second, "second")?,
+ parse(third, "third")?,
+ ]))
+}
+
+impl WaVersionContainer {
+ /// Whether this version is older than `other`.
+ pub fn less_than(&self, other: &WaVersionContainer) -> bool {
+ self.0 < other.0
+ }
+
+ /// Whether the version is all zeros.
+ pub fn is_zero(&self) -> bool {
+ self.0 == [0, 0, 0]
+ }
+
+ /// The MD5 hash of the dot-separated version.
+ pub fn hash(&self) -> [u8; 16] {
+ Md5::digest(self.to_string().as_bytes()).into()
+ }
+
+ /// The version as the client payload's app version.
+ pub fn proto_app_version(&self) -> user_agent::AppVersion {
+ user_agent::AppVersion {
+ primary: Some(self.0[0]),
+ secondary: Some(self.0[1]),
+ tertiary: Some(self.0[2]),
+ ..Default::default()
+ }
+ }
+}
+
+/// The version as a dot-separated string.
+impl fmt::Display for WaVersionContainer {
+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
+ let [primary, secondary, tertiary] = self.0;
+ write!(formatter, "{primary}.{secondary}.{tertiary}")
+ }
+}
+
+/// The WhatsApp web client version.
+static WA_VERSION: RwLock<WaVersionContainer> =
+ RwLock::new(WaVersionContainer([2, 3000, 1050728964]));
+
+/// The OS name and version set with [`set_os_info`].
+static OS_INFO: RwLock<Option<(String, [u32; 3])>> = RwLock::new(None);
+
+/// The current WhatsApp web client version.
+pub fn get_wa_version() -> WaVersionContainer {
+ *WA_VERSION.read().unwrap_or_else(PoisonError::into_inner)
+}
+
+/// Sets the WhatsApp web client version. A zero version is ignored.
+///
+/// In general, keep the library up to date instead, as newer versions may
+/// need code changes too (like protobuf schema changes).
+pub fn set_wa_version(version: WaVersionContainer) {
+ if version.is_zero() {
+ return;
+ }
+ *WA_VERSION.write().unwrap_or_else(PoisonError::into_inner) = version;
+}
+
+/// Sets the OS name and version the device reports while pairing and in its
+/// user agent.
+pub fn set_os_info(name: &str, version: [u32; 3]) {
+ *OS_INFO.write().unwrap_or_else(PoisonError::into_inner) = Some((name.to_owned(), version));
+}
+
+fn os_info() -> Option<(String, [u32; 3])> {
+ OS_INFO
+ .read()
+ .unwrap_or_else(PoisonError::into_inner)
+ .clone()
+}
+
+/// The client payload fields shared by registration and login (Go's
+/// `BaseClientPayload`).
+pub fn base_client_payload() -> ClientPayload {
+ build_base_client_payload(get_wa_version(), os_info())
+}
+
+fn build_base_client_payload(
+ version: WaVersionContainer,
+ os_info: Option<(String, [u32; 3])>,
+) -> ClientPayload {
+ let os_version = os_info.map_or_else(
+ || "0.1".to_owned(),
+ |(_, [primary, secondary, tertiary])| format!("{primary}.{secondary}.{tertiary}"),
+ );
+ ClientPayload {
+ user_agent: Some(UserAgent {
+ platform: Some(user_agent::Platform::Web.into()),
+ release_channel: Some(user_agent::ReleaseChannel::Release.into()),
+ app_version: Some(version.proto_app_version()),
+ mcc: Some("000".to_owned()),
+ mnc: Some("000".to_owned()),
+ os_version: Some(os_version.clone()),
+ manufacturer: Some(String::new()),
+ device: Some("Desktop".to_owned()),
+ os_build_number: Some(os_version),
+ locale_language_iso6391: Some("en".to_owned()),
+ locale_country_iso31661_alpha2: Some("US".to_owned()),
+ ..Default::default()
+ }),
+ web_info: Some(WebInfo {
+ web_sub_platform: Some(web_info::WebSubPlatform::WebBrowser.into()),
+ ..Default::default()
+ }),
+ connect_type: Some(ConnectType::WifiUnknown.into()),
+ connect_reason: Some(ConnectReason::UserActivated.into()),
+ ..Default::default()
+ }
+}
+
+/// The device properties sent while pairing (Go's `DeviceProps`).
+pub fn device_props() -> DeviceProps {
+ build_device_props(os_info())
+}
+
+fn build_device_props(os_info: Option<(String, [u32; 3])>) -> DeviceProps {
+ let (os, [primary, secondary, tertiary]) =
+ os_info.unwrap_or_else(|| ("whatsmeow".to_owned(), [0, 1, 0]));
+ DeviceProps {
+ os: Some(os),
+ version: Some(device_props::AppVersion {
+ primary: Some(primary),
+ secondary: Some(secondary),
+ tertiary: Some(tertiary),
+ ..Default::default()
+ }),
+ history_sync_config: Some(device_props::HistorySyncConfig {
+ storage_quota_mb: Some(10240),
+ inline_initial_payload_in_e2_ee_msg: Some(true),
+ support_call_log_history: Some(true),
+ support_bot_user_agent_chat_history: Some(true),
+ support_cag_reactions_and_polls: Some(true),
+ support_biz_hosted_msg: Some(true),
+ support_recent_sync_chunk_message_count_tuning: Some(true),
+ support_hosted_group_msg: Some(true),
+ support_fbid_bot_chat_history: Some(true),
+ support_message_association: Some(true),
+ support_group_history: Some(true),
+ thumbnail_sync_days_limit: Some(60),
+ support_manus_history: Some(true),
+ support_hatch_history: Some(true),
+ ..Default::default()
+ }),
+ platform_type: Some(device_props::PlatformType::Unknown.into()),
+ require_full_sync: Some(false),
+ }
+}
+
+/// Why [`Device::get_client_payload`] failed (Go panics).
+#[derive(Debug, thiserror::Error, PartialEq, Eq)]
+pub enum ClientPayloadError {
+ /// The device has an ID, but it is the empty JID.
+ #[error("GetClientPayload called with empty JID")]
+ EmptyJid,
+ /// A new device needs a signed prekey signature to register.
+ #[error("signed prekey has no signature")]
+ UnsignedPreKey,
+}
+
+impl Device {
+ fn get_registration_payload(&self) -> Result<ClientPayload, ClientPayloadError> {
+ let signature = self
+ .signed_pre_key
+ .signature
+ .ok_or(ClientPayloadError::UnsignedPreKey)?;
+ let mut payload = base_client_payload();
+ payload.device_pairing_data = Some(DevicePairingRegistrationData {
+ e_regid: Some(self.registration_id.to_be_bytes().to_vec()),
+ e_keytype: Some(vec![DJB_TYPE]),
+ e_ident: Some(self.identity_key.public.to_vec()),
+ e_skey_id: Some(self.signed_pre_key.key_id.to_be_bytes()[1..].to_vec()),
+ e_skey_val: Some(self.signed_pre_key.key_pair.public.to_vec()),
+ e_skey_sig: Some(signature.to_vec()),
+ build_hash: Some(get_wa_version().hash().to_vec()),
+ device_props: Some(device_props().encode_to_vec()),
+ });
+ payload.passive = Some(false);
+ payload.pull = Some(false);
+ Ok(payload)
+ }
+
+ fn get_login_payload(&self, id: &crate::types::Jid) -> ClientPayload {
+ let mut payload = base_client_payload();
+ payload.username = Some(id.user_int());
+ payload.device = Some(u32::from(id.device));
+ payload.passive = Some(true);
+ payload.pull = Some(true);
+ payload.lid_db_migrated = Some(true);
+ payload.lc.get_or_insert(1);
+ payload
+ }
+
+ /// The payload of the last handshake message: a login for a paired
+ /// device, a registration for a new one.
+ pub fn get_client_payload(&self) -> Result<ClientPayload, ClientPayloadError> {
+ match &self.id {
+ Some(id) if *id == crate::types::Jid::default() => Err(ClientPayloadError::EmptyJid),
+ Some(id) => Ok(self.get_login_payload(id)),
+ None => self.get_registration_payload(),
+ }
+ }
+}
+
+#[cfg(test)]
+mod test;
diff --git a/crates/whatsmeow/src/store/clientpayload/test.rs b/crates/whatsmeow/src/store/clientpayload/test.rs
new file mode 100644
index 0000000000..524c82a1b3
--- /dev/null
+++ b/crates/whatsmeow/src/store/clientpayload/test.rs
@@ -0,0 +1,113 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+//! The expected bytes were produced by whatsmeow's Go code at the pinned
+//! revision, with the same fixed keys.
+
+use std::sync::Arc;
+
+use super::*;
+use crate::signal::CurveSignatures;
+use crate::store::MemoryStore;
+use crate::types::{DEFAULT_USER_SERVER, Jid};
+use crate::util::keys::{PreKey, new_key_pair_from_private_key};
+
+struct UnusedSignatures;
+
+impl CurveSignatures for UnusedSignatures {
+ fn calculate_signature(&self, _: &[u8; 32], _: &[u8]) -> [u8; 64] {
+ [0; 64]
+ }
+
+ fn verify_signature(&self, _: &[u8; 32], _: &[u8], _: &[u8; 64]) -> bool {
+ false
+ }
+}
+
+fn fixed_private_key(start: u8) -> [u8; 32] {
+ std::array::from_fn(|index| start + u8::try_from(index).unwrap())
+}
+
+fn device_with_fixed_keys() -> Device {
+ let mut device = Arc::new(MemoryStore::default()).new_device(&UnusedSignatures);
+ device.identity_key = new_key_pair_from_private_key(fixed_private_key(0x20));
+ device.signed_pre_key = PreKey {
+ key_pair: new_key_pair_from_private_key(fixed_private_key(0x30)),
+ key_id: 1,
+ signature: Some(std::array::from_fn(|index| u8::try_from(index).unwrap())),
+ };
+ device.registration_id = 0x0102_0304;
+ device
+}
+
+#[test]
+fn registration_payload_matches_go() {
+ let device = device_with_fixed_keys();
+ assert_eq!(
+ hex::encode(device.get_client_payload().unwrap().encode_to_vec()),
+ "18002a38080e120b080210b8171884b483f5031a0330303022033030302a03302e3132003a074465736b746f704203302e3150005a02656e6202555332022000600168019a01e1010a04010203041201051a20358072d6365880d1aeea329adf9121383851ed21a28e3b75e965d0d2cd16625422030000012a2034e42d4af5ef94a07a3a84201b889d4cd1a743cb27b11b6a10438a8feb8e58473240000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f3a10ed6c6a921d03d857ec78c153a7f7a0cf42390a0977686174736d656f771206080010011800180020002a20188050200130013801400148015001580160017001780198013ca80101b00101880200"
+ );
+}
+
+#[test]
+fn login_payload_matches_go() {
+ let mut device = device_with_fixed_keys();
+ device.id = Some(Jid {
+ user: "1234567890".to_owned(),
+ device: 7,
+ server: DEFAULT_USER_SERVER.to_owned(),
+ ..Jid::default()
+ });
+ assert_eq!(
+ hex::encode(device.get_client_payload().unwrap().encode_to_vec()),
+ "08d285d8cc0418012a38080e120b080210b8171884b483f5031a0330303022033030302a03302e3132003a074465736b746f704203302e3150005a02656e620255533202200060016801900107c00101880201c80201"
+ );
+
+ device.id = Some(Jid::default());
+ assert_eq!(
+ device.get_client_payload(),
+ Err(ClientPayloadError::EmptyJid)
+ );
+}
+
+#[test]
+fn os_info_changes_the_user_agent_and_device_props_like_go() {
+ let os_info = Some(("Macro".to_owned(), [1, 2, 3]));
+ let device = device_with_fixed_keys();
+ let mut payload = build_base_client_payload(get_wa_version(), os_info.clone());
+ let mut expected = device.get_client_payload().unwrap();
+ expected.user_agent = payload.user_agent.take();
+ if let Some(pairing_data) = expected.device_pairing_data.as_mut() {
+ pairing_data.device_props = Some(build_device_props(os_info).encode_to_vec());
+ }
+ assert_eq!(
+ hex::encode(expected.encode_to_vec()),
+ "18002a3c080e120b080210b8171884b483f5031a0330303022033030302a05312e322e3332003a074465736b746f704205312e322e3350005a02656e6202555332022000600168019a01dd010a04010203041201051a20358072d6365880d1aeea329adf9121383851ed21a28e3b75e965d0d2cd16625422030000012a2034e42d4af5ef94a07a3a84201b889d4cd1a743cb27b11b6a10438a8feb8e58473240000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f3a10ed6c6a921d03d857ec78c153a7f7a0cf42350a054d6163726f1206080110021803180020002a20188050200130013801400148015001580160017001780198013ca80101b00101880200"
+ );
+}
+
+#[test]
+fn version_helpers_match_go() {
+ let version = get_wa_version();
+ assert_eq!(version.to_string(), "2.3000.1050728964");
+ assert_eq!(
+ hex::encode(version.hash()),
+ "ed6c6a921d03d857ec78c153a7f7a0cf"
+ );
+ assert_eq!(
+ parse_version("2.3000.1"),
+ Ok(WaVersionContainer([2, 3000, 1]))
+ );
+ assert_eq!(
+ parse_version("2.1").unwrap_err().to_string(),
+ "'2.1' doesn't contain three dot-separated parts"
+ );
+ assert_eq!(
+ parse_version("2.x.1").unwrap_err().to_string(),
+ "second part of '2.x.1' is not a number: invalid digit found in string"
+ );
+ assert!(WaVersionContainer([2, 2999, 9]).less_than(&WaVersionContainer([2, 3000, 1])));
+ assert!(!WaVersionContainer([2, 3000, 1]).less_than(&WaVersionContainer([2, 3000, 1])));
+ assert!(WaVersionContainer::default().is_zero());
+}
diff --git a/crates/whatsmeow/src/store/memorystore.rs b/crates/whatsmeow/src/store/memorystore.rs
new file mode 100644
index 0000000000..e37a9d90e9
--- /dev/null
+++ b/crates/whatsmeow/src/store/memorystore.rs
@@ -0,0 +1,831 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+//! An in-memory implementation of every store, for tests. Not a port of a Go
+//! file: it follows the behaviour of whatsmeow's `store/sqlstore` where tests
+//! depend on it (trust on first use, prekey numbering and upload marking,
+//! address prefix deletes, LID migration), and keeps everything forever.
+
+use std::collections::{BTreeMap, HashMap};
+use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
+
+use async_trait::async_trait;
+use chrono::{DateTime, Utc};
+
+use super::store::*;
+use crate::signal::CurveSignatures;
+use crate::types::{
+ ContactInfo, DEFAULT_USER_SERVER, HIDDEN_USER_SERVER, Jid, LocalChatSettings, MessageId,
+};
+use crate::util::keys::{PreKey, new_key_pair, new_pre_key};
+
+#[derive(Default)]
+struct State {
+ identities: HashMap<String, [u8; 32]>,
+ sessions: HashMap<String, Vec<u8>>,
+ /// Prekeys by ID, with whether they were uploaded.
+ pre_keys: BTreeMap<u32, (PreKey, bool)>,
+ /// Sender keys by (group, sender address).
+ sender_keys: HashMap<(String, String), Vec<u8>>,
+ app_state_sync_keys: HashMap<Vec<u8>, AppStateSyncKey>,
+ app_state_versions: HashMap<String, (u64, [u8; 128])>,
+ /// Mutation MACs per collection, with the version they were stored at.
+ mutation_macs: HashMap<String, Vec<(u64, AppStateMutationMac)>>,
+ contacts: HashMap<Jid, ContactInfo>,
+ chat_settings: HashMap<Jid, LocalChatSettings>,
+ wasa_root_secret_ids: HashMap<Jid, MessageId>,
+ message_secrets: HashMap<(Jid, Jid, MessageId), Vec<u8>>,
+ privacy_tokens: HashMap<Jid, PrivacyToken>,
+ nct_salt: Option<Vec<u8>>,
+ buffered_events: HashMap<[u8; 32], BufferedEvent>,
+ outgoing_events: HashMap<(Jid, MessageId), (String, Vec<u8>)>,
+ /// LID user → phone number user.
+ pn_by_lid: HashMap<String, String>,
+ /// Phone number user → LID user.
+ lid_by_pn: HashMap<String, String>,
+ saved_devices: Vec<Jid>,
+}
+
+/// Every store, kept in memory.
+#[derive(Default)]
+pub struct MemoryStore {
+ state: Mutex<State>,
+}
+
+impl MemoryStore {
+ fn state(&self) -> MutexGuard<'_, State> {
+ // Every mutation below is a single map operation, so a panic can't
+ // leave the state half-written.
+ self.state.lock().unwrap_or_else(PoisonError::into_inner)
+ }
+
+ /// The JIDs of the devices saved to this store as a container.
+ pub fn saved_devices(&self) -> Vec<Jid> {
+ self.state().saved_devices.clone()
+ }
+
+ /// A new unpaired device whose stores are all this store, like
+ /// `sqlstore.Container.NewDevice`.
+ pub fn new_device(self: &Arc<Self>, signatures: &impl CurveSignatures) -> Device {
+ let identity_key = new_key_pair();
+ let signed_pre_key = identity_key.create_signed_pre_key(signatures, 1);
+ Device {
+ noise_key: new_key_pair(),
+ identity_key,
+ signed_pre_key,
+ registration_id: rand::random(),
+ adv_secret_key: rand::random::<[u8; 32]>().to_vec(),
+ id: None,
+ lid: Jid::default(),
+ account: None,
+ platform: String::new(),
+ business_name: String::new(),
+ push_name: String::new(),
+ lid_migration_timestamp: 0,
+ companion_meta_nonce: String::new(),
+ facebook_uuid: None,
+ initialized: false,
+ deleted: false,
+ identities: self.clone(),
+ sessions: self.clone(),
+ pre_keys: self.clone(),
+ sender_keys: self.clone(),
+ app_state_keys: self.clone(),
+ app_state: self.clone(),
+ contacts: self.clone(),
+ chat_settings: self.clone(),
+ msg_secrets: self.clone(),
+ privacy_tokens: self.clone(),
+ nct_salt: self.clone(),
+ event_buffer: self.clone(),
+ lids: self.clone(),
+ container: self.clone(),
+ }
+ }
+}
+
+fn address_prefix(phone: &str) -> String {
+ format!("{phone}:")
+}
+
+fn next_pre_key_id(state: &State) -> u32 {
+ state.pre_keys.last_key_value().map_or(1, |(id, _)| id + 1)
+}
+
+#[async_trait]
+impl IdentityStore for MemoryStore {
+ async fn put_identity(&self, address: &str, key: [u8; 32]) -> Result<(), StoreError> {
+ self.state().identities.insert(address.to_owned(), key);
+ Ok(())
+ }
+
+ async fn delete_all_identities(&self, phone: &str) -> Result<(), StoreError> {
+ let prefix = address_prefix(phone);
+ self.state()
+ .identities
+ .retain(|address, _| !address.starts_with(&prefix));
+ Ok(())
+ }
+
+ async fn delete_identity(&self, address: &str) -> Result<(), StoreError> {
+ self.state().identities.remove(address);
+ Ok(())
+ }
+
+ async fn is_trusted_identity(&self, address: &str, key: [u8; 32]) -> Result<bool, StoreError> {
+ // Trust if not known; it is saved automatically later.
+ Ok(self
+ .state()
+ .identities
+ .get(address)
+ .is_none_or(|existing| *existing == key))
+ }
+}
+
+#[async_trait]
+impl SessionStore for MemoryStore {
+ async fn get_session(&self, address: &str) -> Result<Option<Vec<u8>>, StoreError> {
+ Ok(self.state().sessions.get(address).cloned())
+ }
+
+ async fn has_session(&self, address: &str) -> Result<bool, StoreError> {
+ Ok(self.state().sessions.contains_key(address))
+ }
+
+ async fn get_many_sessions(
+ &self,
+ addresses: &[String],
+ ) -> Result<HashMap<String, Option<Vec<u8>>>, StoreError> {
+ let state = self.state();
+ Ok(addresses
+ .iter()
+ .map(|address| (address.clone(), state.sessions.get(address).cloned()))
+ .collect())
+ }
+
+ async fn put_session(&self, address: &str, session: Vec<u8>) -> Result<(), StoreError> {
+ self.state().sessions.insert(address.to_owned(), session);
+ Ok(())
+ }
+
+ async fn put_many_sessions(
+ &self,
+ sessions: HashMap<String, Vec<u8>>,
+ ) -> Result<(), StoreError> {
+ self.state().sessions.extend(sessions);
+ Ok(())
+ }
+
+ async fn delete_all_sessions(&self, phone: &str) -> Result<(), StoreError> {
+ let prefix = address_prefix(phone);
+ self.state()
+ .sessions
+ .retain(|address, _| !address.starts_with(&prefix));
+ Ok(())
+ }
+
+ async fn delete_session(&self, address: &str) -> Result<(), StoreError> {
+ self.state().sessions.remove(address);
+ Ok(())
+ }
+
+ async fn migrate_pn_to_lid(&self, pn: &Jid, lid: &Jid) -> Result<(), StoreError> {
+ let pn_prefix = address_prefix(&pn.signal_address_user());
+ let lid_prefix = address_prefix(&lid.signal_address_user());
+ let migrate = |address: &str| {
+ address
+ .strip_prefix(&pn_prefix)
+ .map(|device| format!("{lid_prefix}{device}"))
+ };
+ let mut state = self.state();
+ let moved: Vec<(String, Vec<u8>)> = state
+ .sessions
+ .iter()
+ .filter_map(|(address, session)| Some((migrate(address)?, session.clone())))
+ .collect();
+ state
+ .sessions
+ .retain(|address, _| !address.starts_with(&pn_prefix));
+ state.sessions.extend(moved);
+ let moved: Vec<(String, [u8; 32])> = state
+ .identities
+ .iter()
+ .filter_map(|(address, key)| Some((migrate(address)?, *key)))
+ .collect();
+ state
+ .identities
+ .retain(|address, _| !address.starts_with(&pn_prefix));
+ state.identities.extend(moved);
+ let moved: Vec<((String, String), Vec<u8>)> = state
+ .sender_keys
+ .iter()
+ .filter_map(|((group, sender), key)| {
+ Some(((group.clone(), migrate(sender)?), key.clone()))
+ })
+ .collect();
+ state
+ .sender_keys
+ .retain(|(_, sender), _| !sender.starts_with(&pn_prefix));
+ state.sender_keys.extend(moved);
+ Ok(())
+ }
+}
+
+#[async_trait]
+impl PreKeyStore for MemoryStore {
+ async fn get_or_gen_pre_keys(&self, count: u32) -> Result<Vec<PreKey>, StoreError> {
+ let mut state = self.state();
+ let mut keys: Vec<PreKey> = state
+ .pre_keys
+ .values()
+ .filter(|(_, uploaded)| !uploaded)
+ .map(|(key, _)| key.clone())
+ .take(usize::try_from(count).unwrap_or(usize::MAX))
+ .collect();
+ let mut next_id = next_pre_key_id(&state);
+ while keys.len() < usize::try_from(count).unwrap_or(usize::MAX) {
+ let key = new_pre_key(next_id);
+ state.pre_keys.insert(next_id, (key.clone(), false));
+ keys.push(key);
+ next_id += 1;
+ }
+ Ok(keys)
+ }
+
+ async fn gen_one_pre_key(&self) -> Result<PreKey, StoreError> {
+ let mut state = self.state();
+ let key = new_pre_key(next_pre_key_id(&state));
+ state.pre_keys.insert(key.key_id, (key.clone(), true));
+ Ok(key)
+ }
+
+ async fn get_pre_key(&self, id: u32) -> Result<Option<PreKey>, StoreError> {
+ Ok(self.state().pre_keys.get(&id).map(|(key, _)| key.clone()))
+ }
+
+ async fn remove_pre_key(&self, id: u32) -> Result<(), StoreError> {
+ self.state().pre_keys.remove(&id);
+ Ok(())
+ }
+
+ async fn mark_pre_keys_as_uploaded(&self, up_to_id: u32) -> Result<(), StoreError> {
+ for (_, (_, uploaded)) in self.state().pre_keys.range_mut(..=up_to_id) {
+ *uploaded = true;
+ }
+ Ok(())
+ }
+
+ async fn uploaded_pre_key_count(&self) -> Result<usize, StoreError> {
+ Ok(self
+ .state()
+ .pre_keys
+ .values()
+ .filter(|(_, uploaded)| *uploaded)
+ .count())
+ }
+}
+
+#[async_trait]
+impl SenderKeyStore for MemoryStore {
+ async fn put_sender_key(
+ &self,
+ group: &str,
+ user: &str,
+ session: Vec<u8>,
+ ) -> Result<(), StoreError> {
+ self.state()
+ .sender_keys
+ .insert((group.to_owned(), user.to_owned()), session);
+ Ok(())
+ }
+
+ async fn get_sender_key(&self, group: &str, user: &str) -> Result<Option<Vec<u8>>, StoreError> {
+ Ok(self
+ .state()
+ .sender_keys
+ .get(&(group.to_owned(), user.to_owned()))
+ .cloned())
+ }
+}
+
+#[async_trait]
+impl AppStateSyncKeyStore for MemoryStore {
+ async fn put_app_state_sync_key(
+ &self,
+ id: &[u8],
+ key: AppStateSyncKey,
+ ) -> Result<(), StoreError> {
+ self.state().app_state_sync_keys.insert(id.to_vec(), key);
+ Ok(())
+ }
+
+ async fn get_app_state_sync_key(
+ &self,
+ id: &[u8],
+ ) -> Result<Option<AppStateSyncKey>, StoreError> {
+ Ok(self.state().app_state_sync_keys.get(id).cloned())
+ }
+
+ async fn get_latest_app_state_sync_key_id(&self) -> Result<Option<Vec<u8>>, StoreError> {
+ Ok(self
+ .state()
+ .app_state_sync_keys
+ .iter()
+ .max_by_key(|(_, key)| key.timestamp)
+ .map(|(id, _)| id.clone()))
+ }
+
+ async fn get_all_app_state_sync_keys(&self) -> Result<Vec<AppStateSyncKey>, StoreError> {
+ let mut keys: Vec<AppStateSyncKey> =
+ self.state().app_state_sync_keys.values().cloned().collect();
+ keys.sort_by_key(|key| std::cmp::Reverse(key.timestamp));
+ Ok(keys)
+ }
+}
+
+#[async_trait]
+impl AppStateStore for MemoryStore {
+ async fn put_app_state_version(
+ &self,
+ name: &str,
+ version: u64,
+ hash: [u8; 128],
+ ) -> Result<(), StoreError> {
+ self.state()
+ .app_state_versions
+ .insert(name.to_owned(), (version, hash));
+ Ok(())
+ }
+
+ async fn get_app_state_version(&self, name: &str) -> Result<(u64, [u8; 128]), StoreError> {
+ Ok(self
+ .state()
+ .app_state_versions
+ .get(name)
+ .copied()
+ .unwrap_or((0, [0; 128])))
+ }
+
+ async fn delete_app_state_version(&self, name: &str) -> Result<(), StoreError> {
+ self.state().app_state_versions.remove(name);
+ Ok(())
+ }
+
+ async fn put_app_state_mutation_macs(
+ &self,
+ name: &str,
+ version: u64,
+ mutations: &[AppStateMutationMac],
+ ) -> Result<(), StoreError> {
+ self.state()
+ .mutation_macs
+ .entry(name.to_owned())
+ .or_default()
+ .extend(mutations.iter().map(|mutation| (version, mutation.clone())));
+ Ok(())
+ }
+
+ async fn delete_app_state_mutation_macs(
+ &self,
+ name: &str,
+ index_macs: &[Vec<u8>],
+ ) -> Result<(), StoreError> {
+ if let Some(macs) = self.state().mutation_macs.get_mut(name) {
+ macs.retain(|(_, mutation)| !index_macs.contains(&mutation.index_mac));
+ }
+ Ok(())
+ }
+
+ async fn get_app_state_mutation_mac(
+ &self,
+ name: &str,
+ index_mac: &[u8],
+ ) -> Result<Option<Vec<u8>>, StoreError> {
+ Ok(self.state().mutation_macs.get(name).and_then(|macs| {
+ macs.iter()
+ .filter(|(_, mutation)| mutation.index_mac == index_mac)
+ .max_by_key(|(version, _)| *version)
+ .map(|(_, mutation)| mutation.value_mac.clone())
+ }))
+ }
+}
+
+#[async_trait]
+impl ContactStore for MemoryStore {
+ async fn put_push_name(
+ &self,
+ user: &Jid,
+ push_name: &str,
+ ) -> Result<(bool, String), StoreError> {
+ let mut state = self.state();
+ let contact = state.contacts.entry(user.clone()).or_default();
+ if contact.push_name == push_name {
+ return Ok((false, String::new()));
+ }
+ let previous = std::mem::replace(&mut contact.push_name, push_name.to_owned());
+ Ok((true, previous))
+ }
+
+ async fn put_business_name(
+ &self,
+ user: &Jid,
+ business_name: &str,
+ ) -> Result<(bool, String), StoreError> {
+ let mut state = self.state();
+ let contact = state.contacts.entry(user.clone()).or_default();
+ if contact.business_name == business_name {
+ return Ok((false, String::new()));
+ }
+ let previous = std::mem::replace(&mut contact.business_name, business_name.to_owned());
+ Ok((true, previous))
+ }
+
+ async fn put_contact_name(
+ &self,
+ user: &Jid,
+ full_name: &str,
+ first_name: &str,
+ ) -> Result<(), StoreError> {
+ let mut state = self.state();
+ let contact = state.contacts.entry(user.clone()).or_default();
+ contact.full_name = full_name.to_owned();
+ contact.first_name = first_name.to_owned();
+ Ok(())
+ }
+
+ async fn put_all_contact_names(&self, contacts: &[ContactEntry]) -> Result<(), StoreError> {
+ let mut state = self.state();
+ for entry in contacts {
+ let contact = state.contacts.entry(entry.jid.clone()).or_default();
+ contact.full_name = entry.full_name.clone();
+ contact.first_name = entry.first_name.clone();
+ }
+ Ok(())
+ }
+
+ async fn put_many_redacted_phones(
+ &self,
+ entries: &[RedactedPhoneEntry],
+ ) -> Result<(), StoreError> {
+ let mut state = self.state();
+ for entry in entries {
+ state
+ .contacts
+ .entry(entry.jid.clone())
+ .or_default()
+ .redacted_phone = entry.redacted_phone.clone();
+ }
+ Ok(())
+ }
+
+ async fn get_contact(&self, user: &Jid) -> Result<Option<ContactInfo>, StoreError> {
+ Ok(self.state().contacts.get(user).cloned())
+ }
+
+ async fn get_all_contacts(&self) -> Result<HashMap<Jid, ContactInfo>, StoreError> {
+ Ok(self.state().contacts.clone())
+ }
+}
+
+#[async_trait]
+impl ChatSettingsStore for MemoryStore {
+ async fn put_muted_until(
+ &self,
+ chat: &Jid,
+ muted_until: Option<DateTime<Utc>>,
+ ) -> Result<(), StoreError> {
+ self.state()
+ .chat_settings
+ .entry(chat.clone())
+ .or_default()
+ .muted_until = muted_until;
+ Ok(())
+ }
+
+ async fn put_pinned(&self, chat: &Jid, pinned: bool) -> Result<(), StoreError> {
+ self.state()
+ .chat_settings
+ .entry(chat.clone())
+ .or_default()
+ .pinned = pinned;
+ Ok(())
+ }
+
+ async fn put_archived(&self, chat: &Jid, archived: bool) -> Result<(), StoreError> {
+ self.state()
+ .chat_settings
+ .entry(chat.clone())
+ .or_default()
+ .archived = archived;
+ Ok(())
+ }
+
+ async fn put_wasa_root_secret_id(&self, chat: &Jid, id: &MessageId) -> Result<(), StoreError> {
+ self.state()
+ .wasa_root_secret_ids
+ .insert(chat.clone(), id.clone());
+ Ok(())
+ }
+
+ async fn get_wasa_root_secret_id(&self, chat: &Jid) -> Result<Option<MessageId>, StoreError> {
+ Ok(self.state().wasa_root_secret_ids.get(chat).cloned())
+ }
+
+ async fn get_chat_settings(&self, chat: &Jid) -> Result<Option<LocalChatSettings>, StoreError> {
+ Ok(self.state().chat_settings.get(chat).cloned())
+ }
+}
+
+#[async_trait]
+impl DeviceContainer for MemoryStore {
+ async fn put_device(&self, store: &Device) -> Result<(), StoreError> {
+ let jid = store.id.clone().ok_or(StoreError::InvalidArgument(
+ "device JID must be known before accessing database".to_owned(),
+ ))?;
+ let mut state = self.state();
+ if !state.saved_devices.contains(&jid) {
+ state.saved_devices.push(jid);
+ }
+ Ok(())
+ }
+
+ async fn delete_device(&self, store: &Device) -> Result<(), StoreError> {
+ if let Some(jid) = &store.id {
+ self.state().saved_devices.retain(|saved| saved != jid);
+ }
+ Ok(())
+ }
+}
+
+#[async_trait]
+impl MsgSecretStore for MemoryStore {
+ async fn put_message_secrets(&self, inserts: &[MessageSecretInsert]) -> Result<(), StoreError> {
+ let mut state = self.state();
+ for insert in inserts {
+ state
+ .message_secrets
+ .entry((
+ insert.chat.to_non_ad(),
+ insert.sender.to_non_ad(),
+ insert.id.clone(),
+ ))
+ .or_insert_with(|| insert.secret.clone());
+ }
+ Ok(())
+ }
+
+ async fn put_message_secret(
+ &self,
+ chat: &Jid,
+ sender: &Jid,
+ id: &MessageId,
+ secret: Vec<u8>,
+ ) -> Result<(), StoreError> {
+ self.state()
+ .message_secrets
+ .entry((chat.to_non_ad(), sender.to_non_ad(), id.clone()))
+ .or_insert(secret);
+ Ok(())
+ }
+
+ async fn get_message_secret(
+ &self,
+ chat: &Jid,
+ sender: &Jid,
+ id: &MessageId,
+ ) -> Result<Option<(Vec<u8>, Jid)>, StoreError> {
+ let sender = sender.to_non_ad();
+ Ok(self
+ .state()
+ .message_secrets
+ .get(&(chat.to_non_ad(), sender.clone(), id.clone()))
+ .map(|secret| (secret.clone(), sender)))
+ }
+}
+
+#[async_trait]
+impl PrivacyTokenStore for MemoryStore {
+ async fn put_privacy_tokens(&self, tokens: &[PrivacyToken]) -> Result<(), StoreError> {
+ let mut state = self.state();
+ for token in tokens {
+ match state.privacy_tokens.get_mut(&token.user) {
+ Some(existing) if token.timestamp < existing.timestamp => {}
+ Some(existing) => {
+ existing.token = token.token.clone();
+ existing.timestamp = token.timestamp;
+ existing.sender_timestamp =
+ token.sender_timestamp.or(existing.sender_timestamp);
+ }
+ None => {
+ state
+ .privacy_tokens
+ .insert(token.user.clone(), token.clone());
+ }
+ }
+ }
+ Ok(())
+ }
+
+ async fn get_privacy_token(&self, user: &Jid) -> Result<Option<PrivacyToken>, StoreError> {
+ Ok(self.state().privacy_tokens.get(user).cloned())
+ }
+
+ async fn delete_expired_privacy_tokens(
+ &self,
+ cutoff: DateTime<Utc>,
+ ) -> Result<u64, StoreError> {
+ let mut state = self.state();
+ let before = state.privacy_tokens.len();
+ state
+ .privacy_tokens
+ .retain(|_, token| token.timestamp >= cutoff);
+ Ok(u64::try_from(before - state.privacy_tokens.len()).unwrap_or(u64::MAX))
+ }
+}
+
+#[async_trait]
+impl NctSaltStore for MemoryStore {
+ async fn put_nct_salt(&self, salt: Vec<u8>) -> Result<(), StoreError> {
+ self.state().nct_salt = Some(salt);
+ Ok(())
+ }
+
+ async fn get_nct_salt(&self) -> Result<Option<Vec<u8>>, StoreError> {
+ Ok(self.state().nct_salt.clone())
+ }
+
+ async fn delete_nct_salt(&self) -> Result<(), StoreError> {
+ self.state().nct_salt = None;
+ Ok(())
+ }
+}
+
+#[async_trait]
+impl EventBuffer for MemoryStore {
+ async fn get_buffered_event(
+ &self,
+ ciphertext_hash: [u8; 32],
+ ) -> Result<Option<BufferedEvent>, StoreError> {
+ Ok(self.state().buffered_events.get(&ciphertext_hash).cloned())
+ }
+
+ async fn put_buffered_event(
+ &self,
+ ciphertext_hash: [u8; 32],
+ plaintext: Vec<u8>,
+ server_timestamp: DateTime<Utc>,
+ ) -> Result<(), StoreError> {
+ self.state().buffered_events.insert(
+ ciphertext_hash,
+ BufferedEvent {
+ plaintext,
+ insert_time: Utc::now(),
+ server_time: server_timestamp,
+ },
+ );
+ Ok(())
+ }
+
+ async fn do_decryption_txn(&self, body: DecryptionTransaction<'_>) -> Result<(), StoreError> {
+ body.await
+ }
+
+ async fn clear_buffered_event_plaintext(
+ &self,
+ ciphertext_hash: [u8; 32],
+ ) -> Result<(), StoreError> {
+ if let Some(event) = self.state().buffered_events.get_mut(&ciphertext_hash) {
+ event.plaintext.clear();
+ }
+ Ok(())
+ }
+
+ async fn delete_old_buffered_hashes(&self) -> Result<(), StoreError> {
+ Ok(())
+ }
+
+ async fn get_outgoing_event(
+ &self,
+ chat_jid: &Jid,
+ alt_chat_jid: &Jid,
+ id: &MessageId,
+ ) -> Result<Option<(String, Vec<u8>)>, StoreError> {
+ let state = self.state();
+ Ok(state
+ .outgoing_events
+ .get(&(chat_jid.clone(), id.clone()))
+ .or_else(|| {
+ state
+ .outgoing_events
+ .get(&(alt_chat_jid.clone(), id.clone()))
+ })
+ .cloned())
+ }
+
+ async fn add_outgoing_event(
+ &self,
+ chat_jid: &Jid,
+ id: &MessageId,
+ format: &str,
+ plaintext: Vec<u8>,
+ ) -> Result<(), StoreError> {
+ self.state().outgoing_events.insert(
+ (chat_jid.clone(), id.clone()),
+ (format.to_owned(), plaintext),
+ );
+ Ok(())
+ }
+
+ async fn delete_old_outgoing_events(&self) -> Result<(), StoreError> {
+ Ok(())
+ }
+}
+
+#[async_trait]
+impl LidStore for MemoryStore {
+ async fn put_many_lid_mappings(&self, mappings: &[LidMapping]) -> Result<(), StoreError> {
+ let mut state = self.state();
+ for mapping in mappings {
+ if mapping.lid.server != HIDDEN_USER_SERVER || mapping.pn.server != DEFAULT_USER_SERVER
+ {
+ continue;
+ }
+ put_mapping(&mut state, &mapping.lid, &mapping.pn);
+ }
+ Ok(())
+ }
+
+ async fn put_lid_mapping(&self, lid: &Jid, jid: &Jid) -> Result<(), StoreError> {
+ if lid.server != HIDDEN_USER_SERVER || jid.server != DEFAULT_USER_SERVER {
+ return Err(StoreError::InvalidArgument(format!(
+ "invalid PutLIDMapping call {lid}/{jid}"
+ )));
+ }
+ put_mapping(&mut self.state(), lid, jid);
+ Ok(())
+ }
+
+ async fn get_pn_for_lid(&self, lid: &Jid) -> Result<Option<Jid>, StoreError> {
+ if lid.server != HIDDEN_USER_SERVER {
+ return Err(StoreError::InvalidArgument(format!(
+ "invalid GetPNForLID call with non-LID JID {lid}"
+ )));
+ }
+ Ok(self.state().pn_by_lid.get(&lid.user).map(|user| Jid {
+ user: user.clone(),
+ device: lid.device,
+ server: DEFAULT_USER_SERVER.to_owned(),
+ ..Jid::default()
+ }))
+ }
+
+ async fn get_lid_for_pn(&self, pn: &Jid) -> Result<Option<Jid>, StoreError> {
+ if pn.server != DEFAULT_USER_SERVER {
+ return Err(StoreError::InvalidArgument(format!(
+ "invalid GetLIDForPN call with non-PN JID {pn}"
+ )));
+ }
+ Ok(self.state().lid_by_pn.get(&pn.user).map(|user| Jid {
+ user: user.clone(),
+ device: pn.device,
+ server: HIDDEN_USER_SERVER.to_owned(),
+ ..Jid::default()
+ }))
+ }
+
+ async fn get_many_lids_for_pns(&self, pns: &[Jid]) -> Result<HashMap<Jid, Jid>, StoreError> {
+ let state = self.state();
+ Ok(pns
+ .iter()
+ .filter(|pn| pn.server == DEFAULT_USER_SERVER)
+ .filter_map(|pn| {
+ let lid_user = state.lid_by_pn.get(&pn.user)?;
+ Some((
+ pn.clone(),
+ Jid {
+ user: lid_user.clone(),
+ device: pn.device,
+ server: HIDDEN_USER_SERVER.to_owned(),
+ ..Jid::default()
+ },
+ ))
+ })
+ .collect())
+ }
+}
+
+/// Replaces any older mapping of either side.
+fn put_mapping(state: &mut State, lid: &Jid, pn: &Jid) {
+ if let Some(old_lid) = state.lid_by_pn.insert(pn.user.clone(), lid.user.clone()) {
+ state.pn_by_lid.remove(&old_lid);
+ }
+ if let Some(old_pn) = state.pn_by_lid.insert(lid.user.clone(), pn.user.clone())
+ && old_pn != pn.user
+ {
+ state.lid_by_pn.remove(&old_pn);
+ }
+}
+
+#[cfg(test)]
+mod test;
diff --git a/crates/whatsmeow/src/store/memorystore/test.rs b/crates/whatsmeow/src/store/memorystore/test.rs
new file mode 100644
index 0000000000..fe0367ec3e
--- /dev/null
+++ b/crates/whatsmeow/src/store/memorystore/test.rs
@@ -0,0 +1,216 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+use super::*;
+use crate::types::new_jid;
+
+#[tokio::test]
+async fn identities_are_trusted_on_first_use() {
+ let store = MemoryStore::default();
+ assert!(store.is_trusted_identity("111:0", [1; 32]).await.unwrap());
+ store.put_identity("111:0", [1; 32]).await.unwrap();
+ assert!(store.is_trusted_identity("111:0", [1; 32]).await.unwrap());
+ assert!(!store.is_trusted_identity("111:0", [2; 32]).await.unwrap());
+
+ store.put_identity("111:3", [3; 32]).await.unwrap();
+ store.put_identity("1112:0", [4; 32]).await.unwrap();
+ store.delete_all_identities("111").await.unwrap();
+ assert!(store.is_trusted_identity("111:3", [9; 32]).await.unwrap());
+ assert!(!store.is_trusted_identity("1112:0", [9; 32]).await.unwrap());
+}
+
+#[tokio::test]
+async fn pre_keys_are_numbered_from_one_and_marked_uploaded() {
+ let store = MemoryStore::default();
+ let first_batch = store.get_or_gen_pre_keys(3).await.unwrap();
+ assert_eq!(
+ first_batch.iter().map(|key| key.key_id).collect::<Vec<_>>(),
+ vec![1, 2, 3]
+ );
+ // Not uploaded yet, so the same keys come back.
+ let again = store.get_or_gen_pre_keys(2).await.unwrap();
+ assert_eq!(again, first_batch[..2]);
+
+ store.mark_pre_keys_as_uploaded(2).await.unwrap();
+ assert_eq!(store.uploaded_pre_key_count().await.unwrap(), 2);
+ let next_batch = store.get_or_gen_pre_keys(2).await.unwrap();
+ assert_eq!(
+ next_batch.iter().map(|key| key.key_id).collect::<Vec<_>>(),
+ vec![3, 4]
+ );
+ assert_eq!(store.gen_one_pre_key().await.unwrap().key_id, 5);
+ assert_eq!(store.uploaded_pre_key_count().await.unwrap(), 3);
+
+ store.remove_pre_key(1).await.unwrap();
+ assert_eq!(store.get_pre_key(1).await.unwrap(), None);
+ assert_eq!(
+ store.get_pre_key(2).await.unwrap(),
+ Some(first_batch[1].clone())
+ );
+}
+
+#[tokio::test]
+async fn migrate_pn_to_lid_moves_sessions_identities_and_sender_keys() {
+ let store = MemoryStore::default();
+ let pn = new_jid("1234567890", DEFAULT_USER_SERVER);
+ let lid = new_jid("98765432101234", HIDDEN_USER_SERVER);
+ store
+ .put_session("1234567890:0", b"main".to_vec())
+ .await
+ .unwrap();
+ store
+ .put_session("1234567890:5", b"web".to_vec())
+ .await
+ .unwrap();
+ store
+ .put_session("12345678901:0", b"other".to_vec())
+ .await
+ .unwrap();
+ store.put_identity("1234567890:5", [5; 32]).await.unwrap();
+ store
+ .put_sender_key("[email protected]", "1234567890:5", b"sender".to_vec())
+ .await
+ .unwrap();
+
+ store.migrate_pn_to_lid(&pn, &lid).await.unwrap();
+
+ assert_eq!(store.get_session("1234567890:0").await.unwrap(), None);
+ assert_eq!(
+ store.get_session("98765432101234_1:0").await.unwrap(),
+ Some(b"main".to_vec())
+ );
+ assert_eq!(
+ store.get_session("98765432101234_1:5").await.unwrap(),
+ Some(b"web".to_vec())
+ );
+ assert_eq!(
+ store.get_session("12345678901:0").await.unwrap(),
+ Some(b"other".to_vec())
+ );
+ assert!(
+ !store
+ .is_trusted_identity("98765432101234_1:5", [6; 32])
+ .await
+ .unwrap()
+ );
+ assert_eq!(
+ store
+ .get_sender_key("[email protected]", "98765432101234_1:5")
+ .await
+ .unwrap(),
+ Some(b"sender".to_vec())
+ );
+}
+
+#[tokio::test]
+async fn lid_mappings_keep_the_device_and_reject_wrong_servers() {
+ let store = MemoryStore::default();
+ let pn = new_jid("1234567890", DEFAULT_USER_SERVER);
+ let lid = new_jid("98765432101234", HIDDEN_USER_SERVER);
+ assert!(matches!(
+ store.put_lid_mapping(&pn, &lid).await,
+ Err(StoreError::InvalidArgument(_))
+ ));
+ store.put_lid_mapping(&lid, &pn).await.unwrap();
+
+ let pn_device = Jid {
+ device: 3,
+ ..pn.clone()
+ };
+ assert_eq!(
+ store.get_lid_for_pn(&pn_device).await.unwrap(),
+ Some(Jid {
+ device: 3,
+ ..lid.clone()
+ })
+ );
+ assert_eq!(
+ store
+ .get_many_lids_for_pns(&[pn.clone(), new_jid("1", DEFAULT_USER_SERVER)])
+ .await
+ .unwrap(),
+ HashMap::from([(pn.clone(), lid.clone())])
+ );
+
+ // A new LID for the same number replaces the old mapping both ways.
+ let new_lid = new_jid("55555555555555", HIDDEN_USER_SERVER);
+ store.put_lid_mapping(&new_lid, &pn).await.unwrap();
+ assert_eq!(store.get_pn_for_lid(&lid).await.unwrap(), None);
+ assert_eq!(store.get_lid_for_pn(&pn).await.unwrap(), Some(new_lid));
+}
+
+#[tokio::test]
+async fn push_names_report_changes() {
+ let store = MemoryStore::default();
+ let user = new_jid("1234567890", DEFAULT_USER_SERVER);
+ assert_eq!(
+ store.put_push_name(&user, "Wolf").await.unwrap(),
+ (true, String::new())
+ );
+ assert_eq!(
+ store.put_push_name(&user, "Wolf").await.unwrap(),
+ (false, String::new())
+ );
+ assert_eq!(
+ store.put_push_name(&user, "W").await.unwrap(),
+ (true, "Wolf".to_owned())
+ );
+ assert_eq!(
+ store
+ .get_contact(&user)
+ .await
+ .unwrap()
+ .map(|contact| contact.push_name),
+ Some("W".to_owned())
+ );
+}
+
+#[tokio::test]
+async fn app_state_mutation_macs_return_the_newest_version() {
+ let store = MemoryStore::default();
+ store
+ .put_app_state_mutation_macs(
+ "regular",
+ 1,
+ &[AppStateMutationMac {
+ index_mac: b"index".to_vec(),
+ value_mac: b"old".to_vec(),
+ }],
+ )
+ .await
+ .unwrap();
+ store
+ .put_app_state_mutation_macs(
+ "regular",
+ 2,
+ &[AppStateMutationMac {
+ index_mac: b"index".to_vec(),
+ value_mac: b"new".to_vec(),
+ }],
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ store
+ .get_app_state_mutation_mac("regular", b"index")
+ .await
+ .unwrap(),
+ Some(b"new".to_vec())
+ );
+ store
+ .delete_app_state_mutation_macs("regular", &[b"index".to_vec()])
+ .await
+ .unwrap();
+ assert_eq!(
+ store
+ .get_app_state_mutation_mac("regular", b"index")
+ .await
+ .unwrap(),
+ None
+ );
+ assert_eq!(
+ store.get_app_state_version("regular").await.unwrap(),
+ (0, [0; 128])
+ );
+}
diff --git a/crates/whatsmeow/src/store/noop.rs b/crates/whatsmeow/src/store/noop.rs
new file mode 100644
index 0000000000..39aab857fc
--- /dev/null
+++ b/crates/whatsmeow/src/store/noop.rs
@@ -0,0 +1,463 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+//
+// Ported from whatsmeow store/noop.go (MPL-2.0, Copyright (c) Tulir Asokan)
+
+use std::collections::HashMap;
+
+use async_trait::async_trait;
+use chrono::{DateTime, Utc};
+
+use super::store::*;
+use crate::types::{ContactInfo, Jid, LocalChatSettings, MessageId};
+use crate::util::keys::PreKey;
+
+/// Which error a [`NoopStore`] returns. Go stores an `error` value; the port's
+/// store error isn't clonable, so the store keeps the kind.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum NoopError {
+ /// [`StoreError::DeviceDeleted`].
+ DeviceDeleted,
+ /// [`StoreError::StoreIsNil`].
+ StoreIsNil,
+}
+
+impl NoopError {
+ fn to_store_error(self) -> StoreError {
+ match self {
+ NoopError::DeviceDeleted => StoreError::DeviceDeleted,
+ NoopError::StoreIsNil => StoreError::StoreIsNil,
+ }
+ }
+}
+
+/// A store where every operation fails with the same error. A deleted device
+/// uses it for all of its stores.
+///
+/// Not ported: Go's `NoopDevice`, a placeholder device for nil clients.
+#[derive(Clone, Copy, Debug)]
+pub struct NoopStore {
+ /// The error every operation returns.
+ pub error: NoopError,
+}
+
+#[async_trait]
+impl IdentityStore for NoopStore {
+ async fn put_identity(&self, _address: &str, _key: [u8; 32]) -> Result<(), StoreError> {
+ Err(self.error.to_store_error())
+ }
+
+ async fn delete_all_identities(&self, _phone: &str) -> Result<(), StoreError> {
+ Err(self.error.to_store_error())
+ }
+
+ async fn delete_identity(&self, _address: &str) -> Result<(), StoreError> {
+ Err(self.error.to_store_error())
+ }
+
+ async fn is_trusted_identity(
+ &self,
+ _address: &str,
+ _key: [u8; 32],
+ ) -> Result<bool, StoreError> {
+ Err(self.error.to_store_error())
+ }
+}
+
+#[async_trait]
+impl SessionStore for NoopStore {
+ async fn get_session(&self, _address: &str) -> Result<Option<Vec<u8>>, StoreError> {
+ Err(self.error.to_store_error())
+ }
+
+ async fn has_session(&self, _address: &str) -> Result<bool, StoreError> {
+ Err(self.error.to_store_error())
+ }
+
+ async fn get_many_sessions(
+ &self,
+ _addresses: &[String],
+ ) -> Result<HashMap<String, Option<Vec<u8>>>, StoreError> {
+ Err(self.error.to_store_error())
+ }
+
+ async fn put_session(&self, _address: &str, _session: Vec<u8>) -> Result<(), StoreError> {
+ Err(self.error.to_store_error())
+ }
+
+ async fn put_many_sessions(
+ &self,
+ _sessions: HashMap<String, Vec<u8>>,
+ ) -> Result<(), StoreError> {
+ Err(self.error.to_store_error())
+ }
+
+ async fn delete_all_sessions(&self, _phone: &str) -> Result<(), StoreError> {
+ Err(self.error.to_store_error())
+ }
+
+ async fn delete_session(&self, _address: &str) -> Result<(), StoreError> {
+ Err(self.error.to_store_error())
+ }
+
+ async fn migrate_pn_to_lid(&self, _pn: &Jid, _lid: &Jid) -> Result<(), StoreError> {
+ Err(self.error.to_store_error())
+ }
+}
+
+#[async_trait]
+impl PreKeyStore for NoopStore {
+ async fn get_or_gen_pre_keys(&self, _count: u32) -> Result<Vec<PreKey>, StoreError> {
+ Err(self.error.to_store_error())
+ }
+
+ async fn gen_one_pre_key(&self) -> Result<PreKey, StoreError> {
+ Err(self.error.to_store_error())
+ }
+
+ async fn get_pre_key(&self, _id: u32) -> Result<Option<PreKey>, StoreError> {
+ Err(self.error.to_store_error())
+ }
+
+ async fn remove_pre_key(&self, _id: u32) -> Result<(), StoreError> {
+ Err(self.error.to_store_error())
+ }
+
+ async fn mark_pre_keys_as_uploaded(&self, _up_to_id: u32) -> Result<(), StoreError> {
+ Err(self.error.to_store_error())
+ }
+
+ async fn uploaded_pre_key_count(&self) -> Result<usize, StoreError> {
+ Err(self.error.to_store_error())
+ }
+}
+
+#[async_trait]
+impl SenderKeyStore for NoopStore {
+ async fn put_sender_key(
+ &self,
+ _group: &str,
+ _user: &str,
+ _session: Vec<u8>,
+ ) -> Result<(), StoreError> {
+ Err(self.error.to_store_error())
+ }
+
+ async fn get_sender_key(
+ &self,
+ _group: &str,
+ _user: &str,
+ ) -> Result<Option<Vec<u8>>, StoreError> {
+ Err(self.error.to_store_error())
+ }
+}
+
+#[async_trait]
+impl AppStateSyncKeyStore for NoopStore {
+ async fn put_app_state_sync_key(
+ &self,
+ _id: &[u8],
+ _key: AppStateSyncKey,
+ ) -> Result<(), StoreError> {
+ Err(self.error.to_store_error())
+ }
+
+ async fn get_app_state_sync_key(
+ &self,
+ _id: &[u8],
+ ) -> Result<Option<AppStateSyncKey>, StoreError> {
+ Err(self.error.to_store_error())
+ }
+
+ async fn get_latest_app_state_sync_key_id(&self) -> Result<Option<Vec<u8>>, StoreError> {
+ Err(self.error.to_store_error())
+ }
+
+ async fn get_all_app_state_sync_keys(&self) -> Result<Vec<AppStateSyncKey>, StoreError> {
+ Err(self.error.to_store_error())
+ }
+}
+
+#[async_trait]
+impl AppStateStore for NoopStore {
+ async fn put_app_state_version(
+ &self,
+ _name: &str,
+ _version: u64,
+ _hash: [u8; 128],
+ ) -> Result<(), StoreError> {
+ Err(self.error.to_store_error())
+ }
+
+ async fn get_app_state_version(&self, _name: &str) -> Result<(u64, [u8; 128]), StoreError> {
+ Err(self.error.to_store_error())
+ }
+
+ async fn delete_app_state_version(&self, _name: &str) -> Result<(), StoreError> {
+ Err(self.error.to_store_error())
+ }
+
+ async fn put_app_state_mutation_macs(
+ &self,
+ _name: &str,
+ _version: u64,
+ _mutations: &[AppStateMutationMac],
+ ) -> Result<(), StoreError> {
+ Err(self.error.to_store_error())
+ }
+
+ async fn delete_app_state_mutation_macs(
+ &self,
+ _name: &str,
+ _index_macs: &[Vec<u8>],
+ ) -> Result<(), StoreError> {
+ Err(self.error.to_store_error())
+ }
+
+ async fn get_app_state_mutation_mac(
+ &self,
+ _name: &str,
+ _index_mac: &[u8],
+ ) -> Result<Option<Vec<u8>>, StoreError> {
+ Err(self.error.to_store_error())
+ }
+}
+
+#[async_trait]
+impl ContactStore for NoopStore {
+ async fn put_push_name(
+ &self,
+ _user: &Jid,
+ _push_name: &str,
+ ) -> Result<(bool, String), StoreError> {
+ Err(self.error.to_store_error())
+ }
+
+ async fn put_business_name(
+ &self,
+ _user: &Jid,
+ _business_name: &str,
+ ) -> Result<(bool, String), StoreError> {
+ Err(self.error.to_store_error())
+ }
+
+ async fn put_contact_name(
+ &self,
+ _user: &Jid,
+ _full_name: &str,
+ _first_name: &str,
+ ) -> Result<(), StoreError> {
+ Err(self.error.to_store_error())
+ }
+
+ async fn put_all_contact_names(&self, _contacts: &[ContactEntry]) -> Result<(), StoreError> {
+ Err(self.error.to_store_error())
+ }
+
+ async fn put_many_redacted_phones(
+ &self,
+ _entries: &[RedactedPhoneEntry],
+ ) -> Result<(), StoreError> {
+ Err(self.error.to_store_error())
+ }
+
+ async fn get_contact(&self, _user: &Jid) -> Result<Option<ContactInfo>, StoreError> {
+ Err(self.error.to_store_error())
+ }
+
+ async fn get_all_contacts(&self) -> Result<HashMap<Jid, ContactInfo>, StoreError> {
+ Err(self.error.to_store_error())
+ }
+}
+
+#[async_trait]
+impl ChatSettingsStore for NoopStore {
+ async fn put_muted_until(
+ &self,
+ _chat: &Jid,
+ _muted_until: Option<DateTime<Utc>>,
+ ) -> Result<(), StoreError> {
+ Err(self.error.to_store_error())
+ }
+
+ async fn put_pinned(&self, _chat: &Jid, _pinned: bool) -> Result<(), StoreError> {
+ Err(self.error.to_store_error())
+ }
+
+ async fn put_archived(&self, _chat: &Jid, _archived: bool) -> Result<(), StoreError> {
+ Err(self.error.to_store_error())
+ }
+
+ async fn put_wasa_root_secret_id(
+ &self,
+ _chat: &Jid,
+ _id: &MessageId,
+ ) -> Result<(), StoreError> {
+ Err(self.error.to_store_error())
+ }
+
+ async fn get_wasa_root_secret_id(&self, _chat: &Jid) -> Result<Option<MessageId>, StoreError> {
+ Err(self.error.to_store_error())
+ }
+
+ async fn get_chat_settings(
+ &self,
+ _chat: &Jid,
+ ) -> Result<Option<LocalChatSettings>, StoreError> {
+ Err(self.error.to_store_error())
+ }
+}
+
+#[async_trait]
+impl DeviceContainer for NoopStore {
+ async fn put_device(&self, _store: &Device) -> Result<(), StoreError> {
+ Err(self.error.to_store_error())
+ }
+
+ async fn delete_device(&self, _store: &Device) -> Result<(), StoreError> {
+ Err(self.error.to_store_error())
+ }
+}
+
+#[async_trait]
+impl MsgSecretStore for NoopStore {
+ async fn put_message_secrets(
+ &self,
+ _inserts: &[MessageSecretInsert],
+ ) -> Result<(), StoreError> {
+ Err(self.error.to_store_error())
+ }
+
+ async fn put_message_secret(
+ &self,
+ _chat: &Jid,
+ _sender: &Jid,
+ _id: &MessageId,
+ _secret: Vec<u8>,
+ ) -> Result<(), StoreError> {
+ Err(self.error.to_store_error())
+ }
+
+ async fn get_message_secret(
+ &self,
+ _chat: &Jid,
+ _sender: &Jid,
+ _id: &MessageId,
+ ) -> Result<Option<(Vec<u8>, Jid)>, StoreError> {
+ Err(self.error.to_store_error())
+ }
+}
+
+#[async_trait]
+impl PrivacyTokenStore for NoopStore {
+ async fn put_privacy_tokens(&self, _tokens: &[PrivacyToken]) -> Result<(), StoreError> {
+ Err(self.error.to_store_error())
+ }
+
+ async fn get_privacy_token(&self, _user: &Jid) -> Result<Option<PrivacyToken>, StoreError> {
+ Err(self.error.to_store_error())
+ }
+
+ async fn delete_expired_privacy_tokens(
+ &self,
+ _cutoff: DateTime<Utc>,
+ ) -> Result<u64, StoreError> {
+ Err(self.error.to_store_error())
+ }
+}
+
+#[async_trait]
+impl NctSaltStore for NoopStore {
+ async fn put_nct_salt(&self, _salt: Vec<u8>) -> Result<(), StoreError> {
+ Err(self.error.to_store_error())
+ }
+
+ async fn get_nct_salt(&self) -> Result<Option<Vec<u8>>, StoreError> {
+ Err(self.error.to_store_error())
+ }
+
+ async fn delete_nct_salt(&self) -> Result<(), StoreError> {
+ Err(self.error.to_store_error())
+ }
+}
+
+#[async_trait]
+impl EventBuffer for NoopStore {
+ async fn get_buffered_event(
+ &self,
+ _ciphertext_hash: [u8; 32],
+ ) -> Result<Option<BufferedEvent>, StoreError> {
+ Err(self.error.to_store_error())
+ }
+
+ async fn put_buffered_event(
+ &self,
+ _ciphertext_hash: [u8; 32],
+ _plaintext: Vec<u8>,
+ _server_timestamp: DateTime<Utc>,
+ ) -> Result<(), StoreError> {
+ Err(self.error.to_store_error())
+ }
+
+ async fn do_decryption_txn(&self, _body: DecryptionTransaction<'_>) -> Result<(), StoreError> {
+ Err(self.error.to_store_error())
+ }
+
+ async fn clear_buffered_event_plaintext(
+ &self,
+ _ciphertext_hash: [u8; 32],
+ ) -> Result<(), StoreError> {
+ Err(self.error.to_store_error())
+ }
+
+ async fn delete_old_buffered_hashes(&self) -> Result<(), StoreError> {
+ Err(self.error.to_store_error())
+ }
+
+ async fn get_outgoing_event(
+ &self,
+ _chat_jid: &Jid,
+ _alt_chat_jid: &Jid,
+ _id: &MessageId,
+ ) -> Result<Option<(String, Vec<u8>)>, StoreError> {
+ Err(self.error.to_store_error())
+ }
+
+ async fn add_outgoing_event(
+ &self,
+ _chat_jid: &Jid,
+ _id: &MessageId,
+ _format: &str,
+ _plaintext: Vec<u8>,
+ ) -> Result<(), StoreError> {
+ Err(self.error.to_store_error())
+ }
+
+ async fn delete_old_outgoing_events(&self) -> Result<(), StoreError> {
+ Err(self.error.to_store_error())
+ }
+}
+
+#[async_trait]
+impl LidStore for NoopStore {
+ async fn put_many_lid_mappings(&self, _mappings: &[LidMapping]) -> Result<(), StoreError> {
+ Err(self.error.to_store_error())
+ }
+
+ async fn put_lid_mapping(&self, _lid: &Jid, _jid: &Jid) -> Result<(), StoreError> {
+ Err(self.error.to_store_error())
+ }
+
+ async fn get_pn_for_lid(&self, _lid: &Jid) -> Result<Option<Jid>, StoreError> {
+ Err(self.error.to_store_error())
+ }
+
+ async fn get_lid_for_pn(&self, _pn: &Jid) -> Result<Option<Jid>, StoreError> {
+ Err(self.error.to_store_error())
+ }
+
+ async fn get_many_lids_for_pns(&self, _pns: &[Jid]) -> Result<HashMap<Jid, Jid>, StoreError> {
+ Err(self.error.to_store_error())
+ }
+}
diff --git a/crates/whatsmeow/src/store/sessioncache.rs b/crates/whatsmeow/src/store/sessioncache.rs
new file mode 100644
index 0000000000..fddbf23a08
--- /dev/null
+++ b/crates/whatsmeow/src/store/sessioncache.rs
@@ -0,0 +1,111 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+//
+// Ported from whatsmeow store/sessioncache.go (MPL-2.0, Copyright (c) Tulir Asokan)
+
+use std::collections::HashMap;
+use std::sync::Mutex;
+
+use super::store::{Device, StoreError};
+
+/// One cached session record.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct SessionCacheEntry {
+ /// Changed since it was loaded, so it must be written back.
+ pub dirty: bool,
+ /// The store had a session.
+ pub found: bool,
+ /// The serialized record; `None` for a new session.
+ pub record: Option<Vec<u8>>,
+}
+
+/// Sessions prefetched for encrypting to many devices at once, written back
+/// in one batch.
+///
+/// Go hides the cache in the `context.Context` that libsignal passes back to
+/// the store; the port passes it explicitly to [`Device::signal_store`].
+#[derive(Debug, Default)]
+pub struct SessionCache {
+ entries: Mutex<HashMap<String, SessionCacheEntry>>,
+}
+
+impl SessionCache {
+ fn lock(&self) -> std::sync::MutexGuard<'_, HashMap<String, SessionCacheEntry>> {
+ // A panic while holding the lock can't leave a half-written entry.
+ self.entries
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ }
+
+ /// The cached record of an address: `None` when the address isn't
+ /// cached, `Some(None)` when it is cached as a new session.
+ pub fn get_cached_session(&self, address: &str) -> Option<Option<Vec<u8>>> {
+ self.lock().get(address).map(|entry| entry.record.clone())
+ }
+
+ /// Replaces a cached record and marks it dirty.
+ pub fn put_cached_session(&self, address: &str, record: Vec<u8>) {
+ self.lock().insert(
+ address.to_owned(),
+ SessionCacheEntry {
+ dirty: true,
+ found: true,
+ record: Some(record),
+ },
+ );
+ }
+}
+
+impl Device {
+ /// Prefetches the sessions of the addresses. Returns which of them had a
+ /// session, and the cache to pass to [`Device::signal_store`] and then
+ /// [`Device::put_cached_sessions`].
+ pub async fn with_cached_sessions(
+ &self,
+ addresses: &[String],
+ ) -> Result<(HashMap<String, bool>, Option<SessionCache>), StoreError> {
+ if addresses.is_empty() {
+ return Ok((HashMap::new(), None));
+ }
+ let sessions = self.sessions.get_many_sessions(addresses).await?;
+ let mut existing_sessions = HashMap::with_capacity(sessions.len());
+ let mut wrapped = HashMap::with_capacity(sessions.len());
+ for (address, record) in sessions {
+ let found = record.is_some();
+ existing_sessions.insert(address.clone(), found);
+ wrapped.insert(
+ address,
+ SessionCacheEntry {
+ dirty: false,
+ found,
+ record,
+ },
+ );
+ }
+ Ok((
+ existing_sessions,
+ Some(SessionCache {
+ entries: Mutex::new(wrapped),
+ }),
+ ))
+ }
+
+ /// Writes the cache's changed sessions back to the store and empties it.
+ pub async fn put_cached_sessions(&self, cache: &SessionCache) -> Result<(), StoreError> {
+ let dirty_sessions: HashMap<String, Vec<u8>> = cache
+ .lock()
+ .iter()
+ .filter(|(_, entry)| entry.dirty)
+ .filter_map(|(address, entry)| Some((address.clone(), entry.record.clone()?)))
+ .collect();
+ if !dirty_sessions.is_empty() {
+ self.sessions.put_many_sessions(dirty_sessions).await?;
+ }
+ cache.lock().clear();
+ Ok(())
+ }
+}
+
+#[cfg(test)]
+mod test;
diff --git a/crates/whatsmeow/src/store/sessioncache/test.rs b/crates/whatsmeow/src/store/sessioncache/test.rs
new file mode 100644
index 0000000000..9d3bfce8ea
--- /dev/null
+++ b/crates/whatsmeow/src/store/sessioncache/test.rs
@@ -0,0 +1,100 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+use std::sync::Arc;
+
+use super::*;
+use crate::signal::{CurveSignatures, SignalAddress, SignalProtocolStore};
+use crate::store::MemoryStore;
+
+struct UnusedSignatures;
+
+impl CurveSignatures for UnusedSignatures {
+ fn calculate_signature(&self, _: &[u8; 32], _: &[u8]) -> [u8; 64] {
+ [0; 64]
+ }
+
+ fn verify_signature(&self, _: &[u8; 32], _: &[u8], _: &[u8; 64]) -> bool {
+ false
+ }
+}
+
+#[tokio::test]
+async fn cached_sessions_are_written_back_in_one_batch() {
+ let store = Arc::new(MemoryStore::default());
+ let device = store.new_device(&UnusedSignatures);
+ device
+ .sessions
+ .put_session("111:0", b"existing".to_vec())
+ .await
+ .unwrap();
+
+ let (existing, cache) = device
+ .with_cached_sessions(&["111:0".to_owned(), "222:0".to_owned()])
+ .await
+ .unwrap();
+ assert_eq!(
+ existing,
+ HashMap::from([("111:0".to_owned(), true), ("222:0".to_owned(), false)])
+ );
+ let cache = cache.unwrap();
+ let signal_store = device.signal_store(Some(&cache));
+ let new_address = SignalAddress::new("222".to_owned(), 0);
+ assert_eq!(signal_store.load_session(&new_address).await.unwrap(), None);
+
+ signal_store
+ .store_session(&new_address, b"new".to_vec())
+ .await
+ .unwrap();
+ assert_eq!(
+ signal_store.load_session(&new_address).await.unwrap(),
+ Some(b"new".to_vec())
+ );
+ // Not written through until the cache is flushed.
+ assert_eq!(device.sessions.get_session("222:0").await.unwrap(), None);
+
+ device.put_cached_sessions(&cache).await.unwrap();
+ assert_eq!(
+ device.sessions.get_session("222:0").await.unwrap(),
+ Some(b"new".to_vec())
+ );
+ assert_eq!(
+ device.sessions.get_session("111:0").await.unwrap(),
+ Some(b"existing".to_vec())
+ );
+ assert_eq!(cache.get_cached_session("222:0"), None);
+}
+
+#[tokio::test]
+async fn no_addresses_means_no_cache() {
+ let store = Arc::new(MemoryStore::default());
+ let device = store.new_device(&UnusedSignatures);
+ let (existing, cache) = device.with_cached_sessions(&[]).await.unwrap();
+ assert!(existing.is_empty());
+ assert!(cache.is_none());
+}
+
+#[tokio::test]
+async fn without_a_cache_the_signal_store_writes_through() {
+ let store = Arc::new(MemoryStore::default());
+ let device = store.new_device(&UnusedSignatures);
+ let signal_store = device.signal_store(None);
+ let address = SignalAddress::new("333_1".to_owned(), 2);
+ signal_store
+ .store_session(&address, b"record".to_vec())
+ .await
+ .unwrap();
+ assert_eq!(
+ device.sessions.get_session("333_1:2").await.unwrap(),
+ Some(b"record".to_vec())
+ );
+ assert!(signal_store.contains_session(&address).await.unwrap());
+ assert_eq!(
+ signal_store
+ .load_signed_pre_key(1)
+ .map(|(public, _, _)| public),
+ Some(device.signed_pre_key.key_pair.public)
+ );
+ assert_eq!(signal_store.load_signed_pre_key(2), None);
+}
diff --git a/crates/whatsmeow/src/store/signal.rs b/crates/whatsmeow/src/store/signal.rs
new file mode 100644
index 0000000000..b56eb0420b
--- /dev/null
+++ b/crates/whatsmeow/src/store/signal.rs
@@ -0,0 +1,143 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+//
+// Ported from whatsmeow store/signal.go (MPL-2.0, Copyright (c) Tulir Asokan)
+//
+// Go's `Device` implements libsignal's store interface directly, with
+// `panic("not implemented")` for the methods libsignal never calls on it;
+// those are left out of `SignalProtocolStore`.
+
+use async_trait::async_trait;
+
+use super::sessioncache::SessionCache;
+use super::store::{Device, StoreError};
+use crate::signal::{SenderKeyName, SignalAddress, SignalProtocolStore};
+
+/// A device as libsignal's store, with an optional session cache.
+pub struct DeviceSignalStore<'device> {
+ device: &'device Device,
+ cache: Option<&'device SessionCache>,
+}
+
+impl Device {
+ /// The device as the store a [`crate::signal::SignalProtocol`] reads and
+ /// writes, using the session cache from [`Device::with_cached_sessions`]
+ /// if there is one.
+ pub fn signal_store<'device>(
+ &'device self,
+ cache: Option<&'device SessionCache>,
+ ) -> DeviceSignalStore<'device> {
+ DeviceSignalStore {
+ device: self,
+ cache,
+ }
+ }
+}
+
+#[async_trait]
+impl SignalProtocolStore for DeviceSignalStore<'_> {
+ fn get_identity_key_pair(&self) -> ([u8; 32], [u8; 32]) {
+ let identity_key = &self.device.identity_key;
+ (identity_key.public, identity_key.private)
+ }
+
+ fn get_local_registration_id(&self) -> u32 {
+ self.device.registration_id
+ }
+
+ async fn save_identity(
+ &self,
+ address: &SignalAddress,
+ identity_key: [u8; 32],
+ ) -> Result<(), StoreError> {
+ self.device
+ .identities
+ .put_identity(&address.to_string(), identity_key)
+ .await
+ }
+
+ async fn is_trusted_identity(
+ &self,
+ address: &SignalAddress,
+ identity_key: [u8; 32],
+ ) -> Result<bool, StoreError> {
+ self.device
+ .identities
+ .is_trusted_identity(&address.to_string(), identity_key)
+ .await
+ }
+
+ async fn load_pre_key(&self, id: u32) -> Result<Option<([u8; 32], [u8; 32])>, StoreError> {
+ Ok(self
+ .device
+ .pre_keys
+ .get_pre_key(id)
+ .await?
+ .map(|pre_key| (pre_key.key_pair.public, pre_key.key_pair.private)))
+ }
+
+ async fn remove_pre_key(&self, id: u32) -> Result<(), StoreError> {
+ self.device.pre_keys.remove_pre_key(id).await
+ }
+
+ async fn load_session(&self, address: &SignalAddress) -> Result<Option<Vec<u8>>, StoreError> {
+ let address = address.to_string();
+ if let Some(cached) = self
+ .cache
+ .and_then(|cache| cache.get_cached_session(&address))
+ {
+ return Ok(cached);
+ }
+ self.device.sessions.get_session(&address).await
+ }
+
+ async fn store_session(
+ &self,
+ address: &SignalAddress,
+ record: Vec<u8>,
+ ) -> Result<(), StoreError> {
+ let address = address.to_string();
+ match self.cache {
+ Some(cache) => {
+ cache.put_cached_session(&address, record);
+ Ok(())
+ }
+ None => self.device.sessions.put_session(&address, record).await,
+ }
+ }
+
+ async fn contains_session(&self, address: &SignalAddress) -> Result<bool, StoreError> {
+ self.device.sessions.has_session(&address.to_string()).await
+ }
+
+ fn load_signed_pre_key(&self, id: u32) -> Option<([u8; 32], [u8; 32], [u8; 64])> {
+ let signed_pre_key = &self.device.signed_pre_key;
+ if id != signed_pre_key.key_id {
+ return None;
+ }
+ Some((
+ signed_pre_key.key_pair.public,
+ signed_pre_key.key_pair.private,
+ signed_pre_key.signature?,
+ ))
+ }
+
+ async fn store_sender_key(
+ &self,
+ name: &SenderKeyName,
+ record: Vec<u8>,
+ ) -> Result<(), StoreError> {
+ self.device
+ .sender_keys
+ .put_sender_key(&name.group_id, &name.sender.to_string(), record)
+ .await
+ }
+
+ async fn load_sender_key(&self, name: &SenderKeyName) -> Result<Option<Vec<u8>>, StoreError> {
+ self.device
+ .sender_keys
+ .get_sender_key(&name.group_id, &name.sender.to_string())
+ .await
+ }
+}
diff --git a/crates/whatsmeow/src/store/store.rs b/crates/whatsmeow/src/store/store.rs
new file mode 100644
index 0000000000..8bb8dcb7e2
--- /dev/null
+++ b/crates/whatsmeow/src/store/store.rs
@@ -0,0 +1,618 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+//
+// Ported from whatsmeow store/store.go (MPL-2.0, Copyright (c) Tulir Asokan)
+
+//! The store traits are object safe (a [`Device`] holds `Arc<dyn …>` handles,
+//! as Go holds interfaces), hence `async_trait`. Go's `context.Context`
+//! parameters are dropped: cancellation is dropping the future.
+
+use std::collections::HashMap;
+use std::sync::{Arc, LazyLock};
+
+use async_trait::async_trait;
+use chrono::{DateTime, NaiveDate, Utc};
+use uuid::Uuid;
+
+use super::noop::{NoopError, NoopStore};
+use crate::proto::wa_adv::AdvSignedDeviceIdentity;
+use crate::types::{
+ ContactInfo, DEFAULT_USER_SERVER, HIDDEN_USER_SERVER, Jid, LocalChatSettings, MessageId,
+};
+use crate::util::keys::{KeyPair, PreKey};
+
+/// A store failure.
+#[derive(Debug, thiserror::Error)]
+pub enum StoreError {
+ /// The device was deleted (`ErrDeviceDeleted`).
+ #[error("invalid use of deleted device")]
+ DeviceDeleted,
+ /// The store was never set (the error of Go's `nilStore`).
+ #[error("store is nil")]
+ StoreIsNil,
+ /// The call was invalid, like a LID lookup with a phone number JID.
+ #[error("{0}")]
+ InvalidArgument(String),
+ /// The backing storage failed.
+ #[error("store error: {0:?}")]
+ Internal(rootcause::Report),
+}
+
+impl From<rootcause::Report> for StoreError {
+ fn from(report: rootcause::Report) -> Self {
+ StoreError::Internal(report)
+ }
+}
+
+/// Peer identity keys, keyed by Signal address string.
+#[async_trait]
+pub trait IdentityStore: Send + Sync {
+ /// Remembers a peer's identity key.
+ async fn put_identity(&self, address: &str, key: [u8; 32]) -> Result<(), StoreError>;
+ /// Forgets the identity keys of all devices of a user.
+ async fn delete_all_identities(&self, phone: &str) -> Result<(), StoreError>;
+ /// Forgets one device's identity key.
+ async fn delete_identity(&self, address: &str) -> Result<(), StoreError>;
+ /// Whether the key is the known identity key (or there is none yet).
+ async fn is_trusted_identity(&self, address: &str, key: [u8; 32]) -> Result<bool, StoreError>;
+}
+
+/// Serialized Signal sessions, keyed by Signal address string.
+#[async_trait]
+pub trait SessionStore: Send + Sync {
+ /// One session.
+ async fn get_session(&self, address: &str) -> Result<Option<Vec<u8>>, StoreError>;
+ /// Whether there is a session.
+ async fn has_session(&self, address: &str) -> Result<bool, StoreError>;
+ /// Several sessions, with an entry for every requested address (`None`
+ /// when there is no session), as Go's map holds nil values.
+ async fn get_many_sessions(
+ &self,
+ addresses: &[String],
+ ) -> Result<HashMap<String, Option<Vec<u8>>>, StoreError>;
+ /// Stores one session.
+ async fn put_session(&self, address: &str, session: Vec<u8>) -> Result<(), StoreError>;
+ /// Stores several sessions.
+ async fn put_many_sessions(&self, sessions: HashMap<String, Vec<u8>>)
+ -> Result<(), StoreError>;
+ /// Deletes the sessions of all devices of a user.
+ async fn delete_all_sessions(&self, phone: &str) -> Result<(), StoreError>;
+ /// Deletes one session.
+ async fn delete_session(&self, address: &str) -> Result<(), StoreError>;
+ /// Moves a phone number user's sessions and identities to their LID.
+ async fn migrate_pn_to_lid(&self, pn: &Jid, lid: &Jid) -> Result<(), StoreError>;
+}
+
+/// The local one-time prekeys.
+#[async_trait]
+pub trait PreKeyStore: Send + Sync {
+ /// Prekeys not uploaded yet, generating new ones up to `count`.
+ async fn get_or_gen_pre_keys(&self, count: u32) -> Result<Vec<PreKey>, StoreError>;
+ /// Generates one prekey that counts as uploaded.
+ async fn gen_one_pre_key(&self) -> Result<PreKey, StoreError>;
+ /// One prekey.
+ async fn get_pre_key(&self, id: u32) -> Result<Option<PreKey>, StoreError>;
+ /// Removes a used prekey.
+ async fn remove_pre_key(&self, id: u32) -> Result<(), StoreError>;
+ /// Marks every prekey up to the ID as uploaded.
+ async fn mark_pre_keys_as_uploaded(&self, up_to_id: u32) -> Result<(), StoreError>;
+ /// How many uploaded prekeys are left.
+ async fn uploaded_pre_key_count(&self) -> Result<usize, StoreError>;
+}
+
+/// Serialized group sender keys.
+#[async_trait]
+pub trait SenderKeyStore: Send + Sync {
+ /// Stores the sender key of a user in a group.
+ async fn put_sender_key(
+ &self,
+ group: &str,
+ user: &str,
+ session: Vec<u8>,
+ ) -> Result<(), StoreError>;
+ /// The sender key of a user in a group.
+ async fn get_sender_key(&self, group: &str, user: &str) -> Result<Option<Vec<u8>>, StoreError>;
+}
+
+/// An app state sync key shared by the primary device.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct AppStateSyncKey {
+ /// The key material.
+ pub data: Vec<u8>,
+ /// The serialized key fingerprint.
+ pub fingerprint: Vec<u8>,
+ /// When the key was created, in milliseconds.
+ pub timestamp: i64,
+}
+
+/// App state sync keys, keyed by key ID.
+#[async_trait]
+pub trait AppStateSyncKeyStore: Send + Sync {
+ /// Stores a key.
+ async fn put_app_state_sync_key(
+ &self,
+ id: &[u8],
+ key: AppStateSyncKey,
+ ) -> Result<(), StoreError>;
+ /// One key.
+ async fn get_app_state_sync_key(
+ &self,
+ id: &[u8],
+ ) -> Result<Option<AppStateSyncKey>, StoreError>;
+ /// The ID of the newest key.
+ async fn get_latest_app_state_sync_key_id(&self) -> Result<Option<Vec<u8>>, StoreError>;
+ /// Every key.
+ async fn get_all_app_state_sync_keys(&self) -> Result<Vec<AppStateSyncKey>, StoreError>;
+}
+
+/// The MACs of one app state mutation.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct AppStateMutationMac {
+ /// The MAC of the mutation's index.
+ pub index_mac: Vec<u8>,
+ /// The MAC of the mutation's value.
+ pub value_mac: Vec<u8>,
+}
+
+/// App state versions and mutation MACs, per collection name.
+#[async_trait]
+pub trait AppStateStore: Send + Sync {
+ /// Stores a collection's version and LT hash.
+ async fn put_app_state_version(
+ &self,
+ name: &str,
+ version: u64,
+ hash: [u8; 128],
+ ) -> Result<(), StoreError>;
+ /// A collection's version and LT hash; version 0 and a zero hash when unknown.
+ async fn get_app_state_version(&self, name: &str) -> Result<(u64, [u8; 128]), StoreError>;
+ /// Forgets a collection's version.
+ async fn delete_app_state_version(&self, name: &str) -> Result<(), StoreError>;
+ /// Stores the MACs of mutations at a version.
+ async fn put_app_state_mutation_macs(
+ &self,
+ name: &str,
+ version: u64,
+ mutations: &[AppStateMutationMac],
+ ) -> Result<(), StoreError>;
+ /// Deletes mutation MACs by index MAC.
+ async fn delete_app_state_mutation_macs(
+ &self,
+ name: &str,
+ index_macs: &[Vec<u8>],
+ ) -> Result<(), StoreError>;
+ /// The value MAC of the newest mutation with an index MAC.
+ async fn get_app_state_mutation_mac(
+ &self,
+ name: &str,
+ index_mac: &[u8],
+ ) -> Result<Option<Vec<u8>>, StoreError>;
+}
+
+/// A contact name from the address book.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct ContactEntry {
+ /// The contact.
+ pub jid: Jid,
+ /// The first name.
+ pub first_name: String,
+ /// The full name.
+ pub full_name: String,
+}
+
+/// A redacted phone number of a LID user.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct RedactedPhoneEntry {
+ /// The LID user.
+ pub jid: Jid,
+ /// The phone number in the form "+1∙∙∙∙∙∙∙∙80".
+ pub redacted_phone: String,
+}
+
+/// Contact names.
+#[async_trait]
+pub trait ContactStore: Send + Sync {
+ /// Stores a push name; returns whether it changed and the previous name.
+ async fn put_push_name(
+ &self,
+ user: &Jid,
+ push_name: &str,
+ ) -> Result<(bool, String), StoreError>;
+ /// Stores a business name; returns whether it changed and the previous name.
+ async fn put_business_name(
+ &self,
+ user: &Jid,
+ business_name: &str,
+ ) -> Result<(bool, String), StoreError>;
+ /// Stores an address book name.
+ async fn put_contact_name(
+ &self,
+ user: &Jid,
+ full_name: &str,
+ first_name: &str,
+ ) -> Result<(), StoreError>;
+ /// Stores many address book names.
+ async fn put_all_contact_names(&self, contacts: &[ContactEntry]) -> Result<(), StoreError>;
+ /// Stores many redacted phone numbers.
+ async fn put_many_redacted_phones(
+ &self,
+ entries: &[RedactedPhoneEntry],
+ ) -> Result<(), StoreError>;
+ /// One contact; Go returns `Found: false` where this returns `None`.
+ async fn get_contact(&self, user: &Jid) -> Result<Option<ContactInfo>, StoreError>;
+ /// Every contact.
+ async fn get_all_contacts(&self) -> Result<HashMap<Jid, ContactInfo>, StoreError>;
+}
+
+/// The "muted until" time WhatsApp uses for chats muted forever.
+pub static MUTED_FOREVER: LazyLock<DateTime<Utc>> = LazyLock::new(|| {
+ NaiveDate::from_ymd_opt(9999, 12, 31)
+ .and_then(|date| date.and_hms_nano_opt(23, 59, 59, 999_999_999))
+ .map(|time| time.and_utc())
+ .unwrap_or(DateTime::<Utc>::MAX_UTC)
+});
+
+/// Local chat settings synced through app state.
+#[async_trait]
+pub trait ChatSettingsStore: Send + Sync {
+ /// Stores the mute end; `None` means unmuted (Go's zero time).
+ async fn put_muted_until(
+ &self,
+ chat: &Jid,
+ muted_until: Option<DateTime<Utc>>,
+ ) -> Result<(), StoreError>;
+ /// Stores whether the chat is pinned.
+ async fn put_pinned(&self, chat: &Jid, pinned: bool) -> Result<(), StoreError>;
+ /// Stores whether the chat is archived.
+ async fn put_archived(&self, chat: &Jid, archived: bool) -> Result<(), StoreError>;
+ /// Stores the WASA root secret message ID of a chat.
+ async fn put_wasa_root_secret_id(&self, chat: &Jid, id: &MessageId) -> Result<(), StoreError>;
+ /// The WASA root secret message ID of a chat.
+ async fn get_wasa_root_secret_id(&self, chat: &Jid) -> Result<Option<MessageId>, StoreError>;
+ /// A chat's settings; Go returns `Found: false` where this returns `None`.
+ async fn get_chat_settings(&self, chat: &Jid) -> Result<Option<LocalChatSettings>, StoreError>;
+}
+
+/// Where devices are persisted.
+#[async_trait]
+pub trait DeviceContainer: Send + Sync {
+ /// Stores the device's own data (keys, IDs, names).
+ async fn put_device(&self, store: &Device) -> Result<(), StoreError>;
+ /// Deletes the device and its data.
+ async fn delete_device(&self, store: &Device) -> Result<(), StoreError>;
+}
+
+/// One message secret to store.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct MessageSecretInsert {
+ /// The chat of the message.
+ pub chat: Jid,
+ /// The sender of the message.
+ pub sender: Jid,
+ /// The message ID.
+ pub id: MessageId,
+ /// The secret.
+ pub secret: Vec<u8>,
+}
+
+/// Message secrets (for polls, reactions and edits).
+#[async_trait]
+pub trait MsgSecretStore: Send + Sync {
+ /// Stores many secrets.
+ async fn put_message_secrets(&self, inserts: &[MessageSecretInsert]) -> Result<(), StoreError>;
+ /// Stores one secret.
+ async fn put_message_secret(
+ &self,
+ chat: &Jid,
+ sender: &Jid,
+ id: &MessageId,
+ secret: Vec<u8>,
+ ) -> Result<(), StoreError>;
+ /// A message's secret and the sender it was stored under.
+ async fn get_message_secret(
+ &self,
+ chat: &Jid,
+ sender: &Jid,
+ id: &MessageId,
+ ) -> Result<Option<(Vec<u8>, Jid)>, StoreError>;
+}
+
+/// A privacy token from or for a user.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct PrivacyToken {
+ /// The user.
+ pub user: Jid,
+ /// The token.
+ pub token: Vec<u8>,
+ /// When the token was received.
+ pub timestamp: DateTime<Utc>,
+ /// When the token was sent.
+ pub sender_timestamp: Option<DateTime<Utc>>,
+}
+
+/// Privacy tokens.
+#[async_trait]
+pub trait PrivacyTokenStore: Send + Sync {
+ /// Stores tokens.
+ async fn put_privacy_tokens(&self, tokens: &[PrivacyToken]) -> Result<(), StoreError>;
+ /// One user's token.
+ async fn get_privacy_token(&self, user: &Jid) -> Result<Option<PrivacyToken>, StoreError>;
+ /// Deletes tokens older than the cutoff; returns how many.
+ async fn delete_expired_privacy_tokens(&self, cutoff: DateTime<Utc>)
+ -> Result<u64, StoreError>;
+}
+
+/// The NCT salt.
+#[async_trait]
+pub trait NctSaltStore: Send + Sync {
+ /// Stores the salt.
+ async fn put_nct_salt(&self, salt: Vec<u8>) -> Result<(), StoreError>;
+ /// The salt.
+ async fn get_nct_salt(&self) -> Result<Option<Vec<u8>>, StoreError>;
+ /// Deletes the salt.
+ async fn delete_nct_salt(&self) -> Result<(), StoreError>;
+}
+
+/// A decrypted incoming event, buffered so a redelivery isn't decrypted twice.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct BufferedEvent {
+ /// The decrypted plaintext; empty once cleared.
+ pub plaintext: Vec<u8>,
+ /// When it was buffered.
+ pub insert_time: DateTime<Utc>,
+ /// The server timestamp of the event.
+ pub server_time: DateTime<Utc>,
+}
+
+/// A transaction body for [`EventBuffer::do_decryption_txn`].
+pub type DecryptionTransaction<'body> =
+ std::pin::Pin<Box<dyn std::future::Future<Output = Result<(), StoreError>> + Send + 'body>>;
+
+/// Buffered incoming and outgoing events.
+#[async_trait]
+pub trait EventBuffer: Send + Sync {
+ /// A buffered incoming event by ciphertext hash.
+ async fn get_buffered_event(
+ &self,
+ ciphertext_hash: [u8; 32],
+ ) -> Result<Option<BufferedEvent>, StoreError>;
+ /// Buffers a decrypted incoming event.
+ async fn put_buffered_event(
+ &self,
+ ciphertext_hash: [u8; 32],
+ plaintext: Vec<u8>,
+ server_timestamp: DateTime<Utc>,
+ ) -> Result<(), StoreError>;
+ /// Runs the decryption of an event in one transaction.
+ ///
+ /// Go passes the transaction to the body through its context; there is no
+ /// equivalent yet, so implementations can only run the body. Revisit when
+ /// porting message decryption.
+ async fn do_decryption_txn(&self, body: DecryptionTransaction<'_>) -> Result<(), StoreError>;
+ /// Clears a buffered event's plaintext once it is handled.
+ async fn clear_buffered_event_plaintext(
+ &self,
+ ciphertext_hash: [u8; 32],
+ ) -> Result<(), StoreError>;
+ /// Deletes old buffered hashes.
+ async fn delete_old_buffered_hashes(&self) -> Result<(), StoreError>;
+ /// A sent event's format and plaintext, by either chat JID.
+ async fn get_outgoing_event(
+ &self,
+ chat_jid: &Jid,
+ alt_chat_jid: &Jid,
+ id: &MessageId,
+ ) -> Result<Option<(String, Vec<u8>)>, StoreError>;
+ /// Remembers a sent event for retries.
+ async fn add_outgoing_event(
+ &self,
+ chat_jid: &Jid,
+ id: &MessageId,
+ format: &str,
+ plaintext: Vec<u8>,
+ ) -> Result<(), StoreError>;
+ /// Deletes old sent events.
+ async fn delete_old_outgoing_events(&self) -> Result<(), StoreError>;
+}
+
+/// A LID and the phone number JID it belongs to.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct LidMapping {
+ /// The LID.
+ pub lid: Jid,
+ /// The phone number JID.
+ pub pn: Jid,
+}
+
+/// LID ↔ phone number mappings, shared by all devices.
+#[async_trait]
+pub trait LidStore: Send + Sync {
+ /// Stores many mappings.
+ async fn put_many_lid_mappings(&self, mappings: &[LidMapping]) -> Result<(), StoreError>;
+ /// Stores one mapping.
+ async fn put_lid_mapping(&self, lid: &Jid, jid: &Jid) -> Result<(), StoreError>;
+ /// The phone number JID of a LID.
+ async fn get_pn_for_lid(&self, lid: &Jid) -> Result<Option<Jid>, StoreError>;
+ /// The LID of a phone number JID.
+ async fn get_lid_for_pn(&self, pn: &Jid) -> Result<Option<Jid>, StoreError>;
+ /// The LIDs of many phone number JIDs that have one.
+ async fn get_many_lids_for_pns(&self, pns: &[Jid]) -> Result<HashMap<Jid, Jid>, StoreError>;
+}
+
+/// Every store that belongs to one device.
+pub trait AllSessionSpecificStores:
+ IdentityStore
+ + SessionStore
+ + PreKeyStore
+ + SenderKeyStore
+ + AppStateSyncKeyStore
+ + AppStateStore
+ + ContactStore
+ + ChatSettingsStore
+ + MsgSecretStore
+ + PrivacyTokenStore
+ + NctSaltStore
+ + EventBuffer
+{
+}
+
+impl<Store> AllSessionSpecificStores for Store where
+ Store: IdentityStore
+ + SessionStore
+ + PreKeyStore
+ + SenderKeyStore
+ + AppStateSyncKeyStore
+ + AppStateStore
+ + ContactStore
+ + ChatSettingsStore
+ + MsgSecretStore
+ + PrivacyTokenStore
+ + NctSaltStore
+ + EventBuffer
+{
+}
+
+/// Every store shared by all devices.
+pub trait AllGlobalStores: LidStore {}
+
+impl<Store: LidStore> AllGlobalStores for Store {}
+
+/// Every store.
+pub trait AllStores: AllSessionSpecificStores + AllGlobalStores {}
+
+impl<Store: AllSessionSpecificStores + AllGlobalStores> AllStores for Store {}
+
+/// One linked device: its keys, identity, and stores.
+pub struct Device {
+ /// The static key of the noise handshake.
+ pub noise_key: KeyPair,
+ /// The Signal identity key.
+ pub identity_key: KeyPair,
+ /// The signed prekey.
+ pub signed_pre_key: PreKey,
+ /// The Signal registration ID.
+ pub registration_id: u32,
+ /// The secret for verifying the account signature while pairing.
+ pub adv_secret_key: Vec<u8>,
+
+ /// The device's JID, once paired.
+ pub id: Option<Jid>,
+ /// The device's LID, once known.
+ pub lid: Jid,
+
+ /// The account's signature of this device.
+ pub account: Option<AdvSignedDeviceIdentity>,
+ /// The platform of the primary device.
+ pub platform: String,
+ /// The business name of the account.
+ pub business_name: String,
+ /// The push name of the account.
+ pub push_name: String,
+
+ /// When the account migrated to LIDs.
+ pub lid_migration_timestamp: i64,
+ /// The companion meta nonce.
+ pub companion_meta_nonce: String,
+
+ /// The Facebook UUID (Messenger/Instagram only).
+ pub facebook_uuid: Option<Uuid>,
+
+ /// Whether the device was loaded from or saved to the container.
+ pub initialized: bool,
+ /// Whether the device was deleted.
+ pub deleted: bool,
+ /// Peer identity keys.
+ pub identities: Arc<dyn IdentityStore>,
+ /// Signal sessions.
+ pub sessions: Arc<dyn SessionStore>,
+ /// One-time prekeys.
+ pub pre_keys: Arc<dyn PreKeyStore>,
+ /// Group sender keys.
+ pub sender_keys: Arc<dyn SenderKeyStore>,
+ /// App state sync keys.
+ pub app_state_keys: Arc<dyn AppStateSyncKeyStore>,
+ /// App state versions.
+ pub app_state: Arc<dyn AppStateStore>,
+ /// Contacts.
+ pub contacts: Arc<dyn ContactStore>,
+ /// Chat settings.
+ pub chat_settings: Arc<dyn ChatSettingsStore>,
+ /// Message secrets.
+ pub msg_secrets: Arc<dyn MsgSecretStore>,
+ /// Privacy tokens.
+ pub privacy_tokens: Arc<dyn PrivacyTokenStore>,
+ /// The NCT salt.
+ pub nct_salt: Arc<dyn NctSaltStore>,
+ /// Buffered events.
+ pub event_buffer: Arc<dyn EventBuffer>,
+ /// LID mappings.
+ pub lids: Arc<dyn LidStore>,
+ /// Where the device itself is saved.
+ pub container: Arc<dyn DeviceContainer>,
+}
+
+impl Device {
+ /// The device's JID, or the empty JID before pairing.
+ pub fn get_jid(&self) -> Jid {
+ self.id.clone().unwrap_or_default()
+ }
+
+ /// The device's LID, or the empty JID when unknown.
+ pub fn get_lid(&self) -> Jid {
+ self.lid.clone()
+ }
+
+ /// Saves the device's own data to its container.
+ pub async fn save(&self) -> Result<(), StoreError> {
+ if self.deleted {
+ return Err(StoreError::DeviceDeleted);
+ }
+ self.container.put_device(self).await
+ }
+
+ /// Deletes the device from its container and makes every store fail.
+ pub async fn delete(&mut self) -> Result<(), StoreError> {
+ if self.deleted {
+ return Ok(());
+ }
+ self.container.delete_device(self).await?;
+ self.id = None;
+ self.lid = Jid::default();
+ self.deleted = true;
+ self.set_all_stores(Arc::new(NoopStore {
+ error: NoopError::DeviceDeleted,
+ }));
+ Ok(())
+ }
+
+ /// Uses one store for every per-device store.
+ pub fn set_all_stores(&mut self, store: Arc<dyn AllSessionSpecificStores>) {
+ self.identities = store.clone();
+ self.sessions = store.clone();
+ self.pre_keys = store.clone();
+ self.sender_keys = store.clone();
+ self.app_state_keys = store.clone();
+ self.app_state = store.clone();
+ self.contacts = store.clone();
+ self.chat_settings = store.clone();
+ self.msg_secrets = store.clone();
+ self.privacy_tokens = store.clone();
+ self.nct_salt = store.clone();
+ self.event_buffer = store;
+ }
+
+ /// The other identity of a user: the LID of a phone number JID or the
+ /// phone number JID of a LID. `None` for other servers or no mapping;
+ /// Go returns the empty JID.
+ pub async fn get_alt_jid(&self, jid: &Jid) -> Result<Option<Jid>, StoreError> {
+ match jid.server.as_str() {
+ DEFAULT_USER_SERVER => self.lids.get_lid_for_pn(jid).await,
+ HIDDEN_USER_SERVER => self.lids.get_pn_for_lid(jid).await,
+ _ => Ok(None),
+ }
+ }
+}
+
+#[cfg(test)]
+mod test;
diff --git a/crates/whatsmeow/src/store/store/test.rs b/crates/whatsmeow/src/store/store/test.rs
new file mode 100644
index 0000000000..d752ed7e67
--- /dev/null
+++ b/crates/whatsmeow/src/store/store/test.rs
@@ -0,0 +1,80 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+use std::sync::Arc;
+
+use super::*;
+use crate::signal::CurveSignatures;
+use crate::store::MemoryStore;
+use crate::types::{DEFAULT_USER_SERVER, HIDDEN_USER_SERVER, new_jid};
+
+struct UnusedSignatures;
+
+impl CurveSignatures for UnusedSignatures {
+ fn calculate_signature(&self, _: &[u8; 32], _: &[u8]) -> [u8; 64] {
+ [0; 64]
+ }
+
+ fn verify_signature(&self, _: &[u8; 32], _: &[u8], _: &[u8; 64]) -> bool {
+ false
+ }
+}
+
+#[tokio::test]
+async fn save_requires_a_jid_and_delete_disables_every_store() {
+ let store = Arc::new(MemoryStore::default());
+ let mut device = store.new_device(&UnusedSignatures);
+ assert!(matches!(
+ device.save().await,
+ Err(StoreError::InvalidArgument(_))
+ ));
+
+ let jid = new_jid("1234567890", DEFAULT_USER_SERVER);
+ device.id = Some(jid.clone());
+ device.save().await.unwrap();
+ assert_eq!(store.saved_devices(), vec![jid.clone()]);
+ assert_eq!(device.get_jid(), jid);
+
+ device.delete().await.unwrap();
+ assert!(store.saved_devices().is_empty());
+ assert!(device.deleted);
+ assert_eq!(device.get_jid(), Jid::default());
+ assert!(matches!(
+ device.sessions.get_session("1:0").await,
+ Err(StoreError::DeviceDeleted)
+ ));
+ assert!(matches!(
+ device.save().await,
+ Err(StoreError::DeviceDeleted)
+ ));
+ // Deleting twice is a no-op.
+ device.delete().await.unwrap();
+}
+
+#[tokio::test]
+async fn get_alt_jid_maps_between_phone_numbers_and_lids() {
+ let store = Arc::new(MemoryStore::default());
+ let device = store.new_device(&UnusedSignatures);
+ let pn = new_jid("1234567890", DEFAULT_USER_SERVER);
+ let lid = new_jid("98765432101234", HIDDEN_USER_SERVER);
+ device.lids.put_lid_mapping(&lid, &pn).await.unwrap();
+
+ assert_eq!(device.get_alt_jid(&pn).await.unwrap(), Some(lid.clone()));
+ assert_eq!(device.get_alt_jid(&lid).await.unwrap(), Some(pn));
+ assert_eq!(
+ device
+ .get_alt_jid(&new_jid("120363012345678901", "g.us"))
+ .await
+ .unwrap(),
+ None
+ );
+}
+
+#[test]
+fn muted_forever_is_the_end_of_year_9999() {
+ assert_eq!(
+ MUTED_FOREVER.to_rfc3339(),
+ "9999-12-31T23:59:59.999999999+00:00"
+ );
+}
diff --git a/crates/whatsmeow/src/tctoken.rs b/crates/whatsmeow/src/tctoken.rs
new file mode 100644
index 0000000000..e4403e3a27
--- /dev/null
+++ b/crates/whatsmeow/src/tctoken.rs
@@ -0,0 +1,243 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+//
+// Ported from whatsmeow tctoken.go (MPL-2.0, Copyright (c) Tulir Asokan)
+
+//! Trusted contact (privacy) tokens: when they expire, and issuing new ones.
+
+use std::collections::HashMap;
+use std::sync::Arc;
+use std::time::Duration;
+
+use chrono::{DateTime, Utc};
+
+use crate::binary::{Attrs, Node, NodeContent};
+use crate::client::{Client, lock};
+use crate::errors::ClientError;
+use crate::request::{InfoQuery, IqType};
+use crate::types::{DEFAULT_USER_SERVER, HIDDEN_USER_SERVER, Jid, PSA_JID, SERVER_JID};
+
+/// The duration of one bucket in seconds (7 days, AB prop `tctoken_duration`).
+const TC_TOKEN_BUCKET_DURATION: i64 = 604_800;
+/// The number of rolling buckets (~28 days, AB prop `tctoken_num_buckets`).
+const TC_TOKEN_NUM_BUCKETS: i64 = 4;
+const TC_TOKEN_DB_PRUNE_INTERVAL: Duration = Duration::from_secs(24 * 60 * 60);
+
+/// The in-memory sender timestamps of issued tokens, with the last cleanup.
+#[derive(Default)]
+pub(crate) struct TcTokenSenderTimestamps {
+ timestamps: HashMap<Jid, DateTime<Utc>>,
+ last_cleanup: Option<DateTime<Utc>>,
+}
+
+fn timestamp(seconds: i64) -> DateTime<Utc> {
+ DateTime::from_timestamp(seconds, 0).unwrap_or_default()
+}
+
+pub(crate) fn current_tc_token_cutoff_timestamp() -> DateTime<Utc> {
+ let current_bucket = Utc::now().timestamp() / TC_TOKEN_BUCKET_DURATION;
+ let cutoff_bucket = current_bucket - (TC_TOKEN_NUM_BUCKETS - 1);
+ timestamp(cutoff_bucket * TC_TOKEN_BUCKET_DURATION)
+}
+
+/// Whether a token received at the timestamp has expired; `None` is Go's zero time.
+pub(crate) fn is_tc_token_expired(timestamp: Option<DateTime<Utc>>) -> bool {
+ match timestamp {
+ None => true,
+ Some(timestamp) => timestamp < current_tc_token_cutoff_timestamp(),
+ }
+}
+
+/// Whether the current bucket is newer than the bucket of the last issuance.
+pub(crate) fn should_send_new_tc_token(sender_timestamp: Option<DateTime<Utc>>) -> bool {
+ match sender_timestamp {
+ None => true,
+ Some(sender_timestamp) => {
+ Utc::now().timestamp() / TC_TOKEN_BUCKET_DURATION
+ > sender_timestamp.timestamp() / TC_TOKEN_BUCKET_DURATION
+ }
+ }
+}
+
+pub(crate) fn should_send_tc_token_in_chat_action(jid: &Jid) -> bool {
+ let jid = jid.to_non_ad();
+ (jid.server == DEFAULT_USER_SERVER || jid.server == HIDDEN_USER_SERVER)
+ && jid.user != PSA_JID.user
+ && !jid.is_bot()
+}
+
+impl Client {
+ pub(crate) async fn resolve_tc_token_storage_lid(&self, jid: &Jid) -> Jid {
+ let storage_jid = jid.to_non_ad();
+ if storage_jid.server != DEFAULT_USER_SERVER {
+ return storage_jid;
+ }
+ let lids = Arc::clone(&self.store.read().await.lids);
+ match lids.get_lid_for_pn(&storage_jid).await {
+ Err(error) => {
+ tracing::debug!(error = %error, "failed to resolve LID for tctoken JID");
+ storage_jid
+ }
+ Ok(None) => storage_jid,
+ Ok(Some(lid)) if lid.is_empty() => storage_jid,
+ Ok(Some(lid)) => lid.to_non_ad(),
+ }
+ }
+
+ pub(crate) fn get_tc_token_sender_ts(&self, jid: &Jid) -> Option<DateTime<Utc>> {
+ lock(&self.tc_token_sender_ts)
+ .timestamps
+ .get(&jid.to_non_ad())
+ .copied()
+ }
+
+ pub(crate) fn validate_and_set_tc_token_sender_ts(
+ &self,
+ jid: &Jid,
+ stored_sender_timestamp: Option<DateTime<Utc>>,
+ ) -> bool {
+ let mut state = lock(&self.tc_token_sender_ts);
+ let key = jid.to_non_ad();
+ if state.timestamps.contains_key(&key) {
+ return true;
+ }
+ let Some(stored) = stored_sender_timestamp else {
+ return false;
+ };
+ if stored < current_tc_token_cutoff_timestamp() {
+ return false;
+ }
+ state.timestamps.insert(key, stored);
+ unlocked_cleanup_tc_token_sender_ts_map(&mut state);
+ true
+ }
+
+ pub(crate) fn set_tc_token_sender_ts(&self, jid: &Jid, sender_timestamp: DateTime<Utc>) {
+ let mut state = lock(&self.tc_token_sender_ts);
+ state.timestamps.insert(jid.to_non_ad(), sender_timestamp);
+ unlocked_cleanup_tc_token_sender_ts_map(&mut state);
+ }
+
+ /// A stored, unexpired token for the user, if there is one.
+ pub(crate) async fn ensure_tc_token(&self, jid: &Jid) -> Result<Option<Vec<u8>>, ClientError> {
+ if self.get_own_id().await.is_empty() {
+ return Err(ClientError::NotLoggedIn);
+ }
+ self.delete_expired_privacy_tokens().await;
+ let storage_jid = self.resolve_tc_token_storage_lid(jid).await;
+ let privacy_tokens = Arc::clone(&self.store.read().await.privacy_tokens);
+ let existing = privacy_tokens
+ .get_privacy_token(&storage_jid)
+ .await
+ .map_err(|error| ClientError::from(error).wrap("failed to get privacy token"))?;
+ let Some(existing) = existing else {
+ return Ok(None);
+ };
+ self.validate_and_set_tc_token_sender_ts(&storage_jid, existing.sender_timestamp);
+ if !existing.token.is_empty() && !is_tc_token_expired(Some(existing.timestamp)) {
+ return Ok(Some(existing.token));
+ }
+ Ok(None)
+ }
+
+ /// Deletes expired tokens from the store, at most once a day.
+ pub(crate) async fn delete_expired_privacy_tokens(&self) {
+ let Ok(mut last_prune) = self.tc_token_db_prune.try_lock() else {
+ return;
+ };
+ if last_prune.is_some_and(|last| last.elapsed() < TC_TOKEN_DB_PRUNE_INTERVAL) {
+ return;
+ }
+ *last_prune = Some(tokio::time::Instant::now());
+ drop(last_prune);
+ let privacy_tokens = Arc::clone(&self.store.read().await.privacy_tokens);
+ self.spawn(async move {
+ match privacy_tokens
+ .delete_expired_privacy_tokens(current_tc_token_cutoff_timestamp())
+ .await
+ {
+ Err(error) => {
+ tracing::warn!(error = %error, "failed to remove expired tctokens from store")
+ }
+ Ok(deleted) if deleted > 0 => {
+ tracing::debug!(deleted, "removed expired tctokens from store")
+ }
+ Ok(_) => {}
+ }
+ });
+ }
+
+ /// Issues a token to the user and remembers when. Only called when a
+ /// bucket boundary was crossed since the last issuance.
+ pub(crate) async fn issue_privacy_token_and_save(
+ &self,
+ jid: Jid,
+ sender_timestamp: DateTime<Utc>,
+ ) {
+ let storage_jid = jid.to_non_ad();
+ if let Err(error) = self
+ .issue_privacy_token(&storage_jid, sender_timestamp)
+ .await
+ {
+ tracing::error!(error = %error, "failed to issue privacy token");
+ return;
+ }
+ self.set_tc_token_sender_ts(&storage_jid, sender_timestamp);
+ let privacy_tokens = Arc::clone(&self.store.read().await.privacy_tokens);
+ let existing = match privacy_tokens.get_privacy_token(&storage_jid).await {
+ Err(error) => {
+ tracing::error!(error = %error, "failed to load tctoken while persisting sender timestamp");
+ return;
+ }
+ Ok(existing) => existing,
+ };
+ let Some(mut existing) = existing.filter(|existing| !existing.token.is_empty()) else {
+ return;
+ };
+ existing.sender_timestamp = Some(sender_timestamp);
+ if let Err(error) = privacy_tokens.put_privacy_tokens(&[existing]).await {
+ tracing::error!(error = %error, "failed to persist privacy token sender timestamp");
+ }
+ }
+
+ async fn issue_privacy_token(
+ &self,
+ jid: &Jid,
+ timestamp: DateTime<Utc>,
+ ) -> Result<Node, ClientError> {
+ self.send_iq(InfoQuery {
+ namespace: "privacy",
+ r#type: IqType::Set,
+ to: SERVER_JID.clone(),
+ content: Some(NodeContent::Nodes(vec![Node {
+ tag: "tokens".to_owned(),
+ attrs: Attrs::new(),
+ content: Some(NodeContent::Nodes(vec![Node {
+ tag: "token".to_owned(),
+ attrs: Attrs::from([
+ ("jid".to_owned(), jid.to_non_ad().into()),
+ ("t".to_owned(), timestamp.timestamp().to_string().into()),
+ ("type".to_owned(), "trusted_contact".into()),
+ ]),
+ content: None,
+ }])),
+ }])),
+ ..Default::default()
+ })
+ .await
+ }
+}
+
+fn unlocked_cleanup_tc_token_sender_ts_map(state: &mut TcTokenSenderTimestamps) {
+ let now = Utc::now();
+ if state
+ .last_cleanup
+ .is_some_and(|last| (now - last).num_seconds() < TC_TOKEN_BUCKET_DURATION)
+ {
+ return;
+ }
+ state.last_cleanup = Some(now);
+ let cutoff = current_tc_token_cutoff_timestamp();
+ state.timestamps.retain(|_, timestamp| *timestamp >= cutoff);
+}
diff --git a/crates/whatsmeow/src/testing.rs b/crates/whatsmeow/src/testing.rs
new file mode 100644
index 0000000000..c6a5483366
--- /dev/null
+++ b/crates/whatsmeow/src/testing.rs
@@ -0,0 +1,584 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+//! Test doubles: a fake WhatsApp server and a fake Signal implementation.
+//!
+//! Not a port of a Go file; whatsmeow has no test doubles. Built for the
+//! crate's own tests and, behind the `testing` feature, for services that
+//! drive a [`Client`](crate::Client) in their tests. Nothing here talks to
+//! the network: connections are in-memory websockets.
+//!
+//! The fake server plays the noise responder with a certificate chain signed
+//! by [`FakeSignatures`], so the client must use a [`Signal`](crate::Signal)
+//! whose signatures are fake too ([`FakeSignal`]).
+
+use std::sync::Arc;
+
+use aes_gcm::Aes256Gcm;
+use async_trait::async_trait;
+use futures::{SinkExt, StreamExt};
+use prost::Message;
+use sha2::{Digest, Sha256};
+use tokio::io::DuplexStream;
+use tokio::sync::mpsc;
+use tokio_tungstenite::WebSocketStream;
+use tokio_tungstenite::tungstenite::Message as WebSocketMessage;
+use tokio_tungstenite::tungstenite::protocol::Role;
+
+use crate::binary::{AttributeValue, Attrs, Node, NodeContent, marshal, unmarshal, unpack};
+use crate::client::Dialer;
+use crate::handshake::{WA_CERT_ISSUER_SERIAL, WA_CERT_PUB_KEY};
+use crate::proto::wa_cert::CertChain;
+use crate::proto::wa_cert::cert_chain::NoiseCertificate;
+use crate::proto::wa_cert::cert_chain::noise_certificate::Details;
+use crate::proto::wa_wa6::{ClientPayload, HandshakeMessage, handshake_message};
+use crate::signal::{
+ CiphertextMessage, CiphertextType, CurveSignatures, PreKeyBundle, SenderKeyName, SignalAddress,
+ SignalError, SignalProtocol, SignalProtocolStore,
+};
+use crate::socket::{
+ FrameEvent, FrameSocket, NOISE_START_PATTERN, NoiseHandshake, SocketError, WA_CONN_HEADER,
+ generate_iv,
+};
+use crate::types::{Jid, SERVER_JID};
+use crate::util::gcmutil;
+use crate::util::keys::{KeyPair, new_key_pair, new_key_pair_from_private_key};
+
+/// A stand-in for XEdDSA: the signature is SHA-256 of the public key and the
+/// message, twice. Signing derives the public key from the private key, so
+/// signatures made here verify here, and only here.
+#[derive(Clone, Copy, Debug, Default)]
+pub struct FakeSignatures;
+
+/// The fake signature of a message under a public key.
+pub fn fake_signature(public_key: &[u8; 32], message: &[u8]) -> [u8; 64] {
+ let digest: [u8; 32] = Sha256::new()
+ .chain_update(public_key)
+ .chain_update(message)
+ .finalize()
+ .into();
+ let mut signature = [0; 64];
+ signature[..32].copy_from_slice(&digest);
+ signature[32..].copy_from_slice(&digest);
+ signature
+}
+
+impl CurveSignatures for FakeSignatures {
+ fn calculate_signature(&self, private_key: &[u8; 32], message: &[u8]) -> [u8; 64] {
+ fake_signature(&new_key_pair_from_private_key(*private_key).public, message)
+ }
+
+ fn verify_signature(
+ &self,
+ public_key: &[u8; 32],
+ message: &[u8],
+ signature: &[u8; 64],
+ ) -> bool {
+ fake_signature(public_key, message) == *signature
+ }
+}
+
+const FAKE_DIRECT_PREFIX: &[u8] = b"FAKE1";
+const FAKE_GROUP_PREFIX: &[u8] = b"FAKEG";
+const FAKE_SESSION: &[u8] = b"fake-session";
+const FAKE_SENDER_KEY: &[u8] = b"fake-sender-key";
+
+/// A fake Signal protocol: "ciphertexts" are the sender's identity key and
+/// the plaintext behind a marker, sessions and sender keys are marker
+/// records. It exercises the client's session, prekey and sender key
+/// bookkeeping through the real [`SignalProtocolStore`] without any
+/// cryptography.
+#[derive(Clone, Copy, Debug, Default)]
+pub struct FakeSignal;
+
+impl CurveSignatures for FakeSignal {
+ fn calculate_signature(&self, private_key: &[u8; 32], message: &[u8]) -> [u8; 64] {
+ FakeSignatures.calculate_signature(private_key, message)
+ }
+
+ fn verify_signature(
+ &self,
+ public_key: &[u8; 32],
+ message: &[u8],
+ signature: &[u8; 64],
+ ) -> bool {
+ FakeSignatures.verify_signature(public_key, message, signature)
+ }
+}
+
+fn fake_error(message: &str) -> SignalError {
+ SignalError::Internal(rootcause::report!("fake signal: {}", message).into_dynamic())
+}
+
+/// Builds a fake direct ciphertext from a sender identity key.
+pub fn fake_direct_ciphertext(sender_identity: &[u8; 32], plaintext: &[u8]) -> Vec<u8> {
+ [FAKE_DIRECT_PREFIX, sender_identity, plaintext].concat()
+}
+
+/// Builds a fake group ciphertext.
+pub fn fake_group_ciphertext(plaintext: &[u8]) -> Vec<u8> {
+ [FAKE_GROUP_PREFIX, plaintext].concat()
+}
+
+/// Builds a fake sender key distribution message for a group and sender.
+pub fn fake_sender_key_distribution_message(name: &SenderKeyName) -> Vec<u8> {
+ format!("SKDM:{}:{}", name.group_id, name.sender).into_bytes()
+}
+
+#[async_trait]
+impl SignalProtocol for FakeSignal {
+ async fn process_bundle(
+ &self,
+ store: &dyn SignalProtocolStore,
+ address: &SignalAddress,
+ bundle: &PreKeyBundle,
+ ) -> Result<(), SignalError> {
+ if !store
+ .is_trusted_identity(address, bundle.identity_key)
+ .await?
+ {
+ return Err(SignalError::UntrustedIdentity);
+ }
+ store.save_identity(address, bundle.identity_key).await?;
+ store.store_session(address, b"fresh".to_vec()).await?;
+ Ok(())
+ }
+
+ async fn encrypt(
+ &self,
+ store: &dyn SignalProtocolStore,
+ address: &SignalAddress,
+ plaintext: &[u8],
+ ) -> Result<CiphertextMessage, SignalError> {
+ let session = store
+ .load_session(address)
+ .await?
+ .ok_or_else(|| fake_error("no session"))?;
+ let kind = if session == b"fresh" {
+ CiphertextType::PreKey
+ } else {
+ CiphertextType::Whisper
+ };
+ let (identity, _) = store.get_identity_key_pair();
+ Ok(CiphertextMessage {
+ kind,
+ serialized: fake_direct_ciphertext(&identity, plaintext),
+ })
+ }
+
+ async fn decrypt_pre_key_message(
+ &self,
+ store: &dyn SignalProtocolStore,
+ address: &SignalAddress,
+ ciphertext: &[u8],
+ ) -> Result<Vec<u8>, SignalError> {
+ let (identity, plaintext) = split_direct(ciphertext)?;
+ if !store.is_trusted_identity(address, identity).await? {
+ return Err(SignalError::UntrustedIdentity);
+ }
+ store.save_identity(address, identity).await?;
+ store.store_session(address, FAKE_SESSION.to_vec()).await?;
+ Ok(plaintext)
+ }
+
+ async fn decrypt_message(
+ &self,
+ store: &dyn SignalProtocolStore,
+ address: &SignalAddress,
+ ciphertext: &[u8],
+ ) -> Result<Vec<u8>, SignalError> {
+ if store.load_session(address).await?.is_none() {
+ return Err(fake_error("no session"));
+ }
+ let (_, plaintext) = split_direct(ciphertext)?;
+ Ok(plaintext)
+ }
+
+ async fn create_sender_key_distribution_message(
+ &self,
+ store: &dyn SignalProtocolStore,
+ name: &SenderKeyName,
+ ) -> Result<Vec<u8>, SignalError> {
+ if store.load_sender_key(name).await?.is_none() {
+ store
+ .store_sender_key(name, FAKE_SENDER_KEY.to_vec())
+ .await?;
+ }
+ Ok(fake_sender_key_distribution_message(name))
+ }
+
+ async fn process_sender_key_distribution_message(
+ &self,
+ store: &dyn SignalProtocolStore,
+ name: &SenderKeyName,
+ message: &[u8],
+ ) -> Result<(), SignalError> {
+ if !message.starts_with(b"SKDM:") {
+ return Err(fake_error("not a fake sender key distribution message"));
+ }
+ store.store_sender_key(name, message.to_vec()).await?;
+ Ok(())
+ }
+
+ async fn group_encrypt(
+ &self,
+ store: &dyn SignalProtocolStore,
+ name: &SenderKeyName,
+ plaintext: &[u8],
+ ) -> Result<Vec<u8>, SignalError> {
+ if store.load_sender_key(name).await?.is_none() {
+ return Err(SignalError::NoSenderKeyForUser);
+ }
+ Ok(fake_group_ciphertext(plaintext))
+ }
+
+ async fn group_decrypt(
+ &self,
+ store: &dyn SignalProtocolStore,
+ name: &SenderKeyName,
+ ciphertext: &[u8],
+ ) -> Result<Vec<u8>, SignalError> {
+ if store.load_sender_key(name).await?.is_none() {
+ return Err(SignalError::NoSenderKeyForUser);
+ }
+ ciphertext
+ .strip_prefix(FAKE_GROUP_PREFIX)
+ .map(<[u8]>::to_vec)
+ .ok_or_else(|| fake_error("not a fake group ciphertext"))
+ }
+}
+
+fn split_direct(ciphertext: &[u8]) -> Result<([u8; 32], Vec<u8>), SignalError> {
+ let rest = ciphertext
+ .strip_prefix(FAKE_DIRECT_PREFIX)
+ .ok_or_else(|| fake_error("not a fake ciphertext"))?;
+ if rest.len() < 32 {
+ return Err(fake_error("fake ciphertext too short"));
+ }
+ let (identity, plaintext) = rest.split_at(32);
+ let identity = <[u8; 32]>::try_from(identity).map_err(|_| fake_error("bad identity"))?;
+ Ok((identity, plaintext.to_vec()))
+}
+
+/// The key the fake intermediate certificate is issued to.
+const INTERMEDIATE_KEY: [u8; 32] = [0x42; 32];
+
+fn certificate_chain(leaf_key: &[u8; 32]) -> Vec<u8> {
+ const NOT_BEFORE: u64 = 1_600_000_000;
+ const NOT_AFTER: u64 = 4_000_000_000;
+ let intermediate_details = Details {
+ serial: Some(7),
+ issuer_serial: Some(WA_CERT_ISSUER_SERIAL),
+ key: Some(INTERMEDIATE_KEY.to_vec()),
+ not_before: Some(NOT_BEFORE),
+ not_after: Some(NOT_AFTER),
+ }
+ .encode_to_vec();
+ let leaf_details = Details {
+ serial: Some(8),
+ issuer_serial: Some(7),
+ key: Some(leaf_key.to_vec()),
+ not_before: Some(NOT_BEFORE),
+ not_after: Some(NOT_AFTER),
+ }
+ .encode_to_vec();
+ CertChain {
+ intermediate: Some(NoiseCertificate {
+ signature: Some(fake_signature(&WA_CERT_PUB_KEY, &intermediate_details).to_vec()),
+ details: Some(intermediate_details),
+ }),
+ leaf: Some(NoiseCertificate {
+ signature: Some(fake_signature(&INTERMEDIATE_KEY, &leaf_details).to_vec()),
+ details: Some(leaf_details),
+ }),
+ }
+ .encode_to_vec()
+}
+
+/// A fake WhatsApp server. Hand [`FakeServer::dialer`] to the client config;
+/// every dial shows up in [`FakeServer::accept`] once the noise handshake is
+/// done.
+pub struct FakeServer {
+ dialer: Arc<FakeDialer>,
+ connections: mpsc::UnboundedReceiver<ServerConnection>,
+}
+
+impl Default for FakeServer {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl FakeServer {
+ /// A new server with no connections.
+ pub fn new() -> FakeServer {
+ let (sender, connections) = mpsc::unbounded_channel();
+ FakeServer {
+ dialer: Arc::new(FakeDialer {
+ connections: sender,
+ }),
+ connections,
+ }
+ }
+
+ /// The dialer that connects to this server.
+ pub fn dialer(&self) -> Arc<FakeDialer> {
+ Arc::clone(&self.dialer)
+ }
+
+ /// The next connection, after its handshake. `None` once the dialer is
+ /// gone.
+ pub async fn accept(&mut self) -> Option<ServerConnection> {
+ self.connections.recv().await
+ }
+}
+
+/// Dials a [`FakeServer`] over an in-memory websocket.
+pub struct FakeDialer {
+ connections: mpsc::UnboundedSender<ServerConnection>,
+}
+
+#[async_trait]
+impl Dialer for FakeDialer {
+ async fn dial(&self) -> Result<(FrameSocket, mpsc::Receiver<FrameEvent>), SocketError> {
+ let (client, server) = tokio::io::duplex(1 << 20);
+ let client = WebSocketStream::from_raw_socket(client, Role::Client, None).await;
+ let server = WebSocketStream::from_raw_socket(server, Role::Server, None).await;
+ let connections = self.connections.clone();
+ tokio::spawn(async move {
+ match ServerConnection::handshake(server).await {
+ Some(connection) => {
+ let _ = connections.send(connection);
+ }
+ None => tracing::debug!("fake server handshake failed"),
+ }
+ });
+ Ok(FrameSocket::from_websocket(client))
+ }
+}
+
+/// The server side of one connection, after the noise handshake.
+pub struct ServerConnection {
+ websocket: WebSocketStream<DuplexStream>,
+ write_key: Aes256Gcm,
+ read_key: Aes256Gcm,
+ write_counter: u32,
+ read_counter: u32,
+ /// The client's static noise key.
+ pub client_static: [u8; 32],
+ /// The payload the client logged in or registered with.
+ pub client_payload: ClientPayload,
+}
+
+impl ServerConnection {
+ async fn read_frame(
+ websocket: &mut WebSocketStream<DuplexStream>,
+ skip: usize,
+ ) -> Option<Vec<u8>> {
+ loop {
+ match websocket.next().await? {
+ Ok(WebSocketMessage::Binary(data)) => {
+ return data.get(skip + 3..).map(<[u8]>::to_vec);
+ }
+ Ok(WebSocketMessage::Close(_)) | Err(_) => return None,
+ Ok(_) => {}
+ }
+ }
+ }
+
+ fn frame(data: &[u8]) -> WebSocketMessage {
+ let length = u32::try_from(data.len()).unwrap_or(u32::MAX).to_be_bytes();
+ let mut message = length[1..].to_vec();
+ message.extend_from_slice(data);
+ WebSocketMessage::Binary(message.into())
+ }
+
+ async fn handshake(mut websocket: WebSocketStream<DuplexStream>) -> Option<ServerConnection> {
+ let server_ephemeral = new_key_pair();
+ let server_static: KeyPair = new_key_pair();
+
+ let hello = HandshakeMessage::decode(
+ Self::read_frame(&mut websocket, WA_CONN_HEADER.len())
+ .await?
+ .as_slice(),
+ )
+ .ok()?;
+ let client_ephemeral: [u8; 32] = hello.client_hello?.ephemeral?.try_into().ok()?;
+
+ let mut handshake = NoiseHandshake::start(NOISE_START_PATTERN, &WA_CONN_HEADER).ok()?;
+ handshake.authenticate(&client_ephemeral);
+ handshake.authenticate(&server_ephemeral.public);
+ handshake
+ .mix_shared_secret_into_key(server_ephemeral.private, client_ephemeral)
+ .ok()?;
+ let static_ciphertext = handshake.encrypt(&server_static.public).ok()?;
+ handshake
+ .mix_shared_secret_into_key(server_static.private, client_ephemeral)
+ .ok()?;
+ let certificate_ciphertext = handshake
+ .encrypt(&certificate_chain(&server_static.public))
+ .ok()?;
+ let server_hello = HandshakeMessage {
+ server_hello: Some(handshake_message::ServerHello {
+ ephemeral: Some(server_ephemeral.public.to_vec()),
+ r#static: Some(static_ciphertext),
+ payload: Some(certificate_ciphertext),
+ ..Default::default()
+ }),
+ ..Default::default()
+ };
+ websocket
+ .send(Self::frame(&server_hello.encode_to_vec()))
+ .await
+ .ok()?;
+
+ let finish =
+ HandshakeMessage::decode(Self::read_frame(&mut websocket, 0).await?.as_slice())
+ .ok()?
+ .client_finish?;
+ let client_static: [u8; 32] = handshake.decrypt(&finish.r#static?).ok()?.try_into().ok()?;
+ handshake
+ .mix_shared_secret_into_key(server_ephemeral.private, client_static)
+ .ok()?;
+ let client_payload =
+ ClientPayload::decode(handshake.decrypt(&finish.payload?).ok()?.as_slice()).ok()?;
+ let (client_write, client_read) = handshake.transport_keys();
+ Some(ServerConnection {
+ websocket,
+ write_key: gcmutil::prepare(&client_read).ok()?,
+ read_key: gcmutil::prepare(&client_write).ok()?,
+ write_counter: 0,
+ read_counter: 0,
+ client_static,
+ client_payload,
+ })
+ }
+
+ /// The next node from the client; `None` when the client disconnected.
+ pub async fn recv_node(&mut self) -> Option<Node> {
+ let ciphertext = Self::read_frame(&mut self.websocket, 0).await?;
+ let plaintext = gcmutil::open(
+ &self.read_key,
+ &generate_iv(self.read_counter),
+ &ciphertext,
+ &[],
+ )
+ .ok()?;
+ self.read_counter += 1;
+ unmarshal(&unpack(&plaintext).ok()?).ok()
+ }
+
+ /// The next node from the client that isn't a keepalive ping, receipt
+ /// ack or other node matching `skip`.
+ pub async fn recv_node_skipping(&mut self, skip: impl Fn(&Node) -> bool) -> Option<Node> {
+ loop {
+ let node = self.recv_node().await?;
+ if !skip(&node) {
+ return Some(node);
+ }
+ }
+ }
+
+ /// Sends a node to the client.
+ pub async fn send_node(&mut self, node: &Node) {
+ let Ok(plaintext) = marshal(node) else {
+ panic!("fake server failed to marshal a node");
+ };
+ let ciphertext = gcmutil::seal(
+ &self.write_key,
+ &generate_iv(self.write_counter),
+ &plaintext,
+ &[],
+ )
+ .unwrap_or_default();
+ self.write_counter += 1;
+ let _ = self.websocket.send(Self::frame(&ciphertext)).await;
+ }
+
+ /// Sends a node and closes the websocket right behind it, as the server
+ /// does with the 515 after pairing.
+ pub async fn send_node_and_close(mut self, node: &Node) {
+ let Ok(plaintext) = marshal(node) else {
+ panic!("fake server failed to marshal a node");
+ };
+ let ciphertext = gcmutil::seal(
+ &self.write_key,
+ &generate_iv(self.write_counter),
+ &plaintext,
+ &[],
+ )
+ .unwrap_or_default();
+ let _ = self.websocket.feed(Self::frame(&ciphertext)).await;
+ let _ = self.websocket.close(None).await;
+ }
+
+ /// Closes the websocket, as the server going away.
+ pub async fn close(mut self) {
+ let _ = self.websocket.close(None).await;
+ }
+
+ /// Answers an `<iq>` with `type="result"` and the given children.
+ pub async fn respond_iq(&mut self, request: &Node, children: Vec<Node>) {
+ let mut attrs = Attrs::from([
+ ("type".to_owned(), "result".into()),
+ ("from".to_owned(), SERVER_JID.clone().into()),
+ ]);
+ if let Some(id) = request.attrs.get("id") {
+ attrs.insert("id".to_owned(), id.clone());
+ }
+ let content = (!children.is_empty()).then_some(NodeContent::Nodes(children));
+ self.send_node(&Node {
+ tag: "iq".to_owned(),
+ attrs,
+ content,
+ })
+ .await;
+ }
+
+ /// Answers an `<iq>` with `type="error"` and an `<error>` child.
+ pub async fn respond_iq_error(&mut self, request: &Node, code: i64, text: &str) {
+ let mut attrs = Attrs::from([
+ ("type".to_owned(), "error".into()),
+ ("from".to_owned(), SERVER_JID.clone().into()),
+ ]);
+ if let Some(id) = request.attrs.get("id") {
+ attrs.insert("id".to_owned(), id.clone());
+ }
+ self.send_node(&Node {
+ tag: "iq".to_owned(),
+ attrs,
+ content: Some(NodeContent::Nodes(vec![Node {
+ tag: "error".to_owned(),
+ attrs: Attrs::from([
+ ("code".to_owned(), code.into()),
+ ("text".to_owned(), text.into()),
+ ]),
+ content: None,
+ }])),
+ })
+ .await;
+ }
+}
+
+/// Whether a node is an `<iq>` with the given namespace.
+pub fn is_iq(node: &Node, xmlns: &str) -> bool {
+ node.tag == "iq" && attr_string(node, "xmlns") == xmlns
+}
+
+/// A string attribute, or empty.
+pub fn attr_string(node: &Node, key: &str) -> String {
+ match node.attrs.get(key) {
+ Some(AttributeValue::String(value)) => value.clone(),
+ Some(AttributeValue::Jid(jid)) => jid.to_string(),
+ None => String::new(),
+ }
+}
+
+/// A JID attribute, or the empty JID.
+pub fn attr_jid(node: &Node, key: &str) -> Jid {
+ match node.attrs.get(key) {
+ Some(AttributeValue::Jid(jid)) => jid.clone(),
+ _ => Jid::default(),
+ }
+}
diff --git a/crates/whatsmeow/src/types.rs b/crates/whatsmeow/src/types.rs
new file mode 100644
index 0000000000..ffda17bba2
--- /dev/null
+++ b/crates/whatsmeow/src/types.rs
@@ -0,0 +1,82 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+//
+// Ported from whatsmeow types/ (MPL-2.0, Copyright (c) Tulir Asokan)
+
+//! Various structs and other types used by whatsmeow.
+//!
+//! Not ported: `botmap.go`, `business.go`, `call.go`, `newsletter.go`,
+//! `sticker.go` and `richresponse/` (features the port skips).
+
+/// Go's string-typed constants (`type ReceiptType string`) as an enum with the
+/// known values plus `Other` for whatever else the server sends, so unknown
+/// values survive a round trip like they do in Go.
+macro_rules! string_enum {
+ (
+ $(#[$meta:meta])*
+ pub enum $name:ident {
+ $(
+ $(#[$variant_meta:meta])*
+ $variant:ident = $value:literal,
+ )*
+ }
+ ) => {
+ $(#[$meta])*
+ #[derive(Clone, Debug, PartialEq, Eq, Hash)]
+ pub enum $name {
+ $(
+ $(#[$variant_meta])*
+ $variant,
+ )*
+ /// A value this port doesn't know.
+ Other(String),
+ }
+
+ impl $name {
+ /// The wire value.
+ pub fn as_str(&self) -> &str {
+ match self {
+ $($name::$variant => $value,)*
+ $name::Other(value) => value,
+ }
+ }
+ }
+
+ impl From<&str> for $name {
+ fn from(value: &str) -> Self {
+ match value {
+ $($value => $name::$variant,)*
+ other => $name::Other(other.to_owned()),
+ }
+ }
+ }
+
+ impl From<String> for $name {
+ fn from(value: String) -> Self {
+ $name::from(value.as_str())
+ }
+ }
+
+ impl std::fmt::Display for $name {
+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ formatter.write_str(self.as_str())
+ }
+ }
+ };
+}
+
+pub mod events;
+mod group;
+mod jid;
+mod message;
+mod passkey;
+mod presence;
+mod user;
+
+pub use group::*;
+pub use jid::*;
+pub use message::*;
+pub use passkey::*;
+pub use presence::*;
+pub use user::*;
diff --git a/crates/whatsmeow/src/types/events.rs b/crates/whatsmeow/src/types/events.rs
new file mode 100644
index 0000000000..585653a49c
--- /dev/null
+++ b/crates/whatsmeow/src/types/events.rs
@@ -0,0 +1,23 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+//
+// Ported from whatsmeow types/events/ (MPL-2.0, Copyright (c) Tulir Asokan)
+
+//! All the events that the client can emit.
+//!
+//! Go dispatches each event as its own struct through `any`; here every
+//! event is a variant of [`Event`] wrapping the same struct.
+//!
+//! Not ported: `call.go` and the newsletter, passkey, FB/Instagram message
+//! and mex events (features the port skips).
+
+mod appstate;
+#[expect(
+ clippy::module_inception,
+ reason = "mirrors whatsmeow's types/events/events.go"
+)]
+mod events;
+
+pub use appstate::*;
+pub use events::*;
diff --git a/crates/whatsmeow/src/types/events/appstate.rs b/crates/whatsmeow/src/types/events/appstate.rs
new file mode 100644
index 0000000000..d2514d411a
--- /dev/null
+++ b/crates/whatsmeow/src/types/events/appstate.rs
@@ -0,0 +1,296 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+//
+// Ported from whatsmeow types/events/appstate.go (MPL-2.0, Copyright (c) Tulir Asokan)
+//
+// Go's `time.UnixMilli(action.GetTimestamp())` is never the zero time, so
+// the timestamps here aren't optional. Go's nil action pointers are `None`.
+
+use std::sync::Arc;
+
+use chrono::{DateTime, Utc};
+
+use crate::appstate::WaPatchName;
+use crate::errors::ClientError;
+use crate::proto::wa_sync_action::{
+ ArchiveChatAction, ClearChatAction, ContactAction, DeleteChatAction, DeleteMessageForMeAction,
+ LabelAssociationAction, LabelEditAction, MarkChatAsReadAction, MuteAction, PinAction,
+ PushNameSetting as PushNameSettingAction, StarAction, SyncActionValue,
+ UnarchiveChatsSetting as UnarchiveChatsSettingAction, UserStatusMuteAction,
+};
+use crate::types::{Jid, MessageInfo};
+
+/// An entry in the user's contact list was changed from another device.
+#[derive(Clone, Debug, PartialEq)]
+pub struct Contact {
+ /// The contact who was changed.
+ pub jid: Jid,
+ /// When the change happened.
+ pub timestamp: DateTime<Utc>,
+ /// The new contact info.
+ pub action: Option<ContactAction>,
+ /// Whether the event comes from a full sync.
+ pub from_full_sync: bool,
+}
+
+/// A message arrived with a different push name than the cached one.
+#[derive(Clone, Debug, Default, PartialEq)]
+pub struct PushName {
+ /// The user whose push name changed.
+ pub jid: Jid,
+ /// The user's other JID (LID or phone number), if known.
+ pub jid_alt: Jid,
+ /// The message where the change was first noticed.
+ pub message: Option<MessageInfo>,
+ /// The previous push name from the local cache.
+ pub old_push_name: String,
+ /// The new push name from the message.
+ pub new_push_name: String,
+}
+
+/// A message arrived with a different verified business name than the
+/// cached one.
+#[derive(Clone, Debug, Default, PartialEq)]
+pub struct BusinessName {
+ /// The business.
+ pub jid: Jid,
+ /// The message where the change was noticed, if any.
+ pub message: Option<MessageInfo>,
+ /// The previous name.
+ pub old_business_name: String,
+ /// The new name.
+ pub new_business_name: String,
+}
+
+/// A chat was pinned or unpinned from another device.
+#[derive(Clone, Debug, PartialEq)]
+pub struct Pin {
+ /// The chat.
+ pub jid: Jid,
+ /// When the (un)pinning happened.
+ pub timestamp: DateTime<Utc>,
+ /// Whether the chat is now pinned.
+ pub action: Option<PinAction>,
+ /// Whether the event comes from a full sync.
+ pub from_full_sync: bool,
+}
+
+/// A message was starred or unstarred from another device.
+#[derive(Clone, Debug, PartialEq)]
+pub struct Star {
+ /// The chat of the message.
+ pub chat_jid: Jid,
+ /// In groups, who sent the message (empty when the user sent it).
+ pub sender_jid: Jid,
+ /// Whether the user sent the message.
+ pub is_from_me: bool,
+ /// The message.
+ pub message_id: String,
+ /// When the (un)starring happened.
+ pub timestamp: DateTime<Utc>,
+ /// Whether the message is now starred.
+ pub action: Option<StarAction>,
+ /// Whether the event comes from a full sync.
+ pub from_full_sync: bool,
+}
+
+/// A message was deleted for the user only, from another device.
+#[derive(Clone, Debug, PartialEq)]
+pub struct DeleteForMe {
+ /// The chat of the message.
+ pub chat_jid: Jid,
+ /// In groups, who sent the message (empty when the user sent it).
+ pub sender_jid: Jid,
+ /// Whether the user sent the message.
+ pub is_from_me: bool,
+ /// The message.
+ pub message_id: String,
+ /// When the deletion happened.
+ pub timestamp: DateTime<Utc>,
+ /// More about the deletion.
+ pub action: Option<DeleteMessageForMeAction>,
+ /// Whether the event comes from a full sync.
+ pub from_full_sync: bool,
+}
+
+/// A chat was muted or unmuted from another device.
+#[derive(Clone, Debug, PartialEq)]
+pub struct Mute {
+ /// The chat.
+ pub jid: Jid,
+ /// When the (un)muting happened.
+ pub timestamp: DateTime<Utc>,
+ /// The chat's mute status.
+ pub action: Option<MuteAction>,
+ /// Whether the event comes from a full sync.
+ pub from_full_sync: bool,
+}
+
+/// A chat was archived or unarchived from another device.
+#[derive(Clone, Debug, PartialEq)]
+pub struct Archive {
+ /// The chat.
+ pub jid: Jid,
+ /// When the (un)archiving happened.
+ pub timestamp: DateTime<Utc>,
+ /// The chat's archive status.
+ pub action: Option<ArchiveChatAction>,
+ /// Whether the event comes from a full sync.
+ pub from_full_sync: bool,
+}
+
+/// A whole chat was marked as read or unread from another device.
+#[derive(Clone, Debug, PartialEq)]
+pub struct MarkChatAsRead {
+ /// The chat.
+ pub jid: Jid,
+ /// When the marking happened.
+ pub timestamp: DateTime<Utc>,
+ /// Whether the chat is read, and its latest messages.
+ pub action: Option<MarkChatAsReadAction>,
+ /// Whether the event comes from a full sync.
+ pub from_full_sync: bool,
+}
+
+/// A chat was cleared on another device (unlike [`DeleteChat`]).
+#[derive(Clone, Debug, PartialEq)]
+pub struct ClearChat {
+ /// The chat.
+ pub jid: Jid,
+ /// When the clear happened.
+ pub timestamp: DateTime<Utc>,
+ /// More about the clear.
+ pub action: Option<ClearChatAction>,
+ /// Whether the event comes from a full sync.
+ pub from_full_sync: bool,
+ /// Whether media was deleted too.
+ pub delete_media: bool,
+}
+
+/// A chat was deleted on another device.
+#[derive(Clone, Debug, PartialEq)]
+pub struct DeleteChat {
+ /// The chat.
+ pub jid: Jid,
+ /// When the deletion happened.
+ pub timestamp: DateTime<Utc>,
+ /// More about the deletion.
+ pub action: Option<DeleteChatAction>,
+ /// Whether the event comes from a full sync.
+ pub from_full_sync: bool,
+ /// Whether media was deleted too.
+ pub delete_media: bool,
+}
+
+/// The user's push name was changed from another device.
+#[derive(Clone, Debug, PartialEq)]
+pub struct PushNameSetting {
+ /// When the push name changed.
+ pub timestamp: DateTime<Utc>,
+ /// The new push name.
+ pub action: Option<PushNameSettingAction>,
+ /// Whether the event comes from a full sync.
+ pub from_full_sync: bool,
+}
+
+/// The "keep chats archived" setting was changed from another device.
+#[derive(Clone, Debug, PartialEq)]
+pub struct UnarchiveChatsSetting {
+ /// When the setting changed.
+ pub timestamp: DateTime<Utc>,
+ /// The new setting.
+ pub action: Option<UnarchiveChatsSettingAction>,
+ /// Whether the event comes from a full sync.
+ pub from_full_sync: bool,
+}
+
+/// The user muted or unmuted another user's status updates.
+#[derive(Clone, Debug, PartialEq)]
+pub struct UserStatusMute {
+ /// The user who was (un)muted.
+ pub jid: Jid,
+ /// When it happened.
+ pub timestamp: DateTime<Utc>,
+ /// The new mute status.
+ pub action: Option<UserStatusMuteAction>,
+ /// Whether the event comes from a full sync.
+ pub from_full_sync: bool,
+}
+
+/// A label was edited from any device.
+#[derive(Clone, Debug, PartialEq)]
+pub struct LabelEdit {
+ /// When the label was edited.
+ pub timestamp: DateTime<Utc>,
+ /// The label.
+ pub label_id: String,
+ /// The new label info.
+ pub action: Option<LabelEditAction>,
+ /// Whether the event comes from a full sync.
+ pub from_full_sync: bool,
+}
+
+/// A chat was labeled or unlabeled from any device.
+#[derive(Clone, Debug, PartialEq)]
+pub struct LabelAssociationChat {
+ /// The chat.
+ pub jid: Jid,
+ /// When the (un)labeling happened.
+ pub timestamp: DateTime<Utc>,
+ /// The label.
+ pub label_id: String,
+ /// The chat's label status.
+ pub action: Option<LabelAssociationAction>,
+ /// Whether the event comes from a full sync.
+ pub from_full_sync: bool,
+}
+
+/// A message was labeled or unlabeled from any device.
+#[derive(Clone, Debug, PartialEq)]
+pub struct LabelAssociationMessage {
+ /// The chat of the message.
+ pub jid: Jid,
+ /// When the (un)labeling happened.
+ pub timestamp: DateTime<Utc>,
+ /// The label.
+ pub label_id: String,
+ /// The message.
+ pub message_id: String,
+ /// The message's label status.
+ pub action: Option<LabelAssociationAction>,
+ /// Whether the event comes from a full sync.
+ pub from_full_sync: bool,
+}
+
+/// New data from app state syncing. Prefer the specific events like
+/// [`Contact`] and [`Mute`].
+#[derive(Clone, Debug, PartialEq)]
+pub struct AppState {
+ /// The mutation's index.
+ pub index: Vec<String>,
+ /// The mutation's value (Go embeds it).
+ pub sync_action_value: Option<SyncActionValue>,
+}
+
+/// An app state collection was resynced.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct AppStateSyncComplete {
+ /// The collection.
+ pub name: WaPatchName,
+ /// Its version after the sync.
+ pub version: u64,
+ /// Whether the state came from a recovery snapshot.
+ pub recovery: bool,
+}
+
+/// Syncing an app state collection failed.
+#[derive(Clone, Debug)]
+pub struct AppStateSyncError {
+ /// The collection.
+ pub name: WaPatchName,
+ /// What failed.
+ pub error: Arc<ClientError>,
+ /// Whether it was a full sync.
+ pub full_sync: bool,
+}
diff --git a/crates/whatsmeow/src/types/events/events.rs b/crates/whatsmeow/src/types/events/events.rs
new file mode 100644
index 0000000000..3b0293ae85
--- /dev/null
+++ b/crates/whatsmeow/src/types/events/events.rs
@@ -0,0 +1,840 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+//
+// Ported from whatsmeow types/events/events.go (MPL-2.0, Copyright (c) Tulir Asokan)
+//
+// Go's zero `time.Time` is `None` and its `time.Duration` is
+// `std::time::Duration`. Errors carried by events are `Arc`s so events stay
+// `Clone`.
+
+use std::fmt;
+use std::sync::Arc;
+use std::time::Duration;
+
+use chrono::{DateTime, Utc};
+
+use crate::binary::Node;
+use crate::errors::ClientError;
+use crate::proto::wa_companion_reg::ClientPairingProps;
+use crate::proto::wa_e2e;
+use crate::proto::wa_history_sync::HistorySync as HistorySyncData;
+use crate::proto::wa_web::WebMessageInfo;
+use crate::types::{
+ ChatPresence as ChatPresenceState, ChatPresenceMedia, GroupAnnounce, GroupDelete,
+ GroupEphemeral, GroupInfo as GroupInfoType, GroupLinkChange, GroupLocked,
+ GroupMembershipApprovalMode, GroupName, GroupTopic, Jid, MessageId, MessageInfo, MessageSource,
+ PrivacySettings as PrivacySettingsType, ReceiptType,
+};
+
+/// Every event the client emits.
+#[expect(
+ clippy::large_enum_variant,
+ reason = "events are passed by reference to handlers; boxing every large one adds noise for callers"
+)]
+#[derive(Clone, Debug)]
+pub enum Event {
+ /// New QR codes to show for pairing.
+ Qr(Qr),
+ /// The ADV secret in the QR codes changed.
+ RotateAdvSecret(RotateAdvSecret),
+ /// Pairing succeeded.
+ PairSuccess(PairSuccess),
+ /// Pairing failed.
+ PairError(PairError),
+ /// The QR code was scanned by a phone without multidevice.
+ QrScannedWithoutMultidevice(QrScannedWithoutMultidevice),
+ /// Pairing needs a passkey assertion.
+ PairPasskeyRequest(Box<PairPasskeyRequest>),
+ /// Handling a passkey notification failed.
+ PairPasskeyError(PairPasskeyError),
+ /// The passkey was accepted; confirm the code.
+ PairPasskeyConfirmation(PairPasskeyConfirmation),
+ /// The phone answered a media retry request.
+ MediaRetry(Box<MediaRetry>),
+ /// The client connected and authenticated.
+ Connected(Connected),
+ /// A keepalive ping timed out.
+ KeepAliveTimeout(KeepAliveTimeout),
+ /// Keepalive pings work again.
+ KeepAliveRestored(KeepAliveRestored),
+ /// The device was logged out.
+ LoggedOut(LoggedOut),
+ /// Another client connected with the same keys.
+ StreamReplaced(StreamReplaced),
+ /// The server sent a 515 but login auto-reconnect is disabled.
+ ManualLoginReconnect(ManualLoginReconnect),
+ /// The account is temporarily banned.
+ TemporaryBan(TemporaryBan),
+ /// The server refused the connection.
+ ConnectFailure(ConnectFailure),
+ /// The client version is too old.
+ ClientOutdated(ClientOutdated),
+ /// Refreshing the Messenger crypto auth token failed.
+ CatRefreshError(CatRefreshError),
+ /// An unknown stream error.
+ StreamError(StreamError),
+ /// The websocket disconnected unexpectedly.
+ Disconnected(Disconnected),
+ /// A history sync blob was received.
+ HistorySync(Box<HistorySync>),
+ /// A message couldn't be decrypted.
+ UndecryptableMessage(UndecryptableMessage),
+ /// A message was received.
+ Message(Box<Message>),
+ /// A receipt was received.
+ Receipt(Receipt),
+ /// Someone started or stopped typing.
+ ChatPresence(ChatPresence),
+ /// Someone's online status changed.
+ Presence(Presence),
+ /// The user joined or was added to a group.
+ JoinedGroup(Box<JoinedGroup>),
+ /// A group's info or participants changed.
+ GroupInfo(Box<GroupInfo>),
+ /// A profile picture changed.
+ Picture(Picture),
+ /// A user's about text changed.
+ UserAbout(UserAbout),
+ /// A user's identity key changed.
+ IdentityChange(IdentityChange),
+ /// The user's privacy settings changed.
+ PrivacySettings(PrivacySettings),
+ /// The server is about to deliver the offline backlog.
+ OfflineSyncPreview(OfflineSyncPreview),
+ /// The offline backlog was delivered.
+ OfflineSyncCompleted(OfflineSyncCompleted),
+ /// The blocklist changed.
+ Blocklist(Blocklist),
+ /// A contact's push name changed.
+ PushName(Box<super::PushName>),
+ /// A contact's verified business name changed.
+ BusinessName(Box<super::BusinessName>),
+ /// A contact list entry changed on another device.
+ Contact(Box<super::Contact>),
+ /// A chat was (un)pinned on another device.
+ Pin(Box<super::Pin>),
+ /// A message was (un)starred on another device.
+ Star(Box<super::Star>),
+ /// A message was deleted for the user on another device.
+ DeleteForMe(Box<super::DeleteForMe>),
+ /// A chat was (un)muted on another device.
+ Mute(Box<super::Mute>),
+ /// A chat was (un)archived on another device.
+ Archive(Box<super::Archive>),
+ /// A chat was marked as read or unread on another device.
+ MarkChatAsRead(Box<super::MarkChatAsRead>),
+ /// A chat was cleared on another device.
+ ClearChat(Box<super::ClearChat>),
+ /// A chat was deleted on another device.
+ DeleteChat(Box<super::DeleteChat>),
+ /// The user's push name changed on another device.
+ PushNameSetting(Box<super::PushNameSetting>),
+ /// The "keep chats archived" setting changed on another device.
+ UnarchiveChatsSetting(Box<super::UnarchiveChatsSetting>),
+ /// Another user's status updates were (un)muted.
+ UserStatusMute(Box<super::UserStatusMute>),
+ /// A label was edited.
+ LabelEdit(Box<super::LabelEdit>),
+ /// A chat was (un)labeled.
+ LabelAssociationChat(Box<super::LabelAssociationChat>),
+ /// A message was (un)labeled.
+ LabelAssociationMessage(Box<super::LabelAssociationMessage>),
+ /// Raw data from app state syncing.
+ AppState(Box<super::AppState>),
+ /// An app state collection was resynced.
+ AppStateSyncComplete(super::AppStateSyncComplete),
+ /// Syncing an app state collection failed.
+ AppStateSyncError(super::AppStateSyncError),
+}
+
+/// New QR codes for pairing: show the first one, then the next one every
+/// 20 seconds (the first stays 60 seconds).
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct Qr {
+ /// The QR code contents.
+ pub codes: Vec<String>,
+}
+
+/// The ADV secret was rotated; replace it in the QR codes.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct RotateAdvSecret {
+ /// The old secret, base64.
+ pub old_secret: String,
+ /// The new secret, base64.
+ pub new_secret: String,
+}
+
+/// Pairing succeeded. The client disconnects and reconnects by itself.
+#[derive(Clone, Debug, PartialEq)]
+pub struct PairSuccess {
+ /// The new device JID.
+ pub id: Jid,
+ /// The new device LID.
+ pub lid: Jid,
+ /// The business name, if any.
+ pub business_name: String,
+ /// The primary device's platform.
+ pub platform: String,
+ /// The pairing props.
+ pub props: ClientPairingProps,
+}
+
+/// Pairing failed.
+#[derive(Clone, Debug)]
+pub struct PairError {
+ /// The device JID.
+ pub id: Jid,
+ /// The device LID.
+ pub lid: Jid,
+ /// The business name, if any.
+ pub business_name: String,
+ /// The primary device's platform.
+ pub platform: String,
+ /// The pairing props.
+ pub props: ClientPairingProps,
+ /// What failed.
+ pub error: Arc<ClientError>,
+}
+
+/// Pairing needs a passkey: ask the authenticator to sign the request and
+/// pass the answer to `Client::send_passkey_response`.
+#[derive(Clone, Debug, PartialEq)]
+pub struct PairPasskeyRequest {
+ /// The WebAuthn request options.
+ pub public_key: crate::types::WebAuthnPublicKey,
+}
+
+/// Handling a passkey notification failed.
+#[derive(Clone, Debug)]
+pub struct PairPasskeyError {
+ /// What failed.
+ pub error: Arc<ClientError>,
+ /// Whether this came from a continuation notification rather than the
+ /// initial one.
+ pub continuation: bool,
+}
+
+/// The passkey response was accepted. Show `code` to the user and call
+/// `Client::send_passkey_confirmation`; with `skip_handoff_ux`, showing the
+/// code can be skipped.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct PairPasskeyConfirmation {
+ /// The code, `ABCD-EFGH`.
+ pub code: String,
+ /// Whether the code needn't be shown.
+ pub skip_handoff_ux: bool,
+}
+
+/// The error code of a failed media retry.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct MediaRetryError {
+ /// The code; 2 means the media is no longer on the phone.
+ pub code: i64,
+}
+
+/// The phone's answer to `Client::send_media_retry_receipt`. Decrypt it with
+/// `mediaretry::decrypt_media_retry_notification` and the media key.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct MediaRetry {
+ /// The encrypted `MediaRetryNotification`.
+ pub ciphertext: Vec<u8>,
+ /// Its IV.
+ pub iv: Vec<u8>,
+ /// The error, if the phone couldn't re-upload.
+ pub error: Option<MediaRetryError>,
+ /// When the response was sent.
+ pub timestamp: Option<DateTime<Utc>>,
+ /// The message ID.
+ pub message_id: MessageId,
+ /// The chat of the message.
+ pub chat_id: Jid,
+ /// The sender of the message (groups only).
+ pub sender_id: Jid,
+ /// Whether we sent the message.
+ pub from_me: bool,
+}
+
+/// The QR code was scanned by a phone without multidevice enabled.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct QrScannedWithoutMultidevice;
+
+/// The client connected and authenticated.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct Connected;
+
+/// A keepalive ping timed out.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct KeepAliveTimeout {
+ /// How many pings failed in a row.
+ pub error_count: u32,
+ /// When the last ping succeeded.
+ pub last_success: DateTime<Utc>,
+}
+
+/// Keepalive pings work again.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct KeepAliveRestored;
+
+/// The device was logged out: the session is deleted and must be paired again.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct LoggedOut {
+ /// Whether this came as a connect failure rather than a stream error.
+ pub on_connect: bool,
+ /// Why.
+ pub reason: ConnectFailureReason,
+}
+
+/// Another client connected with the same keys.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct StreamReplaced;
+
+/// The server asked for a reconnect after login, but
+/// `disable_login_auto_reconnect` is set.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct ManualLoginReconnect;
+
+/// Why the account is temporarily banned.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct TempBanReason(pub i64);
+
+impl TempBanReason {
+ /// Sent too many messages to people who don't have you in their address books.
+ pub const SENT_TO_TOO_MANY_PEOPLE: TempBanReason = TempBanReason(101);
+ /// Too many people blocked you.
+ pub const BLOCKED_BY_USERS: TempBanReason = TempBanReason(102);
+ /// Created too many groups with strangers.
+ pub const CREATED_TOO_MANY_GROUPS: TempBanReason = TempBanReason(103);
+ /// Sent the same message to too many people.
+ pub const SENT_TOO_MANY_SAME_MESSAGE: TempBanReason = TempBanReason(104);
+ /// Sent too many messages to a broadcast list.
+ pub const BROADCAST_LIST: TempBanReason = TempBanReason(106);
+
+ fn message(self) -> &'static str {
+ match self {
+ TempBanReason::SENT_TO_TOO_MANY_PEOPLE => {
+ "you sent too many messages to people who don't have you in their address books"
+ }
+ TempBanReason::BLOCKED_BY_USERS => "too many people blocked you",
+ TempBanReason::CREATED_TOO_MANY_GROUPS => {
+ "you created too many groups with people who don't have you in their address books"
+ }
+ TempBanReason::SENT_TOO_MANY_SAME_MESSAGE => {
+ "you sent the same message to too many people"
+ }
+ TempBanReason::BROADCAST_LIST => "you sent too many messages to a broadcast list",
+ _ => "you may have violated the terms of service (unknown error)",
+ }
+ }
+}
+
+impl fmt::Display for TempBanReason {
+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
+ write!(formatter, "{}: {}", self.0, self.message())
+ }
+}
+
+/// The account is temporarily banned.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct TemporaryBan {
+ /// Why.
+ pub code: TempBanReason,
+ /// When the ban ends; zero when unknown.
+ pub expire: Duration,
+}
+
+impl fmt::Display for TemporaryBan {
+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
+ if self.expire.is_zero() {
+ write!(formatter, "You've been temporarily banned: {}", self.code)
+ } else {
+ write!(
+ formatter,
+ "You've been temporarily banned: {}. The ban expires in {:?}",
+ self.code, self.expire
+ )
+ }
+ }
+}
+
+/// Why the server refused the connection.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct ConnectFailureReason(pub i64);
+
+impl ConnectFailureReason {
+ /// A generic failure.
+ pub const GENERIC: ConnectFailureReason = ConnectFailureReason(400);
+ /// Logged out from another device.
+ pub const LOGGED_OUT: ConnectFailureReason = ConnectFailureReason(401);
+ /// The account is temporarily banned.
+ pub const TEMP_BANNED: ConnectFailureReason = ConnectFailureReason(402);
+ /// The primary device was logged out (LOCKED in WhatsApp web).
+ pub const MAIN_DEVICE_GONE: ConnectFailureReason = ConnectFailureReason(403);
+ /// Logged out for an unknown reason (BANNED in WhatsApp web).
+ pub const UNKNOWN_LOGOUT: ConnectFailureReason = ConnectFailureReason(406);
+ /// The client is out of date.
+ pub const CLIENT_OUTDATED: ConnectFailureReason = ConnectFailureReason(405);
+ /// The user agent was rejected.
+ pub const BAD_USER_AGENT: ConnectFailureReason = ConnectFailureReason(409);
+ /// The Messenger crypto auth token expired.
+ pub const CAT_EXPIRED: ConnectFailureReason = ConnectFailureReason(413);
+ /// The Messenger crypto auth token is invalid.
+ pub const CAT_INVALID: ConnectFailureReason = ConnectFailureReason(414);
+ /// Not found.
+ pub const NOT_FOUND: ConnectFailureReason = ConnectFailureReason(415);
+ /// Unknown client.
+ pub const CLIENT_UNKNOWN: ConnectFailureReason = ConnectFailureReason(418);
+ /// An internal server error.
+ pub const INTERNAL_SERVER_ERROR: ConnectFailureReason = ConnectFailureReason(500);
+ /// Experimental.
+ pub const EXPERIMENTAL: ConnectFailureReason = ConnectFailureReason(501);
+ /// The service is unavailable.
+ pub const SERVICE_UNAVAILABLE: ConnectFailureReason = ConnectFailureReason(503);
+
+ /// Whether the reason means the device was logged out.
+ pub fn is_logged_out(self) -> bool {
+ self == Self::LOGGED_OUT || self == Self::MAIN_DEVICE_GONE || self == Self::UNKNOWN_LOGOUT
+ }
+
+ /// The code as a string.
+ pub fn number_string(self) -> String {
+ self.0.to_string()
+ }
+
+ fn message(self) -> &'static str {
+ match self {
+ Self::LOGGED_OUT => "logged out from another device",
+ Self::TEMP_BANNED => "account temporarily banned",
+ Self::MAIN_DEVICE_GONE => "primary device was logged out",
+ Self::UNKNOWN_LOGOUT => "logged out for unknown reason",
+ Self::CLIENT_OUTDATED => "client is out of date",
+ Self::BAD_USER_AGENT => "client user agent was rejected",
+ Self::CAT_EXPIRED => "messenger crypto auth token has expired",
+ Self::CAT_INVALID => "messenger crypto auth token is invalid",
+ _ => "unknown error",
+ }
+ }
+}
+
+impl fmt::Display for ConnectFailureReason {
+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
+ write!(formatter, "{}: {}", self.0, self.message())
+ }
+}
+
+/// The server refused the connection for a reason without its own event.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct ConnectFailure {
+ /// Why.
+ pub reason: ConnectFailureReason,
+ /// The server's message.
+ pub message: String,
+ /// The raw failure node.
+ pub raw: Node,
+}
+
+/// The client version is too old; update the WA version.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct ClientOutdated;
+
+/// Refreshing the Messenger crypto auth token failed.
+#[derive(Clone, Debug)]
+pub struct CatRefreshError {
+ /// What failed.
+ pub error: Arc<ClientError>,
+}
+
+/// An unknown stream error.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct StreamError {
+ /// The error code.
+ pub code: String,
+ /// The raw error node.
+ pub raw: Node,
+}
+
+/// The websocket disconnected unexpectedly; the client reconnects by itself
+/// when auto-reconnect is on.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct Disconnected;
+
+/// A history sync blob, downloaded and decoded.
+#[derive(Clone, Debug, PartialEq)]
+pub struct HistorySync {
+ /// The decoded history.
+ pub data: HistorySyncData,
+ /// The notification it came from.
+ pub notification: wa_e2e::HistorySyncNotification,
+}
+
+string_enum! {
+ /// Whether to show a placeholder for an undecryptable message.
+ #[derive(Default)]
+ pub enum DecryptFailMode {
+ /// Show it.
+ #[default]
+ Show = "",
+ /// Hide it.
+ Hide = "hide",
+ }
+}
+
+string_enum! {
+ /// Why a message is unavailable.
+ #[derive(Default)]
+ pub enum UnavailableType {
+ /// Unknown.
+ #[default]
+ Unknown = "",
+ /// A view-once message.
+ ViewOnce = "view_once",
+ }
+}
+
+/// A message couldn't be decrypted.
+#[derive(Clone, Debug, PartialEq)]
+pub struct UndecryptableMessage {
+ /// The message metadata.
+ pub info: MessageInfo,
+ /// Whether the message was unavailable rather than undecryptable.
+ pub is_unavailable: bool,
+ /// Why it was unavailable.
+ pub unavailable_type: UnavailableType,
+ /// Whether to show a placeholder.
+ pub decrypt_fail_mode: DecryptFailMode,
+}
+
+/// A message was received.
+#[derive(Clone, Debug, Default, PartialEq)]
+pub struct Message {
+ /// The chat, sender and other metadata.
+ pub info: MessageInfo,
+ /// The message, unwrapped from ephemeral/view-once/edit wrappers.
+ pub message: Option<wa_e2e::Message>,
+
+ /// Unwrapped from an `EphemeralMessage`.
+ pub is_ephemeral: bool,
+ /// Unwrapped from a view-once message.
+ pub is_view_once: bool,
+ /// Unwrapped from a `ViewOnceMessageV2` or its extension.
+ pub is_view_once_v2: bool,
+ /// Unwrapped from a `ViewOnceMessageV2Extension`.
+ pub is_view_once_v2_extension: bool,
+ /// Unwrapped from a `DocumentWithCaptionMessage`.
+ pub is_document_with_caption: bool,
+ /// Unwrapped from a `LottieStickerMessage`.
+ pub is_lottie_sticker: bool,
+ /// Unwrapped from a `BotInvokeMessage`.
+ pub is_bot_invoke: bool,
+ /// Unwrapped from an `EditedMessage`.
+ pub is_edit: bool,
+
+ /// The source of a message parsed from history sync.
+ pub source_web_msg: Option<WebMessageInfo>,
+ /// The request ID, if this was requested from the phone.
+ pub unavailable_request_id: MessageId,
+ /// How many retry receipts were sent before it decrypted.
+ pub retry_count: i64,
+
+ /// The message as it was received, before unwrapping.
+ pub raw_message: Option<wa_e2e::Message>,
+}
+
+impl Message {
+ /// Fills [`Message::message`] from [`Message::raw_message`], unwrapping
+ /// the wrappers and setting the flags.
+ pub fn unwrap_raw(&mut self) -> &mut Self {
+ self.message = self.raw_message.clone();
+ if let Some(device_sent) = self
+ .message
+ .as_ref()
+ .and_then(|message| message.device_sent_message.as_ref())
+ && let Some(inner) = device_sent.message.as_ref()
+ {
+ self.info.device_sent_meta = Some(crate::types::DeviceSentMeta {
+ destination_jid: device_sent.destination_jid.clone().unwrap_or_default(),
+ phash: device_sent.phash.clone().unwrap_or_default(),
+ });
+ self.message = Some(inner.as_ref().clone());
+ }
+ macro_rules! unwrap_future_proof {
+ ($field:ident, $($flag:ident),*) => {
+ if let Some(inner) = self
+ .message
+ .as_ref()
+ .and_then(|message| message.$field.as_ref())
+ .and_then(|wrapper| wrapper.message.as_ref())
+ {
+ self.message = Some(inner.as_ref().clone());
+ $(self.$flag = true;)*
+ }
+ };
+ }
+ unwrap_future_proof!(bot_invoke_message, is_bot_invoke);
+ unwrap_future_proof!(ephemeral_message, is_ephemeral);
+ unwrap_future_proof!(view_once_message, is_view_once);
+ unwrap_future_proof!(view_once_message_v2, is_view_once, is_view_once_v2);
+ unwrap_future_proof!(
+ view_once_message_v2_extension,
+ is_view_once,
+ is_view_once_v2,
+ is_view_once_v2_extension
+ );
+ unwrap_future_proof!(lottie_sticker_message, is_lottie_sticker);
+ unwrap_future_proof!(document_with_caption_message, is_document_with_caption);
+ unwrap_future_proof!(edited_message, is_edit);
+ if let (Some(message), Some(raw)) = (self.message.as_mut(), self.raw_message.as_ref())
+ && message.message_context_info.is_none()
+ && raw.message_context_info.is_some()
+ {
+ message.message_context_info = raw.message_context_info.clone();
+ }
+ self
+ }
+}
+
+/// A receipt: delivered, read, played, retry, …
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct Receipt {
+ /// Who sent the receipt and where.
+ pub source: MessageSource,
+ /// The receipted messages.
+ pub message_ids: Vec<MessageId>,
+ /// When.
+ pub timestamp: Option<DateTime<Utc>>,
+ /// The kind of receipt.
+ pub r#type: ReceiptType,
+ /// The sender of the messages, for receipts of other people's messages.
+ pub message_sender: Jid,
+}
+
+/// Someone started or stopped typing.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct ChatPresence {
+ /// Who and where.
+ pub source: MessageSource,
+ /// Composing or paused.
+ pub state: ChatPresenceState,
+ /// What kind of message is being composed.
+ pub media: ChatPresenceMedia,
+}
+
+/// Someone's online status changed.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct Presence {
+ /// Whose.
+ pub from: Jid,
+ /// Whether they went offline.
+ pub unavailable: bool,
+ /// When they were last online, if known.
+ pub last_seen: Option<DateTime<Utc>>,
+}
+
+/// The user joined or was added to a group.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct JoinedGroup {
+ /// `invite` if the user joined with an invite link.
+ pub reason: String,
+ /// `new` for a newly created group.
+ pub r#type: String,
+ /// The create key, if the user created the group.
+ pub create_key: MessageId,
+ /// Who added the user.
+ pub sender: Option<Jid>,
+ /// The phone number of who added the user.
+ pub sender_pn: Option<Jid>,
+ /// The notify value.
+ pub notify: String,
+ /// The group.
+ pub group_info: GroupInfoType,
+}
+
+/// A group's info or participants changed.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct GroupInfo {
+ /// The group.
+ pub jid: Jid,
+ /// The notify value.
+ pub notify: String,
+ /// Who made the change.
+ pub sender: Option<Jid>,
+ /// The phone number of who made the change, if the sender is a LID.
+ pub sender_pn: Option<Jid>,
+ /// When.
+ pub timestamp: Option<DateTime<Utc>>,
+
+ /// A name change.
+ pub name: Option<GroupName>,
+ /// A topic change.
+ pub topic: Option<GroupTopic>,
+ /// A locked change.
+ pub locked: Option<GroupLocked>,
+ /// An announce change.
+ pub announce: Option<GroupAnnounce>,
+ /// A disappearing messages change.
+ pub ephemeral: Option<GroupEphemeral>,
+ /// A membership approval mode change.
+ pub membership_approval_mode: Option<GroupMembershipApprovalMode>,
+ /// The group was deleted.
+ pub delete: Option<GroupDelete>,
+ /// The group was linked.
+ pub link: Option<GroupLinkChange>,
+ /// The group was unlinked.
+ pub unlink: Option<GroupLinkChange>,
+ /// A new invite link.
+ pub new_invite_link: Option<String>,
+
+ /// The previous participant list version.
+ pub prev_participant_version_id: String,
+ /// The participant list version.
+ pub participant_version_id: String,
+
+ /// `invite` if the user joined via invite link.
+ pub join_reason: String,
+
+ /// Users who joined or were added.
+ pub join: Vec<Jid>,
+ /// Users who left or were removed.
+ pub leave: Vec<Jid>,
+ /// Users promoted to admins.
+ pub promote: Vec<Jid>,
+ /// Users demoted to normal users.
+ pub demote: Vec<Jid>,
+ /// Whether the group was suspended.
+ pub suspended: bool,
+ /// Whether the group was unsuspended.
+ pub unsuspended: bool,
+ /// Changes this port doesn't parse.
+ pub unknown_changes: Vec<Node>,
+}
+
+/// A profile picture changed.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct Picture {
+ /// The user or group whose picture changed.
+ pub jid: Jid,
+ /// Who changed it.
+ pub author: Jid,
+ /// When.
+ pub timestamp: Option<DateTime<Utc>>,
+ /// Whether the picture was removed.
+ pub remove: bool,
+ /// The new picture ID if it wasn't removed.
+ pub picture_id: String,
+}
+
+/// A user's about text changed.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct UserAbout {
+ /// Whose.
+ pub jid: Jid,
+ /// The new text.
+ pub status: String,
+ /// When.
+ pub timestamp: Option<DateTime<Utc>>,
+}
+
+/// A user's identity key changed; their sessions were deleted.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct IdentityChange {
+ /// Whose.
+ pub jid: Jid,
+ /// When.
+ pub timestamp: Option<DateTime<Utc>>,
+ /// Whether this was detected from an untrusted identity error rather
+ /// than a notification.
+ pub implicit: bool,
+}
+
+/// The user's privacy settings changed.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct PrivacySettings {
+ /// The new settings.
+ pub new_settings: PrivacySettingsType,
+ /// Whether group add changed.
+ pub group_add_changed: bool,
+ /// Whether last seen changed.
+ pub last_seen_changed: bool,
+ /// Whether status changed.
+ pub status_changed: bool,
+ /// Whether profile changed.
+ pub profile_changed: bool,
+ /// Whether read receipts changed.
+ pub read_receipts_changed: bool,
+ /// Whether online changed.
+ pub online_changed: bool,
+ /// Whether call add changed.
+ pub call_add_changed: bool,
+ /// Whether messages changed.
+ pub messages_changed: bool,
+ /// Whether defense changed.
+ pub defense_changed: bool,
+ /// Whether stickers changed.
+ pub stickers_changed: bool,
+}
+
+/// The server is about to deliver the offline backlog.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct OfflineSyncPreview {
+ /// Total items.
+ pub total: i64,
+ /// App state changes.
+ pub app_data_changes: i64,
+ /// Messages.
+ pub messages: i64,
+ /// Notifications.
+ pub notifications: i64,
+ /// Receipts.
+ pub receipts: i64,
+}
+
+/// The offline backlog was delivered.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct OfflineSyncCompleted {
+ /// How many items.
+ pub count: i64,
+}
+
+string_enum! {
+ /// A blocklist event action.
+ #[derive(Default)]
+ pub enum BlocklistAction {
+ /// The whole list.
+ #[default]
+ Default = "",
+ /// A change.
+ Modify = "modify",
+ }
+}
+
+/// The blocklist changed.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct Blocklist {
+ /// Whether this is the whole list or a change.
+ pub action: BlocklistAction,
+ /// The list hash.
+ pub d_hash: String,
+ /// The previous list hash.
+ pub prev_d_hash: String,
+ /// The changes.
+ pub changes: Vec<BlocklistChange>,
+}
+
+string_enum! {
+ /// A blocklist change action.
+ pub enum BlocklistChangeAction {
+ /// Blocked.
+ Block = "block",
+ /// Unblocked.
+ Unblock = "unblock",
+ }
+}
+
+/// One blocklist change.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct BlocklistChange {
+ /// Who.
+ pub jid: Jid,
+ /// Blocked or unblocked.
+ pub action: BlocklistChangeAction,
+}
diff --git a/crates/whatsmeow/src/types/group.rs b/crates/whatsmeow/src/types/group.rs
new file mode 100644
index 0000000000..f73da87e79
--- /dev/null
+++ b/crates/whatsmeow/src/types/group.rs
@@ -0,0 +1,275 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+//
+// Ported from whatsmeow types/group.go (MPL-2.0, Copyright (c) Tulir Asokan)
+//
+// Go embeds the `GroupName`, `GroupTopic`, … structs in `GroupInfo`; here
+// they are named fields. Go's zero `time.Time` is `None`.
+
+use chrono::{DateTime, Utc};
+
+use super::{AddressingMode, Jid};
+
+string_enum! {
+ /// Who can add members to a group.
+ #[derive(Default)]
+ pub enum GroupMemberAddMode {
+ /// Only admins.
+ Admin = "admin_add",
+ /// Every member.
+ AllMember = "all_member_add",
+ /// Not set.
+ #[default]
+ Empty = "",
+ }
+}
+
+/// Basic information about a group chat on WhatsApp.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct GroupInfo {
+ /// The group.
+ pub jid: Jid,
+ /// The owner.
+ pub owner_jid: Jid,
+ /// The owner's phone number JID.
+ pub owner_pn: Jid,
+
+ /// The name.
+ pub name: GroupName,
+ /// The topic (description).
+ pub topic: GroupTopic,
+ /// Whether only admins can edit group info.
+ pub locked: GroupLocked,
+ /// Whether only admins can send messages.
+ pub announce: GroupAnnounce,
+ /// Disappearing messages.
+ pub ephemeral: GroupEphemeral,
+ /// Incognito mode.
+ pub incognito: GroupIncognito,
+
+ /// Community parent settings.
+ pub parent: GroupParent,
+ /// The linked community.
+ pub linked_parent: GroupLinkedParent,
+ /// Whether this is the community's default subgroup.
+ pub is_default_sub: GroupIsDefaultSub,
+ /// Membership approval.
+ pub membership_approval_mode: GroupMembershipApprovalMode,
+
+ /// Whether members are addressed by phone number or LID.
+ pub addressing_mode: AddressingMode,
+ /// When the group was created.
+ pub group_created: Option<DateTime<Utc>>,
+ /// The creator's country code.
+ pub creator_country_code: String,
+
+ /// The participant list version.
+ pub participant_version_id: String,
+ /// The participants.
+ pub participants: Vec<GroupParticipant>,
+ /// The number of participants.
+ pub participant_count: i64,
+
+ /// Who can add members.
+ pub member_add_mode: GroupMemberAddMode,
+
+ /// Whether the group is currently paused/suspended.
+ pub suspended: bool,
+}
+
+/// Whether joining needs admin approval.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct GroupMembershipApprovalMode {
+ /// Whether joining needs approval.
+ pub is_join_approval_required: bool,
+}
+
+/// Community parent settings.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct GroupParent {
+ /// Whether the group is a community.
+ pub is_parent: bool,
+ /// The default membership approval mode (`request_required`).
+ pub default_membership_approval_mode: String,
+}
+
+/// The community a group is linked to.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct GroupLinkedParent {
+ /// The community.
+ pub linked_parent_jid: Jid,
+}
+
+/// Whether a group is a community's default subgroup.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct GroupIsDefaultSub {
+ /// Whether it is the default subgroup.
+ pub is_default_sub_group: bool,
+}
+
+/// The name of a group along with who set it and when.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct GroupName {
+ /// The name.
+ pub name: String,
+ /// When it was set.
+ pub name_set_at: Option<DateTime<Utc>>,
+ /// Who set it.
+ pub name_set_by: Jid,
+ /// The phone number JID of who set it.
+ pub name_set_by_pn: Jid,
+}
+
+/// The topic (description) of a group along with who set it and when.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct GroupTopic {
+ /// The topic.
+ pub topic: String,
+ /// The topic ID.
+ pub topic_id: String,
+ /// When it was set.
+ pub topic_set_at: Option<DateTime<Utc>>,
+ /// Who set it.
+ pub topic_set_by: Jid,
+ /// The phone number JID of who set it.
+ pub topic_set_by_pn: Jid,
+ /// Whether it was deleted.
+ pub topic_deleted: bool,
+}
+
+/// Whether the group info can only be edited by admins.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct GroupLocked {
+ /// Whether it is locked.
+ pub is_locked: bool,
+}
+
+/// Whether only admins can send messages in the group.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct GroupAnnounce {
+ /// Whether it is announce-only.
+ pub is_announce: bool,
+ /// The announce setting version.
+ pub announce_version_id: String,
+}
+
+/// Incognito mode.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct GroupIncognito {
+ /// Whether it is incognito.
+ pub is_incognito: bool,
+}
+
+/// A participant of a WhatsApp group chat.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct GroupParticipant {
+ /// The primary JID to send messages to this participant: either the LID
+ /// or the phone number.
+ pub jid: Jid,
+ /// The phone number JID.
+ pub phone_number: Jid,
+ /// The LID.
+ pub lid: Jid,
+
+ /// Whether the participant is an admin.
+ pub is_admin: bool,
+ /// Whether the participant is the super admin.
+ pub is_super_admin: bool,
+
+ /// Only for anonymous users in announcement groups: an obfuscated phone number.
+ pub display_name: String,
+
+ /// When creating groups, adding some participants may fail with this code.
+ pub error: i64,
+ /// The invite sent instead of adding the participant.
+ pub add_request: Option<GroupParticipantAddRequest>,
+}
+
+/// An invite sent instead of adding a participant directly.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct GroupParticipantAddRequest {
+ /// The invite code.
+ pub code: String,
+ /// When it expires.
+ pub expiration: Option<DateTime<Utc>>,
+}
+
+/// The group's disappearing messages settings.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct GroupEphemeral {
+ /// Whether messages disappear.
+ pub is_ephemeral: bool,
+ /// The timer in seconds.
+ pub disappearing_timer: u32,
+}
+
+/// A group deletion.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct GroupDelete {
+ /// Whether the group was deleted.
+ pub deleted: bool,
+ /// Why.
+ pub delete_reason: String,
+}
+
+string_enum! {
+ /// How a group was linked to another.
+ #[derive(Default)]
+ pub enum GroupLinkChangeType {
+ /// To a parent community.
+ Parent = "parent_group",
+ /// To a subgroup.
+ Sub = "sub_group",
+ /// To a sibling.
+ Sibling = "sibling_group",
+ /// Not set.
+ #[default]
+ Empty = "",
+ }
+}
+
+string_enum! {
+ /// Why a group was unlinked.
+ #[derive(Default)]
+ pub enum GroupUnlinkReason {
+ /// Unlinked.
+ Default = "unlink_group",
+ /// The parent was deleted.
+ Delete = "delete_parent",
+ /// Not set.
+ #[default]
+ Empty = "",
+ }
+}
+
+/// The other group of a link change.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct GroupLinkTarget {
+ /// The group.
+ pub jid: Jid,
+ /// Its name.
+ pub name: GroupName,
+ /// Whether it is the default subgroup.
+ pub is_default_sub: GroupIsDefaultSub,
+}
+
+/// A group link change.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct GroupLinkChange {
+ /// How the groups are linked.
+ pub r#type: GroupLinkChangeType,
+ /// Why they were unlinked.
+ pub unlink_reason: GroupUnlinkReason,
+ /// The other group.
+ pub group: GroupLinkTarget,
+}
+
+/// A request to join a group.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct GroupParticipantRequest {
+ /// Who asked.
+ pub jid: Jid,
+ /// When.
+ pub requested_at: Option<DateTime<Utc>>,
+}
diff --git a/crates/whatsmeow/src/types/jid.rs b/crates/whatsmeow/src/types/jid.rs
new file mode 100644
index 0000000000..b99e4a02d2
--- /dev/null
+++ b/crates/whatsmeow/src/types/jid.rs
@@ -0,0 +1,291 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+//
+// Ported from whatsmeow types/jid.go (MPL-2.0, Copyright (c) Tulir Asokan)
+
+use std::fmt;
+use std::num::ParseIntError;
+use std::str::FromStr;
+use std::sync::LazyLock;
+
+use crate::signal::SignalAddress;
+
+// Known JID servers on WhatsApp.
+
+/// The server of regular (phone number) users.
+pub const DEFAULT_USER_SERVER: &str = "s.whatsapp.net";
+/// The server of groups.
+pub const GROUP_SERVER: &str = "g.us";
+/// The legacy server of regular users.
+pub const LEGACY_USER_SERVER: &str = "c.us";
+/// The server of broadcast lists and the status broadcast.
+pub const BROADCAST_SERVER: &str = "broadcast";
+/// The server of LID (hidden user) JIDs.
+pub const HIDDEN_USER_SERVER: &str = "lid";
+/// The server of Messenger users.
+pub const MESSENGER_SERVER: &str = "msgr";
+/// The server of interop users.
+pub const INTEROP_SERVER: &str = "interop";
+/// The server of newsletters (channels).
+pub const NEWSLETTER_SERVER: &str = "newsletter";
+/// The server of hosted (business API) users.
+pub const HOSTED_SERVER: &str = "hosted";
+/// The server of hosted LID users.
+pub const HOSTED_LID_SERVER: &str = "hosted.lid";
+/// The server of bots.
+pub const BOT_SERVER: &str = "bot";
+
+// Some JIDs that are contacted often.
+
+/// The empty JID.
+pub static EMPTY_JID: LazyLock<Jid> = LazyLock::new(Jid::default);
+/// The group server itself.
+pub static GROUP_SERVER_JID: LazyLock<Jid> = LazyLock::new(|| new_jid("", GROUP_SERVER));
+/// The user server itself.
+pub static SERVER_JID: LazyLock<Jid> = LazyLock::new(|| new_jid("", DEFAULT_USER_SERVER));
+/// The broadcast server itself.
+pub static BROADCAST_SERVER_JID: LazyLock<Jid> = LazyLock::new(|| new_jid("", BROADCAST_SERVER));
+/// The status broadcast.
+pub static STATUS_BROADCAST_JID: LazyLock<Jid> =
+ LazyLock::new(|| new_jid("status", BROADCAST_SERVER));
+/// The legacy public service announcement account.
+pub static LEGACY_PSA_JID: LazyLock<Jid> = LazyLock::new(|| new_jid("0", LEGACY_USER_SERVER));
+/// The public service announcement account.
+pub static PSA_JID: LazyLock<Jid> = LazyLock::new(|| new_jid("0", DEFAULT_USER_SERVER));
+/// The official WhatsApp business account.
+pub static OFFICIAL_BUSINESS_JID: LazyLock<Jid> =
+ LazyLock::new(|| new_jid("16505361212", LEGACY_USER_SERVER));
+/// Meta AI on the user server.
+pub static META_AI_JID: LazyLock<Jid> =
+ LazyLock::new(|| new_jid("13135550002", DEFAULT_USER_SERVER));
+/// Meta AI on the bot server.
+pub static NEW_META_AI_JID: LazyLock<Jid> =
+ LazyLock::new(|| new_jid("867051314767696", BOT_SERVER));
+/// Also known as "hatch".
+pub static MUSE_JID: LazyLock<Jid> = LazyLock::new(|| new_jid("1807055946647697", BOT_SERVER));
+
+/// The main domain type that WhatsApp uses.
+pub const WHATSAPP_DOMAIN: u8 = 0;
+/// The domain for LID type JIDs.
+pub const LID_DOMAIN: u8 = 1;
+/// The domain for hosted type JIDs.
+pub const HOSTED_DOMAIN: u8 = 128;
+/// The domain for hosted LID type JIDs.
+pub const HOSTED_LID_DOMAIN: u8 = 129;
+
+/// The internal ID of a WhatsApp message.
+pub type MessageId = String;
+
+/// The server ID of a WhatsApp newsletter message.
+pub type MessageServerId = i64;
+
+/// A WhatsApp user ID.
+///
+/// There are two types of JIDs: regular JID pairs (user and server) and AD-JIDs
+/// (user, agent and device). AD JIDs are only used to refer to specific devices
+/// of users, so the server is always s.whatsapp.net (`DEFAULT_USER_SERVER`).
+/// Regular JIDs can be used for entities on any servers (users, groups,
+/// broadcasts).
+#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
+pub struct Jid {
+ /// The user part, e.g. a phone number.
+ pub user: String,
+ /// The agent of an AD JID.
+ pub raw_agent: u8,
+ /// The device number of an AD JID.
+ pub device: u16,
+ /// The integrator of an interop JID.
+ pub integrator: u16,
+ /// The server part.
+ pub server: String,
+}
+
+/// An error from [`parse_jid`]. The messages match whatsmeow's.
+#[derive(Debug, thiserror::Error, PartialEq, Eq)]
+pub enum JidParseError {
+ /// The user part had more than one dot.
+ #[error("unexpected number of dots in JID")]
+ UnexpectedDots,
+ /// The user part had more than one colon.
+ #[error("unexpected number of colons in JID")]
+ UnexpectedColons,
+ /// The agent or device wasn't a number in range. Go truncates out-of-range
+ /// numbers silently; the port rejects them.
+ #[error("failed to parse device from JID: {0}")]
+ InvalidDevice(#[source] ParseIntError),
+}
+
+impl Jid {
+ /// The domain type of the JID, derived from the server where it implies one.
+ pub fn actual_agent(&self) -> u8 {
+ match self.server.as_str() {
+ DEFAULT_USER_SERVER => WHATSAPP_DOMAIN,
+ HIDDEN_USER_SERVER => LID_DOMAIN,
+ HOSTED_SERVER => HOSTED_DOMAIN,
+ HOSTED_LID_SERVER => HOSTED_LID_DOMAIN,
+ _ => self.raw_agent,
+ }
+ }
+
+ /// The user as an integer. This is only meaningful for normal users, not
+ /// for groups or broadcast lists; anything unparseable is 0.
+ pub fn user_int(&self) -> u64 {
+ self.user.parse().unwrap_or_default()
+ }
+
+ /// A version of the JID that doesn't have the agent and device set.
+ pub fn to_non_ad(&self) -> Jid {
+ Jid {
+ user: self.user.clone(),
+ server: self.server.clone(),
+ integrator: self.integrator,
+ ..Jid::default()
+ }
+ }
+
+ /// The Signal protocol address for the user.
+ pub fn signal_address(&self) -> SignalAddress {
+ SignalAddress::new(self.signal_address_user(), u32::from(self.device))
+ }
+
+ /// The name part of the Signal protocol address: the user, suffixed with
+ /// the domain type when it isn't the default.
+ pub fn signal_address_user(&self) -> String {
+ let agent = self.actual_agent();
+ if agent != 0 {
+ format!("{}_{}", self.user, agent)
+ } else {
+ self.user.clone()
+ }
+ }
+
+ /// Whether the JID is a broadcast list, but not the status broadcast.
+ pub fn is_broadcast_list(&self) -> bool {
+ self.server == BROADCAST_SERVER && self.user != STATUS_BROADCAST_JID.user
+ }
+
+ /// Whether the JID belongs to a bot.
+ pub fn is_bot(&self) -> bool {
+ (self.server == DEFAULT_USER_SERVER
+ && lazy_regex::regex_is_match!(r"^1313555\d{4}$|^131655500\d{2}$", &self.user)
+ && self.device == 0)
+ || self.server == BOT_SERVER
+ }
+
+ /// The JID in `user.agent:device@server` form, even when agent and device are 0.
+ pub fn ad_string(&self) -> String {
+ format!(
+ "{}.{}:{}@{}",
+ self.user, self.raw_agent, self.device, self.server
+ )
+ }
+
+ /// Whether the JID has no server (which is required for all JIDs).
+ pub fn is_empty(&self) -> bool {
+ self.server.is_empty()
+ }
+
+ /// Same as [`Jid::is_empty`].
+ pub fn is_zero(&self) -> bool {
+ self.is_empty()
+ }
+}
+
+/// Creates a new AD JID.
+///
+/// The agent is really the domain type; WhatsApp usually places them in the
+/// same position. Known domain types pick the server, anything else is kept as
+/// the agent of a regular user.
+pub fn new_ad_jid(user: &str, agent: u8, device: u8) -> Jid {
+ let (server, agent) = match agent {
+ LID_DOMAIN => (HIDDEN_USER_SERVER, 0),
+ HOSTED_DOMAIN => (HOSTED_SERVER, 0),
+ HOSTED_LID_DOMAIN => (HOSTED_LID_SERVER, 0),
+ _ => (DEFAULT_USER_SERVER, agent),
+ };
+ Jid {
+ user: user.to_owned(),
+ raw_agent: agent,
+ device: u16::from(device),
+ integrator: 0,
+ server: server.to_owned(),
+ }
+}
+
+/// Parses a JID out of the given string. It supports both regular and AD JIDs.
+pub fn parse_jid(jid: &str) -> Result<Jid, JidParseError> {
+ let parts: Vec<&str> = jid.split('@').collect();
+ if parts.len() == 1 {
+ return Ok(new_jid("", parts[0]));
+ }
+ let mut parsed = new_jid(parts[0], parts[1]);
+ if parts[0].contains('.') {
+ let dot_parts: Vec<&str> = parts[0].split('.').collect();
+ if dot_parts.len() != 2 {
+ return Err(JidParseError::UnexpectedDots);
+ }
+ parsed.user = dot_parts[0].to_owned();
+ let colon_parts: Vec<&str> = dot_parts[1].split(':').collect();
+ if colon_parts.len() > 2 {
+ return Err(JidParseError::UnexpectedColons);
+ }
+ parsed.raw_agent = colon_parts[0]
+ .parse()
+ .map_err(JidParseError::InvalidDevice)?;
+ if let Some(device) = colon_parts.get(1) {
+ parsed.device = device.parse().map_err(JidParseError::InvalidDevice)?;
+ }
+ } else if parts[0].contains(':') {
+ let colon_parts: Vec<&str> = parts[0].split(':').collect();
+ if colon_parts.len() != 2 {
+ return Err(JidParseError::UnexpectedColons);
+ }
+ parsed.user = colon_parts[0].to_owned();
+ parsed.device = colon_parts[1]
+ .parse()
+ .map_err(JidParseError::InvalidDevice)?;
+ }
+ Ok(parsed)
+}
+
+/// Creates a new regular JID.
+pub fn new_jid(user: &str, server: &str) -> Jid {
+ Jid {
+ user: user.to_owned(),
+ server: server.to_owned(),
+ ..Jid::default()
+ }
+}
+
+/// The string representation of the JID, which [`parse_jid`] can parse back.
+impl fmt::Display for Jid {
+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
+ if self.server.is_empty() {
+ Ok(())
+ } else if self.raw_agent > 0 {
+ write!(
+ formatter,
+ "{}.{}:{}@{}",
+ self.user, self.raw_agent, self.device, self.server
+ )
+ } else if self.device > 0 {
+ write!(formatter, "{}:{}@{}", self.user, self.device, self.server)
+ } else if !self.user.is_empty() {
+ write!(formatter, "{}@{}", self.user, self.server)
+ } else {
+ formatter.write_str(&self.server)
+ }
+ }
+}
+
+impl FromStr for Jid {
+ type Err = JidParseError;
+
+ fn from_str(jid: &str) -> Result<Self, Self::Err> {
+ parse_jid(jid)
+ }
+}
+
+#[cfg(test)]
+mod test;
diff --git a/crates/whatsmeow/src/types/jid/test.rs b/crates/whatsmeow/src/types/jid/test.rs
new file mode 100644
index 0000000000..92c35d3b8b
--- /dev/null
+++ b/crates/whatsmeow/src/types/jid/test.rs
@@ -0,0 +1,159 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+//! whatsmeow has no tests for JIDs. The expected values below were produced
+//! by whatsmeow's Go code at the pinned revision.
+
+use super::*;
+
+#[test]
+fn parse_jid_matches_go() {
+ let cases = [
+ ("", "", 0, 0, "", "", ".0:0@", ":0"),
+ (
+ "s.whatsapp.net",
+ "",
+ 0,
+ 0,
+ "s.whatsapp.net",
+ "s.whatsapp.net",
+ ":0",
+ ),
+ (
+ "1234567890",
+ 0,
+ 0,
+ "s.whatsapp.net",
+ "1234567890.0:[email protected]",
+ "1234567890:0",
+ ),
+ (
+ "1234567890:[email protected]",
+ "1234567890",
+ 0,
+ 12,
+ "s.whatsapp.net",
+ "1234567890:[email protected]",
+ "1234567890.0:[email protected]",
+ "1234567890:12",
+ ),
+ (
+ "1234567890.1:[email protected]",
+ "1234567890",
+ 1,
+ 12,
+ "s.whatsapp.net",
+ "1234567890.1:[email protected]",
+ "1234567890.1:[email protected]",
+ "1234567890:12",
+ ),
+ (
+ "1234567890",
+ 1,
+ 0,
+ "s.whatsapp.net",
+ "1234567890.1:[email protected]",
+ "1234567890.1:[email protected]",
+ "1234567890:0",
+ ),
+ (
+ "98765432101234:3@lid",
+ "98765432101234",
+ 0,
+ 3,
+ "lid",
+ "98765432101234:3@lid",
+ "98765432101234.0:3@lid",
+ "98765432101234_1:3",
+ ),
+ (
+ "status@broadcast",
+ "status",
+ 0,
+ 0,
+ "broadcast",
+ "status@broadcast",
+ "status.0:0@broadcast",
+ "status:0",
+ ),
+ ("a@b@c", "a", 0, 0, "b", "a@b", "a.0:0@b", "a:0"),
+ ];
+ for (input, user, agent, device, server, string, ad_string, signal_address) in cases {
+ let jid = parse_jid(input).unwrap();
+ assert_eq!(jid.user, user, "{input}");
+ assert_eq!(jid.raw_agent, agent, "{input}");
+ assert_eq!(jid.device, device, "{input}");
+ assert_eq!(jid.server, server, "{input}");
+ assert_eq!(jid.to_string(), string, "{input}");
+ assert_eq!(jid.ad_string(), ad_string, "{input}");
+ assert_eq!(jid.signal_address().to_string(), signal_address, "{input}");
+ }
+}
+
+#[test]
+fn parse_jid_errors_match_go() {
+ assert_eq!(
+ parse_jid("[email protected]").unwrap_err().to_string(),
+ "unexpected number of dots in JID"
+ );
+ assert_eq!(
+ parse_jid("a:b:[email protected]").unwrap_err().to_string(),
+ "unexpected number of colons in JID"
+ );
+ assert_eq!(
+ parse_jid("1.2:3:[email protected]").unwrap_err().to_string(),
+ "unexpected number of colons in JID"
+ );
+ assert!(matches!(
+ parse_jid("x:[email protected]"),
+ Err(JidParseError::InvalidDevice(_))
+ ));
+ assert!(matches!(
+ "[email protected]".parse::<Jid>(),
+ Err(JidParseError::InvalidDevice(_))
+ ));
+}
+
+#[test]
+fn new_ad_jid_maps_domains_to_servers() {
+ let cases = [
+ (0, "123:[email protected]", 0, 0, "123:5"),
+ (1, "123:5@lid", 0, 1, "123_1:5"),
+ (128, "123:5@hosted", 0, 128, "123_128:5"),
+ (129, "123:[email protected]", 0, 129, "123_129:5"),
+ (7, "123.7:[email protected]", 7, 0, "123:5"),
+ ];
+ for (domain, string, raw_agent, actual_agent, signal_address) in cases {
+ let jid = new_ad_jid("123", domain, 5);
+ assert_eq!(jid.to_string(), string);
+ assert_eq!(jid.raw_agent, raw_agent);
+ assert_eq!(jid.actual_agent(), actual_agent);
+ assert_eq!(jid.signal_address().to_string(), signal_address);
+ }
+}
+
+#[test]
+fn is_bot_matches_go() {
+ assert!(parse_jid("[email protected]").unwrap().is_bot());
+ assert!(parse_jid("[email protected]").unwrap().is_bot());
+ assert!(!parse_jid("13135551234:[email protected]").unwrap().is_bot());
+ assert!(parse_jid("123@bot").unwrap().is_bot());
+ assert!(!parse_jid("[email protected]").unwrap().is_bot());
+}
+
+#[test]
+fn helpers_follow_go_semantics() {
+ let jid = parse_jid("1234567890.1:[email protected]").unwrap();
+ assert_eq!(jid.to_non_ad().to_string(), "[email protected]");
+ assert_eq!(jid.user_int(), 1_234_567_890);
+ assert_eq!(STATUS_BROADCAST_JID.user_int(), 0);
+ assert!(!STATUS_BROADCAST_JID.is_broadcast_list());
+ assert!(parse_jid("123@broadcast").unwrap().is_broadcast_list());
+ assert!(EMPTY_JID.is_empty());
+ assert!(!SERVER_JID.is_empty());
+}
diff --git a/crates/whatsmeow/src/types/message.rs b/crates/whatsmeow/src/types/message.rs
new file mode 100644
index 0000000000..07366a16c3
--- /dev/null
+++ b/crates/whatsmeow/src/types/message.rs
@@ -0,0 +1,207 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+//
+// Ported from whatsmeow types/message.go (MPL-2.0, Copyright (c) Tulir Asokan)
+
+use chrono::{DateTime, Utc};
+
+use super::{Jid, MessageId, MessageServerId, VerifiedName};
+
+string_enum! {
+ /// Whether a chat addresses users by phone number or by LID.
+ #[derive(Default)]
+ pub enum AddressingMode {
+ /// Phone numbers (`pn`).
+ Pn = "pn",
+ /// LIDs (`lid`).
+ Lid = "lid",
+ /// Not set.
+ #[default]
+ Empty = "",
+ }
+}
+
+/// One recipient of a broadcast list message.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct BroadcastRecipient {
+ /// The recipient's LID.
+ pub lid: Jid,
+ /// The recipient's phone number JID.
+ pub pn: Jid,
+}
+
+/// Basic sender and chat information about a message.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct MessageSource {
+ /// The chat where the message was sent.
+ pub chat: Jid,
+ /// The user who sent the message.
+ pub sender: Jid,
+ /// Whether the message was sent by the current user instead of someone else.
+ pub is_from_me: bool,
+ /// Whether the chat is a group chat or broadcast list.
+ pub is_group: bool,
+
+ /// The addressing mode of the message (phone number or LID).
+ pub addressing_mode: AddressingMode,
+ /// The alternative address of the user who sent the message.
+ pub sender_alt: Jid,
+ /// The alternative address of the recipient of the message for DMs.
+ pub recipient_alt: Jid,
+
+ /// When sending a read receipt to a broadcast list message, the chat is
+ /// the broadcast list and the sender is you, so this holds the recipient.
+ pub broadcast_list_owner: Jid,
+ /// The recipients of a broadcast list message.
+ pub broadcast_recipients: Vec<BroadcastRecipient>,
+}
+
+impl MessageSource {
+ /// Whether the message was sent to a broadcast list instead of directly to
+ /// the user; if so, it shows up in the direct chat with the sender.
+ pub fn is_incoming_broadcast(&self) -> bool {
+ (!self.is_from_me || !self.broadcast_list_owner.is_empty()) && self.chat.is_broadcast_list()
+ }
+
+ /// A log-friendly representation of who sent the message and where.
+ pub fn source_string(&self) -> String {
+ if self.sender != self.chat {
+ format!("{} in {}", self.sender, self.chat)
+ } else {
+ self.chat.to_string()
+ }
+ }
+}
+
+/// Metadata from messages sent by another one of the user's own devices.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct DeviceSentMeta {
+ /// The destination user.
+ pub destination_jid: String,
+ /// The participant hash.
+ pub phash: String,
+}
+
+string_enum! {
+ /// The `edit` attribute of a message.
+ #[derive(Default)]
+ pub enum EditAttribute {
+ /// Not an edit.
+ #[default]
+ Empty = "",
+ /// A message edit.
+ MessageEdit = "1",
+ /// Pinning a message in a chat.
+ PinInChat = "2",
+ /// An admin edit (only used in newsletters).
+ AdminEdit = "3",
+ /// The sender revoking (deleting) a message.
+ SenderRevoke = "7",
+ /// An admin revoking a message.
+ AdminRevoke = "8",
+ }
+}
+
+string_enum! {
+ /// The edit type of a bot message.
+ #[derive(Default)]
+ pub enum BotEditType {
+ /// The first part.
+ First = "first",
+ /// An inner part.
+ Inner = "inner",
+ /// The last part.
+ Last = "last",
+ /// The full message.
+ Full = "full",
+ /// Not set.
+ #[default]
+ Empty = "",
+ }
+}
+
+/// Bot metadata of a message (`<bot>`).
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct MsgBotInfo {
+ /// The edit type.
+ pub edit_type: BotEditType,
+ /// The edited message.
+ pub edit_target_id: MessageId,
+ /// When the edited message was sent.
+ pub edit_sender_timestamp_ms: Option<DateTime<Utc>>,
+ /// The thread ID, for messages sent to bots.
+ pub client_thread_id: String,
+}
+
+/// The `<meta>` metadata of a message.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct MsgMetaInfo {
+ /// The bot target message ID.
+ pub target_id: MessageId,
+ /// The bot target sender.
+ pub target_sender: Jid,
+ /// The bot target chat.
+ pub target_chat: Jid,
+
+ /// The deprecated LID session flag.
+ pub deprecated_lid_session: Option<bool>,
+
+ /// The thread the message is in.
+ pub thread_message_id: MessageId,
+ /// The sender of the thread's root message.
+ pub thread_message_sender_jid: Jid,
+}
+
+/// Metadata about an incoming message.
+#[derive(Clone, Debug, Default, PartialEq)]
+pub struct MessageInfo {
+ /// Who sent the message and where.
+ pub source: MessageSource,
+ /// The message ID.
+ pub id: MessageId,
+ /// The server ID (newsletters only).
+ pub server_id: MessageServerId,
+ /// The message type (`text`, `media`, …).
+ pub r#type: String,
+ /// The sender's push name.
+ pub push_name: String,
+ /// When the message was sent; `None` is Go's zero time.
+ pub timestamp: Option<DateTime<Utc>>,
+ /// The message category.
+ pub category: String,
+ /// Whether the message was multicast.
+ pub multicast: bool,
+ /// The media type.
+ pub media_type: String,
+ /// The edit attribute.
+ pub edit: EditAttribute,
+
+ /// Bot metadata.
+ pub msg_bot_info: MsgBotInfo,
+ /// `<meta>` metadata.
+ pub msg_meta_info: MsgMetaInfo,
+
+ /// Whether this is a newsletter status.
+ pub is_newsletter_status: bool,
+
+ /// The sender's verified business name.
+ pub verified_name: Option<VerifiedName>,
+ /// Metadata for direct messages sent from another one of the user's own devices.
+ pub device_sent_meta: Option<DeviceSentMeta>,
+}
+
+impl std::ops::Deref for MessageInfo {
+ type Target = MessageSource;
+
+ /// Go embeds `MessageSource` in `MessageInfo`.
+ fn deref(&self) -> &MessageSource {
+ &self.source
+ }
+}
+
+impl std::ops::DerefMut for MessageInfo {
+ fn deref_mut(&mut self) -> &mut MessageSource {
+ &mut self.source
+ }
+}
diff --git a/crates/whatsmeow/src/types/passkey.rs b/crates/whatsmeow/src/types/passkey.rs
new file mode 100644
index 0000000000..8a3ef15ea1
--- /dev/null
+++ b/crates/whatsmeow/src/types/passkey.rs
@@ -0,0 +1,99 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+//
+// Ported from whatsmeow types/passkey.go (MPL-2.0, Copyright (c) Tulir Asokan)
+//
+// Go's `jsonbytes.UnpaddedURLBytes` is [`UnpaddedUrlBytes`]; the JSON field
+// names and order match Go's.
+
+use base64::Engine;
+use base64::engine::general_purpose::URL_SAFE_NO_PAD;
+use serde::{Deserialize, Deserializer, Serialize, Serializer};
+
+/// Bytes that are unpadded URL-safe base64 in JSON.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct UnpaddedUrlBytes(pub Vec<u8>);
+
+impl Serialize for UnpaddedUrlBytes {
+ fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
+ serializer.serialize_str(&URL_SAFE_NO_PAD.encode(&self.0))
+ }
+}
+
+impl<'de> Deserialize<'de> for UnpaddedUrlBytes {
+ fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
+ let value = String::deserialize(deserializer)?;
+ URL_SAFE_NO_PAD
+ .decode(value)
+ .map(UnpaddedUrlBytes)
+ .map_err(serde::de::Error::custom)
+ }
+}
+
+/// The WebAuthn request options the server sends when pairing needs a passkey.
+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
+#[serde(default)]
+pub struct WebAuthnPublicKey {
+ /// The challenge to sign.
+ pub challenge: UnpaddedUrlBytes,
+ /// The timeout in milliseconds.
+ pub timeout: i64,
+ /// The relying party ID.
+ #[serde(rename = "rpId")]
+ pub relying_party_id: String,
+ /// The credentials that may answer.
+ #[serde(rename = "allowCredentials")]
+ pub allow_credentials: Vec<AllowedCredential>,
+ /// The user verification requirement.
+ #[serde(rename = "userVerification")]
+ pub user_verification: String,
+ /// Extensions, passed through as JSON.
+ pub extensions: serde_json::Map<String, serde_json::Value>,
+}
+
+/// A credential allowed to answer a WebAuthn request.
+#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(default)]
+pub struct AllowedCredential {
+ /// The credential ID.
+ pub id: UnpaddedUrlBytes,
+ /// The credential type (`public-key`).
+ #[serde(rename = "type")]
+ pub r#type: String,
+ /// The transports.
+ pub transports: Vec<String>,
+}
+
+/// The authenticator's answer to a [`WebAuthnPublicKey`] request.
+#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(default)]
+pub struct WebAuthnResponse {
+ /// The credential ID as a string.
+ pub id: String,
+ /// The raw credential ID.
+ #[serde(rename = "rawId")]
+ pub raw_id: UnpaddedUrlBytes,
+ /// The credential type.
+ #[serde(rename = "type")]
+ pub r#type: String,
+ /// The assertion.
+ pub response: WebAuthnResponseData,
+}
+
+/// The signed parts of a WebAuthn assertion.
+#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(default)]
+pub struct WebAuthnResponseData {
+ /// The client data JSON.
+ #[serde(rename = "clientDataJSON")]
+ pub client_data_json: UnpaddedUrlBytes,
+ /// The authenticator data.
+ #[serde(rename = "authenticatorData")]
+ pub authenticator_data: UnpaddedUrlBytes,
+ /// The signature.
+ pub signature: UnpaddedUrlBytes,
+ /// The user handle, if any.
+ #[serde(rename = "userHandle")]
+ pub user_handle: Option<UnpaddedUrlBytes>,
+}
diff --git a/crates/whatsmeow/src/types/presence.rs b/crates/whatsmeow/src/types/presence.rs
new file mode 100644
index 0000000000..9b95b6ac41
--- /dev/null
+++ b/crates/whatsmeow/src/types/presence.rs
@@ -0,0 +1,68 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+//
+// Ported from whatsmeow types/presence.go (MPL-2.0, Copyright (c) Tulir Asokan)
+
+string_enum! {
+ /// Online presence.
+ pub enum Presence {
+ /// Online.
+ Available = "available",
+ /// Offline.
+ Unavailable = "unavailable",
+ }
+}
+
+string_enum! {
+ /// Typing state in a chat.
+ pub enum ChatPresence {
+ /// Typing.
+ Composing = "composing",
+ /// Stopped typing.
+ Paused = "paused",
+ }
+}
+
+string_enum! {
+ /// What kind of message is being composed.
+ pub enum ChatPresenceMedia {
+ /// Text.
+ Text = "",
+ /// A voice message.
+ Audio = "audio",
+ }
+}
+
+string_enum! {
+ /// The type of a receipt.
+ #[derive(Default)]
+ pub enum ReceiptType {
+ /// The message was delivered to the device (but the user might not
+ /// have noticed).
+ #[default]
+ Delivered = "",
+ /// Sent by your other devices when a message you sent is delivered to them.
+ Sender = "sender",
+ /// The message was delivered, but decrypting it failed.
+ Retry = "retry",
+ /// The user opened the chat and saw the message.
+ Read = "read",
+ /// The current user read a message from a different device, and has
+ /// read receipts disabled in privacy settings.
+ ReadSelf = "read-self",
+ /// The user opened a view-once media message.
+ Played = "played",
+ /// The current user opened a view-once media message from a different
+ /// device, with read receipts disabled.
+ PlayedSelf = "played-self",
+ /// The server failed to deliver the message.
+ ServerError = "server-error",
+ /// Delivered to an inactive client.
+ Inactive = "inactive",
+ /// A peer message.
+ PeerMsg = "peer_msg",
+ /// A history sync.
+ HistorySync = "hist_sync",
+ }
+}
diff --git a/crates/whatsmeow/src/types/user.rs b/crates/whatsmeow/src/types/user.rs
new file mode 100644
index 0000000000..2d75ccc5e5
--- /dev/null
+++ b/crates/whatsmeow/src/types/user.rs
@@ -0,0 +1,222 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+//
+// Ported from whatsmeow types/user.go (MPL-2.0, Copyright (c) Tulir Asokan)
+//
+// Not ported: the bot, business profile, business link, contact QR link and
+// status input types.
+
+use chrono::{DateTime, Utc};
+
+use super::{AddressingMode, Jid};
+use crate::proto::wa_vname_cert::{VerifiedNameCertificate, verified_name_certificate};
+
+/// A verified business name.
+#[derive(Clone, Debug, Default, PartialEq)]
+pub struct VerifiedName {
+ /// The certificate.
+ pub certificate: Option<VerifiedNameCertificate>,
+ /// The certificate details.
+ pub details: Option<verified_name_certificate::Details>,
+
+ /// The verification level.
+ pub verified_level: String,
+ /// The version.
+ pub version: i64,
+ /// The host storage.
+ pub host_storage: i64,
+ /// The actual actors.
+ pub actual_actors: i64,
+ /// The privacy mode timestamp.
+ pub privacy_mode_ts: Option<DateTime<Utc>>,
+}
+
+/// Information about a WhatsApp user.
+#[derive(Clone, Debug, Default, PartialEq)]
+pub struct UserInfo {
+ /// The verified business name.
+ pub verified_name: Option<VerifiedName>,
+ /// The about text.
+ pub status: String,
+ /// The profile picture ID.
+ pub picture_id: String,
+ /// The user's devices.
+ pub devices: Vec<Jid>,
+ /// The user's LID.
+ pub lid: Jid,
+}
+
+/// A user's profile picture.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct ProfilePictureInfo {
+ /// The full URL for the image.
+ pub url: String,
+ /// The ID of the image, the same as [`UserInfo::picture_id`].
+ pub id: String,
+ /// The type of image (`image` or `preview`).
+ pub r#type: String,
+ /// The path to the image.
+ pub direct_path: String,
+ /// Some kind of hash (format unknown).
+ pub hash: Vec<u8>,
+}
+
+/// Whether a phone number is on WhatsApp.
+#[derive(Clone, Debug, Default, PartialEq)]
+pub struct IsOnWhatsAppResponse {
+ /// The query string used.
+ pub query: String,
+ /// The canonical user ID.
+ pub jid: Jid,
+ /// Whether the phone is registered.
+ pub is_in: bool,
+ /// The phone number JID.
+ pub phone_number: Jid,
+ /// The verified business details, if the phone is a business.
+ pub verified_name: Option<VerifiedName>,
+}
+
+string_enum! {
+ /// A privacy setting value.
+ #[derive(Default)]
+ pub enum PrivacySetting {
+ /// Not set.
+ #[default]
+ Undefined = "",
+ /// Everyone.
+ All = "all",
+ /// Contacts.
+ Contacts = "contacts",
+ /// Some contacts.
+ ContactAllowlist = "contact_allowlist",
+ /// Contacts except some.
+ ContactBlacklist = "contact_blacklist",
+ /// Same as last seen.
+ MatchLastSeen = "match_last_seen",
+ /// Known.
+ Known = "known",
+ /// Nobody.
+ None = "none",
+ /// On (standard).
+ OnStandard = "on_standard",
+ /// Off.
+ Off = "off",
+ }
+}
+
+string_enum! {
+ /// A privacy setting name.
+ pub enum PrivacySettingType {
+ /// Who can add you to groups.
+ GroupAdd = "groupadd",
+ /// Who can see your last seen.
+ LastSeen = "last",
+ /// Who can see your status.
+ Status = "status",
+ /// Who can see your profile picture.
+ Profile = "profile",
+ /// Read receipts.
+ ReadReceipts = "readreceipts",
+ /// Who can see you online.
+ Online = "online",
+ /// Who can call you.
+ CallAdd = "calladd",
+ /// Who can message you.
+ Messages = "messages",
+ /// Defense mode.
+ Defense = "defense",
+ /// Who can send you stickers.
+ Stickers = "stickers",
+ }
+}
+
+/// The user's privacy settings.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct PrivacySettings {
+ /// Who can add you to groups.
+ pub group_add: PrivacySetting,
+ /// Who can see your last seen.
+ pub last_seen: PrivacySetting,
+ /// Who can see your status.
+ pub status: PrivacySetting,
+ /// Who can see your profile picture.
+ pub profile: PrivacySetting,
+ /// Read receipts.
+ pub read_receipts: PrivacySetting,
+ /// Who can call you.
+ pub call_add: PrivacySetting,
+ /// Who can see you online.
+ pub online: PrivacySetting,
+ /// Who can message you.
+ pub messages: PrivacySetting,
+ /// Defense mode.
+ pub defense: PrivacySetting,
+ /// Who can send you stickers.
+ pub stickers: PrivacySetting,
+}
+
+/// The cached names of a WhatsApp user. Go's `Found` flag is an `Option`
+/// around this struct instead.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct ContactInfo {
+ /// The first name from the address book.
+ pub first_name: String,
+ /// The full name from the address book.
+ pub full_name: String,
+ /// The name the user set for themselves.
+ pub push_name: String,
+ /// The verified business name.
+ pub business_name: String,
+ /// Only for LID members encountered in groups, the phone number in the
+ /// form "+1∙∙∙∙∙∙∙∙80".
+ pub redacted_phone: String,
+}
+
+/// The cached local settings for a chat. Go's `Found` flag is an `Option`
+/// around this struct instead.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct LocalChatSettings {
+ /// When the mute ends; `None` when not muted.
+ pub muted_until: Option<DateTime<Utc>>,
+ /// Whether the chat is pinned.
+ pub pinned: bool,
+ /// Whether the chat is archived.
+ pub archived: bool,
+}
+
+/// One blocked user.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct BlocklistItem {
+ /// The blocked user's LID.
+ pub lid: Jid,
+ /// The blocked user's phone number JID.
+ pub pn: Jid,
+ /// Whether the block is active.
+ pub active: bool,
+}
+
+/// The user's current list of blocked users.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct Blocklist {
+ /// How the list addresses users.
+ pub addressing_mode: AddressingMode,
+ /// The list hash.
+ pub d_hash: String,
+ /// The blocked users.
+ pub items: Vec<BlocklistItem>,
+}
+
+impl Blocklist {
+ /// The LIDs of the blocked users.
+ pub fn lids(&self) -> Vec<Jid> {
+ self.items.iter().map(|item| item.lid.clone()).collect()
+ }
+
+ /// Whether the user (by LID or phone number) is blocked.
+ pub fn is_blocked(&self, jid: &Jid) -> bool {
+ self.items
+ .iter()
+ .any(|item| item.lid == *jid || item.pn == *jid)
+ }
+}
diff --git a/crates/whatsmeow/src/upload.rs b/crates/whatsmeow/src/upload.rs
new file mode 100644
index 0000000000..36258bdcc3
--- /dev/null
+++ b/crates/whatsmeow/src/upload.rs
@@ -0,0 +1,376 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+//
+// Ported from whatsmeow upload.go (MPL-2.0, Copyright (c) Tulir Asokan)
+//
+// Like `download.rs`, the work happens in free functions taking the media
+// HTTP client and a refreshed media connection; the `Client` methods at the
+// bottom wrap them. Not ported:
+// `UploadReader` and `UploadNewsletterReader`, which stream from a reader
+// (the port's reqwest has no streaming bodies); `util::cbcutil::encrypt_stream`
+// is there for `UploadReader` when it is needed.
+
+//! Encrypting and uploading attachments.
+
+use base64::Engine;
+use base64::engine::general_purpose::{URL_SAFE, URL_SAFE_NO_PAD};
+use hmac::{Hmac, Mac};
+use serde::Deserialize;
+use sha2::{Digest, Sha256};
+
+use crate::download::{MEDIA_HMAC_LENGTH, MediaHttpClient, MediaType, get_media_keys};
+use crate::mediaconn::MediaConn;
+use crate::socket::ORIGIN;
+use crate::util::cbcutil::{self, CbcError};
+
+/// The data from an attachment upload, which can be put into a message to
+/// send the attachment: copy the fields to the corresponding fields of e.g.
+/// an `ImageMessage` (`url`, `direct_path`, `media_key`, `file_enc_sha256`,
+/// `file_sha256`, `file_length`).
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct UploadResponse {
+ /// The `url` from the server.
+ pub url: String,
+ /// The `direct_path` from the server.
+ pub direct_path: String,
+ /// The `handle` from the server; newsletter sends need it.
+ pub handle: String,
+ /// The `object_id` from the server.
+ pub object_id: String,
+
+ /// The random key the attachment is encrypted with; empty for newsletter
+ /// media.
+ pub media_key: Vec<u8>,
+ /// SHA-256 of the uploaded ciphertext and MAC; empty for newsletter media.
+ pub file_enc_sha256: Vec<u8>,
+ /// SHA-256 of the plaintext.
+ pub file_sha256: Vec<u8>,
+ /// The plaintext length.
+ pub file_length: u64,
+}
+
+/// The JSON fields of [`UploadResponse`]. Go decodes into the response, so a
+/// missing or `null` field keeps the value it had.
+#[derive(Deserialize)]
+struct UploadResponseJson {
+ url: Option<String>,
+ direct_path: Option<String>,
+ handle: Option<String>,
+ object_id: Option<String>,
+}
+
+/// An upload or delete failure.
+#[derive(Debug, thiserror::Error)]
+pub enum UploadError {
+ /// Encrypting failed.
+ #[error("failed to encrypt file: {0}")]
+ Encrypt(#[source] CbcError),
+ /// The media connection has no hosts. Go panics on the empty slice.
+ #[error("media connection has no hosts")]
+ NoHosts,
+ /// Sending the request failed.
+ #[error("failed to execute request: {0}")]
+ Request(#[source] reqwest::Error),
+ /// The upload host answered with a status other than 200.
+ #[error("upload failed with status code {0}")]
+ Status(u16),
+ /// The upload response body couldn't be read.
+ #[error("failed to parse upload response: {0}")]
+ ReadResponse(#[source] reqwest::Error),
+ /// The upload response isn't the expected JSON.
+ #[error("failed to parse upload response: {0}")]
+ ParseResponse(#[source] serde_json::Error),
+ /// The delete host answered with a non-2xx status.
+ #[error("media delete failed with status code {0}")]
+ DeleteStatus(u16),
+}
+
+/// Uploads the given attachment to WhatsApp servers, encrypted with a new
+/// random media key.
+///
+/// Copy the fields in the response to the corresponding fields in a protobuf
+/// message, e.g. an `ImageMessage`, then send it.
+pub async fn upload(
+ http: &MediaHttpClient,
+ media_conn: &MediaConn,
+ plaintext: &[u8],
+ app_info: MediaType,
+) -> Result<UploadResponse, UploadError> {
+ let media_key: [u8; 32] = rand::random();
+ let (mut resp, data_to_upload) = encrypt_media(plaintext, &media_key, app_info)?;
+ let file_enc_sha256 = resp.file_enc_sha256.clone();
+ raw_upload(
+ http,
+ media_conn,
+ data_to_upload,
+ &file_enc_sha256,
+ app_info,
+ false,
+ &mut resp,
+ )
+ .await?;
+ Ok(resp)
+}
+
+/// The encryption half of Go's `Upload`: AES-256-CBC under the expanded media
+/// key, followed by the first 10 bytes of HMAC-SHA256(iv || ciphertext).
+/// Returns the response with the key, hashes and length filled in, and the
+/// bytes to upload.
+pub(crate) fn encrypt_media(
+ plaintext: &[u8],
+ media_key: &[u8],
+ app_info: MediaType,
+) -> Result<(UploadResponse, Vec<u8>), UploadError> {
+ let mut resp = UploadResponse {
+ file_length: plaintext.len() as u64,
+ media_key: media_key.to_vec(),
+ file_sha256: Sha256::digest(plaintext).to_vec(),
+ ..UploadResponse::default()
+ };
+
+ let keys = get_media_keys(media_key, Some(app_info));
+ let mut data_to_upload = cbcutil::encrypt(&keys.cipher_key, Some(&keys.iv), plaintext)
+ .map_err(UploadError::Encrypt)?;
+
+ let mut hmac = <Hmac<Sha256> as Mac>::new_from_slice(&keys.mac_key)
+ .expect("HMAC-SHA256 accepts keys of any length");
+ hmac.update(&keys.iv);
+ hmac.update(&data_to_upload);
+ data_to_upload.extend_from_slice(&hmac.finalize().into_bytes()[..MEDIA_HMAC_LENGTH]);
+
+ resp.file_enc_sha256 = Sha256::digest(&data_to_upload).to_vec();
+ Ok((resp, data_to_upload))
+}
+
+/// Uploads the given attachment to WhatsApp servers without encrypting it
+/// first, for newsletters.
+///
+/// The response has no media key or ciphertext hash, and its `handle` must
+/// be passed along when sending the message.
+pub async fn upload_newsletter(
+ http: &MediaHttpClient,
+ media_conn: &MediaConn,
+ data: &[u8],
+ app_info: MediaType,
+) -> Result<UploadResponse, UploadError> {
+ let mut resp = UploadResponse {
+ file_length: data.len() as u64,
+ file_sha256: Sha256::digest(data).to_vec(),
+ ..UploadResponse::default()
+ };
+ let file_sha256 = resp.file_sha256.clone();
+ raw_upload(
+ http,
+ media_conn,
+ data.to_vec(),
+ &file_sha256,
+ app_info,
+ true,
+ &mut resp,
+ )
+ .await?;
+ Ok(resp)
+}
+
+async fn raw_upload(
+ http: &MediaHttpClient,
+ media_conn: &MediaConn,
+ data_to_upload: Vec<u8>,
+ file_hash: &[u8],
+ app_info: MediaType,
+ newsletter: bool,
+ resp: &mut UploadResponse,
+) -> Result<(), UploadError> {
+ let token = URL_SAFE.encode(file_hash);
+ let query = encode_query(&[("auth", &media_conn.auth), ("token", &token)]);
+ let mut mms_type = app_info.mms_type().to_owned();
+ let mut upload_prefix = "mms";
+ if http.messenger {
+ upload_prefix = "wa-msgr/mms";
+ // Messenger upload only allows voice messages, not audio files
+ if mms_type == "audio" {
+ "ptt".clone_into(&mut mms_type);
+ }
+ }
+ if newsletter {
+ mms_type = format!("newsletter-{mms_type}");
+ upload_prefix = "newsletter";
+ }
+ // Hacky hack to prefer last option (rupload.facebook.com) for messenger uploads.
+ // For some reason, the primary host doesn't work, even though it has the <upload/> tag.
+ let host = if http.messenger {
+ media_conn.hosts.last()
+ } else {
+ media_conn.hosts.first()
+ }
+ .ok_or(UploadError::NoHosts)?;
+ // The path parts are base64url and fixed names, which Go's URL.String
+ // leaves unescaped.
+ let upload_url = format!(
+ "{}://{}/{upload_prefix}/{mms_type}/{token}?{query}",
+ http.scheme,
+ http.host(&host.hostname),
+ );
+
+ let http_resp = http
+ .client
+ .post(upload_url)
+ .header("Origin", ORIGIN)
+ .header("Referer", format!("{ORIGIN}/"))
+ .body(data_to_upload)
+ .send()
+ .await
+ .map_err(UploadError::Request)?;
+ if http_resp.status() != reqwest::StatusCode::OK {
+ return Err(UploadError::Status(http_resp.status().as_u16()));
+ }
+ let body = http_resp.bytes().await.map_err(UploadError::ReadResponse)?;
+ let json: UploadResponseJson =
+ serde_json::from_slice(&body).map_err(UploadError::ParseResponse)?;
+ let fields = [
+ (json.url, &mut resp.url),
+ (json.direct_path, &mut resp.direct_path),
+ (json.handle, &mut resp.handle),
+ (json.object_id, &mut resp.object_id),
+ ];
+ for (value, field) in fields {
+ if let Some(value) = value {
+ *field = value;
+ }
+ }
+ Ok(())
+}
+
+/// Deletes the media at the given direct path from WhatsApp servers.
+///
+/// This is only used for things like history syncs, which should be deleted
+/// after processing. `companion_meta_nonce` is Go's
+/// `Client.Store.CompanionMetaNonce`.
+pub async fn delete_media(
+ http: &MediaHttpClient,
+ media_conn: &MediaConn,
+ app_info: MediaType,
+ direct_path: &str,
+ enc_file_hash: &[u8],
+ enc_handle: &str,
+ companion_meta_nonce: &str,
+) -> Result<(), UploadError> {
+ if direct_path.is_empty() {
+ return Ok(());
+ }
+ let direct_path = match direct_path.find('?') {
+ Some(query_start) if query_start > 0 => &direct_path[..query_start],
+ _ => direct_path,
+ };
+
+ let token = URL_SAFE.encode(enc_file_hash);
+ let d_md = URL_SAFE_NO_PAD.encode(direct_path);
+ let mut query = vec![
+ ("token", token.as_str()),
+ ("d_md", d_md.as_str()),
+ ("auth", media_conn.auth.as_str()),
+ ];
+ if !enc_handle.is_empty() {
+ query.push(("e_handle", enc_handle));
+ }
+ let host = media_conn.hosts.first().ok_or(UploadError::NoHosts)?;
+ let delete_url = format!(
+ "{}://{}/mms/{}/{token}?{}",
+ http.scheme,
+ http.host(&host.hostname),
+ app_info.mms_type(),
+ encode_query(&query),
+ );
+
+ let mut request = http
+ .client
+ .delete(delete_url)
+ .header("Origin", ORIGIN)
+ .header("Referer", format!("{ORIGIN}/"));
+ if !companion_meta_nonce.is_empty() && !enc_handle.is_empty() {
+ request = request.header("Companion_User_Secret", companion_meta_nonce);
+ }
+
+ let http_resp = request.send().await.map_err(UploadError::Request)?;
+ if !http_resp.status().is_success() {
+ return Err(UploadError::DeleteStatus(http_resp.status().as_u16()));
+ }
+ Ok(())
+}
+
+/// Go's `url.Values.Encode` for single values: sorted by key, each side
+/// escaped with `url.QueryEscape`.
+fn encode_query(values: &[(&str, &str)]) -> String {
+ let mut values = values.to_vec();
+ values.sort_by_key(|(key, _)| *key);
+ values
+ .iter()
+ .map(|(key, value)| format!("{}={}", query_escape(key), query_escape(value)))
+ .collect::<Vec<_>>()
+ .join("&")
+}
+
+/// Go's `url.QueryEscape`: letters, digits and `-_.~` stay, a space becomes
+/// `+`, everything else is percent-encoded with upper-case hex.
+fn query_escape(value: &str) -> String {
+ let mut escaped = String::with_capacity(value.len());
+ for byte in value.bytes() {
+ match byte {
+ b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
+ escaped.push(char::from(byte));
+ }
+ b' ' => escaped.push('+'),
+ _ => escaped.push_str(&format!("%{byte:02X}")),
+ }
+ }
+ escaped
+}
+
+impl crate::client::Client {
+ /// Encrypts and uploads an attachment (`Upload`); copy the response into
+ /// the message part (e.g. an `ImageMessage`) before sending it.
+ #[tracing::instrument(
+ name = "whatsmeow.upload",
+ skip_all,
+ fields(media_type = %app_info, size = plaintext.len()),
+ err
+ )]
+ pub async fn upload(
+ &self,
+ plaintext: &[u8],
+ app_info: MediaType,
+ ) -> Result<UploadResponse, crate::errors::ClientError> {
+ let media_conn = self.media_conn_for_transfer().await?;
+ Ok(upload(&self.media_http(), &media_conn, plaintext, app_info).await?)
+ }
+
+ /// Deletes media from WhatsApp servers; used for history syncs once
+ /// processed (`DeleteMedia`).
+ pub async fn delete_media(
+ &self,
+ app_info: MediaType,
+ direct_path: &str,
+ enc_file_hash: &[u8],
+ enc_handle: &str,
+ ) -> Result<(), crate::errors::ClientError> {
+ if direct_path.is_empty() {
+ return Ok(());
+ }
+ let media_conn = self.media_conn_for_transfer().await?;
+ let nonce = self.store.read().await.companion_meta_nonce.clone();
+ Ok(delete_media(
+ &self.media_http(),
+ &media_conn,
+ app_info,
+ direct_path,
+ enc_file_hash,
+ enc_handle,
+ &nonce,
+ )
+ .await?)
+ }
+}
+
+#[cfg(test)]
+mod test;
diff --git a/crates/whatsmeow/src/upload/test.rs b/crates/whatsmeow/src/upload/test.rs
new file mode 100644
index 0000000000..fc316ce1fe
--- /dev/null
+++ b/crates/whatsmeow/src/upload/test.rs
@@ -0,0 +1,278 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+//! Expected values come from `testdata/media/vectors.json`, written by
+//! `testdata/generator/media` running a real whatsmeow `Client.Upload`,
+//! `UploadNewsletter` and `DeleteMedia` against local fake hosts.
+
+use serde_json::Value;
+
+use super::*;
+use crate::download::download;
+use crate::download::test::{FakeHosts, Recorded, hex_field, vectors};
+use crate::proto::wa_e2e::ImageMessage;
+
+/// The Go client's own user agent on uploads, which reqwest doesn't send.
+fn without_user_agent(mut request: Recorded) -> Recorded {
+ request.headers.remove("User-Agent");
+ request
+}
+
+fn expected_requests(vector: &Value) -> Vec<Recorded> {
+ vector["requests"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(Recorded::from_vector)
+ .map(without_user_agent)
+ .collect()
+}
+
+#[test]
+fn encryption_matches_go() {
+ let vectors = vectors();
+ let vector = &vectors["upload"];
+ let (resp, data_to_upload) = encrypt_media(
+ &hex_field(&vector["plaintext"]).unwrap(),
+ &hex_field(&vector["media_key"]).unwrap(),
+ MediaType::Image,
+ )
+ .unwrap();
+ assert_eq!(
+ Some(data_to_upload),
+ hex_field(&vector["requests"][0]["body"])
+ );
+ assert_eq!(Some(resp.media_key), hex_field(&vector["media_key"]));
+ assert_eq!(
+ Some(resp.file_enc_sha256),
+ hex_field(&vector["file_enc_sha256"])
+ );
+ assert_eq!(Some(resp.file_sha256), hex_field(&vector["file_sha256"]));
+ assert_eq!(resp.file_length, vector["file_length"].as_u64().unwrap());
+}
+
+#[tokio::test]
+async fn raw_upload_matches_go() {
+ let vectors = vectors();
+ let vector = &vectors["upload"];
+ let hosts = FakeHosts::start(
+ vec![Vec::new(), Vec::new()],
+ vectors["auth"].as_str().unwrap(),
+ )
+ .await;
+ hosts.set_upload_answer(vector["response_json"].as_str().unwrap());
+ let (mut resp, data_to_upload) = encrypt_media(
+ &hex_field(&vector["plaintext"]).unwrap(),
+ &hex_field(&vector["media_key"]).unwrap(),
+ MediaType::Image,
+ )
+ .unwrap();
+ let file_enc_sha256 = resp.file_enc_sha256.clone();
+
+ raw_upload(
+ &FakeHosts::http(),
+ &hosts.media_conn,
+ data_to_upload,
+ &file_enc_sha256,
+ MediaType::Image,
+ false,
+ &mut resp,
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(hosts.take_requests(), expected_requests(vector));
+ assert_eq!(resp.url, vector["url"].as_str().unwrap());
+ assert_eq!(resp.direct_path, vector["direct_path"].as_str().unwrap());
+ assert_eq!(resp.handle, vector["handle"].as_str().unwrap());
+ assert_eq!(resp.object_id, vector["object_id"].as_str().unwrap());
+}
+
+#[tokio::test]
+async fn newsletter_upload_matches_go() {
+ let vectors = vectors();
+ let vector = &vectors["upload_newsletter"];
+ let hosts = FakeHosts::start(vec![Vec::new()], vectors["auth"].as_str().unwrap()).await;
+ hosts.set_upload_answer(vector["response_json"].as_str().unwrap());
+
+ let resp = upload_newsletter(
+ &FakeHosts::http(),
+ &hosts.media_conn,
+ &hex_field(&vector["plaintext"]).unwrap(),
+ MediaType::Video,
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(hosts.take_requests(), expected_requests(vector));
+ assert_eq!(
+ resp,
+ UploadResponse {
+ url: vector["url"].as_str().unwrap().to_owned(),
+ direct_path: vector["direct_path"].as_str().unwrap().to_owned(),
+ handle: vector["handle"].as_str().unwrap().to_owned(),
+ object_id: vector["object_id"].as_str().unwrap().to_owned(),
+ media_key: Vec::new(),
+ file_enc_sha256: Vec::new(),
+ file_sha256: hex_field(&vector["file_sha256"]).unwrap(),
+ file_length: vector["file_length"].as_u64().unwrap(),
+ }
+ );
+}
+
+#[tokio::test]
+async fn delete_media_matches_go() {
+ let vectors = vectors();
+ let vector = &vectors["delete"];
+ let hosts = FakeHosts::start(vec![Vec::new()], vectors["auth"].as_str().unwrap()).await;
+
+ delete_media(
+ &FakeHosts::http(),
+ &hosts.media_conn,
+ MediaType::History,
+ vector["direct_path"].as_str().unwrap(),
+ &hex_field(&vector["enc_file_hash"]).unwrap(),
+ vector["enc_handle"].as_str().unwrap(),
+ vector["companion_meta_nonce"].as_str().unwrap(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(hosts.take_requests(), expected_requests(vector));
+}
+
+#[tokio::test]
+async fn upload_then_download_round_trips() {
+ let hosts = FakeHosts::start(vec![Vec::new()], "auth").await;
+ hosts.set_upload_answer(
+ r#"{"url":"https://example.invalid/u","direct_path":"/v/t62/u.enc?ccb=1"}"#,
+ );
+ let http = FakeHosts::http();
+ let plaintext = b"round trip through the fake media host".repeat(40);
+
+ let resp = upload(&http, &hosts.media_conn, &plaintext, MediaType::Image)
+ .await
+ .unwrap();
+ assert_eq!(resp.direct_path, "/v/t62/u.enc?ccb=1");
+ assert_eq!(resp.media_key.len(), 32);
+
+ let message = ImageMessage {
+ url: Some(resp.url),
+ direct_path: Some(resp.direct_path),
+ media_key: Some(resp.media_key),
+ file_enc_sha256: Some(resp.file_enc_sha256),
+ file_sha256: Some(resp.file_sha256),
+ file_length: Some(resp.file_length),
+ ..ImageMessage::default()
+ };
+ assert_eq!(
+ download(&http, &hosts.media_conn, &message).await.unwrap(),
+ plaintext
+ );
+ let methods: Vec<String> = hosts
+ .take_requests()
+ .into_iter()
+ .map(|request| request.method)
+ .collect();
+ assert_eq!(methods, ["POST", "GET"]);
+}
+
+#[tokio::test]
+async fn upload_failures() {
+ let hosts = FakeHosts::start(Vec::new(), "auth").await;
+ let http = FakeHosts::http();
+ assert!(matches!(
+ upload(&http, &hosts.media_conn, b"x", MediaType::Image).await,
+ Err(UploadError::NoHosts)
+ ));
+
+ let hosts = FakeHosts::start(
+ vec![vec![crate::download::test::Answer {
+ status: 500,
+ retry_after: None,
+ body: Some(Vec::new()),
+ }]],
+ "auth",
+ )
+ .await;
+ assert_eq!(
+ upload(&http, &hosts.media_conn, b"x", MediaType::Image)
+ .await
+ .unwrap_err()
+ .to_string(),
+ "upload failed with status code 500"
+ );
+}
+
+#[test]
+fn query_escape_like_go() {
+ assert_eq!(
+ query_escape("AUTH token/with+odd=chars~*!"),
+ "AUTH+token%2Fwith%2Bodd%3Dchars~%2A%21"
+ );
+ assert_eq!(
+ encode_query(&[("token", "t"), ("auth", "a b")]),
+ "auth=a+b&token=t"
+ );
+}
+
+#[tokio::test]
+async fn the_client_sends_media_to_the_configured_base_url() {
+ use crate::client::test::{children, connect_paired, harness_with, next_node, node, text};
+ use crate::testing::is_iq;
+
+ let hosts = FakeHosts::start(vec![Vec::new()], "auth").await;
+ hosts.set_upload_answer(
+ r#"{"url":"https://example.invalid/u","direct_path":"/v/t62/c.enc?ccb=1"}"#,
+ );
+ let base_url = format!("http://{}", hosts.media_conn.hosts[0].hostname);
+ let mut harness = harness_with(Some(("1234:[email protected]", "9876:5@lid")), |config| {
+ config.media_base_url = Some(base_url);
+ });
+ let mut connection = connect_paired(&mut harness).await;
+
+ let client = std::sync::Arc::clone(&harness.client);
+ let plaintext = b"media through the override".repeat(20);
+ let upload_plaintext = plaintext.clone();
+ let upload =
+ tokio::spawn(async move { client.upload(&upload_plaintext, MediaType::Image).await });
+ let media_conn = next_node(&mut connection).await;
+ assert!(is_iq(&media_conn, "w:m"));
+ // The server names WhatsApp's real host; the override wins.
+ connection
+ .respond_iq(
+ &media_conn,
+ vec![node(
+ "media_conn",
+ &[
+ ("auth", text("auth")),
+ ("ttl", text("300")),
+ ("auth_ttl", text("60")),
+ ("max_buckets", text("1")),
+ ],
+ children(vec![node(
+ "host",
+ &[("hostname", text("mmg.whatsapp.net"))],
+ None,
+ )]),
+ )],
+ )
+ .await;
+ let response = upload.await.unwrap().unwrap();
+ let message = ImageMessage {
+ direct_path: Some(response.direct_path),
+ media_key: Some(response.media_key),
+ file_enc_sha256: Some(response.file_enc_sha256),
+ file_sha256: Some(response.file_sha256),
+ file_length: Some(response.file_length),
+ ..ImageMessage::default()
+ };
+ assert_eq!(harness.client.download(&message).await.unwrap(), plaintext);
+ let methods: Vec<String> = hosts
+ .take_requests()
+ .into_iter()
+ .map(|request| request.method)
+ .collect();
+ assert_eq!(methods, ["POST", "GET"]);
+}
diff --git a/crates/whatsmeow/src/user.rs b/crates/whatsmeow/src/user.rs
new file mode 100644
index 0000000000..f1a7a8b8bd
--- /dev/null
+++ b/crates/whatsmeow/src/user.rs
@@ -0,0 +1,893 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+//
+// Ported from whatsmeow user.go (MPL-2.0, Copyright (c) Tulir Asokan)
+//
+// Not ported: bots (`GetBotListV2`, `GetBotProfiles`, the bot list in
+// `UsyncQueryExtras`), business message and contact QR links, business
+// profiles, `SetStatusMessage` (mex) and Messenger device lists
+// (`getFBIDDevices`): a `msgr` JID passed to `get_user_devices` fails in
+// `usync` as an unknown server.
+//
+// Errors leave out the JIDs Go formats into them, since `err` spans log
+// them.
+
+//! Users: names, verified business names, devices and usync queries.
+
+use std::collections::HashMap;
+use std::sync::Arc;
+
+use base64::Engine;
+use base64::engine::general_purpose::STANDARD;
+use prost::Message;
+
+use crate::binary::{AttributeValue, Attrs, Node, NodeContent};
+use crate::client::{Client, DeviceCache};
+use crate::errors::{ClientError, IqError, element_missing, wrap_iq_error};
+use crate::proto::wa_history_sync::Pushname;
+use crate::proto::wa_vname_cert::{VerifiedNameCertificate, verified_name_certificate};
+use crate::request::{InfoQuery, IqType};
+use crate::send::participant_list_hash_v2;
+use crate::store::LidMapping;
+use crate::types::events::{BlocklistChangeAction, BusinessName, Event, PushName};
+use crate::types::{
+ AddressingMode, Blocklist, BlocklistItem, DEFAULT_USER_SERVER, HIDDEN_USER_SERVER,
+ HOSTED_LID_SERVER, HOSTED_SERVER, IsOnWhatsAppResponse, Jid, LEGACY_USER_SERVER, MessageInfo,
+ ProfilePictureInfo, SERVER_JID, UserInfo, VerifiedName, new_jid, parse_jid,
+};
+
+/// Extra options for [`Client::usync`] (`UsyncQueryExtras`; the bot list
+/// isn't ported).
+#[derive(Clone, Copy, Debug, Default)]
+pub struct UsyncQueryExtras {
+ /// Send the stored privacy token of each user.
+ pub include_privacy_token: bool,
+}
+
+/// Options for [`Client::get_profile_picture_info`].
+#[derive(Clone, Debug, Default)]
+pub struct GetProfilePictureParams {
+ /// Get the small preview instead of the full image.
+ pub preview: bool,
+ /// The last known picture ID: an unchanged picture returns `None`.
+ pub existing_id: String,
+ /// Get a community's picture (others return 401 for communities).
+ pub is_community: bool,
+ /// A group shared with the target.
+ pub common_gid: Jid,
+ /// An invite code, for the picture of a group you haven't joined.
+ pub invite_code: String,
+ /// The persona ID of a Meta AI bot.
+ pub persona_id: String,
+}
+
+fn strip_query(link: &str) -> &str {
+ match link.find('?') {
+ Some(index) if index > 0 => &link[..index],
+ _ => link,
+ }
+}
+
+/// Strips the first matching prefix and then the query string; a link
+/// without any of the prefixes is returned as is.
+pub(crate) fn strip_url_prefix<'link>(link: &'link str, prefixes: &[&str]) -> &'link str {
+ for prefix in prefixes {
+ if let Some(unprefixed) = link.strip_prefix(prefix) {
+ return strip_query(unprefixed);
+ }
+ }
+ link
+}
+
+fn user_node(attrs: Attrs, content: Option<NodeContent>) -> Node {
+ Node {
+ tag: "user".to_owned(),
+ attrs,
+ content,
+ }
+}
+
+fn tag_node(tag: &str, attrs: Attrs, content: Option<NodeContent>) -> Node {
+ Node {
+ tag: tag.to_owned(),
+ attrs,
+ content,
+ }
+}
+
+impl Client {
+ /// Checks whether the phone numbers (international format with the `+`)
+ /// are registered on WhatsApp, storing the LID mappings it learns.
+ ///
+ /// Go returns the results along with a failure to store the mappings;
+ /// here that failure is the error.
+ #[tracing::instrument(name = "whatsmeow.is_on_whatsapp", skip_all, fields(phones = phones.len()), err)]
+ pub async fn is_on_whatsapp(
+ &self,
+ phones: &[&str],
+ ) -> Result<Vec<IsOnWhatsAppResponse>, ClientError> {
+ let jids: Vec<Jid> = phones
+ .iter()
+ .map(|phone| new_jid(phone, LEGACY_USER_SERVER))
+ .collect();
+ let list = self
+ .usync(
+ &jids,
+ "query",
+ "interactive",
+ vec![
+ tag_node(
+ "contact",
+ Attrs::from([("addressing_mode".to_owned(), "lid".into())]),
+ None,
+ ),
+ tag_node(
+ "business",
+ Attrs::new(),
+ Some(NodeContent::Nodes(vec![tag_node(
+ "verified_name",
+ Attrs::new(),
+ None,
+ )])),
+ ),
+ tag_node("disappearing_mode", Attrs::new(), None),
+ tag_node("username", Attrs::new(), None),
+ ],
+ UsyncQueryExtras::default(),
+ )
+ .await?;
+ let mut output = Vec::with_capacity(jids.len());
+ let mut lid_entries = Vec::with_capacity(jids.len());
+ let query_suffix = format!("@{LEGACY_USER_SERVER}");
+ for child in list.get_children() {
+ let mut attrs = child.attr_getter();
+ let jid = attrs.optional_jid_or_empty("jid");
+ let pn_jid = attrs.optional_jid_or_empty("pn_jid");
+ if child.tag != "user" || (jid.is_empty() && pn_jid.is_empty()) {
+ continue;
+ }
+ let mut info = IsOnWhatsAppResponse {
+ jid: if jid.is_empty() { pn_jid.clone() } else { jid },
+ phone_number: pn_jid,
+ ..IsOnWhatsAppResponse::default()
+ };
+ if info.jid.server == HIDDEN_USER_SERVER
+ && info.phone_number.server == DEFAULT_USER_SERVER
+ {
+ lid_entries.push(LidMapping {
+ lid: info.jid.clone(),
+ pn: info.phone_number.clone(),
+ });
+ }
+ match parse_verified_name(child.get_child_by_tag(&["business"])) {
+ Ok(verified_name) => info.verified_name = verified_name,
+ Err(error) => {
+ tracing::warn!(error = %error, "failed to parse verified name details");
+ }
+ }
+ let contact_node = child.get_child_by_tag(&["contact"]);
+ info.is_in = contact_node.attr_getter().string("type") == "in";
+ let contact_query = match &contact_node.content {
+ Some(NodeContent::Bytes(query)) => String::from_utf8_lossy(query).into_owned(),
+ _ => String::new(),
+ };
+ info.query = contact_query
+ .strip_suffix(&query_suffix)
+ .unwrap_or(&contact_query)
+ .to_owned();
+ output.push(info);
+ }
+ if !lid_entries.is_empty() {
+ let lids = Arc::clone(&self.store.read().await.lids);
+ lids.put_many_lid_mappings(&lid_entries)
+ .await
+ .map_err(|error| ClientError::from(error).wrap("failed to store LID mappings"))?;
+ }
+ Ok(output)
+ }
+
+ /// Gets basic user info (picture ID, about text, devices and LID),
+ /// storing the LID mappings and verified business names it learns.
+ ///
+ /// Like Go, the parsed verified name only updates the contact store; it
+ /// isn't set on [`UserInfo::verified_name`].
+ #[tracing::instrument(name = "whatsmeow.get_user_info", skip_all, fields(jids = jids.len()), err)]
+ pub async fn get_user_info(&self, jids: &[Jid]) -> Result<HashMap<Jid, UserInfo>, ClientError> {
+ let list = self
+ .usync(
+ jids,
+ "full",
+ "background",
+ vec![
+ tag_node(
+ "business",
+ Attrs::new(),
+ Some(NodeContent::Nodes(vec![tag_node(
+ "verified_name",
+ Attrs::new(),
+ None,
+ )])),
+ ),
+ tag_node("status", Attrs::new(), None),
+ tag_node("picture", Attrs::new(), None),
+ tag_node(
+ "devices",
+ Attrs::from([("version".to_owned(), "2".into())]),
+ None,
+ ),
+ tag_node("lid", Attrs::new(), None),
+ ],
+ UsyncQueryExtras {
+ include_privacy_token: true,
+ },
+ )
+ .await?;
+ let mut response = HashMap::with_capacity(jids.len());
+ let mut mappings = Vec::with_capacity(jids.len());
+ for child in list.get_children() {
+ let Some(AttributeValue::Jid(jid)) = child.attrs.get("jid") else {
+ continue;
+ };
+ if child.tag != "user" {
+ continue;
+ }
+ let verified_name = match parse_verified_name(child.get_child_by_tag(&["business"])) {
+ Ok(verified_name) => verified_name,
+ Err(error) => {
+ tracing::warn!(error = %error, "failed to parse verified name details");
+ None
+ }
+ };
+ let status = match &child.get_child_by_tag(&["status"]).content {
+ Some(NodeContent::Bytes(status)) => String::from_utf8_lossy(status).into_owned(),
+ _ => String::new(),
+ };
+ let picture_id = match child.get_child_by_tag(&["picture"]).attrs.get("id") {
+ Some(AttributeValue::String(id)) => id.clone(),
+ _ => String::new(),
+ };
+ let info = UserInfo {
+ verified_name: None,
+ status,
+ picture_id,
+ devices: parse_device_list(jid, child.get_child_by_tag(&["devices"])),
+ lid: child
+ .get_child_by_tag(&["lid"])
+ .attr_getter()
+ .optional_jid_or_empty("val"),
+ };
+ if !info.lid.is_empty() {
+ mappings.push(LidMapping {
+ lid: info.lid.clone(),
+ pn: jid.clone(),
+ });
+ }
+ if let Some(verified_name) = &verified_name {
+ let name = verified_name
+ .details
+ .as_ref()
+ .and_then(|details| details.verified_name.clone())
+ .unwrap_or_default();
+ self.update_business_name(jid, &info.lid, None, &name).await;
+ }
+ response.insert(jid.clone(), info);
+ }
+ let lids = Arc::clone(&self.store.read().await.lids);
+ if let Err(error) = lids.put_many_lid_mappings(&mappings).await {
+ // Not worth failing the call over.
+ tracing::error!(error = %error, "failed to place LID mappings from usync call");
+ }
+ Ok(response)
+ }
+
+ /// Same as [`Client::get_user_devices`] (Go keeps both names).
+ pub async fn get_user_devices_context(&self, jids: &[Jid]) -> Result<Vec<Jid>, ClientError> {
+ self.get_user_devices(jids).await
+ }
+
+ /// Gets the devices of the given users: non-AD JIDs (phone numbers or
+ /// LIDs) in, AD JIDs out, in input order. Lists are cached per user with
+ /// their participant hash; device notifications update or drop them.
+ ///
+ /// Like Go, the local device is not filtered out here (despite Go's doc
+ /// comment); the send path drops it. Bots have no devices and are
+ /// returned as they are.
+ #[tracing::instrument(
+ name = "whatsmeow.get_user_devices",
+ skip_all,
+ fields(jids = jids.len(), cached = tracing::field::Empty, synced = tracing::field::Empty),
+ err
+ )]
+ pub async fn get_user_devices(&self, jids: &[Jid]) -> Result<Vec<Jid>, ClientError> {
+ let mut cache = self.user_devices_cache.lock().await;
+ let mut devices = Vec::new();
+ let mut jids_to_sync = Vec::new();
+ let mut cached_count = 0;
+ for jid in jids {
+ match cache.get(jid) {
+ Some(cached) if !cached.devices.is_empty() => {
+ cached_count += 1;
+ devices.extend(cached.devices.iter().cloned());
+ }
+ // Bot JIDs don't have devices; the usync query is empty.
+ _ if jid.is_bot() => devices.push(jid.clone()),
+ _ => jids_to_sync.push(jid.clone()),
+ }
+ }
+ let span = tracing::Span::current();
+ span.record("cached", cached_count);
+ span.record("synced", jids_to_sync.len());
+ if !jids_to_sync.is_empty() {
+ let list = self
+ .usync(
+ &jids_to_sync,
+ "query",
+ "message",
+ vec![tag_node(
+ "devices",
+ Attrs::from([("version".to_owned(), "2".into())]),
+ None,
+ )],
+ UsyncQueryExtras::default(),
+ )
+ .await?;
+ for user in list.get_children() {
+ let Some(AttributeValue::Jid(jid)) = user.attrs.get("jid") else {
+ continue;
+ };
+ if user.tag != "user" {
+ continue;
+ }
+ let user_devices = parse_device_list(jid, user.get_child_by_tag(&["devices"]));
+ cache.insert(
+ jid.clone(),
+ DeviceCache {
+ dhash: participant_list_hash_v2(&user_devices),
+ devices: user_devices.clone(),
+ },
+ );
+ devices.extend(user_devices);
+ }
+ }
+ Ok(devices)
+ }
+
+ /// Gets the URL of a user's profile picture or a group's photo.
+ ///
+ /// With `existing_id`, an unchanged picture returns `None`. Communities
+ /// need `is_community`, otherwise the server may answer 401. When the
+ /// picture's attributes don't parse, Go returns the partial info with the
+ /// error; here only the error.
+ #[tracing::instrument(name = "whatsmeow.get_profile_picture_info", skip_all, err)]
+ pub async fn get_profile_picture_info(
+ &self,
+ jid: &Jid,
+ params: &GetProfilePictureParams,
+ ) -> Result<Option<ProfilePictureInfo>, ClientError> {
+ let mut attrs = Attrs::from([
+ ("query".to_owned(), "url".into()),
+ (
+ "type".to_owned(),
+ if params.preview { "preview" } else { "image" }.into(),
+ ),
+ ]);
+ if !params.existing_id.is_empty() {
+ attrs.insert("id".to_owned(), params.existing_id.as_str().into());
+ }
+ if !params.invite_code.is_empty() {
+ attrs.insert("invite".to_owned(), params.invite_code.as_str().into());
+ }
+ let namespace;
+ let to;
+ let target;
+ let content;
+ if params.is_community {
+ target = Jid::default();
+ namespace = "w:g2";
+ to = jid.clone();
+ attrs.insert("parent_group_jid".to_owned(), jid.into());
+ content = vec![tag_node(
+ "pictures",
+ Attrs::new(),
+ Some(NodeContent::Nodes(vec![tag_node("picture", attrs, None)])),
+ )];
+ } else {
+ namespace = "w:profile:picture";
+ to = SERVER_JID.clone();
+ target = jid.clone();
+ if !params.common_gid.is_empty() {
+ attrs.insert("common_gid".to_owned(), (&params.common_gid).into());
+ }
+ if !params.persona_id.is_empty() {
+ attrs.insert("persona_id".to_owned(), params.persona_id.as_str().into());
+ }
+ let picture_content = match self.ensure_tc_token(jid).await {
+ Ok(Some(token)) => Some(NodeContent::Nodes(vec![tag_node(
+ "tctoken",
+ Attrs::new(),
+ Some(NodeContent::Bytes(token)),
+ )])),
+ _ => None,
+ };
+ content = vec![tag_node("picture", attrs, picture_content)];
+ }
+ let response = self
+ .send_iq(InfoQuery {
+ namespace,
+ r#type: IqType::Get,
+ to,
+ target,
+ content: Some(NodeContent::Nodes(content)),
+ ..InfoQuery::default()
+ })
+ .await;
+ let mut response = match response {
+ Err(error) if error.is(&ClientError::iq_status(IqError::NOT_AUTHORIZED)) => {
+ return Err(wrap_iq_error(
+ ClientError::ProfilePictureUnauthorized,
+ error,
+ ));
+ }
+ Err(error) if error.is(&ClientError::iq_status(IqError::NOT_FOUND)) => {
+ return Err(wrap_iq_error(ClientError::ProfilePictureNotSet, error));
+ }
+ Err(error) => return Err(error),
+ Ok(response) => response,
+ };
+ if params.is_community {
+ response = response
+ .get_optional_child_by_tag(&["pictures"])
+ .ok_or_else(|| element_missing("pictures", "response to profile picture query"))?
+ .clone();
+ }
+ let Some(picture) = response.get_optional_child_by_tag(&["picture"]) else {
+ if !params.existing_id.is_empty() {
+ return Ok(None);
+ }
+ return Err(element_missing(
+ "picture",
+ "response to profile picture query",
+ ));
+ };
+ let mut attrs = picture.attr_getter();
+ match attrs.optional_int("status") {
+ 304 => return Ok(None),
+ 204 => return Err(ClientError::ProfilePictureNotSet),
+ _ => {}
+ }
+ let info = ProfilePictureInfo {
+ id: attrs.string("id"),
+ url: attrs.string("url"),
+ r#type: attrs.string("type"),
+ direct_path: attrs.string("direct_path"),
+ hash: STANDARD
+ .decode(attrs.optional_string("hash"))
+ .unwrap_or_default(),
+ };
+ attrs.error()?;
+ Ok(Some(info))
+ }
+
+ fn parse_blocklist(node: &Node) -> (Blocklist, Vec<LidMapping>) {
+ let mut output = Blocklist {
+ d_hash: node.attr_getter().string("dhash"),
+ addressing_mode: AddressingMode::from(node.attr_getter().string("addressing_mode")),
+ items: Vec::new(),
+ };
+ let mut lid_mappings = Vec::new();
+ for child in node.get_children() {
+ let mut attrs = child.attr_getter();
+ let blocked_jid = attrs.jid("jid");
+ if !attrs.ok() {
+ tracing::debug!(error = ?attrs.error().err(), "ignoring contact blocked data with unexpected attributes");
+ continue;
+ }
+ let item = BlocklistItem {
+ lid: blocked_jid,
+ pn: attrs.optional_jid_or_empty("pn_jid"),
+ active: attrs.optional_bool("active"),
+ };
+ if item.active
+ && item.lid.server == HIDDEN_USER_SERVER
+ && item.pn.server == DEFAULT_USER_SERVER
+ {
+ lid_mappings.push(LidMapping {
+ pn: item.pn.clone(),
+ lid: item.lid.clone(),
+ });
+ }
+ output.items.push(item);
+ }
+ (output, lid_mappings)
+ }
+
+ /// Gets the list of users this user has blocked. With a `dhash` that
+ /// matches the server's, there's no list (`None`).
+ #[tracing::instrument(name = "whatsmeow.get_blocklist", skip_all, err)]
+ pub async fn get_blocklist(&self, dhash: &str) -> Result<Option<Blocklist>, ClientError> {
+ let content = (!dhash.is_empty()).then(|| {
+ NodeContent::Nodes(vec![tag_node(
+ "item",
+ Attrs::from([("dhash".to_owned(), dhash.into())]),
+ None,
+ )])
+ });
+ let response = self
+ .send_iq(InfoQuery {
+ namespace: "blocklist",
+ r#type: IqType::Get,
+ to: SERVER_JID.clone(),
+ content,
+ ..InfoQuery::default()
+ })
+ .await?;
+ let Some(list) = response.get_optional_child_by_tag(&["list"]) else {
+ if !dhash.is_empty() {
+ return Ok(None);
+ }
+ return Err(element_missing("list", "response to blocklist query"));
+ };
+ let (blocklist, mappings) = Self::parse_blocklist(list);
+ if !mappings.is_empty() {
+ let lids = Arc::clone(&self.store.read().await.lids);
+ if let Err(error) = lids.put_many_lid_mappings(&mappings).await {
+ tracing::error!(error = %error, "failed to store LID mappings from blocklist query");
+ }
+ }
+ Ok(Some(blocklist))
+ }
+
+ /// Blocks or unblocks a user and returns the updated list. A phone
+ /// number is blocked by its LID (looked up with [`Client::get_user_info`]
+ /// when unknown). With a `dhash` that matches the server's, there's no
+ /// list (`None`).
+ #[tracing::instrument(name = "whatsmeow.update_blocklist", skip_all, fields(action = %action), err)]
+ pub async fn update_blocklist(
+ &self,
+ jid: &Jid,
+ action: BlocklistChangeAction,
+ dhash: &str,
+ ) -> Result<Option<Blocklist>, ClientError> {
+ let mut lid_jid = Jid::default();
+ let mut pn_jid = Jid::default();
+ let lids = Arc::clone(&self.store.read().await.lids);
+ if jid.server == DEFAULT_USER_SERVER {
+ pn_jid = jid.clone();
+ let mut lid = lids
+ .get_lid_for_pn(jid)
+ .await
+ .map_err(|error| ClientError::from(error).wrap("failed to get LID for PN"))?
+ .unwrap_or_default();
+ if lid.is_empty() {
+ let info = self
+ .get_user_info(std::slice::from_ref(jid))
+ .await
+ .map_err(|error| error.wrap("failed to get user info to fill LID cache"))?;
+ lid = info
+ .get(jid)
+ .map(|info| info.lid.clone())
+ .unwrap_or_default();
+ if lid.is_empty() {
+ return Err(ClientError::Other("no LID found from server".to_owned()));
+ }
+ }
+ lid_jid = lid;
+ } else if jid.server == HIDDEN_USER_SERVER {
+ lid_jid = jid.clone();
+ if action == BlocklistChangeAction::Block {
+ pn_jid = lids
+ .get_pn_for_lid(jid)
+ .await
+ .map_err(|error| ClientError::from(error).wrap("failed to resolve PN"))?
+ .unwrap_or_default();
+ }
+ }
+ let mut item_attrs = Attrs::from([
+ ("jid".to_owned(), lid_jid.into()),
+ ("action".to_owned(), action.as_str().into()),
+ ]);
+ if action == BlocklistChangeAction::Block && !pn_jid.is_empty() {
+ item_attrs.insert("pn_jid".to_owned(), pn_jid.into());
+ }
+ if !dhash.is_empty() {
+ item_attrs.insert("dhash".to_owned(), dhash.into());
+ }
+ let response = self
+ .send_iq(InfoQuery {
+ namespace: "blocklist",
+ r#type: IqType::Set,
+ to: SERVER_JID.clone(),
+ content: Some(NodeContent::Nodes(vec![tag_node("item", item_attrs, None)])),
+ ..InfoQuery::default()
+ })
+ .await?;
+ let list = response
+ .get_optional_child_by_tag(&["list"])
+ .ok_or_else(|| element_missing("list", "response to blocklist update"))?;
+ if !dhash.is_empty() && list.attr_getter().bool("matched") {
+ return Ok(None);
+ }
+ Ok(Some(Self::parse_blocklist(list).0))
+ }
+
+ /// Runs a usync query for the users: `mode` and `context` (`query` /
+ /// `message`, `full` / `background`, …) go on the `<usync>` node and
+ /// `query` lists what to fetch. Returns the response's `<list>`.
+ pub(crate) async fn usync(
+ &self,
+ jids: &[Jid],
+ mode: &str,
+ context: &str,
+ query: Vec<Node>,
+ extras: UsyncQueryExtras,
+ ) -> Result<Node, ClientError> {
+ let mut user_list = Vec::with_capacity(jids.len());
+ for jid in jids {
+ let jid = jid.to_non_ad();
+ let user = match jid.server.as_str() {
+ LEGACY_USER_SERVER => user_node(
+ Attrs::new(),
+ Some(NodeContent::Nodes(vec![tag_node(
+ "contact",
+ Attrs::new(),
+ Some(NodeContent::String(jid.to_string())),
+ )])),
+ ),
+ DEFAULT_USER_SERVER | HIDDEN_USER_SERVER => {
+ // An LID can go in the jid attribute (works for <devices>
+ // queries at least).
+ let mut content = None;
+ if jid.is_bot() {
+ // The bot list (persona IDs) isn't ported.
+ content = Some(NodeContent::Nodes(vec![tag_node(
+ "bot",
+ Attrs::new(),
+ Some(NodeContent::Nodes(vec![tag_node(
+ "profile",
+ Attrs::from([("persona_id".to_owned(), "".into())]),
+ None,
+ )])),
+ )]));
+ } else if extras.include_privacy_token {
+ match self.ensure_tc_token(&jid).await {
+ Err(error) => {
+ tracing::warn!(error = %error, "failed to get privacy token for usync status query")
+ }
+ Ok(Some(token)) if !token.is_empty() => {
+ content = Some(NodeContent::Nodes(vec![tag_node(
+ "tctoken",
+ Attrs::new(),
+ Some(NodeContent::Bytes(token)),
+ )]));
+ }
+ Ok(_) => {}
+ }
+ }
+ user_node(Attrs::from([("jid".to_owned(), jid.into())]), content)
+ }
+ server => {
+ return Err(ClientError::Other(format!(
+ "unknown user server '{server}'"
+ )));
+ }
+ };
+ user_list.push(user);
+ }
+ let response = self
+ .send_iq(InfoQuery {
+ namespace: "usync",
+ r#type: IqType::Get,
+ to: SERVER_JID.clone(),
+ content: Some(NodeContent::Nodes(vec![tag_node(
+ "usync",
+ Attrs::from([
+ ("sid".to_owned(), self.generate_request_id().into()),
+ ("mode".to_owned(), mode.into()),
+ ("last".to_owned(), "true".into()),
+ ("index".to_owned(), "0".into()),
+ ("context".to_owned(), context.into()),
+ ]),
+ Some(NodeContent::Nodes(vec![
+ tag_node("query", Attrs::new(), Some(NodeContent::Nodes(query))),
+ tag_node("list", Attrs::new(), Some(NodeContent::Nodes(user_list))),
+ ])),
+ )])),
+ ..InfoQuery::default()
+ })
+ .await
+ .map_err(|error| error.wrap("failed to send usync query"))?;
+ response
+ .get_optional_child_by_tag(&["usync", "list"])
+ .cloned()
+ .ok_or_else(|| element_missing("list", "response to usync query"))
+ }
+}
+
+impl Client {
+ /// Stores the push names from a push name history sync.
+ pub(crate) async fn handle_historical_push_names(&self, names: &[Pushname]) {
+ let contacts = Arc::clone(&self.store.read().await.contacts);
+ tracing::info!(
+ count = names.len(),
+ "updating contact store with push names from history sync"
+ );
+ for user in names {
+ let push_name = user.pushname.as_deref().unwrap_or_default();
+ if push_name == "-" {
+ continue;
+ }
+ let id = user.id.as_deref().unwrap_or_default();
+ match parse_jid(id) {
+ Err(error) => {
+ tracing::warn!(error = %error, "failed to parse user ID in push name history sync")
+ }
+ Ok(jid) => {
+ if let Err(error) = contacts.put_push_name(&jid, push_name).await {
+ tracing::warn!(error = %error, "failed to store push name from history sync");
+ }
+ }
+ }
+ }
+ }
+
+ /// Stores a push name seen in a message and emits [`Event::PushName`] if
+ /// it changed.
+ pub(crate) async fn update_push_name(
+ &self,
+ user: &Jid,
+ user_alt: &Jid,
+ message_info: &MessageInfo,
+ name: &str,
+ ) {
+ let user = user.to_non_ad();
+ let contacts = Arc::clone(&self.store.read().await.contacts);
+ match contacts.put_push_name(&user, name).await {
+ Err(error) => {
+ tracing::error!(error = %error, "failed to save push name in device store")
+ }
+ Ok((false, _)) => {}
+ Ok((true, previous_name)) => {
+ let user_alt = self.alt_jid_or_lookup(&user, user_alt).await;
+ if !user_alt.is_empty()
+ && let Err(error) = contacts.put_push_name(&user_alt, name).await
+ {
+ tracing::error!(error = %error, "failed to save push name of alternate JID in device store");
+ }
+ tracing::debug!("push name changed, dispatching event");
+ self.dispatch_event(Event::PushName(Box::new(PushName {
+ jid: user,
+ jid_alt: user_alt,
+ message: Some(message_info.clone()),
+ old_push_name: previous_name,
+ new_push_name: name.to_owned(),
+ })))
+ .await;
+ }
+ }
+ }
+
+ /// Stores a verified business name seen in a message (or a usync
+ /// response, without message) and emits [`Event::BusinessName`] if it
+ /// changed.
+ pub(crate) async fn update_business_name(
+ &self,
+ user: &Jid,
+ user_alt: &Jid,
+ message_info: Option<&MessageInfo>,
+ name: &str,
+ ) {
+ let contacts = Arc::clone(&self.store.read().await.contacts);
+ match contacts.put_business_name(user, name).await {
+ Err(error) => {
+ tracing::error!(error = %error, "failed to save business name in device store")
+ }
+ Ok((false, _)) => {}
+ Ok((true, previous_name)) => {
+ let user_alt = self.alt_jid_or_lookup(user, user_alt).await;
+ if !user_alt.is_empty()
+ && let Err(error) = contacts.put_business_name(&user_alt, name).await
+ {
+ tracing::error!(error = %error, "failed to save business name of alternate JID in device store");
+ }
+ tracing::debug!("business name changed, dispatching event");
+ self.dispatch_event(Event::BusinessName(Box::new(BusinessName {
+ jid: user.clone(),
+ message: message_info.cloned(),
+ old_business_name: previous_name,
+ new_business_name: name.to_owned(),
+ })))
+ .await;
+ }
+ }
+ }
+
+ async fn alt_jid_or_lookup(&self, user: &Jid, user_alt: &Jid) -> Jid {
+ let user_alt = user_alt.to_non_ad();
+ if !user_alt.is_empty() {
+ return user_alt;
+ }
+ self.store
+ .read()
+ .await
+ .get_alt_jid(user)
+ .await
+ .ok()
+ .flatten()
+ .unwrap_or_default()
+ }
+}
+
+/// The verified name inside a `<business>` node, if any.
+pub fn parse_verified_name(
+ business_node: &Node,
+) -> Result<Option<VerifiedName>, prost::DecodeError> {
+ if business_node.tag != "business" {
+ return Ok(None);
+ }
+ match business_node.get_optional_child_by_tag(&["verified_name"]) {
+ Some(verified_name_node) => parse_verified_name_content(verified_name_node),
+ None => Ok(None),
+ }
+}
+
+/// Parses a `<verified_name>` node; `None` when it has no certificate bytes.
+pub fn parse_verified_name_content(
+ verified_name_node: &Node,
+) -> Result<Option<VerifiedName>, prost::DecodeError> {
+ let Some(NodeContent::Bytes(raw_cert)) = &verified_name_node.content else {
+ return Ok(None);
+ };
+ let certificate = VerifiedNameCertificate::decode(raw_cert.as_slice())?;
+ let details = verified_name_certificate::Details::decode(
+ certificate.details.as_deref().unwrap_or_default(),
+ )?;
+ let mut attrs = verified_name_node.attr_getter();
+ Ok(Some(VerifiedName {
+ certificate: Some(certificate),
+ details: Some(details),
+ verified_level: attrs.string("verified_level"),
+ version: attrs.int("v"),
+ host_storage: attrs.int("host_storage"),
+ actual_actors: attrs.int("actual_actors"),
+ privacy_mode_ts: attrs.unix_time("privacy_mode_ts"),
+ }))
+}
+
+/// The device JIDs in a usync `<devices>` node of the user. Hosted devices
+/// get the hosted server; device IDs past `u16` truncate like Go's
+/// `uint16()` conversion.
+pub(crate) fn parse_device_list(user: &Jid, device_node: &Node) -> Vec<Jid> {
+ let device_list = device_node.get_child_by_tag(&["device-list"]);
+ if device_node.tag != "devices" || device_list.tag != "device-list" {
+ return Vec::new();
+ }
+ let children = device_list.get_children();
+ let mut devices = Vec::with_capacity(children.len());
+ let mut user = user.clone();
+ for device in children {
+ let device_id = device.attr_getter().get_int64("id", true);
+ let is_hosted = device.attr_getter().bool("is_hosted");
+ let Some(device_id) = device_id else { continue };
+ if device.tag != "device" {
+ continue;
+ }
+ user.device = device_id as u16;
+ if is_hosted {
+ let mut hosted_user = user.clone();
+ hosted_user.server = if user.server == HIDDEN_USER_SERVER {
+ HOSTED_LID_SERVER
+ } else {
+ HOSTED_SERVER
+ }
+ .to_owned();
+ devices.push(hosted_user);
+ } else {
+ devices.push(user.clone());
+ }
+ }
+ devices
+}
+
+#[cfg(test)]
+mod test;
diff --git a/crates/whatsmeow/src/user/test.rs b/crates/whatsmeow/src/user/test.rs
new file mode 100644
index 0000000000..934e4123cd
--- /dev/null
+++ b/crates/whatsmeow/src/user/test.rs
@@ -0,0 +1,555 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+//! Device lists, blocklists and usync requests against whatsmeow's own
+//! output (`testdata/user.json`, see `testdata/generator`), and the user
+//! queries against the fake server.
+
+use std::sync::Arc;
+use std::time::Duration;
+
+use serde_json::{Value, json};
+
+use super::*;
+use crate::client::test::{
+ Harness, capture_request, children, connect_paired, harness, jid, next_node, node, text,
+};
+use crate::store::LidStore;
+use crate::testing::{ServerConnection, attr_string, is_iq};
+use crate::vectors::Vectors;
+
+const OWN: (&str, &str) = ("1234:[email protected]", "9876:5@lid");
+
+fn node_from_hex(value: &Value) -> Node {
+ let data = hex::decode(value.as_str().unwrap()).unwrap();
+ crate::binary::unmarshal(&crate::binary::unpack(&data).unwrap()).unwrap()
+}
+
+fn jid_strings(jids: &[Jid]) -> Vec<String> {
+ jids.iter().map(ToString::to_string).collect()
+}
+
+fn parse(value: &str) -> Jid {
+ parse_jid(value).unwrap()
+}
+
+#[test]
+fn device_lists_and_blocklists_parse_like_go() {
+ let vectors = Vectors::load("user.json");
+ let Value::Array(device_lists) = vectors.value("device_lists") else {
+ panic!("device_lists is a list");
+ };
+ for device_list in device_lists {
+ let user = parse(device_list["user"].as_str().unwrap());
+ let devices = parse_device_list(&user, &node_from_hex(&device_list["node"]));
+ assert_eq!(json!(jid_strings(&devices)), device_list["devices"]);
+ assert_eq!(participant_list_hash_v2(&devices), device_list["hash"]);
+ }
+
+ let (blocklist, mappings) = Client::parse_blocklist(&vectors.node("blocklist_node"));
+ assert_eq!(
+ json!({
+ "d_hash": blocklist.d_hash,
+ "addressing_mode": blocklist.addressing_mode.as_str(),
+ "items": blocklist.items.iter().map(|item| json!({
+ "lid": item.lid.to_string(),
+ "pn": item.pn.to_string(),
+ "active": item.active,
+ })).collect::<Vec<_>>(),
+ }),
+ *vectors.value("blocklist")
+ );
+ assert_eq!(
+ json!(
+ mappings
+ .iter()
+ .map(|pair| [pair.lid.to_string(), pair.pn.to_string()])
+ .collect::<Vec<_>>()
+ ),
+ *vectors.value("blocklist_lid_pairs")
+ );
+}
+
+#[tokio::test(start_paused = true)]
+async fn user_requests_match_go() {
+ let vectors = Vectors::load("user.json");
+ let requests = vectors.value("requests");
+ let mut harness = harness(Some(OWN));
+ let mut connection = connect_paired(&mut harness).await;
+
+ macro_rules! check {
+ ($key:literal, |$client:ident| $call:expr) => {{
+ let $client = Arc::clone(&harness.client);
+ let request = capture_request(&mut connection, async move {
+ let _ = $call;
+ })
+ .await;
+ assert_eq!(request, node_from_hex(&requests[$key]), $key);
+ }};
+ }
+
+ check!("get_user_devices", |client| client
+ .get_user_devices(&[parse("[email protected]"), parse("6666:3@lid")])
+ .await);
+ check!("is_on_whatsapp", |client| client
+ .is_on_whatsapp(&["+15551234567"])
+ .await);
+ check!("get_user_info", |client| client
+ .get_user_info(&[parse("[email protected]"), parse("6666@lid")])
+ .await);
+ check!("profile_picture_preview", |client| client
+ .get_profile_picture_info(
+ &parse("[email protected]"),
+ &GetProfilePictureParams {
+ preview: true,
+ existing_id: "old".to_owned(),
+ ..GetProfilePictureParams::default()
+ },
+ )
+ .await);
+ check!("profile_picture_full", |client| client
+ .get_profile_picture_info(
+ &parse("[email protected]"),
+ &GetProfilePictureParams {
+ common_gid: parse("[email protected]"),
+ invite_code: "inv".to_owned(),
+ persona_id: "persona".to_owned(),
+ ..GetProfilePictureParams::default()
+ },
+ )
+ .await);
+ check!("profile_picture_community", |client| client
+ .get_profile_picture_info(
+ &parse("[email protected]"),
+ &GetProfilePictureParams {
+ is_community: true,
+ ..GetProfilePictureParams::default()
+ },
+ )
+ .await);
+ check!("get_blocklist", |client| client.get_blocklist("").await);
+ check!("get_blocklist_with_hash", |client| client
+ .get_blocklist("hash1")
+ .await);
+ check!("block_lid", |client| client
+ .update_blocklist(&parse("6666@lid"), BlocklistChangeAction::Block, "hash1")
+ .await);
+ check!("unblock_lid", |client| client
+ .update_blocklist(&parse("6666@lid"), BlocklistChangeAction::Unblock, "")
+ .await);
+}
+
+fn usync_devices_response(users: Vec<(&str, &[&str])>) -> Node {
+ node(
+ "usync",
+ &[],
+ children(vec![node(
+ "list",
+ &[],
+ children(
+ users
+ .into_iter()
+ .map(|(user, device_ids)| {
+ node(
+ "user",
+ &[("jid", jid(user))],
+ children(vec![node(
+ "devices",
+ &[],
+ children(vec![node(
+ "device-list",
+ &[],
+ children(
+ device_ids
+ .iter()
+ .map(|id| node("device", &[("id", text(id))], None))
+ .collect(),
+ ),
+ )]),
+ )]),
+ )
+ })
+ .collect(),
+ ),
+ )]),
+ )
+}
+
+fn usync_user_jids(request: &Node) -> Vec<String> {
+ request
+ .get_child_by_tag(&["usync", "list"])
+ .get_children()
+ .iter()
+ .map(|user| attr_string(user, "jid"))
+ .collect()
+}
+
+async fn devices_of(
+ harness: &Harness,
+ connection: &mut ServerConnection,
+ jids: Vec<Jid>,
+ response: Option<Node>,
+) -> Vec<String> {
+ let client = Arc::clone(&harness.client);
+ let call = tokio::spawn(async move { client.get_user_devices(&jids).await });
+ if let Some(response) = response {
+ let request = next_node(connection).await;
+ connection.respond_iq(&request, vec![response]).await;
+ }
+ jid_strings(&call.await.unwrap().unwrap())
+}
+
+#[tokio::test(start_paused = true)]
+async fn user_devices_are_cached_until_a_device_notification() {
+ let mut harness = harness(Some(OWN));
+ let mut connection = connect_paired(&mut harness).await;
+ let users = vec![parse("[email protected]"), parse("6666@lid")];
+
+ let client = Arc::clone(&harness.client);
+ let first_users = users.clone();
+ let first = tokio::spawn(async move { client.get_user_devices(&first_users).await });
+ let request = next_node(&mut connection).await;
+ assert!(is_iq(&request, "usync"));
+ let usync = request.get_child_by_tag(&["usync"]);
+ assert_eq!(attr_string(usync, "mode"), "query");
+ assert_eq!(attr_string(usync, "context"), "message");
+ assert_eq!(
+ usync_user_jids(&request),
+ ["[email protected]", "6666@lid"]
+ );
+ connection
+ .respond_iq(
+ &request,
+ vec![usync_devices_response(vec![
+ ("[email protected]", &["0", "2"]),
+ ("6666@lid", &["0"]),
+ ])],
+ )
+ .await;
+ let expected = ["[email protected]", "5555:[email protected]", "6666@lid"];
+ assert_eq!(jid_strings(&first.await.unwrap().unwrap()), expected);
+
+ // Cached: answered without a query.
+ assert_eq!(
+ devices_of(&harness, &mut connection, users.clone(), None).await,
+ expected
+ );
+ let cached = harness.client.user_devices_cache.lock().await;
+ assert_eq!(
+ cached.get(&parse("[email protected]")).unwrap().dhash,
+ participant_list_hash_v2(&[parse("[email protected]"), parse("5555:[email protected]")])
+ );
+ drop(cached);
+
+ connection
+ .send_node(&node(
+ "notification",
+ &[
+ ("id", text("d1")),
+ ("type", text("devices")),
+ ("from", jid("[email protected]")),
+ ("t", text("1700000000")),
+ ],
+ children(vec![node(
+ "update",
+ &[("device_hash", text("2:whatever"))],
+ children(vec![node(
+ "device",
+ &[("jid", jid("5555:[email protected]"))],
+ None,
+ )]),
+ )]),
+ ))
+ .await;
+ let ack = next_node(&mut connection).await;
+ assert_eq!(ack.tag, "ack");
+
+ let client = Arc::clone(&harness.client);
+ let again = tokio::spawn(async move { client.get_user_devices(&users).await });
+ let request = next_node(&mut connection).await;
+ assert_eq!(
+ usync_user_jids(&request),
+ "only the invalidated user is queried again"
+ );
+ connection
+ .respond_iq(
+ &request,
+ vec![usync_devices_response(vec![(
+ &["0"],
+ )])],
+ )
+ .await;
+ assert_eq!(
+ jid_strings(&again.await.unwrap().unwrap()),
+ ["6666@lid", "[email protected]"],
+ "cached users come first, like Go"
+ );
+}
+
+#[tokio::test(start_paused = true)]
+async fn is_on_whatsapp_parses_users_and_stores_lid_mappings() {
+ let mut harness = harness(Some(OWN));
+ let mut connection = connect_paired(&mut harness).await;
+ let client = Arc::clone(&harness.client);
+ let call = tokio::spawn(async move { client.is_on_whatsapp(&["+15551234567", "+1999"]).await });
+ let request = next_node(&mut connection).await;
+ let usync = request.get_child_by_tag(&["usync"]);
+ assert_eq!(attr_string(usync, "context"), "interactive");
+ let contact = request.get_child_by_tag(&["usync", "list", "user", "contact"]);
+ // Sent as a string; the decoder hands strings back as bytes.
+ assert_eq!(
+ contact.content,
+ Some(NodeContent::Bytes(b"[email protected]".to_vec()))
+ );
+ connection
+ .respond_iq(
+ &request,
+ vec![node(
+ "usync",
+ &[],
+ children(vec![node(
+ "list",
+ &[],
+ children(vec![
+ node(
+ "user",
+ &[
+ ("jid", jid("4242@lid")),
+ ("pn_jid", jid("[email protected]")),
+ ],
+ children(vec![node(
+ "contact",
+ &[("type", text("in"))],
+ crate::client::test::bytes(b"[email protected]"),
+ )]),
+ ),
+ node(
+ "user",
+ &[("pn_jid", jid("[email protected]"))],
+ children(vec![node(
+ "contact",
+ &[("type", text("out"))],
+ crate::client::test::bytes(b"[email protected]"),
+ )]),
+ ),
+ node("user", &[], None),
+ ]),
+ )]),
+ )],
+ )
+ .await;
+ let responses = call.await.unwrap().unwrap();
+ assert_eq!(responses.len(), 2);
+ assert_eq!(responses[0].query, "+15551234567");
+ assert!(responses[0].is_in);
+ assert_eq!(responses[0].jid.to_string(), "4242@lid");
+ assert_eq!(
+ responses[0].phone_number.to_string(),
+ );
+ assert_eq!(responses[1].jid.to_string(), "[email protected]");
+ assert!(!responses[1].is_in);
+ assert_eq!(
+ harness
+ .store
+ .get_pn_for_lid(&parse("4242@lid"))
+ .await
+ .unwrap()
+ .map(|pn| pn.to_string()),
+ Some("[email protected]".to_owned())
+ );
+}
+
+#[tokio::test(start_paused = true)]
+async fn user_info_and_profile_pictures() {
+ let mut harness = harness(Some(OWN));
+ let mut connection = connect_paired(&mut harness).await;
+ let user = parse("[email protected]");
+
+ let client = Arc::clone(&harness.client);
+ let lookup = user.clone();
+ let call = tokio::spawn(async move { client.get_user_info(&[lookup]).await });
+ let request = next_node(&mut connection).await;
+ assert_eq!(
+ attr_string(request.get_child_by_tag(&["usync"]), "mode"),
+ "full"
+ );
+ connection
+ .respond_iq(
+ &request,
+ vec![node(
+ "usync",
+ &[],
+ children(vec![node(
+ "list",
+ &[],
+ children(vec![node(
+ "user",
+ &[("jid", jid("[email protected]"))],
+ children(vec![
+ node("status", &[], crate::client::test::bytes(b"Busy")),
+ node("picture", &[("id", text("pic1"))], None),
+ node("lid", &[("val", jid("7777@lid"))], None),
+ node(
+ "devices",
+ &[],
+ children(vec![node(
+ "device-list",
+ &[],
+ children(vec![node("device", &[("id", text("4"))], None)]),
+ )]),
+ ),
+ ]),
+ )]),
+ )]),
+ )],
+ )
+ .await;
+ let info = call.await.unwrap().unwrap();
+ let info = info.get(&user).unwrap();
+ assert_eq!(info.status, "Busy");
+ assert_eq!(info.picture_id, "pic1");
+ assert_eq!(info.lid.to_string(), "7777@lid");
+ assert_eq!(jid_strings(&info.devices), ["5555:[email protected]"]);
+ assert_eq!(
+ harness
+ .store
+ .get_lid_for_pn(&user)
+ .await
+ .unwrap()
+ .map(|lid| lid.to_string()),
+ Some("7777@lid".to_owned())
+ );
+
+ let client = Arc::clone(&harness.client);
+ let lookup = user.clone();
+ let call = tokio::spawn(async move {
+ client
+ .get_profile_picture_info(&lookup, &GetProfilePictureParams::default())
+ .await
+ });
+ let request = next_node(&mut connection).await;
+ assert!(is_iq(&request, "w:profile:picture"));
+ assert_eq!(attr_string(&request, "target"), "[email protected]");
+ connection
+ .respond_iq(
+ &request,
+ vec![node(
+ "picture",
+ &[
+ ("id", text("pic2")),
+ ("url", text("https://pps.example/pic")),
+ ("type", text("image")),
+ ("direct_path", text("/v/pic")),
+ ("hash", text("AQID")),
+ ],
+ None,
+ )],
+ )
+ .await;
+ let picture = call.await.unwrap().unwrap().unwrap();
+ assert_eq!(picture.id, "pic2");
+ assert_eq!(picture.url, "https://pps.example/pic");
+ assert_eq!(picture.hash, [1, 2, 3]);
+
+ let client = Arc::clone(&harness.client);
+ let lookup = user.clone();
+ let call = tokio::spawn(async move {
+ client
+ .get_profile_picture_info(&lookup, &GetProfilePictureParams::default())
+ .await
+ });
+ let request = next_node(&mut connection).await;
+ connection
+ .respond_iq_error(&request, 404, "item-not-found")
+ .await;
+ let error = call.await.unwrap().unwrap_err();
+ assert_eq!(
+ error.to_string(),
+ "that user or group does not have a profile picture"
+ );
+ assert!(error.is(&ClientError::ProfilePictureNotSet));
+
+ let client = Arc::clone(&harness.client);
+ let call = tokio::spawn(async move {
+ client
+ .get_profile_picture_info(
+ &user,
+ &GetProfilePictureParams {
+ existing_id: "pic2".to_owned(),
+ ..GetProfilePictureParams::default()
+ },
+ )
+ .await
+ });
+ let request = next_node(&mut connection).await;
+ connection
+ .respond_iq(
+ &request,
+ vec![node("picture", &[("status", text("304"))], None)],
+ )
+ .await;
+ assert_eq!(call.await.unwrap().unwrap(), None, "unchanged picture");
+}
+
+#[tokio::test(start_paused = true)]
+async fn blocklists_are_fetched_and_updated() {
+ let mut harness = harness(Some(OWN));
+ let mut connection = connect_paired(&mut harness).await;
+
+ let client = Arc::clone(&harness.client);
+ let call = tokio::spawn(async move { client.get_blocklist("").await });
+ let request = next_node(&mut connection).await;
+ assert!(is_iq(&request, "blocklist"));
+ connection
+ .respond_iq(
+ &request,
+ vec![node(
+ "list",
+ &[("dhash", text("h1"))],
+ children(vec![node(
+ "item",
+ &[
+ ("jid", jid("6666@lid")),
+ ("pn_jid", jid("[email protected]")),
+ ("active", text("true")),
+ ],
+ None,
+ )]),
+ )],
+ )
+ .await;
+ let blocklist = call.await.unwrap().unwrap().unwrap();
+ assert!(blocklist.is_blocked(&parse("[email protected]")));
+ assert_eq!(jid_strings(&blocklist.lids()), ["6666@lid"]);
+
+ // Blocking a phone number goes by the LID the store now knows.
+ let client = Arc::clone(&harness.client);
+ let call = tokio::spawn(async move {
+ client
+ .update_blocklist(
+ &parse("[email protected]"),
+ BlocklistChangeAction::Block,
+ "h1",
+ )
+ .await
+ });
+ let request = next_node(&mut connection).await;
+ let item = request.get_child_by_tag(&["item"]);
+ assert_eq!(attr_string(item, "jid"), "6666@lid");
+ assert_eq!(attr_string(item, "pn_jid"), "[email protected]");
+ assert_eq!(attr_string(item, "action"), "block");
+ connection
+ .respond_iq(
+ &request,
+ vec![node("list", &[("matched", text("true"))], None)],
+ )
+ .await;
+ assert_eq!(call.await.unwrap().unwrap(), None, "the hash matched");
+
+ let nothing = tokio::time::timeout(Duration::from_secs(5), next_node(&mut connection)).await;
+ assert!(nothing.is_err());
+}
diff --git a/crates/whatsmeow/src/util.rs b/crates/whatsmeow/src/util.rs
new file mode 100644
index 0000000000..567b65ef2e
--- /dev/null
+++ b/crates/whatsmeow/src/util.rs
@@ -0,0 +1,14 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+//
+// Ported from whatsmeow util/ (MPL-2.0, Copyright (c) Tulir Asokan)
+
+//! Cryptographic helpers shared across the client.
+//!
+//! Not ported: `util/log`; the port logs with `tracing`.
+
+pub mod cbcutil;
+pub mod gcmutil;
+pub mod hkdfutil;
+pub mod keys;
diff --git a/crates/whatsmeow/src/util/cbcutil.rs b/crates/whatsmeow/src/util/cbcutil.rs
new file mode 100644
index 0000000000..57fda1af33
--- /dev/null
+++ b/crates/whatsmeow/src/util/cbcutil.rs
@@ -0,0 +1,14 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+//
+// Ported from whatsmeow util/cbcutil/ (MPL-2.0, Copyright (c) Tulir Asokan)
+
+//! AES-256-CBC with PKCS#7 padding, as WhatsApp media and app state use it.
+//!
+//! Unpadding is deliberately as lenient as Go's: only the last byte is read,
+//! and it is only checked against the total length.
+
+mod cbc;
+
+pub use cbc::*;
diff --git a/crates/whatsmeow/src/util/cbcutil/cbc.rs b/crates/whatsmeow/src/util/cbcutil/cbc.rs
new file mode 100644
index 0000000000..31557541a8
--- /dev/null
+++ b/crates/whatsmeow/src/util/cbcutil/cbc.rs
@@ -0,0 +1,258 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+//
+// Ported from whatsmeow util/cbcutil/cbc.go (MPL-2.0, Copyright (c) Tulir Asokan)
+
+use std::io::{self, Read, Seek, SeekFrom, Write};
+
+use aes::Aes256;
+use aes::cipher::{BlockDecryptMut, BlockEncryptMut, KeyIvInit};
+use hmac::{Hmac, Mac};
+use sha2::{Digest, Sha256};
+
+/// The AES block size.
+pub const BLOCK_SIZE: usize = 16;
+/// How much `decrypt_file` and `encrypt_stream` process at once.
+const BUFFER_SIZE: usize = 32 * 1024;
+/// How many bytes of the HMAC WhatsApp appends to encrypted media.
+const MAC_SIZE: usize = 10;
+const BLOCK_SIZE_U64: u64 = 16;
+const BUFFER_SIZE_U64: u64 = 32 * 1024;
+
+type Encryptor = cbc::Encryptor<Aes256>;
+type Decryptor = cbc::Decryptor<Aes256>;
+type HmacSha256 = Hmac<Sha256>;
+
+/// An AES-CBC failure.
+#[derive(Debug, thiserror::Error)]
+pub enum CbcError {
+ /// The key isn't 32 bytes or the IV isn't 16 bytes. Go also accepts
+ /// AES-128 and AES-192 keys, but whatsmeow only ever passes 32-byte keys.
+ #[error("invalid AES-256-CBC key or IV length")]
+ InvalidKeyOrIv,
+ /// The ciphertext is empty or not whole blocks.
+ #[error("ciphertext isn't a multiple of block size: {0} / {BLOCK_SIZE}")]
+ NotBlockAligned(u64),
+ /// The padding byte is larger than the data.
+ #[error("padding is greater then the length: {padding} / {length}")]
+ InvalidPadding {
+ /// The padding length the last byte claims.
+ padding: u64,
+ /// The data length.
+ length: u64,
+ },
+ /// Reading or writing failed.
+ #[error("{context}: {source}")]
+ Io {
+ /// What was being done.
+ context: &'static str,
+ /// The underlying failure.
+ source: io::Error,
+ },
+}
+
+fn io_error(context: &'static str) -> impl FnOnce(io::Error) -> CbcError {
+ move |source| CbcError::Io { context, source }
+}
+
+/// Decrypts `ciphertext` with a key and IV and removes the padding.
+pub fn decrypt(key: &[u8], iv: &[u8], ciphertext: &[u8]) -> Result<Vec<u8>, CbcError> {
+ let mut decryptor =
+ Decryptor::new_from_slices(key, iv).map_err(|_| CbcError::InvalidKeyOrIv)?;
+ if ciphertext.is_empty() || !ciphertext.len().is_multiple_of(BLOCK_SIZE) {
+ return Err(CbcError::NotBlockAligned(ciphertext.len() as u64));
+ }
+ let mut plaintext = ciphertext.to_vec();
+ for block in plaintext.chunks_exact_mut(BLOCK_SIZE) {
+ decryptor.decrypt_block_mut(block.into());
+ }
+ unpad(plaintext)
+}
+
+/// A file that can be decrypted in place: Go's `File` interface (`io.Reader`,
+/// `io.WriterAt`, `Truncate`, `Stat`) expressed with seeking.
+pub trait File: Read + Write + Seek {
+ /// Shrinks the file to `size` bytes.
+ fn truncate(&mut self, size: u64) -> io::Result<()>;
+ /// The current size of the file.
+ fn size(&self) -> io::Result<u64>;
+}
+
+impl File for std::fs::File {
+ fn truncate(&mut self, size: u64) -> io::Result<()> {
+ self.set_len(size)
+ }
+
+ fn size(&self) -> io::Result<u64> {
+ Ok(self.metadata()?.len())
+ }
+}
+
+/// Decrypts a whole file in place, from its start, and truncates the padding.
+pub fn decrypt_file(key: &[u8], iv: &[u8], file: &mut impl File) -> Result<(), CbcError> {
+ let mut decryptor =
+ Decryptor::new_from_slices(key, iv).map_err(|_| CbcError::InvalidKeyOrIv)?;
+ let file_size = file.size().map_err(io_error("failed to stat file"))?;
+ if !file_size.is_multiple_of(BLOCK_SIZE_U64) {
+ return Err(CbcError::NotBlockAligned(file_size));
+ }
+
+ let mut buffer = vec![0; BUFFER_SIZE];
+ let mut write_pointer = 0;
+ let mut last_byte = 0;
+ while write_pointer < file_size {
+ let chunk_length = usize::try_from((file_size - write_pointer).min(BUFFER_SIZE_U64))
+ .unwrap_or(BUFFER_SIZE);
+ let chunk = &mut buffer[..chunk_length];
+ file.seek(SeekFrom::Start(write_pointer))
+ .map_err(io_error("failed to read file"))?;
+ file.read_exact(chunk)
+ .map_err(io_error("failed to read file"))?;
+ for block in chunk.chunks_exact_mut(BLOCK_SIZE) {
+ decryptor.decrypt_block_mut(block.into());
+ }
+ file.seek(SeekFrom::Start(write_pointer))
+ .map_err(io_error("failed to write file"))?;
+ file.write_all(chunk)
+ .map_err(io_error("failed to write file"))?;
+ write_pointer += chunk_length as u64;
+ last_byte = chunk[chunk_length - 1];
+ }
+ if u64::from(last_byte) > file_size {
+ return Err(CbcError::InvalidPadding {
+ padding: u64::from(last_byte),
+ length: file_size,
+ });
+ }
+ file.truncate(file_size - u64::from(last_byte))
+ .map_err(io_error("failed to truncate file to remove padding"))
+}
+
+/// Pads and encrypts `plaintext`. Without an IV, a random one is generated and
+/// prepended to the ciphertext.
+pub fn encrypt(key: &[u8], iv: Option<&[u8]>, plaintext: &[u8]) -> Result<Vec<u8>, CbcError> {
+ let generated_iv: [u8; BLOCK_SIZE];
+ let (iv, mut ciphertext) = match iv {
+ Some(iv) => (iv, Vec::with_capacity(plaintext.len() + BLOCK_SIZE)),
+ None => {
+ generated_iv = rand::random();
+ (generated_iv.as_slice(), generated_iv.to_vec())
+ }
+ };
+ let mut encryptor =
+ Encryptor::new_from_slices(key, iv).map_err(|_| CbcError::InvalidKeyOrIv)?;
+ let start = ciphertext.len();
+ ciphertext.extend_from_slice(plaintext);
+ pad(&mut ciphertext);
+ for block in ciphertext[start..].chunks_exact_mut(BLOCK_SIZE) {
+ encryptor.encrypt_block_mut(block.into());
+ }
+ Ok(ciphertext)
+}
+
+/// Appends PKCS#7 padding: 1 to 16 bytes, so there is always some.
+fn pad(data: &mut Vec<u8>) {
+ let padding = BLOCK_SIZE - data.len() % BLOCK_SIZE;
+ // padding is between 1 and BLOCK_SIZE (16).
+ let padding_byte = u8::try_from(padding).unwrap_or(u8::MAX);
+ data.resize(data.len() + padding, padding_byte);
+}
+
+fn unpad(mut source: Vec<u8>) -> Result<Vec<u8>, CbcError> {
+ let length = source.len();
+ let padding = usize::from(source[length - 1]);
+ if padding > length {
+ return Err(CbcError::InvalidPadding {
+ padding: padding as u64,
+ length: length as u64,
+ });
+ }
+ source.truncate(length - padding);
+ Ok(source)
+}
+
+/// The result of [`encrypt_stream`].
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct EncryptedStream {
+ /// SHA-256 of the plaintext.
+ pub plaintext_sha256: [u8; 32],
+ /// SHA-256 of everything written: the ciphertext and the MAC.
+ pub ciphertext_sha256: [u8; 32],
+ /// The plaintext length.
+ pub plaintext_length: u64,
+ /// The written length: ciphertext with padding, plus the MAC.
+ pub ciphertext_length: u64,
+}
+
+/// Encrypts a stream for upload: AES-256-CBC with padding, followed by the
+/// first 10 bytes of HMAC-SHA256(iv || ciphertext) under `mac_key`.
+pub fn encrypt_stream(
+ key: &[u8],
+ iv: &[u8],
+ mac_key: &[u8],
+ plaintext: &mut impl Read,
+ ciphertext: &mut impl Write,
+) -> Result<EncryptedStream, CbcError> {
+ let mut encryptor =
+ Encryptor::new_from_slices(key, iv).map_err(|_| CbcError::InvalidKeyOrIv)?;
+ let mut plain_hasher = Sha256::new();
+ let mut cipher_hasher = Sha256::new();
+ let mut cipher_mac =
+ <HmacSha256 as Mac>::new_from_slice(mac_key).map_err(|_| CbcError::InvalidKeyOrIv)?;
+ cipher_mac.update(iv);
+
+ let mut buffer = vec![0; BUFFER_SIZE];
+ let mut size = 0;
+ loop {
+ let read = read_full(plaintext, &mut buffer).map_err(io_error("failed to read file"))?;
+ plain_hasher.update(&buffer[..read]);
+ size += read as u64;
+ let has_more = read == BUFFER_SIZE;
+ let mut chunk = buffer[..read].to_vec();
+ if !has_more {
+ pad(&mut chunk);
+ }
+ for block in chunk.chunks_exact_mut(BLOCK_SIZE) {
+ encryptor.encrypt_block_mut(block.into());
+ }
+ cipher_mac.update(&chunk);
+ cipher_hasher.update(&chunk);
+ ciphertext
+ .write_all(&chunk)
+ .map_err(io_error("failed to write file"))?;
+ if !has_more {
+ break;
+ }
+ }
+ let mac = cipher_mac.finalize().into_bytes();
+ let mac = &mac[..MAC_SIZE];
+ cipher_hasher.update(mac);
+ ciphertext
+ .write_all(mac)
+ .map_err(io_error("failed to write checksum to file"))?;
+ let padding = BLOCK_SIZE_U64 - size % BLOCK_SIZE_U64;
+ Ok(EncryptedStream {
+ plaintext_sha256: plain_hasher.finalize().into(),
+ ciphertext_sha256: cipher_hasher.finalize().into(),
+ plaintext_length: size,
+ ciphertext_length: size + padding + MAC_SIZE as u64,
+ })
+}
+
+/// Go's `io.ReadFull`, returning how much was read before the end of input.
+fn read_full(reader: &mut impl Read, buffer: &mut [u8]) -> io::Result<usize> {
+ let mut filled = 0;
+ while filled < buffer.len() {
+ match reader.read(&mut buffer[filled..]) {
+ Ok(0) => break,
+ Ok(read) => filled += read,
+ Err(error) if error.kind() == io::ErrorKind::Interrupted => {}
+ Err(error) => return Err(error),
+ }
+ }
+ Ok(filled)
+}
+
+#[cfg(test)]
+mod test;
diff --git a/crates/whatsmeow/src/util/cbcutil/cbc/test.rs b/crates/whatsmeow/src/util/cbcutil/cbc/test.rs
new file mode 100644
index 0000000000..934b7e0a64
--- /dev/null
+++ b/crates/whatsmeow/src/util/cbcutil/cbc/test.rs
@@ -0,0 +1,128 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+//! Expected values were produced by whatsmeow's Go code at the pinned revision.
+
+use std::io::Cursor;
+
+use super::*;
+
+#[test]
+fn encrypt_matches_go_for_every_padding_length() {
+ let key: Vec<u8> = (0x40..0x60).collect();
+ let iv: Vec<u8> = (0x90..0xa0).collect();
+ let cases = [
+ (0, "f21da86a109ab406087a15d196c221ca"),
+ (5, "a006058f4c46efee43e1943499029788"),
+ (
+ 16,
+ "b78f41d7ca2543b61d6b370dd1f94e583c7f117fc6c5d90d37ec4fa4eb949400",
+ ),
+ (
+ 33,
+ "b78f41d7ca2543b61d6b370dd1f94e58f005ca3c5d58924d8b9170e2a3478072dd69d3b79e50ba8835da407b3d4abfce",
+ ),
+ ];
+ for (length, expected) in cases {
+ let plaintext: Vec<u8> = (0x10..0x10 + length).collect();
+ let ciphertext = encrypt(&key, Some(&iv), &plaintext).unwrap();
+ assert_eq!(hex::encode(&ciphertext), expected, "{length}");
+ assert_eq!(decrypt(&key, &iv, &ciphertext).unwrap(), plaintext);
+ }
+}
+
+#[test]
+fn encrypt_without_iv_prepends_a_random_one() {
+ let key: Vec<u8> = (0x40..0x60).collect();
+ let ciphertext = encrypt(&key, None, b"app state").unwrap();
+ assert_eq!(ciphertext.len(), 32);
+ let (iv, ciphertext) = ciphertext.split_at(BLOCK_SIZE);
+ assert_eq!(decrypt(&key, iv, ciphertext).unwrap(), b"app state");
+}
+
+#[test]
+fn decrypt_unpads_as_leniently_as_go() {
+ let key: Vec<u8> = (0x40..0x60).collect();
+ let iv: Vec<u8> = (0x90..0xa0).collect();
+ // A last byte of 0 removes nothing; Go doesn't validate the other padding bytes.
+ let mut block = [3; 16];
+ block[15] = 0;
+ let ciphertext = encrypt(&key, Some(&iv), &block).unwrap();
+ let decrypted_with_padding = decrypt(&key, &iv, &ciphertext).unwrap();
+ assert_eq!(decrypted_with_padding, block);
+
+ assert!(matches!(
+ decrypt(&key, &iv, &ciphertext[..15]),
+ Err(CbcError::NotBlockAligned(15))
+ ));
+ assert!(matches!(
+ decrypt(&key, &iv, &[]),
+ Err(CbcError::NotBlockAligned(0))
+ ));
+}
+
+#[test]
+fn encrypt_stream_matches_go() {
+ let key: Vec<u8> = (0x40..0x60).collect();
+ let iv: Vec<u8> = (0x90..0xa0).collect();
+ let mac_key: Vec<u8> = (0xa0..0xc0).collect();
+ // 33600 bytes, so the stream spans two read buffers.
+ let plaintext = b"whatsmeow media ".repeat(2100);
+ let mut output = Vec::new();
+ let result = encrypt_stream(
+ &key,
+ &iv,
+ &mac_key,
+ &mut Cursor::new(&plaintext),
+ &mut output,
+ )
+ .unwrap();
+
+ assert_eq!(
+ result,
+ EncryptedStream {
+ plaintext_sha256: hex::decode(
+ "f86ecb52292f141f84d227ed410722f9eef5d77b6b207690c5490b1700f4d8ba"
+ )
+ .unwrap()
+ .try_into()
+ .unwrap(),
+ ciphertext_sha256: hex::decode(
+ "b0eb3872d3e97a983d104299a3c8d74901482d1f52e4a6984837fe5cdf6f1058"
+ )
+ .unwrap()
+ .try_into()
+ .unwrap(),
+ plaintext_length: 33600,
+ ciphertext_length: 33626,
+ }
+ );
+ assert_eq!(output.len(), 33626);
+ assert_eq!(
+ hex::encode(&output[output.len() - 26..]),
+ "72320d499cf9ee9c637d32319afcc2fe8f9bc59eda041a466022"
+ );
+ assert_eq!(
+ output[..33616],
+ encrypt(&key, Some(&iv), &plaintext).unwrap()
+ );
+}
+
+#[test]
+fn decrypt_file_decrypts_in_place_and_truncates_padding() {
+ let key: Vec<u8> = (0x40..0x60).collect();
+ let iv: Vec<u8> = (0x90..0xa0).collect();
+ let plaintext = b"whatsmeow media ".repeat(2100);
+ let mut file = tempfile::tempfile().unwrap();
+ file.write_all(&encrypt(&key, Some(&iv), &plaintext).unwrap())
+ .unwrap();
+
+ decrypt_file(&key, &iv, &mut file).unwrap();
+
+ assert_eq!(file.size().unwrap(), 33600);
+ let mut decrypted = Vec::new();
+ file.seek(SeekFrom::Start(0)).unwrap();
+ file.read_to_end(&mut decrypted).unwrap();
+ assert_eq!(decrypted, plaintext);
+}
diff --git a/crates/whatsmeow/src/util/gcmutil.rs b/crates/whatsmeow/src/util/gcmutil.rs
new file mode 100644
index 0000000000..a09db0f827
--- /dev/null
+++ b/crates/whatsmeow/src/util/gcmutil.rs
@@ -0,0 +1,11 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+//
+// Ported from whatsmeow util/gcmutil/ (MPL-2.0, Copyright (c) Tulir Asokan)
+
+//! AES-256-GCM helpers.
+
+mod gcm;
+
+pub use gcm::*;
diff --git a/crates/whatsmeow/src/util/gcmutil/gcm.rs b/crates/whatsmeow/src/util/gcmutil/gcm.rs
new file mode 100644
index 0000000000..596e66e2c9
--- /dev/null
+++ b/crates/whatsmeow/src/util/gcmutil/gcm.rs
@@ -0,0 +1,96 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+//
+// Ported from whatsmeow util/gcmutil/gcm.go (MPL-2.0, Copyright (c) Tulir Asokan)
+
+use aes_gcm::aead::{Aead, Payload};
+use aes_gcm::{Aes256Gcm, KeyInit, Nonce};
+
+/// The nonce length Go's `cipher.NewGCM` uses.
+pub const NONCE_SIZE: usize = 12;
+
+/// An AES-GCM failure.
+#[derive(Debug, thiserror::Error, PartialEq, Eq)]
+pub enum GcmError {
+ /// The key isn't 32 bytes. Go also accepts AES-128 and AES-192 keys, but
+ /// whatsmeow only ever passes 32-byte keys.
+ #[error("failed to initialize AES cipher: invalid key size {0}")]
+ InvalidKeySize(usize),
+ /// The nonce isn't [`NONCE_SIZE`] bytes (Go panics).
+ #[error("invalid GCM nonce size {0}")]
+ InvalidNonceSize(usize),
+ /// Authentication failed while decrypting.
+ #[error("cipher: message authentication failed")]
+ Authentication,
+}
+
+/// Creates an AES-256-GCM cipher from a key.
+pub fn prepare(secret_key: &[u8]) -> Result<Aes256Gcm, GcmError> {
+ Aes256Gcm::new_from_slice(secret_key).map_err(|_| GcmError::InvalidKeySize(secret_key.len()))
+}
+
+/// Decrypts and authenticates `ciphertext` (with the tag appended).
+pub fn decrypt(
+ secret_key: &[u8],
+ iv: &[u8],
+ ciphertext: &[u8],
+ additional_data: &[u8],
+) -> Result<Vec<u8>, GcmError> {
+ open(&prepare(secret_key)?, iv, ciphertext, additional_data)
+}
+
+/// Encrypts `plaintext`, appending the authentication tag.
+pub fn encrypt(
+ secret_key: &[u8],
+ iv: &[u8],
+ plaintext: &[u8],
+ additional_data: &[u8],
+) -> Result<Vec<u8>, GcmError> {
+ seal(&prepare(secret_key)?, iv, plaintext, additional_data)
+}
+
+/// Go's `AEAD.Seal` on a prepared cipher.
+pub fn seal(
+ cipher: &Aes256Gcm,
+ iv: &[u8],
+ plaintext: &[u8],
+ additional_data: &[u8],
+) -> Result<Vec<u8>, GcmError> {
+ let nonce = nonce(iv)?;
+ let payload = Payload {
+ msg: plaintext,
+ aad: additional_data,
+ };
+ // Encryption only fails for plaintexts beyond GCM's 64 GiB limit.
+ cipher
+ .encrypt(nonce, payload)
+ .map_err(|_| GcmError::Authentication)
+}
+
+/// Go's `AEAD.Open` on a prepared cipher.
+pub fn open(
+ cipher: &Aes256Gcm,
+ iv: &[u8],
+ ciphertext: &[u8],
+ additional_data: &[u8],
+) -> Result<Vec<u8>, GcmError> {
+ let nonce = nonce(iv)?;
+ let payload = Payload {
+ msg: ciphertext,
+ aad: additional_data,
+ };
+ cipher
+ .decrypt(nonce, payload)
+ .map_err(|_| GcmError::Authentication)
+}
+
+fn nonce(iv: &[u8]) -> Result<&Nonce<<Aes256Gcm as aes_gcm::AeadCore>::NonceSize>, GcmError> {
+ if iv.len() != NONCE_SIZE {
+ return Err(GcmError::InvalidNonceSize(iv.len()));
+ }
+ Ok(iv.into())
+}
+
+#[cfg(test)]
+mod test;
diff --git a/crates/whatsmeow/src/util/gcmutil/gcm/test.rs b/crates/whatsmeow/src/util/gcmutil/gcm/test.rs
new file mode 100644
index 0000000000..eaabe90c94
--- /dev/null
+++ b/crates/whatsmeow/src/util/gcmutil/gcm/test.rs
@@ -0,0 +1,45 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+//! Expected values were produced by whatsmeow's Go code at the pinned revision.
+
+use super::*;
+
+#[test]
+fn encrypt_matches_go_and_decrypts_back() {
+ let key: Vec<u8> = (0x40..0x60).collect();
+ let iv: Vec<u8> = (0x80..0x8c).collect();
+ let ciphertext = encrypt(&key, &iv, b"hello whatsmeow", b"aad").unwrap();
+ assert_eq!(
+ hex::encode(&ciphertext),
+ "453bd2ab4d545deb091ee34517cde263305e7ba69bd1ef70560c63f3834543"
+ );
+ assert_eq!(
+ decrypt(&key, &iv, &ciphertext, b"aad").unwrap(),
+ b"hello whatsmeow"
+ );
+ assert_eq!(
+ hex::encode(encrypt(&key, &iv, &[], &[]).unwrap()),
+ "181bad459ada9d8a2a177dc184770f4c"
+ );
+}
+
+#[test]
+fn decrypt_rejects_tampering_and_bad_sizes() {
+ let key: Vec<u8> = (0x40..0x60).collect();
+ let iv: Vec<u8> = (0x80..0x8c).collect();
+ let ciphertext = encrypt(&key, &iv, b"hello whatsmeow", b"aad").unwrap();
+ assert_eq!(
+ decrypt(&key, &iv, &ciphertext, b"other"),
+ Err(GcmError::Authentication)
+ );
+ assert_eq!(
+ decrypt(&key[..16], &iv, &ciphertext, b"aad"),
+ Err(GcmError::InvalidKeySize(16))
+ );
+ assert_eq!(
+ decrypt(&key, &iv[..8], &ciphertext, b"aad"),
+ Err(GcmError::InvalidNonceSize(8))
+ );
+}
diff --git a/crates/whatsmeow/src/util/hkdfutil.rs b/crates/whatsmeow/src/util/hkdfutil.rs
new file mode 100644
index 0000000000..b072855c08
--- /dev/null
+++ b/crates/whatsmeow/src/util/hkdfutil.rs
@@ -0,0 +1,11 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+//
+// Ported from whatsmeow util/hkdfutil/ (MPL-2.0, Copyright (c) Tulir Asokan)
+
+//! A simple HKDF wrapper that reads a specified number of bytes.
+
+mod hkdf;
+
+pub use hkdf::*;
diff --git a/crates/whatsmeow/src/util/hkdfutil/hkdf.rs b/crates/whatsmeow/src/util/hkdfutil/hkdf.rs
new file mode 100644
index 0000000000..3f51b7b33a
--- /dev/null
+++ b/crates/whatsmeow/src/util/hkdfutil/hkdf.rs
@@ -0,0 +1,20 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+//
+// Ported from whatsmeow util/hkdfutil/hkdf.go (MPL-2.0, Copyright (c) Tulir Asokan)
+
+use hkdf::Hkdf;
+use sha2::Sha256;
+
+/// Derives `length` bytes with HKDF-SHA256. An empty salt is the same as none.
+pub fn sha256(key: &[u8], salt: &[u8], info: &[u8], length: u8) -> Vec<u8> {
+ let mut data = vec![0; usize::from(length)];
+ Hkdf::<Sha256>::new(Some(salt), key)
+ .expand(info, &mut data)
+ .expect("HKDF-SHA256 expands up to 8160 bytes and length is at most 255");
+ data
+}
+
+#[cfg(test)]
+mod test;
diff --git a/crates/whatsmeow/src/util/hkdfutil/hkdf/test.rs b/crates/whatsmeow/src/util/hkdfutil/hkdf/test.rs
new file mode 100644
index 0000000000..b1160f3004
--- /dev/null
+++ b/crates/whatsmeow/src/util/hkdfutil/hkdf/test.rs
@@ -0,0 +1,21 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+//! Expected values were produced by whatsmeow's Go code at the pinned revision.
+
+use super::*;
+
+#[test]
+fn sha256_matches_go() {
+ let key: Vec<u8> = (0..32).collect();
+ assert_eq!(
+ hex::encode(sha256(&key, &[], b"WhatsApp Media Retry Notification", 32)),
+ "c84dfe50a708e0ec382a7ad2ba40135256f41b652cebe2129661d27871111cb2"
+ );
+ assert_eq!(
+ hex::encode(sha256(&key, b"salt", b"WhatsApp Image Keys", 112)),
+ "39136149f9a1c91144cb1c6bfbc618b0bbcd5cdfb00126e956ebbaf37549ce530dbaf75c7a4951bd2ba8f60aaec7f6db0468b2ecf9dada95e9b4314db65de8fb0857afd2b8f6dd84f0c46a63491d983cae4c2df209c8da79508816ebd81435c3bbae6dead3e5d06a54bd056db3a8f739"
+ );
+ assert_eq!(sha256(&key, &[], &[], 255).len(), 255);
+}
diff --git a/crates/whatsmeow/src/util/keys.rs b/crates/whatsmeow/src/util/keys.rs
new file mode 100644
index 0000000000..ab870f1d36
--- /dev/null
+++ b/crates/whatsmeow/src/util/keys.rs
@@ -0,0 +1,11 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+//
+// Ported from whatsmeow util/keys/ (MPL-2.0, Copyright (c) Tulir Asokan)
+
+//! A utility struct for elliptic curve keypairs.
+
+mod keypair;
+
+pub use keypair::*;
diff --git a/crates/whatsmeow/src/util/keys/keypair.rs b/crates/whatsmeow/src/util/keys/keypair.rs
new file mode 100644
index 0000000000..12975fc8fb
--- /dev/null
+++ b/crates/whatsmeow/src/util/keys/keypair.rs
@@ -0,0 +1,86 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+//
+// Ported from whatsmeow util/keys/keypair.go (MPL-2.0, Copyright (c) Tulir Asokan)
+
+use std::fmt;
+
+use crate::signal::{CurveSignatures, DJB_TYPE};
+
+/// A Curve25519 keypair.
+#[derive(Clone, PartialEq, Eq)]
+pub struct KeyPair {
+ /// The public key.
+ pub public: [u8; 32],
+ /// The (clamped) private key.
+ pub private: [u8; 32],
+}
+
+/// Never prints the private key.
+impl fmt::Debug for KeyPair {
+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
+ formatter
+ .debug_struct("KeyPair")
+ .field("public", &hex::encode(self.public))
+ .finish_non_exhaustive()
+ }
+}
+
+/// Derives the keypair of a private key.
+pub fn new_key_pair_from_private_key(private: [u8; 32]) -> KeyPair {
+ KeyPair {
+ public: x25519_dalek::x25519(private, x25519_dalek::X25519_BASEPOINT_BYTES),
+ private,
+ }
+}
+
+/// Generates a new random keypair.
+pub fn new_key_pair() -> KeyPair {
+ let mut private: [u8; 32] = rand::random();
+ private[0] &= 248;
+ private[31] &= 127;
+ private[31] |= 64;
+ new_key_pair_from_private_key(private)
+}
+
+impl KeyPair {
+ /// Generates a new prekey and signs it with this (identity) keypair.
+ pub fn create_signed_pre_key(&self, signatures: &impl CurveSignatures, key_id: u32) -> PreKey {
+ let mut new_key = new_pre_key(key_id);
+ new_key.signature = Some(self.sign(signatures, &new_key.key_pair));
+ new_key
+ }
+
+ /// Signs the public key of `key_to_sign`, prefixed with the key type byte
+ /// as libsignal serializes public keys.
+ pub fn sign(&self, signatures: &impl CurveSignatures, key_to_sign: &KeyPair) -> [u8; 64] {
+ let mut public_key_for_signature = [0; 33];
+ public_key_for_signature[0] = DJB_TYPE;
+ public_key_for_signature[1..].copy_from_slice(&key_to_sign.public);
+ signatures.calculate_signature(&self.private, &public_key_for_signature)
+ }
+}
+
+/// A one-time or signed prekey.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct PreKey {
+ /// The keypair.
+ pub key_pair: KeyPair,
+ /// The prekey ID.
+ pub key_id: u32,
+ /// The signature by the identity key; only signed prekeys have one.
+ pub signature: Option<[u8; 64]>,
+}
+
+/// Generates a new unsigned prekey.
+pub fn new_pre_key(key_id: u32) -> PreKey {
+ PreKey {
+ key_pair: new_key_pair(),
+ key_id,
+ signature: None,
+ }
+}
+
+#[cfg(test)]
+mod test;
diff --git a/crates/whatsmeow/src/util/keys/keypair/test.rs b/crates/whatsmeow/src/util/keys/keypair/test.rs
new file mode 100644
index 0000000000..de26cb9c8d
--- /dev/null
+++ b/crates/whatsmeow/src/util/keys/keypair/test.rs
@@ -0,0 +1,77 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+//! Expected values were produced by whatsmeow's Go code at the pinned revision.
+
+use std::sync::Mutex;
+
+use super::*;
+
+#[test]
+fn public_key_matches_go_for_a_fixed_private_key() {
+ let private = [
+ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
+ 26, 27, 28, 29, 30, 31, 32,
+ ];
+ let key_pair = new_key_pair_from_private_key(private);
+ assert_eq!(
+ hex::encode(key_pair.public),
+ "07a37cbc142093c8b755dc1b10e86cb426374ad16aa853ed0bdfc0b2b86d1c7c"
+ );
+ // Go stores the private key as given; clamping only happens in new_key_pair.
+ assert_eq!(key_pair.private, private);
+}
+
+#[test]
+fn new_key_pair_clamps_the_private_key() {
+ let key_pair = new_key_pair();
+ assert_eq!(key_pair.private[0] & 7, 0);
+ assert_eq!(key_pair.private[31] & 128, 0);
+ assert_eq!(key_pair.private[31] & 64, 64);
+ assert_eq!(new_key_pair_from_private_key(key_pair.private), key_pair);
+}
+
+/// Records what it was asked to sign and returns a fixed signature.
+struct RecordingSignatures {
+ signed: Mutex<Vec<([u8; 32], Vec<u8>)>>,
+}
+
+impl CurveSignatures for RecordingSignatures {
+ fn calculate_signature(&self, private_key: &[u8; 32], message: &[u8]) -> [u8; 64] {
+ self.signed
+ .lock()
+ .unwrap()
+ .push((*private_key, message.to_vec()));
+ [7; 64]
+ }
+
+ fn verify_signature(&self, _: &[u8; 32], _: &[u8], _: &[u8; 64]) -> bool {
+ false
+ }
+}
+
+#[test]
+fn signed_pre_key_signs_the_type_prefixed_public_key() {
+ let signatures = RecordingSignatures {
+ signed: Mutex::new(Vec::new()),
+ };
+ let identity = new_key_pair();
+ let pre_key = identity.create_signed_pre_key(&signatures, 42);
+
+ assert_eq!(pre_key.key_id, 42);
+ assert_eq!(pre_key.signature, Some([7; 64]));
+ let signed = signatures.signed.into_inner().unwrap();
+ assert_eq!(signed.len(), 1);
+ assert_eq!(signed[0].0, identity.private);
+ assert_eq!(signed[0].1[0], 5);
+ assert_eq!(signed[0].1[1..], pre_key.key_pair.public);
+}
+
+#[test]
+fn debug_output_hides_the_private_key() {
+ let key_pair = new_key_pair_from_private_key([0x11; 32]);
+ let debug = format!("{key_pair:?}");
+ assert!(debug.contains(&hex::encode(key_pair.public)));
+ assert!(!debug.contains(&hex::encode(key_pair.private)));
+}
diff --git a/crates/whatsmeow/src/vectors.rs b/crates/whatsmeow/src/vectors.rs
new file mode 100644
index 0000000000..a58004d8f2
--- /dev/null
+++ b/crates/whatsmeow/src/vectors.rs
@@ -0,0 +1,67 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+//! Reads the expected values whatsmeow's Go code produced (see
+//! `testdata/generator/README.md`). Not a port; test support only.
+
+use std::path::PathBuf;
+
+use serde_json::Value;
+
+/// One JSON object of vectors from `testdata/`.
+pub(crate) struct Vectors {
+ name: String,
+ values: serde_json::Map<String, Value>,
+}
+
+impl Vectors {
+ /// Loads `testdata/<name>`.
+ pub(crate) fn load(name: &str) -> Vectors {
+ let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
+ .join("testdata")
+ .join(name);
+ let data = std::fs::read_to_string(&path)
+ .unwrap_or_else(|error| panic!("reading {}: {error}", path.display()));
+ let Value::Object(values) = serde_json::from_str(&data).expect("vectors are JSON") else {
+ panic!("{name} is not a JSON object");
+ };
+ Vectors {
+ name: name.to_owned(),
+ values,
+ }
+ }
+
+ /// A raw value.
+ pub(crate) fn value(&self, key: &str) -> &Value {
+ self.values
+ .get(key)
+ .unwrap_or_else(|| panic!("{} has no {key}", self.name))
+ }
+
+ /// A string value.
+ pub(crate) fn string(&self, key: &str) -> String {
+ self.value(key)
+ .as_str()
+ .unwrap_or_else(|| panic!("{key} is not a string"))
+ .to_owned()
+ }
+
+ /// A hex string value, decoded.
+ pub(crate) fn bytes(&self, key: &str) -> Vec<u8> {
+ hex::decode(self.string(key)).unwrap_or_else(|error| panic!("{key} is not hex: {error}"))
+ }
+
+ /// A node marshaled by Go (`binary.Marshal`, with the leading flag byte).
+ pub(crate) fn node(&self, key: &str) -> crate::binary::Node {
+ let data = crate::binary::unpack(&self.bytes(key)).expect("unpack vector node");
+ crate::binary::unmarshal(&data).expect("unmarshal vector node")
+ }
+
+ /// A number value.
+ pub(crate) fn u64(&self, key: &str) -> u64 {
+ self.value(key)
+ .as_u64()
+ .unwrap_or_else(|| panic!("{key} is not a number"))
+ }
+}
diff --git a/crates/whatsmeow/testdata/appstate/vectors.json b/crates/whatsmeow/testdata/appstate/vectors.json
new file mode 100644
index 0000000000..c19c48090d
--- /dev/null
+++ b/crates/whatsmeow/testdata/appstate/vectors.json
@@ -0,0 +1,798 @@
+{
+ "lthash": [
+ {
+ "base": "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
+ "subtract": [
+ "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f"
+ ],
+ "add": [
+ "404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f",
+ "76616c7565206d6163"
+ ],
+ "result": "44f32446ac25f9861e17fa4e6f4e5d490d51128366ffa825995afde606630d8bad4d580a0bcc1c10089172c5b6573f44d08bd24131fa16498e4099e3eee1f77d5396455e312aa014af942f142b703b8f3f7716fed340cf71f23afbb7e13851aab1b3aa2c159a3caa8cd36a2956cd81dc83da4906a58b982b627a7eb669e7c388"
+ },
+ {
+ "base": "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f606162636465666768696a6b6c6d6e6f",
+ "subtract": [
+ "0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20"
+ ],
+ "add": [
+ "404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f",
+ "76616c7565206d6163"
+ ],
+ "result": "924a9f607838975637cf714f6b49485de1691ae805d9d1d536db2d675d5e73d10028fce293de6b9e8c5b8064cdda61f0c8e041d9d1c294aad16c098e702c0bfa940819dfbe0d5813bf8817a1731f4c8f1ef031cf77d0a75932bbdbe68cb69fceb2883463dcc73931f112904dc2408cde6c2a0acd099f52ada5b1f28b6838a929"
+ }
+ ],
+ "expanded_keys": [
+ {
+ "key_data": "101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f",
+ "index": "ddf84ab8e3f7d035358faab860cf4d68aaa82444fdcf3ff98e4d38ff3ca0a2b7",
+ "value_encryption": "2c028361b328add92736e295ef965bcca0988f0f8093fe3529d4382dc291f1e9",
+ "value_mac": "0cbf758b5c99b44023f568a037ff169c82427b406107a99089bdab37fb1f593e",
+ "snapshot_mac": "381f92773626fc7493b7d6df291ef22cf5419046f1877dc1bc8c5ce1d21bd244",
+ "patch_mac": "118fd7a9460b9922a5b1c758a4ee599bb816be2857d428c45632a7b8b76434e5"
+ },
+ {
+ "key_data": "505152535455565758595a5b5c5d5e5f606162636465666768696a6b6c6d6e6f",
+ "index": "a6b411385f6ff5b01aead3750627170b3ce0c016be890e13efe1320296148eb9",
+ "value_encryption": "beecef82f08fd0ad33dcd143c912485b4236b1fadf9e0f55a7ce6eeec2cfbd03",
+ "value_mac": "fc3308848ffa615e3bfd79a0bdbc9ba00bd95c5ecb0255aed198f071922d0870",
+ "snapshot_mac": "ff146c9d4f0d14a92f8a498565abf306b46cd96ef56a0f829cc12a6920f7c252",
+ "patch_mac": "f00f49cf45b943f038f3243291ad916424704790b22a9a9f6cc2680c7a804e42"
+ }
+ ],
+ "snapshot_mac": [
+ {
+ "hash": "808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
+ "version": 72623859790382856,
+ "name": "regular_high",
+ "key": "381f92773626fc7493b7d6df291ef22cf5419046f1877dc1bc8c5ce1d21bd244",
+ "mac": "e79869633b73109a255796c9332a6e21373ff60857e1210b3e8932010ae50faf"
+ }
+ ],
+ "patch_mac": [
+ {
+ "patch": "0a02080412a601080012a1010a220a2008412495ff8b26a94a13d615f53e9cbca9dd31f4542bdf5ea55ef80042917e8312720a70505152535455565758595a5b5c5d5e5fa8246af9944f563478f52853de00032df51eeae6411aca3d7dac9976b8c2051283bc7934264ac9d44b7b96d24592166442b8d8fb93d185f198d2f95f74de19c1080faa6cab72b2f3db4e9e2e618ed9d2af4d80cb984e78e187694e3b3d4663a81a070a0500000001aa12b801080112b3010a220a201ef008d9da5877bae8057544fc658a1eaaf1676472668d97e842c05a5faac51b1283010a8001606162636465666768696a6b6c6d6e6fae2fd376d8fba25a9493a4587830c52fe576f54314755e1e10eeadb3fa2d409a0cac432c3255a9031ecd742e7eff0aac1191eb33193744fdf3d8ac10ce210fdbed5bc42a0c79fa7e7fd8ead6412c38b2c95264c7586f0e232d3d893d607b0436363d71670b88fcf29fc14a1d6305c2041a070a0500000001aa12a601080012a1010a220a201c2d2e8fc7d2c7d745ce9ec11ac73273e2b4ff162437e0a1f11da22db637be2912720a70707172737475767778797a7b7c7d7e7fd31b8a255b2fd4cd3c2c2c8ee0d57c17f371f2783d68706bb0e2131f58c1c5d488c1ab5221752984b291e0c7f86b6a823c835b9664cde17cf493d9f568aaee583c3cd80085aa6dd8f48088a15d328ee7cb97994386812300eaef3c7baaf7460c1a070a0500000002bb12a601080112a1010a220a201c2d2e8fc7d2c7d745ce9ec11ac73273e2b4ff162437e0a1f11da22db637be2912720a70808182838485868788898a8b8c8d8e8fc9f3a507d96104804e46ca63bc3f128139411a0289d6a306f3474eb5fe83ce726bffe37e5c9a570c050843b7da1dddd097b3becfd0598c509770750bedc1807201c08c19a61cc7e99a1869bf4776b3dbc419f75f7692d591b2ccaf7a40a8fefc1a070a0500000002bb12960108011291010a220a208fe8e2c57dc368d4f2338e1c015d74ad189dd9bf30f422ddeef33f2b33f3974512620a60909192939495969798999a9b9c9d9e9f012e9b4c7468fc2844a943d9a9466adc9a76cfebed9c6bd8f1f9ea8224784ae7c82ed20ba55895e4067c66e4950d34f0eb943bc0083a2e5ae50ab41662c273f57187ffb3a275de9714064306ec75c9b81a070a0500000001aa2220ac110c81fda4063e81eff76d6030335113e40b593b286df6db02012f87deece92a2074a8961aa073f421b76cbeba6745a80fdf64aec2c8382c636e0842bb9f33214b32070a0500000002bb",
+ "name": "regular_high",
+ "key": "f00f49cf45b943f038f3243291ad916424704790b22a9a9f6cc2680c7a804e42",
+ "version": 4,
+ "mac": "74a8961aa073f421b76cbeba6745a80fdf64aec2c8382c636e0842bb9f33214b"
+ },
+ {
+ "patch": "0a02080512a601080012a1010a220a2023b77172517d7c38bf6b6cc6dd1ae2ac910efb80ee0d73ed1a3022aa444de86512720a7016a0034fde6f136b8ef2ab8eab0164d32d4f438999d130bacba6f79722a64d94c9573eaf5921e4c50ec2458565c7fdadd93579a91b72bc2c81d87bbffffe66ee75222d37e5e778a044c82852b64db4e0d5e88882f2379b8b18ec4970ed2d314fdfceb0487ac8101ca8854d2d3569d5171a070a0500000001aa12d801080012d3010a220a20d357336821f0ecc149ae3b95c8d2d33913c67bb76254dcb41a363626b75aa95112a3010aa001b699b5c04097b485cc46e0b039a8da306928346c1959eb7a294e428537ed4b0c9609dd5543829d857868b73416c71673c3bb77410302d51c8ba7dc3760fe9c5be6549d563ce10245f78eacb52be22d116910840d30cb75e52daa3df5bfc9e3cb676b0ca95916e708463e91de0677bd6b09ddfe40a7888f0241f866584debb61ff3122e04cc3790b8b2715cd189f8dba9026617ea4523084b80e047a3e0e399931a070a0500000001aa2220e1ee797282b7acc89217ab2e8ddac3f25a4d064494299c2b444e9c509b410b0e2a20cab9e5febf96fe243439b2801fd3511bf6d672805bf02daa07f5a67979928bfd32070a0500000001aa",
+ "name": "regular_high",
+ "key": "118fd7a9460b9922a5b1c758a4ee599bb816be2857d428c45632a7b8b76434e5",
+ "version": 5,
+ "mac": "cab9e5febf96fe243439b2801fd3511bf6d672805bf02daa07f5a67979928bfd"
+ }
+ ],
+ "content_mac": [
+ {
+ "operation": 0,
+ "data": "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f",
+ "key_id": "00000001aa",
+ "key": "0cbf758b5c99b44023f568a037ff169c82427b406107a99089bdab37fb1f593e",
+ "mac": "ff3d4fb25d35862b6bab05e3cf2d80b856f2dda861034dc4f2e1045ab55552c9"
+ },
+ {
+ "operation": 1,
+ "data": "0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f50",
+ "key_id": "00000001aa",
+ "key": "0cbf758b5c99b44023f568a037ff169c82427b406107a99089bdab37fb1f593e",
+ "mac": "87856a2b4268cd0092e61e6d8d6a6357b5af13f6d5bc0e7880d5d70e9ddb7886"
+ },
+ {
+ "operation": 255,
+ "data": "ff000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e",
+ "key_id": "00000001aa",
+ "key": "0cbf758b5c99b44023f568a037ff169c82427b406107a99089bdab37fb1f593e",
+ "mac": "902b29bc82496d15687a6df595aa297ce650f5c3024a3b3d91425110c0b742c1"
+ }
+ ],
+ "index_mac": [
+ {
+ "key": "ddf84ab8e3f7d035358faab860cf4d68aaa82444fdcf3ff98e4d38ff3ca0a2b7",
+ "index": "5b226d757465222c2231313131313131313140732e77686174736170702e6e6574225d",
+ "mac": "08412495ff8b26a94a13d615f53e9cbca9dd31f4542bdf5ea55ef80042917e83"
+ }
+ ],
+ "index_json": [
+ {
+ "index": [
+ "mute",
+ ],
+ "json": "[\"mute\",\"[email protected]\"]"
+ },
+ {
+ "index": [],
+ "json": "[]"
+ },
+ {
+ "index": [
+ "a\u003cb\u003e\u0026c",
+ "quote\"back\\slash",
+ "\b\f\n\r\t\u0001\u001f",
+ "\u2028\u2029",
+ "ünï😀"
+ ],
+ "json": "[\"a\\u003cb\\u003e\\u0026c\",\"quote\\\"back\\\\slash\",\"\\b\\f\\n\\r\\t\\u0001\\u001f\",\"\\u2028\\u2029\",\"ünï😀\"]"
+ }
+ ],
+ "builders": [
+ {
+ "type": "regular_high",
+ "mutations": [
+ {
+ "index": [
+ "mute",
+ ],
+ "version": 2,
+ "value": "220d080110ffffffffffffffffff01"
+ }
+ ]
+ },
+ {
+ "type": "regular_high",
+ "mutations": [
+ {
+ "index": [
+ "mute",
+ ],
+ "version": 2,
+ "value": "220908011080dd8ec39c33"
+ }
+ ]
+ },
+ {
+ "type": "regular_high",
+ "mutations": [
+ {
+ "index": [
+ "mute",
+ ],
+ "version": 2,
+ "value": "22020800"
+ }
+ ]
+ },
+ {
+ "type": "regular_low",
+ "mutations": [
+ {
+ "index": [
+ "pin_v1",
+ ],
+ "version": 5,
+ "value": "2a020801"
+ }
+ ]
+ },
+ {
+ "type": "regular_low",
+ "mutations": [
+ {
+ "index": [
+ "archive",
+ ],
+ "version": 3,
+ "value": "8a0139080112350880f09dc7061a2d0a250a1831313131313131313140732e77686174736170702e6e657410011a07334542304b45591080f09dc706"
+ },
+ {
+ "index": [
+ "pin_v1",
+ ],
+ "version": 5,
+ "value": "2a020800"
+ }
+ ]
+ },
+ {
+ "type": "regular_low",
+ "mutations": [
+ {
+ "index": [
+ "archive",
+ ],
+ "version": 3,
+ "value": "8a010a080012060880f09dc706"
+ }
+ ]
+ },
+ {
+ "type": "regular_low",
+ "mutations": [
+ {
+ "index": [
+ "markChatAsRead",
+ ],
+ "version": 3,
+ "value": "a20139080012350880f09dc7061a2d0a250a1831313131313131313140732e77686174736170702e6e657410011a07334542304b45591080f09dc706"
+ }
+ ]
+ },
+ {
+ "type": "regular",
+ "mutations": [
+ {
+ "index": [
+ "label_jid",
+ "7",
+ ],
+ "version": 3,
+ "value": "7a020801"
+ }
+ ]
+ },
+ {
+ "type": "regular",
+ "mutations": [
+ {
+ "index": [
+ "label_message",
+ "7",
+ "3EB0MSG",
+ "0",
+ "0"
+ ],
+ "version": 3,
+ "value": "7a020800"
+ }
+ ]
+ },
+ {
+ "type": "regular",
+ "mutations": [
+ {
+ "index": [
+ "label_edit",
+ "7"
+ ],
+ "version": 3,
+ "value": "720a0a04576f726b10032000"
+ }
+ ]
+ },
+ {
+ "type": "critical_block",
+ "mutations": [
+ {
+ "index": [
+ "setting_pushName"
+ ],
+ "version": 1,
+ "value": "3a060a04576f6c66"
+ }
+ ]
+ },
+ {
+ "type": "regular_high",
+ "mutations": [
+ {
+ "index": [
+ "star",
+ "3EB0MSG",
+ "1",
+ "0"
+ ],
+ "version": 2,
+ "value": "12020801"
+ }
+ ]
+ },
+ {
+ "type": "regular_high",
+ "mutations": [
+ {
+ "index": [
+ "star",
+ "3EB0MSG",
+ "0",
+ ],
+ "version": 2,
+ "value": "12020800"
+ }
+ ]
+ },
+ {
+ "type": "regular_high",
+ "mutations": [
+ {
+ "index": [
+ "deleteChat",
+ "1"
+ ],
+ "version": 6,
+ "value": "b201370a350880f09dc7061a2d0a250a1831313131313131313140732e77686174736170702e6e657410011a07334542304b45591080f09dc706"
+ }
+ ]
+ }
+ ],
+ "sequence": {
+ "name": "regular_high",
+ "keys": [
+ {
+ "id": "00000001aa",
+ "data": "101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f"
+ },
+ {
+ "id": "00000002bb",
+ "data": "505152535455565758595a5b5c5d5e5f606162636465666768696a6b6c6d6e6f"
+ }
+ ],
+ "steps": [
+ {
+ "list": {
+ "snapshot": "0a02080312b3010a220a2008412495ff8b26a94a13d615f53e9cbca9dd31f4542bdf5ea55ef80042917e831283010a8001101112131415161718191a1b1c1d1e1f05504d3645e870661a34c45988b7f92cbd1302c2c075e12a7661d3ebeba11f3fec9680761dae6a8cc128ed76815c701ec1627d7f356649cf59a4da9011175016c0cb3db6d0e0f3553e774200fcbb9f9e4689be6b083a75bdc1c2968b815b21949e274a559e7bd3914b972c1a4ec728c31a070a0500000001aa12b3010a220a201ef008d9da5877bae8057544fc658a1eaaf1676472668d97e842c05a5faac51b1283010a8001202122232425262728292a2b2c2d2e2f0f0ee49645a560a9c380b3024688f70a1bbd60111692480d6786029b1f6874fb7b9aded54600cdfff8ee6398354d634f10bd5e4ce61cd931c9a6d9c797aeed2a1d0a47dba0ad4e0c54a4db4f012ab569af3f1134ca706ae32be8ef00d1d702d696f8971b697780d14302780c3c66782f1a070a0500000001aa12a1010a220a20100b84efff300a224def9982610a9e2e2e366e4c55c234187d6f38d8b94c05d512720a70303132333435363738393a3b3c3d3e3f80c5dde4a082c58a4dfb05f4567a305e2b681d5b99782f65a17d14086b62215c640e063087aea7c8ca2f8ef429610ba0498ef244195cd04d97cc00825142210d40e99dcd61f8662fbc08b1eace0dc465d9e2af49f1f32068c674a5540fc0db1d1a070a0500000002bb12c3010a220a20063e2d71637fb68a87b23ea8a5c1e17c28f53e721fffd17e004943938f5caef91293010a9001404142434445464748494a4b4c4d4e4f3da58431dccbaa20e44d91235b9637374c91210ca4b8cdda073a3c268cda6a092b575085f4c08dabe210d424edac788b77c521ee77430718c4f23cbb4b9fbc2a977e2646e5fa5c6245af0f755d0af186f3d1e875061023adde513f4f8557c84a68e69b90b67502d87d4c212a36afa260bb76b13fc3951524a75b04f0625c19431a070a0500000001aa1a207e31191fd15d4f29d86f64f60d3e45b32734c50697c927ed6efccf7d98739d8722070a0500000001aa",
+ "patches": [
+ "0a02080412a601080012a1010a220a2008412495ff8b26a94a13d615f53e9cbca9dd31f4542bdf5ea55ef80042917e8312720a70505152535455565758595a5b5c5d5e5fa8246af9944f563478f52853de00032df51eeae6411aca3d7dac9976b8c2051283bc7934264ac9d44b7b96d24592166442b8d8fb93d185f198d2f95f74de19c1080faa6cab72b2f3db4e9e2e618ed9d2af4d80cb984e78e187694e3b3d4663a81a070a0500000001aa12b801080112b3010a220a201ef008d9da5877bae8057544fc658a1eaaf1676472668d97e842c05a5faac51b1283010a8001606162636465666768696a6b6c6d6e6fae2fd376d8fba25a9493a4587830c52fe576f54314755e1e10eeadb3fa2d409a0cac432c3255a9031ecd742e7eff0aac1191eb33193744fdf3d8ac10ce210fdbed5bc42a0c79fa7e7fd8ead6412c38b2c95264c7586f0e232d3d893d607b0436363d71670b88fcf29fc14a1d6305c2041a070a0500000001aa12a601080012a1010a220a201c2d2e8fc7d2c7d745ce9ec11ac73273e2b4ff162437e0a1f11da22db637be2912720a70707172737475767778797a7b7c7d7e7fd31b8a255b2fd4cd3c2c2c8ee0d57c17f371f2783d68706bb0e2131f58c1c5d488c1ab5221752984b291e0c7f86b6a823c835b9664cde17cf493d9f568aaee583c3cd80085aa6dd8f48088a15d328ee7cb97994386812300eaef3c7baaf7460c1a070a0500000002bb12a601080112a1010a220a201c2d2e8fc7d2c7d745ce9ec11ac73273e2b4ff162437e0a1f11da22db637be2912720a70808182838485868788898a8b8c8d8e8fc9f3a507d96104804e46ca63bc3f128139411a0289d6a306f3474eb5fe83ce726bffe37e5c9a570c050843b7da1dddd097b3becfd0598c509770750bedc1807201c08c19a61cc7e99a1869bf4776b3dbc419f75f7692d591b2ccaf7a40a8fefc1a070a0500000002bb12960108011291010a220a208fe8e2c57dc368d4f2338e1c015d74ad189dd9bf30f422ddeef33f2b33f3974512620a60909192939495969798999a9b9c9d9e9f012e9b4c7468fc2844a943d9a9466adc9a76cfebed9c6bd8f1f9ea8224784ae7c82ed20ba55895e4067c66e4950d34f0eb943bc0083a2e5ae50ab41662c273f57187ffb3a275de9714064306ec75c9b81a070a0500000001aa2220ac110c81fda4063e81eff76d6030335113e40b593b286df6db02012f87deece92a2074a8961aa073f421b76cbeba6745a80fdf64aec2c8382c636e0842bb9f33214b32070a0500000002bb",
+ "0a02080512a601080012a1010a220a2023b77172517d7c38bf6b6cc6dd1ae2ac910efb80ee0d73ed1a3022aa444de86512720a7016a0034fde6f136b8ef2ab8eab0164d32d4f438999d130bacba6f79722a64d94c9573eaf5921e4c50ec2458565c7fdadd93579a91b72bc2c81d87bbffffe66ee75222d37e5e778a044c82852b64db4e0d5e88882f2379b8b18ec4970ed2d314fdfceb0487ac8101ca8854d2d3569d5171a070a0500000001aa12d801080012d3010a220a20d357336821f0ecc149ae3b95c8d2d33913c67bb76254dcb41a363626b75aa95112a3010aa001b699b5c04097b485cc46e0b039a8da306928346c1959eb7a294e428537ed4b0c9609dd5543829d857868b73416c71673c3bb77410302d51c8ba7dc3760fe9c5be6549d563ce10245f78eacb52be22d116910840d30cb75e52daa3df5bfc9e3cb676b0ca95916e708463e91de0677bd6b09ddfe40a7888f0241f866584debb61ff3122e04cc3790b8b2715cd189f8dba9026617ea4523084b80e047a3e0e399931a070a0500000001aa2220e1ee797282b7acc89217ab2e8ddac3f25a4d064494299c2b444e9c509b410b0e2a20cab9e5febf96fe243439b2801fd3511bf6d672805bf02daa07f5a67979928bfd32070a0500000001aa"
+ ]
+ },
+ "initial_state": {
+ "version": 0,
+ "hash": "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
+ },
+ "mutations": [
+ {
+ "key_id": "00000001aa",
+ "operation": 0,
+ "action": "08fb80b3c19c33220d080110ffffffffffffffffff01",
+ "version": 2,
+ "index": [
+ "mute",
+ ],
+ "index_mac": "08412495ff8b26a94a13d615f53e9cbca9dd31f4542bdf5ea55ef80042917e83",
+ "value_mac": "4689be6b083a75bdc1c2968b815b21949e274a559e7bd3914b972c1a4ec728c3",
+ "patch_version": 3
+ },
+ {
+ "key_id": "00000001aa",
+ "operation": 0,
+ "action": "08fb80b3c19c3312020801",
+ "version": 2,
+ "index": [
+ "star",
+ "3EB0STARRED",
+ "1",
+ "0"
+ ],
+ "index_mac": "1ef008d9da5877bae8057544fc658a1eaaf1676472668d97e842c05a5faac51b",
+ "value_mac": "af3f1134ca706ae32be8ef00d1d702d696f8971b697780d14302780c3c66782f",
+ "patch_version": 3
+ },
+ {
+ "key_id": "00000002bb",
+ "operation": 0,
+ "action": "08fb80b3c19c33220908011080dd8ec39c33",
+ "version": 2,
+ "index": [
+ "mute",
+ ],
+ "index_mac": "100b84efff300a224def9982610a9e2e2e366e4c55c234187d6f38d8b94c05d5",
+ "value_mac": "40e99dcd61f8662fbc08b1eace0dc465d9e2af49f1f32068c674a5540fc0db1d",
+ "patch_version": 3
+ },
+ {
+ "key_id": "00000001aa",
+ "operation": 0,
+ "action": "08fb80b3c19c33aa0100",
+ "version": 6,
+ "index": [
+ "clearChat",
+ "\u003c\u0026\u003e",
+ "1"
+ ],
+ "index_mac": "063e2d71637fb68a87b23ea8a5c1e17c28f53e721fffd17e004943938f5caef9",
+ "value_mac": "68e69b90b67502d87d4c212a36afa260bb76b13fc3951524a75b04f0625c1943",
+ "patch_version": 3
+ },
+ {
+ "key_id": "00000001aa",
+ "operation": 0,
+ "action": "08e388b3c19c3322020800",
+ "version": 2,
+ "index": [
+ "mute",
+ ],
+ "index_mac": "08412495ff8b26a94a13d615f53e9cbca9dd31f4542bdf5ea55ef80042917e83",
+ "value_mac": "080faa6cab72b2f3db4e9e2e618ed9d2af4d80cb984e78e187694e3b3d4663a8",
+ "patch_version": 4
+ },
+ {
+ "key_id": "00000001aa",
+ "operation": 1,
+ "action": "08e388b3c19c3312020800",
+ "version": 2,
+ "index": [
+ "star",
+ "3EB0STARRED",
+ "1",
+ "0"
+ ],
+ "index_mac": "1ef008d9da5877bae8057544fc658a1eaaf1676472668d97e842c05a5faac51b",
+ "value_mac": "c95264c7586f0e232d3d893d607b0436363d71670b88fcf29fc14a1d6305c204",
+ "patch_version": 4
+ },
+ {
+ "key_id": "00000002bb",
+ "operation": 0,
+ "action": "08e388b3c19c3322020801",
+ "version": 2,
+ "index": [
+ "mute",
+ ],
+ "index_mac": "1c2d2e8fc7d2c7d745ce9ec11ac73273e2b4ff162437e0a1f11da22db637be29",
+ "value_mac": "3c3cd80085aa6dd8f48088a15d328ee7cb97994386812300eaef3c7baaf7460c",
+ "patch_version": 4
+ },
+ {
+ "key_id": "00000002bb",
+ "operation": 1,
+ "action": "08e388b3c19c33",
+ "version": 2,
+ "index": [
+ "mute",
+ ],
+ "index_mac": "1c2d2e8fc7d2c7d745ce9ec11ac73273e2b4ff162437e0a1f11da22db637be29",
+ "value_mac": "01c08c19a61cc7e99a1869bf4776b3dbc419f75f7692d591b2ccaf7a40a8fefc",
+ "patch_version": 4
+ },
+ {
+ "key_id": "00000001aa",
+ "operation": 1,
+ "action": "08e388b3c19c33",
+ "version": 2,
+ "index": [
+ "mute",
+ ],
+ "index_mac": "8fe8e2c57dc368d4f2338e1c015d74ad189dd9bf30f422ddeef33f2b33f39745",
+ "value_mac": "eb943bc0083a2e5ae50ab41662c273f57187ffb3a275de9714064306ec75c9b8",
+ "patch_version": 4
+ },
+ {
+ "key_id": "00000001aa",
+ "operation": 0,
+ "action": "08cb90b3c19c3322020800",
+ "version": 2,
+ "index": [
+ "mute",
+ ],
+ "index_mac": "23b77172517d7c38bf6b6cc6dd1ae2ac910efb80ee0d73ed1a3022aa444de865",
+ "value_mac": "d5e88882f2379b8b18ec4970ed2d314fdfceb0487ac8101ca8854d2d3569d517",
+ "patch_version": 5
+ },
+ {
+ "key_id": "00000001aa",
+ "operation": 0,
+ "action": "08cb90b3c19c3312020801",
+ "version": 2,
+ "index": [
+ "star",
+ "3EB0OTHER",
+ "0",
+ ],
+ "index_mac": "d357336821f0ecc149ae3b95c8d2d33913c67bb76254dcb41a363626b75aa951",
+ "value_mac": "f3122e04cc3790b8b2715cd189f8dba9026617ea4523084b80e047a3e0e39993",
+ "patch_version": 5
+ }
+ ],
+ "state": {
+ "version": 5,
+ "hash": "7337d274bc19dfe87b2ab85d5a73be0cda7bcbed99d1d54f918177cd12a2b4692307b1fc953bed200fb1922b978d65decc6ac8ea6f91e6cd8d53a8cba608705bec8f13d5825d5a0dc1f10af4c02c6beed961d08524fd0e66bc30f48b78a70c2ef17d70215a9dd7cf839e3127811dce060c8c526eed372815f645eea7a0086c9f"
+ },
+ "stored_state": {
+ "version": 5,
+ "hash": "7337d274bc19dfe87b2ab85d5a73be0cda7bcbed99d1d54f918177cd12a2b4692307b1fc953bed200fb1922b978d65decc6ac8ea6f91e6cd8d53a8cba608705bec8f13d5825d5a0dc1f10af4c02c6beed961d08524fd0e66bc30f48b78a70c2ef17d70215a9dd7cf839e3127811dce060c8c526eed372815f645eea7a0086c9f"
+ },
+ "lookups": [
+ {
+ "index_mac": "08412495ff8b26a94a13d615f53e9cbca9dd31f4542bdf5ea55ef80042917e83",
+ "value_mac": "080faa6cab72b2f3db4e9e2e618ed9d2af4d80cb984e78e187694e3b3d4663a8"
+ },
+ {
+ "index_mac": "1ef008d9da5877bae8057544fc658a1eaaf1676472668d97e842c05a5faac51b",
+ "value_mac": null
+ },
+ {
+ "index_mac": "100b84efff300a224def9982610a9e2e2e366e4c55c234187d6f38d8b94c05d5",
+ "value_mac": "40e99dcd61f8662fbc08b1eace0dc465d9e2af49f1f32068c674a5540fc0db1d"
+ },
+ {
+ "index_mac": "063e2d71637fb68a87b23ea8a5c1e17c28f53e721fffd17e004943938f5caef9",
+ "value_mac": "68e69b90b67502d87d4c212a36afa260bb76b13fc3951524a75b04f0625c1943"
+ },
+ {
+ "index_mac": "08412495ff8b26a94a13d615f53e9cbca9dd31f4542bdf5ea55ef80042917e83",
+ "value_mac": "080faa6cab72b2f3db4e9e2e618ed9d2af4d80cb984e78e187694e3b3d4663a8"
+ },
+ {
+ "index_mac": "1ef008d9da5877bae8057544fc658a1eaaf1676472668d97e842c05a5faac51b",
+ "value_mac": null
+ },
+ {
+ "index_mac": "1c2d2e8fc7d2c7d745ce9ec11ac73273e2b4ff162437e0a1f11da22db637be29",
+ "value_mac": null
+ },
+ {
+ "index_mac": "1c2d2e8fc7d2c7d745ce9ec11ac73273e2b4ff162437e0a1f11da22db637be29",
+ "value_mac": null
+ },
+ {
+ "index_mac": "8fe8e2c57dc368d4f2338e1c015d74ad189dd9bf30f422ddeef33f2b33f39745",
+ "value_mac": null
+ },
+ {
+ "index_mac": "23b77172517d7c38bf6b6cc6dd1ae2ac910efb80ee0d73ed1a3022aa444de865",
+ "value_mac": "d5e88882f2379b8b18ec4970ed2d314fdfceb0487ac8101ca8854d2d3569d517"
+ },
+ {
+ "index_mac": "d357336821f0ecc149ae3b95c8d2d33913c67bb76254dcb41a363626b75aa951",
+ "value_mac": "f3122e04cc3790b8b2715cd189f8dba9026617ea4523084b80e047a3e0e39993"
+ }
+ ]
+ },
+ {
+ "list": {
+ "snapshot": null,
+ "patches": [
+ "0a02080612a601080112a1010a220a2023b77172517d7c38bf6b6cc6dd1ae2ac910efb80ee0d73ed1a3022aa444de86512720a70a0a1a2a3a4a5a6a7a8a9aaabacadaeaf9775c9ec733ac1c40d37c0802faf5217b1924df7d52e514bfd4f73d91d99686f4926dea46c4d1d718cfaf33720ce0bcda76576edc8c2ae1040929bb5fe88773b8be3420bb9918b0c0b40f793c82cd70038d0721e4d6f4f659045677604cb57bd1a070a0500000001aa12c801080012c3010a220a20063e2d71637fb68a87b23ea8a5c1e17c28f53e721fffd17e004943938f5caef91293010a9001b0b1b2b3b4b5b6b7b8b9babbbcbdbebfbc0027ea22c218dbcc11dd8a624711e274eb5b786410355d2334ebbea6a062d62cb8ef0caf683dcbdb8f7c50a64d5d73d24293f46b754969967b6258ad2d469cb71a1be2374b515a23b43cff28b00dad0f329ed11dabc46e7dd64806db02a62297b9fb74aada976d2efd36dbb7df08b60b343dc3700cee7e0c32c31a851e17fe1a070a0500000001aa2220eef0f91e5b9831f681a08dae6c32a688980006b76a13860754864022cc8c48982a20cd15c3c6a03a1c15ae7eabe290c561c71dfaeababba8036605e77bef87b6c92d32070a0500000001aa"
+ ]
+ },
+ "initial_state": {
+ "version": 5,
+ "hash": "7337d274bc19dfe87b2ab85d5a73be0cda7bcbed99d1d54f918177cd12a2b4692307b1fc953bed200fb1922b978d65decc6ac8ea6f91e6cd8d53a8cba608705bec8f13d5825d5a0dc1f10af4c02c6beed961d08524fd0e66bc30f48b78a70c2ef17d70215a9dd7cf839e3127811dce060c8c526eed372815f645eea7a0086c9f"
+ },
+ "mutations": [
+ {
+ "key_id": "00000001aa",
+ "operation": 1,
+ "action": "08b398b3c19c33",
+ "version": 2,
+ "index": [
+ "mute",
+ ],
+ "index_mac": "23b77172517d7c38bf6b6cc6dd1ae2ac910efb80ee0d73ed1a3022aa444de865",
+ "value_mac": "8be3420bb9918b0c0b40f793c82cd70038d0721e4d6f4f659045677604cb57bd",
+ "patch_version": 6
+ },
+ {
+ "key_id": "00000001aa",
+ "operation": 0,
+ "action": "08b398b3c19c33aa01080a060883f09dc706",
+ "version": 6,
+ "index": [
+ "clearChat",
+ "\u003c\u0026\u003e",
+ "1"
+ ],
+ "index_mac": "063e2d71637fb68a87b23ea8a5c1e17c28f53e721fffd17e004943938f5caef9",
+ "value_mac": "97b9fb74aada976d2efd36dbb7df08b60b343dc3700cee7e0c32c31a851e17fe",
+ "patch_version": 6
+ }
+ ],
+ "state": {
+ "version": 6,
+ "hash": "133dfecc59ea5331ac4a890590d0ac13460bebf0c4bb7f32bdd8a8a7c876b218724eb347cd6a0859eaaae4dd90286bba2d3c1271a3fd2f18fe353670e16375cedcda593dbcbb72d1336bee121fae231092c92c8b676f6d645e3f0b1ca0efc5e27f9e5ff6b2673944401eb10550ca505304d34563e8c320015498037d2d121a45"
+ },
+ "stored_state": {
+ "version": 6,
+ "hash": "133dfecc59ea5331ac4a890590d0ac13460bebf0c4bb7f32bdd8a8a7c876b218724eb347cd6a0859eaaae4dd90286bba2d3c1271a3fd2f18fe353670e16375cedcda593dbcbb72d1336bee121fae231092c92c8b676f6d645e3f0b1ca0efc5e27f9e5ff6b2673944401eb10550ca505304d34563e8c320015498037d2d121a45"
+ },
+ "lookups": [
+ {
+ "index_mac": "23b77172517d7c38bf6b6cc6dd1ae2ac910efb80ee0d73ed1a3022aa444de865",
+ "value_mac": null
+ },
+ {
+ "index_mac": "063e2d71637fb68a87b23ea8a5c1e17c28f53e721fffd17e004943938f5caef9",
+ "value_mac": "97b9fb74aada976d2efd36dbb7df08b60b343dc3700cee7e0c32c31a851e17fe"
+ }
+ ]
+ }
+ ]
+ },
+ "decode_errors": [
+ {
+ "description": "snapshot MAC mismatch",
+ "list": {
+ "snapshot": "0a02080312b3010a220a2008412495ff8b26a94a13d615f53e9cbca9dd31f4542bdf5ea55ef80042917e831283010a8001101112131415161718191a1b1c1d1e1f05504d3645e870661a34c45988b7f92cbd1302c2c075e12a7661d3ebeba11f3fec9680761dae6a8cc128ed76815c701ec1627d7f356649cf59a4da9011175016c0cb3db6d0e0f3553e774200fcbb9f9e4689be6b083a75bdc1c2968b815b21949e274a559e7bd3914b972c1a4ec728c31a070a0500000001aa12b3010a220a201ef008d9da5877bae8057544fc658a1eaaf1676472668d97e842c05a5faac51b1283010a8001202122232425262728292a2b2c2d2e2f0f0ee49645a560a9c380b3024688f70a1bbd60111692480d6786029b1f6874fb7b9aded54600cdfff8ee6398354d634f10bd5e4ce61cd931c9a6d9c797aeed2a1d0a47dba0ad4e0c54a4db4f012ab569af3f1134ca706ae32be8ef00d1d702d696f8971b697780d14302780c3c66782f1a070a0500000001aa12a1010a220a20100b84efff300a224def9982610a9e2e2e366e4c55c234187d6f38d8b94c05d512720a70303132333435363738393a3b3c3d3e3f80c5dde4a082c58a4dfb05f4567a305e2b681d5b99782f65a17d14086b62215c640e063087aea7c8ca2f8ef429610ba0498ef244195cd04d97cc00825142210d40e99dcd61f8662fbc08b1eace0dc465d9e2af49f1f32068c674a5540fc0db1d1a070a0500000002bb12c3010a220a20063e2d71637fb68a87b23ea8a5c1e17c28f53e721fffd17e004943938f5caef91293010a9001404142434445464748494a4b4c4d4e4f3da58431dccbaa20e44d91235b9637374c91210ca4b8cdda073a3c268cda6a092b575085f4c08dabe210d424edac788b77c521ee77430718c4f23cbb4b9fbc2a977e2646e5fa5c6245af0f755d0af186f3d1e875061023adde513f4f8557c84a68e69b90b67502d87d4c212a36afa260bb76b13fc3951524a75b04f0625c19431a070a0500000001aa1a207f31191fd15d4f29d86f64f60d3e45b32734c50697c927ed6efccf7d98739d8722070a0500000001aa",
+ "patches": [
+ "0a02080412a601080012a1010a220a2008412495ff8b26a94a13d615f53e9cbca9dd31f4542bdf5ea55ef80042917e8312720a70505152535455565758595a5b5c5d5e5fa8246af9944f563478f52853de00032df51eeae6411aca3d7dac9976b8c2051283bc7934264ac9d44b7b96d24592166442b8d8fb93d185f198d2f95f74de19c1080faa6cab72b2f3db4e9e2e618ed9d2af4d80cb984e78e187694e3b3d4663a81a070a0500000001aa12b801080112b3010a220a201ef008d9da5877bae8057544fc658a1eaaf1676472668d97e842c05a5faac51b1283010a8001606162636465666768696a6b6c6d6e6fae2fd376d8fba25a9493a4587830c52fe576f54314755e1e10eeadb3fa2d409a0cac432c3255a9031ecd742e7eff0aac1191eb33193744fdf3d8ac10ce210fdbed5bc42a0c79fa7e7fd8ead6412c38b2c95264c7586f0e232d3d893d607b0436363d71670b88fcf29fc14a1d6305c2041a070a0500000001aa12a601080012a1010a220a201c2d2e8fc7d2c7d745ce9ec11ac73273e2b4ff162437e0a1f11da22db637be2912720a70707172737475767778797a7b7c7d7e7fd31b8a255b2fd4cd3c2c2c8ee0d57c17f371f2783d68706bb0e2131f58c1c5d488c1ab5221752984b291e0c7f86b6a823c835b9664cde17cf493d9f568aaee583c3cd80085aa6dd8f48088a15d328ee7cb97994386812300eaef3c7baaf7460c1a070a0500000002bb12a601080112a1010a220a201c2d2e8fc7d2c7d745ce9ec11ac73273e2b4ff162437e0a1f11da22db637be2912720a70808182838485868788898a8b8c8d8e8fc9f3a507d96104804e46ca63bc3f128139411a0289d6a306f3474eb5fe83ce726bffe37e5c9a570c050843b7da1dddd097b3becfd0598c509770750bedc1807201c08c19a61cc7e99a1869bf4776b3dbc419f75f7692d591b2ccaf7a40a8fefc1a070a0500000002bb12960108011291010a220a208fe8e2c57dc368d4f2338e1c015d74ad189dd9bf30f422ddeef33f2b33f3974512620a60909192939495969798999a9b9c9d9e9f012e9b4c7468fc2844a943d9a9466adc9a76cfebed9c6bd8f1f9ea8224784ae7c82ed20ba55895e4067c66e4950d34f0eb943bc0083a2e5ae50ab41662c273f57187ffb3a275de9714064306ec75c9b81a070a0500000001aa2220ac110c81fda4063e81eff76d6030335113e40b593b286df6db02012f87deece92a2074a8961aa073f421b76cbeba6745a80fdf64aec2c8382c636e0842bb9f33214b32070a0500000002bb",
+ "0a02080512a601080012a1010a220a2023b77172517d7c38bf6b6cc6dd1ae2ac910efb80ee0d73ed1a3022aa444de86512720a7016a0034fde6f136b8ef2ab8eab0164d32d4f438999d130bacba6f79722a64d94c9573eaf5921e4c50ec2458565c7fdadd93579a91b72bc2c81d87bbffffe66ee75222d37e5e778a044c82852b64db4e0d5e88882f2379b8b18ec4970ed2d314fdfceb0487ac8101ca8854d2d3569d5171a070a0500000001aa12d801080012d3010a220a20d357336821f0ecc149ae3b95c8d2d33913c67bb76254dcb41a363626b75aa95112a3010aa001b699b5c04097b485cc46e0b039a8da306928346c1959eb7a294e428537ed4b0c9609dd5543829d857868b73416c71673c3bb77410302d51c8ba7dc3760fe9c5be6549d563ce10245f78eacb52be22d116910840d30cb75e52daa3df5bfc9e3cb676b0ca95916e708463e91de0677bd6b09ddfe40a7888f0241f866584debb61ff3122e04cc3790b8b2715cd189f8dba9026617ea4523084b80e047a3e0e399931a070a0500000001aa2220e1ee797282b7acc89217ab2e8ddac3f25a4d064494299c2b444e9c509b410b0e2a20cab9e5febf96fe243439b2801fd3511bf6d672805bf02daa07f5a67979928bfd32070a0500000001aa"
+ ]
+ },
+ "initial_state": {
+ "version": 0,
+ "hash": "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
+ },
+ "error": "failed to verify snapshot: failed to verify patch v3: mismatching LTHash",
+ "key_not_found": false,
+ "missing_keys": []
+ },
+ {
+ "description": "content MAC mismatch",
+ "list": {
+ "snapshot": "0a02080312b3010a220a2008412495ff8b26a94a13d615f53e9cbca9dd31f4542bdf5ea55ef80042917e831283010a8001101112131415161718191a1b1c1d1e1f05504d3645e870661a34c45988b7f92cbd1302c2c075e12a7661d3ebeba11f3fec9680761dae6a8cc128ed76815c701ec1627d7f356649cf59a4da9011175016c0cb3db6d0e0f3553e774200fcbb9f9e4689be6b083a75bdc1c2968b815b21949e274a559e7bd3914b972c1a4ec728c31a070a0500000001aa12b3010a220a201ef008d9da5877bae8057544fc658a1eaaf1676472668d97e842c05a5faac51b1283010a8001202122232425262728292a2b2c2d2e2f0f0ee49644a560a9c380b3024688f70a1bbd60111692480d6786029b1f6874fb7b9aded54600cdfff8ee6398354d634f10bd5e4ce61cd931c9a6d9c797aeed2a1d0a47dba0ad4e0c54a4db4f012ab569af3f1134ca706ae32be8ef00d1d702d696f8971b697780d14302780c3c66782f1a070a0500000001aa12a1010a220a20100b84efff300a224def9982610a9e2e2e366e4c55c234187d6f38d8b94c05d512720a70303132333435363738393a3b3c3d3e3f80c5dde4a082c58a4dfb05f4567a305e2b681d5b99782f65a17d14086b62215c640e063087aea7c8ca2f8ef429610ba0498ef244195cd04d97cc00825142210d40e99dcd61f8662fbc08b1eace0dc465d9e2af49f1f32068c674a5540fc0db1d1a070a0500000002bb12c3010a220a20063e2d71637fb68a87b23ea8a5c1e17c28f53e721fffd17e004943938f5caef91293010a9001404142434445464748494a4b4c4d4e4f3da58431dccbaa20e44d91235b9637374c91210ca4b8cdda073a3c268cda6a092b575085f4c08dabe210d424edac788b77c521ee77430718c4f23cbb4b9fbc2a977e2646e5fa5c6245af0f755d0af186f3d1e875061023adde513f4f8557c84a68e69b90b67502d87d4c212a36afa260bb76b13fc3951524a75b04f0625c19431a070a0500000001aa1a207e31191fd15d4f29d86f64f60d3e45b32734c50697c927ed6efccf7d98739d8722070a0500000001aa",
+ "patches": [
+ "0a02080412a601080012a1010a220a2008412495ff8b26a94a13d615f53e9cbca9dd31f4542bdf5ea55ef80042917e8312720a70505152535455565758595a5b5c5d5e5fa8246af9944f563478f52853de00032df51eeae6411aca3d7dac9976b8c2051283bc7934264ac9d44b7b96d24592166442b8d8fb93d185f198d2f95f74de19c1080faa6cab72b2f3db4e9e2e618ed9d2af4d80cb984e78e187694e3b3d4663a81a070a0500000001aa12b801080112b3010a220a201ef008d9da5877bae8057544fc658a1eaaf1676472668d97e842c05a5faac51b1283010a8001606162636465666768696a6b6c6d6e6fae2fd376d8fba25a9493a4587830c52fe576f54314755e1e10eeadb3fa2d409a0cac432c3255a9031ecd742e7eff0aac1191eb33193744fdf3d8ac10ce210fdbed5bc42a0c79fa7e7fd8ead6412c38b2c95264c7586f0e232d3d893d607b0436363d71670b88fcf29fc14a1d6305c2041a070a0500000001aa12a601080012a1010a220a201c2d2e8fc7d2c7d745ce9ec11ac73273e2b4ff162437e0a1f11da22db637be2912720a70707172737475767778797a7b7c7d7e7fd31b8a255b2fd4cd3c2c2c8ee0d57c17f371f2783d68706bb0e2131f58c1c5d488c1ab5221752984b291e0c7f86b6a823c835b9664cde17cf493d9f568aaee583c3cd80085aa6dd8f48088a15d328ee7cb97994386812300eaef3c7baaf7460c1a070a0500000002bb12a601080112a1010a220a201c2d2e8fc7d2c7d745ce9ec11ac73273e2b4ff162437e0a1f11da22db637be2912720a70808182838485868788898a8b8c8d8e8fc9f3a507d96104804e46ca63bc3f128139411a0289d6a306f3474eb5fe83ce726bffe37e5c9a570c050843b7da1dddd097b3becfd0598c509770750bedc1807201c08c19a61cc7e99a1869bf4776b3dbc419f75f7692d591b2ccaf7a40a8fefc1a070a0500000002bb12960108011291010a220a208fe8e2c57dc368d4f2338e1c015d74ad189dd9bf30f422ddeef33f2b33f3974512620a60909192939495969798999a9b9c9d9e9f012e9b4c7468fc2844a943d9a9466adc9a76cfebed9c6bd8f1f9ea8224784ae7c82ed20ba55895e4067c66e4950d34f0eb943bc0083a2e5ae50ab41662c273f57187ffb3a275de9714064306ec75c9b81a070a0500000001aa2220ac110c81fda4063e81eff76d6030335113e40b593b286df6db02012f87deece92a2074a8961aa073f421b76cbeba6745a80fdf64aec2c8382c636e0842bb9f33214b32070a0500000002bb",
+ "0a02080512a601080012a1010a220a2023b77172517d7c38bf6b6cc6dd1ae2ac910efb80ee0d73ed1a3022aa444de86512720a7016a0034fde6f136b8ef2ab8eab0164d32d4f438999d130bacba6f79722a64d94c9573eaf5921e4c50ec2458565c7fdadd93579a91b72bc2c81d87bbffffe66ee75222d37e5e778a044c82852b64db4e0d5e88882f2379b8b18ec4970ed2d314fdfceb0487ac8101ca8854d2d3569d5171a070a0500000001aa12d801080012d3010a220a20d357336821f0ecc149ae3b95c8d2d33913c67bb76254dcb41a363626b75aa95112a3010aa001b699b5c04097b485cc46e0b039a8da306928346c1959eb7a294e428537ed4b0c9609dd5543829d857868b73416c71673c3bb77410302d51c8ba7dc3760fe9c5be6549d563ce10245f78eacb52be22d116910840d30cb75e52daa3df5bfc9e3cb676b0ca95916e708463e91de0677bd6b09ddfe40a7888f0241f866584debb61ff3122e04cc3790b8b2715cd189f8dba9026617ea4523084b80e047a3e0e399931a070a0500000001aa2220e1ee797282b7acc89217ab2e8ddac3f25a4d064494299c2b444e9c509b410b0e2a20cab9e5febf96fe243439b2801fd3511bf6d672805bf02daa07f5a67979928bfd32070a0500000001aa"
+ ]
+ },
+ "initial_state": {
+ "version": 0,
+ "hash": "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
+ },
+ "error": "failed to decode snapshot of v3: failed to verify mutation #2: mismatching content MAC",
+ "key_not_found": false,
+ "missing_keys": []
+ },
+ {
+ "description": "index MAC mismatch",
+ "list": {
+ "snapshot": "0a02080312b3010a220a2009412495ff8b26a94a13d615f53e9cbca9dd31f4542bdf5ea55ef80042917e831283010a8001101112131415161718191a1b1c1d1e1f05504d3645e870661a34c45988b7f92cbd1302c2c075e12a7661d3ebeba11f3fec9680761dae6a8cc128ed76815c701ec1627d7f356649cf59a4da9011175016c0cb3db6d0e0f3553e774200fcbb9f9e4689be6b083a75bdc1c2968b815b21949e274a559e7bd3914b972c1a4ec728c31a070a0500000001aa12b3010a220a201ef008d9da5877bae8057544fc658a1eaaf1676472668d97e842c05a5faac51b1283010a8001202122232425262728292a2b2c2d2e2f0f0ee49645a560a9c380b3024688f70a1bbd60111692480d6786029b1f6874fb7b9aded54600cdfff8ee6398354d634f10bd5e4ce61cd931c9a6d9c797aeed2a1d0a47dba0ad4e0c54a4db4f012ab569af3f1134ca706ae32be8ef00d1d702d696f8971b697780d14302780c3c66782f1a070a0500000001aa12a1010a220a20100b84efff300a224def9982610a9e2e2e366e4c55c234187d6f38d8b94c05d512720a70303132333435363738393a3b3c3d3e3f80c5dde4a082c58a4dfb05f4567a305e2b681d5b99782f65a17d14086b62215c640e063087aea7c8ca2f8ef429610ba0498ef244195cd04d97cc00825142210d40e99dcd61f8662fbc08b1eace0dc465d9e2af49f1f32068c674a5540fc0db1d1a070a0500000002bb12c3010a220a20063e2d71637fb68a87b23ea8a5c1e17c28f53e721fffd17e004943938f5caef91293010a9001404142434445464748494a4b4c4d4e4f3da58431dccbaa20e44d91235b9637374c91210ca4b8cdda073a3c268cda6a092b575085f4c08dabe210d424edac788b77c521ee77430718c4f23cbb4b9fbc2a977e2646e5fa5c6245af0f755d0af186f3d1e875061023adde513f4f8557c84a68e69b90b67502d87d4c212a36afa260bb76b13fc3951524a75b04f0625c19431a070a0500000001aa1a207e31191fd15d4f29d86f64f60d3e45b32734c50697c927ed6efccf7d98739d8722070a0500000001aa",
+ "patches": [
+ "0a02080412a601080012a1010a220a2008412495ff8b26a94a13d615f53e9cbca9dd31f4542bdf5ea55ef80042917e8312720a70505152535455565758595a5b5c5d5e5fa8246af9944f563478f52853de00032df51eeae6411aca3d7dac9976b8c2051283bc7934264ac9d44b7b96d24592166442b8d8fb93d185f198d2f95f74de19c1080faa6cab72b2f3db4e9e2e618ed9d2af4d80cb984e78e187694e3b3d4663a81a070a0500000001aa12b801080112b3010a220a201ef008d9da5877bae8057544fc658a1eaaf1676472668d97e842c05a5faac51b1283010a8001606162636465666768696a6b6c6d6e6fae2fd376d8fba25a9493a4587830c52fe576f54314755e1e10eeadb3fa2d409a0cac432c3255a9031ecd742e7eff0aac1191eb33193744fdf3d8ac10ce210fdbed5bc42a0c79fa7e7fd8ead6412c38b2c95264c7586f0e232d3d893d607b0436363d71670b88fcf29fc14a1d6305c2041a070a0500000001aa12a601080012a1010a220a201c2d2e8fc7d2c7d745ce9ec11ac73273e2b4ff162437e0a1f11da22db637be2912720a70707172737475767778797a7b7c7d7e7fd31b8a255b2fd4cd3c2c2c8ee0d57c17f371f2783d68706bb0e2131f58c1c5d488c1ab5221752984b291e0c7f86b6a823c835b9664cde17cf493d9f568aaee583c3cd80085aa6dd8f48088a15d328ee7cb97994386812300eaef3c7baaf7460c1a070a0500000002bb12a601080112a1010a220a201c2d2e8fc7d2c7d745ce9ec11ac73273e2b4ff162437e0a1f11da22db637be2912720a70808182838485868788898a8b8c8d8e8fc9f3a507d96104804e46ca63bc3f128139411a0289d6a306f3474eb5fe83ce726bffe37e5c9a570c050843b7da1dddd097b3becfd0598c509770750bedc1807201c08c19a61cc7e99a1869bf4776b3dbc419f75f7692d591b2ccaf7a40a8fefc1a070a0500000002bb12960108011291010a220a208fe8e2c57dc368d4f2338e1c015d74ad189dd9bf30f422ddeef33f2b33f3974512620a60909192939495969798999a9b9c9d9e9f012e9b4c7468fc2844a943d9a9466adc9a76cfebed9c6bd8f1f9ea8224784ae7c82ed20ba55895e4067c66e4950d34f0eb943bc0083a2e5ae50ab41662c273f57187ffb3a275de9714064306ec75c9b81a070a0500000001aa2220ac110c81fda4063e81eff76d6030335113e40b593b286df6db02012f87deece92a2074a8961aa073f421b76cbeba6745a80fdf64aec2c8382c636e0842bb9f33214b32070a0500000002bb",
+ "0a02080512a601080012a1010a220a2023b77172517d7c38bf6b6cc6dd1ae2ac910efb80ee0d73ed1a3022aa444de86512720a7016a0034fde6f136b8ef2ab8eab0164d32d4f438999d130bacba6f79722a64d94c9573eaf5921e4c50ec2458565c7fdadd93579a91b72bc2c81d87bbffffe66ee75222d37e5e778a044c82852b64db4e0d5e88882f2379b8b18ec4970ed2d314fdfceb0487ac8101ca8854d2d3569d5171a070a0500000001aa12d801080012d3010a220a20d357336821f0ecc149ae3b95c8d2d33913c67bb76254dcb41a363626b75aa95112a3010aa001b699b5c04097b485cc46e0b039a8da306928346c1959eb7a294e428537ed4b0c9609dd5543829d857868b73416c71673c3bb77410302d51c8ba7dc3760fe9c5be6549d563ce10245f78eacb52be22d116910840d30cb75e52daa3df5bfc9e3cb676b0ca95916e708463e91de0677bd6b09ddfe40a7888f0241f866584debb61ff3122e04cc3790b8b2715cd189f8dba9026617ea4523084b80e047a3e0e399931a070a0500000001aa2220e1ee797282b7acc89217ab2e8ddac3f25a4d064494299c2b444e9c509b410b0e2a20cab9e5febf96fe243439b2801fd3511bf6d672805bf02daa07f5a67979928bfd32070a0500000001aa"
+ ]
+ },
+ "initial_state": {
+ "version": 0,
+ "hash": "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
+ },
+ "error": "failed to decode snapshot of v3: failed to verify mutation #1: mismatching index MAC",
+ "key_not_found": false,
+ "missing_keys": []
+ },
+ {
+ "description": "patch MAC mismatch",
+ "list": {
+ "snapshot": "0a02080312b3010a220a2008412495ff8b26a94a13d615f53e9cbca9dd31f4542bdf5ea55ef80042917e831283010a8001101112131415161718191a1b1c1d1e1f05504d3645e870661a34c45988b7f92cbd1302c2c075e12a7661d3ebeba11f3fec9680761dae6a8cc128ed76815c701ec1627d7f356649cf59a4da9011175016c0cb3db6d0e0f3553e774200fcbb9f9e4689be6b083a75bdc1c2968b815b21949e274a559e7bd3914b972c1a4ec728c31a070a0500000001aa12b3010a220a201ef008d9da5877bae8057544fc658a1eaaf1676472668d97e842c05a5faac51b1283010a8001202122232425262728292a2b2c2d2e2f0f0ee49645a560a9c380b3024688f70a1bbd60111692480d6786029b1f6874fb7b9aded54600cdfff8ee6398354d634f10bd5e4ce61cd931c9a6d9c797aeed2a1d0a47dba0ad4e0c54a4db4f012ab569af3f1134ca706ae32be8ef00d1d702d696f8971b697780d14302780c3c66782f1a070a0500000001aa12a1010a220a20100b84efff300a224def9982610a9e2e2e366e4c55c234187d6f38d8b94c05d512720a70303132333435363738393a3b3c3d3e3f80c5dde4a082c58a4dfb05f4567a305e2b681d5b99782f65a17d14086b62215c640e063087aea7c8ca2f8ef429610ba0498ef244195cd04d97cc00825142210d40e99dcd61f8662fbc08b1eace0dc465d9e2af49f1f32068c674a5540fc0db1d1a070a0500000002bb12c3010a220a20063e2d71637fb68a87b23ea8a5c1e17c28f53e721fffd17e004943938f5caef91293010a9001404142434445464748494a4b4c4d4e4f3da58431dccbaa20e44d91235b9637374c91210ca4b8cdda073a3c268cda6a092b575085f4c08dabe210d424edac788b77c521ee77430718c4f23cbb4b9fbc2a977e2646e5fa5c6245af0f755d0af186f3d1e875061023adde513f4f8557c84a68e69b90b67502d87d4c212a36afa260bb76b13fc3951524a75b04f0625c19431a070a0500000001aa1a207e31191fd15d4f29d86f64f60d3e45b32734c50697c927ed6efccf7d98739d8722070a0500000001aa",
+ "patches": [
+ "0a02080412a601080012a1010a220a2008412495ff8b26a94a13d615f53e9cbca9dd31f4542bdf5ea55ef80042917e8312720a70505152535455565758595a5b5c5d5e5fa8246af9944f563478f52853de00032df51eeae6411aca3d7dac9976b8c2051283bc7934264ac9d44b7b96d24592166442b8d8fb93d185f198d2f95f74de19c1080faa6cab72b2f3db4e9e2e618ed9d2af4d80cb984e78e187694e3b3d4663a81a070a0500000001aa12b801080112b3010a220a201ef008d9da5877bae8057544fc658a1eaaf1676472668d97e842c05a5faac51b1283010a8001606162636465666768696a6b6c6d6e6fae2fd376d8fba25a9493a4587830c52fe576f54314755e1e10eeadb3fa2d409a0cac432c3255a9031ecd742e7eff0aac1191eb33193744fdf3d8ac10ce210fdbed5bc42a0c79fa7e7fd8ead6412c38b2c95264c7586f0e232d3d893d607b0436363d71670b88fcf29fc14a1d6305c2041a070a0500000001aa12a601080012a1010a220a201c2d2e8fc7d2c7d745ce9ec11ac73273e2b4ff162437e0a1f11da22db637be2912720a70707172737475767778797a7b7c7d7e7fd31b8a255b2fd4cd3c2c2c8ee0d57c17f371f2783d68706bb0e2131f58c1c5d488c1ab5221752984b291e0c7f86b6a823c835b9664cde17cf493d9f568aaee583c3cd80085aa6dd8f48088a15d328ee7cb97994386812300eaef3c7baaf7460c1a070a0500000002bb12a601080112a1010a220a201c2d2e8fc7d2c7d745ce9ec11ac73273e2b4ff162437e0a1f11da22db637be2912720a70808182838485868788898a8b8c8d8e8fc9f3a507d96104804e46ca63bc3f128139411a0289d6a306f3474eb5fe83ce726bffe37e5c9a570c050843b7da1dddd097b3becfd0598c509770750bedc1807201c08c19a61cc7e99a1869bf4776b3dbc419f75f7692d591b2ccaf7a40a8fefc1a070a0500000002bb12960108011291010a220a208fe8e2c57dc368d4f2338e1c015d74ad189dd9bf30f422ddeef33f2b33f3974512620a60909192939495969798999a9b9c9d9e9f012e9b4c7468fc2844a943d9a9466adc9a76cfebed9c6bd8f1f9ea8224784ae7c82ed20ba55895e4067c66e4950d34f0eb943bc0083a2e5ae50ab41662c273f57187ffb3a275de9714064306ec75c9b81a070a0500000001aa2220ac110c81fda4063e81eff76d6030335113e40b593b286df6db02012f87deece92a2075a8961aa073f421b76cbeba6745a80fdf64aec2c8382c636e0842bb9f33214b32070a0500000002bb",
+ "0a02080512a601080012a1010a220a2023b77172517d7c38bf6b6cc6dd1ae2ac910efb80ee0d73ed1a3022aa444de86512720a7016a0034fde6f136b8ef2ab8eab0164d32d4f438999d130bacba6f79722a64d94c9573eaf5921e4c50ec2458565c7fdadd93579a91b72bc2c81d87bbffffe66ee75222d37e5e778a044c82852b64db4e0d5e88882f2379b8b18ec4970ed2d314fdfceb0487ac8101ca8854d2d3569d5171a070a0500000001aa12d801080012d3010a220a20d357336821f0ecc149ae3b95c8d2d33913c67bb76254dcb41a363626b75aa95112a3010aa001b699b5c04097b485cc46e0b039a8da306928346c1959eb7a294e428537ed4b0c9609dd5543829d857868b73416c71673c3bb77410302d51c8ba7dc3760fe9c5be6549d563ce10245f78eacb52be22d116910840d30cb75e52daa3df5bfc9e3cb676b0ca95916e708463e91de0677bd6b09ddfe40a7888f0241f866584debb61ff3122e04cc3790b8b2715cd189f8dba9026617ea4523084b80e047a3e0e399931a070a0500000001aa2220e1ee797282b7acc89217ab2e8ddac3f25a4d064494299c2b444e9c509b410b0e2a20cab9e5febf96fe243439b2801fd3511bf6d672805bf02daa07f5a67979928bfd32070a0500000001aa"
+ ]
+ },
+ "initial_state": {
+ "version": 0,
+ "hash": "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
+ },
+ "error": "failed to verify patch v4: mismatching patch MAC",
+ "key_not_found": false,
+ "missing_keys": []
+ },
+ {
+ "description": "patch LT hash mismatch",
+ "list": {
+ "snapshot": "0a02080312b3010a220a2008412495ff8b26a94a13d615f53e9cbca9dd31f4542bdf5ea55ef80042917e831283010a8001101112131415161718191a1b1c1d1e1f05504d3645e870661a34c45988b7f92cbd1302c2c075e12a7661d3ebeba11f3fec9680761dae6a8cc128ed76815c701ec1627d7f356649cf59a4da9011175016c0cb3db6d0e0f3553e774200fcbb9f9e4689be6b083a75bdc1c2968b815b21949e274a559e7bd3914b972c1a4ec728c31a070a0500000001aa12b3010a220a201ef008d9da5877bae8057544fc658a1eaaf1676472668d97e842c05a5faac51b1283010a8001202122232425262728292a2b2c2d2e2f0f0ee49645a560a9c380b3024688f70a1bbd60111692480d6786029b1f6874fb7b9aded54600cdfff8ee6398354d634f10bd5e4ce61cd931c9a6d9c797aeed2a1d0a47dba0ad4e0c54a4db4f012ab569af3f1134ca706ae32be8ef00d1d702d696f8971b697780d14302780c3c66782f1a070a0500000001aa12a1010a220a20100b84efff300a224def9982610a9e2e2e366e4c55c234187d6f38d8b94c05d512720a70303132333435363738393a3b3c3d3e3f80c5dde4a082c58a4dfb05f4567a305e2b681d5b99782f65a17d14086b62215c640e063087aea7c8ca2f8ef429610ba0498ef244195cd04d97cc00825142210d40e99dcd61f8662fbc08b1eace0dc465d9e2af49f1f32068c674a5540fc0db1d1a070a0500000002bb12c3010a220a20063e2d71637fb68a87b23ea8a5c1e17c28f53e721fffd17e004943938f5caef91293010a9001404142434445464748494a4b4c4d4e4f3da58431dccbaa20e44d91235b9637374c91210ca4b8cdda073a3c268cda6a092b575085f4c08dabe210d424edac788b77c521ee77430718c4f23cbb4b9fbc2a977e2646e5fa5c6245af0f755d0af186f3d1e875061023adde513f4f8557c84a68e69b90b67502d87d4c212a36afa260bb76b13fc3951524a75b04f0625c19431a070a0500000001aa1a207e31191fd15d4f29d86f64f60d3e45b32734c50697c927ed6efccf7d98739d8722070a0500000001aa",
+ "patches": [
+ "0a02080412a601080012a1010a220a2008412495ff8b26a94a13d615f53e9cbca9dd31f4542bdf5ea55ef80042917e8312720a70505152535455565758595a5b5c5d5e5fa8246af9944f563478f52853de00032df51eeae6411aca3d7dac9976b8c2051283bc7934264ac9d44b7b96d24592166442b8d8fb93d185f198d2f95f74de19c1080faa6cab72b2f3db4e9e2e618ed9d2af4d80cb984e78e187694e3b3d4663a81a070a0500000001aa12b801080112b3010a220a201ef008d9da5877bae8057544fc658a1eaaf1676472668d97e842c05a5faac51b1283010a8001606162636465666768696a6b6c6d6e6fae2fd376d8fba25a9493a4587830c52fe576f54314755e1e10eeadb3fa2d409a0cac432c3255a9031ecd742e7eff0aac1191eb33193744fdf3d8ac10ce210fdbed5bc42a0c79fa7e7fd8ead6412c38b2c95264c7586f0e232d3d893d607b0436363d71670b88fcf29fc14a1d6305c2041a070a0500000001aa12a601080012a1010a220a201c2d2e8fc7d2c7d745ce9ec11ac73273e2b4ff162437e0a1f11da22db637be2912720a70707172737475767778797a7b7c7d7e7fd31b8a255b2fd4cd3c2c2c8ee0d57c17f371f2783d68706bb0e2131f58c1c5d488c1ab5221752984b291e0c7f86b6a823c835b9664cde17cf493d9f568aaee583c3cd80085aa6dd8f48088a15d328ee7cb97994386812300eaef3c7baaf7460c1a070a0500000002bb12a601080112a1010a220a201c2d2e8fc7d2c7d745ce9ec11ac73273e2b4ff162437e0a1f11da22db637be2912720a70808182838485868788898a8b8c8d8e8fc9f3a507d96104804e46ca63bc3f128139411a0289d6a306f3474eb5fe83ce726bffe37e5c9a570c050843b7da1dddd097b3becfd0598c509770750bedc1807201c08c19a61cc7e99a1869bf4776b3dbc419f75f7692d591b2ccaf7a40a8fefc1a070a0500000002bb12960108011291010a220a208fe8e2c57dc368d4f2338e1c015d74ad189dd9bf30f422ddeef33f2b33f3974512620a60909192939495969798999a9b9c9d9e9f012e9b4c7468fc2844a943d9a9466adc9a76cfebed9c6bd8f1f9ea8224784ae7c82ed20ba55895e4067c66e4950d34f0eb943bc0083a2e5ae50ab41662c273f57187ffb3a275de9714064306ec75c9b81a070a0500000001aa2220ac110c81fda4063e81eff76d6030335113e40b593b286df6db02012f87deece92a2074a8961aa073f421b76cbeba6745a80fdf64aec2c8382c636e0842bb9f33214b32070a0500000002bb",
+ "0a02080512a601080012a1010a220a2023b77172517d7c38bf6b6cc6dd1ae2ac910efb80ee0d73ed1a3022aa444de86512720a7016a0034fde6f136b8ef2ab8eab0164d32d4f438999d130bacba6f79722a64d94c9573eaf5921e4c50ec2458565c7fdadd93579a91b72bc2c81d87bbffffe66ee75222d37e5e778a044c82852b64db4e0d5e88882f2379b8b18ec4970ed2d314fdfceb0487ac8101ca8854d2d3569d5171a070a0500000001aa12d801080012d3010a220a20d357336821f0ecc149ae3b95c8d2d33913c67bb76254dcb41a363626b75aa95112a3010aa001b699b5c04097b485cc46e0b039a8da306928346c1959eb7a294e428537ed4b0c9609dd5543829d857868b73416c71673c3bb77410302d51c8ba7dc3760fe9c5be6549d563ce10245f78eacb52be22d116910840d30cb75e52daa3df5bfc9e3cb676b0ca95916e708463e91de0677bd6b09ddfe40a7888f0241f866584debb61ff3122e04cc3790b8b2715cd189f8dba9026617ea4523084b80e047a3e0e399931a070a0500000001aa2220e0ee797282b7acc89217ab2e8ddac3f25a4d064494299c2b444e9c509b410b0e2a20cab9e5febf96fe243439b2801fd3511bf6d672805bf02daa07f5a67979928bfd32070a0500000001aa"
+ ]
+ },
+ "initial_state": {
+ "version": 0,
+ "hash": "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
+ },
+ "error": "failed to verify patch v5: mismatching LTHash",
+ "key_not_found": false,
+ "missing_keys": []
+ },
+ {
+ "description": "missing snapshot key",
+ "list": {
+ "snapshot": "0a02080312b3010a220a2008412495ff8b26a94a13d615f53e9cbca9dd31f4542bdf5ea55ef80042917e831283010a8001101112131415161718191a1b1c1d1e1f05504d3645e870661a34c45988b7f92cbd1302c2c075e12a7661d3ebeba11f3fec9680761dae6a8cc128ed76815c701ec1627d7f356649cf59a4da9011175016c0cb3db6d0e0f3553e774200fcbb9f9e4689be6b083a75bdc1c2968b815b21949e274a559e7bd3914b972c1a4ec728c31a070a0500000001aa12b3010a220a201ef008d9da5877bae8057544fc658a1eaaf1676472668d97e842c05a5faac51b1283010a8001202122232425262728292a2b2c2d2e2f0f0ee49645a560a9c380b3024688f70a1bbd60111692480d6786029b1f6874fb7b9aded54600cdfff8ee6398354d634f10bd5e4ce61cd931c9a6d9c797aeed2a1d0a47dba0ad4e0c54a4db4f012ab569af3f1134ca706ae32be8ef00d1d702d696f8971b697780d14302780c3c66782f1a070a0500000001aa12a1010a220a20100b84efff300a224def9982610a9e2e2e366e4c55c234187d6f38d8b94c05d512720a70303132333435363738393a3b3c3d3e3f80c5dde4a082c58a4dfb05f4567a305e2b681d5b99782f65a17d14086b62215c640e063087aea7c8ca2f8ef429610ba0498ef244195cd04d97cc00825142210d40e99dcd61f8662fbc08b1eace0dc465d9e2af49f1f32068c674a5540fc0db1d1a070a0500000002bb12c3010a220a20063e2d71637fb68a87b23ea8a5c1e17c28f53e721fffd17e004943938f5caef91293010a9001404142434445464748494a4b4c4d4e4f3da58431dccbaa20e44d91235b9637374c91210ca4b8cdda073a3c268cda6a092b575085f4c08dabe210d424edac788b77c521ee77430718c4f23cbb4b9fbc2a977e2646e5fa5c6245af0f755d0af186f3d1e875061023adde513f4f8557c84a68e69b90b67502d87d4c212a36afa260bb76b13fc3951524a75b04f0625c19431a070a0500000001aa1a207e31191fd15d4f29d86f64f60d3e45b32734c50697c927ed6efccf7d98739d8722070a0500000003cc",
+ "patches": [
+ "0a02080412a601080012a1010a220a2008412495ff8b26a94a13d615f53e9cbca9dd31f4542bdf5ea55ef80042917e8312720a70505152535455565758595a5b5c5d5e5fa8246af9944f563478f52853de00032df51eeae6411aca3d7dac9976b8c2051283bc7934264ac9d44b7b96d24592166442b8d8fb93d185f198d2f95f74de19c1080faa6cab72b2f3db4e9e2e618ed9d2af4d80cb984e78e187694e3b3d4663a81a070a0500000001aa12b801080112b3010a220a201ef008d9da5877bae8057544fc658a1eaaf1676472668d97e842c05a5faac51b1283010a8001606162636465666768696a6b6c6d6e6fae2fd376d8fba25a9493a4587830c52fe576f54314755e1e10eeadb3fa2d409a0cac432c3255a9031ecd742e7eff0aac1191eb33193744fdf3d8ac10ce210fdbed5bc42a0c79fa7e7fd8ead6412c38b2c95264c7586f0e232d3d893d607b0436363d71670b88fcf29fc14a1d6305c2041a070a0500000001aa12a601080012a1010a220a201c2d2e8fc7d2c7d745ce9ec11ac73273e2b4ff162437e0a1f11da22db637be2912720a70707172737475767778797a7b7c7d7e7fd31b8a255b2fd4cd3c2c2c8ee0d57c17f371f2783d68706bb0e2131f58c1c5d488c1ab5221752984b291e0c7f86b6a823c835b9664cde17cf493d9f568aaee583c3cd80085aa6dd8f48088a15d328ee7cb97994386812300eaef3c7baaf7460c1a070a0500000002bb12a601080112a1010a220a201c2d2e8fc7d2c7d745ce9ec11ac73273e2b4ff162437e0a1f11da22db637be2912720a70808182838485868788898a8b8c8d8e8fc9f3a507d96104804e46ca63bc3f128139411a0289d6a306f3474eb5fe83ce726bffe37e5c9a570c050843b7da1dddd097b3becfd0598c509770750bedc1807201c08c19a61cc7e99a1869bf4776b3dbc419f75f7692d591b2ccaf7a40a8fefc1a070a0500000002bb12960108011291010a220a208fe8e2c57dc368d4f2338e1c015d74ad189dd9bf30f422ddeef33f2b33f3974512620a60909192939495969798999a9b9c9d9e9f012e9b4c7468fc2844a943d9a9466adc9a76cfebed9c6bd8f1f9ea8224784ae7c82ed20ba55895e4067c66e4950d34f0eb943bc0083a2e5ae50ab41662c273f57187ffb3a275de9714064306ec75c9b81a070a0500000001aa2220ac110c81fda4063e81eff76d6030335113e40b593b286df6db02012f87deece92a2074a8961aa073f421b76cbeba6745a80fdf64aec2c8382c636e0842bb9f33214b32070a0500000002bb",
+ "0a02080512a601080012a1010a220a2023b77172517d7c38bf6b6cc6dd1ae2ac910efb80ee0d73ed1a3022aa444de86512720a7016a0034fde6f136b8ef2ab8eab0164d32d4f438999d130bacba6f79722a64d94c9573eaf5921e4c50ec2458565c7fdadd93579a91b72bc2c81d87bbffffe66ee75222d37e5e778a044c82852b64db4e0d5e88882f2379b8b18ec4970ed2d314fdfceb0487ac8101ca8854d2d3569d5171a070a0500000001aa12d801080012d3010a220a20d357336821f0ecc149ae3b95c8d2d33913c67bb76254dcb41a363626b75aa95112a3010aa001b699b5c04097b485cc46e0b039a8da306928346c1959eb7a294e428537ed4b0c9609dd5543829d857868b73416c71673c3bb77410302d51c8ba7dc3760fe9c5be6549d563ce10245f78eacb52be22d116910840d30cb75e52daa3df5bfc9e3cb676b0ca95916e708463e91de0677bd6b09ddfe40a7888f0241f866584debb61ff3122e04cc3790b8b2715cd189f8dba9026617ea4523084b80e047a3e0e399931a070a0500000001aa2220e1ee797282b7acc89217ab2e8ddac3f25a4d064494299c2b444e9c509b410b0e2a20cab9e5febf96fe243439b2801fd3511bf6d672805bf02daa07f5a67979928bfd32070a0500000001aa"
+ ]
+ },
+ "initial_state": {
+ "version": 0,
+ "hash": "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
+ },
+ "error": "failed to verify snapshot: failed to get key 00000003CC to verify patch v3 MACs: didn't find app state key",
+ "key_not_found": true,
+ "missing_keys": [
+ "00000003cc"
+ ]
+ },
+ {
+ "description": "missing record key",
+ "list": {
+ "snapshot": "0a02080312b3010a220a2008412495ff8b26a94a13d615f53e9cbca9dd31f4542bdf5ea55ef80042917e831283010a8001101112131415161718191a1b1c1d1e1f05504d3645e870661a34c45988b7f92cbd1302c2c075e12a7661d3ebeba11f3fec9680761dae6a8cc128ed76815c701ec1627d7f356649cf59a4da9011175016c0cb3db6d0e0f3553e774200fcbb9f9e4689be6b083a75bdc1c2968b815b21949e274a559e7bd3914b972c1a4ec728c31a070a0500000001aa12b3010a220a201ef008d9da5877bae8057544fc658a1eaaf1676472668d97e842c05a5faac51b1283010a8001202122232425262728292a2b2c2d2e2f0f0ee49645a560a9c380b3024688f70a1bbd60111692480d6786029b1f6874fb7b9aded54600cdfff8ee6398354d634f10bd5e4ce61cd931c9a6d9c797aeed2a1d0a47dba0ad4e0c54a4db4f012ab569af3f1134ca706ae32be8ef00d1d702d696f8971b697780d14302780c3c66782f1a070a0500000001aa12a1010a220a20100b84efff300a224def9982610a9e2e2e366e4c55c234187d6f38d8b94c05d512720a70303132333435363738393a3b3c3d3e3f80c5dde4a082c58a4dfb05f4567a305e2b681d5b99782f65a17d14086b62215c640e063087aea7c8ca2f8ef429610ba0498ef244195cd04d97cc00825142210d40e99dcd61f8662fbc08b1eace0dc465d9e2af49f1f32068c674a5540fc0db1d1a070a0500000003cc12c3010a220a20063e2d71637fb68a87b23ea8a5c1e17c28f53e721fffd17e004943938f5caef91293010a9001404142434445464748494a4b4c4d4e4f3da58431dccbaa20e44d91235b9637374c91210ca4b8cdda073a3c268cda6a092b575085f4c08dabe210d424edac788b77c521ee77430718c4f23cbb4b9fbc2a977e2646e5fa5c6245af0f755d0af186f3d1e875061023adde513f4f8557c84a68e69b90b67502d87d4c212a36afa260bb76b13fc3951524a75b04f0625c19431a070a0500000001aa1a207e31191fd15d4f29d86f64f60d3e45b32734c50697c927ed6efccf7d98739d8722070a0500000001aa",
+ "patches": [
+ "0a02080412a601080012a1010a220a2008412495ff8b26a94a13d615f53e9cbca9dd31f4542bdf5ea55ef80042917e8312720a70505152535455565758595a5b5c5d5e5fa8246af9944f563478f52853de00032df51eeae6411aca3d7dac9976b8c2051283bc7934264ac9d44b7b96d24592166442b8d8fb93d185f198d2f95f74de19c1080faa6cab72b2f3db4e9e2e618ed9d2af4d80cb984e78e187694e3b3d4663a81a070a0500000001aa12b801080112b3010a220a201ef008d9da5877bae8057544fc658a1eaaf1676472668d97e842c05a5faac51b1283010a8001606162636465666768696a6b6c6d6e6fae2fd376d8fba25a9493a4587830c52fe576f54314755e1e10eeadb3fa2d409a0cac432c3255a9031ecd742e7eff0aac1191eb33193744fdf3d8ac10ce210fdbed5bc42a0c79fa7e7fd8ead6412c38b2c95264c7586f0e232d3d893d607b0436363d71670b88fcf29fc14a1d6305c2041a070a0500000001aa12a601080012a1010a220a201c2d2e8fc7d2c7d745ce9ec11ac73273e2b4ff162437e0a1f11da22db637be2912720a70707172737475767778797a7b7c7d7e7fd31b8a255b2fd4cd3c2c2c8ee0d57c17f371f2783d68706bb0e2131f58c1c5d488c1ab5221752984b291e0c7f86b6a823c835b9664cde17cf493d9f568aaee583c3cd80085aa6dd8f48088a15d328ee7cb97994386812300eaef3c7baaf7460c1a070a0500000002bb12a601080112a1010a220a201c2d2e8fc7d2c7d745ce9ec11ac73273e2b4ff162437e0a1f11da22db637be2912720a70808182838485868788898a8b8c8d8e8fc9f3a507d96104804e46ca63bc3f128139411a0289d6a306f3474eb5fe83ce726bffe37e5c9a570c050843b7da1dddd097b3becfd0598c509770750bedc1807201c08c19a61cc7e99a1869bf4776b3dbc419f75f7692d591b2ccaf7a40a8fefc1a070a0500000002bb12960108011291010a220a208fe8e2c57dc368d4f2338e1c015d74ad189dd9bf30f422ddeef33f2b33f3974512620a60909192939495969798999a9b9c9d9e9f012e9b4c7468fc2844a943d9a9466adc9a76cfebed9c6bd8f1f9ea8224784ae7c82ed20ba55895e4067c66e4950d34f0eb943bc0083a2e5ae50ab41662c273f57187ffb3a275de9714064306ec75c9b81a070a0500000001aa2220ac110c81fda4063e81eff76d6030335113e40b593b286df6db02012f87deece92a2074a8961aa073f421b76cbeba6745a80fdf64aec2c8382c636e0842bb9f33214b32070a0500000002bb",
+ "0a02080512a601080012a1010a220a2023b77172517d7c38bf6b6cc6dd1ae2ac910efb80ee0d73ed1a3022aa444de86512720a7016a0034fde6f136b8ef2ab8eab0164d32d4f438999d130bacba6f79722a64d94c9573eaf5921e4c50ec2458565c7fdadd93579a91b72bc2c81d87bbffffe66ee75222d37e5e778a044c82852b64db4e0d5e88882f2379b8b18ec4970ed2d314fdfceb0487ac8101ca8854d2d3569d5171a070a0500000001aa12d801080012d3010a220a20d357336821f0ecc149ae3b95c8d2d33913c67bb76254dcb41a363626b75aa95112a3010aa001b699b5c04097b485cc46e0b039a8da306928346c1959eb7a294e428537ed4b0c9609dd5543829d857868b73416c71673c3bb77410302d51c8ba7dc3760fe9c5be6549d563ce10245f78eacb52be22d116910840d30cb75e52daa3df5bfc9e3cb676b0ca95916e708463e91de0677bd6b09ddfe40a7888f0241f866584debb61ff3122e04cc3790b8b2715cd189f8dba9026617ea4523084b80e047a3e0e399931a070a0500000001aa2220e1ee797282b7acc89217ab2e8ddac3f25a4d064494299c2b444e9c509b410b0e2a20cab9e5febf96fe243439b2801fd3511bf6d672805bf02daa07f5a67979928bfd32060a0400000004"
+ ]
+ },
+ "initial_state": {
+ "version": 0,
+ "hash": "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
+ },
+ "error": "failed to decode snapshot of v3: failed to get key 00000003CC to decode mutation: didn't find app state key",
+ "key_not_found": true,
+ "missing_keys": [
+ "00000003cc",
+ "00000004"
+ ]
+ }
+ ],
+ "recovery": {
+ "collection_snapshot": "1f8b08000000000000ffe262e2d012e22e4a4d2fcd492c8acfc92f974ae432e3528d562ac8cc8b2f3354d2513284018762bdf28cc492e2c48202bdbcd412a558216e8e8686cd07e7186b3171302ab00ab132303030ae925228282c2a2e292d2bafa8acaaaea9adab6f686c6a6e696d6befe8eceaeee9edeb974ae6b2e0528b564a2c4acec82c4b55d2513282014c3b78381ac1767431822c61065bc2b45b4a61c2c44993a74c9d367dc6cc59b3e7cc9d377fc1c2458b972c5db67cc5ca55abd7ac5db75ea9819191899985958d9d83938b9b87978f5f4050485844544c5c42524a5a46564e5e4151495945554d5d43534b5b47574fdfc0d0c8d8c4d4ccdcc2d2cadac6d6cedec1d1c9d9c5d5cdddc3d3cbdbc7d7cf3f2030283824342c3c22322a3a26362e3e2131293925352d3d23332b3b27372f1fc3db80000000ffff87d280535c010000",
+ "is_compressed": true,
+ "name": "regular_low",
+ "mutations": [
+ {
+ "key_id": "00000001aa",
+ "operation": 0,
+ "action": "088080b3c19c332a020801",
+ "version": 5,
+ "index": [
+ "pin_v1",
+ ],
+ "index_mac": "5f99cc86998a9075c3b2b391e16dd998f681b8344fcd431a82d3ce687db2a8c3",
+ "value_mac": "707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f",
+ "patch_version": 42
+ },
+ {
+ "key_id": "00000002bb",
+ "operation": 0,
+ "action": "088180b3c19c338a01020801",
+ "version": 3,
+ "index": [
+ "archive",
+ ],
+ "index_mac": "f1d6e9d7505987364d397dfad0e33beef679a3e91cb0705d8fd4af1a4abfb5eb",
+ "value_mac": "909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeaf",
+ "patch_version": 42
+ }
+ ],
+ "stored_state": {
+ "version": 42,
+ "hash": "0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f80"
+ },
+ "lookups": [
+ {
+ "index_mac": "5f99cc86998a9075c3b2b391e16dd998f681b8344fcd431a82d3ce687db2a8c3",
+ "value_mac": "707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f"
+ },
+ {
+ "index_mac": "f1d6e9d7505987364d397dfad0e33beef679a3e91cb0705d8fd4af1a4abfb5eb",
+ "value_mac": "909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeaf"
+ }
+ ],
+ "invalid_lthash_snapshot": "0a02082a120b726567756c61725f6c6f771a610a360a255b2270696e5f7631222c2231313131313131313140732e77686174736170702e6e6574225d120b088080b3c19c332a0208012005120500000001aa1a20707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f1a630a380a265b2261726368697665222c2232323232323232323240732e77686174736170702e6e6574225d120c088180b3c19c338a010208012003120500000002bb1a20909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeaf227f000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e",
+ "invalid_lthash_error": "invalid lthash length: 127"
+ }
+}
diff --git a/crates/whatsmeow/testdata/appstate_client.json b/crates/whatsmeow/testdata/appstate_client.json
new file mode 100644
index 0000000000..9d679270f1
--- /dev/null
+++ b/crates/whatsmeow/testdata/appstate_client.json
@@ -0,0 +1,310 @@
+{
+ "critical_unblock_low_v1_patch": "0a02080112b701080012b2010a220a2023ff327599a6eab4243f1177092ff10075038724e5b7df70884bc4a2951300ea1283010a800161057a7b98f0cca82fdc3a9685d87dad39efd881f11d2a16eb5f59ccaa7ebea336fe4de8aa15ac412c711c1d9cf143cbf1ff4adf168d858d753118423c3e9ff17ed9c1a44aa12cb2fcfdf105ee2e324135e00066640737c6259e156be2df0c313822e45be8fc332941bcfd7822a1fa10656f75d8e8bce2a18dd986d0cc32c6bf1a060a040000000112a501080012a0010a220a20306b006bd93cfc1c224308aa4c55a746c78a955944c3b76b0ebdfa297501470612720a70aeafbc132dd78b5880c740548430b09e383e246cd92b1c80afb3fbe0a427f4715b8930910df08c5d36723f53f5c4796f19486caafff81c39060dbf4360e8631a195cacc8b87e75cee7e756c25ab86e2d8df01b443537c862e2cfd6d8475bf9f70a69cf7ad1b862f3c9483ad2d84bda231a060a040000000122209b1784eb47ef4d83d16a164e531ab1f5ce400e2cd1a04af1c69e1a075b5ff4482a204c4aecf8dd99017a52a8135e3803df211685ec785fc8ab50f1f163f2034edee932060a0400000001",
+ "fetch_snapshot_iq": "00f80a1908ff831b2a1f16ec9c045a11fa0003f801f802ece3f801f805ec5b89eceded1e9b",
+ "fetch_version_iq": "00f80a1908ff831b2a2f16ec9c045a11fa0003f801f802ece3f801f807ec5b89eceded1eec0f5455",
+ "key_1_data": "101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f",
+ "key_1_id": "00000001",
+ "key_2_data": "202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f",
+ "key_2_id": "00000002",
+ "mark_not_dirty_iq": "00f80a1908ff831b2a3f16ecb8045a11fa0003f801f805edf804ecc0ec9aff051700000000",
+ "recovery_request": "621d101082011808083a140a0c726567756c61725f686967681080e2cfaa06",
+ "regular_high_v1_events": [
+ {
+ "action": "08fbd095ffbc31220908011080adf180bd31",
+ "index": [
+ "mute",
+ ],
+ "type": "AppState"
+ },
+ {
+ "action": "08011080adf180bd31",
+ "from_full_sync": true,
+ "jid": "[email protected]",
+ "timestamp": 1700000000123,
+ "type": "Mute"
+ },
+ {
+ "action": "08fbd095ffbc312a020801",
+ "index": [
+ "pin_v1",
+ ],
+ "type": "AppState"
+ },
+ {
+ "action": "0801",
+ "from_full_sync": true,
+ "jid": "[email protected]",
+ "timestamp": 1700000000123,
+ "type": "Pin"
+ },
+ {
+ "action": "08fbd095ffbc318a0134080112300880e2cfaa061a280a200a133131313140732e77686174736170702e6e657410011a074c4153544d53471080e2cfaa06",
+ "index": [
+ "archive",
+ ],
+ "type": "AppState"
+ },
+ {
+ "action": "080112300880e2cfaa061a280a200a133131313140732e77686174736170702e6e657410011a074c4153544d53471080e2cfaa06",
+ "from_full_sync": true,
+ "jid": "[email protected]",
+ "timestamp": 1700000000123,
+ "type": "Archive"
+ },
+ {
+ "action": "08fbd095ffbc312a020800",
+ "index": [
+ "pin_v1",
+ ],
+ "type": "AppState"
+ },
+ {
+ "action": "0800",
+ "from_full_sync": true,
+ "jid": "[email protected]",
+ "timestamp": 1700000000123,
+ "type": "Pin"
+ },
+ {
+ "action": "08fbd095ffbc31a20134080112300880e2cfaa061a280a200a133131313140732e77686174736170702e6e657410011a074c4153544d53471080e2cfaa06",
+ "index": [
+ "markChatAsRead",
+ ],
+ "type": "AppState"
+ },
+ {
+ "action": "080112300880e2cfaa061a280a200a133131313140732e77686174736170702e6e657410011a074c4153544d53471080e2cfaa06",
+ "from_full_sync": true,
+ "jid": "[email protected]",
+ "timestamp": 1700000000123,
+ "type": "MarkChatAsRead"
+ },
+ {
+ "action": "08fbd095ffbc3112020801",
+ "index": [
+ "star",
+ "STARRED",
+ "0",
+ ],
+ "type": "AppState"
+ },
+ {
+ "action": "0801",
+ "from_full_sync": true,
+ "is_from_me": false,
+ "jid": "[email protected]",
+ "message_id": "STARRED",
+ "sender_jid": "[email protected]",
+ "timestamp": 1700000000123,
+ "type": "Star"
+ },
+ {
+ "action": "08fbd095ffbc31b201320a300880e2cfaa061a280a200a133131313140732e77686174736170702e6e657410011a074c4153544d53471080e2cfaa06",
+ "index": [
+ "deleteChat",
+ "1"
+ ],
+ "type": "AppState"
+ },
+ {
+ "action": "0a300880e2cfaa061a280a200a133131313140732e77686174736170702e6e657410011a074c4153544d53471080e2cfaa06",
+ "delete_media": true,
+ "from_full_sync": true,
+ "jid": "[email protected]",
+ "timestamp": 1700000000123,
+ "type": "DeleteChat"
+ },
+ {
+ "action": "08fbd095ffbc31720a0a04576f726b10032000",
+ "index": [
+ "label_edit",
+ "5"
+ ],
+ "type": "AppState"
+ },
+ {
+ "action": "0a04576f726b10032000",
+ "from_full_sync": true,
+ "label_id": "5",
+ "timestamp": 1700000000123,
+ "type": "LabelEdit"
+ },
+ {
+ "action": "08fbd095ffbc317a020801",
+ "index": [
+ "label_jid",
+ "5",
+ ],
+ "type": "AppState"
+ },
+ {
+ "action": "0801",
+ "from_full_sync": true,
+ "jid": "[email protected]",
+ "label_id": "5",
+ "timestamp": 1700000000123,
+ "type": "LabelAssociationChat"
+ },
+ {
+ "action": "08fbd095ffbc317a020801",
+ "index": [
+ "label_message",
+ "5",
+ "LABELED",
+ "0",
+ "0"
+ ],
+ "type": "AppState"
+ },
+ {
+ "action": "0801",
+ "from_full_sync": true,
+ "jid": "[email protected]",
+ "label_id": "5",
+ "message_id": "LABELED",
+ "timestamp": 1700000000123,
+ "type": "LabelAssociationMessage"
+ },
+ {
+ "action": "08fbd095ffbc313a0a0a084e6577204e616d65",
+ "index": [
+ "setting_pushName"
+ ],
+ "type": "AppState"
+ },
+ {
+ "action": "0a084e6577204e616d65",
+ "from_full_sync": true,
+ "timestamp": 1700000000123,
+ "type": "PushNameSetting"
+ },
+ {
+ "action": "08fbd095ffbc311a170a0c436f6e746163742046756c6c1207436f6e74616374",
+ "index": [
+ "contact",
+ ],
+ "type": "AppState"
+ },
+ {
+ "action": "0a0c436f6e746163742046756c6c1207436f6e74616374",
+ "from_full_sync": true,
+ "jid": "[email protected]",
+ "timestamp": 1700000000123,
+ "type": "Contact"
+ },
+ {
+ "action": "08fbd095ffbc31aa0100",
+ "index": [
+ "clearChat",
+ "1",
+ "1"
+ ],
+ "type": "AppState"
+ },
+ {
+ "action": "",
+ "delete_media": true,
+ "from_full_sync": true,
+ "jid": "[email protected]",
+ "timestamp": 1700000000123,
+ "type": "ClearChat"
+ },
+ {
+ "action": "08fbd095ffbc31920108080110ffe1cfaa06",
+ "index": [
+ "deleteMessageForMe",
+ "DELETED",
+ "1",
+ "0"
+ ],
+ "type": "AppState"
+ },
+ {
+ "action": "080110ffe1cfaa06",
+ "from_full_sync": true,
+ "is_from_me": true,
+ "jid": "[email protected]",
+ "message_id": "DELETED",
+ "sender_jid": "",
+ "timestamp": 1700000000123,
+ "type": "DeleteForMe"
+ },
+ {
+ "action": "08fbd095ffbc31ba01020801",
+ "index": [
+ "setting_unarchiveChats"
+ ],
+ "type": "AppState"
+ },
+ {
+ "action": "0801",
+ "from_full_sync": true,
+ "timestamp": 1700000000123,
+ "type": "UnarchiveChatsSetting"
+ },
+ {
+ "action": "08fbd095ffbc31ea01020801",
+ "index": [
+ "userStatusMute",
+ ],
+ "type": "AppState"
+ },
+ {
+ "action": "0801",
+ "from_full_sync": true,
+ "jid": "[email protected]",
+ "timestamp": 1700000000123,
+ "type": "UserStatusMute"
+ }
+ ],
+ "regular_high_v1_patch": "0a02080112a501080012a0010a220a20fd8f08fd42bb0cf831b0b5cb91d5a777ab789bd1e3a1a681d5b497b1f571ed9d12720a701fc6b4e2628ad11bf4fb6b59dfc7218d4a397cb5b5e0fb602a271c9718168b43d140900b0a3a35c0ff4bc3fef034ef4d7e88f73b780606b93ff975b76222a4a16a2b4bd51b19d6b7e0d6a91b1abb531101b49a5ec8f073ee14a164753950afded47dad32f5104ab7bf38071c199d466a1a060a040000000112a501080012a0010a220a20240b1e9857ae8780d74379047fa0fe0817c2fd260baef328bc5dc5eee152c8e212720a70986c84315cc92ff04321541f8b828554e38bb90a5386bc8dc40d7605a11af9a4ddd840a772a731b6516d56e04b9dc4194f87097c208c04db16cba17a3b5126e589f8d9b7a53c2ff91766ddc44c707fa1610fc0cab681f1b6fa0c1435037afdd7c588ef3474e6d438c4e337ff6341e8fc1a060a040000000112d701080012d2010a220a20fd198cc281cacc56535e913d9083ce1e739f0b191e09546d3e436a88da59bf3f12a3010aa00188db7a4f8afbb4672c2d44f77dbcf1b5f42db4b869981764dd3242c43fa142686e8a58f9a36beff48c42e69f5cb58984801c6410079a1d384f4d0676f1d7afd20754346eed954b6fadd860e4f9bd746af77f97016813e0f1bc318fe12dc348b2bea7e5355423cf354a1c8bf128d6d2961172a2dd246a04e201131c8e2ce9255e0853b5d164659904d5709b14b875df307b5beda58c63c055c0edebbc19c7960b1a060a040000000112a501080012a0010a220a20306b006bd93cfc1c224308aa4c55a746c78a955944c3b76b0ebdfa297501470612720a700e8888bffdbb4e672d08df4403607f6bf3c72788f7b4503f658a45e5d372e76394f761e330ef2c678481ce8e378190910a9c366b26987f1f88db1a9abc2201b62eff5d8eba0c5d32f7ea8274341ac7340ef46dc8d8c68da08d6f82f02b46dc16b33273d5b90f03b4c760cd4c1b74d5731a060a040000000112d701080012d2010a220a20c97dc2e89bc87d0dad894c1ec026c9e3e90deded4e1ecee9bf62bd1d0a19c5fa12a3010aa001eaf12f6109b92c59d8a4004c044a8513b3b30157450dba5cbc2fe9ff7adbbf401431847b6b98b950c83f59d6f44774867c31472985bd17983d3853a48644238462072d1f1310de687c508b3c26f556aff0791dad6aebf16016cd35d59490f26c9c95ecdabffb7d49fb313ba40a738cc206ea9a50d1bfd3b34d8f77d01a43f48e3d662ec235953d96d7133c6ef0ce0f8515f860e9597b43b5b308929b9d498cf01a060a040000000112c701080012c2010a220a206b36787a74f8cee12cfb30b81f828ee3644baf2c1ad922a83c7e03e206cebd481293010a9001ed42f391f1f244a37864e8f6e75af0951a023ad47d1aa4446506ac3ad131386cdfd027cabe7a448fad73bc0891a30e42cfe13f3e0635f7e3e717e17545910fd70c5120fbe7da89058ed146353bd2926d194ccbe64835500de02735d38128f3c4fcf813f044d9d6706a93393798e0d47b530ef05f1a1eabace0a997edfbdb67b0adbdbe17c041889e6bbee1c10b6b2d9c1a060a040000000112d701080012d2010a220a2007468814b960863dc8461ce93131a6992fcc2f7e3b21d066a6195d707537016812a3010aa00191c7f712dd1b64d55ef71b04621323ff21226914ff8cda66aed81cf73c9c87b6808441c53ef949f4f967a17284dc471f3f67e41dbc3f413e2bb12a4460cb12cb8d53312b0bf8a71b031acfb525edd392d57c0edb75ebd93f74a3f53024d0cfc86e60968808fa9434165f92f4b6ad774bbe400d585084e2ac03f509b6f43f2e7f83de931e4813be9b1a88a02ba7c9eef1cf1074461bd09591173f4e2ef8ebd46d1a060a040000000112950108001290010a220a209c57180afa7c43acfdc7a271ac2676392a9ec86232515273365a1958ae73ed1412620a602336ddf1eae731a5746709a9d1a051a1da5cf0e5801881a0ffd64df9cb0f2faf4881bae9149265ae1f79e762754ffbfd9e823016b9d53d41ce4989643d892de7fb44bdcfdbc6eca257e0349513976c88471160bb3544aed11f6c6eb40bc7ceeb1a060a040000000112a501080012a0010a220a20105aef1f755cfd1abddd3ed26bbb9843aebd8bc36ab5def311a3155a90a8a5b912720a707217f58b9742cdacd93be54a4da781bd3ab459b944b46ff96ddc6dc3a4960b83c26f95010662f8ffa78819ff2716ee9322f60266ddaa30929be0a108c0abc68767102f3feb9f2c42de4c21148f1b8d7f843b4590c84bddd833c769776674159e485a26dfc93a116ab2fa130181e1948d1a060a040000000112c701080012c2010a220a2092d0b05818241b5875cba76e488cafdaccf3a90d4758cc773653a26858bf9bc01293010a90019d0e1fdfedded6da3913b57d461c07229a5f7321a0df7d4c2febf96eee90ec7e3c6e960bc05e8a7ebe707e55d24cc392698445eb126c7751e2b9f890120157353215c3796002d5d58cd8127386873fd1371f922a1e2d392d3036d369f068a77b55fb6195d43b307c91296d337b151b7b1ada5027b4266d8c1e509b81fbe3d66460d3c88406e224679974834aff1db8f51a060a040000000112950108001290010a220a2028a68b23170e40d044dc3b7842730273657c039a4bf84fcb28b4fe5ab24358d412620a6069411b74aeb3fc2ca06a23c60cd347306025b0cf08c34f9e532597febb2e5d38d1a281bb84eb75fb0bd9a5f4fcd8db0a3541946bde4996e8c5698c7945204d94ae1034acf5400fb0762a1171d91f1b695a3c6996d84799ea8ea2346036ddc03e1a060a040000000112b701080012b2010a220a2023ff327599a6eab4243f1177092ff10075038724e5b7df70884bc4a2951300ea1283010a8001d4e472778e0c1e430eee19b6f522a338f0bc69d01914713743e95986666a398d8ed55c06671d8ae60ebbca2ba4ac3cc8c884ada569615cd0d9d3b3f0cf51fc737ec73e69f3b85ef8cee2e5604a12233ac9cb848d067f4cfedb94ba7974f9157cbf40bd228b23b0f2a7792fc15d4ced70ee27e4e910e3c0d5aa96d7d6bb29401c1a060a040000000112a501080012a0010a220a20d3319649e02ef88635cf6465e5ca843d6d51f3d673594dbb664c0563442582e112720a70992a916caac1349196a8a4f0339425e569f9ded0ae051c4ac164e63dbd83b40de534dc4401603b63bcfc26d8301925b952a93daec64403513b4a20321be3a066710fbd5ee87c18b5e3c9b34c1c10370cec0d05e50f97daf1dd276b109cfe969af3890089accbf7b8a93f75c9d93f418b1a060a040000000112c701080012c2010a220a20dfbbca10174f693643f9496dd23e11eb9e982900da0ae7b7a83b97c4015a38321293010a9001c2988a367ba170dff73c127358be94af11b2fb409850fff9c5778f18dbe120c1cb171b54ced6b586ed0478d7a69827a7539f3e9f6d6e18653e8bf7677d855a4332bf93057f7b3065a002c2bdf048650363b9dfe7ecb64bbd5095fbb4b64b2041583d562cd76ad33eea4cf5373b001b9e342b80a9b33305a1853e0d57bf395f2a0a0944dbfae191e006c415e1343f1ea71a060a040000000112950108001290010a220a2048316ef643a37824dff98677428c6a56b954fc22a7b7bb9ce430c22ee623acba12620a60b3c65c5c77c8dd593e71f9e5a1548e6a2f709ebbc8f41ebed04b8af913acb049d9d7ef7bdbde2c3ab34e55145fba97013b355f69f16fc677bb8a8afc4f7e396c41fcffb045dcb6e8003be242a6058b83c06ac9a7d9d405581dc896c1432599ca1a060a040000000112a501080012a0010a220a20dc14644d2c872e2a5bcfe98267e076440432fe4821a3948e891659141c4bde6112720a70ba2ef54b290122f9f9e9917575809eb26420e051bf27ff7a733a2b072af302cc237ef604f428adab84e80ee500dc6359169fc4562beaf70204f1bc5332703bbdfe5642ab6ff80fda5da96c1a4f8fd771724d0721c7ae0c927ef7b01d01b058af30c9d56004f0c1c5c63568e0512395421a060a040000000122201f9dcf627a570e7d1d0f68994cdfb497daf4e0d833aa5193eae847bba08dee922a20aa6563121c7af512a85b3d17cb78af47eddce04eb6e73145c61c99ea61088de132060a0400000001",
+ "regular_high_v2_events": [
+ {
+ "action": "08dba599ffbc3122020800",
+ "index": [
+ "mute",
+ ],
+ "type": "AppState"
+ },
+ {
+ "action": "0800",
+ "from_full_sync": false,
+ "jid": "[email protected]",
+ "timestamp": 1700000060123,
+ "type": "Mute"
+ },
+ {
+ "action": "08dba599ffbc312a020800",
+ "index": [
+ "pin_v1",
+ ],
+ "type": "AppState"
+ },
+ {
+ "action": "0800",
+ "from_full_sync": false,
+ "jid": "[email protected]",
+ "timestamp": 1700000060123,
+ "type": "Pin"
+ }
+ ],
+ "regular_high_v2_patch": "0a02080212a501080012a0010a220a20fd8f08fd42bb0cf831b0b5cb91d5a777ab789bd1e3a1a681d5b497b1f571ed9d12720a70135eea664dbb942e261159389263672ec4d88652aee5f4be8e14febebcfb3856981b86cba475a4fa5a5b7f4c72245b932314b224702e78aea40a10395e4dced0372a6caf6001726fde3087d0747fbc4800ae587dc18167a3e9f03ed180974dcf53523605b90ca5c02d1dcffcd42a8d5d1a060a040000000112a501080012a0010a220a20306b006bd93cfc1c224308aa4c55a746c78a955944c3b76b0ebdfa297501470612720a70379df43f0a617d369f7d502a98b6bc4b5f7cc3b61e21d2184aba89712c4dc04b1388c08e0473bf88e6e1875dcf682ba54f4b721b017508f9e9c5626e6c4104da9fb69e3f2aafe94eae4740955950e9dfbdfb8be9ca63f577b964b7437da59eadd89197b3fc2117b0fb3cdc06a40f28671a060a0400000001222042076bfd6162eb422dd8105a2ff94fbc8fa003a4e83dd2363b2280e07f7ab6642a20e5d2bbf686f5b2dc70dbf1c0ab62b3cccded0618865563166b2dea97906f2ff432060a0400000001",
+ "regular_low_v1_patch_key_2": "0a02080112d701080012d2010a220a207e75952f2dae79b9207f52c04c76a0955531d97682d25b60e4c4c6cc5e11acd012a3010aa0015677f10ded2d2b940af69f9e6ae4163d61c4bb64bb2f251888472fec5e8be91ade1085a528e9de801374a558adda85d80bc7e26546c9302ab8b1ff80e80a8608be7962731ca102d11542ec52336ec872105796f5721c054a26072a3e077cdc67301fae16396e61c947a3a0528fdd0bf376b82c0ad2349caa23e6bc68acb6df683034c6ebbb3e079ca6c8a8a774a301679a022af679c0fe376c86442844fd10e01a060a040000000212a501080012a0010a220a206e530e423af2cd0ffb9b24633ebb47e9a544eab68519af50157e1f90035f493112720a700dd3fbf6b23250c5f73570c86383b3de8a4a9c1dfe82bfbbb80e461ab7f03b018cfba6f5a14dc62b935e6e1af01f42300ba9483583d1664b1d9ff7ddf2458e4d86f44025b494565126bcf4449e989b8606aead4d70ad9ec1b46439a540b61fc7bd93af6fd0ea6964f1bd9d56ae0e4e6d1a060a04000000022220cfaf62e5af99f1d2893feaf195874487f8ed3171024252f7d682bdc11baa16772a207eb1a9b21e9bb3671169461780aae427e74602ebe9230c098f0e93626111968b32060a0400000002",
+ "send_app_state_iq_without_patch": "00f80a1908ff831b2a1f16ec9c045a11fa0003f801f802ece3f801f808ec5b89ed28542ded1eec0ff801f801ecf6"
+}
diff --git a/crates/whatsmeow/testdata/generator/README.md b/crates/whatsmeow/testdata/generator/README.md
new file mode 100644
index 0000000000..694f165e9c
--- /dev/null
+++ b/crates/whatsmeow/testdata/generator/README.md
@@ -0,0 +1,32 @@
+# Test vector generators
+
+Go code that runs whatsmeow's own code at the pinned revision
+(`b2b1e71d45e2ff171153b025b5a42f475bb30ef8`) and writes the expected values
+the Rust tests compare against. Test tooling only: not built in CI, and it
+never contacts WhatsApp.
+
+## Programs (`media`, `appstate`)
+
+Each is its own `package main` directory in this Go module. `go.mod` requires
+whatsmeow at the pinned revision as a pseudo-version, so Go fetches it from
+the module proxy; to use a local checkout instead, run `go mod edit -replace
+go.mau.fi/whatsmeow=/path/to/whatsmeow` (don't commit the replace). They
+reach unexported whatsmeow functions with `go:linkname`, which the linker only
+allows with `-checklinkname=0`. Run from this directory:
+
+| Generator | Command | Writes |
+| --- | --- | --- |
+| `media` | `go run -ldflags=-checklinkname=0 ./media` | `../media/vectors.json` |
+| `appstate` | `go run -ldflags=-checklinkname=0 ./appstate` | `../appstate/vectors.json` |
+
+`media` runs a real `Client` against local TLS test servers. Its vectors
+change on every run (Go's `Upload` picks a random media key), and so does one
+`appstate` patch (`EncodePatch` uses random IVs); the assertions don't.
+
+## In-package tests (`inpackage`)
+
+Most client code is unexported methods on `*Client`, so these generators are
+`_test.go` files in `package whatsmeow`. `inpackage/generate.sh [checkout]`
+copies them into a whatsmeow checkout at the pinned revision (cloning one if
+no path is given), runs `go test -run TestGenerate`, and writes
+`../*.json`, which the Rust tests read through `src/vectors.rs`.
diff --git a/crates/whatsmeow/testdata/generator/appstate/main.go b/crates/whatsmeow/testdata/generator/appstate/main.go
new file mode 100644
index 0000000000..d4aa97dcb5
--- /dev/null
+++ b/crates/whatsmeow/testdata/generator/appstate/main.go
@@ -0,0 +1,832 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+// Command appstate writes the test vectors for the Rust port of whatsmeow's
+// appstate package by running whatsmeow's own code. Unexported functions are
+// reached with go:linkname, so it must be run with -ldflags=-checklinkname=0
+// (see ../README.md).
+package main
+
+import (
+ "bytes"
+ "compress/gzip"
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "flag"
+ "fmt"
+ "hash"
+ "os"
+ "slices"
+ "time"
+ _ "unsafe"
+
+ "google.golang.org/protobuf/proto"
+
+ "go.mau.fi/whatsmeow/appstate"
+ "go.mau.fi/whatsmeow/appstate/lthash"
+ "go.mau.fi/whatsmeow/proto/waCommon"
+ "go.mau.fi/whatsmeow/proto/waE2E"
+ "go.mau.fi/whatsmeow/proto/waServerSync"
+ "go.mau.fi/whatsmeow/proto/waSyncAction"
+ "go.mau.fi/whatsmeow/proto/waSyncdSnapshotRecovery"
+ "go.mau.fi/whatsmeow/store"
+ "go.mau.fi/whatsmeow/types"
+ "go.mau.fi/whatsmeow/util/cbcutil"
+ waLog "go.mau.fi/whatsmeow/util/log"
+)
+
+//go:linkname expandAppStateKeys go.mau.fi/whatsmeow/appstate.expandAppStateKeys
+func expandAppStateKeys(keyData []byte) appstate.ExpandedAppStateKeys
+
+//go:linkname concatAndHMAC go.mau.fi/whatsmeow/appstate.concatAndHMAC
+func concatAndHMAC(alg func() hash.Hash, key []byte, data ...[]byte) []byte
+
+//go:linkname generateSnapshotMAC go.mau.fi/whatsmeow/appstate.(*HashState).generateSnapshotMAC
+func generateSnapshotMAC(hs *appstate.HashState, name appstate.WAPatchName, key []byte) []byte
+
+//go:linkname updateHash go.mau.fi/whatsmeow/appstate.(*HashState).updateHash
+func updateHash(hs *appstate.HashState, mutations []*waServerSync.SyncdMutation, getPrevSetValueMAC func(indexMAC []byte, maxIndex int) ([]byte, error)) ([]error, error)
+
+//go:linkname generatePatchMAC go.mau.fi/whatsmeow/appstate.generatePatchMAC
+func generatePatchMAC(patch *waServerSync.SyncdPatch, name appstate.WAPatchName, key []byte, version uint64) []byte
+
+//go:linkname generateContentMAC go.mau.fi/whatsmeow/appstate.generateContentMAC
+func generateContentMAC(operation waServerSync.SyncdMutation_SyncdOperation, data, keyID, key []byte) []byte
+
+// memoryStore follows whatsmeow's sqlstore semantics for app state keys,
+// versions and mutation MACs.
+type memoryStore struct {
+ keys map[string]store.AppStateSyncKey
+ versions map[string]appstate.HashState
+ macs map[string][]storedMAC
+}
+
+type storedMAC struct {
+ version uint64
+ mac store.AppStateMutationMAC
+}
+
+func newMemoryStore(keys map[string][]byte) *memoryStore {
+ mem := &memoryStore{
+ keys: make(map[string]store.AppStateSyncKey),
+ versions: make(map[string]appstate.HashState),
+ macs: make(map[string][]storedMAC),
+ }
+ for id, data := range keys {
+ mem.keys[id] = store.AppStateSyncKey{Data: data}
+ }
+ return mem
+}
+
+func (m *memoryStore) PutAppStateSyncKey(_ context.Context, id []byte, key store.AppStateSyncKey) error {
+ m.keys[string(id)] = key
+ return nil
+}
+
+func (m *memoryStore) GetAppStateSyncKey(_ context.Context, id []byte) (*store.AppStateSyncKey, error) {
+ key, ok := m.keys[string(id)]
+ if !ok {
+ return nil, nil
+ }
+ return &key, nil
+}
+
+func (m *memoryStore) GetLatestAppStateSyncKeyID(context.Context) ([]byte, error) {
+ panic("unused")
+}
+
+func (m *memoryStore) GetAllAppStateSyncKeys(context.Context) ([]*store.AppStateSyncKey, error) {
+ panic("unused")
+}
+
+func (m *memoryStore) PutAppStateVersion(_ context.Context, name string, version uint64, hash [128]byte) error {
+ m.versions[name] = appstate.HashState{Version: version, Hash: hash}
+ return nil
+}
+
+func (m *memoryStore) GetAppStateVersion(_ context.Context, name string) (uint64, [128]byte, error) {
+ state := m.versions[name]
+ return state.Version, state.Hash, nil
+}
+
+func (m *memoryStore) DeleteAppStateVersion(_ context.Context, name string) error {
+ delete(m.versions, name)
+ return nil
+}
+
+func (m *memoryStore) PutAppStateMutationMACs(_ context.Context, name string, version uint64, mutations []store.AppStateMutationMAC) error {
+ for _, mutation := range mutations {
+ m.macs[name] = append(m.macs[name], storedMAC{version, mutation})
+ }
+ return nil
+}
+
+func (m *memoryStore) DeleteAppStateMutationMACs(_ context.Context, name string, indexMACs [][]byte) error {
+ m.macs[name] = slices.DeleteFunc(m.macs[name], func(stored storedMAC) bool {
+ return slices.ContainsFunc(indexMACs, func(indexMAC []byte) bool {
+ return bytes.Equal(indexMAC, stored.mac.IndexMAC)
+ })
+ })
+ return nil
+}
+
+func (m *memoryStore) GetAppStateMutationMAC(_ context.Context, name string, indexMAC []byte) ([]byte, error) {
+ var found *storedMAC
+ for i, stored := range m.macs[name] {
+ if bytes.Equal(stored.mac.IndexMAC, indexMAC) && (found == nil || stored.version >= found.version) {
+ found = &m.macs[name][i]
+ }
+ }
+ if found == nil {
+ return nil, nil
+ }
+ return found.mac.ValueMAC, nil
+}
+
+func newProcessor(mem *memoryStore) *appstate.Processor {
+ return appstate.NewProcessor(&store.Device{AppStateKeys: mem, AppState: mem}, waLog.Noop)
+}
+
+func must[T any](value T, err error) T {
+ if err != nil {
+ panic(err)
+ }
+ return value
+}
+
+func marshal(message proto.Message) string {
+ return hex.EncodeToString(must(proto.MarshalOptions{Deterministic: true}.Marshal(message)))
+}
+
+func bytesRange(start, length int) []byte {
+ out := make([]byte, length)
+ for i := range out {
+ out[i] = byte(start + i)
+ }
+ return out
+}
+
+type hexBytes []byte
+
+func (h hexBytes) MarshalJSON() ([]byte, error) {
+ if h == nil {
+ return []byte("null"), nil
+ }
+ return json.Marshal(hex.EncodeToString(h))
+}
+
+type lthashVector struct {
+ Base hexBytes `json:"base"`
+ Subtract []hexBytes `json:"subtract"`
+ Add []hexBytes `json:"add"`
+ Result hexBytes `json:"result"`
+}
+
+type expandedKeysVector struct {
+ KeyData hexBytes `json:"key_data"`
+ Index hexBytes `json:"index"`
+ ValueEncryption hexBytes `json:"value_encryption"`
+ ValueMAC hexBytes `json:"value_mac"`
+ SnapshotMAC hexBytes `json:"snapshot_mac"`
+ PatchMAC hexBytes `json:"patch_mac"`
+}
+
+type snapshotMACVector struct {
+ Hash hexBytes `json:"hash"`
+ Version uint64 `json:"version"`
+ Name string `json:"name"`
+ Key hexBytes `json:"key"`
+ MAC hexBytes `json:"mac"`
+}
+
+type patchMACVector struct {
+ Patch string `json:"patch"`
+ Name string `json:"name"`
+ Key hexBytes `json:"key"`
+ Version uint64 `json:"version"`
+ MAC hexBytes `json:"mac"`
+}
+
+type contentMACVector struct {
+ Operation int32 `json:"operation"`
+ Data hexBytes `json:"data"`
+ KeyID hexBytes `json:"key_id"`
+ Key hexBytes `json:"key"`
+ MAC hexBytes `json:"mac"`
+}
+
+type indexMACVector struct {
+ Key hexBytes `json:"key"`
+ Index hexBytes `json:"index"`
+ MAC hexBytes `json:"mac"`
+}
+
+type indexJSONVector struct {
+ Index []string `json:"index"`
+ JSON string `json:"json"`
+}
+
+type keyVector struct {
+ ID hexBytes `json:"id"`
+ Data hexBytes `json:"data"`
+}
+
+type stateVector struct {
+ Version uint64 `json:"version"`
+ Hash hexBytes `json:"hash"`
+}
+
+type mutationVector struct {
+ KeyID hexBytes `json:"key_id"`
+ Operation int32 `json:"operation"`
+ Action *string `json:"action"`
+ Version int32 `json:"version"`
+ Index []string `json:"index"`
+ IndexMAC hexBytes `json:"index_mac"`
+ ValueMAC hexBytes `json:"value_mac"`
+ PatchVersion uint64 `json:"patch_version"`
+}
+
+type lookupVector struct {
+ IndexMAC hexBytes `json:"index_mac"`
+ ValueMAC hexBytes `json:"value_mac"`
+}
+
+type patchListVector struct {
+ Snapshot *string `json:"snapshot"`
+ Patches []string `json:"patches"`
+}
+
+type decodeStepVector struct {
+ List patchListVector `json:"list"`
+ InitialState stateVector `json:"initial_state"`
+ Mutations []mutationVector `json:"mutations"`
+ State stateVector `json:"state"`
+ StoredState stateVector `json:"stored_state"`
+ Lookups []lookupVector `json:"lookups"`
+}
+
+type sequenceVector struct {
+ Name string `json:"name"`
+ Keys []keyVector `json:"keys"`
+ Steps []decodeStepVector `json:"steps"`
+}
+
+type decodeErrorVector struct {
+ Description string `json:"description"`
+ List patchListVector `json:"list"`
+ InitialState stateVector `json:"initial_state"`
+ Error string `json:"error"`
+ KeyNotFound bool `json:"key_not_found"`
+ MissingKeys []hexBytes `json:"missing_keys"`
+}
+
+type patchInfoVector struct {
+ Type string `json:"type"`
+ Mutations []mutationInfoVector `json:"mutations"`
+}
+
+type mutationInfoVector struct {
+ Index []string `json:"index"`
+ Version int32 `json:"version"`
+ Value string `json:"value"`
+}
+
+type recoveryVector struct {
+ CollectionSnapshot hexBytes `json:"collection_snapshot"`
+ IsCompressed bool `json:"is_compressed"`
+ Name string `json:"name"`
+ Mutations []mutationVector `json:"mutations"`
+ StoredState stateVector `json:"stored_state"`
+ Lookups []lookupVector `json:"lookups"`
+ InvalidLTHash hexBytes `json:"invalid_lthash_snapshot"`
+ InvalidLTHashError string `json:"invalid_lthash_error"`
+}
+
+type vectors struct {
+ LTHash []lthashVector `json:"lthash"`
+ ExpandedKeys []expandedKeysVector `json:"expanded_keys"`
+ SnapshotMAC []snapshotMACVector `json:"snapshot_mac"`
+ PatchMAC []patchMACVector `json:"patch_mac"`
+ ContentMAC []contentMACVector `json:"content_mac"`
+ IndexMAC []indexMACVector `json:"index_mac"`
+ IndexJSON []indexJSONVector `json:"index_json"`
+ Builders []patchInfoVector `json:"builders"`
+ Sequence sequenceVector `json:"sequence"`
+ DecodeErrors []decodeErrorVector `json:"decode_errors"`
+ Recovery recoveryVector `json:"recovery"`
+}
+
+const name = appstate.WAPatchRegularHigh
+
+var (
+ key1ID = []byte{0, 0, 0, 1, 0xaa}
+ key1Data = bytesRange(0x10, 32)
+ key2ID = []byte{0, 0, 0, 2, 0xbb}
+ key2Data = bytesRange(0x50, 32)
+ key3ID = []byte{0, 0, 0, 3, 0xcc}
+ chatA = types.NewJID("111111111", types.DefaultUserServer)
+ chatB = types.NewJID("222222222", types.DefaultUserServer)
+ chatC = types.NewJID("333333333", types.DefaultUserServer)
+ group = types.NewJID("120363000000000000", types.GroupServer)
+ ivCount = byte(0)
+)
+
+func nextIV() []byte {
+ ivCount++
+ return bytesRange(int(ivCount)*16, 16)
+}
+
+// record encrypts one mutation with a fixed IV, the way EncodePatch does with
+// a random one.
+func record(op waServerSync.SyncdMutation_SyncdOperation, keyID []byte, index []string, version int32, value *waSyncAction.SyncActionValue) *waServerSync.SyncdMutation {
+ keys := expandAppStateKeys(keyData(keyID))
+ indexBytes := must(json.Marshal(index))
+ content := must(proto.Marshal(&waSyncAction.SyncActionData{
+ Index: indexBytes,
+ Value: value,
+ Padding: []byte{},
+ Version: &version,
+ }))
+ iv := nextIV()
+ encrypted := append(iv, must(cbcutil.Encrypt(keys.ValueEncryption, iv, content))...)
+ valueMAC := generateContentMAC(op, encrypted, keyID, keys.ValueMAC)
+ return &waServerSync.SyncdMutation{
+ Operation: op.Enum(),
+ Record: &waServerSync.SyncdRecord{
+ Index: &waServerSync.SyncdIndex{Blob: concatAndHMAC(sha256.New, keys.Index, indexBytes)},
+ Value: &waServerSync.SyncdValue{Blob: append(encrypted, valueMAC...)},
+ KeyID: &waServerSync.KeyId{ID: keyID},
+ },
+ }
+}
+
+func keyData(keyID []byte) []byte {
+ switch {
+ case bytes.Equal(keyID, key1ID):
+ return key1Data
+ case bytes.Equal(keyID, key2ID):
+ return key2Data
+ }
+ panic("unknown key")
+}
+
+// snapshot builds a snapshot of SET records on top of the zero state.
+func snapshot(version uint64, keyID []byte, mutations []*waServerSync.SyncdMutation) *waServerSync.SyncdSnapshot {
+ state := appstate.HashState{Version: version}
+ must(updateHash(&state, mutations, func([]byte, int) ([]byte, error) { return nil, nil }))
+ records := make([]*waServerSync.SyncdRecord, len(mutations))
+ for i, mutation := range mutations {
+ records[i] = mutation.Record
+ }
+ return &waServerSync.SyncdSnapshot{
+ Version: &waServerSync.SyncdVersion{Version: &version},
+ Records: records,
+ Mac: generateSnapshotMAC(&state, name, expandAppStateKeys(keyData(keyID)).SnapshotMAC),
+ KeyID: &waServerSync.KeyId{ID: keyID},
+ }
+}
+
+// patch builds a patch on top of state, looking previous values up in the
+// patch and then in mem, as the decoder does.
+func patch(mem *memoryStore, state appstate.HashState, keyID []byte, mutations []*waServerSync.SyncdMutation) *waServerSync.SyncdPatch {
+ state.Version++
+ must(updateHash(&state, mutations, func(indexMAC []byte, maxIndex int) ([]byte, error) {
+ for i := maxIndex - 1; i >= 0; i-- {
+ if bytes.Equal(mutations[i].GetRecord().GetIndex().GetBlob(), indexMAC) {
+ if mutations[i].GetOperation() == waServerSync.SyncdMutation_SET {
+ value := mutations[i].GetRecord().GetValue().GetBlob()
+ return value[len(value)-32:], nil
+ }
+ return nil, nil
+ }
+ }
+ return mem.GetAppStateMutationMAC(context.Background(), string(name), indexMAC)
+ }))
+ keys := expandAppStateKeys(keyData(keyID))
+ result := &waServerSync.SyncdPatch{
+ Version: &waServerSync.SyncdVersion{Version: proto.Uint64(state.Version)},
+ Mutations: mutations,
+ SnapshotMAC: generateSnapshotMAC(&state, name, keys.SnapshotMAC),
+ KeyID: &waServerSync.KeyId{ID: keyID},
+ }
+ result.PatchMAC = generatePatchMAC(result, name, keys.PatchMAC, state.Version)
+ return result
+}
+
+func mutationVectors(mutations []appstate.Mutation) []mutationVector {
+ out := make([]mutationVector, len(mutations))
+ for i, mutation := range mutations {
+ var action *string
+ if mutation.Action != nil {
+ action = proto.String(marshal(mutation.Action))
+ }
+ out[i] = mutationVector{
+ KeyID: mutation.KeyID,
+ Operation: int32(mutation.Operation),
+ Action: action,
+ Version: mutation.Version,
+ Index: mutation.Index,
+ IndexMAC: mutation.IndexMAC,
+ ValueMAC: mutation.ValueMAC,
+ PatchVersion: mutation.PatchVersion,
+ }
+ }
+ return out
+}
+
+func lookups(mem *memoryStore, collection string, indexMACs [][]byte) []lookupVector {
+ out := make([]lookupVector, len(indexMACs))
+ for i, indexMAC := range indexMACs {
+ out[i] = lookupVector{IndexMAC: indexMAC, ValueMAC: must(mem.GetAppStateMutationMAC(context.Background(), collection, indexMAC))}
+ }
+ return out
+}
+
+func listVector(list *appstate.PatchList) patchListVector {
+ out := patchListVector{Patches: []string{}}
+ if list.Snapshot != nil {
+ out.Snapshot = proto.String(marshal(list.Snapshot))
+ }
+ for _, p := range list.Patches {
+ out.Patches = append(out.Patches, marshal(p))
+ }
+ return out
+}
+
+func stateOf(state appstate.HashState) stateVector {
+ return stateVector{Version: state.Version, Hash: state.Hash[:]}
+}
+
+func allIndexMACs(list *appstate.PatchList) [][]byte {
+ var out [][]byte
+ if list.Snapshot != nil {
+ for _, r := range list.Snapshot.Records {
+ out = append(out, r.GetIndex().GetBlob())
+ }
+ }
+ for _, p := range list.Patches {
+ for _, m := range p.Mutations {
+ out = append(out, m.GetRecord().GetIndex().GetBlob())
+ }
+ }
+ return out
+}
+
+func decodeStep(mem *memoryStore, list *appstate.PatchList, initial appstate.HashState) decodeStepVector {
+ mutations, state, err := newProcessor(mem).DecodePatches(context.Background(), list, initial, true)
+ if err != nil {
+ panic(err)
+ }
+ stored := must2(mem.GetAppStateVersion(context.Background(), string(list.Name)))
+ return decodeStepVector{
+ List: listVector(list),
+ InitialState: stateOf(initial),
+ Mutations: mutationVectors(mutations),
+ State: stateOf(state),
+ StoredState: stateOf(stored),
+ Lookups: lookups(mem, string(list.Name), allIndexMACs(list)),
+ }
+}
+
+func must2(version uint64, hash [128]byte, err error) appstate.HashState {
+ if err != nil {
+ panic(err)
+ }
+ return appstate.HashState{Version: version, Hash: hash}
+}
+
+func keysStore() *memoryStore {
+ return newMemoryStore(map[string][]byte{string(key1ID): key1Data, string(key2ID): key2Data})
+}
+
+func buildSequence() (sequenceVector, *appstate.PatchList) {
+ // The generator's own copy of the store, to build patches against.
+ builder := keysStore()
+ ctx := context.Background()
+ at := time.UnixMilli(1760000000123)
+
+ snapshotMutations := []*waServerSync.SyncdMutation{
+ record(waServerSync.SyncdMutation_SET, key1ID, []string{appstate.IndexMute, chatA.String()}, 2, &waSyncAction.SyncActionValue{
+ Timestamp: proto.Int64(at.UnixMilli()),
+ MuteAction: &waSyncAction.MuteAction{Muted: proto.Bool(true), MuteEndTimestamp: proto.Int64(-1)},
+ }),
+ record(waServerSync.SyncdMutation_SET, key1ID, []string{appstate.IndexStar, chatA.String(), "3EB0STARRED", "1", "0"}, 2, &waSyncAction.SyncActionValue{
+ Timestamp: proto.Int64(at.UnixMilli()),
+ StarAction: &waSyncAction.StarAction{Starred: proto.Bool(true)},
+ }),
+ record(waServerSync.SyncdMutation_SET, key2ID, []string{appstate.IndexMute, chatB.String()}, 2, &waSyncAction.SyncActionValue{
+ Timestamp: proto.Int64(at.UnixMilli()),
+ MuteAction: &waSyncAction.MuteAction{Muted: proto.Bool(true), MuteEndTimestamp: proto.Int64(1760003600000)},
+ }),
+ // An index that needs JSON escaping.
+ record(waServerSync.SyncdMutation_SET, key1ID, []string{appstate.IndexClearChat, group.String(), "<&>", "1"}, 6, &waSyncAction.SyncActionValue{
+ Timestamp: proto.Int64(at.UnixMilli()),
+ ClearChatAction: &waSyncAction.ClearChatAction{},
+ }),
+ }
+ ss := snapshot(3, key1ID, snapshotMutations)
+ firstList := &appstate.PatchList{Name: name, Snapshot: ss}
+ must3(newProcessor(builder).DecodePatches(ctx, firstList, appstate.HashState{}, true))
+ stateAfterSnapshot := must2(builder.GetAppStateVersion(ctx, string(name)))
+
+ newIndex := []string{appstate.IndexMute, chatC.String()}
+ patch4 := patch(builder, stateAfterSnapshot, key2ID, []*waServerSync.SyncdMutation{
+ // Overwrites the snapshot's mute of chat A (same key, so same index MAC).
+ record(waServerSync.SyncdMutation_SET, key1ID, []string{appstate.IndexMute, chatA.String()}, 2, &waSyncAction.SyncActionValue{
+ Timestamp: proto.Int64(at.UnixMilli() + 1000),
+ MuteAction: &waSyncAction.MuteAction{Muted: proto.Bool(false)},
+ }),
+ // Removes the snapshot's star.
+ record(waServerSync.SyncdMutation_REMOVE, key1ID, []string{appstate.IndexStar, chatA.String(), "3EB0STARRED", "1", "0"}, 2, &waSyncAction.SyncActionValue{
+ Timestamp: proto.Int64(at.UnixMilli() + 1000),
+ StarAction: &waSyncAction.StarAction{Starred: proto.Bool(false)},
+ }),
+ // Set and removed again within the patch.
+ record(waServerSync.SyncdMutation_SET, key2ID, newIndex, 2, &waSyncAction.SyncActionValue{
+ Timestamp: proto.Int64(at.UnixMilli() + 1000),
+ MuteAction: &waSyncAction.MuteAction{Muted: proto.Bool(true)},
+ }),
+ record(waServerSync.SyncdMutation_REMOVE, key2ID, newIndex, 2, &waSyncAction.SyncActionValue{
+ Timestamp: proto.Int64(at.UnixMilli() + 1000),
+ }),
+ // A REMOVE without a previous SET: only a warning.
+ record(waServerSync.SyncdMutation_REMOVE, key1ID, []string{appstate.IndexMute, "[email protected]"}, 2, &waSyncAction.SyncActionValue{
+ Timestamp: proto.Int64(at.UnixMilli() + 1000),
+ }),
+ })
+ must3(newProcessor(builder).DecodePatches(ctx, &appstate.PatchList{Name: name, Patches: []*waServerSync.SyncdPatch{patch4}}, stateAfterSnapshot, true))
+ stateAfter4 := must2(builder.GetAppStateVersion(ctx, string(name)))
+
+ // Patch 5 comes from EncodePatch itself, with random IVs.
+ encoded5 := must(newProcessor(builder).EncodePatch(ctx, key1ID, stateAfter4, appstate.PatchInfo{
+ Timestamp: at.Add(2 * time.Second),
+ Type: name,
+ Mutations: []appstate.MutationInfo{
+ appstate.BuildMuteAbs(chatB, false, nil).Mutations[0],
+ appstate.BuildStar(chatC, chatA, "3EB0OTHER", false, true).Mutations[0],
+ },
+ }))
+ var patch5 waServerSync.SyncdPatch
+ must(0, proto.Unmarshal(encoded5, &patch5))
+ patch5.Version = &waServerSync.SyncdVersion{Version: proto.Uint64(stateAfter4.Version + 1)}
+ firstList.Patches = []*waServerSync.SyncdPatch{patch4, &patch5}
+ must3(newProcessor(builder).DecodePatches(ctx, &appstate.PatchList{Name: name, Patches: []*waServerSync.SyncdPatch{&patch5}}, stateAfter4, true))
+ stateAfter5 := must2(builder.GetAppStateVersion(ctx, string(name)))
+
+ // A second fetch: removes the snapshot's mute of chat B, which is only
+ // in the store, and overwrites the clear chat.
+ patch6 := patch(builder, stateAfter5, key1ID, []*waServerSync.SyncdMutation{
+ record(waServerSync.SyncdMutation_REMOVE, key1ID, []string{appstate.IndexMute, chatB.String()}, 2, &waSyncAction.SyncActionValue{
+ Timestamp: proto.Int64(at.UnixMilli() + 3000),
+ }),
+ record(waServerSync.SyncdMutation_SET, key1ID, []string{appstate.IndexClearChat, group.String(), "<&>", "1"}, 6, &waSyncAction.SyncActionValue{
+ Timestamp: proto.Int64(at.UnixMilli() + 3000),
+ ClearChatAction: &waSyncAction.ClearChatAction{MessageRange: &waSyncAction.SyncActionMessageRange{LastMessageTimestamp: proto.Int64(1760000003)}},
+ }),
+ })
+ secondList := &appstate.PatchList{Name: name, HasMorePatches: false, Patches: []*waServerSync.SyncdPatch{patch6}}
+
+ // The expected values come from decoding everything with a fresh store.
+ mem := keysStore()
+ step1 := decodeStep(mem, firstList, appstate.HashState{})
+ step2 := decodeStep(mem, secondList, must2(mem.GetAppStateVersion(ctx, string(name))))
+ return sequenceVector{
+ Name: string(name),
+ Keys: []keyVector{{key1ID, key1Data}, {key2ID, key2Data}},
+ Steps: []decodeStepVector{step1, step2},
+ }, firstList
+}
+
+func must3(_ []appstate.Mutation, _ appstate.HashState, err error) {
+ if err != nil {
+ panic(err)
+ }
+}
+
+func decodeError(description string, list *appstate.PatchList, initial appstate.HashState) decodeErrorVector {
+ mem := keysStore()
+ proc := newProcessor(mem)
+ _, _, err := proc.DecodePatches(context.Background(), list, initial, true)
+ if err == nil {
+ panic("expected an error for " + description)
+ }
+ missing := proc.GetMissingKeyIDs(context.Background(), list)
+ missingKeys := make([]hexBytes, len(missing))
+ for i, keyID := range missing {
+ missingKeys[i] = keyID
+ }
+ return decodeErrorVector{
+ Description: description,
+ List: listVector(list),
+ InitialState: stateOf(initial),
+ Error: err.Error(),
+ KeyNotFound: errorsIsKeyNotFound(err),
+ MissingKeys: missingKeys,
+ }
+}
+
+func errorsIsKeyNotFound(err error) bool {
+ for err != nil {
+ if err == appstate.ErrKeyNotFound {
+ return true
+ }
+ unwrapper, ok := err.(interface{ Unwrap() error })
+ if !ok {
+ return false
+ }
+ err = unwrapper.Unwrap()
+ }
+ return false
+}
+
+func buildDecodeErrors(list *appstate.PatchList) []decodeErrorVector {
+ clone := func() *appstate.PatchList {
+ out := &appstate.PatchList{Name: list.Name, Snapshot: proto.Clone(list.Snapshot).(*waServerSync.SyncdSnapshot)}
+ for _, p := range list.Patches {
+ out.Patches = append(out.Patches, proto.Clone(p).(*waServerSync.SyncdPatch))
+ }
+ return out
+ }
+ var out []decodeErrorVector
+
+ badSnapshotMAC := clone()
+ badSnapshotMAC.Snapshot.Mac[0] ^= 1
+ out = append(out, decodeError("snapshot MAC mismatch", badSnapshotMAC, appstate.HashState{}))
+
+ badContent := clone()
+ badContent.Snapshot.Records[1].Value.Blob[20] ^= 1
+ out = append(out, decodeError("content MAC mismatch", badContent, appstate.HashState{}))
+
+ badIndex := clone()
+ badIndex.Snapshot.Records[0].Index.Blob[0] ^= 1
+ out = append(out, decodeError("index MAC mismatch", badIndex, appstate.HashState{}))
+
+ badPatchMAC := clone()
+ badPatchMAC.Patches[0].PatchMAC[0] ^= 1
+ out = append(out, decodeError("patch MAC mismatch", badPatchMAC, appstate.HashState{}))
+
+ badPatchLTHash := clone()
+ badPatchLTHash.Patches[1].SnapshotMAC[0] ^= 1
+ out = append(out, decodeError("patch LT hash mismatch", badPatchLTHash, appstate.HashState{}))
+
+ missingSnapshotKey := clone()
+ missingSnapshotKey.Snapshot.KeyID.ID = key3ID
+ out = append(out, decodeError("missing snapshot key", missingSnapshotKey, appstate.HashState{}))
+
+ missingRecordKey := clone()
+ missingRecordKey.Snapshot.Records[2].KeyID.ID = key3ID
+ missingRecordKey.Patches[1].KeyID.ID = []byte{0, 0, 0, 4}
+ out = append(out, decodeError("missing record key", missingRecordKey, appstate.HashState{}))
+ return out
+}
+
+func buildRecovery() recoveryVector {
+ mutations := []*waSyncdSnapshotRecovery.SyncdPlainTextRecord{
+ {
+ Value: &waSyncAction.SyncActionData{
+ Index: must(json.Marshal([]string{appstate.IndexPin, chatA.String()})),
+ Value: &waSyncAction.SyncActionValue{Timestamp: proto.Int64(1760000000000), PinAction: &waSyncAction.PinAction{Pinned: proto.Bool(true)}},
+ Version: proto.Int32(5),
+ },
+ KeyID: key1ID,
+ Mac: bytesRange(0x70, 32),
+ },
+ {
+ Value: &waSyncAction.SyncActionData{
+ Index: must(json.Marshal([]string{appstate.IndexArchive, chatB.String()})),
+ Value: &waSyncAction.SyncActionValue{Timestamp: proto.Int64(1760000000001), ArchiveChatAction: &waSyncAction.ArchiveChatAction{Archived: proto.Bool(true)}},
+ Version: proto.Int32(3),
+ },
+ KeyID: key2ID,
+ Mac: bytesRange(0x90, 32),
+ },
+ }
+ recovery := &waSyncdSnapshotRecovery.SyncdSnapshotRecovery{
+ Version: &waSyncdSnapshotRecovery.SyncdVersion{Version: proto.Uint64(42)},
+ CollectionName: proto.String(string(appstate.WAPatchRegularLow)),
+ MutationRecords: mutations,
+ CollectionLthash: bytesRange(0x01, 128),
+ }
+ var compressed bytes.Buffer
+ writer := gzip.NewWriter(&compressed)
+ must(writer.Write(must(proto.Marshal(recovery))))
+ must(0, writer.Close())
+
+ resp := &waE2E.PeerDataOperationRequestResponseMessage_PeerDataOperationResult_SyncDSnapshotFatalRecoveryResponse{
+ CollectionSnapshot: compressed.Bytes(),
+ IsCompressed: proto.Bool(true),
+ }
+ parsed := must(appstate.ParseRecovery(resp))
+ mem := keysStore()
+ result := must(newProcessor(mem).ProcessRecovery(context.Background(), parsed))
+ indexMACs := make([][]byte, len(result))
+ for i, mutation := range result {
+ indexMACs[i] = mutation.IndexMAC
+ }
+
+ invalid := proto.Clone(recovery).(*waSyncdSnapshotRecovery.SyncdSnapshotRecovery)
+ invalid.CollectionLthash = bytesRange(0, 127)
+ _, invalidErr := newProcessor(keysStore()).ProcessRecovery(context.Background(), invalid)
+
+ return recoveryVector{
+ CollectionSnapshot: compressed.Bytes(),
+ IsCompressed: true,
+ Name: parsed.GetCollectionName(),
+ Mutations: mutationVectors(result),
+ StoredState: stateOf(must2(mem.GetAppStateVersion(context.Background(), parsed.GetCollectionName()))),
+ Lookups: lookups(mem, parsed.GetCollectionName(), indexMACs),
+ InvalidLTHash: must(proto.Marshal(invalid)),
+ InvalidLTHashError: invalidErr.Error(),
+ }
+}
+
+func patchInfoVectorOf(info appstate.PatchInfo) patchInfoVector {
+ out := patchInfoVector{Type: string(info.Type)}
+ for _, mutation := range info.Mutations {
+ out.Mutations = append(out.Mutations, mutationInfoVector{
+ Index: mutation.Index,
+ Version: mutation.Version,
+ Value: marshal(mutation.Value),
+ })
+ }
+ return out
+}
+
+func buildBuilders() []patchInfoVector {
+ at := time.Unix(1760000000, 0)
+ key := &waCommon.MessageKey{RemoteJID: proto.String(chatA.String()), FromMe: proto.Bool(true), ID: proto.String("3EB0KEY")}
+ end := int64(1760003600000)
+ return []patchInfoVector{
+ patchInfoVectorOf(appstate.BuildMuteAbs(chatA, true, nil)),
+ patchInfoVectorOf(appstate.BuildMuteAbs(chatA, true, &end)),
+ patchInfoVectorOf(appstate.BuildMuteAbs(chatA, false, nil)),
+ patchInfoVectorOf(appstate.BuildPin(chatB, true)),
+ patchInfoVectorOf(appstate.BuildArchive(chatA, true, at, key)),
+ patchInfoVectorOf(appstate.BuildArchive(chatA, false, at, nil)),
+ patchInfoVectorOf(appstate.BuildMarkChatAsRead(chatB, false, at, key)),
+ patchInfoVectorOf(appstate.BuildLabelChat(chatA, "7", true)),
+ patchInfoVectorOf(appstate.BuildLabelMessage(chatA, "7", "3EB0MSG", false)),
+ patchInfoVectorOf(appstate.BuildLabelEdit("7", "Work", 3, false)),
+ patchInfoVectorOf(appstate.BuildSettingPushName("Wolf")),
+ patchInfoVectorOf(appstate.BuildStar(chatA, chatA, "3EB0MSG", true, true)),
+ patchInfoVectorOf(appstate.BuildStar(group, chatB, "3EB0MSG", false, false)),
+ patchInfoVectorOf(appstate.BuildDeleteChat(chatC, at, key, true)),
+ }
+}
+
+func main() {
+ out := flag.String("out", "../appstate/vectors.json", "where to write the vectors")
+ flag.Parse()
+
+ var v vectors
+ for i, base := range [][]byte{make([]byte, 128), bytesRange(0xf0, 128)} {
+ subtract := [][]byte{bytesRange(i, 32)}
+ add := [][]byte{bytesRange(0x40, 32), []byte("value mac")}
+ v.LTHash = append(v.LTHash, lthashVector{
+ Base: base, Subtract: []hexBytes{subtract[0]}, Add: []hexBytes{add[0], add[1]},
+ Result: lthash.WAPatchIntegrity.SubtractThenAdd(base, subtract, add),
+ })
+ }
+ for _, keyData := range [][]byte{key1Data, key2Data} {
+ keys := expandAppStateKeys(keyData)
+ v.ExpandedKeys = append(v.ExpandedKeys, expandedKeysVector{keyData, keys.Index, keys.ValueEncryption, keys.ValueMAC, keys.SnapshotMAC, keys.PatchMAC})
+ }
+ keys := expandAppStateKeys(key1Data)
+ state := appstate.HashState{Version: 0x0102030405060708}
+ copy(state.Hash[:], bytesRange(0x80, 128))
+ v.SnapshotMAC = append(v.SnapshotMAC, snapshotMACVector{state.Hash[:], state.Version, string(name), keys.SnapshotMAC, generateSnapshotMAC(&state, name, keys.SnapshotMAC)})
+ for _, op := range []waServerSync.SyncdMutation_SyncdOperation{waServerSync.SyncdMutation_SET, waServerSync.SyncdMutation_REMOVE, 255} {
+ data := bytesRange(int(op), 80)
+ v.ContentMAC = append(v.ContentMAC, contentMACVector{int32(op), data, key1ID, keys.ValueMAC, generateContentMAC(op, data, key1ID, keys.ValueMAC)})
+ }
+ indexBytes := must(json.Marshal([]string{appstate.IndexMute, chatA.String()}))
+ v.IndexMAC = append(v.IndexMAC, indexMACVector{keys.Index, indexBytes, concatAndHMAC(sha256.New, keys.Index, indexBytes)})
+ for _, index := range [][]string{
+ {appstate.IndexMute, chatA.String()},
+ {},
+ {"a<b>&c", "quote\"back\\slash", "\b\f\n\r\t\x01\x1f\x7f", "

", "ünï😀"},
+ } {
+ v.IndexJSON = append(v.IndexJSON, indexJSONVector{index, string(must(json.Marshal(index)))})
+ }
+ v.Builders = buildBuilders()
+
+ sequence, firstList := buildSequence()
+ v.Sequence = sequence
+ for _, p := range firstList.Patches {
+ v.PatchMAC = append(v.PatchMAC, patchMACVector{
+ Patch: marshal(p), Name: string(name), Key: expandAppStateKeys(keyData(p.GetKeyID().GetID())).PatchMAC,
+ Version: p.GetVersion().GetVersion(),
+ MAC: generatePatchMAC(p, name, expandAppStateKeys(keyData(p.GetKeyID().GetID())).PatchMAC, p.GetVersion().GetVersion()),
+ })
+ }
+ v.DecodeErrors = buildDecodeErrors(firstList)
+ v.Recovery = buildRecovery()
+
+ data := must(json.MarshalIndent(v, "", " "))
+ must(0, os.WriteFile(*out, append(data, '\n'), 0o644))
+ fmt.Fprintln(os.Stderr, "wrote", *out)
+}
diff --git a/crates/whatsmeow/testdata/generator/go.mod b/crates/whatsmeow/testdata/generator/go.mod
new file mode 100644
index 0000000000..f53456ce42
--- /dev/null
+++ b/crates/whatsmeow/testdata/generator/go.mod
@@ -0,0 +1,27 @@
+module whatsmeow-rs/testdata/generator
+
+go 1.26.7
+
+require (
+ go.mau.fi/whatsmeow v0.0.0-20261017175727-b2b1e71d45e2
+ google.golang.org/protobuf v1.36.12
+)
+
+require (
+ filippo.io/edwards25519 v1.2.0 // indirect
+ github.com/beeper/argo-go v1.1.2 // indirect
+ github.com/coder/websocket v1.8.15 // indirect
+ github.com/elliotchance/orderedmap/v3 v3.1.0 // indirect
+ github.com/google/uuid v1.6.0 // indirect
+ github.com/mattn/go-colorable v0.1.14 // indirect
+ github.com/mattn/go-isatty v0.0.20 // indirect
+ github.com/rs/zerolog v1.35.1 // indirect
+ github.com/vektah/gqlparser/v2 v2.5.27 // indirect
+ go.mau.fi/libsignal v0.2.2 // indirect
+ go.mau.fi/util v0.11.0 // indirect
+ golang.org/x/crypto v0.58.0 // indirect
+ golang.org/x/net v0.61.0 // indirect
+ golang.org/x/sync v0.24.0 // indirect
+ golang.org/x/sys v0.49.0 // indirect
+ golang.org/x/text v0.43.0 // indirect
+)
diff --git a/crates/whatsmeow/testdata/generator/go.sum b/crates/whatsmeow/testdata/generator/go.sum
new file mode 100644
index 0000000000..0dfc4efdbb
--- /dev/null
+++ b/crates/whatsmeow/testdata/generator/go.sum
@@ -0,0 +1,53 @@
+filippo.io/edwards25519 v1.2.0 h1:crnVqOiS4jqYleHd9vaKZ+HKtHfllngJIiOpNpoJsjo=
+filippo.io/edwards25519 v1.2.0/go.mod h1:xzAOLCNug/yB62zG1bQ8uziwrIqIuxhctzJT18Q77mc=
+github.com/agnivade/levenshtein v1.2.1 h1:EHBY3UOn1gwdy/VbFwgo4cxecRznFk7fKWN1KOX7eoM=
+github.com/agnivade/levenshtein v1.2.1/go.mod h1:QVVI16kDrtSuwcpd0p1+xMC6Z/VfhtCyDIjcwga4/DU=
+github.com/andreyvit/diff v0.0.0-20170406064948-c7f18ee00883 h1:bvNMNQO63//z+xNgfBlViaCIJKLlCJ6/fmUseuG0wVQ=
+github.com/andreyvit/diff v0.0.0-20170406064948-c7f18ee00883/go.mod h1:rCTlJbsFo29Kk6CurOXKm700vrz8f0KW0JNfpkRJY/8=
+github.com/beeper/argo-go v1.1.2 h1:UQI2G8F+NLfGTOmTUI0254pGKx/HUU/etbUGTJv91Fs=
+github.com/beeper/argo-go v1.1.2/go.mod h1:M+LJAnyowKVQ6Rdj6XYGEn+qcVFkb3R/MUpqkGR0hM4=
+github.com/coder/websocket v1.8.15 h1:6B2JPeOGlpff2Uz6vOEH1Vzpi0iUz20A+lPVhPHtNUA=
+github.com/coder/websocket v1.8.15/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg=
+github.com/elliotchance/orderedmap/v3 v3.1.0 h1:j4DJ5ObEmMBt/lcwIecKcoRxIQUEnw0L804lXYDt/pg=
+github.com/elliotchance/orderedmap/v3 v3.1.0/go.mod h1:G+Hc2RwaZvJMcS4JpGCOyViCnGeKf0bTYCGTO4uhjSo=
+github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
+github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
+github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
+github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
+github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE=
+github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
+github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
+github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
+github.com/petermattis/goid v0.0.0-20260918085751-abfca077860b h1:OzNsuVdSWGwXvWKTtChx9ve89k4cFJ6NxYM4Aw4/f+E=
+github.com/petermattis/goid v0.0.0-20260918085751-abfca077860b/go.mod h1:pxMtw7cyUw6B2bRH0ZBANSPg+AoSud1I1iyJHI69jH4=
+github.com/rs/zerolog v1.35.1 h1:m7xQeoiLIiV0BCEY4Hs+j2NG4Gp2o2KPKmhnnLiazKI=
+github.com/rs/zerolog v1.35.1/go.mod h1:EjML9kdfa/RMA7h/6z6pYmq1ykOuA8/mjWaEvGI+jcw=
+github.com/sergi/go-diff v1.3.1 h1:xkr+Oxo4BOQKmkn/B9eMK0g5Kg/983T9DqqPHwYqD+8=
+github.com/sergi/go-diff v1.3.1/go.mod h1:aMJSSKb2lpPvRNec0+w3fl7LP9IOFzdc9Pa4NFbPK1I=
+github.com/stretchr/testify v1.12.0 h1:K6Mr6jO9JICuend/5xzTM03ydSV3vdNRYAdPSukj8uI=
+github.com/stretchr/testify v1.12.0/go.mod h1:bOYBZb5qJ00vPzWfIqBUZPaxK8jWiXc6d3ErP4Ca9Gw=
+github.com/vektah/gqlparser/v2 v2.5.27 h1:RHPD3JOplpk5mP5JGX8RKZkt2/Vwj/PZv0HxTdwFp0s=
+github.com/vektah/gqlparser/v2 v2.5.27/go.mod h1:D1/VCZtV3LPnQrcPBeR/q5jkSQIPti0uYCP/RI0gIeo=
+go.mau.fi/libsignal v0.2.2 h1:QV+XdzQkm3x3aSG7FcqfGSZuFXz83pRZPBFaPygHbOU=
+go.mau.fi/libsignal v0.2.2/go.mod h1:CRlIQg2J8uYTfDFvNoO8/KcZjs5cey0vbc6oj/bssY0=
+go.mau.fi/util v0.11.0 h1:JNEpkVRxfTdJUC0DIGKiRlLKzl4G/qLX/eVzoP7QuwY=
+go.mau.fi/util v0.11.0/go.mod h1:04AEFVsc4zNdIkDC1gkdqbg/nZFolHY50pyXh2DSy7s=
+go.mau.fi/whatsmeow v0.0.0-20261017175727-b2b1e71d45e2 h1:/2ifXqR9Ls19CcIJ6ukwF8wpS7DJjhviJ3YJzwKa9+o=
+go.mau.fi/whatsmeow v0.0.0-20261017175727-b2b1e71d45e2/go.mod h1:iY4lm61nTLWsNiIE1EmHUZwhKGBeoV4dhnVE2uMtNoQ=
+golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54=
+golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w=
+golang.org/x/exp v0.0.0-20261014143641-f0251eb4aa3e h1:HgI6W1OolKK6tcV74is+rl9SMT0njsHlp0TbQiGXI/A=
+golang.org/x/exp v0.0.0-20261014143641-f0251eb4aa3e/go.mod h1:DBoxwWhjaW8DJJw/YeM4zpeOKMC1FMXSblsYy+1mFSw=
+golang.org/x/net v0.61.0 h1:RR+6j/BTBCrggOLugxa+66R8FvoN6MHlzDlZIbN9YFw=
+golang.org/x/net v0.61.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI=
+golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA=
+golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
+golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA=
+golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
+golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc=
+golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s=
+google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc=
+google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
+gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
+gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
diff --git a/crates/whatsmeow/testdata/generator/inpackage/appstate_client_vectors_test.go b/crates/whatsmeow/testdata/generator/inpackage/appstate_client_vectors_test.go
new file mode 100644
index 0000000000..236ff8e174
--- /dev/null
+++ b/crates/whatsmeow/testdata/generator/inpackage/appstate_client_vectors_test.go
@@ -0,0 +1,430 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+//go:build rustport
+
+package whatsmeow
+
+import (
+ "context"
+ "encoding/hex"
+ "fmt"
+ "testing"
+ "time"
+
+ "google.golang.org/protobuf/proto"
+
+ "go.mau.fi/whatsmeow/appstate"
+ waBinary "go.mau.fi/whatsmeow/binary"
+ "go.mau.fi/whatsmeow/proto/waCommon"
+ "go.mau.fi/whatsmeow/proto/waServerSync"
+ "go.mau.fi/whatsmeow/proto/waSyncAction"
+ "go.mau.fi/whatsmeow/socket"
+ "go.mau.fi/whatsmeow/store"
+ "go.mau.fi/whatsmeow/types/events"
+ waLog "go.mau.fi/whatsmeow/util/log"
+)
+
+// appStateMemory follows whatsmeow's sqlstore semantics for app state keys,
+// versions and mutation MACs.
+type appStateMemory struct {
+ keys map[string]store.AppStateSyncKey
+ latest []byte
+ versions map[string]appstate.HashState
+ macs map[string][]appStateStoredMAC
+}
+
+type appStateStoredMAC struct {
+ version uint64
+ mac store.AppStateMutationMAC
+}
+
+func newAppStateMemory() *appStateMemory {
+ return &appStateMemory{
+ keys: make(map[string]store.AppStateSyncKey),
+ versions: make(map[string]appstate.HashState),
+ macs: make(map[string][]appStateStoredMAC),
+ }
+}
+
+func (m *appStateMemory) PutAppStateSyncKey(_ context.Context, id []byte, key store.AppStateSyncKey) error {
+ m.keys[string(id)] = key
+ m.latest = id
+ return nil
+}
+
+func (m *appStateMemory) GetAppStateSyncKey(_ context.Context, id []byte) (*store.AppStateSyncKey, error) {
+ key, ok := m.keys[string(id)]
+ if !ok {
+ return nil, nil
+ }
+ return &key, nil
+}
+
+func (m *appStateMemory) GetLatestAppStateSyncKeyID(context.Context) ([]byte, error) {
+ return m.latest, nil
+}
+
+func (m *appStateMemory) GetAllAppStateSyncKeys(context.Context) ([]*store.AppStateSyncKey, error) {
+ return nil, nil
+}
+
+func (m *appStateMemory) PutAppStateVersion(_ context.Context, name string, version uint64, hash [128]byte) error {
+ m.versions[name] = appstate.HashState{Version: version, Hash: hash}
+ return nil
+}
+
+func (m *appStateMemory) GetAppStateVersion(_ context.Context, name string) (uint64, [128]byte, error) {
+ state := m.versions[name]
+ return state.Version, state.Hash, nil
+}
+
+func (m *appStateMemory) DeleteAppStateVersion(_ context.Context, name string) error {
+ delete(m.versions, name)
+ delete(m.macs, name)
+ return nil
+}
+
+func (m *appStateMemory) PutAppStateMutationMACs(_ context.Context, name string, version uint64, mutations []store.AppStateMutationMAC) error {
+ for _, mutation := range mutations {
+ m.macs[name] = append(m.macs[name], appStateStoredMAC{version: version, mac: mutation})
+ }
+ return nil
+}
+
+func (m *appStateMemory) DeleteAppStateMutationMACs(_ context.Context, name string, indexMACs [][]byte) error {
+ kept := m.macs[name][:0]
+ for _, stored := range m.macs[name] {
+ removed := false
+ for _, indexMAC := range indexMACs {
+ if string(indexMAC) == string(stored.mac.IndexMAC) {
+ removed = true
+ }
+ }
+ if !removed {
+ kept = append(kept, stored)
+ }
+ }
+ m.macs[name] = kept
+ return nil
+}
+
+func (m *appStateMemory) GetAppStateMutationMAC(_ context.Context, name string, indexMAC []byte) ([]byte, error) {
+ var found *appStateStoredMAC
+ for i, stored := range m.macs[name] {
+ if string(stored.mac.IndexMAC) == string(indexMAC) && (found == nil || stored.version >= found.version) {
+ found = &m.macs[name][i]
+ }
+ }
+ if found == nil {
+ return nil, nil
+ }
+ return found.mac.ValueMAC, nil
+}
+
+type noopContainer struct{}
+
+func (noopContainer) PutDevice(context.Context, *store.Device) error { return nil }
+func (noopContainer) DeleteDevice(context.Context, *store.Device) error { return nil }
+
+// appStateCaptureLogger records the nodes the client logs right before sending them.
+type appStateCaptureLogger struct {
+ waLog.Logger
+ nodes []waBinary.Node
+}
+
+func (c *appStateCaptureLogger) Debugf(_ string, args ...any) {
+ if len(args) == 1 {
+ if node, ok := args[0].(*waBinary.Node); ok {
+ c.nodes = append(c.nodes, *node)
+ }
+ }
+}
+
+func (c *appStateCaptureLogger) last(t *testing.T) waBinary.Node {
+ t.Helper()
+ if len(c.nodes) == 0 {
+ t.Fatal("no node was sent")
+ }
+ node := c.nodes[len(c.nodes)-1]
+ c.nodes = nil
+ return node
+}
+
+func protoHex(t *testing.T, message proto.Message) string {
+ t.Helper()
+ data, err := proto.MarshalOptions{Deterministic: true}.Marshal(message)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return hex.EncodeToString(data)
+}
+
+func appStateEventVector(t *testing.T, evt any) map[string]any {
+ t.Helper()
+ switch evt := evt.(type) {
+ case *events.AppState:
+ return map[string]any{"type": "AppState", "index": evt.Index, "action": protoHex(t, evt.SyncActionValue)}
+ case *events.Contact:
+ return map[string]any{"type": "Contact", "jid": evt.JID.String(), "timestamp": evt.Timestamp.UnixMilli(), "action": protoHex(t, evt.Action), "from_full_sync": evt.FromFullSync}
+ case *events.Mute:
+ return map[string]any{"type": "Mute", "jid": evt.JID.String(), "timestamp": evt.Timestamp.UnixMilli(), "action": protoHex(t, evt.Action), "from_full_sync": evt.FromFullSync}
+ case *events.Pin:
+ return map[string]any{"type": "Pin", "jid": evt.JID.String(), "timestamp": evt.Timestamp.UnixMilli(), "action": protoHex(t, evt.Action), "from_full_sync": evt.FromFullSync}
+ case *events.Archive:
+ return map[string]any{"type": "Archive", "jid": evt.JID.String(), "timestamp": evt.Timestamp.UnixMilli(), "action": protoHex(t, evt.Action), "from_full_sync": evt.FromFullSync}
+ case *events.MarkChatAsRead:
+ return map[string]any{"type": "MarkChatAsRead", "jid": evt.JID.String(), "timestamp": evt.Timestamp.UnixMilli(), "action": protoHex(t, evt.Action), "from_full_sync": evt.FromFullSync}
+ case *events.ClearChat:
+ return map[string]any{"type": "ClearChat", "jid": evt.JID.String(), "timestamp": evt.Timestamp.UnixMilli(), "action": protoHex(t, evt.Action), "from_full_sync": evt.FromFullSync, "delete_media": evt.DeleteMedia}
+ case *events.DeleteChat:
+ return map[string]any{"type": "DeleteChat", "jid": evt.JID.String(), "timestamp": evt.Timestamp.UnixMilli(), "action": protoHex(t, evt.Action), "from_full_sync": evt.FromFullSync, "delete_media": evt.DeleteMedia}
+ case *events.Star:
+ return map[string]any{"type": "Star", "jid": evt.ChatJID.String(), "sender_jid": evt.SenderJID.String(), "is_from_me": evt.IsFromMe, "message_id": evt.MessageID, "timestamp": evt.Timestamp.UnixMilli(), "action": protoHex(t, evt.Action), "from_full_sync": evt.FromFullSync}
+ case *events.DeleteForMe:
+ return map[string]any{"type": "DeleteForMe", "jid": evt.ChatJID.String(), "sender_jid": evt.SenderJID.String(), "is_from_me": evt.IsFromMe, "message_id": evt.MessageID, "timestamp": evt.Timestamp.UnixMilli(), "action": protoHex(t, evt.Action), "from_full_sync": evt.FromFullSync}
+ case *events.PushNameSetting:
+ return map[string]any{"type": "PushNameSetting", "timestamp": evt.Timestamp.UnixMilli(), "action": protoHex(t, evt.Action), "from_full_sync": evt.FromFullSync}
+ case *events.UnarchiveChatsSetting:
+ return map[string]any{"type": "UnarchiveChatsSetting", "timestamp": evt.Timestamp.UnixMilli(), "action": protoHex(t, evt.Action), "from_full_sync": evt.FromFullSync}
+ case *events.UserStatusMute:
+ return map[string]any{"type": "UserStatusMute", "jid": evt.JID.String(), "timestamp": evt.Timestamp.UnixMilli(), "action": protoHex(t, evt.Action), "from_full_sync": evt.FromFullSync}
+ case *events.LabelEdit:
+ return map[string]any{"type": "LabelEdit", "label_id": evt.LabelID, "timestamp": evt.Timestamp.UnixMilli(), "action": protoHex(t, evt.Action), "from_full_sync": evt.FromFullSync}
+ case *events.LabelAssociationChat:
+ return map[string]any{"type": "LabelAssociationChat", "jid": evt.JID.String(), "label_id": evt.LabelID, "timestamp": evt.Timestamp.UnixMilli(), "action": protoHex(t, evt.Action), "from_full_sync": evt.FromFullSync}
+ case *events.LabelAssociationMessage:
+ return map[string]any{"type": "LabelAssociationMessage", "jid": evt.JID.String(), "label_id": evt.LabelID, "message_id": evt.MessageID, "timestamp": evt.Timestamp.UnixMilli(), "action": protoHex(t, evt.Action), "from_full_sync": evt.FromFullSync}
+ default:
+ t.Fatalf("unexpected event %T", evt)
+ return nil
+ }
+}
+
+func appStateEventVectors(t *testing.T, evts []any) []map[string]any {
+ t.Helper()
+ out := make([]map[string]any, len(evts))
+ for i, evt := range evts {
+ out[i] = appStateEventVector(t, evt)
+ }
+ return out
+}
+
+func appStateKeyID(id byte) []byte {
+ return []byte{0, 0, 0, id}
+}
+
+func appStateKeyData(id byte) []byte {
+ data := make([]byte, 32)
+ for i := range data {
+ data[i] = id*0x10 + byte(i)
+ }
+ return data
+}
+
+// encodeAppStatePatch encodes the patch on top of the stored state and
+// decodes it, like a client receiving it, so the store holds the MACs the
+// next patch builds on.
+func encodeAppStatePatch(t *testing.T, proc *appstate.Processor, mem *appStateMemory, keyID []byte, info appstate.PatchInfo) ([]byte, []appstate.Mutation) {
+ t.Helper()
+ ctx := context.Background()
+ state := mem.versions[string(info.Type)]
+ encoded, err := proc.EncodePatch(ctx, keyID, state, info)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var patch waServerSync.SyncdPatch
+ if err = proto.Unmarshal(encoded, &patch); err != nil {
+ t.Fatal(err)
+ }
+ // The server assigns the version.
+ patch.Version = &waServerSync.SyncdVersion{Version: proto.Uint64(state.Version + 1)}
+ if encoded, err = proto.Marshal(&patch); err != nil {
+ t.Fatal(err)
+ }
+ mutations, newState, err := proc.DecodePatches(ctx, &appstate.PatchList{Name: info.Type, Patches: []*waServerSync.SyncdPatch{&patch}}, state, true)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if newState.Version != state.Version+1 {
+ t.Fatalf("unexpected version %d", newState.Version)
+ }
+ return encoded, mutations
+}
+
+func mutationsOf(infos ...appstate.PatchInfo) []appstate.MutationInfo {
+ var out []appstate.MutationInfo
+ for _, info := range infos {
+ out = append(out, info.Mutations...)
+ }
+ return out
+}
+
+func TestGenerateAppStateClient(t *testing.T) {
+ ctx := context.Background()
+ values := vectors{}
+
+ chat := mustJID(t, "[email protected]")
+ group := mustJID(t, "[email protected]")
+ sender := mustJID(t, "[email protected]")
+ contact := mustJID(t, "[email protected]")
+ timestamp := time.UnixMilli(1700000000123)
+ lastMessageKey := &waCommon.MessageKey{RemoteJID: proto.String(chat.String()), FromMe: proto.Bool(true), ID: proto.String("LASTMSG")}
+
+ mem := newAppStateMemory()
+ if err := mem.PutAppStateSyncKey(ctx, appStateKeyID(1), store.AppStateSyncKey{Data: appStateKeyData(1)}); err != nil {
+ t.Fatal(err)
+ }
+ device := &store.Device{AppStateKeys: mem, AppState: mem, Container: noopContainer{}, PushName: "Tester"}
+ cli := NewClient(device, nil)
+ cli.EmitAppStateEventsOnFullSync = true
+ proc := appstate.NewProcessor(device, waLog.Noop)
+
+ values["key_1_id"] = hex.EncodeToString(appStateKeyID(1))
+ values["key_1_data"] = hex.EncodeToString(appStateKeyData(1))
+ values["key_2_id"] = hex.EncodeToString(appStateKeyID(2))
+ values["key_2_data"] = hex.EncodeToString(appStateKeyData(2))
+
+ muteEnd := int64(1700003600000)
+ firstInfo := appstate.PatchInfo{
+ Timestamp: timestamp,
+ Type: appstate.WAPatchRegularHigh,
+ Mutations: mutationsOf(
+ appstate.BuildMuteAbs(chat, true, &muteEnd),
+ appstate.BuildPin(group, true),
+ appstate.BuildArchive(chat, true, timestamp, lastMessageKey),
+ appstate.BuildMarkChatAsRead(chat, true, timestamp, lastMessageKey),
+ appstate.BuildStar(group, sender, "STARRED", false, true),
+ appstate.BuildDeleteChat(chat, timestamp, lastMessageKey, true),
+ appstate.BuildLabelEdit("5", "Work", 3, false),
+ appstate.BuildLabelChat(chat, "5", true),
+ appstate.BuildLabelMessage(chat, "5", "LABELED", true),
+ appstate.BuildSettingPushName("New Name"),
+ ),
+ }
+ firstInfo.Mutations = append(firstInfo.Mutations,
+ appstate.MutationInfo{
+ Index: []string{appstate.IndexContact, contact.String()},
+ Version: 2,
+ Value: &waSyncAction.SyncActionValue{ContactAction: &waSyncAction.ContactAction{
+ FullName: proto.String("Contact Full"),
+ FirstName: proto.String("Contact"),
+ }},
+ },
+ appstate.MutationInfo{
+ Index: []string{appstate.IndexClearChat, chat.String(), "1", "1"},
+ Version: 6,
+ Value: &waSyncAction.SyncActionValue{ClearChatAction: &waSyncAction.ClearChatAction{}},
+ },
+ appstate.MutationInfo{
+ Index: []string{appstate.IndexDeleteMessageForMe, group.String(), "DELETED", "1", "0"},
+ Version: 3,
+ Value: &waSyncAction.SyncActionValue{DeleteMessageForMeAction: &waSyncAction.DeleteMessageForMeAction{
+ DeleteMedia: proto.Bool(true),
+ MessageTimestamp: proto.Int64(1699999999),
+ }},
+ },
+ appstate.MutationInfo{
+ Index: []string{appstate.IndexSettingUnarchiveChats},
+ Version: 4,
+ Value: &waSyncAction.SyncActionValue{UnarchiveChatsSetting: &waSyncAction.UnarchiveChatsSetting{UnarchiveChats: proto.Bool(true)}},
+ },
+ appstate.MutationInfo{
+ Index: []string{appstate.IndexUserStatusMute, sender.String()},
+ Version: 7,
+ Value: &waSyncAction.SyncActionValue{UserStatusMuteAction: &waSyncAction.UserStatusMuteAction{Muted: proto.Bool(true)}},
+ },
+ )
+ firstPatch, firstMutations := encodeAppStatePatch(t, proc, mem, appStateKeyID(1), firstInfo)
+ values["regular_high_v1_patch"] = hex.EncodeToString(firstPatch)
+ var firstEvents []any
+ if err := cli.collectEventsToDispatch(ctx, appstate.WAPatchRegularHigh, firstMutations, true, &firstEvents); err != nil {
+ t.Fatal(err)
+ }
+ values["regular_high_v1_events"] = appStateEventVectors(t, firstEvents)
+ if device.PushName != "New Name" {
+ t.Fatalf("push name not updated: %q", device.PushName)
+ }
+
+ secondInfo := appstate.PatchInfo{
+ Timestamp: timestamp.Add(time.Minute),
+ Type: appstate.WAPatchRegularHigh,
+ Mutations: mutationsOf(appstate.BuildMute(chat, false, 0), appstate.BuildPin(chat, false)),
+ }
+ secondPatch, secondMutations := encodeAppStatePatch(t, proc, mem, appStateKeyID(1), secondInfo)
+ values["regular_high_v2_patch"] = hex.EncodeToString(secondPatch)
+ var secondEvents []any
+ if err := cli.collectEventsToDispatch(ctx, appstate.WAPatchRegularHigh, secondMutations, false, &secondEvents); err != nil {
+ t.Fatal(err)
+ }
+ values["regular_high_v2_events"] = appStateEventVectors(t, secondEvents)
+
+ contactsInfo := appstate.PatchInfo{
+ Timestamp: timestamp,
+ Type: appstate.WAPatchCriticalUnblockLow,
+ Mutations: []appstate.MutationInfo{{
+ Index: []string{appstate.IndexContact, contact.String()},
+ Version: 2,
+ Value: &waSyncAction.SyncActionValue{ContactAction: &waSyncAction.ContactAction{
+ FullName: proto.String("Contact Full"),
+ FirstName: proto.String("Contact"),
+ }},
+ }, {
+ Index: []string{appstate.IndexPin, chat.String()},
+ Version: 5,
+ Value: &waSyncAction.SyncActionValue{PinAction: &waSyncAction.PinAction{Pinned: proto.Bool(true)}},
+ }},
+ }
+ contactsPatch, _ := encodeAppStatePatch(t, proc, mem, appStateKeyID(1), contactsInfo)
+ values["critical_unblock_low_v1_patch"] = hex.EncodeToString(contactsPatch)
+
+ // A patch with a key the client doesn't have yet.
+ otherMem := newAppStateMemory()
+ if err := otherMem.PutAppStateSyncKey(ctx, appStateKeyID(2), store.AppStateSyncKey{Data: appStateKeyData(2)}); err != nil {
+ t.Fatal(err)
+ }
+ otherProc := appstate.NewProcessor(&store.Device{AppStateKeys: otherMem, AppState: otherMem}, waLog.Noop)
+ missingKeyPatch, _ := encodeAppStatePatch(t, otherProc, otherMem, appStateKeyID(2), appstate.PatchInfo{
+ Timestamp: timestamp,
+ Type: appstate.WAPatchRegularLow,
+ Mutations: mutationsOf(appstate.BuildArchive(chat, true, timestamp, lastMessageKey)),
+ })
+ values["regular_low_v1_patch_key_2"] = hex.EncodeToString(missingKeyPatch)
+
+ // The requests, captured right before the (cancelled) send.
+ capture := &appStateCaptureLogger{Logger: waLog.Noop}
+ cli.sendLog = capture
+ cli.socket = &socket.NoiseSocket{}
+ cli.uniqueID = "1.2-"
+ cancelled, cancel := context.WithCancel(ctx)
+ cancel()
+
+ _, _ = cli.fetchAppStatePatches(cancelled, appstate.WAPatchRegularHigh, 0, true)
+ values["fetch_snapshot_iq"] = marshalHex(t, capture.last(t))
+ _, _ = cli.fetchAppStatePatches(cancelled, appstate.WAPatchRegularHigh, 1, false)
+ values["fetch_version_iq"] = marshalHex(t, capture.last(t))
+ _ = cli.MarkNotDirty(cancelled, "groups", time.Unix(1700000000, 0))
+ values["mark_not_dirty_iq"] = marshalHex(t, capture.last(t))
+
+ // Sending from a client that has only key 1 and no synced state.
+ sendMem := newAppStateMemory()
+ if err := sendMem.PutAppStateSyncKey(ctx, appStateKeyID(1), store.AppStateSyncKey{Data: appStateKeyData(1)}); err != nil {
+ t.Fatal(err)
+ }
+ sendCli := NewClient(&store.Device{AppStateKeys: sendMem, AppState: sendMem, Container: noopContainer{}}, nil)
+ sendCli.sendLog = capture
+ sendCli.socket = &socket.NoiseSocket{}
+ sendCli.uniqueID = "1.2-"
+ _ = sendCli.sendAppState(cancelled, appstate.BuildPin(chat, true), true)
+ sendNode := capture.last(t)
+ sendNode.Content.([]waBinary.Node)[0].Content.([]waBinary.Node)[0].Content.([]waBinary.Node)[0].Content = nil
+ values["send_app_state_iq_without_patch"] = marshalHex(t, sendNode)
+
+ recovery := BuildAppStateRecoveryRequest(appstate.WAPatchRegularHigh)
+ recovery.ProtocolMessage.PeerDataOperationRequestMessage.SyncdCollectionFatalRecoveryRequest.Timestamp = proto.Int64(1700000000)
+ values["recovery_request"] = protoHex(t, recovery)
+
+ writeVectors(t, "appstate_client.json", values)
+ fmt.Println("wrote appstate_client.json")
+}
diff --git a/crates/whatsmeow/testdata/generator/inpackage/generate.sh b/crates/whatsmeow/testdata/generator/inpackage/generate.sh
new file mode 100755
index 0000000000..f1d1a3ebfb
--- /dev/null
+++ b/crates/whatsmeow/testdata/generator/inpackage/generate.sh
@@ -0,0 +1,30 @@
+#!/usr/bin/env bash
+# Regenerates the test vectors under crates/whatsmeow/testdata from
+# whatsmeow's own code at the pinned revision. Test tooling only; not run in CI.
+#
+# Usage: generate.sh [path to a whatsmeow checkout]
+# Without a path, it clones whatsmeow into a temporary directory.
+set -euo pipefail
+
+REVISION=b2b1e71d45e2ff171153b025b5a42f475bb30ef8
+HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+OUT="$(cd "$HERE/../.." && pwd)"
+CHECKOUT="${1:-}"
+
+if [[ -z "$CHECKOUT" ]]; then
+ CHECKOUT="$(mktemp -d)/whatsmeow"
+ git clone --quiet https://github.com/tulir/whatsmeow "$CHECKOUT"
+fi
+git -C "$CHECKOUT" checkout --quiet "$REVISION"
+
+cleanup() {
+ for file in "$HERE"/*_test.go; do
+ rm -f "$CHECKOUT/zz_rustport_$(basename "$file")"
+ done
+}
+trap cleanup EXIT
+
+for file in "$HERE"/*_test.go; do
+ cp "$file" "$CHECKOUT/zz_rustport_$(basename "$file")"
+done
+(cd "$CHECKOUT" && VECTORS_OUT="$OUT" go test -count=1 -tags rustport -run 'TestGenerate' .)
diff --git a/crates/whatsmeow/testdata/generator/inpackage/group_vectors_test.go b/crates/whatsmeow/testdata/generator/inpackage/group_vectors_test.go
new file mode 100644
index 0000000000..c7c812bcfd
--- /dev/null
+++ b/crates/whatsmeow/testdata/generator/inpackage/group_vectors_test.go
@@ -0,0 +1,442 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+//go:build rustport
+
+package whatsmeow
+
+import (
+ "context"
+ "testing"
+
+ waBinary "go.mau.fi/whatsmeow/binary"
+ "go.mau.fi/whatsmeow/types"
+ "go.mau.fi/whatsmeow/types/events"
+)
+
+func participantVector(participant types.GroupParticipant) map[string]any {
+ var addRequest any
+ if participant.AddRequest != nil {
+ addRequest = map[string]any{
+ "code": participant.AddRequest.Code,
+ "expiration": unixOrZero(participant.AddRequest.Expiration),
+ }
+ }
+ return map[string]any{
+ "jid": jidString(participant.JID),
+ "phone_number": jidString(participant.PhoneNumber),
+ "lid": jidString(participant.LID),
+ "is_admin": participant.IsAdmin,
+ "is_super_admin": participant.IsSuperAdmin,
+ "display_name": participant.DisplayName,
+ "error": participant.Error,
+ "add_request": addRequest,
+ }
+}
+
+func groupInfoVector(group *types.GroupInfo) map[string]any {
+ participants := make([]map[string]any, 0, len(group.Participants))
+ for _, participant := range group.Participants {
+ participants = append(participants, participantVector(participant))
+ }
+ return map[string]any{
+ "jid": jidString(group.JID),
+ "owner_jid": jidString(group.OwnerJID),
+ "owner_pn": jidString(group.OwnerPN),
+ "name": group.Name,
+ "name_set_at": unixOrZero(group.NameSetAt),
+ "name_set_by": jidString(group.NameSetBy),
+ "name_set_by_pn": jidString(group.NameSetByPN),
+ "topic": group.Topic,
+ "topic_id": group.TopicID,
+ "topic_set_at": unixOrZero(group.TopicSetAt),
+ "topic_set_by": jidString(group.TopicSetBy),
+ "topic_set_by_pn": jidString(group.TopicSetByPN),
+ "topic_deleted": group.TopicDeleted,
+ "is_locked": group.IsLocked,
+ "is_announce": group.IsAnnounce,
+ "announce_version_id": group.AnnounceVersionID,
+ "is_ephemeral": group.IsEphemeral,
+ "disappearing_timer": group.DisappearingTimer,
+ "is_incognito": group.IsIncognito,
+ "is_parent": group.IsParent,
+ "default_membership_approval_mode": group.DefaultMembershipApprovalMode,
+ "linked_parent_jid": jidString(group.LinkedParentJID),
+ "is_default_sub_group": group.IsDefaultSubGroup,
+ "is_join_approval_required": group.IsJoinApprovalRequired,
+ "addressing_mode": string(group.AddressingMode),
+ "group_created": unixOrZero(group.GroupCreated),
+ "creator_country_code": group.CreatorCountryCode,
+ "participant_version_id": group.ParticipantVersionID,
+ "participants": participants,
+ "participant_count": group.ParticipantCount,
+ "member_add_mode": string(group.MemberAddMode),
+ "suspended": group.Suspended,
+ }
+}
+
+func linkChangeVector(change *types.GroupLinkChange) any {
+ if change == nil {
+ return nil
+ }
+ return map[string]any{
+ "type": string(change.Type),
+ "unlink_reason": string(change.UnlinkReason),
+ "group": map[string]any{
+ "jid": jidString(change.Group.JID),
+ "name": change.Group.Name,
+ "name_set_at": unixOrZero(change.Group.NameSetAt),
+ "is_default_sub_group": change.Group.IsDefaultSubGroup,
+ },
+ }
+}
+
+func groupChangeVector(evt *events.GroupInfo) map[string]any {
+ values := map[string]any{
+ "jid": jidString(evt.JID),
+ "notify": evt.Notify,
+ "sender": optionalJIDString(evt.Sender),
+ "sender_pn": optionalJIDString(evt.SenderPN),
+ "timestamp": unixOrZero(evt.Timestamp),
+ "name": nil,
+ "topic": nil,
+ "locked": nil,
+ "announce": nil,
+ "ephemeral": nil,
+ "membership_approval_mode": nil,
+ "delete": nil,
+ "link": linkChangeVector(evt.Link),
+ "unlink": linkChangeVector(evt.Unlink),
+ "new_invite_link": nil,
+ "prev_participant_version_id": evt.PrevParticipantVersionID,
+ "participant_version_id": evt.ParticipantVersionID,
+ "join_reason": evt.JoinReason,
+ "join": jidStrings(evt.Join),
+ "leave": jidStrings(evt.Leave),
+ "promote": jidStrings(evt.Promote),
+ "demote": jidStrings(evt.Demote),
+ "suspended": evt.Suspended,
+ "unsuspended": evt.Unsuspended,
+ }
+ if evt.Name != nil {
+ values["name"] = map[string]any{
+ "name": evt.Name.Name,
+ "name_set_at": unixOrZero(evt.Name.NameSetAt),
+ "name_set_by": jidString(evt.Name.NameSetBy),
+ "name_set_by_pn": jidString(evt.Name.NameSetByPN),
+ }
+ }
+ if evt.Topic != nil {
+ values["topic"] = map[string]any{
+ "topic": evt.Topic.Topic,
+ "topic_id": evt.Topic.TopicID,
+ "topic_set_at": unixOrZero(evt.Topic.TopicSetAt),
+ "topic_set_by": jidString(evt.Topic.TopicSetBy),
+ "topic_deleted": evt.Topic.TopicDeleted,
+ }
+ }
+ if evt.Locked != nil {
+ values["locked"] = evt.Locked.IsLocked
+ }
+ if evt.Announce != nil {
+ values["announce"] = map[string]any{
+ "is_announce": evt.Announce.IsAnnounce,
+ "announce_version_id": evt.Announce.AnnounceVersionID,
+ }
+ }
+ if evt.Ephemeral != nil {
+ values["ephemeral"] = map[string]any{
+ "is_ephemeral": evt.Ephemeral.IsEphemeral,
+ "disappearing_timer": evt.Ephemeral.DisappearingTimer,
+ }
+ }
+ if evt.MembershipApprovalMode != nil {
+ values["membership_approval_mode"] = evt.MembershipApprovalMode.IsJoinApprovalRequired
+ }
+ if evt.Delete != nil {
+ values["delete"] = map[string]any{
+ "deleted": evt.Delete.Deleted,
+ "delete_reason": evt.Delete.DeleteReason,
+ }
+ }
+ if evt.NewInviteLink != nil {
+ values["new_invite_link"] = *evt.NewInviteLink
+ }
+ unknown := make([]string, 0, len(evt.UnknownChanges))
+ for _, change := range evt.UnknownChanges {
+ unknown = append(unknown, change.Tag)
+ }
+ values["unknown_changes"] = unknown
+ return values
+}
+
+func TestGenerateGroups(t *testing.T) {
+ values := vectors{}
+ cli, logger := newCaptureClient(t)
+ ctx := context.Background()
+ group := mustJID(t, "[email protected]")
+ parent := mustJID(t, "[email protected]")
+
+ groupNode := waBinary.Node{
+ Tag: "group",
+ Attrs: waBinary.Attrs{
+ "id": "120363001234567890",
+ "creator": mustJID(t, "1111@lid"),
+ "creator_pn": mustJID(t, "[email protected]"),
+ "subject": "Team",
+ "s_t": "1700000001",
+ "s_o": mustJID(t, "2222@lid"),
+ "s_o_pn": mustJID(t, "[email protected]"),
+ "creation": "1700000000",
+ "creator_country_code": "US",
+ "a_v_id": "av1",
+ "p_v_id": "pv1",
+ "size": "4",
+ "addressing_mode": "lid",
+ },
+ Content: []waBinary.Node{
+ {Tag: "participant", Attrs: waBinary.Attrs{"jid": mustJID(t, "1111@lid"), "type": "superadmin", "phone_number": mustJID(t, "[email protected]")}},
+ {Tag: "participant", Attrs: waBinary.Attrs{"jid": mustJID(t, "2222@lid"), "type": "admin", "display_name": "+1∙∙∙∙∙∙∙∙22"}},
+ {Tag: "participant", Attrs: waBinary.Attrs{"jid": mustJID(t, "[email protected]"), "lid": mustJID(t, "3333@lid")}},
+ {Tag: "participant", Attrs: waBinary.Attrs{"jid": mustJID(t, "[email protected]"), "error": "403"}, Content: []waBinary.Node{
+ {Tag: "add_request", Attrs: waBinary.Attrs{"code": "abc", "expiration": "1700100000"}},
+ }},
+ {Tag: "description", Attrs: waBinary.Attrs{"id": "topic1", "participant": mustJID(t, "2222@lid"), "participant_pn": mustJID(t, "[email protected]"), "t": "1700000002"}, Content: []waBinary.Node{
+ {Tag: "body", Content: []byte("Hello")},
+ }},
+ {Tag: "announcement"},
+ {Tag: "locked"},
+ {Tag: "ephemeral", Attrs: waBinary.Attrs{"expiration": "86400"}},
+ {Tag: "member_add_mode", Content: []byte("admin_add")},
+ {Tag: "linked_parent", Attrs: waBinary.Attrs{"jid": parent}},
+ {Tag: "default_sub_group"},
+ {Tag: "parent", Attrs: waBinary.Attrs{"default_membership_approval_mode": "request_required"}},
+ {Tag: "incognito"},
+ {Tag: "membership_approval_mode"},
+ {Tag: "suspended"},
+ {Tag: "mystery"},
+ },
+ }
+ values["group_node"] = marshalHex(t, groupNode)
+ parsed, err := cli.parseGroupNode(&groupNode)
+ if err != nil {
+ t.Fatal(err)
+ }
+ values["group_info"] = groupInfoVector(parsed)
+ lidPairs, redactedPhones := cli.cacheGroupInfo(parsed, true)
+ values["group_lid_pairs"] = lidPairStrings(lidPairs)
+ redacted := make([][2]string, 0, len(redactedPhones))
+ for _, entry := range redactedPhones {
+ redacted = append(redacted, [2]string{entry.JID.String(), entry.RedactedPhone})
+ }
+ values["group_redacted_phones"] = redacted
+
+ brokenGroup := waBinary.Node{Tag: "group", Attrs: waBinary.Attrs{"subject": "No ID"}}
+ values["broken_group_node"] = marshalHex(t, brokenGroup)
+ brokenInfo, err := cli.parseGroupNode(&brokenGroup)
+ values["broken_group_info"] = groupInfoVector(brokenInfo)
+ values["broken_group_error"] = err.Error()
+
+ notificationAttrs := func(extra waBinary.Attrs) waBinary.Attrs {
+ attrs := waBinary.Attrs{
+ "from": group,
+ "type": "w:gp2",
+ "id": "notif",
+ "t": "1700000100",
+ "participant": mustJID(t, "1111@lid"),
+ "participant_pn": mustJID(t, "[email protected]"),
+ "notify": "Owner",
+ }
+ for key, value := range extra {
+ if value == nil {
+ delete(attrs, key)
+ } else {
+ attrs[key] = value
+ }
+ }
+ return attrs
+ }
+ notifications := []waBinary.Node{
+ {Tag: "notification", Attrs: notificationAttrs(nil), Content: []waBinary.Node{
+ {Tag: "add", Attrs: waBinary.Attrs{"reason": "invite", "prev_v_id": "1", "v_id": "2"}, Content: []waBinary.Node{
+ {Tag: "participant", Attrs: waBinary.Attrs{"jid": mustJID(t, "5555@lid"), "phone_number": mustJID(t, "[email protected]")}},
+ {Tag: "participant", Attrs: waBinary.Attrs{"jid": mustJID(t, "[email protected]"), "lid": mustJID(t, "6666@lid")}},
+ {Tag: "participant", Attrs: waBinary.Attrs{"jid": mustJID(t, "1111@lid")}},
+ }},
+ }},
+ {Tag: "notification", Attrs: notificationAttrs(nil), Content: []waBinary.Node{
+ {Tag: "remove", Attrs: waBinary.Attrs{"v_id": "3"}, Content: []waBinary.Node{
+ {Tag: "participant", Attrs: waBinary.Attrs{"jid": mustJID(t, "1111@lid")}},
+ }},
+ {Tag: "promote", Content: []waBinary.Node{
+ {Tag: "participant", Attrs: waBinary.Attrs{"jid": mustJID(t, "5555@lid")}},
+ {Tag: "participant", Attrs: waBinary.Attrs{"jid": mustJID(t, "2222@lid")}},
+ }},
+ }},
+ {Tag: "notification", Attrs: notificationAttrs(nil), Content: []waBinary.Node{
+ {Tag: "demote", Content: []waBinary.Node{
+ {Tag: "participant", Attrs: waBinary.Attrs{"jid": mustJID(t, "2222@lid"), "phone_number": mustJID(t, "[email protected]")}},
+ }},
+ {Tag: "subject", Attrs: waBinary.Attrs{"subject": "Renamed", "s_t": "1700000101", "s_o": mustJID(t, "1111@lid"), "s_o_pn": mustJID(t, "[email protected]")}},
+ {Tag: "description", Attrs: waBinary.Attrs{"id": "topic2"}, Content: []waBinary.Node{{Tag: "body", Content: []byte("New topic")}}},
+ {Tag: "announcement", Attrs: waBinary.Attrs{"v_id": "a2"}},
+ {Tag: "invite", Attrs: waBinary.Attrs{"code": "XyZ"}},
+ {Tag: "ephemeral", Attrs: waBinary.Attrs{"expiration": "604800"}},
+ {Tag: "locked"},
+ {Tag: "membership_approval_mode"},
+ {Tag: "suspended"},
+ {Tag: "mystery"},
+ }},
+ {Tag: "notification", Attrs: notificationAttrs(waBinary.Attrs{"participant_pn": nil}), Content: []waBinary.Node{
+ {Tag: "not_announcement", Attrs: waBinary.Attrs{"v_id": "a3"}},
+ {Tag: "not_ephemeral"},
+ {Tag: "unlocked"},
+ {Tag: "delete", Attrs: waBinary.Attrs{"reason": "admin"}},
+ {Tag: "description", Attrs: waBinary.Attrs{"id": "topic3"}, Content: []waBinary.Node{{Tag: "delete"}}},
+ {Tag: "unsuspended"},
+ {Tag: "link", Attrs: waBinary.Attrs{"link_type": "parent_group"}, Content: []waBinary.Node{
+ {Tag: "group", Attrs: waBinary.Attrs{"jid": parent, "subject": "Community", "s_t": "1700000003"}, Content: []waBinary.Node{{Tag: "default_sub_group"}}},
+ }},
+ {Tag: "unlink", Attrs: waBinary.Attrs{"unlink_type": "sub_group", "unlink_reason": "delete_parent"}, Content: []waBinary.Node{
+ {Tag: "group", Attrs: waBinary.Attrs{"id": "120363008888888888"}},
+ }},
+ }},
+ }
+ changes := make([]map[string]any, 0, len(notifications))
+ for _, notification := range notifications {
+ evt, lidPairs, redactedPhones, err := cli.parseGroupNotification(&notification)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(redactedPhones) != 0 {
+ t.Fatal("unexpected redacted phones in a group change")
+ }
+ changes = append(changes, map[string]any{
+ "node": marshalHex(t, notification),
+ "event": groupChangeVector(evt.(*events.GroupInfo)),
+ "lid_pairs": lidPairStrings(lidPairs),
+ })
+ }
+ values["group_changes"] = changes
+ cached := cli.groupCache[group]
+ values["cached_after_changes"] = map[string]any{
+ "addressing_mode": string(cached.AddressingMode),
+ "community_announcement_group": cached.CommunityAnnouncementGroup,
+ "read_only": cached.ReadOnly,
+ "members": jidStrings(cached.Members),
+ "admins": jidStrings(cached.Admins),
+ }
+
+ createNode := waBinary.Node{
+ Tag: "notification",
+ Attrs: notificationAttrs(waBinary.Attrs{"from": mustJID(t, "[email protected]"), "addressing_mode": "lid"}),
+ Content: []waBinary.Node{{
+ Tag: "create",
+ Attrs: waBinary.Attrs{"reason": "invite", "key": "ck1", "type": "new"},
+ Content: []waBinary.Node{{
+ Tag: "group",
+ Attrs: waBinary.Attrs{"id": "120363007777777777", "subject": "Fresh", "creation": "1700000050"},
+ Content: []waBinary.Node{
+ {Tag: "participant", Attrs: waBinary.Attrs{"jid": mustJID(t, "1111@lid"), "type": "superadmin", "phone_number": mustJID(t, "[email protected]"), "display_name": "+1∙∙11"}},
+ {Tag: "participant", Attrs: waBinary.Attrs{"jid": mustJID(t, "9876@lid")}},
+ },
+ }},
+ }},
+ }
+ values["create_node"] = marshalHex(t, createNode)
+ evt, lidPairs, redactedPhones, err := cli.parseGroupNotification(&createNode)
+ if err != nil {
+ t.Fatal(err)
+ }
+ joined := evt.(*events.JoinedGroup)
+ values["joined_group"] = map[string]any{
+ "reason": joined.Reason,
+ "type": joined.Type,
+ "create_key": joined.CreateKey,
+ "sender": optionalJIDString(joined.Sender),
+ "sender_pn": optionalJIDString(joined.SenderPN),
+ "notify": joined.Notify,
+ "group_info": groupInfoVector(&joined.GroupInfo),
+ }
+ values["joined_lid_pairs"] = lidPairStrings(lidPairs)
+ redacted = make([][2]string, 0, len(redactedPhones))
+ for _, entry := range redactedPhones {
+ redacted = append(redacted, [2]string{entry.JID.String(), entry.RedactedPhone})
+ }
+ values["joined_redacted_phones"] = redacted
+
+ failures := []waBinary.Node{
+ {Tag: "notification", Attrs: waBinary.Attrs{"from": group}},
+ {Tag: "notification", Attrs: notificationAttrs(nil), Content: []waBinary.Node{{Tag: "subject", Attrs: waBinary.Attrs{"s_t": "1"}}}},
+ {Tag: "notification", Attrs: notificationAttrs(nil), Content: []waBinary.Node{{Tag: "link", Attrs: waBinary.Attrs{"link_type": "sub_group"}}}},
+ {Tag: "notification", Attrs: notificationAttrs(nil), Content: []waBinary.Node{{Tag: "create"}}},
+ }
+ failureVectors := make([]map[string]any, 0, len(failures))
+ for _, failure := range failures {
+ _, _, _, err := cli.parseGroupNotification(&failure)
+ if err == nil {
+ t.Fatal("expected an error")
+ }
+ failureVectors = append(failureVectors, map[string]any{
+ "node": marshalHex(t, failure),
+ "error": err.Error(),
+ })
+ }
+ values["group_change_failures"] = failureVectors
+
+ inviter := mustJID(t, "[email protected]")
+ requests := map[string]string{}
+ requests["get_joined_groups"] = captureNode(t, logger, func() { _, _ = cli.GetJoinedGroups(ctx) })
+ requests["get_group_info"] = captureNode(t, logger, func() { _, _ = cli.GetGroupInfo(ctx, group) })
+ requests["create_group"] = captureNode(t, logger, func() {
+ req := ReqCreateGroup{
+ Name: "Team",
+ Participants: []types.JID{mustJID(t, "[email protected]"), mustJID(t, "5555:2@lid")},
+ MemberAddMode: types.GroupMemberAddModeAdmin,
+ }
+ req.IsLocked = true
+ req.IsAnnounce = true
+ req.IsEphemeral = true
+ req.DisappearingTimer = 604800
+ req.IsJoinApprovalRequired = true
+ req.LinkedParentJID = parent
+ _, _ = cli.CreateGroup(ctx, req)
+ })
+ requests["create_community"] = captureNode(t, logger, func() {
+ req := ReqCreateGroup{Name: "Community"}
+ req.IsParent = true
+ _, _ = cli.CreateGroup(ctx, req)
+ })
+ requests["leave_group"] = captureNode(t, logger, func() { _ = cli.LeaveGroup(ctx, group) })
+ requests["add_participants"] = captureNode(t, logger, func() {
+ _, _ = cli.UpdateGroupParticipants(ctx, group, []types.JID{mustJID(t, "5555@lid"), mustJID(t, "[email protected]")}, ParticipantChangeAdd)
+ })
+ requests["demote_participants"] = captureNode(t, logger, func() {
+ _, _ = cli.UpdateGroupParticipants(ctx, group, []types.JID{mustJID(t, "5555@lid")}, ParticipantChangeDemote)
+ })
+ requests["get_request_participants"] = captureNode(t, logger, func() { _, _ = cli.GetGroupRequestParticipants(ctx, group) })
+ requests["approve_request_participants"] = captureNode(t, logger, func() {
+ _, _ = cli.UpdateGroupRequestParticipants(ctx, group, []types.JID{mustJID(t, "5555@lid")}, ParticipantChangeApprove)
+ })
+ requests["set_group_photo"] = captureNode(t, logger, func() { _, _ = cli.SetGroupPhoto(ctx, group, []byte{0xff, 0xd8}) })
+ requests["remove_group_photo"] = captureNode(t, logger, func() { _, _ = cli.SetGroupPhoto(ctx, group, nil) })
+ requests["set_group_name"] = captureNode(t, logger, func() { _ = cli.SetGroupName(ctx, group, "New name") })
+ requests["set_group_topic"] = captureNode(t, logger, func() { _ = cli.SetGroupTopic(ctx, group, "prev1", "new1", "Topic") })
+ requests["delete_group_topic"] = captureNode(t, logger, func() { _ = cli.SetGroupTopic(ctx, group, "prev1", "new2", "") })
+ requests["set_group_locked"] = captureNode(t, logger, func() { _ = cli.SetGroupLocked(ctx, group, true) })
+ requests["set_group_unlocked"] = captureNode(t, logger, func() { _ = cli.SetGroupLocked(ctx, group, false) })
+ requests["set_group_announce"] = captureNode(t, logger, func() { _ = cli.SetGroupAnnounce(ctx, group, true) })
+ requests["set_group_not_announce"] = captureNode(t, logger, func() { _ = cli.SetGroupAnnounce(ctx, group, false) })
+ requests["reset_invite_link"] = captureNode(t, logger, func() { _, _ = cli.GetGroupInviteLink(ctx, group, true) })
+ requests["get_invite_link"] = captureNode(t, logger, func() { _, _ = cli.GetGroupInviteLink(ctx, group, false) })
+ requests["info_from_invite"] = captureNode(t, logger, func() { _, _ = cli.GetGroupInfoFromInvite(ctx, group, inviter, "code1", 1700000000) })
+ requests["join_with_invite"] = captureNode(t, logger, func() { _ = cli.JoinGroupWithInvite(ctx, group, inviter, "code1", 1700000000) })
+ requests["info_from_link"] = captureNode(t, logger, func() { _, _ = cli.GetGroupInfoFromLink(ctx, "https://chat.whatsapp.com/AbC?x=1") })
+ requests["join_with_link"] = captureNode(t, logger, func() { _, _ = cli.JoinGroupWithLink(ctx, "AbC") })
+ requests["join_approval_mode"] = captureNode(t, logger, func() { _ = cli.SetGroupJoinApprovalMode(ctx, group, true) })
+ requests["member_add_mode"] = captureNode(t, logger, func() { _ = cli.SetGroupMemberAddMode(ctx, group, types.GroupMemberAddModeAdmin) })
+ values["requests"] = requests
+
+ writeVectors(t, "group.json", values)
+}
diff --git a/crates/whatsmeow/testdata/generator/inpackage/message_vectors_test.go b/crates/whatsmeow/testdata/generator/inpackage/message_vectors_test.go
new file mode 100644
index 0000000000..cdd59a4e21
--- /dev/null
+++ b/crates/whatsmeow/testdata/generator/inpackage/message_vectors_test.go
@@ -0,0 +1,154 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+//go:build rustport
+
+package whatsmeow
+
+import (
+ "encoding/hex"
+ "testing"
+
+ "google.golang.org/protobuf/proto"
+
+ waBinary "go.mau.fi/whatsmeow/binary"
+ "go.mau.fi/whatsmeow/proto/waE2E"
+ "go.mau.fi/whatsmeow/store"
+ "go.mau.fi/whatsmeow/types"
+)
+
+func vectorClient(t *testing.T) *Client {
+ own := mustJID(t, "1234:[email protected]")
+ return &Client{Store: &store.Device{ID: &own, LID: mustJID(t, "9876:5@lid")}}
+}
+
+type sourceVector struct {
+ Node string `json:"node"`
+ Chat string `json:"chat"`
+ Sender string `json:"sender"`
+ FromMe bool `json:"from_me"`
+ Group bool `json:"group"`
+ Mode string `json:"addressing_mode"`
+ Alt string `json:"sender_alt"`
+ RecAlt string `json:"recipient_alt"`
+ ID string `json:"id"`
+ TS int64 `json:"t"`
+ Push string `json:"push_name"`
+ Type string `json:"type"`
+ Edit string `json:"edit"`
+ Media string `json:"media_type"`
+}
+
+func TestGenerateMessage(t *testing.T) {
+ cli := vectorClient(t)
+ nodes := []waBinary.Node{
+ {Tag: "message", Attrs: waBinary.Attrs{
+ "from": mustJID(t, "[email protected]"), "id": "A1", "t": "1700000000",
+ "type": "text", "notify": "Peer", "sender_lid": mustJID(t, "777@lid"),
+ }},
+ {Tag: "message", Attrs: waBinary.Attrs{
+ "from": mustJID(t, "[email protected]"), "participant": mustJID(t, "777:3@lid"),
+ "participant_pn": mustJID(t, "[email protected]"), "addressing_mode": "lid",
+ "id": "A2", "t": "1700000001", "type": "media", "edit": "1",
+ }, Content: []waBinary.Node{{Tag: "enc", Attrs: waBinary.Attrs{"mediatype": "image"}}}},
+ {Tag: "message", Attrs: waBinary.Attrs{
+ "from": mustJID(t, "1234:[email protected]"), "recipient": mustJID(t, "[email protected]"),
+ "peer_recipient_lid": mustJID(t, "777@lid"), "id": "A3", "t": "1700000002", "type": "text",
+ }},
+ {Tag: "message", Attrs: waBinary.Attrs{
+ "from": mustJID(t, "9876:2@lid"), "id": "A4", "t": "1700000003", "type": "text",
+ "peer_recipient_pn": mustJID(t, "[email protected]"),
+ }},
+ }
+ var sources []sourceVector
+ for _, node := range nodes {
+ info, err := cli.parseMessageInfo(&node)
+ if err != nil {
+ t.Fatal(err)
+ }
+ sources = append(sources, sourceVector{
+ Node: marshalHex(t, node), Chat: info.Chat.String(), Sender: info.Sender.String(),
+ FromMe: info.IsFromMe, Group: info.IsGroup, Mode: string(info.AddressingMode),
+ Alt: info.SenderAlt.String(), RecAlt: info.RecipientAlt.String(), ID: info.ID,
+ TS: info.Timestamp.Unix(), Push: info.PushName, Type: info.Type, Edit: string(info.Edit),
+ Media: info.MediaType,
+ })
+ }
+
+ type typeVector struct {
+ Message string `json:"message"`
+ Type string `json:"type"`
+ Media string `json:"media_type"`
+ Edit string `json:"edit"`
+ Plain string `json:"plaintext"`
+ DSM string `json:"device_sent_plaintext"`
+ }
+ messages := []*waE2E.Message{
+ {Conversation: proto.String("hi")},
+ {ImageMessage: &waE2E.ImageMessage{Caption: proto.String("pic")}},
+ {AudioMessage: &waE2E.AudioMessage{PTT: proto.Bool(true)}},
+ {VideoMessage: &waE2E.VideoMessage{GifPlayback: proto.Bool(true)}},
+ {ExtendedTextMessage: &waE2E.ExtendedTextMessage{Text: proto.String("x"), Title: proto.String("t")}},
+ {EphemeralMessage: &waE2E.FutureProofMessage{Message: &waE2E.Message{DocumentMessage: &waE2E.DocumentMessage{}}}},
+ {ReactionMessage: &waE2E.ReactionMessage{Text: proto.String("")}},
+ {PollUpdateMessage: &waE2E.PollUpdateMessage{}},
+ cli.BuildRevoke(mustJID(t, "[email protected]"), mustJID(t, "[email protected]"), "OLD"),
+ cli.BuildRevoke(mustJID(t, "[email protected]"), types.EmptyJID, "OLD"),
+ cli.BuildEdit(mustJID(t, "[email protected]"), "OLD", &waE2E.Message{Conversation: proto.String("new")}),
+ }
+ to := mustJID(t, "777@lid")
+ var types_ []typeVector
+ for _, msg := range messages {
+ // BuildEdit stamps the current time; zero it for a stable vector.
+ if msg.EditedMessage != nil {
+ msg.EditedMessage.Message.ProtocolMessage.TimestampMS = proto.Int64(1700000000000)
+ }
+ raw, err := proto.Marshal(msg)
+ if err != nil {
+ t.Fatal(err)
+ }
+ plain, dsm, err := marshalMessage(to, msg)
+ if err != nil {
+ t.Fatal(err)
+ }
+ types_ = append(types_, typeVector{
+ Message: hex.EncodeToString(raw), Type: getTypeFromMessage(msg),
+ Media: getMediaTypeFromMessage(msg), Edit: string(getEditAttribute(msg)),
+ Plain: hex.EncodeToString(plain), DSM: hex.EncodeToString(dsm),
+ })
+ }
+
+ var hashes []map[string]any
+ for _, list := range [][]string{
+ {"777:1@lid", "777@lid", "1234:[email protected]"},
+ {},
+ } {
+ var jids []types.JID
+ for _, j := range list {
+ jids = append(jids, mustJID(t, j))
+ }
+ hashes = append(hashes, map[string]any{"jids": list, "hash": participantListHashV2(jids)})
+ }
+
+ unpadded, err := unpadMessage([]byte("abc\x03\x03\x03"), 2)
+ if err != nil {
+ t.Fatal(err)
+ }
+ writeVectors(t, "message.json", vectors{
+ "sources": sources,
+ "types": types_,
+ "hashes": hashes,
+ "unpadded": hex.EncodeToString(unpadded),
+ "unavailable_req": marshalProtoHex(t, cli.BuildUnavailableMessageRequest(mustJID(t, "[email protected]"), mustJID(t, "777@lid"), "LOST")),
+ })
+}
+
+func marshalProtoHex(t *testing.T, msg proto.Message) string {
+ data, err := proto.Marshal(msg)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return hex.EncodeToString(data)
+}
diff --git a/crates/whatsmeow/testdata/generator/inpackage/pairing_media_vectors_test.go b/crates/whatsmeow/testdata/generator/inpackage/pairing_media_vectors_test.go
new file mode 100644
index 0000000000..bf31867842
--- /dev/null
+++ b/crates/whatsmeow/testdata/generator/inpackage/pairing_media_vectors_test.go
@@ -0,0 +1,152 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+//go:build rustport
+
+package whatsmeow
+
+import (
+ "context"
+ "crypto/aes"
+ "crypto/cipher"
+ "crypto/sha256"
+ "encoding/hex"
+ "testing"
+
+ "go.mau.fi/util/random"
+ "golang.org/x/crypto/pbkdf2"
+
+ waBinary "go.mau.fi/whatsmeow/binary"
+ "go.mau.fi/whatsmeow/types"
+ "go.mau.fi/whatsmeow/types/events"
+)
+
+// TestGeneratePairingMedia records phone-number pairing, media retry,
+// privacy settings and message secret vectors.
+func TestGeneratePairingMedia(t *testing.T) {
+ values := vectors{}
+
+ // generateCompanionEphemeralKey: its randomness is recoverable from the
+ // output (salt, IV, code), so Rust can recompute it.
+ keyPair, ephemeralKey, code := generateCompanionEphemeralKey()
+ values["companion_private"] = hex.EncodeToString(keyPair.Priv[:])
+ values["companion_ephemeral_key"] = hex.EncodeToString(ephemeralKey)
+ values["companion_linking_code"] = code
+ linkingCode, err := linkingBase32.DecodeString(code)
+ if err != nil {
+ t.Fatal(err)
+ }
+ values["companion_linking_code_bytes"] = hex.EncodeToString(linkingCode)
+
+ // handleCodePairNotification: the primary device wraps its ephemeral key
+ // with the same code; the client answers with the key bundle.
+ cli, logger := newCaptureClient(t)
+ cli.Store.IdentityKey = fixedKeyPair(0x20)
+ primaryEphemeral := fixedKeyPair(0x40)
+ primaryIdentity := fixedKeyPair(0x60)
+ _, wrappedPrimary, _ := func() (any, []byte, string) {
+ salt := random.Bytes(32)
+ iv := random.Bytes(16)
+ key := ctrEncryptForVector(code, salt, iv, primaryEphemeral.Pub[:])
+ return nil, append(append(salt, iv...), key...), ""
+ }()
+ cli.phoneLinkingCache.Store(&phoneLinkingCache{
+ jid: mustJID(t, "[email protected]"), keyPair: keyPair, linkingCode: code, pairingRef: "REF1",
+ })
+ notification := waBinary.Node{Tag: "notification", Content: []waBinary.Node{{
+ Tag: "link_code_companion_reg",
+ Content: []waBinary.Node{
+ {Tag: "link_code_pairing_ref", Content: []byte("REF1")},
+ {Tag: "link_code_pairing_wrapped_primary_ephemeral_pub", Content: wrappedPrimary},
+ {Tag: "primary_identity_pub", Content: primaryIdentity.Pub[:]},
+ },
+ }}}
+ values["code_pair_notification"] = marshalHex(t, notification)
+ values["code_pair_finish"] = captureNode(t, logger, func() {
+ _ = cli.handleCodePairNotification(context.Background(), &notification)
+ })
+ values["code_pair_adv_secret"] = hex.EncodeToString(cli.Store.AdvSecretKey)
+ values["code_pair_identity_private"] = hex.EncodeToString(cli.Store.IdentityKey.Priv[:])
+ values["code_pair_primary_identity"] = hex.EncodeToString(primaryIdentity.Pub[:])
+
+ // Media retry receipts and notifications.
+ mediaKey := fixedKeyPair(0x11).Pub[:]
+ ciphertext, iv, err := encryptMediaRetryReceipt("MSGID1", mediaKey)
+ if err != nil {
+ t.Fatal(err)
+ }
+ values["media_key"] = hex.EncodeToString(mediaKey)
+ values["media_retry_receipt_iv"] = hex.EncodeToString(iv)
+ values["media_retry_receipt_ciphertext"] = hex.EncodeToString(ciphertext)
+ retryNode := waBinary.Node{
+ Tag: "notification",
+ Attrs: waBinary.Attrs{"id": "MSGID1", "t": "1700000000", "type": "mediaretry"},
+ Content: []waBinary.Node{
+ {Tag: "rmr", Attrs: waBinary.Attrs{"jid": mustJID(t, "[email protected]"), "from_me": "false", "participant": mustJID(t, "777@lid")}},
+ {Tag: "encrypt", Content: []waBinary.Node{
+ {Tag: "enc_p", Content: ciphertext},
+ {Tag: "enc_iv", Content: iv},
+ }},
+ },
+ }
+ values["media_retry_notification"] = marshalHex(t, retryNode)
+ parsed, err := parseMediaRetryNotification(&retryNode)
+ if err != nil {
+ t.Fatal(err)
+ }
+ values["media_retry_chat"] = parsed.ChatID.String()
+ values["media_retry_sender"] = parsed.SenderID.String()
+ _, err = DecryptMediaRetryNotification(&events.MediaRetry{MessageID: "MSGID1", Error: &events.MediaRetryError{Code: 2}}, mediaKey)
+ values["media_retry_error_2"] = err.Error()
+ info := &types.MessageInfo{
+ MessageSource: types.MessageSource{Chat: mustJID(t, "[email protected]"), Sender: mustJID(t, "777@lid"), IsGroup: true},
+ ID: "MSGID1",
+ }
+ values["media_retry_send"] = captureNode(t, logger, func() {
+ _ = cli.SendMediaRetryReceipt(context.Background(), info, mediaKey)
+ })
+
+ // Privacy settings.
+ privacy := waBinary.Node{Tag: "privacy", Content: []waBinary.Node{
+ {Tag: "category", Attrs: waBinary.Attrs{"name": "readreceipts", "value": "none"}},
+ {Tag: "category", Attrs: waBinary.Attrs{"name": "last", "value": "contacts"}},
+ {Tag: "category", Attrs: waBinary.Attrs{"name": "unknown", "value": "x"}},
+ }}
+ values["privacy_node"] = marshalHex(t, privacy)
+ var settings types.PrivacySettings
+ evt := cli.parsePrivacySettings(&privacy, &settings)
+ values["privacy_read_receipts"] = string(settings.ReadReceipts)
+ values["privacy_last_seen"] = string(settings.LastSeen)
+ values["privacy_changed"] = []bool{evt.ReadReceiptsChanged, evt.LastSeenChanged, evt.GroupAddChanged}
+
+ // Message secret keys.
+ secret := fixedKeyPair(0x70).Pub[:]
+ for _, useCase := range []MsgSecretType{EncSecretReaction, EncSecretPollVote, EncSecretMessageEdit} {
+ key, additional := generateMsgSecretKey(useCase, mustJID(t, "9876:5@lid"), "ORIG1", mustJID(t, "777:2@lid"), secret)
+ values["msg_secret_key_"+string(useCase)] = hex.EncodeToString(key)
+ values["msg_secret_ad_"+string(useCase)] = hex.EncodeToString(additional)
+ }
+ values["msg_secret"] = hex.EncodeToString(secret)
+ values["poll_option_hashes"] = hexList(HashPollOptions([]string{"yes", "no"}))
+
+ writeVectors(t, "pairing_media.json", values)
+}
+
+func hexList(items [][]byte) []string {
+ out := make([]string, len(items))
+ for i, item := range items {
+ out[i] = hex.EncodeToString(item)
+ }
+ return out
+}
+
+// ctrEncryptForVector wraps a key the way the primary device does, playing
+// the phone in the code pairing vector.
+func ctrEncryptForVector(code string, salt, iv, data []byte) []byte {
+ key := pbkdf2.Key([]byte(code), salt, 2<<16, 32, sha256.New)
+ block, _ := aes.NewCipher(key)
+ out := make([]byte, len(data))
+ cipher.NewCTR(block, iv).XORKeyStream(out, data)
+ return out
+}
diff --git a/crates/whatsmeow/testdata/generator/inpackage/prekeys_vectors_test.go b/crates/whatsmeow/testdata/generator/inpackage/prekeys_vectors_test.go
new file mode 100644
index 0000000000..7bd34ecfe5
--- /dev/null
+++ b/crates/whatsmeow/testdata/generator/inpackage/prekeys_vectors_test.go
@@ -0,0 +1,88 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+//go:build rustport
+
+package whatsmeow
+
+import (
+ "encoding/binary"
+ "encoding/hex"
+ "testing"
+
+ waBinary "go.mau.fi/whatsmeow/binary"
+ "go.mau.fi/whatsmeow/util/keys"
+)
+
+func TestGeneratePreKeys(t *testing.T) {
+ values := vectors{}
+ preKey := &keys.PreKey{KeyPair: *fixedKeyPair(0x30), KeyID: 0x010203}
+ values["pre_key_node"] = marshalHex(t, preKeyToNode(preKey))
+ var signature [64]byte
+ for i := range signature {
+ signature[i] = 0x77
+ }
+ signedPreKey := &keys.PreKey{KeyPair: *fixedKeyPair(0x50), KeyID: 1, Signature: &signature}
+ values["signed_pre_key_node"] = marshalHex(t, preKeyToNode(signedPreKey))
+
+ var registration [4]byte
+ binary.BigEndian.PutUint32(registration[:], 0x0a0b0c0d)
+ identity := fixedKeyPair(0x10).Pub[:]
+ oneTime := &keys.PreKey{KeyPair: *fixedKeyPair(0x60), KeyID: 42}
+ user := waBinary.Node{
+ Tag: "user",
+ Attrs: waBinary.Attrs{"jid": mustJID(t, "1234:[email protected]")},
+ Content: []waBinary.Node{
+ {Tag: "registration", Content: registration[:]},
+ {Tag: "type", Content: []byte{5}},
+ {Tag: "identity", Content: identity},
+ preKeyToNode(oneTime),
+ preKeyToNode(signedPreKey),
+ },
+ }
+ values["bundle_user_node"] = marshalHex(t, user)
+ bundle, err := nodeToPreKeyBundle(7, user)
+ if err != nil {
+ t.Fatal(err)
+ }
+ values["bundle_registration_id"] = bundle.RegistrationID()
+ values["bundle_pre_key_id"] = bundle.PreKeyID().Value
+ preKeyPublic := bundle.PreKey().PublicKey()
+ values["bundle_pre_key_public"] = hex.EncodeToString(preKeyPublic[:])
+ values["bundle_signed_pre_key_id"] = bundle.SignedPreKeyID()
+ signedPublic := bundle.SignedPreKey().PublicKey()
+ values["bundle_signed_pre_key_public"] = hex.EncodeToString(signedPublic[:])
+ bundleSignature := bundle.SignedPreKeySignature()
+ values["bundle_signed_pre_key_signature"] = hex.EncodeToString(bundleSignature[:])
+ identityPublic := bundle.IdentityKey().PublicKey().PublicKey()
+ values["bundle_identity_key"] = hex.EncodeToString(identityPublic[:])
+
+ withoutPreKey := waBinary.Node{
+ Tag: "user",
+ Attrs: user.Attrs,
+ Content: []waBinary.Node{
+ {Tag: "registration", Content: registration[:]},
+ {Tag: "keys", Content: []waBinary.Node{
+ {Tag: "identity", Content: identity},
+ preKeyToNode(signedPreKey),
+ }},
+ },
+ }
+ values["bundle_without_pre_key_node"] = marshalHex(t, withoutPreKey)
+ if bundle, err = nodeToPreKeyBundle(7, withoutPreKey); err != nil || bundle.PreKeyID() != nil && !bundle.PreKeyID().IsEmpty {
+ t.Fatalf("expected a bundle without prekey: %v", err)
+ }
+
+ errorNode := waBinary.Node{
+ Tag: "user",
+ Attrs: user.Attrs,
+ Content: []waBinary.Node{
+ {Tag: "error", Attrs: waBinary.Attrs{"code": "404", "text": "item-not-found"}},
+ },
+ }
+ values["bundle_error_node"] = marshalHex(t, errorNode)
+ _, err = nodeToPreKeyBundle(7, errorNode)
+ values["bundle_error_message"] = err.Error()
+ writeVectors(t, "prekeys.json", values)
+}
diff --git a/crates/whatsmeow/testdata/generator/inpackage/presence_vectors_test.go b/crates/whatsmeow/testdata/generator/inpackage/presence_vectors_test.go
new file mode 100644
index 0000000000..25ed50ca18
--- /dev/null
+++ b/crates/whatsmeow/testdata/generator/inpackage/presence_vectors_test.go
@@ -0,0 +1,32 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+//go:build rustport
+
+package whatsmeow
+
+import (
+ "context"
+ "testing"
+
+ "go.mau.fi/whatsmeow/types"
+)
+
+func TestGeneratePresence(t *testing.T) {
+ values := vectors{}
+ cli, logger := newCaptureClient(t)
+ ctx := context.Background()
+ jid := mustJID(t, "[email protected]")
+ requests := map[string]string{}
+ requests["unavailable"] = captureNode(t, logger, func() { _ = cli.SendPresence(ctx, types.PresenceUnavailable) })
+ requests["subscribe"] = captureNode(t, logger, func() { _ = cli.SubscribePresence(ctx, jid) })
+ requests["composing_audio"] = captureNode(t, logger, func() {
+ _ = cli.SendChatPresence(ctx, jid, types.ChatPresenceComposing, types.ChatPresenceMediaAudio)
+ })
+ requests["paused"] = captureNode(t, logger, func() {
+ _ = cli.SendChatPresence(ctx, jid, types.ChatPresencePaused, types.ChatPresenceMediaAudio)
+ })
+ values["requests"] = requests
+ writeVectors(t, "presence.json", values)
+}
diff --git a/crates/whatsmeow/testdata/generator/inpackage/user_vectors_test.go b/crates/whatsmeow/testdata/generator/inpackage/user_vectors_test.go
new file mode 100644
index 0000000000..304d9496de
--- /dev/null
+++ b/crates/whatsmeow/testdata/generator/inpackage/user_vectors_test.go
@@ -0,0 +1,121 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+//go:build rustport
+
+package whatsmeow
+
+import (
+ "context"
+ "testing"
+
+ waBinary "go.mau.fi/whatsmeow/binary"
+ "go.mau.fi/whatsmeow/types"
+ "go.mau.fi/whatsmeow/types/events"
+)
+
+func TestGenerateUsers(t *testing.T) {
+ values := vectors{}
+ cli, logger := newCaptureClient(t)
+ ctx := context.Background()
+
+ pnUser := mustJID(t, "[email protected]")
+ lidUser := mustJID(t, "6666@lid")
+ deviceList := func(devices ...waBinary.Node) waBinary.Node {
+ return waBinary.Node{Tag: "devices", Content: []waBinary.Node{{
+ Tag: "device-list",
+ Content: devices,
+ }}}
+ }
+ device := func(attrs waBinary.Attrs) waBinary.Node {
+ return waBinary.Node{Tag: "device", Attrs: attrs}
+ }
+ cases := []struct {
+ user types.JID
+ node waBinary.Node
+ }{
+ {pnUser, deviceList(
+ device(waBinary.Attrs{"id": "0"}),
+ device(waBinary.Attrs{"id": "3", "key-index": "2"}),
+ device(waBinary.Attrs{"id": "99", "is_hosted": "true"}),
+ waBinary.Node{Tag: "key-index-list", Attrs: waBinary.Attrs{"id": "7"}},
+ device(waBinary.Attrs{"key-index": "1"}),
+ device(waBinary.Attrs{"id": "70000"}),
+ )},
+ {lidUser, deviceList(
+ device(waBinary.Attrs{"id": "0"}),
+ device(waBinary.Attrs{"id": "12", "is_hosted": "true"}),
+ )},
+ {pnUser, waBinary.Node{Tag: "devices"}},
+ {pnUser, waBinary.Node{Tag: "not-devices", Content: []waBinary.Node{{Tag: "device-list", Content: []waBinary.Node{device(waBinary.Attrs{"id": "1"})}}}}},
+ }
+ deviceLists := make([]map[string]any, 0, len(cases))
+ for _, deviceCase := range cases {
+ devices := parseDeviceList(deviceCase.user, deviceCase.node)
+ deviceLists = append(deviceLists, map[string]any{
+ "user": deviceCase.user.String(),
+ "node": marshalHex(t, deviceCase.node),
+ "devices": jidStrings(devices),
+ "hash": participantListHashV2(devices),
+ })
+ }
+ values["device_lists"] = deviceLists
+
+ blocklistNode := waBinary.Node{
+ Tag: "list",
+ Attrs: waBinary.Attrs{"dhash": "1700000000", "addressing_mode": "lid"},
+ Content: []waBinary.Node{
+ {Tag: "item", Attrs: waBinary.Attrs{"jid": lidUser, "pn_jid": pnUser, "active": "true"}},
+ {Tag: "item", Attrs: waBinary.Attrs{"jid": mustJID(t, "7777@lid")}},
+ {Tag: "item", Attrs: waBinary.Attrs{"action": "block"}},
+ },
+ }
+ values["blocklist_node"] = marshalHex(t, blocklistNode)
+ blocklist, mappings := cli.parseBlocklist(&blocklistNode)
+ items := make([]map[string]any, 0, len(blocklist.Items))
+ for _, item := range blocklist.Items {
+ items = append(items, map[string]any{
+ "lid": item.LID.String(),
+ "pn": item.PN.String(),
+ "active": item.Active,
+ })
+ }
+ values["blocklist"] = map[string]any{
+ "d_hash": blocklist.DHash,
+ "addressing_mode": string(blocklist.AddressingMode),
+ "items": items,
+ }
+ values["blocklist_lid_pairs"] = lidPairStrings(mappings)
+
+ requests := map[string]string{}
+ requests["get_user_devices"] = captureNode(t, logger, func() {
+ _, _ = cli.GetUserDevices(ctx, []types.JID{pnUser, mustJID(t, "6666:3@lid")})
+ })
+ requests["is_on_whatsapp"] = captureNode(t, logger, func() { _, _ = cli.IsOnWhatsApp(ctx, []string{"+15551234567"}) })
+ requests["get_user_info"] = captureNode(t, logger, func() { _, _ = cli.GetUserInfo(ctx, []types.JID{pnUser, lidUser}) })
+ requests["profile_picture_preview"] = captureNode(t, logger, func() {
+ _, _ = cli.GetProfilePictureInfo(ctx, pnUser, &GetProfilePictureParams{Preview: true, ExistingID: "old"})
+ })
+ requests["profile_picture_full"] = captureNode(t, logger, func() {
+ _, _ = cli.GetProfilePictureInfo(ctx, pnUser, &GetProfilePictureParams{
+ CommonGID: mustJID(t, "[email protected]"),
+ InviteCode: "inv",
+ PersonaID: "persona",
+ })
+ })
+ requests["profile_picture_community"] = captureNode(t, logger, func() {
+ _, _ = cli.GetProfilePictureInfo(ctx, mustJID(t, "[email protected]"), &GetProfilePictureParams{IsCommunity: true})
+ })
+ requests["get_blocklist"] = captureNode(t, logger, func() { _, _ = cli.GetBlocklist(ctx, "") })
+ requests["get_blocklist_with_hash"] = captureNode(t, logger, func() { _, _ = cli.GetBlocklist(ctx, "hash1") })
+ requests["block_lid"] = captureNode(t, logger, func() {
+ _, _ = cli.UpdateBlocklist(ctx, lidUser, events.BlocklistChangeActionBlock, "hash1")
+ })
+ requests["unblock_lid"] = captureNode(t, logger, func() {
+ _, _ = cli.UpdateBlocklist(ctx, lidUser, events.BlocklistChangeActionUnblock, "")
+ })
+ values["requests"] = requests
+
+ writeVectors(t, "user.json", values)
+}
diff --git a/crates/whatsmeow/testdata/generator/inpackage/vectors_test.go b/crates/whatsmeow/testdata/generator/inpackage/vectors_test.go
new file mode 100644
index 0000000000..a7d60d8ee6
--- /dev/null
+++ b/crates/whatsmeow/testdata/generator/inpackage/vectors_test.go
@@ -0,0 +1,184 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+//go:build rustport
+
+// Test vectors for the Rust port, generated by whatsmeow's own unexported
+// code. generate.sh copies the *_test.go files of this directory into a
+// whatsmeow checkout (package whatsmeow) and runs them with the rustport
+// tag; they write JSON files into $VECTORS_OUT. The tag keeps them out of
+// the generator module's own builds.
+package whatsmeow
+
+import (
+ "encoding/hex"
+ "encoding/json"
+ "maps"
+ "os"
+ "path/filepath"
+ "testing"
+ "time"
+
+ waBinary "go.mau.fi/whatsmeow/binary"
+ "go.mau.fi/whatsmeow/socket"
+ "go.mau.fi/whatsmeow/store"
+ "go.mau.fi/whatsmeow/types"
+ "go.mau.fi/whatsmeow/util/keys"
+ waLog "go.mau.fi/whatsmeow/util/log"
+)
+
+type vectors map[string]any
+
+func writeVectors(t *testing.T, name string, values vectors) {
+ t.Helper()
+ out := os.Getenv("VECTORS_OUT")
+ if out == "" {
+ t.Skip("VECTORS_OUT not set")
+ }
+ data, err := json.MarshalIndent(values, "", " ")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = os.WriteFile(filepath.Join(out, name), append(data, '\n'), 0o644); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func fixedKeyPair(start byte) *keys.KeyPair {
+ var private [32]byte
+ for i := range private {
+ private[i] = start + byte(i)
+ }
+ return keys.NewKeyPairFromPrivateKey(private)
+}
+
+func marshalHex(t *testing.T, node waBinary.Node) string {
+ t.Helper()
+ data, err := waBinary.Marshal(node)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return hex.EncodeToString(data)
+}
+
+func mustJID(t *testing.T, jid string) types.JID {
+ t.Helper()
+ parsed, err := types.ParseJID(jid)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return parsed
+}
+
+// captureLogger records the node sendNodeAndGetData logs right before it
+// hands the payload to the socket.
+type captureLogger struct {
+ node *waBinary.Node
+}
+
+func (l *captureLogger) Warnf(string, ...any) {}
+func (l *captureLogger) Errorf(string, ...any) {}
+func (l *captureLogger) Infof(string, ...any) {}
+func (l *captureLogger) Debugf(_ string, args ...any) {
+ if len(args) == 1 {
+ if node, ok := args[0].(*waBinary.Node); ok {
+ copied := *node
+ l.node = &copied
+ }
+ }
+}
+func (l *captureLogger) Sub(string) waLog.Logger { return l }
+
+// newCaptureClient returns a logged-in client (1234:[email protected],
+// 9876:5@lid) with empty stores whose socket is a zero NoiseSocket: sending
+// logs the node and then panics before anything leaves the process, and
+// captureNode recovers.
+func newCaptureClient(t *testing.T) (*Client, *captureLogger) {
+ t.Helper()
+ empty := &store.NoopStore{}
+ id := mustJID(t, "1234:[email protected]")
+ device := *store.NoopDevice
+ device.ID = &id
+ device.LID = mustJID(t, "9876:5@lid")
+ device.PushName = "Tester"
+ device.Identities = empty
+ device.Sessions = empty
+ device.PreKeys = empty
+ device.SenderKeys = empty
+ device.AppStateKeys = empty
+ device.AppState = empty
+ device.Contacts = empty
+ device.ChatSettings = empty
+ device.MsgSecrets = empty
+ device.PrivacyTokens = empty
+ device.NCTSalt = empty
+ device.EventBuffer = empty
+ device.LIDs = empty
+ device.Container = empty
+ logger := &captureLogger{}
+ cli := NewClient(&device, waLog.Noop)
+ cli.sendLog = logger
+ cli.socket = &socket.NoiseSocket{}
+ return cli, logger
+}
+
+// captureNode runs send and returns the node it sent, with the iq id and
+// usync sid replaced by ID and SID (they come from a random prefix).
+func captureNode(t *testing.T, logger *captureLogger, send func()) string {
+ t.Helper()
+ logger.node = nil
+ func() {
+ defer func() { _ = recover() }()
+ send()
+ }()
+ if logger.node == nil {
+ t.Fatal("nothing was sent")
+ }
+ node := *logger.node
+ if node.Tag == "iq" {
+ node.Attrs = maps.Clone(node.Attrs)
+ node.Attrs["id"] = "ID"
+ if children := node.GetChildren(); len(children) == 1 && children[0].Tag == "usync" {
+ usync := children[0]
+ usync.Attrs = maps.Clone(usync.Attrs)
+ usync.Attrs["sid"] = "SID"
+ node.Content = []waBinary.Node{usync}
+ }
+ }
+ return marshalHex(t, node)
+}
+
+func jidString(jid types.JID) string {
+ return jid.String()
+}
+
+func optionalJIDString(jid *types.JID) any {
+ if jid == nil {
+ return nil
+ }
+ return jid.String()
+}
+
+func jidStrings(jids []types.JID) []string {
+ out := make([]string, 0, len(jids))
+ for _, jid := range jids {
+ out = append(out, jid.String())
+ }
+ return out
+}
+
+func unixOrZero(ts time.Time) int64 {
+ if ts.IsZero() {
+ return 0
+ }
+ return ts.Unix()
+}
+
+func lidPairStrings(pairs []store.LIDMapping) [][2]string {
+ out := make([][2]string, 0, len(pairs))
+ for _, pair := range pairs {
+ out = append(out, [2]string{pair.LID.String(), pair.PN.String()})
+ }
+ return out
+}
diff --git a/crates/whatsmeow/testdata/generator/media/main.go b/crates/whatsmeow/testdata/generator/media/main.go
new file mode 100644
index 0000000000..074b325343
--- /dev/null
+++ b/crates/whatsmeow/testdata/generator/media/main.go
@@ -0,0 +1,570 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+// Command media writes ../media/vectors.json: expected values for the Rust
+// port of whatsmeow's mediaconn.go, download.go, download-to-file.go and
+// upload.go, produced by running whatsmeow's own code at the pinned revision.
+//
+// Uploads and downloads go through a real whatsmeow Client against local TLS
+// test servers; the media connection cache is filled in with reflection so no
+// IQ is sent. Unexported helpers are reached with go:linkname.
+package main
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "flag"
+ "fmt"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "reflect"
+ "strings"
+ "sync"
+ "time"
+ "unsafe"
+
+ "go.mau.fi/whatsmeow"
+ waBinary "go.mau.fi/whatsmeow/binary"
+ "go.mau.fi/whatsmeow/proto/waE2E"
+ "go.mau.fi/whatsmeow/store"
+ "go.mau.fi/whatsmeow/types"
+)
+
+//go:linkname getMediaKeys go.mau.fi/whatsmeow.getMediaKeys
+func getMediaKeys(mediaKey []byte, appInfo whatsmeow.MediaType) (iv, cipherKey, macKey, refKey []byte)
+
+//go:linkname mediaTypeToMMSType go.mau.fi/whatsmeow.mediaTypeToMMSType
+var mediaTypeToMMSType map[whatsmeow.MediaType]string
+
+//go:linkname validateMedia go.mau.fi/whatsmeow.validateMedia
+func validateMedia(iv, file, macKey, mac []byte) error
+
+type hexBytes []byte
+
+func (h hexBytes) MarshalJSON() ([]byte, error) {
+ if h == nil {
+ return []byte("null"), nil
+ }
+ return json.Marshal(hex.EncodeToString(h))
+}
+
+type mediaKeys struct {
+ MediaType string `json:"media_type"`
+ MMSType string `json:"mms_type"`
+ MediaKey hexBytes `json:"media_key"`
+ IV hexBytes `json:"iv"`
+ CipherKey hexBytes `json:"cipher_key"`
+ MACKey hexBytes `json:"mac_key"`
+ RefKey hexBytes `json:"ref_key"`
+}
+
+type validateCase struct {
+ IV hexBytes `json:"iv"`
+ File hexBytes `json:"file"`
+ MACKey hexBytes `json:"mac_key"`
+ MAC hexBytes `json:"mac"`
+ Error string `json:"error"`
+}
+
+type request struct {
+ Host int `json:"host"`
+ Method string `json:"method"`
+ RequestURI string `json:"request_uri"`
+ Headers map[string]string `json:"headers"`
+ Body hexBytes `json:"body"`
+}
+
+type uploadVector struct {
+ MediaType string `json:"media_type"`
+ Plaintext hexBytes `json:"plaintext"`
+ ResponseJSON string `json:"response_json"`
+ Requests []request `json:"requests"`
+
+ URL string `json:"url"`
+ DirectPath string `json:"direct_path"`
+ Handle string `json:"handle"`
+ ObjectID string `json:"object_id"`
+ MediaKey hexBytes `json:"media_key"`
+ FileEncSHA256 hexBytes `json:"file_enc_sha256"`
+ FileSHA256 hexBytes `json:"file_sha256"`
+ FileLength uint64 `json:"file_length"`
+}
+
+// response is what a fake host answers for one request.
+type response struct {
+ Status int `json:"status"`
+ RetryAfter string `json:"retry_after,omitempty"`
+ // Body is the served body; null means the uploaded ciphertext.
+ Body hexBytes `json:"body"`
+}
+
+type downloadVector struct {
+ Name string `json:"name"`
+ DirectPath string `json:"direct_path"`
+ MediaKey hexBytes `json:"media_key"`
+ FileSHA256 hexBytes `json:"file_sha256"`
+ FileEncSHA256 hexBytes `json:"file_enc_sha256"`
+ // Responses per host, consumed in order; the last one repeats.
+ Responses [][]response `json:"responses"`
+ Requests []request `json:"requests"`
+ Data hexBytes `json:"data"`
+ Error string `json:"error"`
+ ToFile bool `json:"to_file"`
+}
+
+type deleteVector struct {
+ MediaType string `json:"media_type"`
+ DirectPath string `json:"direct_path"`
+ EncFileHash hexBytes `json:"enc_file_hash"`
+ EncHandle string `json:"enc_handle"`
+ CompanionMetaNonce string `json:"companion_meta_nonce"`
+ Requests []request `json:"requests"`
+}
+
+type mediaConnHost struct {
+ Hostname string `json:"hostname"`
+}
+
+type mediaConnVector struct {
+ Response hexBytes `json:"response"`
+ Auth string `json:"auth"`
+ AuthTTL int `json:"auth_ttl"`
+ TTL int `json:"ttl"`
+ MaxBuckets int `json:"max_buckets"`
+ Hosts []mediaConnHost `json:"hosts"`
+ Request hexBytes `json:"request"`
+}
+
+type vectors struct {
+ Auth string `json:"auth"`
+ UserAgent string `json:"user_agent"`
+ MediaKeys []mediaKeys `json:"media_keys"`
+ Validate []validateCase `json:"validate"`
+ Upload uploadVector `json:"upload"`
+ Newsletter uploadVector `json:"upload_newsletter"`
+ Downloads []downloadVector `json:"downloads"`
+ Delete deleteVector `json:"delete"`
+ MediaConn mediaConnVector `json:"media_conn"`
+}
+
+func seq(start byte, length int) []byte {
+ out := make([]byte, length)
+ for i := range out {
+ out[i] = start + byte(i)
+ }
+ return out
+}
+
+func must(err error) {
+ if err != nil {
+ panic(err)
+ }
+}
+
+// fakeHost is one media host: it records requests and answers from a script.
+type fakeHost struct {
+ index int
+ server *httptest.Server
+ lock sync.Mutex
+ script []response
+ requests *[]request
+ allLock *sync.Mutex
+ uploadAns string
+}
+
+func (h *fakeHost) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+ body, _ := io.ReadAll(r.Body)
+ headers := map[string]string{}
+ for _, name := range []string{"Origin", "Referer", "User-Agent", "Companion_user_secret", "Content-Length"} {
+ if value := r.Header.Get(name); value != "" {
+ headers[name] = value
+ }
+ }
+ if r.ContentLength > 0 {
+ headers["Content-Length"] = fmt.Sprint(r.ContentLength)
+ }
+ h.allLock.Lock()
+ *h.requests = append(*h.requests, request{
+ Host: h.index,
+ Method: r.Method,
+ RequestURI: r.RequestURI,
+ Headers: headers,
+ Body: body,
+ })
+ h.allLock.Unlock()
+
+ h.lock.Lock()
+ var answer response
+ if len(h.script) > 0 {
+ answer = h.script[0]
+ if len(h.script) > 1 {
+ h.script = h.script[1:]
+ }
+ } else {
+ answer = response{Status: 200, Body: []byte(h.uploadAns)}
+ }
+ h.lock.Unlock()
+ if answer.RetryAfter != "" {
+ w.Header().Set("Retry-After", answer.RetryAfter)
+ }
+ w.WriteHeader(answer.Status)
+ _, _ = w.Write(answer.Body)
+}
+
+type harness struct {
+ cli *whatsmeow.Client
+ hosts []*fakeHost
+ requests []request
+ lock sync.Mutex
+}
+
+func newHarness(hostCount int, auth string) *harness {
+ h := &harness{}
+ device := &store.Device{CompanionMetaNonce: "companion-nonce"}
+ h.cli = whatsmeow.NewClient(device, nil)
+ h.cli.UserAgent = "whatsmeow-rs-test/1.0"
+ var conn whatsmeow.MediaConn
+ conn.Auth = auth
+ conn.TTL = 3600
+ conn.FetchedAt = time.Now()
+ for i := range hostCount {
+ host := &fakeHost{index: i, requests: &h.requests, allLock: &h.lock}
+ host.server = httptest.NewTLSServer(host)
+ h.hosts = append(h.hosts, host)
+ conn.Hosts = append(conn.Hosts, whatsmeow.MediaConnHost{Hostname: strings.TrimPrefix(host.server.URL, "https://")})
+ }
+ h.cli.SetMediaHTTPClient(h.hosts[0].server.Client())
+ field := reflect.ValueOf(h.cli).Elem().FieldByName("mediaConnCache")
+ reflect.NewAt(field.Type(), unsafe.Pointer(field.UnsafeAddr())).Elem().Set(reflect.ValueOf(&conn))
+ return h
+}
+
+func (h *harness) close() {
+ for _, host := range h.hosts {
+ host.server.Close()
+ }
+}
+
+func (h *harness) takeRequests() []request {
+ h.lock.Lock()
+ defer h.lock.Unlock()
+ out := h.requests
+ h.requests = nil
+ return out
+}
+
+func errString(err error) string {
+ if err == nil {
+ return ""
+ }
+ return err.Error()
+}
+
+// fileBuffer is an in-memory whatsmeow.File.
+type fileBuffer struct {
+ data []byte
+ pos int64
+}
+
+func (f *fileBuffer) Read(p []byte) (int, error) {
+ if f.pos >= int64(len(f.data)) {
+ return 0, io.EOF
+ }
+ n := copy(p, f.data[f.pos:])
+ f.pos += int64(n)
+ return n, nil
+}
+
+func (f *fileBuffer) Write(p []byte) (int, error) {
+ n, err := f.WriteAt(p, f.pos)
+ f.pos += int64(n)
+ return n, err
+}
+
+func (f *fileBuffer) Seek(offset int64, whence int) (int64, error) {
+ switch whence {
+ case io.SeekStart:
+ f.pos = offset
+ case io.SeekCurrent:
+ f.pos += offset
+ case io.SeekEnd:
+ f.pos = int64(len(f.data)) + offset
+ }
+ return f.pos, nil
+}
+
+func (f *fileBuffer) ReadAt(p []byte, off int64) (int, error) {
+ if off >= int64(len(f.data)) {
+ return 0, io.EOF
+ }
+ n := copy(p, f.data[off:])
+ if n < len(p) {
+ return n, io.EOF
+ }
+ return n, nil
+}
+
+func (f *fileBuffer) WriteAt(p []byte, off int64) (int, error) {
+ if end := off + int64(len(p)); end > int64(len(f.data)) {
+ f.data = append(f.data, make([]byte, end-int64(len(f.data)))...)
+ }
+ return copy(f.data[off:], p), nil
+}
+
+func (f *fileBuffer) Truncate(size int64) error {
+ f.data = f.data[:size]
+ return nil
+}
+
+func (f *fileBuffer) Stat() (os.FileInfo, error) {
+ return fileInfo{size: int64(len(f.data))}, nil
+}
+
+// fileInfo reports only the size, which is all cbcutil.DecryptFile reads.
+type fileInfo struct {
+ os.FileInfo
+ size int64
+}
+
+func (i fileInfo) Size() int64 {
+ return i.size
+}
+
+func main() {
+ out := flag.String("out", "../media/vectors.json", "output file")
+ flag.Parse()
+ ctx := context.Background()
+
+ var v vectors
+ v.Auth = "AUTH token/with+odd=chars~*!"
+ v.UserAgent = "whatsmeow-rs-test/1.0"
+
+ mediaKey := seq(0x20, 32)
+ for _, mediaType := range []whatsmeow.MediaType{
+ whatsmeow.MediaImage, whatsmeow.MediaVideo, whatsmeow.MediaAudio, whatsmeow.MediaDocument,
+ whatsmeow.MediaHistory, whatsmeow.MediaAppState, whatsmeow.MediaStickerPack, whatsmeow.MediaLinkThumbnail,
+ } {
+ iv, cipherKey, macKey, refKey := getMediaKeys(mediaKey, mediaType)
+ v.MediaKeys = append(v.MediaKeys, mediaKeys{
+ MediaType: string(mediaType),
+ MMSType: mediaTypeToMMSType[mediaType],
+ MediaKey: mediaKey,
+ IV: iv,
+ CipherKey: cipherKey,
+ MACKey: macKey,
+ RefKey: refKey,
+ })
+ }
+
+ iv, _, macKey, _ := getMediaKeys(mediaKey, whatsmeow.MediaImage)
+ file := seq(0x50, 48)
+
+ // Upload: a real Client.Upload against a fake host.
+ plaintext := []byte(strings.Repeat("whatsmeow media upload ", 5))
+ upload := newHarness(2, v.Auth)
+ responseJSON := `{"url":"https://mmg.whatsapp.net/o1/v/t62.7118-24/f1/m231/up.enc?ccb=9-4","direct_path":"/o1/v/t62.7118-24/f1/m231/up.enc?ccb=9-4&oh=01_Q5&oe=68","handle":"","object_id":"obj-1","extra":true}`
+ for _, host := range upload.hosts {
+ host.uploadAns = responseJSON
+ }
+ resp, err := upload.cli.Upload(ctx, plaintext, whatsmeow.MediaImage)
+ must(err)
+ v.Upload = uploadVector{
+ MediaType: string(whatsmeow.MediaImage),
+ Plaintext: plaintext,
+ ResponseJSON: responseJSON,
+ Requests: upload.takeRequests(),
+ URL: resp.URL,
+ DirectPath: resp.DirectPath,
+ Handle: resp.Handle,
+ ObjectID: resp.ObjectID,
+ MediaKey: resp.MediaKey,
+ FileEncSHA256: resp.FileEncSHA256,
+ FileSHA256: resp.FileSHA256,
+ FileLength: resp.FileLength,
+ }
+ uploaded := v.Upload.Requests[0].Body
+
+ newsletterJSON := `{"url":"https://mmg.whatsapp.net/newsletter/x","direct_path":"/newsletter/x?a=b","handle":"handle-1"}`
+ for _, host := range upload.hosts {
+ host.uploadAns = newsletterJSON
+ }
+ newsResp, err := upload.cli.UploadNewsletter(ctx, plaintext, whatsmeow.MediaVideo)
+ must(err)
+ v.Newsletter = uploadVector{
+ MediaType: string(whatsmeow.MediaVideo),
+ Plaintext: plaintext,
+ ResponseJSON: newsletterJSON,
+ Requests: upload.takeRequests(),
+ URL: newsResp.URL,
+ DirectPath: newsResp.DirectPath,
+ Handle: newsResp.Handle,
+ ObjectID: newsResp.ObjectID,
+ FileSHA256: newsResp.FileSHA256,
+ FileLength: newsResp.FileLength,
+ }
+
+ // Delete.
+ v.Delete = deleteVector{
+ MediaType: string(whatsmeow.MediaHistory),
+ DirectPath: "/v/t62.15575-24/hist.enc?ccb=11-4&oh=01",
+ EncFileHash: resp.FileEncSHA256,
+ EncHandle: "enc-handle",
+ CompanionMetaNonce: "companion-nonce",
+ }
+ must(upload.cli.DeleteMedia(ctx, whatsmeow.MediaHistory, v.Delete.DirectPath, v.Delete.EncFileHash, v.Delete.EncHandle))
+ v.Delete.Requests = upload.takeRequests()
+ upload.close()
+
+ // validateMedia: the uploaded body is ciphertext || mac.
+ ciphertext, mac := uploaded[:len(uploaded)-10], uploaded[len(uploaded)-10:]
+ uploadIV, _, uploadMACKey, _ := getMediaKeys(resp.MediaKey, whatsmeow.MediaImage)
+ badMAC := append([]byte{}, mac...)
+ badMAC[0] ^= 1
+ for _, c := range []validateCase{
+ {IV: uploadIV, File: ciphertext, MACKey: uploadMACKey, MAC: mac},
+ {IV: uploadIV, File: ciphertext, MACKey: uploadMACKey, MAC: badMAC},
+ {IV: uploadIV, File: ciphertext, MACKey: uploadMACKey, MAC: mac[:9]},
+ {IV: iv, File: file, MACKey: macKey, MAC: seq(0, 10)},
+ } {
+ c.Error = errString(validateMedia(c.IV, c.File, c.MACKey, c.MAC))
+ v.Validate = append(v.Validate, c)
+ }
+
+ // Downloads.
+ directPath := "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4&oh=01_Q5Aa&oe=6700&_nc_sid=5e03e0"
+ tampered := append([]byte{}, uploaded...)
+ tampered[len(tampered)-1] ^= 1
+ tamperedSHA := sha256.Sum256(tampered)
+ wrongSHA := sha256.Sum256([]byte("wrong"))
+ unencrypted := []byte("plain newsletter media")
+ unencryptedSHA := sha256.Sum256(unencrypted)
+ ok := response{Status: 200}
+ cases := []downloadVector{
+ {Name: "ok", Responses: [][]response{{ok}, {ok}}},
+ {Name: "next_host_on_500", Responses: [][]response{{{Status: 500}}, {ok}}},
+ {Name: "retry_on_503", Responses: [][]response{{{Status: 503, RetryAfter: "0"}, {Status: 429, RetryAfter: "0"}, ok}, {ok}}},
+ {Name: "retries_exhausted", Responses: [][]response{{{Status: 502, RetryAfter: "0"}}, {ok}}},
+ {Name: "not_found", Responses: [][]response{{{Status: 404}}, {ok}}},
+ {Name: "gone", Responses: [][]response{{{Status: 410}}, {ok}}},
+ {Name: "last_host_500", Responses: [][]response{{{Status: 500}}, {{Status: 500}}}},
+ {Name: "bad_hmac", FileEncSHA256: tamperedSHA[:], Responses: [][]response{{{Status: 200, Body: tampered}}, {{Status: 200, Body: tampered}}}},
+ {Name: "bad_enc_sha256", FileEncSHA256: wrongSHA[:], Responses: [][]response{{ok}, {ok}}},
+ {Name: "bad_sha256", FileSHA256: wrongSHA[:], Responses: [][]response{{ok}, {ok}}},
+ {Name: "too_short", Responses: [][]response{{{Status: 200, Body: seq(1, 10)}}, {ok}}},
+ {Name: "unencrypted", MediaKey: []byte{}, FileEncSHA256: []byte{}, FileSHA256: unencryptedSHA[:], Responses: [][]response{{{Status: 200, Body: unencrypted}}, {ok}}},
+ {Name: "unencrypted_bad_sha256", MediaKey: []byte{}, FileEncSHA256: []byte{}, FileSHA256: wrongSHA[:], Responses: [][]response{{{Status: 200, Body: unencrypted}}, {ok}}},
+ {Name: "no_slash", DirectPath: "v/no-slash", Responses: [][]response{{ok}, {ok}}},
+ }
+ for _, toFile := range []bool{false, true} {
+ for _, c := range cases {
+ c.ToFile = toFile
+ if c.DirectPath == "" {
+ c.DirectPath = directPath
+ }
+ if c.MediaKey == nil {
+ c.MediaKey = resp.MediaKey
+ } else if len(c.MediaKey) == 0 {
+ c.MediaKey = nil
+ }
+ if c.FileEncSHA256 == nil {
+ c.FileEncSHA256 = resp.FileEncSHA256
+ } else if len(c.FileEncSHA256) == 0 {
+ c.FileEncSHA256 = nil
+ }
+ if c.FileSHA256 == nil {
+ c.FileSHA256 = resp.FileSHA256
+ }
+ h := newHarness(len(c.Responses), v.Auth)
+ for i, script := range c.Responses {
+ for _, answer := range script {
+ if answer.Body == nil {
+ answer.Body = uploaded
+ }
+ h.hosts[i].script = append(h.hosts[i].script, answer)
+ }
+ }
+ msg := &waE2E.ImageMessage{
+ DirectPath: &c.DirectPath,
+ MediaKey: c.MediaKey,
+ FileSHA256: c.FileSHA256,
+ FileEncSHA256: c.FileEncSHA256,
+ }
+ if toFile {
+ f := &fileBuffer{}
+ err = h.cli.DownloadToFile(ctx, msg, f)
+ if err == nil {
+ c.Data = f.data
+ }
+ } else {
+ c.Data, err = h.cli.Download(ctx, msg)
+ }
+ c.Error = errString(err)
+ c.Requests = h.takeRequests()
+ h.close()
+ v.Downloads = append(v.Downloads, c)
+ }
+ }
+
+ // Media conn: the response node as WhatsApp sends it, and the request.
+ connNode := waBinary.Node{
+ Tag: "iq",
+ Attrs: waBinary.Attrs{
+ "from": types.ServerJID,
+ "id": "1234.5678-1",
+ "type": "result",
+ },
+ Content: []waBinary.Node{{
+ Tag: "media_conn",
+ Attrs: waBinary.Attrs{
+ "auth": v.Auth,
+ "ttl": "300",
+ "auth_ttl": "21600",
+ "max_buckets": "12",
+ },
+ Content: []waBinary.Node{
+ {Tag: "host", Attrs: waBinary.Attrs{"hostname": "mmg.whatsapp.net"}, Content: []waBinary.Node{{Tag: "download"}}},
+ {Tag: "unknown"},
+ {Tag: "host", Attrs: waBinary.Attrs{"hostname": "media-ams2-1.cdn.whatsapp.net", "type": "fallback"}},
+ },
+ }},
+ }
+ connBytes, err := waBinary.Marshal(connNode)
+ must(err)
+ v.MediaConn.Response = connBytes
+ // Mirrors queryMediaConn's attribute reads.
+ respMC := connNode.GetChildren()[0]
+ ag := respMC.AttrGetter()
+ v.MediaConn.Auth = ag.String("auth")
+ v.MediaConn.TTL = ag.Int("ttl")
+ v.MediaConn.AuthTTL = ag.Int("auth_ttl")
+ v.MediaConn.MaxBuckets = ag.Int("max_buckets")
+ for _, child := range respMC.GetChildren() {
+ if child.Tag == "host" {
+ v.MediaConn.Hosts = append(v.MediaConn.Hosts, mediaConnHost{Hostname: child.AttrGetter().String("hostname")})
+ }
+ }
+ // Mirrors sendIQAsyncAndGetData's node for queryMediaConn's infoQuery.
+ requestBytes, err := waBinary.Marshal(waBinary.Node{
+ Tag: "iq",
+ Attrs: waBinary.Attrs{
+ "id": "1234.5678-2",
+ "xmlns": "w:m",
+ "type": "set",
+ "to": types.ServerJID,
+ },
+ Content: []waBinary.Node{{Tag: "media_conn"}},
+ })
+ must(err)
+ v.MediaConn.Request = requestBytes
+
+ data, err := json.MarshalIndent(v, "", " ")
+ must(err)
+ must(os.MkdirAll(filepath.Dir(*out), 0o755))
+ must(os.WriteFile(*out, append(data, '\n'), 0o644))
+}
diff --git a/crates/whatsmeow/testdata/group.json b/crates/whatsmeow/testdata/group.json
new file mode 100644
index 0000000000..d1bc3bd902
--- /dev/null
+++ b/crates/whatsmeow/testdata/group.json
@@ -0,0 +1,485 @@
+{
+ "broken_group_error": "[didn't find required attribute 'id']",
+ "broken_group_info": {
+ "addressing_mode": "",
+ "announce_version_id": "",
+ "creator_country_code": "",
+ "default_membership_approval_mode": "",
+ "disappearing_timer": 0,
+ "group_created": 0,
+ "is_announce": false,
+ "is_default_sub_group": false,
+ "is_ephemeral": false,
+ "is_incognito": false,
+ "is_join_approval_required": false,
+ "is_locked": false,
+ "is_parent": false,
+ "jid": "g.us",
+ "linked_parent_jid": "",
+ "member_add_mode": "",
+ "name": "No ID",
+ "name_set_at": 0,
+ "name_set_by": "",
+ "name_set_by_pn": "",
+ "owner_jid": "",
+ "owner_pn": "",
+ "participant_count": 0,
+ "participant_version_id": "",
+ "participants": [],
+ "suspended": false,
+ "topic": "",
+ "topic_deleted": false,
+ "topic_id": "",
+ "topic_set_at": 0,
+ "topic_set_by": "",
+ "topic_set_by_pn": ""
+ },
+ "broken_group_node": "00f803ecaaec7ffc054e6f204944",
+ "cached_after_changes": {
+ "addressing_mode": "lid",
+ "admins": [
+ "5555@lid"
+ ],
+ "community_announcement_group": true,
+ "members": [
+ "2222@lid",
+ "5555@lid"
+ ],
+ "read_only": false
+ },
+ "create_node": "00f8120906faff091203630077777777771c04ec2008fc056e6f7469661aff05170000010005faeee276fc0e7061727469636970616e745f706efaeee20318fc054f776e6572fc0f61646472657373696e675f6d6f646576f801f808ef4c9efc03636b3104fc036e6577ec2eec61f801f808ecaaec7ffc0546726573683cff05170000005008ff09120363007777777777f802f809050cfaeee27604ec94fc0c70686f6e655f6e756d626572faeee20348fc0a2b31e28899e288993131f803050cfaff02987676",
+ "group_change_failures": [
+ {
+ "error": "group change doesn't contain required attributes: [didn't find required attribute 't']",
+ "node": "00f8030906faff091203630012345678901c"
+ },
+ {
+ "error": "group change subject element doesn't contain required attributes: [didn't find required attribute 'subject']",
+ "node": "00f8100908fc056e6f7469661aff05170000010005faeee276fc0e7061727469636970616e745f706efaeee20318fc054f776e657206faff091203630012345678901c04ec20f801f803ec7fecee55"
+ },
+ {
+ "error": "missing \u003cgroup\u003e element in group link",
+ "node": "00f8100906faff091203630012345678901c04ec2008fc056e6f7469661aff05170000010005faeee276fc0e7061727469636970616e745f706efaeee20318fc054f776e6572f801f803fc046c696e6bfc096c696e6b5f74797065fc097375625f67726f7570"
+ },
+ {
+ "error": "group create notification didn't contain group info",
+ "node": "00f8100904ec2008fc056e6f7469661aff05170000010005faeee276fc0e7061727469636970616e745f706efaeee20318fc054f776e657206faff091203630012345678901cf801f801ef4c"
+ }
+ ],
+ "group_changes": [
+ {
+ "event": {
+ "announce": null,
+ "delete": null,
+ "demote": [],
+ "ephemeral": null,
+ "jid": "[email protected]",
+ "join": [
+ "5555@lid",
+ "1111@lid"
+ ],
+ "join_reason": "invite",
+ "leave": [],
+ "link": null,
+ "locked": null,
+ "membership_approval_mode": null,
+ "name": null,
+ "new_invite_link": null,
+ "notify": "Owner",
+ "participant_version_id": "2",
+ "prev_participant_version_id": "1",
+ "promote": [],
+ "sender": "1111@lid",
+ "sender_pn": "[email protected]",
+ "suspended": false,
+ "timestamp": 1700000100,
+ "topic": null,
+ "unknown_changes": [],
+ "unlink": null,
+ "unsuspended": false
+ },
+ "lid_pairs": [
+ [
+ "5555@lid",
+ ],
+ [
+ "6666@lid",
+ ]
+ ],
+ "node": "00f81009fc0e7061727469636970616e745f706efaeee20318fc054f776e657206faff091203630012345678901c04ec2008fc056e6f7469661aff05170000010005faeee276f801f80897ec2eec61ec2655ec7245f803f805050cfaff02555576fc0c70686f6e655f6e756d626572faff02555503f805050cfaff0266660376faff02666676f803050cfaeee276"
+ },
+ {
+ "event": {
+ "announce": null,
+ "delete": null,
+ "demote": [],
+ "ephemeral": null,
+ "jid": "[email protected]",
+ "join": [],
+ "join_reason": "",
+ "leave": [
+ "1111@lid"
+ ],
+ "link": null,
+ "locked": null,
+ "membership_approval_mode": null,
+ "name": null,
+ "new_invite_link": null,
+ "notify": "Owner",
+ "participant_version_id": "",
+ "prev_participant_version_id": "",
+ "promote": [
+ "5555@lid",
+ "2222@lid"
+ ],
+ "sender": "1111@lid",
+ "sender_pn": "[email protected]",
+ "suspended": false,
+ "timestamp": 1700000100,
+ "topic": null,
+ "unknown_changes": [],
+ "unlink": null,
+ "unsuspended": false
+ },
+ "lid_pairs": [],
+ "node": "00f8100904ec2008fc056e6f7469661aff05170000010005faeee276fc0e7061727469636970616e745f706efaeee20318fc054f776e657206faff091203630012345678901cf802f804afec72a2f801f803050cfaeee276f802fc0770726f6d6f7465f802f803050cfaff02555576f803050cfaef3e76"
+ },
+ {
+ "event": {
+ "announce": {
+ "announce_version_id": "a2",
+ "is_announce": true
+ },
+ "delete": null,
+ "demote": [
+ "2222@lid"
+ ],
+ "ephemeral": {
+ "disappearing_timer": 604800,
+ "is_ephemeral": true
+ },
+ "jid": "[email protected]",
+ "join": [],
+ "join_reason": "",
+ "leave": [],
+ "link": null,
+ "locked": true,
+ "membership_approval_mode": true,
+ "name": {
+ "name": "Renamed",
+ "name_set_at": 1700000101,
+ "name_set_by": "1111@lid",
+ "name_set_by_pn": "[email protected]"
+ },
+ "new_invite_link": "https://chat.whatsapp.com/XyZ",
+ "notify": "Owner",
+ "participant_version_id": "",
+ "prev_participant_version_id": "",
+ "promote": [],
+ "sender": "1111@lid",
+ "sender_pn": "[email protected]",
+ "suspended": true,
+ "timestamp": 1700000100,
+ "topic": {
+ "topic": "New topic",
+ "topic_deleted": false,
+ "topic_id": "topic2",
+ "topic_set_at": 1700000100,
+ "topic_set_by": "1111@lid"
+ },
+ "unknown_changes": [
+ "mystery"
+ ],
+ "unlink": null,
+ "unsuspended": false
+ },
+ "lid_pairs": [
+ [
+ "2222@lid",
+ ]
+ ],
+ "node": "00f81009fc0e7061727469636970616e745f706efaeee20318fc054f776e657206faff091203630012345678901c04ec2008fc056e6f7469661aff05170000010005faeee276f80af802fc0664656d6f7465f801f805050cfaef3e76fc0c70686f6e655f6e756d626572faef3e03f809ec7fec7ffc0752656e616d6564eceeff051700000101ed16faeee276fc06735f6f5f706efaeee203f804b708fc06746f70696332f801f802ed75fc094e657720746f706963f803ed02ec72fc026132f803ec6170fc0358795af803edc8bbff03604800f801ed2bf801fc186d656d626572736869705f617070726f76616c5f6d6f6465f801fc0973757370656e646564f801fc076d797374657279"
+ },
+ {
+ "event": {
+ "announce": {
+ "announce_version_id": "a3",
+ "is_announce": false
+ },
+ "delete": {
+ "delete_reason": "admin",
+ "deleted": true
+ },
+ "demote": [],
+ "ephemeral": {
+ "disappearing_timer": 0,
+ "is_ephemeral": false
+ },
+ "jid": "[email protected]",
+ "join": [],
+ "join_reason": "",
+ "leave": [],
+ "link": {
+ "group": {
+ "is_default_sub_group": true,
+ "jid": "[email protected]",
+ "name": "Community",
+ "name_set_at": 1700000003
+ },
+ "type": "parent_group",
+ "unlink_reason": ""
+ },
+ "locked": false,
+ "membership_approval_mode": null,
+ "name": null,
+ "new_invite_link": null,
+ "notify": "Owner",
+ "participant_version_id": "",
+ "prev_participant_version_id": "",
+ "promote": [],
+ "sender": "1111@lid",
+ "sender_pn": null,
+ "suspended": false,
+ "timestamp": 1700000100,
+ "topic": {
+ "topic": "",
+ "topic_deleted": true,
+ "topic_id": "topic3",
+ "topic_set_at": 1700000100,
+ "topic_set_by": "1111@lid"
+ },
+ "unknown_changes": [],
+ "unlink": {
+ "group": {
+ "is_default_sub_group": false,
+ "jid": "[email protected]",
+ "name": "",
+ "name_set_at": 0
+ },
+ "type": "sub_group",
+ "unlink_reason": "delete_parent"
+ },
+ "unsuspended": true
+ },
+ "lid_pairs": [],
+ "node": "00f80e0918fc054f776e657206faff091203630012345678901c04ec2008fc056e6f7469661aff05170000010005faeee276f808f803fc106e6f745f616e6e6f756e63656d656e74ec72fc026133f801fc0d6e6f745f657068656d6572616cf801fc08756e6c6f636b6564f803ec52ec2eec56f804b708fc06746f70696333f801f801ec52f801fc0b756e73757370656e646564f804fc046c696e6bfc096c696e6b5f74797065fc0c706172656e745f67726f7570f801f808ecaa0cfaff091203630099999999991cec7ffc09436f6d6d756e697479eceeff051700000003f801f801fc1164656661756c745f7375625f67726f7570f806fc06756e6c696e6bfc0b756e6c696e6b5f74797065fc097375625f67726f7570fc0d756e6c696e6b5f726561736f6efc0d64656c6574655f706172656e74f801f803ecaa08ff09120363008888888888"
+ }
+ ],
+ "group_info": {
+ "addressing_mode": "lid",
+ "announce_version_id": "av1",
+ "creator_country_code": "US",
+ "default_membership_approval_mode": "request_required",
+ "disappearing_timer": 86400,
+ "group_created": 1700000000,
+ "is_announce": true,
+ "is_default_sub_group": true,
+ "is_ephemeral": true,
+ "is_incognito": true,
+ "is_join_approval_required": true,
+ "is_locked": true,
+ "is_parent": true,
+ "jid": "[email protected]",
+ "linked_parent_jid": "[email protected]",
+ "member_add_mode": "admin_add",
+ "name": "Team",
+ "name_set_at": 1700000001,
+ "name_set_by": "2222@lid",
+ "name_set_by_pn": "[email protected]",
+ "owner_jid": "1111@lid",
+ "owner_pn": "[email protected]",
+ "participant_count": 4,
+ "participant_version_id": "pv1",
+ "participants": [
+ {
+ "add_request": null,
+ "display_name": "",
+ "error": 0,
+ "is_admin": true,
+ "is_super_admin": true,
+ "jid": "1111@lid",
+ "lid": "1111@lid",
+ "phone_number": "[email protected]"
+ },
+ {
+ "add_request": null,
+ "display_name": "+1∙∙∙∙∙∙∙∙22",
+ "error": 0,
+ "is_admin": true,
+ "is_super_admin": false,
+ "jid": "2222@lid",
+ "lid": "2222@lid",
+ "phone_number": ""
+ },
+ {
+ "add_request": null,
+ "display_name": "",
+ "error": 0,
+ "is_admin": false,
+ "is_super_admin": false,
+ "jid": "[email protected]",
+ "lid": "3333@lid",
+ "phone_number": "[email protected]"
+ },
+ {
+ "add_request": {
+ "code": "abc",
+ "expiration": 1700100000
+ },
+ "display_name": "",
+ "error": 403,
+ "is_admin": false,
+ "is_super_admin": false,
+ "jid": "[email protected]",
+ "lid": "",
+ "phone_number": "[email protected]"
+ }
+ ],
+ "suspended": true,
+ "topic": "Hello",
+ "topic_deleted": false,
+ "topic_id": "topic1",
+ "topic_set_at": 1700000002,
+ "topic_set_by": "2222@lid",
+ "topic_set_by_pn": "[email protected]"
+ },
+ "group_lid_pairs": [
+ [
+ "1111@lid",
+ ],
+ [
+ "",
+ ""
+ ],
+ [
+ "3333@lid",
+ ],
+ [
+ "",
+ ""
+ ]
+ ],
+ "group_node": "00f81cecaaecbafc03617631fc0a63726561746f725f706efaeee203ec7ffc045465616deca0fc03707631edc6ec22fc0f61646472657373696e675f6d6f64657608ff09120363001234567890eca6faeee276eceeff051700000001ed16faef3e76fc06735f6f5f706efaef3e033cff051700000000fc1463726561746f725f636f756e7472795f636f6465fc025553f810f807050cfaeee27604ec94fc0c70686f6e655f6e756d626572faeee203f807050cfaef3e7604ec5648fc1c2b31e28899e28899e28899e28899e28899e28899e28899e288993232f805050cfaff0233330376faff02333376f806050cfaff02444403a8ff82403ff801f805fc0b6164645f7265717565737470fc03616263bbff051700100000f80ab71aff05170000000208fc06746f7069633105faef3e76fc0e7061727469636970616e745f706efaef3e03f801f802ed75fc0548656c6c6ff801ed02f801ed2bf803edc8bbff8386400ff802ec3cfc0961646d696e5f616464f803fc0d6c696e6b65645f706172656e740cfaff091203630099999999991cf801fc1164656661756c745f7375625f67726f7570f803fc06706172656e74fc2064656661756c745f6d656d626572736869705f617070726f76616c5f6d6f6465fc10726571756573745f7265717569726564f801fc09696e636f676e69746ff801fc186d656d626572736869705f617070726f76616c5f6d6f6465f801fc0973757370656e646564f801fc076d797374657279",
+ "group_redacted_phones": [
+ [
+ "2222@lid",
+ "+1∙∙∙∙∙∙∙∙22"
+ ]
+ ],
+ "joined_group": {
+ "create_key": "ck1",
+ "group_info": {
+ "addressing_mode": "lid",
+ "announce_version_id": "",
+ "creator_country_code": "",
+ "default_membership_approval_mode": "",
+ "disappearing_timer": 0,
+ "group_created": 1700000050,
+ "is_announce": false,
+ "is_default_sub_group": false,
+ "is_ephemeral": false,
+ "is_incognito": false,
+ "is_join_approval_required": false,
+ "is_locked": false,
+ "is_parent": false,
+ "jid": "[email protected]",
+ "linked_parent_jid": "",
+ "member_add_mode": "",
+ "name": "Fresh",
+ "name_set_at": 0,
+ "name_set_by": "",
+ "name_set_by_pn": "",
+ "owner_jid": "",
+ "owner_pn": "",
+ "participant_count": 0,
+ "participant_version_id": "",
+ "participants": [
+ {
+ "add_request": null,
+ "display_name": "+1∙∙11",
+ "error": 0,
+ "is_admin": true,
+ "is_super_admin": true,
+ "jid": "1111@lid",
+ "lid": "1111@lid",
+ "phone_number": "[email protected]"
+ },
+ {
+ "add_request": null,
+ "display_name": "",
+ "error": 0,
+ "is_admin": false,
+ "is_super_admin": false,
+ "jid": "9876@lid",
+ "lid": "9876@lid",
+ "phone_number": ""
+ }
+ ],
+ "suspended": false,
+ "topic": "",
+ "topic_deleted": false,
+ "topic_id": "",
+ "topic_set_at": 0,
+ "topic_set_by": "",
+ "topic_set_by_pn": ""
+ },
+ "notify": "Owner",
+ "reason": "invite",
+ "sender": "1111@lid",
+ "sender_pn": "[email protected]",
+ "type": "new"
+ },
+ "joined_lid_pairs": [
+ [
+ "1111@lid",
+ ],
+ [
+ "",
+ ""
+ ]
+ ],
+ "joined_redacted_phones": [
+ [
+ "1111@lid",
+ "+1∙∙11"
+ ]
+ ],
+ "requests": {
+ "add_participants": "00f80a1916ed33045a11faff091203630012345678901c08fc024944f801f80297f802f803050cfaff02555576f803050cfaff02333303",
+ "approve_request_participants": "00f80a1908fc02494416ed33045a11faff091203630012345678901cf801f802fc1a6d656d626572736869705f72657175657374735f616374696f6ef801f802fc07617070726f7665f801f803050cfaff02555576",
+ "create_community": "00f80a1908fc02494416ed33045a11fa001cf801f804ef4cec7ffc09436f6d6d756e697479f804f802ec3cfc0e616c6c5f6d656d6265725f616464f803fc06706172656e74fc2064656661756c745f6d656d626572736869705f617070726f76616c5f6d6f6465fc10726571756573745f7265717569726564f803edc8bb2df802fc186d656d626572736869705f617070726f76616c5f6d6f6465f801f803fc0a67726f75705f6a6f696ed0fc036f6666",
+ "create_group": "00f80a1908fc02494416ed33045a11fa001cf801f804ef4cec7ffc045465616df808f803050cfaff02333303f803050cfaff02555576f802ec3cfc0961646d696e5f616464f803fc0d6c696e6b65645f706172656e740cfaff091203630099999999991cf801ed2bf801ed02f805edc8bbff03604800fc077472696767657255f802fc186d656d626572736869705f617070726f76616c5f6d6f6465f801f803fc0a67726f75705f6a6f696ed0fc026f6e",
+ "delete_group_topic": "00f80a1911faff091203630012345678901c08fc02494416ed33045af801f808b708fc046e657732fc0470726576fc057072657631ec529b00",
+ "demote_participants": "00f80a1908fc02494416ed33045a11faff091203630012345678901cf801f802fc0664656d6f7465f801f803050cfaff02555576",
+ "get_group_info": "00f80a1908fc02494416ed33042911faff091203630012345678901cf801f8036dedc7e5",
+ "get_invite_link": "00f80a1908fc02494416ed33042911faff091203630012345678901cf801f801ec61",
+ "get_joined_groups": "00f80a1908fc02494416ed33042911fa001cf801f802ed78f802f8016bf801b7",
+ "get_request_participants": "00f80a1911faff091203630012345678901c08fc02494416ed330429f801f801fc1c6d656d626572736869705f617070726f76616c5f7265717565737473",
+ "info_from_invite": "00f80a1908fc02494416ed33042911faff091203630012345678901cf801f8026df801f807fc0b6164645f7265717565737470fc05636f646531bbff051700000000ec56faeee203",
+ "info_from_link": "00f80a1911fa001c08fc02494416ed330429f801f803ec6170fc03416243",
+ "join_approval_mode": "00f80a1908fc02494416ed33045a11faff091203630012345678901cf801f802fc186d656d626572736869705f617070726f76616c5f6d6f6465f801f803fc0a67726f75705f6a6f696ed0fc026f6e",
+ "join_with_invite": "00f80a1911faff091203630012345678901c08fc02494416ed33045af801f807ec6270fc05636f646531bbff051700000000ec56faeee203",
+ "join_with_link": "00f80a1908fc02494416ed33045a11fa001cf801f803ec6170fc03416243",
+ "leave_group": "00f80a1916ed33045a11fa001c08fc024944f801f802fc056c65617665f801f803ecaa08faff091203630012345678901c",
+ "member_add_mode": "00f80a1908fc02494416ed33045a11faff091203630012345678901cf801f802ec3cfc0961646d696e5f616464",
+ "remove_group_photo": "00f80b19045a11fa000387faff091203630012345678901c08fc0249441642",
+ "reset_invite_link": "00f80a1908fc02494416ed33045a11faff091203630012345678901cf801f801ec61",
+ "set_group_announce": "00f80a19045a11faff091203630012345678901c08fc02494416ed33f801f801ed02",
+ "set_group_locked": "00f80a1908fc02494416ed33045a11faff091203630012345678901cf801f801ed2b",
+ "set_group_name": "00f80a1908fc02494416ed33045a11faff091203630012345678901cf801f802ec7ffc084e6577206e616d65",
+ "set_group_not_announce": "00f80a1911faff091203630012345678901c08fc02494416ed33045af801f801fc106e6f745f616e6e6f756e63656d656e74",
+ "set_group_photo": "00f80c1911fa000387faff091203630012345678901c08fc0249441642045af801f804210443fc02ffd8",
+ "set_group_topic": "00f80a1908fc02494416ed33045a11faff091203630012345678901cf801f806b7fc0470726576fc05707265763108fc046e657731f801f802ed75fc05546f706963",
+ "set_group_unlocked": "00f80a1908fc02494416ed33045a11faff091203630012345678901cf801f801fc08756e6c6f636b6564"
+ }
+}
diff --git a/crates/whatsmeow/testdata/media/vectors.json b/crates/whatsmeow/testdata/media/vectors.json
new file mode 100644
index 0000000000..2f32b1ebc1
--- /dev/null
+++ b/crates/whatsmeow/testdata/media/vectors.json
@@ -0,0 +1,1521 @@
+{
+ "auth": "AUTH token/with+odd=chars~*!",
+ "user_agent": "whatsmeow-rs-test/1.0",
+ "media_keys": [
+ {
+ "media_type": "WhatsApp Image Keys",
+ "mms_type": "image",
+ "media_key": "202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f",
+ "iv": "9eec22fdf8297f59632d79711adc9ed2",
+ "cipher_key": "3d46bb135bc7abfbe9906600d04538d68c3390c423b80bb390b4ccd7babe7d39",
+ "mac_key": "b60ea78adc0f4cc6828d6d93f08a03c829362343a08170e2af7b9686de1e54a8",
+ "ref_key": "c73d53bdd058ed552b730ac5c3733ad2d9415549b426390848396f82a4498839"
+ },
+ {
+ "media_type": "WhatsApp Video Keys",
+ "mms_type": "video",
+ "media_key": "202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f",
+ "iv": "293451e11439ba681d55a8be34733a47",
+ "cipher_key": "740dbf00f76ee065cd32865e7e95eb60f2bd40a9682699768cc056e17d72050c",
+ "mac_key": "79da58694bc08c043361b8e811da301e70c45110cfbc876c77cf0f31ae943a1d",
+ "ref_key": "5dc15c57c72d422d4002bd7cdf2139524d221a947221aa257a3a34f2ccc4e3d9"
+ },
+ {
+ "media_type": "WhatsApp Audio Keys",
+ "mms_type": "audio",
+ "media_key": "202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f",
+ "iv": "7e1de9660e74284748f27255b4d722ca",
+ "cipher_key": "0c41620d1764bd3d0bc5676b1a09e00207bae918cf43310b2df053c50558bd14",
+ "mac_key": "5280ccf7fa7b357b76597ff35f7d28316fa20ca3b4d1c7dc480d4746fc6171b8",
+ "ref_key": "e8a6a618cf334d6a7b02b709fe19771b026e4cc78ce5ba912d116064bd5bb380"
+ },
+ {
+ "media_type": "WhatsApp Document Keys",
+ "mms_type": "document",
+ "media_key": "202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f",
+ "iv": "cb42d215dc7132af71548c4048d8aeb2",
+ "cipher_key": "ad8263fb3d01ec5718e222e407e074cd6088b6809314039354f774fded4e6d91",
+ "mac_key": "7445972d87a5765100d66b28bf8a7a075f75284b4bc19a9f17206000a346e1d1",
+ "ref_key": "124f950348af443fbb02d69608a5679810c58749ddf8c8598107b82017e9fb77"
+ },
+ {
+ "media_type": "WhatsApp History Keys",
+ "mms_type": "md-msg-hist",
+ "media_key": "202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f",
+ "iv": "853d43d13a6b100cc55630633e348b4b",
+ "cipher_key": "ee21357548048adebb3d70805d57b886fcabac6a487ed480289d10d32062f313",
+ "mac_key": "94dfe0eaa382434c2b3f426a2111cbb6ad890a4bf17bc777a060aa4f3809f357",
+ "ref_key": "47710ce06d15c418e24d4953408b125b73915b8aa03d7687b962abec4dca23e0"
+ },
+ {
+ "media_type": "WhatsApp App State Keys",
+ "mms_type": "md-app-state",
+ "media_key": "202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f",
+ "iv": "9f85645e77056b9e45eb937a4a43ffbc",
+ "cipher_key": "eef686039ae20ae7920f73e798b24e84025b9f8060e06f2c81163dc8c37fda2f",
+ "mac_key": "95e517e5587cd1d57b57dc13b1687e2b995b6612a8dd0e682258f4d0bd493555",
+ "ref_key": "7e79121a5e3a420adc9384f70588bf0819b61443d91f2f61142b573c42c8eacd"
+ },
+ {
+ "media_type": "WhatsApp Sticker Pack Keys",
+ "mms_type": "sticker-pack",
+ "media_key": "202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f",
+ "iv": "f2e85632f92841601cee96716b603a20",
+ "cipher_key": "92104f943a197422500ba4b8347928907a28aca387d92fe776d7bc330b18274e",
+ "mac_key": "0fdd15eb08f7185a687fad96aefb84408dd9423d1622cfc02a286a45c5f05ed3",
+ "ref_key": "381bb7f62114504e501aa3466bb29dc1748b8aa2a1db18b1e6f2f8b4ce8fd715"
+ },
+ {
+ "media_type": "WhatsApp Link Thumbnail Keys",
+ "mms_type": "thumbnail-link",
+ "media_key": "202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f",
+ "iv": "2cd0841c59d9b148cc6ea9166baca5e3",
+ "cipher_key": "7b809302bca50c76ad46299392d938614c2a484e7a4ee015bf8d5e3d32e8d093",
+ "mac_key": "a9a909a0f54b05fa192b025139b7a3130e691e20240f1e7c55430f6fcf535a7a",
+ "ref_key": "583d24305ab2b3420f19b745e0b26dade6565d7c51088cda446dd920e2acb4f1"
+ }
+ ],
+ "validate": [
+ {
+ "iv": "82d2a4f7d706ee0c0f6bb255f3611cf2",
+ "file": "307e9550bb6bc0077e8ce2d008b7ae058bf4a4151ed61be21aa8c5490fa24b34f7eef210d7af8bdd201cbc21d10167c944b079dab9b5937b7951222ee83c0547e2f43ae79b6a7ed892e4b4540df8c59c18bd0dbd61cafc1e9e886e5cbd38b2b03bf8222392103d3d709306000ea6063e112e0c96e3f90c98250f2816ccc2d184",
+ "mac_key": "5bb83cffa91cc51dd51a0e4ba9f4943b1de8713811fd998774501152e7e942c5",
+ "mac": "d1c84737775419acb094",
+ "error": ""
+ },
+ {
+ "iv": "82d2a4f7d706ee0c0f6bb255f3611cf2",
+ "file": "307e9550bb6bc0077e8ce2d008b7ae058bf4a4151ed61be21aa8c5490fa24b34f7eef210d7af8bdd201cbc21d10167c944b079dab9b5937b7951222ee83c0547e2f43ae79b6a7ed892e4b4540df8c59c18bd0dbd61cafc1e9e886e5cbd38b2b03bf8222392103d3d709306000ea6063e112e0c96e3f90c98250f2816ccc2d184",
+ "mac_key": "5bb83cffa91cc51dd51a0e4ba9f4943b1de8713811fd998774501152e7e942c5",
+ "mac": "d0c84737775419acb094",
+ "error": "invalid media hmac"
+ },
+ {
+ "iv": "82d2a4f7d706ee0c0f6bb255f3611cf2",
+ "file": "307e9550bb6bc0077e8ce2d008b7ae058bf4a4151ed61be21aa8c5490fa24b34f7eef210d7af8bdd201cbc21d10167c944b079dab9b5937b7951222ee83c0547e2f43ae79b6a7ed892e4b4540df8c59c18bd0dbd61cafc1e9e886e5cbd38b2b03bf8222392103d3d709306000ea6063e112e0c96e3f90c98250f2816ccc2d184",
+ "mac_key": "5bb83cffa91cc51dd51a0e4ba9f4943b1de8713811fd998774501152e7e942c5",
+ "mac": "d1c84737775419acb0",
+ "error": "invalid media hmac"
+ },
+ {
+ "iv": "9eec22fdf8297f59632d79711adc9ed2",
+ "file": "505152535455565758595a5b5c5d5e5f606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f",
+ "mac_key": "b60ea78adc0f4cc6828d6d93f08a03c829362343a08170e2af7b9686de1e54a8",
+ "mac": "00010203040506070809",
+ "error": "invalid media hmac"
+ }
+ ],
+ "upload": {
+ "media_type": "WhatsApp Image Keys",
+ "plaintext": "77686174736d656f77206d656469612075706c6f61642077686174736d656f77206d656469612075706c6f61642077686174736d656f77206d656469612075706c6f61642077686174736d656f77206d656469612075706c6f61642077686174736d656f77206d656469612075706c6f616420",
+ "response_json": "{\"url\":\"https://mmg.whatsapp.net/o1/v/t62.7118-24/f1/m231/up.enc?ccb=9-4\",\"direct_path\":\"/o1/v/t62.7118-24/f1/m231/up.enc?ccb=9-4\u0026oh=01_Q5\u0026oe=68\",\"handle\":\"\",\"object_id\":\"obj-1\",\"extra\":true}",
+ "requests": [
+ {
+ "host": 0,
+ "method": "POST",
+ "request_uri": "/mms/image/5pKCvBIh3YJJWqkCSwj9Y4Ori5KXEIxqx3kni0ewsyI=?auth=AUTH+token%2Fwith%2Bodd%3Dchars~%2A%21\u0026token=5pKCvBIh3YJJWqkCSwj9Y4Ori5KXEIxqx3kni0ewsyI%3D",
+ "headers": {
+ "Content-Length": "138",
+ "Origin": "https://web.whatsapp.com",
+ "Referer": "https://web.whatsapp.com/",
+ "User-Agent": "Go-http-client/1.1"
+ },
+ "body": "307e9550bb6bc0077e8ce2d008b7ae058bf4a4151ed61be21aa8c5490fa24b34f7eef210d7af8bdd201cbc21d10167c944b079dab9b5937b7951222ee83c0547e2f43ae79b6a7ed892e4b4540df8c59c18bd0dbd61cafc1e9e886e5cbd38b2b03bf8222392103d3d709306000ea6063e112e0c96e3f90c98250f2816ccc2d184d1c84737775419acb094"
+ }
+ ],
+ "url": "https://mmg.whatsapp.net/o1/v/t62.7118-24/f1/m231/up.enc?ccb=9-4",
+ "direct_path": "/o1/v/t62.7118-24/f1/m231/up.enc?ccb=9-4\u0026oh=01_Q5\u0026oe=68",
+ "handle": "",
+ "object_id": "obj-1",
+ "media_key": "61b6d24e801b23e06fc2df9405a203aad8389f7ffc8740b4a5885b4f5ff9391a",
+ "file_enc_sha256": "e69282bc1221dd82495aa9024b08fd6383ab8b9297108c6ac779278b47b0b322",
+ "file_sha256": "e7ace578c2da599125382176ef0ca30ee5a152a55ac827811942df99aaa2651b",
+ "file_length": 115
+ },
+ "upload_newsletter": {
+ "media_type": "WhatsApp Video Keys",
+ "plaintext": "77686174736d656f77206d656469612075706c6f61642077686174736d656f77206d656469612075706c6f61642077686174736d656f77206d656469612075706c6f61642077686174736d656f77206d656469612075706c6f61642077686174736d656f77206d656469612075706c6f616420",
+ "response_json": "{\"url\":\"https://mmg.whatsapp.net/newsletter/x\",\"direct_path\":\"/newsletter/x?a=b\",\"handle\":\"handle-1\"}",
+ "requests": [
+ {
+ "host": 0,
+ "method": "POST",
+ "request_uri": "/newsletter/newsletter-video/56zleMLaWZElOCF27wyjDuWhUqVayCeBGULfmaqiZRs=?auth=AUTH+token%2Fwith%2Bodd%3Dchars~%2A%21\u0026token=56zleMLaWZElOCF27wyjDuWhUqVayCeBGULfmaqiZRs%3D",
+ "headers": {
+ "Content-Length": "115",
+ "Origin": "https://web.whatsapp.com",
+ "Referer": "https://web.whatsapp.com/",
+ "User-Agent": "Go-http-client/1.1"
+ },
+ "body": "77686174736d656f77206d656469612075706c6f61642077686174736d656f77206d656469612075706c6f61642077686174736d656f77206d656469612075706c6f61642077686174736d656f77206d656469612075706c6f61642077686174736d656f77206d656469612075706c6f616420"
+ }
+ ],
+ "url": "https://mmg.whatsapp.net/newsletter/x",
+ "direct_path": "/newsletter/x?a=b",
+ "handle": "handle-1",
+ "object_id": "",
+ "media_key": null,
+ "file_enc_sha256": null,
+ "file_sha256": "e7ace578c2da599125382176ef0ca30ee5a152a55ac827811942df99aaa2651b",
+ "file_length": 115
+ },
+ "downloads": [
+ {
+ "name": "ok",
+ "direct_path": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0",
+ "media_key": "61b6d24e801b23e06fc2df9405a203aad8389f7ffc8740b4a5885b4f5ff9391a",
+ "file_sha256": "e7ace578c2da599125382176ef0ca30ee5a152a55ac827811942df99aaa2651b",
+ "file_enc_sha256": "e69282bc1221dd82495aa9024b08fd6383ab8b9297108c6ac779278b47b0b322",
+ "responses": [
+ [
+ {
+ "status": 200,
+ "body": null
+ }
+ ],
+ [
+ {
+ "status": 200,
+ "body": null
+ }
+ ]
+ ],
+ "requests": [
+ {
+ "host": 0,
+ "method": "GET",
+ "request_uri": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0\u0026hash=5pKCvBIh3YJJWqkCSwj9Y4Ori5KXEIxqx3kni0ewsyI=\u0026mms-type=image\u0026__wa-mms=",
+ "headers": {
+ "Origin": "https://web.whatsapp.com",
+ "Referer": "https://web.whatsapp.com/",
+ "User-Agent": "whatsmeow-rs-test/1.0"
+ },
+ "body": ""
+ }
+ ],
+ "data": "77686174736d656f77206d656469612075706c6f61642077686174736d656f77206d656469612075706c6f61642077686174736d656f77206d656469612075706c6f61642077686174736d656f77206d656469612075706c6f61642077686174736d656f77206d656469612075706c6f616420",
+ "error": "",
+ "to_file": false
+ },
+ {
+ "name": "next_host_on_500",
+ "direct_path": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0",
+ "media_key": "61b6d24e801b23e06fc2df9405a203aad8389f7ffc8740b4a5885b4f5ff9391a",
+ "file_sha256": "e7ace578c2da599125382176ef0ca30ee5a152a55ac827811942df99aaa2651b",
+ "file_enc_sha256": "e69282bc1221dd82495aa9024b08fd6383ab8b9297108c6ac779278b47b0b322",
+ "responses": [
+ [
+ {
+ "status": 500,
+ "body": null
+ }
+ ],
+ [
+ {
+ "status": 200,
+ "body": null
+ }
+ ]
+ ],
+ "requests": [
+ {
+ "host": 0,
+ "method": "GET",
+ "request_uri": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0\u0026hash=5pKCvBIh3YJJWqkCSwj9Y4Ori5KXEIxqx3kni0ewsyI=\u0026mms-type=image\u0026__wa-mms=",
+ "headers": {
+ "Origin": "https://web.whatsapp.com",
+ "Referer": "https://web.whatsapp.com/",
+ "User-Agent": "whatsmeow-rs-test/1.0"
+ },
+ "body": ""
+ },
+ {
+ "host": 1,
+ "method": "GET",
+ "request_uri": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0\u0026hash=5pKCvBIh3YJJWqkCSwj9Y4Ori5KXEIxqx3kni0ewsyI=\u0026mms-type=image\u0026__wa-mms=",
+ "headers": {
+ "Origin": "https://web.whatsapp.com",
+ "Referer": "https://web.whatsapp.com/",
+ "User-Agent": "whatsmeow-rs-test/1.0"
+ },
+ "body": ""
+ }
+ ],
+ "data": "77686174736d656f77206d656469612075706c6f61642077686174736d656f77206d656469612075706c6f61642077686174736d656f77206d656469612075706c6f61642077686174736d656f77206d656469612075706c6f61642077686174736d656f77206d656469612075706c6f616420",
+ "error": "",
+ "to_file": false
+ },
+ {
+ "name": "retry_on_503",
+ "direct_path": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0",
+ "media_key": "61b6d24e801b23e06fc2df9405a203aad8389f7ffc8740b4a5885b4f5ff9391a",
+ "file_sha256": "e7ace578c2da599125382176ef0ca30ee5a152a55ac827811942df99aaa2651b",
+ "file_enc_sha256": "e69282bc1221dd82495aa9024b08fd6383ab8b9297108c6ac779278b47b0b322",
+ "responses": [
+ [
+ {
+ "status": 503,
+ "retry_after": "0",
+ "body": null
+ },
+ {
+ "status": 429,
+ "retry_after": "0",
+ "body": null
+ },
+ {
+ "status": 200,
+ "body": null
+ }
+ ],
+ [
+ {
+ "status": 200,
+ "body": null
+ }
+ ]
+ ],
+ "requests": [
+ {
+ "host": 0,
+ "method": "GET",
+ "request_uri": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0\u0026hash=5pKCvBIh3YJJWqkCSwj9Y4Ori5KXEIxqx3kni0ewsyI=\u0026mms-type=image\u0026__wa-mms=",
+ "headers": {
+ "Origin": "https://web.whatsapp.com",
+ "Referer": "https://web.whatsapp.com/",
+ "User-Agent": "whatsmeow-rs-test/1.0"
+ },
+ "body": ""
+ },
+ {
+ "host": 0,
+ "method": "GET",
+ "request_uri": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0\u0026hash=5pKCvBIh3YJJWqkCSwj9Y4Ori5KXEIxqx3kni0ewsyI=\u0026mms-type=image\u0026__wa-mms=",
+ "headers": {
+ "Origin": "https://web.whatsapp.com",
+ "Referer": "https://web.whatsapp.com/",
+ "User-Agent": "whatsmeow-rs-test/1.0"
+ },
+ "body": ""
+ },
+ {
+ "host": 0,
+ "method": "GET",
+ "request_uri": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0\u0026hash=5pKCvBIh3YJJWqkCSwj9Y4Ori5KXEIxqx3kni0ewsyI=\u0026mms-type=image\u0026__wa-mms=",
+ "headers": {
+ "Origin": "https://web.whatsapp.com",
+ "Referer": "https://web.whatsapp.com/",
+ "User-Agent": "whatsmeow-rs-test/1.0"
+ },
+ "body": ""
+ }
+ ],
+ "data": "77686174736d656f77206d656469612075706c6f61642077686174736d656f77206d656469612075706c6f61642077686174736d656f77206d656469612075706c6f61642077686174736d656f77206d656469612075706c6f61642077686174736d656f77206d656469612075706c6f616420",
+ "error": "",
+ "to_file": false
+ },
+ {
+ "name": "retries_exhausted",
+ "direct_path": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0",
+ "media_key": "61b6d24e801b23e06fc2df9405a203aad8389f7ffc8740b4a5885b4f5ff9391a",
+ "file_sha256": "e7ace578c2da599125382176ef0ca30ee5a152a55ac827811942df99aaa2651b",
+ "file_enc_sha256": "e69282bc1221dd82495aa9024b08fd6383ab8b9297108c6ac779278b47b0b322",
+ "responses": [
+ [
+ {
+ "status": 502,
+ "retry_after": "0",
+ "body": null
+ }
+ ],
+ [
+ {
+ "status": 200,
+ "body": null
+ }
+ ]
+ ],
+ "requests": [
+ {
+ "host": 0,
+ "method": "GET",
+ "request_uri": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0\u0026hash=5pKCvBIh3YJJWqkCSwj9Y4Ori5KXEIxqx3kni0ewsyI=\u0026mms-type=image\u0026__wa-mms=",
+ "headers": {
+ "Origin": "https://web.whatsapp.com",
+ "Referer": "https://web.whatsapp.com/",
+ "User-Agent": "whatsmeow-rs-test/1.0"
+ },
+ "body": ""
+ },
+ {
+ "host": 0,
+ "method": "GET",
+ "request_uri": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0\u0026hash=5pKCvBIh3YJJWqkCSwj9Y4Ori5KXEIxqx3kni0ewsyI=\u0026mms-type=image\u0026__wa-mms=",
+ "headers": {
+ "Origin": "https://web.whatsapp.com",
+ "Referer": "https://web.whatsapp.com/",
+ "User-Agent": "whatsmeow-rs-test/1.0"
+ },
+ "body": ""
+ },
+ {
+ "host": 0,
+ "method": "GET",
+ "request_uri": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0\u0026hash=5pKCvBIh3YJJWqkCSwj9Y4Ori5KXEIxqx3kni0ewsyI=\u0026mms-type=image\u0026__wa-mms=",
+ "headers": {
+ "Origin": "https://web.whatsapp.com",
+ "Referer": "https://web.whatsapp.com/",
+ "User-Agent": "whatsmeow-rs-test/1.0"
+ },
+ "body": ""
+ },
+ {
+ "host": 0,
+ "method": "GET",
+ "request_uri": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0\u0026hash=5pKCvBIh3YJJWqkCSwj9Y4Ori5KXEIxqx3kni0ewsyI=\u0026mms-type=image\u0026__wa-mms=",
+ "headers": {
+ "Origin": "https://web.whatsapp.com",
+ "Referer": "https://web.whatsapp.com/",
+ "User-Agent": "whatsmeow-rs-test/1.0"
+ },
+ "body": ""
+ },
+ {
+ "host": 0,
+ "method": "GET",
+ "request_uri": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0\u0026hash=5pKCvBIh3YJJWqkCSwj9Y4Ori5KXEIxqx3kni0ewsyI=\u0026mms-type=image\u0026__wa-mms=",
+ "headers": {
+ "Origin": "https://web.whatsapp.com",
+ "Referer": "https://web.whatsapp.com/",
+ "User-Agent": "whatsmeow-rs-test/1.0"
+ },
+ "body": ""
+ },
+ {
+ "host": 1,
+ "method": "GET",
+ "request_uri": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0\u0026hash=5pKCvBIh3YJJWqkCSwj9Y4Ori5KXEIxqx3kni0ewsyI=\u0026mms-type=image\u0026__wa-mms=",
+ "headers": {
+ "Origin": "https://web.whatsapp.com",
+ "Referer": "https://web.whatsapp.com/",
+ "User-Agent": "whatsmeow-rs-test/1.0"
+ },
+ "body": ""
+ }
+ ],
+ "data": "77686174736d656f77206d656469612075706c6f61642077686174736d656f77206d656469612075706c6f61642077686174736d656f77206d656469612075706c6f61642077686174736d656f77206d656469612075706c6f61642077686174736d656f77206d656469612075706c6f616420",
+ "error": "",
+ "to_file": false
+ },
+ {
+ "name": "not_found",
+ "direct_path": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0",
+ "media_key": "61b6d24e801b23e06fc2df9405a203aad8389f7ffc8740b4a5885b4f5ff9391a",
+ "file_sha256": "e7ace578c2da599125382176ef0ca30ee5a152a55ac827811942df99aaa2651b",
+ "file_enc_sha256": "e69282bc1221dd82495aa9024b08fd6383ab8b9297108c6ac779278b47b0b322",
+ "responses": [
+ [
+ {
+ "status": 404,
+ "body": null
+ }
+ ],
+ [
+ {
+ "status": 200,
+ "body": null
+ }
+ ]
+ ],
+ "requests": [
+ {
+ "host": 0,
+ "method": "GET",
+ "request_uri": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0\u0026hash=5pKCvBIh3YJJWqkCSwj9Y4Ori5KXEIxqx3kni0ewsyI=\u0026mms-type=image\u0026__wa-mms=",
+ "headers": {
+ "Origin": "https://web.whatsapp.com",
+ "Referer": "https://web.whatsapp.com/",
+ "User-Agent": "whatsmeow-rs-test/1.0"
+ },
+ "body": ""
+ }
+ ],
+ "data": null,
+ "error": "download failed with status code 404",
+ "to_file": false
+ },
+ {
+ "name": "gone",
+ "direct_path": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0",
+ "media_key": "61b6d24e801b23e06fc2df9405a203aad8389f7ffc8740b4a5885b4f5ff9391a",
+ "file_sha256": "e7ace578c2da599125382176ef0ca30ee5a152a55ac827811942df99aaa2651b",
+ "file_enc_sha256": "e69282bc1221dd82495aa9024b08fd6383ab8b9297108c6ac779278b47b0b322",
+ "responses": [
+ [
+ {
+ "status": 410,
+ "body": null
+ }
+ ],
+ [
+ {
+ "status": 200,
+ "body": null
+ }
+ ]
+ ],
+ "requests": [
+ {
+ "host": 0,
+ "method": "GET",
+ "request_uri": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0\u0026hash=5pKCvBIh3YJJWqkCSwj9Y4Ori5KXEIxqx3kni0ewsyI=\u0026mms-type=image\u0026__wa-mms=",
+ "headers": {
+ "Origin": "https://web.whatsapp.com",
+ "Referer": "https://web.whatsapp.com/",
+ "User-Agent": "whatsmeow-rs-test/1.0"
+ },
+ "body": ""
+ }
+ ],
+ "data": null,
+ "error": "download failed with status code 410",
+ "to_file": false
+ },
+ {
+ "name": "last_host_500",
+ "direct_path": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0",
+ "media_key": "61b6d24e801b23e06fc2df9405a203aad8389f7ffc8740b4a5885b4f5ff9391a",
+ "file_sha256": "e7ace578c2da599125382176ef0ca30ee5a152a55ac827811942df99aaa2651b",
+ "file_enc_sha256": "e69282bc1221dd82495aa9024b08fd6383ab8b9297108c6ac779278b47b0b322",
+ "responses": [
+ [
+ {
+ "status": 500,
+ "body": null
+ }
+ ],
+ [
+ {
+ "status": 500,
+ "body": null
+ }
+ ]
+ ],
+ "requests": [
+ {
+ "host": 0,
+ "method": "GET",
+ "request_uri": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0\u0026hash=5pKCvBIh3YJJWqkCSwj9Y4Ori5KXEIxqx3kni0ewsyI=\u0026mms-type=image\u0026__wa-mms=",
+ "headers": {
+ "Origin": "https://web.whatsapp.com",
+ "Referer": "https://web.whatsapp.com/",
+ "User-Agent": "whatsmeow-rs-test/1.0"
+ },
+ "body": ""
+ },
+ {
+ "host": 1,
+ "method": "GET",
+ "request_uri": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0\u0026hash=5pKCvBIh3YJJWqkCSwj9Y4Ori5KXEIxqx3kni0ewsyI=\u0026mms-type=image\u0026__wa-mms=",
+ "headers": {
+ "Origin": "https://web.whatsapp.com",
+ "Referer": "https://web.whatsapp.com/",
+ "User-Agent": "whatsmeow-rs-test/1.0"
+ },
+ "body": ""
+ }
+ ],
+ "data": null,
+ "error": "failed to download media from last host: download failed with status code 500",
+ "to_file": false
+ },
+ {
+ "name": "bad_hmac",
+ "direct_path": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0",
+ "media_key": "61b6d24e801b23e06fc2df9405a203aad8389f7ffc8740b4a5885b4f5ff9391a",
+ "file_sha256": "e7ace578c2da599125382176ef0ca30ee5a152a55ac827811942df99aaa2651b",
+ "file_enc_sha256": "5b596692f203383392a3bdeee934def4e765ae92369c7bd1928bcdfb7eaa8100",
+ "responses": [
+ [
+ {
+ "status": 200,
+ "body": "307e9550bb6bc0077e8ce2d008b7ae058bf4a4151ed61be21aa8c5490fa24b34f7eef210d7af8bdd201cbc21d10167c944b079dab9b5937b7951222ee83c0547e2f43ae79b6a7ed892e4b4540df8c59c18bd0dbd61cafc1e9e886e5cbd38b2b03bf8222392103d3d709306000ea6063e112e0c96e3f90c98250f2816ccc2d184d1c84737775419acb095"
+ }
+ ],
+ [
+ {
+ "status": 200,
+ "body": "307e9550bb6bc0077e8ce2d008b7ae058bf4a4151ed61be21aa8c5490fa24b34f7eef210d7af8bdd201cbc21d10167c944b079dab9b5937b7951222ee83c0547e2f43ae79b6a7ed892e4b4540df8c59c18bd0dbd61cafc1e9e886e5cbd38b2b03bf8222392103d3d709306000ea6063e112e0c96e3f90c98250f2816ccc2d184d1c84737775419acb095"
+ }
+ ]
+ ],
+ "requests": [
+ {
+ "host": 0,
+ "method": "GET",
+ "request_uri": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0\u0026hash=W1lmkvIDODOSo73u6TTe9OdlrpI2nHvRkovN-36qgQA=\u0026mms-type=image\u0026__wa-mms=",
+ "headers": {
+ "Origin": "https://web.whatsapp.com",
+ "Referer": "https://web.whatsapp.com/",
+ "User-Agent": "whatsmeow-rs-test/1.0"
+ },
+ "body": ""
+ },
+ {
+ "host": 1,
+ "method": "GET",
+ "request_uri": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0\u0026hash=W1lmkvIDODOSo73u6TTe9OdlrpI2nHvRkovN-36qgQA=\u0026mms-type=image\u0026__wa-mms=",
+ "headers": {
+ "Origin": "https://web.whatsapp.com",
+ "Referer": "https://web.whatsapp.com/",
+ "User-Agent": "whatsmeow-rs-test/1.0"
+ },
+ "body": ""
+ }
+ ],
+ "data": null,
+ "error": "failed to download media from last host: invalid media hmac",
+ "to_file": false
+ },
+ {
+ "name": "bad_enc_sha256",
+ "direct_path": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0",
+ "media_key": "61b6d24e801b23e06fc2df9405a203aad8389f7ffc8740b4a5885b4f5ff9391a",
+ "file_sha256": "e7ace578c2da599125382176ef0ca30ee5a152a55ac827811942df99aaa2651b",
+ "file_enc_sha256": "8810ad581e59f2bc3928b261707a71308f7e139eb04820366dc4d5c18d980225",
+ "responses": [
+ [
+ {
+ "status": 200,
+ "body": null
+ }
+ ],
+ [
+ {
+ "status": 200,
+ "body": null
+ }
+ ]
+ ],
+ "requests": [
+ {
+ "host": 0,
+ "method": "GET",
+ "request_uri": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0\u0026hash=iBCtWB5Z8rw5KLJhcHpxMI9-E56wSCA2bcTVwY2YAiU=\u0026mms-type=image\u0026__wa-mms=",
+ "headers": {
+ "Origin": "https://web.whatsapp.com",
+ "Referer": "https://web.whatsapp.com/",
+ "User-Agent": "whatsmeow-rs-test/1.0"
+ },
+ "body": ""
+ },
+ {
+ "host": 1,
+ "method": "GET",
+ "request_uri": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0\u0026hash=iBCtWB5Z8rw5KLJhcHpxMI9-E56wSCA2bcTVwY2YAiU=\u0026mms-type=image\u0026__wa-mms=",
+ "headers": {
+ "Origin": "https://web.whatsapp.com",
+ "Referer": "https://web.whatsapp.com/",
+ "User-Agent": "whatsmeow-rs-test/1.0"
+ },
+ "body": ""
+ }
+ ],
+ "data": null,
+ "error": "failed to download media from last host: hash of media ciphertext doesn't match",
+ "to_file": false
+ },
+ {
+ "name": "bad_sha256",
+ "direct_path": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0",
+ "media_key": "61b6d24e801b23e06fc2df9405a203aad8389f7ffc8740b4a5885b4f5ff9391a",
+ "file_sha256": "8810ad581e59f2bc3928b261707a71308f7e139eb04820366dc4d5c18d980225",
+ "file_enc_sha256": "e69282bc1221dd82495aa9024b08fd6383ab8b9297108c6ac779278b47b0b322",
+ "responses": [
+ [
+ {
+ "status": 200,
+ "body": null
+ }
+ ],
+ [
+ {
+ "status": 200,
+ "body": null
+ }
+ ]
+ ],
+ "requests": [
+ {
+ "host": 0,
+ "method": "GET",
+ "request_uri": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0\u0026hash=5pKCvBIh3YJJWqkCSwj9Y4Ori5KXEIxqx3kni0ewsyI=\u0026mms-type=image\u0026__wa-mms=",
+ "headers": {
+ "Origin": "https://web.whatsapp.com",
+ "Referer": "https://web.whatsapp.com/",
+ "User-Agent": "whatsmeow-rs-test/1.0"
+ },
+ "body": ""
+ }
+ ],
+ "data": "77686174736d656f77206d656469612075706c6f61642077686174736d656f77206d656469612075706c6f61642077686174736d656f77206d656469612075706c6f61642077686174736d656f77206d656469612075706c6f61642077686174736d656f77206d656469612075706c6f616420",
+ "error": "hash of media plaintext doesn't match",
+ "to_file": false
+ },
+ {
+ "name": "too_short",
+ "direct_path": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0",
+ "media_key": "61b6d24e801b23e06fc2df9405a203aad8389f7ffc8740b4a5885b4f5ff9391a",
+ "file_sha256": "e7ace578c2da599125382176ef0ca30ee5a152a55ac827811942df99aaa2651b",
+ "file_enc_sha256": "e69282bc1221dd82495aa9024b08fd6383ab8b9297108c6ac779278b47b0b322",
+ "responses": [
+ [
+ {
+ "status": 200,
+ "body": "0102030405060708090a"
+ }
+ ],
+ [
+ {
+ "status": 200,
+ "body": null
+ }
+ ]
+ ],
+ "requests": [
+ {
+ "host": 0,
+ "method": "GET",
+ "request_uri": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0\u0026hash=5pKCvBIh3YJJWqkCSwj9Y4Ori5KXEIxqx3kni0ewsyI=\u0026mms-type=image\u0026__wa-mms=",
+ "headers": {
+ "Origin": "https://web.whatsapp.com",
+ "Referer": "https://web.whatsapp.com/",
+ "User-Agent": "whatsmeow-rs-test/1.0"
+ },
+ "body": ""
+ },
+ {
+ "host": 1,
+ "method": "GET",
+ "request_uri": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0\u0026hash=5pKCvBIh3YJJWqkCSwj9Y4Ori5KXEIxqx3kni0ewsyI=\u0026mms-type=image\u0026__wa-mms=",
+ "headers": {
+ "Origin": "https://web.whatsapp.com",
+ "Referer": "https://web.whatsapp.com/",
+ "User-Agent": "whatsmeow-rs-test/1.0"
+ },
+ "body": ""
+ }
+ ],
+ "data": "77686174736d656f77206d656469612075706c6f61642077686174736d656f77206d656469612075706c6f61642077686174736d656f77206d656469612075706c6f61642077686174736d656f77206d656469612075706c6f61642077686174736d656f77206d656469612075706c6f616420",
+ "error": "",
+ "to_file": false
+ },
+ {
+ "name": "unencrypted",
+ "direct_path": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0",
+ "media_key": null,
+ "file_sha256": "e3e1eda7e8eba1f5a068ecbbf96b4d964aea22457890e3f87fba27cfe3b757c4",
+ "file_enc_sha256": null,
+ "responses": [
+ [
+ {
+ "status": 200,
+ "body": "706c61696e206e6577736c6574746572206d65646961"
+ }
+ ],
+ [
+ {
+ "status": 200,
+ "body": null
+ }
+ ]
+ ],
+ "requests": [
+ {
+ "host": 0,
+ "method": "GET",
+ "request_uri": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0\u0026hash=\u0026mms-type=image\u0026__wa-mms=",
+ "headers": {
+ "Origin": "https://web.whatsapp.com",
+ "Referer": "https://web.whatsapp.com/",
+ "User-Agent": "whatsmeow-rs-test/1.0"
+ },
+ "body": ""
+ }
+ ],
+ "data": "706c61696e206e6577736c6574746572206d65646961",
+ "error": "",
+ "to_file": false
+ },
+ {
+ "name": "unencrypted_bad_sha256",
+ "direct_path": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0",
+ "media_key": null,
+ "file_sha256": "8810ad581e59f2bc3928b261707a71308f7e139eb04820366dc4d5c18d980225",
+ "file_enc_sha256": null,
+ "responses": [
+ [
+ {
+ "status": 200,
+ "body": "706c61696e206e6577736c6574746572206d65646961"
+ }
+ ],
+ [
+ {
+ "status": 200,
+ "body": null
+ }
+ ]
+ ],
+ "requests": [
+ {
+ "host": 0,
+ "method": "GET",
+ "request_uri": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0\u0026hash=\u0026mms-type=image\u0026__wa-mms=",
+ "headers": {
+ "Origin": "https://web.whatsapp.com",
+ "Referer": "https://web.whatsapp.com/",
+ "User-Agent": "whatsmeow-rs-test/1.0"
+ },
+ "body": ""
+ },
+ {
+ "host": 1,
+ "method": "GET",
+ "request_uri": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0\u0026hash=\u0026mms-type=image\u0026__wa-mms=",
+ "headers": {
+ "Origin": "https://web.whatsapp.com",
+ "Referer": "https://web.whatsapp.com/",
+ "User-Agent": "whatsmeow-rs-test/1.0"
+ },
+ "body": ""
+ }
+ ],
+ "data": null,
+ "error": "failed to download media from last host: hash of unencrypted media doesn't match",
+ "to_file": false
+ },
+ {
+ "name": "no_slash",
+ "direct_path": "v/no-slash",
+ "media_key": "61b6d24e801b23e06fc2df9405a203aad8389f7ffc8740b4a5885b4f5ff9391a",
+ "file_sha256": "e7ace578c2da599125382176ef0ca30ee5a152a55ac827811942df99aaa2651b",
+ "file_enc_sha256": "e69282bc1221dd82495aa9024b08fd6383ab8b9297108c6ac779278b47b0b322",
+ "responses": [
+ [
+ {
+ "status": 200,
+ "body": null
+ }
+ ],
+ [
+ {
+ "status": 200,
+ "body": null
+ }
+ ]
+ ],
+ "requests": null,
+ "data": null,
+ "error": "media download path does not start with slash: v/no-slash",
+ "to_file": false
+ },
+ {
+ "name": "ok",
+ "direct_path": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0",
+ "media_key": "61b6d24e801b23e06fc2df9405a203aad8389f7ffc8740b4a5885b4f5ff9391a",
+ "file_sha256": "e7ace578c2da599125382176ef0ca30ee5a152a55ac827811942df99aaa2651b",
+ "file_enc_sha256": "e69282bc1221dd82495aa9024b08fd6383ab8b9297108c6ac779278b47b0b322",
+ "responses": [
+ [
+ {
+ "status": 200,
+ "body": null
+ }
+ ],
+ [
+ {
+ "status": 200,
+ "body": null
+ }
+ ]
+ ],
+ "requests": [
+ {
+ "host": 0,
+ "method": "GET",
+ "request_uri": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0\u0026hash=5pKCvBIh3YJJWqkCSwj9Y4Ori5KXEIxqx3kni0ewsyI=\u0026mms-type=image\u0026__wa-mms=",
+ "headers": {
+ "Origin": "https://web.whatsapp.com",
+ "Referer": "https://web.whatsapp.com/",
+ "User-Agent": "whatsmeow-rs-test/1.0"
+ },
+ "body": ""
+ }
+ ],
+ "data": "77686174736d656f77206d656469612075706c6f61642077686174736d656f77206d656469612075706c6f61642077686174736d656f77206d656469612075706c6f61642077686174736d656f77206d656469612075706c6f61642077686174736d656f77206d656469612075706c6f616420",
+ "error": "",
+ "to_file": true
+ },
+ {
+ "name": "next_host_on_500",
+ "direct_path": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0",
+ "media_key": "61b6d24e801b23e06fc2df9405a203aad8389f7ffc8740b4a5885b4f5ff9391a",
+ "file_sha256": "e7ace578c2da599125382176ef0ca30ee5a152a55ac827811942df99aaa2651b",
+ "file_enc_sha256": "e69282bc1221dd82495aa9024b08fd6383ab8b9297108c6ac779278b47b0b322",
+ "responses": [
+ [
+ {
+ "status": 500,
+ "body": null
+ }
+ ],
+ [
+ {
+ "status": 200,
+ "body": null
+ }
+ ]
+ ],
+ "requests": [
+ {
+ "host": 0,
+ "method": "GET",
+ "request_uri": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0\u0026hash=5pKCvBIh3YJJWqkCSwj9Y4Ori5KXEIxqx3kni0ewsyI=\u0026mms-type=image\u0026__wa-mms=",
+ "headers": {
+ "Origin": "https://web.whatsapp.com",
+ "Referer": "https://web.whatsapp.com/",
+ "User-Agent": "whatsmeow-rs-test/1.0"
+ },
+ "body": ""
+ },
+ {
+ "host": 1,
+ "method": "GET",
+ "request_uri": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0\u0026hash=5pKCvBIh3YJJWqkCSwj9Y4Ori5KXEIxqx3kni0ewsyI=\u0026mms-type=image\u0026__wa-mms=",
+ "headers": {
+ "Origin": "https://web.whatsapp.com",
+ "Referer": "https://web.whatsapp.com/",
+ "User-Agent": "whatsmeow-rs-test/1.0"
+ },
+ "body": ""
+ }
+ ],
+ "data": "77686174736d656f77206d656469612075706c6f61642077686174736d656f77206d656469612075706c6f61642077686174736d656f77206d656469612075706c6f61642077686174736d656f77206d656469612075706c6f61642077686174736d656f77206d656469612075706c6f616420",
+ "error": "",
+ "to_file": true
+ },
+ {
+ "name": "retry_on_503",
+ "direct_path": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0",
+ "media_key": "61b6d24e801b23e06fc2df9405a203aad8389f7ffc8740b4a5885b4f5ff9391a",
+ "file_sha256": "e7ace578c2da599125382176ef0ca30ee5a152a55ac827811942df99aaa2651b",
+ "file_enc_sha256": "e69282bc1221dd82495aa9024b08fd6383ab8b9297108c6ac779278b47b0b322",
+ "responses": [
+ [
+ {
+ "status": 503,
+ "retry_after": "0",
+ "body": null
+ },
+ {
+ "status": 429,
+ "retry_after": "0",
+ "body": null
+ },
+ {
+ "status": 200,
+ "body": null
+ }
+ ],
+ [
+ {
+ "status": 200,
+ "body": null
+ }
+ ]
+ ],
+ "requests": [
+ {
+ "host": 0,
+ "method": "GET",
+ "request_uri": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0\u0026hash=5pKCvBIh3YJJWqkCSwj9Y4Ori5KXEIxqx3kni0ewsyI=\u0026mms-type=image\u0026__wa-mms=",
+ "headers": {
+ "Origin": "https://web.whatsapp.com",
+ "Referer": "https://web.whatsapp.com/",
+ "User-Agent": "whatsmeow-rs-test/1.0"
+ },
+ "body": ""
+ },
+ {
+ "host": 0,
+ "method": "GET",
+ "request_uri": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0\u0026hash=5pKCvBIh3YJJWqkCSwj9Y4Ori5KXEIxqx3kni0ewsyI=\u0026mms-type=image\u0026__wa-mms=",
+ "headers": {
+ "Origin": "https://web.whatsapp.com",
+ "Referer": "https://web.whatsapp.com/",
+ "User-Agent": "whatsmeow-rs-test/1.0"
+ },
+ "body": ""
+ },
+ {
+ "host": 0,
+ "method": "GET",
+ "request_uri": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0\u0026hash=5pKCvBIh3YJJWqkCSwj9Y4Ori5KXEIxqx3kni0ewsyI=\u0026mms-type=image\u0026__wa-mms=",
+ "headers": {
+ "Origin": "https://web.whatsapp.com",
+ "Referer": "https://web.whatsapp.com/",
+ "User-Agent": "whatsmeow-rs-test/1.0"
+ },
+ "body": ""
+ }
+ ],
+ "data": "77686174736d656f77206d656469612075706c6f61642077686174736d656f77206d656469612075706c6f61642077686174736d656f77206d656469612075706c6f61642077686174736d656f77206d656469612075706c6f61642077686174736d656f77206d656469612075706c6f616420",
+ "error": "",
+ "to_file": true
+ },
+ {
+ "name": "retries_exhausted",
+ "direct_path": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0",
+ "media_key": "61b6d24e801b23e06fc2df9405a203aad8389f7ffc8740b4a5885b4f5ff9391a",
+ "file_sha256": "e7ace578c2da599125382176ef0ca30ee5a152a55ac827811942df99aaa2651b",
+ "file_enc_sha256": "e69282bc1221dd82495aa9024b08fd6383ab8b9297108c6ac779278b47b0b322",
+ "responses": [
+ [
+ {
+ "status": 502,
+ "retry_after": "0",
+ "body": null
+ }
+ ],
+ [
+ {
+ "status": 200,
+ "body": null
+ }
+ ]
+ ],
+ "requests": [
+ {
+ "host": 0,
+ "method": "GET",
+ "request_uri": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0\u0026hash=5pKCvBIh3YJJWqkCSwj9Y4Ori5KXEIxqx3kni0ewsyI=\u0026mms-type=image\u0026__wa-mms=",
+ "headers": {
+ "Origin": "https://web.whatsapp.com",
+ "Referer": "https://web.whatsapp.com/",
+ "User-Agent": "whatsmeow-rs-test/1.0"
+ },
+ "body": ""
+ },
+ {
+ "host": 0,
+ "method": "GET",
+ "request_uri": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0\u0026hash=5pKCvBIh3YJJWqkCSwj9Y4Ori5KXEIxqx3kni0ewsyI=\u0026mms-type=image\u0026__wa-mms=",
+ "headers": {
+ "Origin": "https://web.whatsapp.com",
+ "Referer": "https://web.whatsapp.com/",
+ "User-Agent": "whatsmeow-rs-test/1.0"
+ },
+ "body": ""
+ },
+ {
+ "host": 0,
+ "method": "GET",
+ "request_uri": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0\u0026hash=5pKCvBIh3YJJWqkCSwj9Y4Ori5KXEIxqx3kni0ewsyI=\u0026mms-type=image\u0026__wa-mms=",
+ "headers": {
+ "Origin": "https://web.whatsapp.com",
+ "Referer": "https://web.whatsapp.com/",
+ "User-Agent": "whatsmeow-rs-test/1.0"
+ },
+ "body": ""
+ },
+ {
+ "host": 0,
+ "method": "GET",
+ "request_uri": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0\u0026hash=5pKCvBIh3YJJWqkCSwj9Y4Ori5KXEIxqx3kni0ewsyI=\u0026mms-type=image\u0026__wa-mms=",
+ "headers": {
+ "Origin": "https://web.whatsapp.com",
+ "Referer": "https://web.whatsapp.com/",
+ "User-Agent": "whatsmeow-rs-test/1.0"
+ },
+ "body": ""
+ },
+ {
+ "host": 0,
+ "method": "GET",
+ "request_uri": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0\u0026hash=5pKCvBIh3YJJWqkCSwj9Y4Ori5KXEIxqx3kni0ewsyI=\u0026mms-type=image\u0026__wa-mms=",
+ "headers": {
+ "Origin": "https://web.whatsapp.com",
+ "Referer": "https://web.whatsapp.com/",
+ "User-Agent": "whatsmeow-rs-test/1.0"
+ },
+ "body": ""
+ },
+ {
+ "host": 1,
+ "method": "GET",
+ "request_uri": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0\u0026hash=5pKCvBIh3YJJWqkCSwj9Y4Ori5KXEIxqx3kni0ewsyI=\u0026mms-type=image\u0026__wa-mms=",
+ "headers": {
+ "Origin": "https://web.whatsapp.com",
+ "Referer": "https://web.whatsapp.com/",
+ "User-Agent": "whatsmeow-rs-test/1.0"
+ },
+ "body": ""
+ }
+ ],
+ "data": "77686174736d656f77206d656469612075706c6f61642077686174736d656f77206d656469612075706c6f61642077686174736d656f77206d656469612075706c6f61642077686174736d656f77206d656469612075706c6f61642077686174736d656f77206d656469612075706c6f616420",
+ "error": "",
+ "to_file": true
+ },
+ {
+ "name": "not_found",
+ "direct_path": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0",
+ "media_key": "61b6d24e801b23e06fc2df9405a203aad8389f7ffc8740b4a5885b4f5ff9391a",
+ "file_sha256": "e7ace578c2da599125382176ef0ca30ee5a152a55ac827811942df99aaa2651b",
+ "file_enc_sha256": "e69282bc1221dd82495aa9024b08fd6383ab8b9297108c6ac779278b47b0b322",
+ "responses": [
+ [
+ {
+ "status": 404,
+ "body": null
+ }
+ ],
+ [
+ {
+ "status": 200,
+ "body": null
+ }
+ ]
+ ],
+ "requests": [
+ {
+ "host": 0,
+ "method": "GET",
+ "request_uri": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0\u0026hash=5pKCvBIh3YJJWqkCSwj9Y4Ori5KXEIxqx3kni0ewsyI=\u0026mms-type=image\u0026__wa-mms=",
+ "headers": {
+ "Origin": "https://web.whatsapp.com",
+ "Referer": "https://web.whatsapp.com/",
+ "User-Agent": "whatsmeow-rs-test/1.0"
+ },
+ "body": ""
+ }
+ ],
+ "data": null,
+ "error": "download failed with status code 404",
+ "to_file": true
+ },
+ {
+ "name": "gone",
+ "direct_path": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0",
+ "media_key": "61b6d24e801b23e06fc2df9405a203aad8389f7ffc8740b4a5885b4f5ff9391a",
+ "file_sha256": "e7ace578c2da599125382176ef0ca30ee5a152a55ac827811942df99aaa2651b",
+ "file_enc_sha256": "e69282bc1221dd82495aa9024b08fd6383ab8b9297108c6ac779278b47b0b322",
+ "responses": [
+ [
+ {
+ "status": 410,
+ "body": null
+ }
+ ],
+ [
+ {
+ "status": 200,
+ "body": null
+ }
+ ]
+ ],
+ "requests": [
+ {
+ "host": 0,
+ "method": "GET",
+ "request_uri": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0\u0026hash=5pKCvBIh3YJJWqkCSwj9Y4Ori5KXEIxqx3kni0ewsyI=\u0026mms-type=image\u0026__wa-mms=",
+ "headers": {
+ "Origin": "https://web.whatsapp.com",
+ "Referer": "https://web.whatsapp.com/",
+ "User-Agent": "whatsmeow-rs-test/1.0"
+ },
+ "body": ""
+ }
+ ],
+ "data": null,
+ "error": "download failed with status code 410",
+ "to_file": true
+ },
+ {
+ "name": "last_host_500",
+ "direct_path": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0",
+ "media_key": "61b6d24e801b23e06fc2df9405a203aad8389f7ffc8740b4a5885b4f5ff9391a",
+ "file_sha256": "e7ace578c2da599125382176ef0ca30ee5a152a55ac827811942df99aaa2651b",
+ "file_enc_sha256": "e69282bc1221dd82495aa9024b08fd6383ab8b9297108c6ac779278b47b0b322",
+ "responses": [
+ [
+ {
+ "status": 500,
+ "body": null
+ }
+ ],
+ [
+ {
+ "status": 500,
+ "body": null
+ }
+ ]
+ ],
+ "requests": [
+ {
+ "host": 0,
+ "method": "GET",
+ "request_uri": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0\u0026hash=5pKCvBIh3YJJWqkCSwj9Y4Ori5KXEIxqx3kni0ewsyI=\u0026mms-type=image\u0026__wa-mms=",
+ "headers": {
+ "Origin": "https://web.whatsapp.com",
+ "Referer": "https://web.whatsapp.com/",
+ "User-Agent": "whatsmeow-rs-test/1.0"
+ },
+ "body": ""
+ },
+ {
+ "host": 1,
+ "method": "GET",
+ "request_uri": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0\u0026hash=5pKCvBIh3YJJWqkCSwj9Y4Ori5KXEIxqx3kni0ewsyI=\u0026mms-type=image\u0026__wa-mms=",
+ "headers": {
+ "Origin": "https://web.whatsapp.com",
+ "Referer": "https://web.whatsapp.com/",
+ "User-Agent": "whatsmeow-rs-test/1.0"
+ },
+ "body": ""
+ }
+ ],
+ "data": null,
+ "error": "failed to download media from last host: download failed with status code 500",
+ "to_file": true
+ },
+ {
+ "name": "bad_hmac",
+ "direct_path": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0",
+ "media_key": "61b6d24e801b23e06fc2df9405a203aad8389f7ffc8740b4a5885b4f5ff9391a",
+ "file_sha256": "e7ace578c2da599125382176ef0ca30ee5a152a55ac827811942df99aaa2651b",
+ "file_enc_sha256": "5b596692f203383392a3bdeee934def4e765ae92369c7bd1928bcdfb7eaa8100",
+ "responses": [
+ [
+ {
+ "status": 200,
+ "body": "307e9550bb6bc0077e8ce2d008b7ae058bf4a4151ed61be21aa8c5490fa24b34f7eef210d7af8bdd201cbc21d10167c944b079dab9b5937b7951222ee83c0547e2f43ae79b6a7ed892e4b4540df8c59c18bd0dbd61cafc1e9e886e5cbd38b2b03bf8222392103d3d709306000ea6063e112e0c96e3f90c98250f2816ccc2d184d1c84737775419acb095"
+ }
+ ],
+ [
+ {
+ "status": 200,
+ "body": "307e9550bb6bc0077e8ce2d008b7ae058bf4a4151ed61be21aa8c5490fa24b34f7eef210d7af8bdd201cbc21d10167c944b079dab9b5937b7951222ee83c0547e2f43ae79b6a7ed892e4b4540df8c59c18bd0dbd61cafc1e9e886e5cbd38b2b03bf8222392103d3d709306000ea6063e112e0c96e3f90c98250f2816ccc2d184d1c84737775419acb095"
+ }
+ ]
+ ],
+ "requests": [
+ {
+ "host": 0,
+ "method": "GET",
+ "request_uri": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0\u0026hash=W1lmkvIDODOSo73u6TTe9OdlrpI2nHvRkovN-36qgQA=\u0026mms-type=image\u0026__wa-mms=",
+ "headers": {
+ "Origin": "https://web.whatsapp.com",
+ "Referer": "https://web.whatsapp.com/",
+ "User-Agent": "whatsmeow-rs-test/1.0"
+ },
+ "body": ""
+ },
+ {
+ "host": 1,
+ "method": "GET",
+ "request_uri": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0\u0026hash=W1lmkvIDODOSo73u6TTe9OdlrpI2nHvRkovN-36qgQA=\u0026mms-type=image\u0026__wa-mms=",
+ "headers": {
+ "Origin": "https://web.whatsapp.com",
+ "Referer": "https://web.whatsapp.com/",
+ "User-Agent": "whatsmeow-rs-test/1.0"
+ },
+ "body": ""
+ }
+ ],
+ "data": null,
+ "error": "failed to download media from last host: invalid media hmac",
+ "to_file": true
+ },
+ {
+ "name": "bad_enc_sha256",
+ "direct_path": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0",
+ "media_key": "61b6d24e801b23e06fc2df9405a203aad8389f7ffc8740b4a5885b4f5ff9391a",
+ "file_sha256": "e7ace578c2da599125382176ef0ca30ee5a152a55ac827811942df99aaa2651b",
+ "file_enc_sha256": "8810ad581e59f2bc3928b261707a71308f7e139eb04820366dc4d5c18d980225",
+ "responses": [
+ [
+ {
+ "status": 200,
+ "body": null
+ }
+ ],
+ [
+ {
+ "status": 200,
+ "body": null
+ }
+ ]
+ ],
+ "requests": [
+ {
+ "host": 0,
+ "method": "GET",
+ "request_uri": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0\u0026hash=iBCtWB5Z8rw5KLJhcHpxMI9-E56wSCA2bcTVwY2YAiU=\u0026mms-type=image\u0026__wa-mms=",
+ "headers": {
+ "Origin": "https://web.whatsapp.com",
+ "Referer": "https://web.whatsapp.com/",
+ "User-Agent": "whatsmeow-rs-test/1.0"
+ },
+ "body": ""
+ },
+ {
+ "host": 1,
+ "method": "GET",
+ "request_uri": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0\u0026hash=iBCtWB5Z8rw5KLJhcHpxMI9-E56wSCA2bcTVwY2YAiU=\u0026mms-type=image\u0026__wa-mms=",
+ "headers": {
+ "Origin": "https://web.whatsapp.com",
+ "Referer": "https://web.whatsapp.com/",
+ "User-Agent": "whatsmeow-rs-test/1.0"
+ },
+ "body": ""
+ }
+ ],
+ "data": null,
+ "error": "failed to download media from last host: hash of media ciphertext doesn't match",
+ "to_file": true
+ },
+ {
+ "name": "bad_sha256",
+ "direct_path": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0",
+ "media_key": "61b6d24e801b23e06fc2df9405a203aad8389f7ffc8740b4a5885b4f5ff9391a",
+ "file_sha256": "8810ad581e59f2bc3928b261707a71308f7e139eb04820366dc4d5c18d980225",
+ "file_enc_sha256": "e69282bc1221dd82495aa9024b08fd6383ab8b9297108c6ac779278b47b0b322",
+ "responses": [
+ [
+ {
+ "status": 200,
+ "body": null
+ }
+ ],
+ [
+ {
+ "status": 200,
+ "body": null
+ }
+ ]
+ ],
+ "requests": [
+ {
+ "host": 0,
+ "method": "GET",
+ "request_uri": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0\u0026hash=5pKCvBIh3YJJWqkCSwj9Y4Ori5KXEIxqx3kni0ewsyI=\u0026mms-type=image\u0026__wa-mms=",
+ "headers": {
+ "Origin": "https://web.whatsapp.com",
+ "Referer": "https://web.whatsapp.com/",
+ "User-Agent": "whatsmeow-rs-test/1.0"
+ },
+ "body": ""
+ }
+ ],
+ "data": null,
+ "error": "hash of media plaintext doesn't match",
+ "to_file": true
+ },
+ {
+ "name": "too_short",
+ "direct_path": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0",
+ "media_key": "61b6d24e801b23e06fc2df9405a203aad8389f7ffc8740b4a5885b4f5ff9391a",
+ "file_sha256": "e7ace578c2da599125382176ef0ca30ee5a152a55ac827811942df99aaa2651b",
+ "file_enc_sha256": "e69282bc1221dd82495aa9024b08fd6383ab8b9297108c6ac779278b47b0b322",
+ "responses": [
+ [
+ {
+ "status": 200,
+ "body": "0102030405060708090a"
+ }
+ ],
+ [
+ {
+ "status": 200,
+ "body": null
+ }
+ ]
+ ],
+ "requests": [
+ {
+ "host": 0,
+ "method": "GET",
+ "request_uri": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0\u0026hash=5pKCvBIh3YJJWqkCSwj9Y4Ori5KXEIxqx3kni0ewsyI=\u0026mms-type=image\u0026__wa-mms=",
+ "headers": {
+ "Origin": "https://web.whatsapp.com",
+ "Referer": "https://web.whatsapp.com/",
+ "User-Agent": "whatsmeow-rs-test/1.0"
+ },
+ "body": ""
+ },
+ {
+ "host": 1,
+ "method": "GET",
+ "request_uri": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0\u0026hash=5pKCvBIh3YJJWqkCSwj9Y4Ori5KXEIxqx3kni0ewsyI=\u0026mms-type=image\u0026__wa-mms=",
+ "headers": {
+ "Origin": "https://web.whatsapp.com",
+ "Referer": "https://web.whatsapp.com/",
+ "User-Agent": "whatsmeow-rs-test/1.0"
+ },
+ "body": ""
+ }
+ ],
+ "data": null,
+ "error": "failed to download media from last host: invalid media hmac",
+ "to_file": true
+ },
+ {
+ "name": "unencrypted",
+ "direct_path": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0",
+ "media_key": null,
+ "file_sha256": "e3e1eda7e8eba1f5a068ecbbf96b4d964aea22457890e3f87fba27cfe3b757c4",
+ "file_enc_sha256": null,
+ "responses": [
+ [
+ {
+ "status": 200,
+ "body": "706c61696e206e6577736c6574746572206d65646961"
+ }
+ ],
+ [
+ {
+ "status": 200,
+ "body": null
+ }
+ ]
+ ],
+ "requests": [
+ {
+ "host": 0,
+ "method": "GET",
+ "request_uri": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0\u0026hash=\u0026mms-type=image\u0026__wa-mms=",
+ "headers": {
+ "Origin": "https://web.whatsapp.com",
+ "Referer": "https://web.whatsapp.com/",
+ "User-Agent": "whatsmeow-rs-test/1.0"
+ },
+ "body": ""
+ }
+ ],
+ "data": "706c61696e206e6577736c6574746572206d65646961",
+ "error": "",
+ "to_file": true
+ },
+ {
+ "name": "unencrypted_bad_sha256",
+ "direct_path": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0",
+ "media_key": null,
+ "file_sha256": "8810ad581e59f2bc3928b261707a71308f7e139eb04820366dc4d5c18d980225",
+ "file_enc_sha256": null,
+ "responses": [
+ [
+ {
+ "status": 200,
+ "body": "706c61696e206e6577736c6574746572206d65646961"
+ }
+ ],
+ [
+ {
+ "status": 200,
+ "body": null
+ }
+ ]
+ ],
+ "requests": [
+ {
+ "host": 0,
+ "method": "GET",
+ "request_uri": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0\u0026hash=\u0026mms-type=image\u0026__wa-mms=",
+ "headers": {
+ "Origin": "https://web.whatsapp.com",
+ "Referer": "https://web.whatsapp.com/",
+ "User-Agent": "whatsmeow-rs-test/1.0"
+ },
+ "body": ""
+ },
+ {
+ "host": 1,
+ "method": "GET",
+ "request_uri": "/v/t62.7118-24/12345_67890_n.enc?ccb=11-4\u0026oh=01_Q5Aa\u0026oe=6700\u0026_nc_sid=5e03e0\u0026hash=\u0026mms-type=image\u0026__wa-mms=",
+ "headers": {
+ "Origin": "https://web.whatsapp.com",
+ "Referer": "https://web.whatsapp.com/",
+ "User-Agent": "whatsmeow-rs-test/1.0"
+ },
+ "body": ""
+ }
+ ],
+ "data": null,
+ "error": "failed to download media from last host: hash of unencrypted media doesn't match",
+ "to_file": true
+ },
+ {
+ "name": "no_slash",
+ "direct_path": "v/no-slash",
+ "media_key": "61b6d24e801b23e06fc2df9405a203aad8389f7ffc8740b4a5885b4f5ff9391a",
+ "file_sha256": "e7ace578c2da599125382176ef0ca30ee5a152a55ac827811942df99aaa2651b",
+ "file_enc_sha256": "e69282bc1221dd82495aa9024b08fd6383ab8b9297108c6ac779278b47b0b322",
+ "responses": [
+ [
+ {
+ "status": 200,
+ "body": null
+ }
+ ],
+ [
+ {
+ "status": 200,
+ "body": null
+ }
+ ]
+ ],
+ "requests": null,
+ "data": null,
+ "error": "media download path does not start with slash: v/no-slash",
+ "to_file": true
+ }
+ ],
+ "delete": {
+ "media_type": "WhatsApp History Keys",
+ "direct_path": "/v/t62.15575-24/hist.enc?ccb=11-4\u0026oh=01",
+ "enc_file_hash": "e69282bc1221dd82495aa9024b08fd6383ab8b9297108c6ac779278b47b0b322",
+ "enc_handle": "enc-handle",
+ "companion_meta_nonce": "companion-nonce",
+ "requests": [
+ {
+ "host": 0,
+ "method": "DELETE",
+ "request_uri": "/mms/md-msg-hist/5pKCvBIh3YJJWqkCSwj9Y4Ori5KXEIxqx3kni0ewsyI=?auth=AUTH+token%2Fwith%2Bodd%3Dchars~%2A%21\u0026d_md=L3YvdDYyLjE1NTc1LTI0L2hpc3QuZW5j\u0026e_handle=enc-handle\u0026token=5pKCvBIh3YJJWqkCSwj9Y4Ori5KXEIxqx3kni0ewsyI%3D",
+ "headers": {
+ "Companion_user_secret": "companion-nonce",
+ "Origin": "https://web.whatsapp.com",
+ "Referer": "https://web.whatsapp.com/",
+ "User-Agent": "Go-http-client/1.1"
+ },
+ "body": ""
+ }
+ ]
+ },
+ "media_conn": {
+ "response": "00f8081906fa000308ff861234b5678a1f0414f801f80a3aa9fc1c4155544820746f6b656e2f776974682b6f64643d63686172737e2a21bdbe7cff8321600f63cff803f80472468bf801f80158f8015ef8057246fc1d6d656469612d616d73322d312e63646e2e77686174736170702e6e657404bc",
+ "auth": "AUTH token/with+odd=chars~*!",
+ "auth_ttl": 21600,
+ "ttl": 300,
+ "max_buckets": 12,
+ "hosts": [
+ {
+ "hostname": "mmg.whatsapp.net"
+ },
+ {
+ "hostname": "media-ams2-1.cdn.whatsapp.net"
+ }
+ ],
+ "request": "00f80a1908ff861234b5678a2f16c2045a11fa0003f801f8013a"
+ }
+}
diff --git a/crates/whatsmeow/testdata/message.json b/crates/whatsmeow/testdata/message.json
new file mode 100644
index 0000000000..8c871eda51
--- /dev/null
+++ b/crates/whatsmeow/testdata/message.json
@@ -0,0 +1,181 @@
+{
+ "hashes": [
+ {
+ "hash": "2:XzulbVk1",
+ "jids": [
+ "5550001:[email protected]"
+ ]
+ },
+ {
+ "hash": "2:Gp17HBNi",
+ "jids": [
+ "777:1@lid",
+ "777@lid",
+ ]
+ },
+ {
+ "hash": "2:47DEQpj8",
+ "jids": []
+ }
+ ],
+ "sources": [
+ {
+ "node": "00f80d1306faff845550001f0308fb01a11aff051700000000043818fc0450656572fc0a73656e6465725f6c6964faef7e76",
+ "chat": "[email protected]",
+ "sender": "[email protected]",
+ "from_me": false,
+ "group": false,
+ "addressing_mode": "",
+ "sender_alt": "777@lid",
+ "recipient_alt": "",
+ "id": "A1",
+ "t": 1700000000,
+ "push_name": "Peer",
+ "type": "text",
+ "edit": "",
+ "media_type": ""
+ },
+ {
+ "node": "00f8121306faff091203630000000000011c05f70103ef7efc0e7061727469636970616e745f706efaff845550001f03fc0f61646472657373696e675f6d6f64657608fb01a21aff05170000000104379555f801f8031d2643",
+ "chat": "[email protected]",
+ "sender": "777:3@lid",
+ "from_me": false,
+ "group": true,
+ "addressing_mode": "lid",
+ "sender_alt": "5550001:[email protected]",
+ "recipient_alt": "",
+ "id": "A2",
+ "t": 1700000001,
+ "push_name": "",
+ "type": "media",
+ "edit": "1",
+ "media_type": "image"
+ },
+ {
+ "node": "00f80d13043806f70007ff02123494faff845550001f03fc12706565725f726563697069656e745f6c6964faef7e7608fb01a31aff051700000002",
+ "chat": "[email protected]",
+ "sender": "1234:[email protected]",
+ "from_me": true,
+ "group": false,
+ "addressing_mode": "",
+ "sender_alt": "",
+ "recipient_alt": "777@lid",
+ "id": "A3",
+ "t": 1700000002,
+ "push_name": "",
+ "type": "text",
+ "edit": "",
+ "media_type": ""
+ },
+ {
+ "node": "00f80b1306f70102ff02987608fb01a41aff0517000000030438fc11706565725f726563697069656e745f706efaff845550001f03",
+ "chat": "9876@lid",
+ "sender": "9876:2@lid",
+ "from_me": true,
+ "group": false,
+ "addressing_mode": "",
+ "sender_alt": "",
+ "recipient_alt": "[email protected]",
+ "id": "A4",
+ "t": 1700000003,
+ "push_name": "",
+ "type": "text",
+ "edit": "",
+ "media_type": ""
+ }
+ ],
+ "types": [
+ {
+ "message": "0a026869",
+ "type": "text",
+ "media_type": "",
+ "edit": "",
+ "plaintext": "0a026869",
+ "device_sent_plaintext": "fa010f0a07373737406c696412040a026869"
+ },
+ {
+ "message": "1a051a03706963",
+ "type": "media",
+ "media_type": "image",
+ "edit": "",
+ "plaintext": "1a051a03706963",
+ "device_sent_plaintext": "fa01120a07373737406c696412071a051a03706963"
+ },
+ {
+ "message": "42023001",
+ "type": "media",
+ "media_type": "ptt",
+ "edit": "",
+ "plaintext": "42023001",
+ "device_sent_plaintext": "fa010f0a07373737406c6964120442023001"
+ },
+ {
+ "message": "4a024001",
+ "type": "media",
+ "media_type": "gif",
+ "edit": "",
+ "plaintext": "4a024001",
+ "device_sent_plaintext": "fa010f0a07373737406c696412044a024001"
+ },
+ {
+ "message": "32060a0178320174",
+ "type": "media",
+ "media_type": "url",
+ "edit": "",
+ "plaintext": "32060a0178320174",
+ "device_sent_plaintext": "fa01130a07373737406c6964120832060a0178320174"
+ },
+ {
+ "message": "c202040a023a00",
+ "type": "media",
+ "media_type": "document",
+ "edit": "",
+ "plaintext": "c202040a023a00",
+ "device_sent_plaintext": "fa01120a07373737406c69641207c202040a023a00"
+ },
+ {
+ "message": "f202021200",
+ "type": "reaction",
+ "media_type": "",
+ "edit": "7",
+ "plaintext": "f202021200",
+ "device_sent_plaintext": "fa01100a07373737406c69641205f202021200"
+ },
+ {
+ "message": "920300",
+ "type": "poll",
+ "media_type": "",
+ "edit": "",
+ "plaintext": "920300",
+ "device_sent_plaintext": "fa010e0a07373737406c69641203920300"
+ },
+ {
+ "message": "623c0a380a1731323033363330303030303030303030303140672e757310001a034f4c4422163535353030303140732e77686174736170702e6e65741000",
+ "type": "text",
+ "media_type": "",
+ "edit": "8",
+ "plaintext": "623c0a380a1731323033363330303030303030303030303140672e757310001a034f4c4422163535353030303140732e77686174736170702e6e65741000",
+ "device_sent_plaintext": "fa01490a07373737406c6964123e623c0a380a1731323033363330303030303030303030303140672e757310001a034f4c4422163535353030303140732e77686174736170702e6e65741000"
+ },
+ {
+ "message": "62230a1f0a163535353030303140732e77686174736170702e6e657410011a034f4c441000",
+ "type": "text",
+ "media_type": "",
+ "edit": "7",
+ "plaintext": "62230a1f0a163535353030303140732e77686174736170702e6e657410011a034f4c441000",
+ "device_sent_plaintext": "fa01300a07373737406c6964122562230a1f0a163535353030303140732e77686174736170702e6e657410011a034f4c441000"
+ },
+ {
+ "message": "d203350a3362310a1f0a163535353030303140732e77686174736170702e6e657410011a034f4c44100e72050a036e65777880d095ffbc31",
+ "type": "text",
+ "media_type": "",
+ "edit": "1",
+ "plaintext": "d203350a3362310a1f0a163535353030303140732e77686174736170702e6e657410011a034f4c44100e72050a036e65777880d095ffbc31",
+ "device_sent_plaintext": "fa01430a07373737406c69641238d203350a3362310a1f0a163535353030303140732e77686174736170702e6e657410011a034f4c44100e72050a036e65777880d095ffbc31"
+ }
+ ],
+ "unavailable_req": "6235101082013008042a2c0a2a0a1731323033363330303030303030303030303140672e757310001a044c4f53542207373737406c6964",
+ "unpadded": "616263"
+}
diff --git a/crates/whatsmeow/testdata/pairing_media.json b/crates/whatsmeow/testdata/pairing_media.json
new file mode 100644
index 0000000000..20a3e86b2e
--- /dev/null
+++ b/crates/whatsmeow/testdata/pairing_media.json
@@ -0,0 +1,38 @@
+{
+ "code_pair_adv_secret": "43f95d876b5ebea45ad10dfba5ff6a4e600c38997bc72e32a532a937ea59f82b",
+ "code_pair_finish": "00f80a1908fc02494416fc026d64045a11fa0003f801f806fc176c696e6b5f636f64655f636f6d70616e696f6e5f7265670cfaff8615550001111f03ec8bfc10636f6d70616e696f6e5f66696e697368f803f802fc246c696e6b5f636f64655f70616972696e675f777261707065645f6b65795f62756e646c65fc9c33dc5d3d38fd5cfd350de378ce2f24f929a4d6e01c718847cc2684b0f19c42e8386d82bf4ddd036317800ed8c77a17140daac334e1fe6d8eea438ae16550d912fb152d866b9d1fd90a87c64104589b82d557309f2cf887d99ceb6dc8d445ab17695e71407c5cf9df48dabe245e7ac78addc172e872679e21bfeb82bbf94c17250b1871a70d91a5ce232c0de8d963a6f33864aadaf1cdf59e3e52658ff802fc19636f6d70616e696f6e5f6964656e746974795f7075626c6963fc20358072d6365880d1aeea329adf9121383851ed21a28e3b75e965d0d2cd166254f802fc156c696e6b5f636f64655f70616972696e675f726566fc0452454631",
+ "code_pair_identity_private": "202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f",
+ "code_pair_notification": "00f80209f801f802fc176c696e6b5f636f64655f636f6d70616e696f6e5f726567f803f802fc156c696e6b5f636f64655f70616972696e675f726566fc0452454631f802fc2f6c696e6b5f636f64655f70616972696e675f777261707065645f7072696d6172795f657068656d6572616c5f707562fc50a22b7f568762fc78531f67e66e1eb8ae81ee432772a227de051a15acc2f21e1a696500be0e60122ed2494ab5db979dd4146005a8f870813763bc4c160c201355813904bbbdfaa602bb820dde677b8987f802fc147072696d6172795f6964656e746974795f707562fc20675dd574ed7789310b3d2e7681f3790b466c773b1521fecf36577958371ea52f",
+ "code_pair_primary_identity": "675dd574ed7789310b3d2e7681f3790b466c773b1521fecf36577958371ea52f",
+ "companion_ephemeral_key": "91a29f341aad4fdb47432ec4acf42b4423d076129f52ce69d45ba62d2132ee070c502ee432fab3e0495609dcba486526120d5e58df739dcfcd9eeb8d5a3072b380eab82172af85c8385beff379002fb2",
+ "companion_linking_code": "8MH47VJ2",
+ "companion_linking_code_bytes": "3d20336e21",
+ "companion_private": "68f79714c44b00963b03aa57aa667bdeca21ccb7fa8d377f2cd1b91ff7ac724a",
+ "media_key": "4d27bcee3135c4944b28d27dd809b07be10c35160d20131caa7e85575498d07c",
+ "media_retry_chat": "[email protected]",
+ "media_retry_error_2": "media no longer available on phone",
+ "media_retry_notification": "00f8080904ee0e08fc064d53474944311aff051700000000f802f807fc03726d7205faef7e760cfaff091203630000000000011cfc0766726f6d5f6d65ec0ff802cbf802f802ee62fc1823cc0e1a5810a0be7ef11dbad50670bac4159559f669e2edf802ee3afc0c4b04ab17bb4337be5be91cf7",
+ "media_retry_receipt_ciphertext": "23cc0e1a5810a0be7ef11dbad50670bac4159559f669e2ed",
+ "media_retry_receipt_iv": "4b04ab17bb4337be5be91cf7",
+ "media_retry_send": "00f8080708fc064d534749443111faff0212340304ed91f802f802cbf802f802ee62fc188ef4c4404a8bf28f8602debc4f36a41a714bb582e574523af802ee3afc0cd58fdf5c365322e9d57c522bf807fc03726d720cfaff091203630000000000011cfc0766726f6d5f6d65ec0f05faef7e76",
+ "media_retry_sender": "777@lid",
+ "msg_secret": "23b7bb8c91ae008711fb12846780bcdf1e065f821bdfec49f57e7c7dcd4c4823",
+ "msg_secret_ad_Enc Reaction": "",
+ "msg_secret_ad_Message Edit": "",
+ "msg_secret_ad_Poll Vote": "4f524947310039383736406c6964",
+ "msg_secret_key_Enc Reaction": "de069385fa4a70bea24794a6cf91ecaabc63682eca1b0576bd1c73a8f0f2eb76",
+ "msg_secret_key_Message Edit": "9153132f60015a6c9471ad1e7d555d7ed01fe07b2496f884e4dd968da33abb2b",
+ "msg_secret_key_Poll Vote": "625afbe591c5bce5ee783d5cf0ff0c2898f6f0267551dbda671f655b853ccd48",
+ "poll_option_hashes": [
+ "8a798890fe93817163b10b5f7bd2ca4d25d84c52739a645a889c173eee7d9d3d",
+ "9390298f3fb0c5b160498935d79cb139aef28e1c47358b4bbba61862b9c26e59"
+ ],
+ "privacy_changed": [
+ true,
+ true,
+ false
+ ],
+ "privacy_last_seen": "contacts",
+ "privacy_node": "00f802e2f803f8058189de6cecbef8058189616c74f80581895e6cfc0178",
+ "privacy_read_receipts": "none"
+}
diff --git a/crates/whatsmeow/testdata/prekeys.json b/crates/whatsmeow/testdata/prekeys.json
new file mode 100644
index 0000000000..16ab82eff7
--- /dev/null
+++ b/crates/whatsmeow/testdata/prekeys.json
@@ -0,0 +1,15 @@
+{
+ "bundle_error_message": "got error getting prekeys: \u003cerror code=\"404\" text=\"item-not-found\"/\u003e",
+ "bundle_error_node": "00f8040e0cf70007ff021234f801f805a870ec3538b6",
+ "bundle_identity_key": "d89e3bad79437dbed9f843418304f460ff05c7fe81fe4a9577a804cb9367ff66",
+ "bundle_pre_key_id": 42,
+ "bundle_pre_key_public": "675dd574ed7789310b3d2e7681f3790b466c773b1521fecf36577958371ea52f",
+ "bundle_registration_id": 168496141,
+ "bundle_signed_pre_key_id": 1,
+ "bundle_signed_pre_key_public": "392d174a38b3b1beafaf1fe824870841c5fa531bc6eafdb6402c124664488c1c",
+ "bundle_signed_pre_key_signature": "77777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777",
+ "bundle_user_node": "00f8040e0cf70007ff021234f805f802adfc040a0b0c0df80204fc0105f8029cfc20d89e3bad79437dbed9f843418304f460ff05c7fe81fe4a9577a804cb9367ff66f8029ef802f80208fc0300002af8026cfc20675dd574ed7789310b3d2e7681f3790b466c773b1521fecf36577958371ea52ff802ec2df803f80208fc03000001f8026cfc20392d174a38b3b1beafaf1fe824870841c5fa531bc6eafdb6402c124664488c1cf802d4fc4077777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777",
+ "bundle_without_pre_key_node": "00f8040e0cf70007ff021234f802f802adfc040a0b0c0df802ef1ef802f8029cfc20d89e3bad79437dbed9f843418304f460ff05c7fe81fe4a9577a804cb9367ff66f802ec2df803f80208fc03000001f8026cfc20392d174a38b3b1beafaf1fe824870841c5fa531bc6eafdb6402c124664488c1cf802d4fc4077777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777",
+ "pre_key_node": "00f8029ef802f80208fc03010203f8026cfc2034e42d4af5ef94a07a3a84201b889d4cd1a743cb27b11b6a10438a8feb8e5847",
+ "signed_pre_key_node": "00f802ec2df803f80208fc03000001f8026cfc20392d174a38b3b1beafaf1fe824870841c5fa531bc6eafdb6402c124664488c1cf802d4fc4077777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777"
+}
diff --git a/crates/whatsmeow/testdata/presence.json b/crates/whatsmeow/testdata/presence.json
new file mode 100644
index 0000000000..e96245b5a5
--- /dev/null
+++ b/crates/whatsmeow/testdata/presence.json
@@ -0,0 +1,8 @@
+{
+ "requests": {
+ "composing_audio": "00f8042e11faff02555503f801f8033437a1",
+ "paused": "00f8042e11faff02555503f801f8019a",
+ "subscribe": "00f8051f046211faff02555503",
+ "unavailable": "00f8051f043089fc06546573746572"
+ }
+}
diff --git a/crates/whatsmeow/testdata/user.json b/crates/whatsmeow/testdata/user.json
new file mode 100644
index 0000000000..499bf0cfbf
--- /dev/null
+++ b/crates/whatsmeow/testdata/user.json
@@ -0,0 +1,71 @@
+{
+ "blocklist": {
+ "addressing_mode": "lid",
+ "d_hash": "1700000000",
+ "items": [
+ {
+ "active": true,
+ "lid": "6666@lid",
+ },
+ {
+ "active": false,
+ "lid": "7777@lid",
+ "pn": ""
+ }
+ ]
+ },
+ "blocklist_lid_pairs": [
+ [
+ "6666@lid",
+ ]
+ ],
+ "blocklist_node": "00f80671ecd6ff051700000000fc0f61646472657373696e675f6d6f646576f803f8073f0cfaff02666676fc06706e5f6a6964faff02555503ec019bf8033f0cfaff02777776f8033fedd3fc05626c6f636b",
+ "device_lists": [
+ {
+ "devices": [
+ "5555:99@hosted",
+ ],
+ "hash": "2:JqlljRY5",
+ "node": "00f8020ff801f80236f806f8033b082df8053b08a25045f8053b08ff0199fc0969735f686f737465649bf8032408e3f8033b5055f8033b08ff8370000f",
+ "user": "[email protected]"
+ },
+ {
+ "devices": [
+ "6666@lid",
+ ],
+ "hash": "2:t38vXlMn",
+ "node": "00f8020ff801f80236f802f8033b082df8053b08cffc0969735f686f737465649b",
+ "user": "6666@lid"
+ },
+ {
+ "devices": [],
+ "hash": "2:47DEQpj8",
+ "node": "00f8010f",
+ "user": "[email protected]"
+ },
+ {
+ "devices": [],
+ "hash": "2:47DEQpj8",
+ "node": "00f802fc0b6e6f742d64657669636573f801f80236f801f8033b0855",
+ "user": "[email protected]"
+ }
+ ],
+ "requests": {
+ "block_lid": "00f80a1908fc02494416ecd9045a11fa0003f801f8073f0cfaff02666676edd3fc05626c6f636becd6fc056861736831",
+ "get_blocklist": "00f80a19042911fa000308fc02494416ecd900",
+ "get_blocklist_with_hash": "00f80a1908fc02494416ecd9042911fa0003f801f8033fecd6fc056861736831",
+ "get_user_devices": "00f80a191679042911fa000308fc024944f801f80c79619b8f2d7d13fc03736964fc035349446a6df802f8026df801f8030f5445f80271f802f8030e0cfaff02555503f8030e0cfaff02666676",
+ "get_user_info": "00f80a1908fc0249441679042911fa0003f801f80c798f2d7da0fc03736964fc035349446aed0a619bf802f8026df805f80244f801f80122f8010bf80121f8030f5445f80176f80271f802f8030e0cfaff02555503f8030e0cfaff02666676",
+ "is_on_whatsapp": "00f80a19042911fa000308fc0249441679f801f80c79fc03736964fc035349446a6d619b8f2d7de5f802f8026df804f80325fc0f61646472657373696e675f6d6f646576f80244f801f80122f8010af801fc08757365726e616d65f80271f801f8020ef801f80225fc112b313535353132333435363740632e7573",
+ "profile_picture_community": "00f80a1908fc02494416ed33042911faff091203630099999999991cf801f802fc087069637475726573f801f807210443fc10706172656e745f67726f75705f6a6964faff091203630099999999991c6dd2",
+ "profile_picture_full": "00f80c1987faff0255550308fc0249441642042911fa0003f801f80c210443ec61fc03696e76fc0a636f6d6d6f6e5f676964faff091203630012345678901cfc0a706572736f6e615f6964fc07706572736f6e616dd200",
+ "profile_picture_preview": "00f80c1908fc0249441642042911fa000387faff02555503f801f808216dd2047708fc036f6c6400",
+ "unblock_lid": "00f80a1908fc02494416ecd9045a11fa0003f801f8053f0cfaff02666676edd3fc07756e626c6f636b"
+ }
+}
diff --git a/crates/whatsmeow_proto/AGENTS.md b/crates/whatsmeow_proto/AGENTS.md
new file mode 100644
index 0000000000..f941a039a8
--- /dev/null
+++ b/crates/whatsmeow_proto/AGENTS.md
@@ -0,0 +1,32 @@
+# whatsmeow_proto
+
+## What it is
+
+The protobuf types of the `whatsmeow` port (WhatsApp linked-device client):
+prost code generated at build time from whatsmeow's `proto/` tree, kept in its
+own crate so the ~29k generated lines don't recompile with every edit to
+`crates/whatsmeow`.
+
+## Start here
+
+- `proto/<goPackage>/*.proto`: copies of whatsmeow's `.proto` files with MPL-2.0 headers at
+ the revision pinned in `crates/whatsmeow/AGENTS.md`.
+- `build.rs`: compiles them with `protox` (pure Rust, no `protoc` needed) and
+ `prost-build`.
+- `src/lib.rs`: the generated module tree plus aliases named after the Go
+ import paths (`waE2E` → `wa_e2e`).
+
+## Recipes
+
+- Update the protos: copy whatsmeow's `proto/**/*.proto` over `proto/` at the
+ new revision, keep the directory layout (imports depend on it), and
+ regenerate the aliases at the bottom of `src/lib.rs` if a package was added.
+
+## Gotchas
+
+- Preserve upstream protobuf definitions; retain the MPL-2.0 header when updating them.
+- License is MPL-2.0 (see `LICENSE`), like the rest of the port.
+
+## Related
+
+- `crates/whatsmeow/AGENTS.md`
diff --git a/crates/whatsmeow_proto/CLAUDE.md b/crates/whatsmeow_proto/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/whatsmeow_proto/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/whatsmeow_proto/Cargo.toml b/crates/whatsmeow_proto/Cargo.toml
new file mode 100644
index 0000000000..a675f271b9
--- /dev/null
+++ b/crates/whatsmeow_proto/Cargo.toml
@@ -0,0 +1,15 @@
+[package]
+edition = "2024"
+name = "whatsmeow_proto"
+publish = false
+version = "0.1.0"
+license = "MPL-2.0"
+description = "Protobuf types of the whatsmeow Rust port, generated from whatsmeow's proto/ tree."
+
+[dependencies]
+prost = { workspace = true }
+workspace-hack = { version = "0.1", path = "../workspace-hack" }
+
+[build-dependencies]
+prost-build = { workspace = true }
+protox = { workspace = true }
diff --git a/crates/whatsmeow_proto/LICENSE b/crates/whatsmeow_proto/LICENSE
new file mode 100644
index 0000000000..a612ad9813
--- /dev/null
+++ b/crates/whatsmeow_proto/LICENSE
@@ -0,0 +1,373 @@
+Mozilla Public License Version 2.0
+==================================
+
+1. Definitions
+--------------
+
+1.1. "Contributor"
+ means each individual or legal entity that creates, contributes to
+ the creation of, or owns Covered Software.
+
+1.2. "Contributor Version"
+ means the combination of the Contributions of others (if any) used
+ by a Contributor and that particular Contributor's Contribution.
+
+1.3. "Contribution"
+ means Covered Software of a particular Contributor.
+
+1.4. "Covered Software"
+ means Source Code Form to which the initial Contributor has attached
+ the notice in Exhibit A, the Executable Form of such Source Code
+ Form, and Modifications of such Source Code Form, in each case
+ including portions thereof.
+
+1.5. "Incompatible With Secondary Licenses"
+ means
+
+ (a) that the initial Contributor has attached the notice described
+ in Exhibit B to the Covered Software; or
+
+ (b) that the Covered Software was made available under the terms of
+ version 1.1 or earlier of the License, but not also under the
+ terms of a Secondary License.
+
+1.6. "Executable Form"
+ means any form of the work other than Source Code Form.
+
+1.7. "Larger Work"
+ means a work that combines Covered Software with other material, in
+ a separate file or files, that is not Covered Software.
+
+1.8. "License"
+ means this document.
+
+1.9. "Licensable"
+ means having the right to grant, to the maximum extent possible,
+ whether at the time of the initial grant or subsequently, any and
+ all of the rights conveyed by this License.
+
+1.10. "Modifications"
+ means any of the following:
+
+ (a) any file in Source Code Form that results from an addition to,
+ deletion from, or modification of the contents of Covered
+ Software; or
+
+ (b) any new file in Source Code Form that contains any Covered
+ Software.
+
+1.11. "Patent Claims" of a Contributor
+ means any patent claim(s), including without limitation, method,
+ process, and apparatus claims, in any patent Licensable by such
+ Contributor that would be infringed, but for the grant of the
+ License, by the making, using, selling, offering for sale, having
+ made, import, or transfer of either its Contributions or its
+ Contributor Version.
+
+1.12. "Secondary License"
+ means either the GNU General Public License, Version 2.0, the GNU
+ Lesser General Public License, Version 2.1, the GNU Affero General
+ Public License, Version 3.0, or any later versions of those
+ licenses.
+
+1.13. "Source Code Form"
+ means the form of the work preferred for making modifications.
+
+1.14. "You" (or "Your")
+ means an individual or a legal entity exercising rights under this
+ License. For legal entities, "You" includes any entity that
+ controls, is controlled by, or is under common control with You. For
+ purposes of this definition, "control" means (a) the power, direct
+ or indirect, to cause the direction or management of such entity,
+ whether by contract or otherwise, or (b) ownership of more than
+ fifty percent (50%) of the outstanding shares or beneficial
+ ownership of such entity.
+
+2. License Grants and Conditions
+--------------------------------
+
+2.1. Grants
+
+Each Contributor hereby grants You a world-wide, royalty-free,
+non-exclusive license:
+
+(a) under intellectual property rights (other than patent or trademark)
+ Licensable by such Contributor to use, reproduce, make available,
+ modify, display, perform, distribute, and otherwise exploit its
+ Contributions, either on an unmodified basis, with Modifications, or
+ as part of a Larger Work; and
+
+(b) under Patent Claims of such Contributor to make, use, sell, offer
+ for sale, have made, import, and otherwise transfer either its
+ Contributions or its Contributor Version.
+
+2.2. Effective Date
+
+The licenses granted in Section 2.1 with respect to any Contribution
+become effective for each Contribution on the date the Contributor first
+distributes such Contribution.
+
+2.3. Limitations on Grant Scope
+
+The licenses granted in this Section 2 are the only rights granted under
+this License. No additional rights or licenses will be implied from the
+distribution or licensing of Covered Software under this License.
+Notwithstanding Section 2.1(b) above, no patent license is granted by a
+Contributor:
+
+(a) for any code that a Contributor has removed from Covered Software;
+ or
+
+(b) for infringements caused by: (i) Your and any other third party's
+ modifications of Covered Software, or (ii) the combination of its
+ Contributions with other software (except as part of its Contributor
+ Version); or
+
+(c) under Patent Claims infringed by Covered Software in the absence of
+ its Contributions.
+
+This License does not grant any rights in the trademarks, service marks,
+or logos of any Contributor (except as may be necessary to comply with
+the notice requirements in Section 3.4).
+
+2.4. Subsequent Licenses
+
+No Contributor makes additional grants as a result of Your choice to
+distribute the Covered Software under a subsequent version of this
+License (see Section 10.2) or under the terms of a Secondary License (if
+permitted under the terms of Section 3.3).
+
+2.5. Representation
+
+Each Contributor represents that the Contributor believes its
+Contributions are its original creation(s) or it has sufficient rights
+to grant the rights to its Contributions conveyed by this License.
+
+2.6. Fair Use
+
+This License is not intended to limit any rights You have under
+applicable copyright doctrines of fair use, fair dealing, or other
+equivalents.
+
+2.7. Conditions
+
+Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
+in Section 2.1.
+
+3. Responsibilities
+-------------------
+
+3.1. Distribution of Source Form
+
+All distribution of Covered Software in Source Code Form, including any
+Modifications that You create or to which You contribute, must be under
+the terms of this License. You must inform recipients that the Source
+Code Form of the Covered Software is governed by the terms of this
+License, and how they can obtain a copy of this License. You may not
+attempt to alter or restrict the recipients' rights in the Source Code
+Form.
+
+3.2. Distribution of Executable Form
+
+If You distribute Covered Software in Executable Form then:
+
+(a) such Covered Software must also be made available in Source Code
+ Form, as described in Section 3.1, and You must inform recipients of
+ the Executable Form how they can obtain a copy of such Source Code
+ Form by reasonable means in a timely manner, at a charge no more
+ than the cost of distribution to the recipient; and
+
+(b) You may distribute such Executable Form under the terms of this
+ License, or sublicense it under different terms, provided that the
+ license for the Executable Form does not attempt to limit or alter
+ the recipients' rights in the Source Code Form under this License.
+
+3.3. Distribution of a Larger Work
+
+You may create and distribute a Larger Work under terms of Your choice,
+provided that You also comply with the requirements of this License for
+the Covered Software. If the Larger Work is a combination of Covered
+Software with a work governed by one or more Secondary Licenses, and the
+Covered Software is not Incompatible With Secondary Licenses, this
+License permits You to additionally distribute such Covered Software
+under the terms of such Secondary License(s), so that the recipient of
+the Larger Work may, at their option, further distribute the Covered
+Software under the terms of either this License or such Secondary
+License(s).
+
+3.4. Notices
+
+You may not remove or alter the substance of any license notices
+(including copyright notices, patent notices, disclaimers of warranty,
+or limitations of liability) contained within the Source Code Form of
+the Covered Software, except that You may alter any license notices to
+the extent required to remedy known factual inaccuracies.
+
+3.5. Application of Additional Terms
+
+You may choose to offer, and to charge a fee for, warranty, support,
+indemnity or liability obligations to one or more recipients of Covered
+Software. However, You may do so only on Your own behalf, and not on
+behalf of any Contributor. You must make it absolutely clear that any
+such warranty, support, indemnity, or liability obligation is offered by
+You alone, and You hereby agree to indemnify every Contributor for any
+liability incurred by such Contributor as a result of warranty, support,
+indemnity or liability terms You offer. You may include additional
+disclaimers of warranty and limitations of liability specific to any
+jurisdiction.
+
+4. Inability to Comply Due to Statute or Regulation
+---------------------------------------------------
+
+If it is impossible for You to comply with any of the terms of this
+License with respect to some or all of the Covered Software due to
+statute, judicial order, or regulation then You must: (a) comply with
+the terms of this License to the maximum extent possible; and (b)
+describe the limitations and the code they affect. Such description must
+be placed in a text file included with all distributions of the Covered
+Software under this License. Except to the extent prohibited by statute
+or regulation, such description must be sufficiently detailed for a
+recipient of ordinary skill to be able to understand it.
+
+5. Termination
+--------------
+
+5.1. The rights granted under this License will terminate automatically
+if You fail to comply with any of its terms. However, if You become
+compliant, then the rights granted under this License from a particular
+Contributor are reinstated (a) provisionally, unless and until such
+Contributor explicitly and finally terminates Your grants, and (b) on an
+ongoing basis, if such Contributor fails to notify You of the
+non-compliance by some reasonable means prior to 60 days after You have
+come back into compliance. Moreover, Your grants from a particular
+Contributor are reinstated on an ongoing basis if such Contributor
+notifies You of the non-compliance by some reasonable means, this is the
+first time You have received notice of non-compliance with this License
+from such Contributor, and You become compliant prior to 30 days after
+Your receipt of the notice.
+
+5.2. If You initiate litigation against any entity by asserting a patent
+infringement claim (excluding declaratory judgment actions,
+counter-claims, and cross-claims) alleging that a Contributor Version
+directly or indirectly infringes any patent, then the rights granted to
+You by any and all Contributors for the Covered Software under Section
+2.1 of this License shall terminate.
+
+5.3. In the event of termination under Sections 5.1 or 5.2 above, all
+end user license agreements (excluding distributors and resellers) which
+have been validly granted by You or Your distributors under this License
+prior to termination shall survive termination.
+
+************************************************************************
+* *
+* 6. Disclaimer of Warranty *
+* ------------------------- *
+* *
+* Covered Software is provided under this License on an "as is" *
+* basis, without warranty of any kind, either expressed, implied, or *
+* statutory, including, without limitation, warranties that the *
+* Covered Software is free of defects, merchantable, fit for a *
+* particular purpose or non-infringing. The entire risk as to the *
+* quality and performance of the Covered Software is with You. *
+* Should any Covered Software prove defective in any respect, You *
+* (not any Contributor) assume the cost of any necessary servicing, *
+* repair, or correction. This disclaimer of warranty constitutes an *
+* essential part of this License. No use of any Covered Software is *
+* authorized under this License except under this disclaimer. *
+* *
+************************************************************************
+
+************************************************************************
+* *
+* 7. Limitation of Liability *
+* -------------------------- *
+* *
+* Under no circumstances and under no legal theory, whether tort *
+* (including negligence), contract, or otherwise, shall any *
+* Contributor, or anyone who distributes Covered Software as *
+* permitted above, be liable to You for any direct, indirect, *
+* special, incidental, or consequential damages of any character *
+* including, without limitation, damages for lost profits, loss of *
+* goodwill, work stoppage, computer failure or malfunction, or any *
+* and all other commercial damages or losses, even if such party *
+* shall have been informed of the possibility of such damages. This *
+* limitation of liability shall not apply to liability for death or *
+* personal injury resulting from such party's negligence to the *
+* extent applicable law prohibits such limitation. Some *
+* jurisdictions do not allow the exclusion or limitation of *
+* incidental or consequential damages, so this exclusion and *
+* limitation may not apply to You. *
+* *
+************************************************************************
+
+8. Litigation
+-------------
+
+Any litigation relating to this License may be brought only in the
+courts of a jurisdiction where the defendant maintains its principal
+place of business and such litigation shall be governed by laws of that
+jurisdiction, without reference to its conflict-of-law provisions.
+Nothing in this Section shall prevent a party's ability to bring
+cross-claims or counter-claims.
+
+9. Miscellaneous
+----------------
+
+This License represents the complete agreement concerning the subject
+matter hereof. If any provision of this License is held to be
+unenforceable, such provision shall be reformed only to the extent
+necessary to make it enforceable. Any law or regulation which provides
+that the language of a contract shall be construed against the drafter
+shall not be used to construe this License against a Contributor.
+
+10. Versions of the License
+---------------------------
+
+10.1. New Versions
+
+Mozilla Foundation is the license steward. Except as provided in Section
+10.3, no one other than the license steward has the right to modify or
+publish new versions of this License. Each version will be given a
+distinguishing version number.
+
+10.2. Effect of New Versions
+
+You may distribute the Covered Software under the terms of the version
+of the License under which You originally received the Covered Software,
+or under the terms of any subsequent version published by the license
+steward.
+
+10.3. Modified Versions
+
+If you create software not governed by this License, and you want to
+create a new license for such software, you may create and use a
+modified version of this License if you rename the license and remove
+any references to the name of the license steward (except to note that
+such modified license differs from this License).
+
+10.4. Distributing Source Code Form that is Incompatible With Secondary
+Licenses
+
+If You choose to distribute Source Code Form that is Incompatible With
+Secondary Licenses under the terms of this version of the License, the
+notice described in Exhibit B of this License must be attached.
+
+Exhibit A - Source Code Form License Notice
+-------------------------------------------
+
+ This Source Code Form is subject to the terms of the Mozilla Public
+ License, v. 2.0. If a copy of the MPL was not distributed with this
+ file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+If it is not possible or desirable to put the notice in a particular
+file, then You may include the notice in a location (such as a LICENSE
+file in a relevant directory) where a recipient would be likely to look
+for such a notice.
+
+You may add additional accurate notices of copyright ownership.
+
+Exhibit B - "Incompatible With Secondary Licenses" Notice
+---------------------------------------------------------
+
+ This Source Code Form is "Incompatible With Secondary Licenses", as
+ defined by the Mozilla Public License, v. 2.0.
diff --git a/crates/whatsmeow_proto/build.rs b/crates/whatsmeow_proto/build.rs
new file mode 100644
index 0000000000..69ac6952c7
--- /dev/null
+++ b/crates/whatsmeow_proto/build.rs
@@ -0,0 +1,39 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+//! Compiles whatsmeow's `.proto` files with the pure-Rust `protox` compiler, so
+//! no `protoc` binary is needed, and generates prost types from them.
+
+use std::path::{Path, PathBuf};
+
+const PROTO_ROOT: &str = "proto";
+
+fn main() {
+ let mut files = Vec::new();
+ collect_proto_files(Path::new(PROTO_ROOT), &mut files);
+ files.sort();
+ println!("cargo:rerun-if-changed={PROTO_ROOT}");
+
+ let descriptors = protox::compile(&files, [PROTO_ROOT])
+ .expect("the vendored .proto files compile; they are copied verbatim from whatsmeow");
+ prost_build::Config::new()
+ .include_file("_includes.rs")
+ .compile_fds(descriptors)
+ .expect("prost can write generated code into OUT_DIR");
+}
+
+fn collect_proto_files(directory: &Path, files: &mut Vec<PathBuf>) {
+ let entries = std::fs::read_dir(directory).expect("the proto directory is readable");
+ for entry in entries {
+ let path = entry.expect("proto directory entries are readable").path();
+ if path.is_dir() {
+ collect_proto_files(&path, files);
+ } else if path
+ .extension()
+ .is_some_and(|extension| extension == "proto")
+ {
+ files.push(path);
+ }
+ }
+}
diff --git a/crates/whatsmeow_proto/proto/instamadilloAddMessage/InstamadilloAddMessage.proto b/crates/whatsmeow_proto/proto/instamadilloAddMessage/InstamadilloAddMessage.proto
new file mode 100644
index 0000000000..7be3e83965
--- /dev/null
+++ b/crates/whatsmeow_proto/proto/instamadilloAddMessage/InstamadilloAddMessage.proto
@@ -0,0 +1,89 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+syntax = "proto2";
+package InstamadilloAddMessage;
+option go_package = "go.mau.fi/whatsmeow/proto/instamadilloAddMessage";
+
+import "instamadilloCoreTypeActionLog/InstamadilloCoreTypeActionLog.proto";
+import "instamadilloCoreTypeAdminMessage/InstamadilloCoreTypeAdminMessage.proto";
+import "instamadilloCoreTypeCollection/InstamadilloCoreTypeCollection.proto";
+import "instamadilloCoreTypeLink/InstamadilloCoreTypeLink.proto";
+import "instamadilloCoreTypeMedia/InstamadilloCoreTypeMedia.proto";
+import "instamadilloCoreTypeText/InstamadilloCoreTypeText.proto";
+import "instamadilloXmaContentRef/InstamadilloXmaContentRef.proto";
+
+message AddMessagePayload {
+ optional AddMessageContent content = 1;
+ optional AddMessageMetadata metadata = 2;
+}
+
+message AddMessageContent {
+ oneof addMessageContent {
+ InstamadilloCoreTypeText.Text text = 1;
+ Like like = 2;
+ InstamadilloCoreTypeLink.Link link = 3;
+ ReceiverFetchXma receiverFetchXma = 4;
+ InstamadilloCoreTypeMedia.Media media = 5;
+ Placeholder placeholder = 6;
+ InstamadilloCoreTypeCollection.Collection collection = 7;
+ InstamadilloCoreTypeAdminMessage.AdminMessage adminMessage = 8;
+ InstamadilloCoreTypeActionLog.ActionLog actionLog = 9;
+ }
+}
+
+message AddMessageMetadata {
+ optional bool sendSilently = 1;
+ optional PrivateReplyInfo privateReplyInfo = 2;
+ optional RepliedToMessage repliedToMessage = 3;
+ optional ForwardingParams forwardingParams = 4;
+ optional EphemeralityParams ephemeralityParams = 5;
+}
+
+message RepliedToMessage {
+ optional string repliedToMessageOtid = 1;
+ optional string repliedToMessageWaServerTimeSec = 2;
+ optional string repliedToMessageCollectionItemID = 3;
+ optional OpenMessageMicroSecondTimestamp omMicroSecTS = 4;
+}
+
+message OpenMessageMicroSecondTimestamp {
+ optional int64 timestampMS = 1;
+ optional int32 microSecondsBits = 2;
+}
+
+message PrivateReplyInfo {
+ optional string commentID = 1;
+ optional string postLink = 2;
+}
+
+message ForwardingParams {
+ optional string forwardedThreadID = 1;
+}
+
+message EphemeralityParams {
+ optional int64 ephemeralDurationSec = 1;
+}
+
+message Like {
+}
+
+message ReceiverFetchXma {
+ optional string contentRef = 1;
+ optional string text = 2;
+ optional InstamadilloCoreTypeMedia.Media media = 3;
+ optional InstamadilloXmaContentRef.XmaContentRef xmaContentRef = 4;
+}
+
+message Placeholder {
+ enum Type {
+ PLACEHOLDER_TYPE_NONE = 0;
+ PLACEHOLDER_TYPE_DECRYPTION_FAILURE = 1;
+ PLACEHOLDER_TYPE_NOT_SUPPORTED_NEED_UPDATE = 2;
+ PLACEHOLDER_TYPE_DEVICE_UNAVAILABLE = 3;
+ PLACEHOLDER_TYPE_NOT_SUPPORTED_NOT_RECOVERABLE = 4;
+ }
+
+ optional Type placeholderType = 1;
+}
diff --git a/crates/whatsmeow_proto/proto/instamadilloCoreTypeActionLog/InstamadilloCoreTypeActionLog.proto b/crates/whatsmeow_proto/proto/instamadilloCoreTypeActionLog/InstamadilloCoreTypeActionLog.proto
new file mode 100644
index 0000000000..4efe93ab95
--- /dev/null
+++ b/crates/whatsmeow_proto/proto/instamadilloCoreTypeActionLog/InstamadilloCoreTypeActionLog.proto
@@ -0,0 +1,17 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+syntax = "proto2";
+package InstamadilloCoreTypeActionLog;
+option go_package = "go.mau.fi/whatsmeow/proto/instamadilloCoreTypeActionLog";
+
+message ActionLog {
+ oneof actionLogSubtype {
+ ActionLogReaction actionLogReaction = 1;
+ }
+}
+
+message ActionLogReaction {
+ optional string emojiUnicode = 1;
+}
diff --git a/crates/whatsmeow_proto/proto/instamadilloCoreTypeAdminMessage/InstamadilloCoreTypeAdminMessage.proto b/crates/whatsmeow_proto/proto/instamadilloCoreTypeAdminMessage/InstamadilloCoreTypeAdminMessage.proto
new file mode 100644
index 0000000000..759e731894
--- /dev/null
+++ b/crates/whatsmeow_proto/proto/instamadilloCoreTypeAdminMessage/InstamadilloCoreTypeAdminMessage.proto
@@ -0,0 +1,25 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+syntax = "proto2";
+package InstamadilloCoreTypeAdminMessage;
+option go_package = "go.mau.fi/whatsmeow/proto/instamadilloCoreTypeAdminMessage";
+
+message AdminMessage {
+ oneof adminMessageSubtype {
+ DeviceAdminMessage deviceAdminMessage = 1;
+ }
+}
+
+message DeviceAdminMessage {
+ enum Type {
+ DEVICE_ADMIN_MESSAGE_TYPE_NONE = 0;
+ DEVICE_ADMIN_MESSAGE_TYPE_LOCAL_USER_CHANGED_IDENTITY_KEY_NAMED_DEVICE = 1;
+ DEVICE_ADMIN_MESSAGE_TYPE_SECURITY_ALERT_PARTICIPANT_KEY_CHANGE = 2;
+ DEVICE_ADMIN_MESSAGE_TYPE_SECURITY_ALERT_PARTICIPANT_NEW_LOGIN = 3;
+ }
+
+ optional Type deviceAdminMessageType = 1;
+ optional string deviceName = 2;
+}
diff --git a/crates/whatsmeow_proto/proto/instamadilloCoreTypeCollection/InstamadilloCoreTypeCollection.proto b/crates/whatsmeow_proto/proto/instamadilloCoreTypeCollection/InstamadilloCoreTypeCollection.proto
new file mode 100644
index 0000000000..441ab41e9c
--- /dev/null
+++ b/crates/whatsmeow_proto/proto/instamadilloCoreTypeCollection/InstamadilloCoreTypeCollection.proto
@@ -0,0 +1,14 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+syntax = "proto2";
+package InstamadilloCoreTypeCollection;
+option go_package = "go.mau.fi/whatsmeow/proto/instamadilloCoreTypeCollection";
+
+import "instamadilloCoreTypeMedia/InstamadilloCoreTypeMedia.proto";
+
+message Collection {
+ optional string name = 1;
+ repeated InstamadilloCoreTypeMedia.Media media = 2;
+}
diff --git a/crates/whatsmeow_proto/proto/instamadilloCoreTypeLink/InstamadilloCoreTypeLink.proto b/crates/whatsmeow_proto/proto/instamadilloCoreTypeLink/InstamadilloCoreTypeLink.proto
new file mode 100644
index 0000000000..3a2de9eaac
--- /dev/null
+++ b/crates/whatsmeow_proto/proto/instamadilloCoreTypeLink/InstamadilloCoreTypeLink.proto
@@ -0,0 +1,31 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+syntax = "proto2";
+package InstamadilloCoreTypeLink;
+option go_package = "go.mau.fi/whatsmeow/proto/instamadilloCoreTypeLink";
+
+import "instamadilloCoreTypeMedia/InstamadilloCoreTypeMedia.proto";
+
+message Link {
+ optional string text = 1;
+ optional LinkContext linkContext = 2;
+}
+
+message LinkContext {
+ optional ImageUrl linkImageURL = 1;
+ optional string linkPreviewTitle = 2;
+ optional string linkURL = 3;
+ optional string linkSummary = 4;
+ optional string linkMusicPreviewURL = 5;
+ repeated string linkMusicPreviewCountriesAllowed = 6;
+ optional InstamadilloCoreTypeMedia.Thumbnail linkPreviewThumbnail = 7;
+ optional string linkPreviewBody = 8;
+}
+
+message ImageUrl {
+ optional string URL = 1;
+ optional int32 width = 2;
+ optional int32 height = 3;
+}
diff --git a/crates/whatsmeow_proto/proto/instamadilloCoreTypeMedia/InstamadilloCoreTypeMedia.proto b/crates/whatsmeow_proto/proto/instamadilloCoreTypeMedia/InstamadilloCoreTypeMedia.proto
new file mode 100644
index 0000000000..c675eaff09
--- /dev/null
+++ b/crates/whatsmeow_proto/proto/instamadilloCoreTypeMedia/InstamadilloCoreTypeMedia.proto
@@ -0,0 +1,116 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+syntax = "proto2";
+package InstamadilloCoreTypeMedia;
+option go_package = "go.mau.fi/whatsmeow/proto/instamadilloCoreTypeMedia";
+
+enum PjpegScanConfiguration {
+ PJPEG_SCAN_CONFIGURATION_UNSPECIFIED = 0;
+ PJPEG_SCAN_CONFIGURATION_WA = 1;
+ PJPEG_SCAN_CONFIGURATION_E15 = 2;
+ PJPEG_SCAN_CONFIGURATION_E35 = 3;
+}
+
+message Media {
+ enum InterventionType {
+ UNSET = 0;
+ NONE = 1;
+ NUDE = 2;
+ }
+
+ oneof media {
+ StaticPhoto staticPhoto = 1;
+ Voice voice = 2;
+ Video video = 3;
+ Raven raven = 4;
+ Gif gif = 5;
+ AvatarSticker avatarSticker = 6;
+ }
+}
+
+message StaticPhoto {
+ optional CommonMediaTransport mediaTransport = 1;
+ optional int32 height = 2;
+ optional int32 width = 3;
+ repeated int32 scanLengths = 4 [packed=true];
+ optional Thumbnail thumbnail = 5;
+ optional PjpegScanConfiguration pjpegScanConfiguration = 6;
+}
+
+message Voice {
+ optional CommonMediaTransport mediaTransport = 1;
+ optional int32 duration = 2;
+ repeated float waveforms = 3 [packed=true];
+ optional int32 waveformSamplingFrequencyHz = 4;
+}
+
+message Video {
+ optional CommonMediaTransport mediaTransport = 1;
+ optional int32 height = 2;
+ optional int32 width = 3;
+ optional Thumbnail thumbnail = 4;
+ optional VideoExtraMetadata videoExtraMetadata = 5;
+}
+
+message Gif {
+ optional CommonMediaTransport mediaTransport = 1;
+ optional int32 height = 2;
+ optional int32 width = 3;
+ optional bool isSticker = 4;
+ optional string stickerID = 5;
+ optional string gifURL = 6;
+ optional int32 gifSize = 7;
+ optional bool isRandom = 8;
+}
+
+message AvatarSticker {
+ optional CommonMediaTransport mediaTransport = 1;
+ optional bool isAnimated = 2;
+ optional string stickerID = 3;
+ optional string stickerTemplate = 4;
+ optional int32 nuxType = 5;
+}
+
+message Raven {
+ enum ViewMode {
+ RAVEN_VIEW_MODEL_UNSPECIFIED = 0;
+ RAVEN_VIEW_MODEL_ONCE = 1;
+ RAVEN_VIEW_MODEL_REPLAYABLE = 2;
+ RAVEN_VIEW_MODEL_PERMANENT = 3;
+ }
+
+ optional ViewMode viewMode = 1;
+ optional RavenContent content = 2;
+}
+
+message RavenContent {
+ oneof ravenContent {
+ StaticPhoto staticPhoto = 1;
+ Video video = 2;
+ }
+}
+
+message Thumbnail {
+ optional CommonMediaTransport mediaTransport = 1;
+ optional int32 height = 2;
+ optional int32 width = 3;
+}
+
+message CommonMediaTransport {
+ optional string mediaID = 1;
+ optional string fileSHA256 = 2;
+ optional string mediaKey = 3;
+ optional string fileEncSHA256 = 4;
+ optional string directPath = 5;
+ optional string mediaKeyTimestamp = 6;
+ optional string sidecar = 7;
+ optional int32 fileLength = 8;
+ optional string mimetype = 9;
+ optional string objectID = 10;
+}
+
+message VideoExtraMetadata {
+ optional float uploadMosClientScore = 1;
+}
diff --git a/crates/whatsmeow_proto/proto/instamadilloCoreTypeText/InstamadilloCoreTypeText.proto b/crates/whatsmeow_proto/proto/instamadilloCoreTypeText/InstamadilloCoreTypeText.proto
new file mode 100644
index 0000000000..049d2bffa8
--- /dev/null
+++ b/crates/whatsmeow_proto/proto/instamadilloCoreTypeText/InstamadilloCoreTypeText.proto
@@ -0,0 +1,51 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+syntax = "proto2";
+package InstamadilloCoreTypeText;
+option go_package = "go.mau.fi/whatsmeow/proto/instamadilloCoreTypeText";
+
+import "instamadilloCoreTypeMedia/InstamadilloCoreTypeMedia.proto";
+
+message Text {
+ enum FormatStyle {
+ TEXT_FORMAT_STYLE_UNSPECIFIED = 0;
+ TEXT_FORMAT_STYLE_BOLD = 1;
+ TEXT_FORMAT_STYLE_ITALIC = 2;
+ TEXT_FORMAT_STYLE_STRIKETHROUGH = 3;
+ TEXT_FORMAT_STYLE_UNDERLINE = 4;
+ TEXT_FORMAT_STYLE_INVALID = 5;
+ }
+
+ optional string text = 1;
+ optional bool isSuggestedReply = 2;
+ optional string postbackPayload = 3;
+ optional PowerUpsData powerUpData = 4;
+ repeated CommandRangeData commands = 5;
+ repeated AnimatedEmojiCharacterRange animatedEmojiCharacterRanges = 6;
+}
+
+message PowerUpsData {
+ optional int32 style = 1;
+ optional InstamadilloCoreTypeMedia.CommonMediaTransport mediaAttachment = 2;
+}
+
+message CommandRangeData {
+ optional int32 offset = 1;
+ optional int32 length = 2;
+ optional int32 type = 3;
+ optional string FBID = 4;
+ optional string userOrThreadFbid = 5;
+}
+
+message FormattedText {
+ optional int32 offset = 1;
+ optional int32 length = 2;
+ optional Text.FormatStyle style = 3;
+}
+
+message AnimatedEmojiCharacterRange {
+ optional int32 offset = 1;
+ optional int32 length = 2;
+}
diff --git a/crates/whatsmeow_proto/proto/instamadilloDeleteMessage/InstamadilloDeleteMessage.proto b/crates/whatsmeow_proto/proto/instamadilloDeleteMessage/InstamadilloDeleteMessage.proto
new file mode 100644
index 0000000000..d9b61f0e15
--- /dev/null
+++ b/crates/whatsmeow_proto/proto/instamadilloDeleteMessage/InstamadilloDeleteMessage.proto
@@ -0,0 +1,11 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+syntax = "proto2";
+package InstamadilloDeleteMessage;
+option go_package = "go.mau.fi/whatsmeow/proto/instamadilloDeleteMessage";
+
+message DeleteMessagePayload {
+ optional string messageOtid = 1;
+}
diff --git a/crates/whatsmeow_proto/proto/instamadilloSupplementMessage/InstamadilloSupplementMessage.proto b/crates/whatsmeow_proto/proto/instamadilloSupplementMessage/InstamadilloSupplementMessage.proto
new file mode 100644
index 0000000000..8d1e393168
--- /dev/null
+++ b/crates/whatsmeow_proto/proto/instamadilloSupplementMessage/InstamadilloSupplementMessage.proto
@@ -0,0 +1,63 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+syntax = "proto2";
+package InstamadilloSupplementMessage;
+option go_package = "go.mau.fi/whatsmeow/proto/instamadilloSupplementMessage";
+
+import "instamadilloCoreTypeMedia/InstamadilloCoreTypeMedia.proto";
+
+message SupplementMessagePayload {
+ optional string targetMessageOtid = 1;
+ optional string uniquingKeyForSupplementalData = 2;
+ optional SupplementMessageContent content = 3;
+ optional string targetMessageWaServerTimeSec = 4;
+ optional string targetWaThreadID = 5;
+}
+
+message SupplementMessageContent {
+ oneof supplementMessageContent {
+ Reaction reaction = 1;
+ ContentView contentView = 2;
+ EditText editText = 3;
+ MediaReaction mediaReaction = 4;
+ OriginalTransportPayload originalTransportPayload = 5;
+ MediaInterventions mediaInterventions = 6;
+ }
+}
+
+message MediaReaction {
+ optional string mediaID = 1;
+ optional Reaction reaction = 2;
+}
+
+message Reaction {
+ optional string reactionType = 1;
+ optional string reactionStatus = 2;
+ optional string emoji = 3;
+ optional string superReactType = 4;
+ optional string actionLogOtid = 5;
+}
+
+message ContentView {
+ optional bool seen = 1;
+ optional bool screenshotted = 2;
+ optional bool replayed = 3;
+ optional string mimetype = 4;
+ optional string objectID = 5;
+}
+
+message EditText {
+ optional string newContent = 1;
+ optional int32 editCount = 2;
+}
+
+message OriginalTransportPayload {
+ optional bytes originalTransportPayload = 1;
+}
+
+message MediaInterventions {
+ optional string mediaID = 1;
+ optional InstamadilloCoreTypeMedia.Media.InterventionType interventionType = 2;
+}
diff --git a/crates/whatsmeow_proto/proto/instamadilloTransportPayload/InstamadilloTransportPayload.proto b/crates/whatsmeow_proto/proto/instamadilloTransportPayload/InstamadilloTransportPayload.proto
new file mode 100644
index 0000000000..daf167957c
--- /dev/null
+++ b/crates/whatsmeow_proto/proto/instamadilloTransportPayload/InstamadilloTransportPayload.proto
@@ -0,0 +1,37 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+syntax = "proto2";
+package InstamadilloTransportPayload;
+option go_package = "go.mau.fi/whatsmeow/proto/instamadilloTransportPayload";
+
+import "instamadilloAddMessage/InstamadilloAddMessage.proto";
+import "instamadilloDeleteMessage/InstamadilloDeleteMessage.proto";
+import "instamadilloSupplementMessage/InstamadilloSupplementMessage.proto";
+
+enum PayloadCreator {
+ PAYLOAD_CREATOR_UNSPECIFIED = 0;
+ PAYLOAD_CREATOR_IGIOS = 1;
+ PAYLOAD_CREATOR_IG4A = 2;
+ PAYLOAD_CREATOR_WWW = 3;
+ PAYLOAD_CREATOR_IGLITE = 4;
+}
+
+message TransportPayload {
+ oneof transportPayload {
+ InstamadilloAddMessage.AddMessagePayload add = 1;
+ InstamadilloDeleteMessage.DeleteMessagePayload delete = 2;
+ InstamadilloSupplementMessage.SupplementMessagePayload supplement = 3;
+ }
+
+ optional Franking franking = 4;
+ optional bool openEb = 5;
+ optional bool isE2EeAttributed = 6;
+ optional PayloadCreator payloadCreator = 7;
+}
+
+message Franking {
+ optional bytes frankingKey = 1;
+ optional int32 frankingVersion = 2;
+}
diff --git a/crates/whatsmeow_proto/proto/instamadilloXmaContentRef/InstamadilloXmaContentRef.proto b/crates/whatsmeow_proto/proto/instamadilloXmaContentRef/InstamadilloXmaContentRef.proto
new file mode 100644
index 0000000000..eed2096932
--- /dev/null
+++ b/crates/whatsmeow_proto/proto/instamadilloXmaContentRef/InstamadilloXmaContentRef.proto
@@ -0,0 +1,109 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+syntax = "proto2";
+package InstamadilloXmaContentRef;
+option go_package = "go.mau.fi/whatsmeow/proto/instamadilloXmaContentRef";
+
+enum XmaActionType {
+ XMA_ACTION_TYPE_UNSPECIFIED = 0;
+ XMA_ACTION_TYPE_SHARE = 1;
+ XMA_ACTION_TYPE_REPLY = 2;
+ XMA_ACTION_TYPE_REACT = 3;
+ XMA_ACTION_TYPE_MENTION = 4;
+}
+
+enum ReceiverFetchContentType {
+ RECEIVER_FETCH_CONTENT_TYPE_UNSPECIFIED = 0;
+ RECEIVER_FETCH_CONTENT_TYPE_NOTE = 1;
+ RECEIVER_FETCH_CONTENT_TYPE_STORY = 2;
+ RECEIVER_FETCH_CONTENT_TYPE_PROFILE = 3;
+ RECEIVER_FETCH_CONTENT_TYPE_CLIP = 4;
+ RECEIVER_FETCH_CONTENT_TYPE_FEED = 5;
+ RECEIVER_FETCH_CONTENT_TYPE_LIVE = 6;
+ RECEIVER_FETCH_CONTENT_TYPE_COMMENT = 7;
+ RECEIVER_FETCH_CONTENT_TYPE_LOCATION_SHARE = 8;
+ RECEIVER_FETCH_CONTENT_TYPE_REELS_AUDIO = 9;
+ RECEIVER_FETCH_CONTENT_TYPE_MEDIA_NOTE = 10;
+ RECEIVER_FETCH_CONTENT_TYPE_STORY_HIGHLIGHT = 11;
+ RECEIVER_FETCH_CONTENT_TYPE_SOCIAL_CONTEXT = 12;
+}
+
+enum MediaNoteFetchParamsMessageType {
+ MEDIA_NOTE_FETCH_PARAMS_MESSAGE_TYPE_UNSPECIFIED = 0;
+ MEDIA_NOTE_FETCH_PARAMS_MESSAGE_TYPE_MENTION = 1;
+ MEDIA_NOTE_FETCH_PARAMS_MESSAGE_TYPE_REPLY = 2;
+}
+
+message XmaContentRef {
+ optional XmaActionType actionType = 1;
+ optional ReceiverFetchContentType contentType = 2;
+ optional string targetURL = 3;
+ optional string userName = 4;
+ optional string ownerFbid = 5;
+ optional ReceiverFetchXmaFetchParams fetchParams = 6;
+}
+
+message ReceiverFetchXmaFetchParams {
+ oneof receiverFetchXmaFetchParams {
+ ReceiverFetchXmaNoteFetchParams noteFetchParams = 1;
+ ReceiverFetchXmaStoryFetchParams storyFetchParams = 2;
+ ReceiverFetchXmaProfileFetchParams profileFetchParams = 3;
+ ReceiverFetchXmaClipFetchParams clipFetchParams = 4;
+ ReceiverFetchXmaFeedFetchParams feedFetchParams = 5;
+ ReceiverFetchXmaLiveFetchParams liveFetchParams = 6;
+ ReceiverFetchXmaCommentFetchParams commentFetchParams = 7;
+ ReceiverFetchXmaLocationShareFetchParams locationShareFetchParams = 8;
+ ReceiverFetchXmaReelsAudioFetchParams reelsAudioFetchParams = 9;
+ ReceiverFetchXmaMediaNoteFetchParams mediaNoteFetchParams = 10;
+ ReceiverFetchXmaSocialContextFetchParams socialContextFetchParams = 11;
+ }
+}
+
+message ReceiverFetchXmaNoteFetchParams {
+ optional string noteIgid = 1;
+}
+
+message ReceiverFetchXmaStoryFetchParams {
+ optional string storyIgid = 1;
+ optional string reelID = 2;
+}
+
+message ReceiverFetchXmaProfileFetchParams {
+ optional string profileIgid = 1;
+}
+
+message ReceiverFetchXmaClipFetchParams {
+ optional string mediaIgid = 1;
+}
+
+message ReceiverFetchXmaFeedFetchParams {
+ optional string mediaIgid = 1;
+ optional string carouselShareChildMediaIgid = 2;
+}
+
+message ReceiverFetchXmaLiveFetchParams {
+ optional string liveIgid = 1;
+}
+
+message ReceiverFetchXmaCommentFetchParams {
+ optional string commentFbid = 1;
+}
+
+message ReceiverFetchXmaLocationShareFetchParams {
+ optional string locationIgid = 1;
+}
+
+message ReceiverFetchXmaReelsAudioFetchParams {
+ optional string audioIgid = 1;
+}
+
+message ReceiverFetchXmaMediaNoteFetchParams {
+ optional string mediaNoteIgid = 1;
+ optional MediaNoteFetchParamsMessageType messageType = 2;
+}
+
+message ReceiverFetchXmaSocialContextFetchParams {
+ optional string mediaIgid = 1;
+}
diff --git a/crates/whatsmeow_proto/proto/waAICommon/WAWebProtobufsAICommon.proto b/crates/whatsmeow_proto/proto/waAICommon/WAWebProtobufsAICommon.proto
new file mode 100644
index 0000000000..5eac6731d0
--- /dev/null
+++ b/crates/whatsmeow_proto/proto/waAICommon/WAWebProtobufsAICommon.proto
@@ -0,0 +1,905 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+syntax = "proto2";
+package WAWebProtobufsAICommon;
+option go_package = "go.mau.fi/whatsmeow/proto/waAICommon";
+
+import "waCommon/WACommon.proto";
+
+enum BotMetricsEntryPoint {
+ UNDEFINED_ENTRY_POINT = 0;
+ FAVICON = 1;
+ CHATLIST = 2;
+ AISEARCH_NULL_STATE_PAPER_PLANE = 3;
+ AISEARCH_NULL_STATE_SUGGESTION = 4;
+ AISEARCH_TYPE_AHEAD_SUGGESTION = 5;
+ AISEARCH_TYPE_AHEAD_PAPER_PLANE = 6;
+ AISEARCH_TYPE_AHEAD_RESULT_CHATLIST = 7;
+ AISEARCH_TYPE_AHEAD_RESULT_MESSAGES = 8;
+ AIVOICE_SEARCH_BAR = 9;
+ AIVOICE_FAVICON = 10;
+ AISTUDIO = 11;
+ DEEPLINK = 12;
+ NOTIFICATION = 13;
+ PROFILE_MESSAGE_BUTTON = 14;
+ FORWARD = 15;
+ APP_SHORTCUT = 16;
+ FF_FAMILY = 17;
+ AI_TAB = 18;
+ AI_HOME = 19;
+ AI_DEEPLINK_IMMERSIVE = 20;
+ AI_DEEPLINK = 21;
+ META_AI_CHAT_SHORTCUT_AI_STUDIO = 22;
+ UGC_CHAT_SHORTCUT_AI_STUDIO = 23;
+ NEW_CHAT_AI_STUDIO = 24;
+ AIVOICE_FAVICON_CALL_HISTORY = 25;
+ ASK_META_AI_CONTEXT_MENU = 26;
+ ASK_META_AI_CONTEXT_MENU_1ON1 = 27;
+ ASK_META_AI_CONTEXT_MENU_GROUP = 28;
+ INVOKE_META_AI_1ON1 = 29;
+ INVOKE_META_AI_GROUP = 30;
+ META_AI_FORWARD = 31;
+ NEW_CHAT_AI_CONTACT = 32;
+ MESSAGE_QUICK_ACTION_1_ON_1_CHAT = 33;
+ MESSAGE_QUICK_ACTION_GROUP_CHAT = 34;
+ ATTACHMENT_TRAY_1_ON_1_CHAT = 35;
+ ATTACHMENT_TRAY_GROUP_CHAT = 36;
+ ASK_META_AI_MEDIA_VIEWER_1ON1 = 37;
+ ASK_META_AI_MEDIA_VIEWER_GROUP = 38;
+ MEDIA_PICKER_1_ON_1_CHAT = 39;
+ MEDIA_PICKER_GROUP_CHAT = 40;
+ ASK_META_AI_NO_SEARCH_RESULTS = 41;
+ META_AI_SETTINGS = 45;
+ WEB_INTRO_PANEL = 46;
+ WEB_NAVIGATION_BAR = 47;
+ GROUP_MEMBER = 54;
+ CHATLIST_SEARCH = 55;
+ NEW_CHAT_LIST = 56;
+ CONTACTS_TAB = 57;
+ NEW_3P_AGENT_CREATION = 58;
+ SHARE = 59;
+}
+
+enum BotMetricsThreadEntryPoint {
+ AI_TAB_THREAD = 1;
+ AI_HOME_THREAD = 2;
+ AI_DEEPLINK_IMMERSIVE_THREAD = 3;
+ AI_DEEPLINK_THREAD = 4;
+ ASK_META_AI_CONTEXT_MENU_THREAD = 5;
+}
+
+enum BotSessionSource {
+ NONE = 0;
+ NULL_STATE = 1;
+ TYPEAHEAD = 2;
+ USER_INPUT = 3;
+ EMU_FLASH = 4;
+ EMU_FLASH_FOLLOWUP = 5;
+ VOICE = 6;
+ AI_HOME_SESSION = 7;
+}
+
+enum AISubscriptionRequestType {
+ UNSPECIFIED = 0;
+ THINK_HARD = 1;
+ IMAGE_GEN = 2;
+ VIDEO_GEN = 3;
+}
+
+enum SessionTransparencyType {
+ UNKNOWN_TYPE = 0;
+ NY_AI_SAFETY_DISCLAIMER = 1;
+}
+
+message BotPluginMetadata {
+ enum PluginType {
+ UNKNOWN_PLUGIN = 0;
+ REELS = 1;
+ SEARCH = 2;
+ }
+
+ enum SearchProvider {
+ UNKNOWN = 0;
+ BING = 1;
+ GOOGLE = 2;
+ SUPPORT = 3;
+ }
+
+ optional SearchProvider provider = 1;
+ optional PluginType pluginType = 2;
+ optional string thumbnailCDNURL = 3;
+ optional string profilePhotoCDNURL = 4;
+ optional string searchProviderURL = 5;
+ optional uint32 referenceIndex = 6;
+ optional uint32 expectedLinksCount = 7;
+ optional string searchQuery = 9;
+ optional WACommon.MessageKey parentPluginMessageKey = 10;
+ optional PluginType deprecatedField = 11;
+ optional PluginType parentPluginType = 12;
+ optional string faviconCDNURL = 13;
+}
+
+message BotLinkedAccount {
+ enum BotLinkedAccountType {
+ BOT_LINKED_ACCOUNT_TYPE_1P = 0;
+ }
+
+ optional BotLinkedAccountType type = 1;
+}
+
+message BotSignatureVerificationUseCaseProof {
+ enum BotSignatureUseCase {
+ UNSPECIFIED = 0;
+ WA_BOT_MSG = 1;
+ WA_TEE_BOT_MSG = 2;
+ P2P_PILLS = 3;
+ WA_WAFFLE = 4;
+ WA_FEATURE_PKI = 5;
+ }
+
+ message CertificateSKI {
+ optional BotSignatureUseCase useCase = 1;
+ optional bytes ski = 2;
+ }
+
+ optional int32 version = 1;
+ optional BotSignatureUseCase useCase = 2;
+ optional bytes signature = 3;
+ repeated bytes certificateChain = 4;
+ repeated CertificateSKI certificateChainSki = 5;
+}
+
+message BotPromotionMessageMetadata {
+ enum BotPromotionType {
+ UNKNOWN_TYPE = 0;
+ C50 = 1;
+ SURVEY_PLATFORM = 2;
+ }
+
+ optional BotPromotionType promotionType = 1;
+ optional string buttonTitle = 2;
+}
+
+message BotMediaMetadata {
+ enum OrientationType {
+ CENTER = 1;
+ LEFT = 2;
+ RIGHT = 3;
+ }
+
+ optional string fileSHA256 = 1;
+ optional string mediaKey = 2;
+ optional string fileEncSHA256 = 3;
+ optional string directPath = 4;
+ optional int64 mediaKeyTimestamp = 5;
+ optional string mimetype = 6;
+ optional OrientationType orientationType = 7;
+}
+
+message BotReminderMetadata {
+ enum ReminderFrequency {
+ ONCE = 1;
+ DAILY = 2;
+ WEEKLY = 3;
+ BIWEEKLY = 4;
+ MONTHLY = 5;
+ }
+
+ enum ReminderAction {
+ NOTIFY = 1;
+ CREATE = 2;
+ DELETE = 3;
+ UPDATE = 4;
+ }
+
+ optional WACommon.MessageKey requestMessageKey = 1;
+ optional ReminderAction action = 2;
+ optional string name = 3;
+ optional uint64 nextTriggerTimestamp = 4;
+ optional ReminderFrequency frequency = 5;
+}
+
+message BotModelMetadata {
+ enum PremiumModelStatus {
+ UNKNOWN_STATUS = 0;
+ AVAILABLE = 1;
+ QUOTA_EXCEED_LIMIT = 2;
+ }
+
+ enum ModelType {
+ UNKNOWN_TYPE = 0;
+ LLAMA_PROD = 1;
+ LLAMA_PROD_PREMIUM = 2;
+ }
+
+ optional ModelType modelType = 1;
+ optional PremiumModelStatus premiumModelStatus = 2;
+ optional string modelNameOverride = 3;
+}
+
+message BotProgressIndicatorMetadata {
+ message BotPlanningStepMetadata {
+ enum BotSearchSourceProvider {
+ UNKNOWN_PROVIDER = 0;
+ OTHER = 1;
+ GOOGLE = 2;
+ BING = 3;
+ }
+
+ enum PlanningStepStatus {
+ UNKNOWN = 0;
+ PLANNED = 1;
+ EXECUTING = 2;
+ FINISHED = 3;
+ }
+
+ message BotPlanningSearchSourcesMetadata {
+ enum BotPlanningSearchSourceProvider {
+ UNKNOWN = 0;
+ OTHER = 1;
+ GOOGLE = 2;
+ BING = 3;
+ }
+
+ optional string sourceTitle = 1;
+ optional BotPlanningSearchSourceProvider provider = 2;
+ optional string sourceURL = 3;
+ }
+
+ message BotPlanningStepSectionMetadata {
+ optional string sectionTitle = 1;
+ optional string sectionBody = 2;
+ repeated BotPlanningSearchSourceMetadata sourcesMetadata = 3;
+ }
+
+ message BotPlanningSearchSourceMetadata {
+ optional string title = 1;
+ optional BotSearchSourceProvider provider = 2;
+ optional string sourceURL = 3;
+ optional string favIconURL = 4;
+ }
+
+ optional string statusTitle = 1;
+ optional string statusBody = 2;
+ repeated BotPlanningSearchSourcesMetadata sourcesMetadata = 3;
+ optional PlanningStepStatus status = 4;
+ optional bool isReasoning = 5;
+ optional bool isEnhancedSearch = 6;
+ repeated BotPlanningStepSectionMetadata sections = 7;
+ }
+
+ optional string progressDescription = 1;
+ repeated BotPlanningStepMetadata stepsMetadata = 2;
+ optional int64 estimatedCompletionTime = 3;
+}
+
+message BotCapabilityMetadata {
+ enum BotCapabilityType {
+ UNKNOWN = 0;
+ PROGRESS_INDICATOR = 1;
+ RICH_RESPONSE_HEADING = 2;
+ RICH_RESPONSE_NESTED_LIST = 3;
+ AI_MEMORY = 4;
+ RICH_RESPONSE_THREAD_SURFING = 5;
+ RICH_RESPONSE_TABLE = 6;
+ RICH_RESPONSE_CODE = 7;
+ RICH_RESPONSE_STRUCTURED_RESPONSE = 8;
+ RICH_RESPONSE_INLINE_IMAGE = 9;
+ WA_IG_1P_PLUGIN_RANKING_CONTROL = 10;
+ WA_IG_1P_PLUGIN_RANKING_UPDATE_1 = 11;
+ WA_IG_1P_PLUGIN_RANKING_UPDATE_2 = 12;
+ WA_IG_1P_PLUGIN_RANKING_UPDATE_3 = 13;
+ WA_IG_1P_PLUGIN_RANKING_UPDATE_4 = 14;
+ WA_IG_1P_PLUGIN_RANKING_UPDATE_5 = 15;
+ WA_IG_1P_PLUGIN_RANKING_UPDATE_6 = 16;
+ WA_IG_1P_PLUGIN_RANKING_UPDATE_7 = 17;
+ WA_IG_1P_PLUGIN_RANKING_UPDATE_8 = 18;
+ WA_IG_1P_PLUGIN_RANKING_UPDATE_9 = 19;
+ WA_IG_1P_PLUGIN_RANKING_UPDATE_10 = 20;
+ RICH_RESPONSE_SUB_HEADING = 21;
+ RICH_RESPONSE_GRID_IMAGE = 22;
+ AI_STUDIO_UGC_MEMORY = 23;
+ RICH_RESPONSE_LATEX = 24;
+ RICH_RESPONSE_MAPS = 25;
+ RICH_RESPONSE_INLINE_REELS = 26;
+ AGENTIC_PLANNING = 27;
+ ACCOUNT_LINKING = 28;
+ STREAMING_DISAGGREGATION = 29;
+ RICH_RESPONSE_GRID_IMAGE_3P = 30;
+ RICH_RESPONSE_LATEX_INLINE = 31;
+ QUERY_PLAN = 32;
+ PROACTIVE_MESSAGE = 33;
+ RICH_RESPONSE_UNIFIED_RESPONSE = 34;
+ PROMOTION_MESSAGE = 35;
+ SIMPLIFIED_PROFILE_PAGE = 36;
+ RICH_RESPONSE_SOURCES_IN_MESSAGE = 37;
+ RICH_RESPONSE_SIDE_BY_SIDE_SURVEY = 38;
+ RICH_RESPONSE_UNIFIED_TEXT_COMPONENT = 39;
+ AI_SHARED_MEMORY = 40;
+ RICH_RESPONSE_UNIFIED_SOURCES = 41;
+ RICH_RESPONSE_UNIFIED_DOMAIN_CITATIONS = 42;
+ RICH_RESPONSE_UR_INLINE_REELS_ENABLED = 43;
+ RICH_RESPONSE_UR_MEDIA_GRID_ENABLED = 44;
+ RICH_RESPONSE_UR_TIMESTAMP_PLACEHOLDER = 45;
+ RICH_RESPONSE_IN_APP_SURVEY = 46;
+ AI_RESPONSE_MODEL_BRANDING = 47;
+ SESSION_TRANSPARENCY_SYSTEM_MESSAGE = 48;
+ RICH_RESPONSE_UR_REASONING = 49;
+ RICH_RESPONSE_UR_ZEITGEIST_CITATIONS = 50;
+ RICH_RESPONSE_UR_ZEITGEIST_CAROUSEL = 51;
+ AI_IMAGINE_LOADING_INDICATOR = 52;
+ RICH_RESPONSE_UR_IMAGINE = 53;
+ AI_IMAGINE_UR_TO_NATIVE_LOADING_INDICATOR = 54;
+ RICH_RESPONSE_UR_BLOKS_ENABLED = 55;
+ RICH_RESPONSE_INLINE_LINKS_ENABLED = 56;
+ RICH_RESPONSE_UR_IMAGINE_VIDEO = 57;
+ JSON_PATCH_STREAMING = 58;
+ AI_TAB_FORCE_CLIPPY = 59;
+ UNIFIED_RESPONSE_EMBEDDED_SCREENS = 60;
+ AI_SUBSCRIPTION_ENABLED = 61;
+ UNIFIED_RESPONSE_AI_CONTENT_SEARCH_ENABLED = 62;
+ UNIFIED_RESPONSE_MARKDOWN_LINKS_ENABLED = 63;
+ AI_RICH_RESPONSE_MAPS_V2_ENABLED = 64;
+ AI_SUBSCRIPTION_METERING_ENABLED = 65;
+ RICH_RESPONSE_SPORTS_WIDGET_ENABLED = 66;
+ AI_RICH_RESPONSE_ARTIFACTS_ENABLED = 67;
+ AI_RICH_RESPONSE_EMAIL_CALENDAR_ENABLED = 68;
+ AI_RICH_RESPONSE_REMINDERS_ENABLED = 69;
+ AI_STOP_GENERATION_ENABLED = 70;
+ AI_RICH_RESPONSE_3P_LINKING_CARD_ENABLED = 71;
+ HATCH_NOTIFICATION_METADATA_EVENT_ENABLED = 72;
+ AI_SUGGESTED_REPLIES_ENABLED = 73;
+ RICH_RESPONSE_IN_APP_SURVEY_BLOKS = 74;
+ RICH_RESPONSE_IMAGE_SOURCE_ATTRIBUTION = 75;
+ HATCH_CONNECTOR_ACTION_CARD_ENABLED = 76;
+ HATCH_SECURE_CREDENTIAL_CARD_ENABLED = 77;
+ HATCH_BROWSER_TASK_CARD_ENABLED = 78;
+ HATCH_ARTIFACT_CARD_ENABLED = 79;
+ AI_STUDY_CENTER_ENABLED = 80;
+ AI_MUSE_JARVIS_SCHEMA_ENABLED = 81;
+ AI_STUDY_QUIZ_ENABLED = 82;
+ }
+
+ repeated BotCapabilityType capabilities = 1;
+}
+
+message BotModeSelectionMetadata {
+ enum BotUserSelectionMode {
+ DEFAULT_MODE = 0;
+ THINK_HARD_MODE = 1;
+ }
+
+ repeated BotUserSelectionMode mode = 1;
+ repeated uint32 overrideMode = 2;
+}
+
+message BotQuotaMetadata {
+ message BotFeatureQuotaMetadata {
+ enum BotFeatureType {
+ UNKNOWN_FEATURE = 0;
+ REASONING_FEATURE = 1;
+ }
+
+ optional BotFeatureType featureType = 1;
+ optional uint32 remainingQuota = 2;
+ optional uint64 expirationTimestamp = 3;
+ }
+
+ repeated BotFeatureQuotaMetadata botFeatureQuotaMetadata = 1;
+}
+
+message BotImagineMetadata {
+ enum ImagineType {
+ UNKNOWN = 0;
+ IMAGINE = 1;
+ MEMU = 2;
+ FLASH = 3;
+ EDIT = 4;
+ }
+
+ optional ImagineType imagineType = 1;
+ optional string shortPrompt = 2;
+}
+
+message BotAgeCollectionMetadata {
+ enum AgeCollectionType {
+ O18_BINARY = 0;
+ WAFFLE = 1;
+ }
+
+ optional bool ageCollectionEligible = 1;
+ optional bool shouldTriggerAgeCollectionOnClient = 2;
+ optional AgeCollectionType ageCollectionType = 3;
+}
+
+message BotSourcesMetadata {
+ message BotSourceItem {
+ enum SourceProvider {
+ UNKNOWN = 0;
+ BING = 1;
+ GOOGLE = 2;
+ SUPPORT = 3;
+ OTHER = 4;
+ }
+
+ optional SourceProvider provider = 1;
+ optional string thumbnailCDNURL = 2;
+ optional string sourceProviderURL = 3;
+ optional string sourceQuery = 4;
+ optional string faviconCDNURL = 5;
+ optional uint32 citationNumber = 6;
+ optional string sourceTitle = 7;
+ }
+
+ repeated BotSourceItem sources = 1;
+}
+
+message BotMessageOrigin {
+ enum BotMessageOriginType {
+ BOT_MESSAGE_ORIGIN_TYPE_AI_INITIATED = 0;
+ BOT_MESSAGE_ORIGIN_TYPE_META_AI_THREAD_WELCOME = 1;
+ }
+
+ optional BotMessageOriginType type = 1;
+}
+
+message AIThreadInfo {
+ message AIThreadClientInfo {
+ enum AIThreadType {
+ UNKNOWN = 0;
+ DEFAULT = 1;
+ INCOGNITO = 2;
+ SIDE_CHAT = 3;
+ PRIVATE_SEARCH_CHAT = 4;
+ }
+
+ optional AIThreadType type = 1;
+ optional string sourceChatJID = 2;
+ }
+
+ message AIThreadServerInfo {
+ optional string title = 1;
+ }
+
+ optional AIThreadServerInfo serverInfo = 1;
+ optional AIThreadClientInfo clientInfo = 2;
+}
+
+message BotFeedbackMessage {
+ enum ReportKind {
+ NONE = 0;
+ GENERIC = 1;
+ }
+
+ enum BotFeedbackKindMultiplePositive {
+ BOT_FEEDBACK_MULTIPLE_POSITIVE_GENERIC = 1;
+ }
+
+ enum BotFeedbackKindMultipleNegative {
+ BOT_FEEDBACK_MULTIPLE_NEGATIVE_GENERIC = 1;
+ BOT_FEEDBACK_MULTIPLE_NEGATIVE_HELPFUL = 2;
+ BOT_FEEDBACK_MULTIPLE_NEGATIVE_INTERESTING = 4;
+ BOT_FEEDBACK_MULTIPLE_NEGATIVE_ACCURATE = 8;
+ BOT_FEEDBACK_MULTIPLE_NEGATIVE_SAFE = 16;
+ BOT_FEEDBACK_MULTIPLE_NEGATIVE_OTHER = 32;
+ BOT_FEEDBACK_MULTIPLE_NEGATIVE_REFUSED = 64;
+ BOT_FEEDBACK_MULTIPLE_NEGATIVE_NOT_VISUALLY_APPEALING = 128;
+ BOT_FEEDBACK_MULTIPLE_NEGATIVE_NOT_RELEVANT_TO_TEXT = 256;
+ }
+
+ enum BotFeedbackKind {
+ BOT_FEEDBACK_POSITIVE = 0;
+ BOT_FEEDBACK_NEGATIVE_GENERIC = 1;
+ BOT_FEEDBACK_NEGATIVE_HELPFUL = 2;
+ BOT_FEEDBACK_NEGATIVE_INTERESTING = 3;
+ BOT_FEEDBACK_NEGATIVE_ACCURATE = 4;
+ BOT_FEEDBACK_NEGATIVE_SAFE = 5;
+ BOT_FEEDBACK_NEGATIVE_OTHER = 6;
+ BOT_FEEDBACK_NEGATIVE_REFUSED = 7;
+ BOT_FEEDBACK_NEGATIVE_NOT_VISUALLY_APPEALING = 8;
+ BOT_FEEDBACK_NEGATIVE_NOT_RELEVANT_TO_TEXT = 9;
+ BOT_FEEDBACK_NEGATIVE_PERSONALIZED = 10;
+ BOT_FEEDBACK_NEGATIVE_CLARITY = 11;
+ BOT_FEEDBACK_NEGATIVE_DOESNT_LOOK_LIKE_THE_PERSON = 12;
+ BOT_FEEDBACK_NEGATIVE_HALLUCINATION_INTERNAL_ONLY = 13;
+ BOT_FEEDBACK_NEGATIVE = 14;
+ }
+
+ message SideBySideSurveyMetadata {
+ message SidebySideSurveyMetaAiAnalyticsData {
+ message SideBySideSurveyAbandonEventData {
+ optional string abandonDwellTimeMSString = 1;
+ }
+
+ message SideBySideSurveyResponseEventData {
+ optional string responseDwellTimeMSString = 1;
+ optional string selectedResponseID = 2;
+ }
+
+ message SideBySideSurveyCardImpressionEventData {
+ }
+
+ message SideBySideSurveyCTAClickEventData {
+ optional bool isSurveyExpired = 1;
+ optional string clickDwellTimeMSString = 2;
+ }
+
+ message SideBySideSurveyCTAImpressionEventData {
+ optional bool isSurveyExpired = 1;
+ }
+
+ optional uint32 surveyID = 1;
+ optional string primaryResponseID = 2;
+ optional string testArmName = 3;
+ optional string timestampMSString = 4;
+ optional SideBySideSurveyCTAImpressionEventData ctaImpressionEvent = 5;
+ optional SideBySideSurveyCTAClickEventData ctaClickEvent = 6;
+ optional SideBySideSurveyCardImpressionEventData cardImpressionEvent = 7;
+ optional SideBySideSurveyResponseEventData responseEvent = 8;
+ optional SideBySideSurveyAbandonEventData abandonEvent = 9;
+ }
+
+ message SideBySideSurveyAnalyticsData {
+ optional string tessaEvent = 1;
+ optional string tessaSessionFbid = 2;
+ optional string simonSessionFbid = 3;
+ }
+
+ optional string selectedRequestID = 1;
+ optional uint32 surveyID = 2;
+ optional string simonSessionFbid = 3;
+ optional string responseOtid = 4;
+ optional string responseTimestampMSString = 5;
+ optional bool isSelectedResponsePrimary = 6;
+ optional string messageIDToEdit = 7;
+ optional SideBySideSurveyAnalyticsData analyticsData = 8;
+ optional SidebySideSurveyMetaAiAnalyticsData metaAiAnalyticsData = 9;
+ }
+
+ optional WACommon.MessageKey messageKey = 1;
+ optional BotFeedbackKind kind = 2;
+ optional string text = 3;
+ optional uint64 kindNegative = 4;
+ optional uint64 kindPositive = 5;
+ optional ReportKind kindReport = 6;
+ optional SideBySideSurveyMetadata sideBySideSurveyMetadata = 7;
+}
+
+message BotDocumentMessageMetadata {
+ enum DocumentPluginType {
+ TEXT_EXTRACTION = 0;
+ OCR_AND_IMAGES = 1;
+ }
+
+ optional DocumentPluginType pluginType = 1;
+}
+
+message AIHomeState {
+ message AIHomeOption {
+ enum AIHomeActionType {
+ PROMPT = 0;
+ CREATE_IMAGE = 1;
+ ANIMATE_PHOTO = 2;
+ ANALYZE_FILE = 3;
+ COLLABORATE = 4;
+ OPEN_GREETING_CARD = 5;
+ }
+
+ optional AIHomeActionType type = 1;
+ optional string title = 2;
+ optional string promptText = 3;
+ optional string sessionID = 4;
+ optional string imageWdsIdentifier = 5;
+ optional string imageTintColor = 6;
+ optional string imageBackgroundColor = 7;
+ optional string cardTypeID = 8;
+ }
+
+ optional int64 lastFetchTime = 1;
+ repeated AIHomeOption capabilityOptions = 2;
+ repeated AIHomeOption conversationOptions = 3;
+}
+
+message BotInfrastructureDiagnostics {
+ enum BotBackend {
+ AAPI = 0;
+ CLIPPY = 1;
+ }
+
+ optional BotBackend botBackend = 1;
+ repeated string toolsUsed = 2;
+ optional bool isThinking = 3;
+}
+
+message BizAIMetadataSync {
+ message ServerEvent {
+ enum ProtocolEvent {
+ UNSPECIFIED = 0;
+ AGENT_CHAT_READY = 1;
+ }
+
+ message AgentOnboardingStarted {
+ optional int64 composerBlockDurationSecs = 1;
+ }
+
+ oneof event {
+ ProtocolEvent protocolEvent = 1;
+ AgentOnboardingStarted agentOnboardingStarted = 2;
+ }
+ }
+
+ oneof operation {
+ ServerEvent serverEvent = 1;
+ }
+}
+
+message BotSuggestedPromptMetadata {
+ repeated string suggestedPrompts = 1;
+ optional uint32 selectedPromptIndex = 2;
+ optional BotPromptSuggestions promptSuggestions = 3;
+ optional string selectedPromptID = 4;
+}
+
+message BotPromptSuggestions {
+ repeated BotPromptSuggestion suggestions = 1;
+}
+
+message BotPromptSuggestion {
+ optional string prompt = 1;
+ optional string promptID = 2;
+}
+
+message BotLinkedAccountsMetadata {
+ repeated BotLinkedAccount accounts = 1;
+ optional bytes acAuthTokens = 2;
+ optional int32 acErrorCode = 3;
+}
+
+message BotMemoryMetadata {
+ repeated BotMemoryFact addedFacts = 1;
+ repeated BotMemoryFact removedFacts = 2;
+ optional string disclaimer = 3;
+}
+
+message BotMemoryFact {
+ optional string fact = 1;
+ optional string factID = 2;
+}
+
+message BotSignatureVerificationMetadata {
+ repeated BotSignatureVerificationUseCaseProof proofs = 1;
+}
+
+message BotRenderingMetadata {
+ message Keyword {
+ optional string value = 1;
+ repeated string associatedPrompts = 2;
+ }
+
+ repeated Keyword keywords = 1;
+}
+
+message BotMetricsMetadata {
+ optional string destinationID = 1;
+ optional BotMetricsEntryPoint destinationEntryPoint = 2;
+ optional BotMetricsThreadEntryPoint threadOrigin = 3;
+}
+
+message BotSessionMetadata {
+ optional string sessionID = 1;
+ optional BotSessionSource sessionSource = 2;
+}
+
+message BotMemuMetadata {
+ repeated BotMediaMetadata faceImages = 1;
+}
+
+message InThreadSurveyMetadata {
+ message InThreadSurveyPrivacyStatementPart {
+ optional string text = 1;
+ optional string URL = 2;
+ }
+
+ message InThreadSurveyOption {
+ optional string stringValue = 1;
+ optional uint32 numericValue = 2;
+ optional string textTranslated = 3;
+ }
+
+ message InThreadSurveyQuestion {
+ optional string questionText = 1;
+ optional string questionID = 2;
+ repeated InThreadSurveyOption questionOptions = 3;
+ }
+
+ optional string tessaSessionID = 1;
+ optional string simonSessionID = 2;
+ optional string simonSurveyID = 3;
+ optional string tessaRootID = 4;
+ optional string requestID = 5;
+ optional string tessaEvent = 6;
+ optional string invitationHeaderText = 7;
+ optional string invitationBodyText = 8;
+ optional string invitationCtaText = 9;
+ optional string invitationCtaURL = 10;
+ optional string surveyTitle = 11;
+ repeated InThreadSurveyQuestion questions = 12;
+ optional string surveyContinueButtonText = 13;
+ optional string surveySubmitButtonText = 14;
+ optional string privacyStatementFull = 15;
+ repeated InThreadSurveyPrivacyStatementPart privacyStatementParts = 16;
+ optional string feedbackToastText = 17;
+ optional int32 startQuestionIndex = 18;
+}
+
+message BotMessageOriginMetadata {
+ repeated BotMessageOrigin origins = 1;
+}
+
+message BotUnifiedResponseMutation {
+ message MediaDetailsMetadata {
+ optional string ID = 1;
+ optional BotMediaMetadata highResMedia = 2;
+ optional BotMediaMetadata previewMedia = 3;
+ }
+
+ message SideBySideMetadata {
+ optional string primaryResponseID = 1;
+ optional bool surveyCtaHasRendered = 2;
+ }
+
+ optional SideBySideMetadata sbsMetadata = 1;
+ repeated MediaDetailsMetadata mediaDetailsMetadataList = 2;
+}
+
+message AIMediaCollectionMetadata {
+ optional string collectionID = 1;
+ optional uint32 uploadOrderIndex = 2;
+}
+
+message AIMediaCollectionMessage {
+ optional string collectionID = 1;
+ optional uint32 expectedMediaCount = 2;
+ optional bool hasGlobalCaption = 3;
+}
+
+message HatchMetadataSync {
+ optional bytes data = 1;
+ optional int64 timestampMS = 2;
+ optional string requestID = 3;
+}
+
+message AIMetadataOperation {
+ optional HatchMetadataSync hatchMetadataSync = 1;
+ optional BizAIMetadataSync bizAiMetadataSync = 2;
+}
+
+message BotCommandMetadata {
+ optional string commandName = 1;
+ optional string commandDescription = 2;
+ optional string commandPrompt = 3;
+}
+
+message BotResolvedToolCallMetadata {
+ optional string toolCallID = 1;
+ optional string resolutionDataSerialized = 2;
+}
+
+message BotPttPromptMetadata {
+ optional string transcript = 1;
+}
+
+message BotMetadata {
+ optional string personaID = 2;
+ optional BotPluginMetadata pluginMetadata = 3;
+ optional BotSuggestedPromptMetadata suggestedPromptMetadata = 4;
+ optional string invokerJID = 5;
+ optional BotSessionMetadata sessionMetadata = 6;
+ optional BotMemuMetadata memuMetadata = 7;
+ optional string timezone = 8;
+ optional BotReminderMetadata reminderMetadata = 9;
+ optional BotModelMetadata modelMetadata = 10;
+ optional string messageDisclaimerText = 11;
+ optional BotProgressIndicatorMetadata progressIndicatorMetadata = 12;
+ optional BotCapabilityMetadata capabilityMetadata = 13;
+ optional BotImagineMetadata imagineMetadata = 14;
+ optional BotMemoryMetadata memoryMetadata = 15;
+ optional BotRenderingMetadata renderingMetadata = 16;
+ optional BotMetricsMetadata botMetricsMetadata = 17;
+ optional BotLinkedAccountsMetadata botLinkedAccountsMetadata = 18;
+ optional BotSourcesMetadata richResponseSourcesMetadata = 19;
+ optional bytes aiConversationContext = 20;
+ optional BotPromotionMessageMetadata botPromotionMessageMetadata = 21;
+ optional BotModeSelectionMetadata botModeSelectionMetadata = 22;
+ optional BotQuotaMetadata botQuotaMetadata = 23;
+ optional BotAgeCollectionMetadata botAgeCollectionMetadata = 24;
+ optional string conversationStarterPromptID = 25;
+ optional string botResponseID = 26;
+ optional BotSignatureVerificationMetadata verificationMetadata = 27;
+ optional BotUnifiedResponseMutation unifiedResponseMutation = 28;
+ optional BotMessageOriginMetadata botMessageOriginMetadata = 29;
+ optional InThreadSurveyMetadata inThreadSurveyMetadata = 30;
+ optional AIThreadInfo botThreadInfo = 31;
+ optional AIRegenerateMetadata regenerateMetadata = 32;
+ optional SessionTransparencyMetadata sessionTransparencyMetadata = 33;
+ optional BotDocumentMessageMetadata botDocumentMessageMetadata = 34;
+ optional BotGroupMetadata botGroupMetadata = 35;
+ optional BotRenderingConfigMetadata botRenderingConfigMetadata = 36;
+ optional BotInfrastructureDiagnostics botInfrastructureDiagnostics = 37;
+ optional AIMediaCollectionMetadata aiMediaCollectionMetadata = 38;
+ optional BotCommandMetadata commandMetadata = 39;
+ optional BotResolvedToolCallMetadata resolvedToolCallMetadata = 40;
+ optional AISubscriptionUpsellMetadata subscriptionUpsellMetadata = 41;
+ optional BotPttPromptMetadata pttPromptMetadata = 42;
+ optional BotHistoryShareMetadata botHistoryShareMetadata = 43;
+ optional bool responseStoppedByUser = 44;
+ optional bytes internalMetadata = 999;
+}
+
+message AISubscriptionUpsellMetadata {
+ optional AISubscriptionRequestType requestType = 1;
+}
+
+message BotGroupMetadata {
+ repeated BotGroupParticipantMetadata participantsMetadata = 1;
+}
+
+message BotHistoryShareMetadata {
+ repeated BotGroupParticipantMetadata participantsMetadata = 1;
+}
+
+message BotRenderingConfigMetadata {
+ optional string bloksVersioningID = 1;
+ optional double pixelDensity = 2;
+}
+
+message BotGroupParticipantMetadata {
+ optional string botFbid = 1;
+}
+
+message ForwardedAIBotMessageInfo {
+ optional string botName = 1;
+ optional string botJID = 2;
+ optional string creatorName = 3;
+}
+
+message BotMessageSharingInfo {
+ optional BotMetricsEntryPoint botEntryPointOrigin = 1;
+ optional uint32 forwardScore = 2;
+}
+
+message AIRichResponseUnifiedResponse {
+ optional bytes data = 1;
+}
+
+message AIRegenerateMetadata {
+ optional WACommon.MessageKey messageKey = 1;
+ optional int64 responseTimestampMS = 2;
+}
+
+message SessionTransparencyMetadata {
+ optional string disclaimerText = 1;
+ optional string hcaID = 2;
+ optional SessionTransparencyType sessionTransparencyType = 3;
+}
+
+message BotAgentMetadata {
+ optional BotAgentDeepLinkMetadata deepLinkMetadata = 1;
+}
+
+message BotAgentDeepLinkMetadata {
+ optional string token = 1;
+ optional bytes clientPublicKey = 2;
+}
+
+message AIProvenance {
+ message Metadata {
+ optional bool createdWithGenAi = 1;
+ optional bool editedWithGenAi = 2;
+ }
+
+ optional Metadata c2PaMetadata = 1;
+ optional Metadata iptcMetadata = 2;
+}
diff --git a/crates/whatsmeow_proto/proto/waAICommonDeprecated/WAAICommonDeprecated.proto b/crates/whatsmeow_proto/proto/waAICommonDeprecated/WAAICommonDeprecated.proto
new file mode 100644
index 0000000000..23d6467257
--- /dev/null
+++ b/crates/whatsmeow_proto/proto/waAICommonDeprecated/WAAICommonDeprecated.proto
@@ -0,0 +1,161 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+syntax = "proto2";
+package WAAICommonDeprecated;
+option go_package = "go.mau.fi/whatsmeow/proto/waAICommonDeprecated";
+
+enum AIRichResponseMessageType {
+ AI_RICH_RESPONSE_TYPE_UNKNOWN = 0;
+ AI_RICH_RESPONSE_TYPE_STANDARD = 1;
+}
+
+enum AIRichResponseSubMessageType {
+ AI_RICH_RESPONSE_UNKNOWN = 0;
+ AI_RICH_RESPONSE_GRID_IMAGE = 1;
+ AI_RICH_RESPONSE_TEXT = 2;
+ AI_RICH_RESPONSE_INLINE_IMAGE = 3;
+ AI_RICH_RESPONSE_TABLE = 4;
+ AI_RICH_RESPONSE_CODE = 5;
+ AI_RICH_RESPONSE_DYNAMIC = 6;
+ AI_RICH_RESPONSE_MAP = 7;
+ AI_RICH_RESPONSE_LATEX = 8;
+ AI_RICH_RESPONSE_CONTENT_ITEMS = 9;
+}
+
+message AIRichResponseInlineImageMetadata {
+ enum AIRichResponseImageAlignment {
+ AI_RICH_RESPONSE_IMAGE_LAYOUT_LEADING_ALIGNED = 0;
+ AI_RICH_RESPONSE_IMAGE_LAYOUT_TRAILING_ALIGNED = 1;
+ AI_RICH_RESPONSE_IMAGE_LAYOUT_CENTER_ALIGNED = 2;
+ }
+
+ optional AIRichResponseImageURL imageURL = 1;
+ optional string imageText = 2;
+ optional AIRichResponseImageAlignment alignment = 3;
+ optional string tapLinkURL = 4;
+}
+
+message AIRichResponseCodeMetadata {
+ enum AIRichResponseCodeHighlightType {
+ AI_RICH_RESPONSE_CODE_HIGHLIGHT_DEFAULT = 0;
+ AI_RICH_RESPONSE_CODE_HIGHLIGHT_KEYWORD = 1;
+ AI_RICH_RESPONSE_CODE_HIGHLIGHT_METHOD = 2;
+ AI_RICH_RESPONSE_CODE_HIGHLIGHT_STRING = 3;
+ AI_RICH_RESPONSE_CODE_HIGHLIGHT_NUMBER = 4;
+ AI_RICH_RESPONSE_CODE_HIGHLIGHT_COMMENT = 5;
+ }
+
+ message AIRichResponseCodeBlock {
+ optional AIRichResponseCodeHighlightType highlightType = 1;
+ optional string codeContent = 2;
+ }
+
+ optional string codeLanguage = 1;
+ repeated AIRichResponseCodeBlock codeBlocks = 2;
+}
+
+message AIRichResponseDynamicMetadata {
+ enum AIRichResponseDynamicMetadataType {
+ AI_RICH_RESPONSE_DYNAMIC_METADATA_TYPE_UNKNOWN = 0;
+ AI_RICH_RESPONSE_DYNAMIC_METADATA_TYPE_IMAGE = 1;
+ AI_RICH_RESPONSE_DYNAMIC_METADATA_TYPE_GIF = 2;
+ }
+
+ optional AIRichResponseDynamicMetadataType type = 1;
+ optional uint64 version = 2;
+ optional string URL = 3;
+ optional uint32 loopCount = 4;
+}
+
+message AIRichResponseContentItemsMetadata {
+ enum ContentType {
+ DEFAULT = 0;
+ CAROUSEL = 1;
+ }
+
+ message AIRichResponseContentItemMetadata {
+ oneof aIRichResponseContentItem {
+ AIRichResponseReelItem reelItem = 1;
+ }
+ }
+
+ message AIRichResponseReelItem {
+ optional string title = 1;
+ optional string profileIconURL = 2;
+ optional string thumbnailURL = 3;
+ optional string videoURL = 4;
+ }
+
+ repeated AIRichResponseContentItemMetadata itemsMetadata = 1;
+ optional ContentType contentType = 2;
+}
+
+message AIRichResponseImageURL {
+ optional string imagePreviewURL = 1;
+ optional string imageHighResURL = 2;
+ optional string sourceURL = 3;
+}
+
+message AIRichResponseGridImageMetadata {
+ optional AIRichResponseImageURL gridImageURL = 1;
+ repeated AIRichResponseImageURL imageURLs = 2;
+}
+
+message AIRichResponseTableMetadata {
+ message AIRichResponseTableRow {
+ repeated string items = 1;
+ optional bool isHeading = 2;
+ }
+
+ repeated AIRichResponseTableRow rows = 1;
+ optional string title = 2;
+}
+
+message AIRichResponseLatexMetadata {
+ message AIRichResponseLatexExpression {
+ optional string latexExpression = 1;
+ optional string URL = 2;
+ optional double width = 3;
+ optional double height = 4;
+ optional double fontHeight = 5;
+ optional double imageTopPadding = 6;
+ optional double imageLeadingPadding = 7;
+ optional double imageBottomPadding = 8;
+ optional double imageTrailingPadding = 9;
+ }
+
+ optional string text = 1;
+ repeated AIRichResponseLatexExpression expressions = 2;
+}
+
+message AIRichResponseMapMetadata {
+ message AIRichResponseMapAnnotation {
+ optional uint32 annotationNumber = 1;
+ optional double latitude = 2;
+ optional double longitude = 3;
+ optional string title = 4;
+ optional string body = 5;
+ }
+
+ optional double centerLatitude = 1;
+ optional double centerLongitude = 2;
+ optional double latitudeDelta = 3;
+ optional double longitudeDelta = 4;
+ repeated AIRichResponseMapAnnotation annotations = 5;
+ optional bool showInfoList = 6;
+}
+
+message AIRichResponseSubMessage {
+ optional AIRichResponseSubMessageType messageType = 1;
+ optional AIRichResponseGridImageMetadata gridImageMetadata = 2;
+ optional string messageText = 3;
+ optional AIRichResponseInlineImageMetadata imageMetadata = 4;
+ optional AIRichResponseCodeMetadata codeMetadata = 5;
+ optional AIRichResponseTableMetadata tableMetadata = 6;
+ optional AIRichResponseDynamicMetadata dynamicMetadata = 7;
+ optional AIRichResponseLatexMetadata latexMetadata = 8;
+ optional AIRichResponseMapMetadata mapMetadata = 9;
+ optional AIRichResponseContentItemsMetadata contentItemsMetadata = 10;
+}
diff --git a/crates/whatsmeow_proto/proto/waAdv/WAAdv.proto b/crates/whatsmeow_proto/proto/waAdv/WAAdv.proto
new file mode 100644
index 0000000000..6cca7f62f7
--- /dev/null
+++ b/crates/whatsmeow_proto/proto/waAdv/WAAdv.proto
@@ -0,0 +1,47 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+syntax = "proto2";
+package WAAdv;
+option go_package = "go.mau.fi/whatsmeow/proto/waAdv";
+
+enum ADVEncryptionType {
+ E2EE = 0;
+ HOSTED = 1;
+}
+
+message ADVKeyIndexList {
+ optional uint32 rawID = 1;
+ optional uint64 timestamp = 2;
+ optional uint32 currentIndex = 3;
+ repeated uint32 validIndexes = 4 [packed=true];
+ optional ADVEncryptionType accountType = 5;
+}
+
+message ADVSignedKeyIndexList {
+ optional bytes details = 1;
+ optional bytes accountSignature = 2;
+ optional bytes accountSignatureKey = 3;
+}
+
+message ADVDeviceIdentity {
+ optional uint32 rawID = 1;
+ optional uint64 timestamp = 2;
+ optional uint32 keyIndex = 3;
+ optional ADVEncryptionType accountType = 4;
+ optional ADVEncryptionType deviceType = 5;
+}
+
+message ADVSignedDeviceIdentity {
+ optional bytes details = 1;
+ optional bytes accountSignatureKey = 2;
+ optional bytes accountSignature = 3;
+ optional bytes deviceSignature = 4;
+}
+
+message ADVSignedDeviceIdentityHMAC {
+ optional bytes details = 1;
+ optional bytes HMAC = 2;
+ optional ADVEncryptionType accountType = 3;
+}
diff --git a/crates/whatsmeow_proto/proto/waAea/WAWebProtobufsAea.proto b/crates/whatsmeow_proto/proto/waAea/WAWebProtobufsAea.proto
new file mode 100644
index 0000000000..93e47d42b5
--- /dev/null
+++ b/crates/whatsmeow_proto/proto/waAea/WAWebProtobufsAea.proto
@@ -0,0 +1,17 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+syntax = "proto2";
+package WAWebProtobufsAea;
+option go_package = "go.mau.fi/whatsmeow/proto/waAea";
+
+message NonE2EEAttestation {
+ enum AccountType {
+ E2EE = 0;
+ HYBRID_E2EE = 1;
+ NON_E2EE = 2;
+ }
+
+ optional AccountType accountType = 1;
+}
diff --git a/crates/whatsmeow_proto/proto/waArmadilloApplication/WAArmadilloApplication.proto b/crates/whatsmeow_proto/proto/waArmadilloApplication/WAArmadilloApplication.proto
new file mode 100644
index 0000000000..d9e93c939f
--- /dev/null
+++ b/crates/whatsmeow_proto/proto/waArmadilloApplication/WAArmadilloApplication.proto
@@ -0,0 +1,287 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+syntax = "proto2";
+package WAArmadilloApplication;
+option go_package = "go.mau.fi/whatsmeow/proto/waArmadilloApplication";
+
+import "waArmadilloXMA/WAArmadilloXMA.proto";
+import "waCommon/WACommon.proto";
+
+message Armadillo {
+ message Metadata {
+ }
+
+ message Payload {
+ oneof payload {
+ Content content = 1;
+ ApplicationData applicationData = 2;
+ Signal signal = 3;
+ SubProtocolPayload subProtocol = 4;
+ }
+ }
+
+ message SubProtocolPayload {
+ optional WACommon.FutureProofBehavior futureProof = 1;
+ }
+
+ message Signal {
+ message EncryptedBackupsSecrets {
+ message Epoch {
+ enum EpochStatus {
+ ES_OPEN = 1;
+ ES_CLOSE = 2;
+ }
+
+ optional uint64 ID = 1;
+ optional bytes anonID = 2;
+ optional bytes rootKey = 3;
+ optional EpochStatus status = 4;
+ }
+
+ optional uint64 backupID = 1;
+ optional uint64 serverDataID = 2;
+ repeated Epoch epoch = 3;
+ optional bytes tempOcmfClientState = 4;
+ optional bytes mailboxRootKey = 5;
+ optional bytes obliviousValidationToken = 6;
+ }
+
+ oneof signal {
+ EncryptedBackupsSecrets encryptedBackupsSecrets = 1;
+ }
+ }
+
+ message ApplicationData {
+ message MessageHistoryDocumentMessage {
+ optional WACommon.SubProtocol document = 1;
+ }
+
+ message AIBotResponseMessage {
+ optional string summonToken = 1;
+ optional string messageText = 2;
+ optional string serializedExtras = 3;
+ }
+
+ message MetadataSyncAction {
+ message SyncAttachmentInterventionAction {
+ enum InterventionType {
+ UNKNOWN = 0;
+ NUDE = 1;
+ NOT_NUDE = 2;
+ }
+
+ optional WACommon.MessageKey messageKey = 1;
+ optional InterventionType interventionType = 2;
+ }
+
+ message SyncSpectraAction {
+ enum SpectraActionType {
+ TAKEDOWN = 0;
+ RESTORE = 1;
+ }
+
+ optional WACommon.MessageKey key = 1;
+ optional SpectraActionType actionType = 2;
+ optional int64 takedownActionID = 3;
+ optional string config = 4;
+ }
+
+ message SyncMessageAction {
+ message ActionMessageDelete {
+ }
+
+ oneof action {
+ ActionMessageDelete messageDelete = 101;
+ }
+
+ optional WACommon.MessageKey key = 1;
+ }
+
+ message SyncChatAction {
+ message ActionChatRead {
+ optional SyncActionMessageRange messageRange = 1;
+ optional bool read = 2;
+ }
+
+ message ActionChatDelete {
+ optional SyncActionMessageRange messageRange = 1;
+ }
+
+ message ActionChatArchive {
+ optional SyncActionMessageRange messageRange = 1;
+ optional bool archived = 2;
+ }
+
+ oneof action {
+ ActionChatArchive chatArchive = 101;
+ ActionChatDelete chatDelete = 102;
+ ActionChatRead chatRead = 103;
+ }
+
+ optional string chatID = 1;
+ }
+
+ message SyncActionMessage {
+ optional WACommon.MessageKey key = 1;
+ optional int64 timestamp = 2;
+ }
+
+ message SyncActionMessageRange {
+ optional int64 lastMessageTimestamp = 1;
+ optional int64 lastSystemMessageTimestamp = 2;
+ repeated SyncActionMessage messages = 3;
+ }
+
+ oneof actionType {
+ SyncChatAction chatAction = 101;
+ SyncMessageAction messageAction = 102;
+ SyncSpectraAction spectraAction = 103;
+ SyncAttachmentInterventionAction attachmentInterventionAction = 104;
+ }
+
+ optional int64 actionTimestamp = 1;
+ }
+
+ message MetadataSyncNotification {
+ repeated MetadataSyncAction actions = 2;
+ }
+
+ oneof applicationData {
+ MetadataSyncNotification metadataSync = 1;
+ AIBotResponseMessage aiBotResponse = 2;
+ MessageHistoryDocumentMessage messageHistoryDocumentMessage = 3;
+ }
+ }
+
+ message Content {
+ message PaymentsTransactionMessage {
+ enum PaymentStatus {
+ PAYMENT_UNKNOWN = 0;
+ REQUEST_INITED = 4;
+ REQUEST_DECLINED = 5;
+ REQUEST_TRANSFER_INITED = 6;
+ REQUEST_TRANSFER_COMPLETED = 7;
+ REQUEST_TRANSFER_FAILED = 8;
+ REQUEST_CANCELED = 9;
+ REQUEST_EXPIRED = 10;
+ TRANSFER_INITED = 11;
+ TRANSFER_PENDING = 12;
+ TRANSFER_PENDING_RECIPIENT_VERIFICATION = 13;
+ TRANSFER_CANCELED = 14;
+ TRANSFER_COMPLETED = 15;
+ TRANSFER_NO_RECEIVER_CREDENTIAL_NO_RTS_PENDING_CANCELED = 16;
+ TRANSFER_NO_RECEIVER_CREDENTIAL_NO_RTS_PENDING_OTHER = 17;
+ TRANSFER_REFUNDED = 18;
+ TRANSFER_PARTIAL_REFUND = 19;
+ TRANSFER_CHARGED_BACK = 20;
+ TRANSFER_EXPIRED = 21;
+ TRANSFER_DECLINED = 22;
+ TRANSFER_UNAVAILABLE = 23;
+ }
+
+ optional uint64 transactionID = 1;
+ optional string amount = 2;
+ optional string currency = 3;
+ optional PaymentStatus paymentStatus = 4;
+ optional WAArmadilloXMA.ExtendedContentMessage extendedContentMessage = 5;
+ }
+
+ message NetworkVerificationMessage {
+ optional string codeText = 1;
+ }
+
+ message NoteReplyMessage {
+ oneof noteReplyContent {
+ WACommon.MessageText textContent = 4;
+ WACommon.SubProtocol stickerContent = 5;
+ WACommon.SubProtocol videoContent = 6;
+ }
+
+ optional string noteID = 1;
+ optional WACommon.MessageText noteText = 2;
+ optional int64 noteTimestampMS = 3;
+ }
+
+ message BumpExistingMessage {
+ optional WACommon.MessageKey key = 1;
+ }
+
+ message ImageGalleryMessage {
+ repeated WACommon.SubProtocol images = 1;
+ }
+
+ message ScreenshotAction {
+ enum ScreenshotType {
+ SCREENSHOT_IMAGE = 1;
+ SCREEN_RECORDING = 2;
+ }
+
+ optional ScreenshotType screenshotType = 1;
+ }
+
+ message ExtendedContentMessageWithSear {
+ optional string searID = 1;
+ optional bytes payload = 2;
+ optional string nativeURL = 3;
+ optional WACommon.SubProtocol searAssociatedMessage = 4;
+ optional string searSentWithMessageID = 5;
+ }
+
+ message RavenActionNotifMessage {
+ enum ActionType {
+ PLAYED = 0;
+ SCREENSHOT = 1;
+ FORCE_DISABLE = 2;
+ }
+
+ optional WACommon.MessageKey key = 1;
+ optional int64 actionTimestamp = 2;
+ optional ActionType actionType = 3;
+ }
+
+ message RavenMessage {
+ enum EphemeralType {
+ VIEW_ONCE = 0;
+ ALLOW_REPLAY = 1;
+ KEEP_IN_CHAT = 2;
+ }
+
+ oneof mediaContent {
+ WACommon.SubProtocol imageMessage = 2;
+ WACommon.SubProtocol videoMessage = 3;
+ }
+
+ optional EphemeralType ephemeralType = 1;
+ }
+
+ message CommonSticker {
+ enum StickerType {
+ SMALL_LIKE = 1;
+ MEDIUM_LIKE = 2;
+ LARGE_LIKE = 3;
+ }
+
+ optional StickerType stickerType = 1;
+ }
+
+ oneof content {
+ CommonSticker commonSticker = 1;
+ ScreenshotAction screenshotAction = 3;
+ WAArmadilloXMA.ExtendedContentMessage extendedContentMessage = 4;
+ RavenMessage ravenMessage = 5;
+ RavenActionNotifMessage ravenActionNotifMessage = 6;
+ ExtendedContentMessageWithSear extendedMessageContentWithSear = 7;
+ ImageGalleryMessage imageGalleryMessage = 8;
+ PaymentsTransactionMessage paymentsTransactionMessage = 10;
+ BumpExistingMessage bumpExistingMessage = 11;
+ NoteReplyMessage noteReplyMessage = 13;
+ RavenMessage ravenMessageMsgr = 14;
+ NetworkVerificationMessage networkVerificationMessage = 15;
+ }
+ }
+
+ optional Payload payload = 1;
+ optional Metadata metadata = 2;
+}
diff --git a/crates/whatsmeow_proto/proto/waArmadilloBackupCommon/WAArmadilloBackupCommon.proto b/crates/whatsmeow_proto/proto/waArmadilloBackupCommon/WAArmadilloBackupCommon.proto
new file mode 100644
index 0000000000..16afa964a3
--- /dev/null
+++ b/crates/whatsmeow_proto/proto/waArmadilloBackupCommon/WAArmadilloBackupCommon.proto
@@ -0,0 +1,28 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+syntax = "proto2";
+package WAArmadilloBackupCommon;
+option go_package = "go.mau.fi/whatsmeow/proto/waArmadilloBackupCommon";
+
+message Subprotocol {
+ optional bytes payload = 1;
+ optional int32 version = 2;
+}
+
+message FrankingMetadata {
+ optional bytes frankingTag = 3;
+ optional bytes reportingTag = 4;
+}
+
+message Metadata {
+ optional string senderID = 1;
+ optional string messageID = 2;
+ optional int64 timestampMS = 3;
+ optional FrankingMetadata frankingMetadata = 4;
+ optional int32 payloadVersion = 5;
+ optional int32 futureProofBehavior = 6;
+ optional int32 threadTypeTag = 7;
+ optional int64 clientTimestampMS = 8;
+}
diff --git a/crates/whatsmeow_proto/proto/waArmadilloBackupMessage/WAArmadilloBackupMessage.proto b/crates/whatsmeow_proto/proto/waArmadilloBackupMessage/WAArmadilloBackupMessage.proto
new file mode 100644
index 0000000000..d8d18acab2
--- /dev/null
+++ b/crates/whatsmeow_proto/proto/waArmadilloBackupMessage/WAArmadilloBackupMessage.proto
@@ -0,0 +1,20 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+syntax = "proto2";
+package WAArmadilloBackupMessage;
+option go_package = "go.mau.fi/whatsmeow/proto/waArmadilloBackupMessage";
+
+import "waArmadilloBackupCommon/WAArmadilloBackupCommon.proto";
+
+message BackupMessage {
+ oneof payload {
+ bytes encryptedTransportMessage = 2;
+ WAArmadilloBackupCommon.Subprotocol encryptedTransportEvent = 5;
+ WAArmadilloBackupCommon.Subprotocol encryptedTransportLocallyTransformedMessage = 6;
+ WAArmadilloBackupCommon.Subprotocol miTransportAdminMessage = 7;
+ }
+
+ optional WAArmadilloBackupCommon.Metadata metadata = 1;
+}
diff --git a/crates/whatsmeow_proto/proto/waArmadilloICDC/WAArmadilloICDC.proto b/crates/whatsmeow_proto/proto/waArmadilloICDC/WAArmadilloICDC.proto
new file mode 100644
index 0000000000..160440f3ac
--- /dev/null
+++ b/crates/whatsmeow_proto/proto/waArmadilloICDC/WAArmadilloICDC.proto
@@ -0,0 +1,19 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+syntax = "proto2";
+package WAArmadilloICDC;
+option go_package = "go.mau.fi/whatsmeow/proto/waArmadilloICDC";
+
+message ICDCIdentityList {
+ optional int32 seq = 1;
+ optional int64 timestamp = 2;
+ repeated bytes devices = 3;
+ optional int32 signingDeviceIndex = 4;
+}
+
+message SignedICDCIdentityList {
+ optional bytes details = 1;
+ optional bytes signature = 2;
+}
diff --git a/crates/whatsmeow_proto/proto/waArmadilloMiTransportAdminMessage/WAArmadilloMiTransportAdminMessage.proto b/crates/whatsmeow_proto/proto/waArmadilloMiTransportAdminMessage/WAArmadilloMiTransportAdminMessage.proto
new file mode 100644
index 0000000000..eb267272d3
--- /dev/null
+++ b/crates/whatsmeow_proto/proto/waArmadilloMiTransportAdminMessage/WAArmadilloMiTransportAdminMessage.proto
@@ -0,0 +1,336 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+syntax = "proto2";
+package WAArmadilloMiTransportAdminMessage;
+option go_package = "go.mau.fi/whatsmeow/proto/waArmadilloMiTransportAdminMessage";
+
+message MiTransportAdminMessage {
+ message LimitSharingChanged {
+ enum SharingType {
+ UNSET = 0;
+ DISABLED = 1;
+ ENABLED = 2;
+ }
+
+ optional SharingType sharingType = 1;
+ }
+
+ message GroupImageChanged {
+ enum Action {
+ UNSET = 0;
+ CHANGED = 1;
+ REMOVED = 2;
+ }
+
+ optional Action action = 1;
+ }
+
+ message MessagePinned {
+ enum Action {
+ UNSET = 0;
+ PINNED = 1;
+ UNPINNED = 2;
+ }
+
+ optional Action action = 1;
+ }
+
+ message GroupMembershipAddModeChanged {
+ enum Mode {
+ UNSET = 0;
+ ALL_MEMBERS = 1;
+ ADMINS_ONLY = 2;
+ }
+
+ optional Mode mode = 1;
+ }
+
+ message GroupAdminChanged {
+ enum Action {
+ UNSET = 0;
+ ADDED = 1;
+ REMOVED = 2;
+ }
+
+ repeated string targetUserID = 1;
+ optional Action action = 2;
+ }
+
+ message GroupParticipantChanged {
+ enum Action {
+ UNSET = 0;
+ ADDED = 1;
+ REMOVED = 2;
+ }
+
+ repeated string targetUserID = 1;
+ optional Action action = 2;
+ }
+
+ message XmatMessengerMessageReminderTriggered {
+ optional int64 offlineThreadingID = 1;
+ optional int64 scheduledTime = 2;
+ }
+
+ message XmatMessengerMessageReminderSet {
+ optional int64 offlineThreadingID = 1;
+ optional int64 scheduledTime = 2;
+ }
+
+ message XmatSetParticipantUpdateMode {
+ optional string participantUpdateMode = 1;
+ optional int64 setterID = 2;
+ optional int64 transportThreadFbid = 3;
+ }
+
+ message XmatGroupThreadCreated {
+ optional string threadSubtype = 1;
+ }
+
+ message XmatChangeThreadName {
+ optional string newThreadName = 1;
+ }
+
+ message XmatChangeThreadAdmins {
+ optional string adminEvent = 1;
+ optional int64 targetID = 2;
+ optional string threadCategory = 3;
+ optional string adminType = 4;
+ }
+
+ message XmatRemoveParticipant {
+ optional int64 removedParticipantFbid = 1;
+ }
+
+ message XmatAddParticipants {
+ repeated int64 participantsAdded = 1 [packed=true];
+ optional bool addedThroughJoinRequests = 2;
+ }
+
+ message XmatGenAITaskAdd {
+ optional int64 taskID = 1;
+ }
+
+ message XmatUnpinMessageV2 {
+ optional string pinnedMessageID = 1;
+ }
+
+ message XmatPinMessageV2 {
+ optional string pinnedMessageID = 1;
+ }
+
+ message XmatUpdatePayments {
+ optional string receiverName = 1;
+ optional string senderName = 2;
+ optional float amount = 3;
+ optional int64 transactionID = 4;
+ optional int32 transactionStatus = 5;
+ }
+
+ message XmatThreadQuickReaction {
+ optional string threadQuickReactionEmoji = 1;
+ optional string threadQuickReactionInstructionKeyID = 2;
+ }
+
+ message XmatThreadNickname {
+ optional int64 participantID = 1;
+ optional string nickname = 2;
+ }
+
+ message XmatThreadIcon {
+ optional string threadIcon = 1;
+ }
+
+ message XmatThemeColor {
+ optional string themeID = 1;
+ optional string themeColor = 2;
+ repeated string gradient = 3;
+ optional bool shouldShowIcon = 4;
+ optional int32 themeType = 5;
+ optional string accessibilityLabel = 6;
+ optional string themeNameWithSubtitle = 7;
+ optional string themeEmoji = 8;
+ }
+
+ message XmatMessengerSharedAlbum {
+ optional string xmaDataclass = 1;
+ }
+
+ message XmatMessengerSharedAlbumRename {
+ optional int64 sharedAlbumID = 1;
+ optional string oldAlbumTitle = 2;
+ optional string newAlbumTitle = 3;
+ }
+
+ message XmatMessengerSharedAlbumDeletion {
+ optional int64 sharedAlbumID = 1;
+ optional string albumTitle = 2;
+ }
+
+ message XmatMessengerSharedAlbumContentRemoval {
+ message RemovedContentTuple {
+ optional int64 key = 1;
+ optional string value = 2;
+ }
+
+ optional int64 sharedAlbumID = 1;
+ repeated RemovedContentTuple removedContentMap = 2;
+ optional int64 removedContentCount = 3;
+ optional string albumTitle = 4;
+ }
+
+ message XmatMessengerSharedAlbumAddition {
+ optional int64 sharedAlbumID = 1;
+ optional string albumTitle = 2;
+ optional int64 numOfAttachments = 3;
+ optional bool isAlbumCreation = 4;
+ }
+
+ message XmatMessengerQRCodeScanned {
+ optional string receiverName = 1;
+ optional string senderName = 2;
+ }
+
+ message XmatMessagingLimitSharing {
+ optional string senderName = 1;
+ optional string senderID = 2;
+ optional string limitSharingType = 3;
+ }
+
+ message XmatMagicWords {
+ optional int64 newMagicWordCount = 1;
+ optional int64 removedMagicWordCount = 2;
+ optional string magicWord = 3;
+ optional string emojiEffect = 4;
+ optional bool isAllEdited = 5;
+ optional string themeName = 6;
+ }
+
+ message XmatLinkCTA {
+ optional string linkCtaXmatPrimaryText = 1;
+ optional string linkCtaXmatCtaText = 2;
+ optional string linkCtaXmatCtaURL = 3;
+ optional string linkCtaXmatCtaIosURL = 4;
+ optional string androidUri = 5;
+ optional string asyncURL = 6;
+ optional bool wwwIsAsyncURL = 7;
+ optional bool msiteEnabled = 8;
+ optional bool hideUriInFallback = 9;
+ optional bool showConfirmationDialog = 10;
+ optional string graphPayload = 11;
+ optional string identifierName = 12;
+ optional string threadID = 13;
+ optional bool hideCtaInFallback = 14;
+ optional string ctxAdConversationStarterInfo = 15;
+ optional string fbmUri = 16;
+ optional string initiatorUserID = 17;
+ }
+
+ message XmatInstantGameEncryptedDynamicCustomUpdate {
+ optional string senderName = 1;
+ optional string muteManagementAdminTextType = 2;
+ optional string gameName = 3;
+ }
+
+ message XmatFriendRequestConfirmedEncrypted {
+ optional string otherUserName = 1;
+ optional string isTurnOnCohort = 2;
+ optional string userWhoAcceptedFriendRequest = 3;
+ }
+
+ message XmatDisappearingSetting {
+ optional int64 disappearingSettingTime = 1;
+ optional int64 oldDisappearingSettingTime = 2;
+ optional int64 disappearingSettingActorFbid = 3;
+ optional int64 newEphemeralityType = 4;
+ optional int64 oldEphemeralityType = 5;
+ }
+
+ message DisappearingSettingChanged {
+ optional int32 disappearingSettingDurationSeconds = 1;
+ optional int32 oldDisappearingSettingDurationSeconds = 2;
+ }
+
+ message IconChanged {
+ optional string threadIcon = 1;
+ }
+
+ message LinkCta {
+ message UkOsaAdminText {
+ optional string initiatorUserID = 2;
+ }
+
+ oneof content {
+ UkOsaAdminText ukOsaAdminText = 1;
+ }
+ }
+
+ message QuickReactionChanged {
+ optional string emojiName = 1;
+ }
+
+ message GroupNameChanged {
+ optional string groupName = 1;
+ }
+
+ message NicknameChanged {
+ optional string targetUserID = 1;
+ optional string nickname = 2;
+ }
+
+ message ChatThemeChanged {
+ optional string themeName = 1;
+ optional string themeEmoji = 2;
+ optional int32 themeType = 3;
+ }
+
+ oneof content {
+ ChatThemeChanged chatThemeChanged = 1;
+ NicknameChanged nicknameChanged = 2;
+ GroupParticipantChanged groupParticipantChanged = 3;
+ GroupAdminChanged groupAdminChanged = 4;
+ GroupNameChanged groupNameChanged = 5;
+ GroupMembershipAddModeChanged groupMembershipAddModeChanged = 6;
+ MessagePinned messagePinned = 7;
+ GroupImageChanged groupImageChanged = 8;
+ QuickReactionChanged quickReactionChanged = 9;
+ LinkCta linkCta = 10;
+ IconChanged iconChanged = 11;
+ DisappearingSettingChanged disappearingSettingChanged = 12;
+ LimitSharingChanged limitSharingChanged = 13;
+ XmatDisappearingSetting xmatDisappearingSetting = 14;
+ XmatFriendRequestConfirmedEncrypted xmatFriendRequestConfirmedEncrypted = 15;
+ XmatInstantGameEncryptedDynamicCustomUpdate xmatInstantGameEncryptedDynamicCustomUpdate = 16;
+ XmatLinkCTA xmatLinkCta = 17;
+ XmatMagicWords xmatMagicWords = 18;
+ XmatMessagingLimitSharing xmatMessagingLimitSharing = 19;
+ XmatMessengerQRCodeScanned xmatMessengerQrCodeScanned = 20;
+ XmatMessengerSharedAlbumAddition xmatMessengerSharedAlbumAddition = 21;
+ XmatMessengerSharedAlbumContentRemoval xmatMessengerSharedAlbumContentRemoval = 22;
+ XmatMessengerSharedAlbumDeletion xmatMessengerSharedAlbumDeletion = 23;
+ XmatMessengerSharedAlbumRename xmatMessengerSharedAlbumRename = 24;
+ XmatMessengerSharedAlbum xmatMessengerSharedAlbum = 25;
+ XmatThemeColor xmatThemeColor = 26;
+ XmatThreadIcon xmatThreadIcon = 27;
+ XmatThreadNickname xmatThreadNickname = 28;
+ XmatThreadQuickReaction xmatThreadQuickReaction = 29;
+ XmatUpdatePayments xmatUpdatePayments = 30;
+ XmatPinMessageV2 xmatPinMessageV2 = 31;
+ XmatUnpinMessageV2 xmatUnpinMessageV2 = 32;
+ XmatGenAITaskAdd xmatGenaiTaskAdd = 33;
+ XmatAddParticipants xmatAddParticipants = 37;
+ XmatRemoveParticipant xmatRemoveParticipant = 38;
+ XmatChangeThreadAdmins xmatChangeThreadAdmins = 39;
+ XmatChangeThreadName xmatChangeThreadName = 40;
+ XmatGroupThreadCreated xmatGroupThreadCreated = 41;
+ XmatSetParticipantUpdateMode xmatSetParticipantUpdateMode = 42;
+ XmatMessengerMessageReminderSet xmatMessengerMessageReminderSet = 43;
+ XmatMessengerMessageReminderTriggered xmatMessengerMessageReminderTriggered = 44;
+ }
+
+ optional bool skipBumpThread = 34;
+ optional bool skipSnippetUpdate = 35;
+ optional string readonlyMetadataDataclass = 36;
+}
diff --git a/crates/whatsmeow_proto/proto/waArmadilloTransportEvent/WAArmadilloTransportEvent.proto b/crates/whatsmeow_proto/proto/waArmadilloTransportEvent/WAArmadilloTransportEvent.proto
new file mode 100644
index 0000000000..41a51d7711
--- /dev/null
+++ b/crates/whatsmeow_proto/proto/waArmadilloTransportEvent/WAArmadilloTransportEvent.proto
@@ -0,0 +1,54 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+syntax = "proto2";
+package WAArmadilloTransportEvent;
+option go_package = "go.mau.fi/whatsmeow/proto/waArmadilloTransportEvent";
+
+message TransportEvent {
+ message Event {
+ message IcdcAlert {
+ enum Type {
+ NONE = 0;
+ DETECTED = 1;
+ CLEARED = 2;
+ }
+
+ optional Type type = 1;
+ }
+
+ message DeviceChange {
+ enum Type {
+ NONE = 0;
+ ADDED = 1;
+ REMOVED = 2;
+ REPLACED = 3;
+ }
+
+ optional Type type = 1;
+ optional string deviceName = 2;
+ optional string devicePlatform = 3;
+ optional string deviceModel = 4;
+ }
+
+ oneof event {
+ DeviceChange deviceChange = 1;
+ IcdcAlert icdcAlert = 2;
+ }
+ }
+
+ message Placeholder {
+ enum Type {
+ DECRYPTION_FAILURE = 1;
+ UNAVAILABLE_MESSAGE = 2;
+ }
+
+ optional Type type = 1;
+ }
+
+ oneof content {
+ Placeholder placeholder = 1;
+ Event event = 2;
+ }
+}
diff --git a/crates/whatsmeow_proto/proto/waArmadilloXMA/WAArmadilloXMA.proto b/crates/whatsmeow_proto/proto/waArmadilloXMA/WAArmadilloXMA.proto
new file mode 100644
index 0000000000..8ecfc31246
--- /dev/null
+++ b/crates/whatsmeow_proto/proto/waArmadilloXMA/WAArmadilloXMA.proto
@@ -0,0 +1,176 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+syntax = "proto2";
+package WAArmadilloXMA;
+option go_package = "go.mau.fi/whatsmeow/proto/waArmadilloXMA";
+
+import "waCommon/WACommon.proto";
+
+message ExtendedContentMessage {
+ enum XmaDataclassType {
+ SENDER_COPY = 0;
+ SERVER = 1;
+ SIGNED_CLIENT = 2;
+ }
+
+ enum OverlayIconGlyph {
+ INFO = 0;
+ EYE_OFF = 1;
+ NEWS_OFF = 2;
+ WARNING = 3;
+ PRIVATE = 4;
+ NONE = 5;
+ MEDIA_LABEL = 6;
+ POST_COVER = 7;
+ POST_LABEL = 8;
+ WARNING_SCREENS = 9;
+ }
+
+ enum CtaButtonType {
+ OPEN_NATIVE = 11;
+ }
+
+ enum XmaLayoutType {
+ SINGLE = 0;
+ HSCROLL = 1;
+ PORTRAIT = 3;
+ STANDARD_DXMA = 12;
+ LIST_DXMA = 15;
+ GRID = 16;
+ }
+
+ enum ExtendedContentType {
+ UNSUPPORTED = 0;
+ IG_STORY_PHOTO_MENTION = 4;
+ IG_SINGLE_IMAGE_POST_SHARE = 9;
+ IG_MULTIPOST_SHARE = 10;
+ IG_SINGLE_VIDEO_POST_SHARE = 11;
+ IG_STORY_PHOTO_SHARE = 12;
+ IG_STORY_VIDEO_SHARE = 13;
+ IG_CLIPS_SHARE = 14;
+ IG_IGTV_SHARE = 15;
+ IG_SHOP_SHARE = 16;
+ IG_PROFILE_SHARE = 19;
+ IG_STORY_PHOTO_HIGHLIGHT_SHARE = 20;
+ IG_STORY_VIDEO_HIGHLIGHT_SHARE = 21;
+ IG_STORY_REPLY = 22;
+ IG_STORY_REACTION = 23;
+ IG_STORY_VIDEO_MENTION = 24;
+ IG_STORY_HIGHLIGHT_REPLY = 25;
+ IG_STORY_HIGHLIGHT_REACTION = 26;
+ IG_EXTERNAL_LINK = 27;
+ IG_RECEIVER_FETCH = 28;
+ FB_FEED_SHARE = 1000;
+ FB_STORY_REPLY = 1001;
+ FB_STORY_SHARE = 1002;
+ FB_STORY_MENTION = 1003;
+ FB_FEED_VIDEO_SHARE = 1004;
+ FB_GAMING_CUSTOM_UPDATE = 1005;
+ FB_PRODUCER_STORY_REPLY = 1006;
+ FB_EVENT = 1007;
+ FB_FEED_POST_PRIVATE_REPLY = 1008;
+ FB_SHORT = 1009;
+ FB_COMMENT_MENTION_SHARE = 1010;
+ FB_POST_MENTION = 1011;
+ FB_PROFILE_DIRECTORY_ITEM = 1013;
+ FB_FEED_POST_REACTION_REPLY = 1014;
+ FB_QUICKSNAP_REPLY = 1015;
+ MSG_STATUS_REPLY = 1016;
+ FB_GROUP_POST = 1017;
+ FB_DAILY_GAME_CHALLENGE = 1018;
+ FB_QUICKSNAP_REACTION_REPLY = 1019;
+ MSG_EXTERNAL_LINK_SHARE = 2000;
+ MSG_P2P_PAYMENT = 2001;
+ MSG_LOCATION_SHARING = 2002;
+ MSG_LOCATION_SHARING_V2 = 2003;
+ MSG_HIGHLIGHTS_TAB_FRIEND_UPDATES_REPLY = 2004;
+ MSG_HIGHLIGHTS_TAB_LOCAL_EVENT_REPLY = 2005;
+ MSG_RECEIVER_FETCH = 2006;
+ MSG_IG_MEDIA_SHARE = 2007;
+ MSG_GEN_AI_SEARCH_PLUGIN_RESPONSE = 2008;
+ MSG_REELS_LIST = 2009;
+ MSG_CONTACT = 2010;
+ MSG_THREADS_POST_SHARE = 2011;
+ MSG_FILE = 2012;
+ MSG_AVATAR_DETAILS = 2013;
+ MSG_AI_CONTACT = 2014;
+ MSG_MEMORIES_SHARE = 2015;
+ MSG_SHARED_ALBUM_REPLY = 2016;
+ MSG_SHARED_ALBUM = 2017;
+ MSG_OCCAMADILLO_XMA = 2018;
+ MSG_GEN_AI_SUBSCRIPTION = 2021;
+ MSG_GEN_AI_REMINDER = 2022;
+ MSG_GEN_AI_MEMU_ONBOARDING_RESPONSE = 2023;
+ MSG_NOTE_REPLY = 2024;
+ MSG_NOTE_MENTION = 2025;
+ GEN_AI_ENTITY = 2026;
+ MSG_OPG_P2P_PAYMENT = 2027;
+ GEN_AI_RICH_RESPONSE = 2028;
+ MSG_MUSIC_STICKER = 2029;
+ MSG_PHONE_NUMBER = 2030;
+ AI_ACTIVITY_SHARE = 2031;
+ MSG_PRIVATE_XMA = 2032;
+ MSG_SOCIAL_CUE_MEMORIES = 2033;
+ MSG_MANUS_GROWTH_REFERRAL = 2060;
+ MSG_MOMENT_LINK = 2061;
+ MSG_HORIZON_WEEL = 2062;
+ MSG_MOMENT_ADDED = 2063;
+ MSG_STORYTELLING_PROMPT = 2067;
+ MSG_SUPERVISION_INVITE = 2068;
+ MSG_SOCIAL_CUE_MLE = 2069;
+ MSG_SOCIAL_CUE_POST = 2070;
+ RTC_AUDIO_CALL = 3000;
+ RTC_VIDEO_CALL = 3001;
+ RTC_MISSED_AUDIO_CALL = 3002;
+ RTC_MISSED_VIDEO_CALL = 3003;
+ RTC_GROUP_AUDIO_CALL = 3004;
+ RTC_GROUP_VIDEO_CALL = 3005;
+ RTC_MISSED_GROUP_AUDIO_CALL = 3006;
+ RTC_MISSED_GROUP_VIDEO_CALL = 3007;
+ RTC_ONGOING_AUDIO_CALL = 3008;
+ RTC_ONGOING_VIDEO_CALL = 3009;
+ MSG_RECEIVER_FETCH_FALLBACK = 3025;
+ DATACLASS_SENDER_COPY = 4000;
+ }
+
+ message CTA {
+ optional CtaButtonType buttonType = 1;
+ optional string title = 2;
+ optional string actionURL = 3;
+ optional string nativeURL = 4;
+ optional string ctaType = 5;
+ optional string actionContentBlob = 6;
+ }
+
+ optional WACommon.SubProtocol associatedMessage = 1;
+ optional ExtendedContentType targetType = 2;
+ optional string targetUsername = 3;
+ optional string targetID = 4;
+ optional int64 targetExpiringAtSec = 5;
+ optional XmaLayoutType xmaLayoutType = 6;
+ repeated CTA ctas = 7;
+ repeated WACommon.SubProtocol previews = 8;
+ optional string titleText = 9;
+ optional string subtitleText = 10;
+ optional uint32 maxTitleNumOfLines = 11;
+ optional uint32 maxSubtitleNumOfLines = 12;
+ optional WACommon.SubProtocol favicon = 13;
+ optional WACommon.SubProtocol headerImage = 14;
+ optional string headerTitle = 15;
+ optional OverlayIconGlyph overlayIconGlyph = 16;
+ optional string overlayTitle = 17;
+ optional string overlayDescription = 18;
+ optional string sentWithMessageID = 19;
+ optional string messageText = 20;
+ optional string headerSubtitle = 21;
+ optional string xmaDataclass = 22;
+ optional string contentRef = 23;
+ repeated string mentionedJID = 24;
+ repeated WACommon.Command commands = 25;
+ repeated WACommon.Mention mentions = 26;
+ optional XmaDataclassType xmaDataclassType = 27;
+ optional string signedXmaDataclassValidation = 28;
+ optional string featureSharedSessionID = 29;
+}
diff --git a/crates/whatsmeow_proto/proto/waBotMetadata/WABotMetadata.proto b/crates/whatsmeow_proto/proto/waBotMetadata/WABotMetadata.proto
new file mode 100644
index 0000000000..34f567864d
--- /dev/null
+++ b/crates/whatsmeow_proto/proto/waBotMetadata/WABotMetadata.proto
@@ -0,0 +1,531 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+syntax = "proto2";
+package WABotMetadata;
+option go_package = "go.mau.fi/whatsmeow/proto/waBotMetadata";
+
+import "waCommon/WACommon.proto";
+
+enum BotMetricsEntryPoint {
+ FAVICON = 1;
+ CHATLIST = 2;
+ AISEARCH_NULL_STATE_PAPER_PLANE = 3;
+ AISEARCH_NULL_STATE_SUGGESTION = 4;
+ AISEARCH_TYPE_AHEAD_SUGGESTION = 5;
+ AISEARCH_TYPE_AHEAD_PAPER_PLANE = 6;
+ AISEARCH_TYPE_AHEAD_RESULT_CHATLIST = 7;
+ AISEARCH_TYPE_AHEAD_RESULT_MESSAGES = 8;
+ AIVOICE_SEARCH_BAR = 9;
+ AIVOICE_FAVICON = 10;
+ AISTUDIO = 11;
+ DEEPLINK = 12;
+ NOTIFICATION = 13;
+ PROFILE_MESSAGE_BUTTON = 14;
+ FORWARD = 15;
+ APP_SHORTCUT = 16;
+ FF_FAMILY = 17;
+ AI_TAB = 18;
+ AI_HOME = 19;
+ AI_DEEPLINK_IMMERSIVE = 20;
+ AI_DEEPLINK = 21;
+ META_AI_CHAT_SHORTCUT_AI_STUDIO = 22;
+ UGC_CHAT_SHORTCUT_AI_STUDIO = 23;
+ NEW_CHAT_AI_STUDIO = 24;
+ AIVOICE_FAVICON_CALL_HISTORY = 25;
+ ASK_META_AI_CONTEXT_MENU = 26;
+ ASK_META_AI_CONTEXT_MENU_1ON1 = 27;
+ ASK_META_AI_CONTEXT_MENU_GROUP = 28;
+ INVOKE_META_AI_1ON1 = 29;
+ INVOKE_META_AI_GROUP = 30;
+ META_AI_FORWARD = 31;
+ NEW_CHAT_AI_CONTACT = 32;
+}
+
+enum BotMetricsThreadEntryPoint {
+ AI_TAB_THREAD = 1;
+ AI_HOME_THREAD = 2;
+ AI_DEEPLINK_IMMERSIVE_THREAD = 3;
+ AI_DEEPLINK_THREAD = 4;
+ ASK_META_AI_CONTEXT_MENU_THREAD = 5;
+}
+
+enum BotSessionSource {
+ NONE = 0;
+ NULL_STATE = 1;
+ TYPEAHEAD = 2;
+ USER_INPUT = 3;
+ EMU_FLASH = 4;
+ EMU_FLASH_FOLLOWUP = 5;
+ VOICE = 6;
+}
+
+message BotPluginMetadata {
+ enum PluginType {
+ UNKNOWN_PLUGIN = 0;
+ REELS = 1;
+ SEARCH = 2;
+ }
+
+ enum SearchProvider {
+ UNKNOWN = 0;
+ BING = 1;
+ GOOGLE = 2;
+ SUPPORT = 3;
+ }
+
+ optional SearchProvider provider = 1;
+ optional PluginType pluginType = 2;
+ optional string thumbnailCDNURL = 3;
+ optional string profilePhotoCDNURL = 4;
+ optional string searchProviderURL = 5;
+ optional uint32 referenceIndex = 6;
+ optional uint32 expectedLinksCount = 7;
+ optional string searchQuery = 9;
+ optional WACommon.MessageKey parentPluginMessageKey = 10;
+ optional PluginType deprecatedField = 11;
+ optional PluginType parentPluginType = 12;
+ optional string faviconCDNURL = 13;
+}
+
+message BotLinkedAccount {
+ enum BotLinkedAccountType {
+ BOT_LINKED_ACCOUNT_TYPE_1P = 0;
+ }
+
+ optional BotLinkedAccountType type = 1;
+}
+
+message BotSignatureVerificationUseCaseProof {
+ enum BotSignatureUseCase {
+ WA_BOT_MSG = 0;
+ }
+
+ optional int32 version = 1;
+ optional BotSignatureUseCase useCase = 2;
+ optional bytes signature = 3;
+ optional bytes certificateChain = 4;
+}
+
+message BotPromotionMessageMetadata {
+ enum BotPromotionType {
+ UNKNOWN_TYPE = 0;
+ C50 = 1;
+ SURVEY_PLATFORM = 2;
+ }
+
+ optional BotPromotionType promotionType = 1;
+ optional string buttonTitle = 2;
+}
+
+message BotMediaMetadata {
+ enum OrientationType {
+ CENTER = 1;
+ LEFT = 2;
+ RIGHT = 3;
+ }
+
+ optional string fileSHA256 = 1;
+ optional string mediaKey = 2;
+ optional string fileEncSHA256 = 3;
+ optional string directPath = 4;
+ optional int64 mediaKeyTimestamp = 5;
+ optional string mimetype = 6;
+ optional OrientationType orientationType = 7;
+}
+
+message BotReminderMetadata {
+ enum ReminderFrequency {
+ ONCE = 1;
+ DAILY = 2;
+ WEEKLY = 3;
+ BIWEEKLY = 4;
+ MONTHLY = 5;
+ }
+
+ enum ReminderAction {
+ NOTIFY = 1;
+ CREATE = 2;
+ DELETE = 3;
+ UPDATE = 4;
+ }
+
+ optional WACommon.MessageKey requestMessageKey = 1;
+ optional ReminderAction action = 2;
+ optional string name = 3;
+ optional uint64 nextTriggerTimestamp = 4;
+ optional ReminderFrequency frequency = 5;
+}
+
+message BotModelMetadata {
+ enum PremiumModelStatus {
+ UNKNOWN_STATUS = 0;
+ AVAILABLE = 1;
+ QUOTA_EXCEED_LIMIT = 2;
+ }
+
+ enum ModelType {
+ UNKNOWN_TYPE = 0;
+ LLAMA_PROD = 1;
+ LLAMA_PROD_PREMIUM = 2;
+ }
+
+ optional ModelType modelType = 1;
+ optional PremiumModelStatus premiumModelStatus = 2;
+}
+
+message BotProgressIndicatorMetadata {
+ message BotPlanningStepMetadata {
+ enum BotSearchSourceProvider {
+ UNKNOWN_PROVIDER = 0;
+ OTHER = 1;
+ GOOGLE = 2;
+ BING = 3;
+ }
+
+ enum PlanningStepStatus {
+ UNKNOWN = 0;
+ PLANNED = 1;
+ EXECUTING = 2;
+ FINISHED = 3;
+ }
+
+ message BotPlanningSearchSourcesMetadata {
+ enum BotPlanningSearchSourceProvider {
+ UNKNOWN = 0;
+ OTHER = 1;
+ GOOGLE = 2;
+ BING = 3;
+ }
+
+ optional string sourceTitle = 1;
+ optional BotPlanningSearchSourceProvider provider = 2;
+ optional string sourceURL = 3;
+ }
+
+ message BotPlanningStepSectionMetadata {
+ optional string sectionTitle = 1;
+ optional string sectionBody = 2;
+ repeated BotPlanningSearchSourceMetadata sourcesMetadata = 3;
+ }
+
+ message BotPlanningSearchSourceMetadata {
+ optional string title = 1;
+ optional BotSearchSourceProvider provider = 2;
+ optional string sourceURL = 3;
+ optional string favIconURL = 4;
+ }
+
+ optional string statusTitle = 1;
+ optional string statusBody = 2;
+ repeated BotPlanningSearchSourcesMetadata sourcesMetadata = 3;
+ optional PlanningStepStatus status = 4;
+ optional bool isReasoning = 5;
+ optional bool isEnhancedSearch = 6;
+ repeated BotPlanningStepSectionMetadata sections = 7;
+ }
+
+ optional string progressDescription = 1;
+ repeated BotPlanningStepMetadata stepsMetadata = 2;
+}
+
+message BotCapabilityMetadata {
+ enum BotCapabilityType {
+ UNKNOWN = 0;
+ PROGRESS_INDICATOR = 1;
+ RICH_RESPONSE_HEADING = 2;
+ RICH_RESPONSE_NESTED_LIST = 3;
+ AI_MEMORY = 4;
+ RICH_RESPONSE_THREAD_SURFING = 5;
+ RICH_RESPONSE_TABLE = 6;
+ RICH_RESPONSE_CODE = 7;
+ RICH_RESPONSE_STRUCTURED_RESPONSE = 8;
+ RICH_RESPONSE_INLINE_IMAGE = 9;
+ WA_IG_1P_PLUGIN_RANKING_CONTROL = 10;
+ WA_IG_1P_PLUGIN_RANKING_UPDATE_1 = 11;
+ WA_IG_1P_PLUGIN_RANKING_UPDATE_2 = 12;
+ WA_IG_1P_PLUGIN_RANKING_UPDATE_3 = 13;
+ WA_IG_1P_PLUGIN_RANKING_UPDATE_4 = 14;
+ WA_IG_1P_PLUGIN_RANKING_UPDATE_5 = 15;
+ WA_IG_1P_PLUGIN_RANKING_UPDATE_6 = 16;
+ WA_IG_1P_PLUGIN_RANKING_UPDATE_7 = 17;
+ WA_IG_1P_PLUGIN_RANKING_UPDATE_8 = 18;
+ WA_IG_1P_PLUGIN_RANKING_UPDATE_9 = 19;
+ WA_IG_1P_PLUGIN_RANKING_UPDATE_10 = 20;
+ RICH_RESPONSE_SUB_HEADING = 21;
+ RICH_RESPONSE_GRID_IMAGE = 22;
+ AI_STUDIO_UGC_MEMORY = 23;
+ RICH_RESPONSE_LATEX = 24;
+ RICH_RESPONSE_MAPS = 25;
+ RICH_RESPONSE_INLINE_REELS = 26;
+ AGENTIC_PLANNING = 27;
+ ACCOUNT_LINKING = 28;
+ STREAMING_DISAGGREGATION = 29;
+ RICH_RESPONSE_GRID_IMAGE_3P = 30;
+ RICH_RESPONSE_LATEX_INLINE = 31;
+ QUERY_PLAN = 32;
+ PROACTIVE_MESSAGE = 33;
+ RICH_RESPONSE_UNIFIED_RESPONSE = 34;
+ PROMOTION_MESSAGE = 35;
+ SIMPLIFIED_PROFILE_PAGE = 36;
+ RICH_RESPONSE_SOURCES_IN_MESSAGE = 37;
+ RICH_RESPONSE_SIDE_BY_SIDE_SURVEY = 38;
+ RICH_RESPONSE_UNIFIED_TEXT_COMPONENT = 39;
+ AI_SHARED_MEMORY = 40;
+ RICH_RESPONSE_UNIFIED_SOURCES = 41;
+ RICH_RESPONSE_UNIFIED_DOMAIN_CITATIONS = 42;
+ }
+
+ repeated BotCapabilityType capabilities = 1;
+}
+
+message BotModeSelectionMetadata {
+ enum BotUserSelectionMode {
+ UNKNOWN_MODE = 0;
+ REASONING_MODE = 1;
+ }
+
+ repeated BotUserSelectionMode mode = 1;
+}
+
+message BotQuotaMetadata {
+ message BotFeatureQuotaMetadata {
+ enum BotFeatureType {
+ UNKNOWN_FEATURE = 0;
+ REASONING_FEATURE = 1;
+ }
+
+ optional BotFeatureType featureType = 1;
+ optional uint32 remainingQuota = 2;
+ optional uint64 expirationTimestamp = 3;
+ }
+
+ repeated BotFeatureQuotaMetadata botFeatureQuotaMetadata = 1;
+}
+
+message BotImagineMetadata {
+ enum ImagineType {
+ UNKNOWN = 0;
+ IMAGINE = 1;
+ MEMU = 2;
+ FLASH = 3;
+ EDIT = 4;
+ }
+
+ optional ImagineType imagineType = 1;
+}
+
+message BotSourcesMetadata {
+ message BotSourceItem {
+ enum SourceProvider {
+ UNKNOWN = 0;
+ BING = 1;
+ GOOGLE = 2;
+ SUPPORT = 3;
+ OTHER = 4;
+ }
+
+ optional SourceProvider provider = 1;
+ optional string thumbnailCDNURL = 2;
+ optional string sourceProviderURL = 3;
+ optional string sourceQuery = 4;
+ optional string faviconCDNURL = 5;
+ optional uint32 citationNumber = 6;
+ optional string sourceTitle = 7;
+ }
+
+ repeated BotSourceItem sources = 1;
+}
+
+message BotMessageOrigin {
+ enum BotMessageOriginType {
+ BOT_MESSAGE_ORIGIN_TYPE_AI_INITIATED = 0;
+ }
+
+ optional BotMessageOriginType type = 1;
+}
+
+message AIThreadInfo {
+ message AIThreadClientInfo {
+ enum AIThreadType {
+ UNKNOWN = 0;
+ DEFAULT = 1;
+ INCOGNITO = 2;
+ }
+
+ optional AIThreadType type = 1;
+ }
+
+ message AIThreadServerInfo {
+ optional string title = 1;
+ }
+
+ optional AIThreadServerInfo serverInfo = 1;
+ optional AIThreadClientInfo clientInfo = 2;
+}
+
+message BotAvatarMetadata {
+ optional uint32 sentiment = 1;
+ optional string behaviorGraph = 2;
+ optional uint32 action = 3;
+ optional uint32 intensity = 4;
+ optional uint32 wordCount = 5;
+}
+
+message BotSuggestedPromptMetadata {
+ repeated string suggestedPrompts = 1;
+ optional uint32 selectedPromptIndex = 2;
+ optional BotPromptSuggestions promptSuggestions = 3;
+ optional string selectedPromptID = 4;
+}
+
+message BotPromptSuggestions {
+ repeated BotPromptSuggestion suggestions = 1;
+}
+
+message BotPromptSuggestion {
+ optional string prompt = 1;
+ optional string promptID = 2;
+}
+
+message BotLinkedAccountsMetadata {
+ repeated BotLinkedAccount accounts = 1;
+ optional bytes acAuthTokens = 2;
+ optional int32 acErrorCode = 3;
+}
+
+message BotMemoryMetadata {
+ repeated BotMemoryFact addedFacts = 1;
+ repeated BotMemoryFact removedFacts = 2;
+ optional string disclaimer = 3;
+}
+
+message BotMemoryFact {
+ optional string fact = 1;
+ optional string factID = 2;
+}
+
+message BotSignatureVerificationMetadata {
+ repeated BotSignatureVerificationUseCaseProof proofs = 1;
+}
+
+message BotRenderingMetadata {
+ message Keyword {
+ optional string value = 1;
+ repeated string associatedPrompts = 2;
+ }
+
+ repeated Keyword keywords = 1;
+}
+
+message BotMetricsMetadata {
+ optional string destinationID = 1;
+ optional BotMetricsEntryPoint destinationEntryPoint = 2;
+ optional BotMetricsThreadEntryPoint threadOrigin = 3;
+}
+
+message BotSessionMetadata {
+ optional string sessionID = 1;
+ optional BotSessionSource sessionSource = 2;
+}
+
+message BotMemuMetadata {
+ repeated BotMediaMetadata faceImages = 1;
+}
+
+message BotAgeCollectionMetadata {
+ optional bool ageCollectionEligible = 1;
+ optional bool shouldTriggerAgeCollectionOnClient = 2;
+}
+
+message InThreadSurveyMetadata {
+ message InThreadSurveyPrivacyStatementPart {
+ optional string text = 1;
+ optional string URL = 2;
+ }
+
+ message InThreadSurveyOption {
+ optional string stringValue = 1;
+ optional uint32 numericValue = 2;
+ optional string textTranslated = 3;
+ }
+
+ message InThreadSurveyQuestion {
+ optional string questionText = 1;
+ optional string questionID = 2;
+ repeated InThreadSurveyOption questionOptions = 3;
+ }
+
+ optional string tessaSessionID = 1;
+ optional string simonSessionID = 2;
+ optional string simonSurveyID = 3;
+ optional string tessaRootID = 4;
+ optional string requestID = 5;
+ optional string tessaEvent = 6;
+ optional string invitationHeaderText = 7;
+ optional string invitationBodyText = 8;
+ optional string invitationCtaText = 9;
+ optional string invitationCtaURL = 10;
+ optional string surveyTitle = 11;
+ repeated InThreadSurveyQuestion questions = 12;
+ optional string surveyContinueButtonText = 13;
+ optional string surveySubmitButtonText = 14;
+ optional string privacyStatementFull = 15;
+ repeated InThreadSurveyPrivacyStatementPart privacyStatementParts = 16;
+ optional string feedbackToastText = 17;
+}
+
+message BotMessageOriginMetadata {
+ repeated BotMessageOrigin origins = 1;
+}
+
+message BotUnifiedResponseMutation {
+ message MediaDetailsMetadata {
+ optional string ID = 1;
+ optional BotMediaMetadata highResMedia = 2;
+ optional BotMediaMetadata previewMedia = 3;
+ }
+
+ message SideBySideMetadata {
+ optional string primaryResponseID = 1;
+ }
+
+ optional SideBySideMetadata sbsMetadata = 1;
+ repeated MediaDetailsMetadata mediaDetailsMetadataList = 2;
+}
+
+message BotMetadata {
+ optional BotAvatarMetadata avatarMetadata = 1;
+ optional string personaID = 2;
+ optional BotPluginMetadata pluginMetadata = 3;
+ optional BotSuggestedPromptMetadata suggestedPromptMetadata = 4;
+ optional string invokerJID = 5;
+ optional BotSessionMetadata sessionMetadata = 6;
+ optional BotMemuMetadata memuMetadata = 7;
+ optional string timezone = 8;
+ optional BotReminderMetadata reminderMetadata = 9;
+ optional BotModelMetadata modelMetadata = 10;
+ optional string messageDisclaimerText = 11;
+ optional BotProgressIndicatorMetadata progressIndicatorMetadata = 12;
+ optional BotCapabilityMetadata capabilityMetadata = 13;
+ optional BotImagineMetadata imagineMetadata = 14;
+ optional BotMemoryMetadata memoryMetadata = 15;
+ optional BotRenderingMetadata renderingMetadata = 16;
+ optional BotMetricsMetadata botMetricsMetadata = 17;
+ optional BotLinkedAccountsMetadata botLinkedAccountsMetadata = 18;
+ optional BotSourcesMetadata richResponseSourcesMetadata = 19;
+ optional bytes aiConversationContext = 20;
+ optional BotPromotionMessageMetadata botPromotionMessageMetadata = 21;
+ optional BotModeSelectionMetadata botModeSelectionMetadata = 22;
+ optional BotQuotaMetadata botQuotaMetadata = 23;
+ optional BotAgeCollectionMetadata botAgeCollectionMetadata = 24;
+ optional string conversationStarterPromptID = 25;
+ optional string botResponseID = 26;
+ optional BotSignatureVerificationMetadata verificationMetadata = 27;
+ optional BotUnifiedResponseMutation unifiedResponseMutation = 28;
+ optional BotMessageOriginMetadata botMessageOriginMetadata = 29;
+ optional InThreadSurveyMetadata inThreadSurveyMetadata = 30;
+ optional AIThreadInfo botThreadInfo = 31;
+ optional bytes internalMetadata = 999;
+}
diff --git a/crates/whatsmeow_proto/proto/waCert/WACert.proto b/crates/whatsmeow_proto/proto/waCert/WACert.proto
new file mode 100644
index 0000000000..c1cad3637e
--- /dev/null
+++ b/crates/whatsmeow_proto/proto/waCert/WACert.proto
@@ -0,0 +1,38 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+syntax = "proto2";
+package WACert;
+option go_package = "go.mau.fi/whatsmeow/proto/waCert";
+
+message NoiseCertificate {
+ message Details {
+ optional uint32 serial = 1;
+ optional string issuer = 2;
+ optional uint64 expires = 3;
+ optional string subject = 4;
+ optional bytes key = 5;
+ }
+
+ optional bytes details = 1;
+ optional bytes signature = 2;
+}
+
+message CertChain {
+ message NoiseCertificate {
+ message Details {
+ optional uint32 serial = 1;
+ optional uint32 issuerSerial = 2;
+ optional bytes key = 3;
+ optional uint64 notBefore = 4;
+ optional uint64 notAfter = 5;
+ }
+
+ optional bytes details = 1;
+ optional bytes signature = 2;
+ }
+
+ optional NoiseCertificate leaf = 1;
+ optional NoiseCertificate intermediate = 2;
+}
diff --git a/crates/whatsmeow_proto/proto/waChatLockSettings/WAWebProtobufsChatLockSettings.proto b/crates/whatsmeow_proto/proto/waChatLockSettings/WAWebProtobufsChatLockSettings.proto
new file mode 100644
index 0000000000..03827c2a86
--- /dev/null
+++ b/crates/whatsmeow_proto/proto/waChatLockSettings/WAWebProtobufsChatLockSettings.proto
@@ -0,0 +1,14 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+syntax = "proto2";
+package WAWebProtobufsChatLockSettings;
+option go_package = "go.mau.fi/whatsmeow/proto/waChatLockSettings";
+
+import "waUserPassword/WAWebProtobufsUserPassword.proto";
+
+message ChatLockSettings {
+ optional bool hideLockedChats = 1;
+ optional WAWebProtobufsUserPassword.UserPassword secretCode = 2;
+}
diff --git a/crates/whatsmeow_proto/proto/waCommon/WACommon.proto b/crates/whatsmeow_proto/proto/waCommon/WACommon.proto
new file mode 100644
index 0000000000..7a7563c534
--- /dev/null
+++ b/crates/whatsmeow_proto/proto/waCommon/WACommon.proto
@@ -0,0 +1,78 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+syntax = "proto2";
+package WACommon;
+option go_package = "go.mau.fi/whatsmeow/proto/waCommon";
+
+enum FutureProofBehavior {
+ PLACEHOLDER = 0;
+ NO_PLACEHOLDER = 1;
+ IGNORE = 2;
+}
+
+message MessageKey {
+ optional string remoteJID = 1;
+ optional bool fromMe = 2;
+ optional string ID = 3;
+ optional string participant = 4;
+}
+
+message Command {
+ enum CommandType {
+ EVERYONE = 1;
+ SILENT = 2;
+ AI = 3;
+ AI_IMAGINE = 4;
+ }
+
+ optional CommandType commandType = 1;
+ optional uint32 offset = 2;
+ optional uint32 length = 3;
+ optional string validationToken = 4;
+}
+
+message Mention {
+ enum MentionType {
+ PROFILE = 0;
+ }
+
+ optional MentionType mentionType = 1;
+ optional string mentionedJID = 2;
+ optional uint32 offset = 3;
+ optional uint32 length = 4;
+}
+
+message MessageText {
+ optional string text = 1;
+ repeated string mentionedJID = 2;
+ repeated Command commands = 3;
+ repeated Mention mentions = 4;
+}
+
+message SubProtocol {
+ optional bytes payload = 1;
+ optional int32 version = 2;
+}
+
+message LimitSharing {
+ enum Trigger {
+ UNKNOWN = 0;
+ CHAT_SETTING = 1;
+ BIZ_SUPPORTS_FB_HOSTING = 2;
+ UNKNOWN_GROUP = 3;
+ }
+
+ optional bool sharingLimited = 1;
+ optional Trigger trigger = 2;
+ optional int64 limitSharingSettingTimestamp = 3;
+ optional bool initiatedByMe = 4;
+}
+
+message ACP2Setting {
+ optional bool enabled = 1;
+ optional LimitSharing.Trigger trigger = 2;
+ optional int64 settingTimestamp = 3;
+ optional bool initiatedByMe = 4;
+}
diff --git a/crates/whatsmeow_proto/proto/waCommonParameterised/WACommonParameterised.proto b/crates/whatsmeow_proto/proto/waCommonParameterised/WACommonParameterised.proto
new file mode 100644
index 0000000000..ff8f7a94f8
--- /dev/null
+++ b/crates/whatsmeow_proto/proto/waCommonParameterised/WACommonParameterised.proto
@@ -0,0 +1,57 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+syntax = "proto2";
+package WACommonParameterised;
+option go_package = "go.mau.fi/whatsmeow/proto/waCommonParameterised";
+
+enum FutureProofBehavior {
+ PLACEHOLDER = 0;
+ NO_PLACEHOLDER = 1;
+ IGNORE = 2;
+}
+
+message MessageKey {
+ optional string remoteJID = 1;
+ optional bool fromMe = 2;
+ optional string ID = 3;
+ optional string participant = 4;
+}
+
+message Command {
+ enum CommandType {
+ EVERYONE = 1;
+ SILENT = 2;
+ AI = 3;
+ AI_IMAGINE = 4;
+ }
+
+ optional CommandType commandType = 1;
+ optional uint32 offset = 2;
+ optional uint32 length = 3;
+ optional string validationToken = 4;
+}
+
+message Mention {
+ enum MentionType {
+ PROFILE = 0;
+ }
+
+ optional MentionType mentionType = 1;
+ optional string mentionedJID = 2;
+ optional uint32 offset = 3;
+ optional uint32 length = 4;
+}
+
+message MessageText {
+ optional string text = 1;
+ repeated string mentionedJID = 2;
+ repeated Command commands = 3;
+ repeated Mention mentions = 4;
+}
+
+message SubProtocol {
+ optional bytes payload = 1;
+ optional int32 version = 2;
+}
diff --git a/crates/whatsmeow_proto/proto/waCompanionReg/WACompanionReg.proto b/crates/whatsmeow_proto/proto/waCompanionReg/WACompanionReg.proto
new file mode 100644
index 0000000000..523adeae92
--- /dev/null
+++ b/crates/whatsmeow_proto/proto/waCompanionReg/WACompanionReg.proto
@@ -0,0 +1,117 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+syntax = "proto2";
+package WACompanionReg;
+option go_package = "go.mau.fi/whatsmeow/proto/waCompanionReg";
+
+message DeviceProps {
+ enum PlatformType {
+ UNKNOWN = 0;
+ CHROME = 1;
+ FIREFOX = 2;
+ IE = 3;
+ OPERA = 4;
+ SAFARI = 5;
+ EDGE = 6;
+ DESKTOP = 7;
+ IPAD = 8;
+ ANDROID_TABLET = 9;
+ OHANA = 10;
+ ALOHA = 11;
+ CATALINA = 12;
+ TCL_TV = 13;
+ IOS_PHONE = 14;
+ IOS_CATALYST = 15;
+ ANDROID_PHONE = 16;
+ ANDROID_AMBIGUOUS = 17;
+ WEAR_OS = 18;
+ AR_WRIST = 19;
+ AR_DEVICE = 20;
+ UWP = 21;
+ VR = 22;
+ CLOUD_API = 23;
+ SMARTGLASSES = 24;
+ }
+
+ message HistorySyncConfig {
+ optional uint32 fullSyncDaysLimit = 1;
+ optional uint32 fullSyncSizeMbLimit = 2;
+ optional uint32 storageQuotaMb = 3;
+ optional bool inlineInitialPayloadInE2EeMsg = 4;
+ optional uint32 recentSyncDaysLimit = 5;
+ optional bool supportCallLogHistory = 6;
+ optional bool supportBotUserAgentChatHistory = 7;
+ optional bool supportCagReactionsAndPolls = 8;
+ optional bool supportBizHostedMsg = 9;
+ optional bool supportRecentSyncChunkMessageCountTuning = 10;
+ optional bool supportHostedGroupMsg = 11;
+ optional bool supportFbidBotChatHistory = 12;
+ optional bool supportAddOnHistorySyncMigration = 13;
+ optional bool supportMessageAssociation = 14;
+ optional bool supportGroupHistory = 15;
+ optional bool onDemandReady = 16;
+ optional bool supportGuestChat = 17;
+ optional bool completeOnDemandReady = 18;
+ optional uint32 thumbnailSyncDaysLimit = 19;
+ optional uint32 initialSyncMaxMessagesPerChat = 20;
+ optional bool supportManusHistory = 21;
+ optional bool supportHatchHistory = 22;
+ repeated string supportedBotChannelFbids = 23;
+ optional bool supportInlineContacts = 24;
+ }
+
+ message AppVersion {
+ optional uint32 primary = 1;
+ optional uint32 secondary = 2;
+ optional uint32 tertiary = 3;
+ optional uint32 quaternary = 4;
+ optional uint32 quinary = 5;
+ }
+
+ optional string os = 1;
+ optional AppVersion version = 2;
+ optional PlatformType platformType = 3;
+ optional bool requireFullSync = 4;
+ optional HistorySyncConfig historySyncConfig = 5;
+}
+
+message CompanionEphemeralIdentity {
+ optional bytes publicKey = 1;
+ optional DeviceProps.PlatformType deviceType = 2;
+ optional string ref = 3;
+}
+
+message CompanionCommitment {
+ optional bytes hash = 1;
+}
+
+message ProloguePayload {
+ optional bytes companionEphemeralIdentity = 1;
+ optional CompanionCommitment commitment = 2;
+}
+
+message PrimaryEphemeralIdentity {
+ optional bytes publicKey = 1;
+ optional bytes nonce = 2;
+}
+
+message PairingRequest {
+ optional bytes companionPublicKey = 1;
+ optional bytes companionIdentityKey = 2;
+ optional bytes advSecret = 3;
+}
+
+message EncryptedPairingRequest {
+ optional bytes encryptedPayload = 1;
+ optional bytes IV = 2;
+}
+
+message ClientPairingProps {
+ optional bool isChatDbLidMigrated = 1;
+ optional bool isSyncdPureLidSession = 2;
+ optional bool isSyncdSnapshotRecoveryEnabled = 3;
+ optional bool isHsThumbnailSyncEnabled = 4;
+ optional bytes subscriptionSyncPayload = 5;
+}
diff --git a/crates/whatsmeow_proto/proto/waConsumerApplication/WAConsumerApplication.proto b/crates/whatsmeow_proto/proto/waConsumerApplication/WAConsumerApplication.proto
new file mode 100644
index 0000000000..8663870b48
--- /dev/null
+++ b/crates/whatsmeow_proto/proto/waConsumerApplication/WAConsumerApplication.proto
@@ -0,0 +1,237 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+syntax = "proto2";
+package WAConsumerApplication;
+option go_package = "go.mau.fi/whatsmeow/proto/waConsumerApplication";
+
+import "waCommon/WACommon.proto";
+
+message ConsumerApplication {
+ message Payload {
+ oneof payload {
+ Content content = 1;
+ ApplicationData applicationData = 2;
+ Signal signal = 3;
+ SubProtocolPayload subProtocol = 4;
+ }
+ }
+
+ message SubProtocolPayload {
+ optional WACommon.FutureProofBehavior futureProof = 1;
+ }
+
+ message Metadata {
+ enum SpecialTextSize {
+ SMALL = 1;
+ MEDIUM = 2;
+ LARGE = 3;
+ }
+
+ optional SpecialTextSize specialTextSize = 1;
+ }
+
+ message Signal {
+ }
+
+ message ApplicationData {
+ oneof applicationContent {
+ RevokeMessage revoke = 1;
+ }
+ }
+
+ message Content {
+ oneof content {
+ WACommon.MessageText messageText = 1;
+ ImageMessage imageMessage = 2;
+ ContactMessage contactMessage = 3;
+ LocationMessage locationMessage = 4;
+ ExtendedTextMessage extendedTextMessage = 5;
+ StatusTextMesage statusTextMessage = 6;
+ DocumentMessage documentMessage = 7;
+ AudioMessage audioMessage = 8;
+ VideoMessage videoMessage = 9;
+ ContactsArrayMessage contactsArrayMessage = 10;
+ LiveLocationMessage liveLocationMessage = 11;
+ StickerMessage stickerMessage = 12;
+ GroupInviteMessage groupInviteMessage = 13;
+ ViewOnceMessage viewOnceMessage = 14;
+ ReactionMessage reactionMessage = 16;
+ PollCreationMessage pollCreationMessage = 17;
+ PollUpdateMessage pollUpdateMessage = 18;
+ EditMessage editMessage = 19;
+ }
+ }
+
+ message EditMessage {
+ optional WACommon.MessageKey key = 1;
+ optional WACommon.MessageText message = 2;
+ optional int64 timestampMS = 3;
+ }
+
+ message PollAddOptionMessage {
+ repeated Option pollOption = 1;
+ }
+
+ message PollVoteMessage {
+ repeated bytes selectedOptions = 1;
+ optional int64 senderTimestampMS = 2;
+ }
+
+ message PollEncValue {
+ optional bytes encPayload = 1;
+ optional bytes encIV = 2;
+ }
+
+ message PollUpdateMessage {
+ optional WACommon.MessageKey pollCreationMessageKey = 1;
+ optional PollEncValue vote = 2;
+ optional PollEncValue addOption = 3;
+ }
+
+ message PollCreationMessage {
+ optional bytes encKey = 1;
+ optional string name = 2;
+ repeated Option options = 3;
+ optional uint32 selectableOptionsCount = 4;
+ }
+
+ message Option {
+ optional string optionName = 1;
+ }
+
+ message ReactionMessage {
+ optional WACommon.MessageKey key = 1;
+ optional string text = 2;
+ optional string groupingKey = 3;
+ optional int64 senderTimestampMS = 4;
+ optional string reactionMetadataDataclassData = 5;
+ optional int32 style = 6;
+ }
+
+ message RevokeMessage {
+ optional WACommon.MessageKey key = 1;
+ }
+
+ message ViewOnceMessage {
+ oneof viewOnceContent {
+ ImageMessage imageMessage = 1;
+ VideoMessage videoMessage = 2;
+ }
+ }
+
+ message GroupInviteMessage {
+ optional string groupJID = 1;
+ optional string inviteCode = 2;
+ optional int64 inviteExpiration = 3;
+ optional string groupName = 4;
+ optional bytes JPEGThumbnail = 5;
+ optional WACommon.MessageText caption = 6;
+ }
+
+ message LiveLocationMessage {
+ optional Location location = 1;
+ optional uint32 accuracyInMeters = 2;
+ optional float speedInMps = 3;
+ optional uint32 degreesClockwiseFromMagneticNorth = 4;
+ optional WACommon.MessageText caption = 5;
+ optional int64 sequenceNumber = 6;
+ optional uint32 timeOffset = 7;
+ }
+
+ message ContactsArrayMessage {
+ optional string displayName = 1;
+ repeated ContactMessage contacts = 2;
+ }
+
+ message ContactMessage {
+ optional WACommon.SubProtocol contact = 1;
+ }
+
+ message StatusTextMesage {
+ enum FontType {
+ SANS_SERIF = 0;
+ SERIF = 1;
+ NORICAN_REGULAR = 2;
+ BRYNDAN_WRITE = 3;
+ BEBASNEUE_REGULAR = 4;
+ OSWALD_HEAVY = 5;
+ }
+
+ optional ExtendedTextMessage text = 1;
+ optional fixed32 textArgb = 6;
+ optional fixed32 backgroundArgb = 7;
+ optional FontType font = 8;
+ }
+
+ message ExtendedTextMessage {
+ enum PreviewType {
+ NONE = 0;
+ VIDEO = 1;
+ }
+
+ optional WACommon.MessageText text = 1;
+ optional string matchedText = 2;
+ optional string canonicalURL = 3;
+ optional string description = 4;
+ optional string title = 5;
+ optional WACommon.SubProtocol thumbnail = 6;
+ optional PreviewType previewType = 7;
+ }
+
+ message LocationMessage {
+ optional Location location = 1;
+ optional string address = 2;
+ }
+
+ message StickerMessage {
+ optional WACommon.SubProtocol sticker = 1;
+ }
+
+ message DocumentMessage {
+ optional WACommon.SubProtocol document = 1;
+ optional string fileName = 2;
+ }
+
+ message VideoMessage {
+ optional WACommon.SubProtocol video = 1;
+ optional WACommon.MessageText caption = 2;
+ }
+
+ message AudioMessage {
+ optional WACommon.SubProtocol audio = 1;
+ optional bool PTT = 2;
+ }
+
+ message ImageMessage {
+ optional WACommon.SubProtocol image = 1;
+ optional WACommon.MessageText caption = 2;
+ }
+
+ message InteractiveAnnotation {
+ oneof action {
+ Location location = 2;
+ }
+
+ repeated Point polygonVertices = 1;
+ }
+
+ message Point {
+ optional double x = 1;
+ optional double y = 2;
+ }
+
+ message Location {
+ optional double degreesLatitude = 1;
+ optional double degreesLongitude = 2;
+ optional string name = 3;
+ }
+
+ message MediaPayload {
+ optional WACommon.SubProtocol protocol = 1;
+ }
+
+ optional Payload payload = 1;
+ optional Metadata metadata = 2;
+}
diff --git a/crates/whatsmeow_proto/proto/waConsumerApplicationParameterised/WAConsumerApplicationParameterised.proto b/crates/whatsmeow_proto/proto/waConsumerApplicationParameterised/WAConsumerApplicationParameterised.proto
new file mode 100644
index 0000000000..9b2486ff1d
--- /dev/null
+++ b/crates/whatsmeow_proto/proto/waConsumerApplicationParameterised/WAConsumerApplicationParameterised.proto
@@ -0,0 +1,237 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+syntax = "proto2";
+package WAConsumerApplicationParameterised;
+option go_package = "go.mau.fi/whatsmeow/proto/waConsumerApplicationParameterised";
+
+import "waCommonParameterised/WACommonParameterised.proto";
+
+message ConsumerApplication {
+ message Payload {
+ oneof payload {
+ Content content = 1;
+ ApplicationData applicationData = 2;
+ Signal signal = 3;
+ SubProtocolPayload subProtocol = 4;
+ }
+ }
+
+ message SubProtocolPayload {
+ optional WACommonParameterised.FutureProofBehavior futureProof = 1;
+ }
+
+ message Metadata {
+ enum SpecialTextSize {
+ SMALL = 1;
+ MEDIUM = 2;
+ LARGE = 3;
+ }
+
+ optional SpecialTextSize specialTextSize = 1;
+ }
+
+ message Signal {
+ }
+
+ message ApplicationData {
+ oneof applicationContent {
+ RevokeMessage revoke = 1;
+ }
+ }
+
+ message Content {
+ oneof content {
+ WACommonParameterised.MessageText messageText = 1;
+ ImageMessage imageMessage = 2;
+ ContactMessage contactMessage = 3;
+ LocationMessage locationMessage = 4;
+ ExtendedTextMessage extendedTextMessage = 5;
+ StatusTextMesage statusTextMessage = 6;
+ DocumentMessage documentMessage = 7;
+ AudioMessage audioMessage = 8;
+ VideoMessage videoMessage = 9;
+ ContactsArrayMessage contactsArrayMessage = 10;
+ LiveLocationMessage liveLocationMessage = 11;
+ StickerMessage stickerMessage = 12;
+ GroupInviteMessage groupInviteMessage = 13;
+ ViewOnceMessage viewOnceMessage = 14;
+ ReactionMessage reactionMessage = 16;
+ PollCreationMessage pollCreationMessage = 17;
+ PollUpdateMessage pollUpdateMessage = 18;
+ EditMessage editMessage = 19;
+ }
+ }
+
+ message EditMessage {
+ optional WACommonParameterised.MessageKey key = 1;
+ optional WACommonParameterised.MessageText message = 2;
+ optional int64 timestampMS = 3;
+ }
+
+ message PollAddOptionMessage {
+ repeated Option pollOption = 1;
+ }
+
+ message PollVoteMessage {
+ repeated bytes selectedOptions = 1;
+ optional int64 senderTimestampMS = 2;
+ }
+
+ message PollEncValue {
+ optional bytes encPayload = 1;
+ optional bytes encIV = 2;
+ }
+
+ message PollUpdateMessage {
+ optional WACommonParameterised.MessageKey pollCreationMessageKey = 1;
+ optional PollEncValue vote = 2;
+ optional PollEncValue addOption = 3;
+ }
+
+ message PollCreationMessage {
+ optional bytes encKey = 1;
+ optional string name = 2;
+ repeated Option options = 3;
+ optional uint32 selectableOptionsCount = 4;
+ }
+
+ message Option {
+ optional string optionName = 1;
+ }
+
+ message ReactionMessage {
+ optional WACommonParameterised.MessageKey key = 1;
+ optional string text = 2;
+ optional string groupingKey = 3;
+ optional int64 senderTimestampMS = 4;
+ optional string reactionMetadataDataclassData = 5;
+ optional int32 style = 6;
+ }
+
+ message RevokeMessage {
+ optional WACommonParameterised.MessageKey key = 1;
+ }
+
+ message ViewOnceMessage {
+ oneof viewOnceContent {
+ ImageMessage imageMessage = 1;
+ VideoMessage videoMessage = 2;
+ }
+ }
+
+ message GroupInviteMessage {
+ optional string groupJID = 1;
+ optional string inviteCode = 2;
+ optional int64 inviteExpiration = 3;
+ optional string groupName = 4;
+ optional bytes JPEGThumbnail = 5;
+ optional WACommonParameterised.MessageText caption = 6;
+ }
+
+ message LiveLocationMessage {
+ optional Location location = 1;
+ optional uint32 accuracyInMeters = 2;
+ optional float speedInMps = 3;
+ optional uint32 degreesClockwiseFromMagneticNorth = 4;
+ optional WACommonParameterised.MessageText caption = 5;
+ optional int64 sequenceNumber = 6;
+ optional uint32 timeOffset = 7;
+ }
+
+ message ContactsArrayMessage {
+ optional string displayName = 1;
+ repeated ContactMessage contacts = 2;
+ }
+
+ message ContactMessage {
+ optional WACommonParameterised.SubProtocol contact = 1;
+ }
+
+ message StatusTextMesage {
+ enum FontType {
+ SANS_SERIF = 0;
+ SERIF = 1;
+ NORICAN_REGULAR = 2;
+ BRYNDAN_WRITE = 3;
+ BEBASNEUE_REGULAR = 4;
+ OSWALD_HEAVY = 5;
+ }
+
+ optional ExtendedTextMessage text = 1;
+ optional fixed32 textArgb = 6;
+ optional fixed32 backgroundArgb = 7;
+ optional FontType font = 8;
+ }
+
+ message ExtendedTextMessage {
+ enum PreviewType {
+ NONE = 0;
+ VIDEO = 1;
+ }
+
+ optional WACommonParameterised.MessageText text = 1;
+ optional string matchedText = 2;
+ optional string canonicalURL = 3;
+ optional string description = 4;
+ optional string title = 5;
+ optional WACommonParameterised.SubProtocol thumbnail = 6;
+ optional PreviewType previewType = 7;
+ }
+
+ message LocationMessage {
+ optional Location location = 1;
+ optional string address = 2;
+ }
+
+ message StickerMessage {
+ optional WACommonParameterised.SubProtocol sticker = 1;
+ }
+
+ message DocumentMessage {
+ optional WACommonParameterised.SubProtocol document = 1;
+ optional string fileName = 2;
+ }
+
+ message VideoMessage {
+ optional WACommonParameterised.SubProtocol video = 1;
+ optional WACommonParameterised.MessageText caption = 2;
+ }
+
+ message AudioMessage {
+ optional WACommonParameterised.SubProtocol audio = 1;
+ optional bool PTT = 2;
+ }
+
+ message ImageMessage {
+ optional WACommonParameterised.SubProtocol image = 1;
+ optional WACommonParameterised.MessageText caption = 2;
+ }
+
+ message InteractiveAnnotation {
+ oneof action {
+ Location location = 2;
+ }
+
+ repeated Point polygonVertices = 1;
+ }
+
+ message Point {
+ optional double x = 1;
+ optional double y = 2;
+ }
+
+ message Location {
+ optional double degreesLatitude = 1;
+ optional double degreesLongitude = 2;
+ optional string name = 3;
+ }
+
+ message MediaPayload {
+ optional WACommonParameterised.SubProtocol protocol = 1;
+ }
+
+ optional Payload payload = 1;
+ optional Metadata metadata = 2;
+}
diff --git a/crates/whatsmeow_proto/proto/waDeviceCapabilities/WAWebProtobufsDeviceCapabilities.proto b/crates/whatsmeow_proto/proto/waDeviceCapabilities/WAWebProtobufsDeviceCapabilities.proto
new file mode 100644
index 0000000000..7b77a63e62
--- /dev/null
+++ b/crates/whatsmeow_proto/proto/waDeviceCapabilities/WAWebProtobufsDeviceCapabilities.proto
@@ -0,0 +1,93 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+syntax = "proto2";
+package WAWebProtobufsDeviceCapabilities;
+option go_package = "go.mau.fi/whatsmeow/proto/waDeviceCapabilities";
+
+message DeviceCapabilities {
+ enum MemberNameTagPrimarySupport {
+ DISABLED = 0;
+ RECEIVER_ENABLED = 1;
+ SENDER_ENABLED = 2;
+ }
+
+ enum ChatLockSupportLevel {
+ NONE = 0;
+ MINIMAL = 1;
+ FULL = 2;
+ }
+
+ message ReverseHistorySync {
+ enum Product {
+ PRODUCT_UNSPECIFIED = 0;
+ HATCH = 1;
+ }
+
+ repeated Product enabledProducts = 1;
+ }
+
+ message AiThread {
+ enum SupportLevel {
+ NONE = 0;
+ INFRA = 1;
+ FULL = 2;
+ }
+
+ optional SupportLevel supportLevel = 1;
+ }
+
+ message HostWriteMutationSupport {
+ repeated string mutationNames = 1;
+ }
+
+ message NewsletterChatsMigration {
+ optional bool effectiveMigrated = 1;
+ optional int64 countdownEndsAt = 2;
+ optional bool rolledBack = 3;
+ }
+
+ message ContactRefresh {
+ optional bool refreshSupported = 1;
+ }
+
+ message BizAiSettingsSync {
+ optional bool handoffRemovalTimingEnabled = 1;
+ }
+
+ message AiFbidMigration {
+ optional uint64 chatDbMigrationTimestamp = 1;
+ optional uint32 supportVersion = 2;
+ }
+
+ message UserHasAvatar {
+ optional bool userHasAvatar = 1;
+ }
+
+ message BusinessBroadcast {
+ optional bool importListEnabled = 1;
+ optional bool companionSupportEnabled = 2;
+ optional bool campaignSyncEnabled = 3;
+ optional bool insightsSyncEnabled = 4;
+ optional int32 recipientLimit = 5;
+ optional bool proCompanionSupportEnabled = 6;
+ }
+
+ message LIDMigration {
+ optional uint64 chatDbMigrationTimestamp = 1;
+ }
+
+ optional ChatLockSupportLevel chatLockSupportLevel = 1;
+ optional LIDMigration lidMigration = 2;
+ optional BusinessBroadcast businessBroadcast = 3;
+ optional UserHasAvatar userHasAvatar = 4;
+ optional MemberNameTagPrimarySupport memberNameTagPrimarySupport = 5;
+ optional AiThread aiThread = 6;
+ optional AiFbidMigration aiFbidMigration = 7;
+ optional BizAiSettingsSync bizAiSettingsSync = 8;
+ optional ContactRefresh contactRefresh = 9;
+ optional ReverseHistorySync reverseHistorySync = 10;
+ optional NewsletterChatsMigration newsletterChatsMigration = 11;
+ optional HostWriteMutationSupport hostWriteMutationSupport = 12;
+}
diff --git a/crates/whatsmeow_proto/proto/waE2E/WAWebProtobufsE2E.proto b/crates/whatsmeow_proto/proto/waE2E/WAWebProtobufsE2E.proto
new file mode 100644
index 0000000000..7df2c9a193
--- /dev/null
+++ b/crates/whatsmeow_proto/proto/waE2E/WAWebProtobufsE2E.proto
@@ -0,0 +1,2738 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+syntax = "proto2";
+package WAWebProtobufsE2E;
+option go_package = "go.mau.fi/whatsmeow/proto/waE2E";
+
+import "waAICommon/WAWebProtobufsAICommon.proto";
+import "waAICommonDeprecated/WAAICommonDeprecated.proto";
+import "waAdv/WAAdv.proto";
+import "waAea/WAWebProtobufsAea.proto";
+import "waCompanionReg/WACompanionReg.proto";
+import "waMmsRetry/WAMmsRetry.proto";
+import "waCommon/WACommon.proto";
+import "waServerSync/WAWebProtobufsServerSync.proto";
+import "waStatusAttributions/WAStatusAttributions.proto";
+
+enum PollType {
+ POLL = 0;
+ QUIZ = 1;
+}
+
+enum PollContentType {
+ UNKNOWN_POLL_CONTENT_TYPE = 0;
+ TEXT = 1;
+ IMAGE = 2;
+}
+
+enum InsightDeliveryState {
+ SENT = 0;
+ DELIVERED = 1;
+ READ = 2;
+ REPLIED = 3;
+ QUICK_REPLIED = 4;
+}
+
+enum PeerDataOperationRequestType {
+ UPLOAD_STICKER = 0;
+ SEND_RECENT_STICKER_BOOTSTRAP = 1;
+ GENERATE_LINK_PREVIEW = 2;
+ HISTORY_SYNC_ON_DEMAND = 3;
+ PLACEHOLDER_MESSAGE_RESEND = 4;
+ WAFFLE_LINKING_NONCE_FETCH = 5;
+ FULL_HISTORY_SYNC_ON_DEMAND = 6;
+ COMPANION_META_NONCE_FETCH = 7;
+ COMPANION_SYNCD_SNAPSHOT_FATAL_RECOVERY = 8;
+ COMPANION_CANONICAL_USER_NONCE_FETCH = 9;
+ HISTORY_SYNC_CHUNK_RETRY = 10;
+ GALAXY_FLOW_ACTION = 11;
+ BUSINESS_BROADCAST_INSIGHTS_DELIVERED_TO = 12;
+ BUSINESS_BROADCAST_INSIGHTS_REFRESH = 13;
+ CONTACT_REFRESH_REQUEST = 14;
+}
+
+enum HistorySyncType {
+ INITIAL_BOOTSTRAP = 0;
+ INITIAL_STATUS_V3 = 1;
+ FULL = 2;
+ RECENT = 3;
+ PUSH_NAME = 4;
+ NON_BLOCKING_DATA = 5;
+ ON_DEMAND = 6;
+ NO_HISTORY = 7;
+ MESSAGE_ACCESS_STATUS = 8;
+}
+
+enum MediaKeyDomain {
+ MEDIA_KEY_DOMAIN_UNKNOWN = 0;
+ MEDIA_KEY_DOMAIN_E2EE = 1;
+ MEDIA_KEY_DOMAIN_NON_E2EE = 2;
+}
+
+enum WebLinkRenderConfig {
+ WEBVIEW = 0;
+ SYSTEM = 1;
+}
+
+enum KeepType {
+ UNKNOWN_KEEP_TYPE = 0;
+ KEEP_FOR_ALL = 1;
+ UNDO_KEEP_FOR_ALL = 2;
+}
+
+message StatusLinkPreviewMetadata {
+ enum Style {
+ AUTO = 0;
+ COMPACT = 1;
+ FULL = 2;
+ IMMERSIVE = 3;
+ }
+
+ optional Style style = 1;
+}
+
+message StickerPackMessage {
+ enum StickerPackOrigin {
+ FIRST_PARTY = 0;
+ THIRD_PARTY = 1;
+ USER_CREATED = 2;
+ }
+
+ message Sticker {
+ optional string fileName = 1;
+ optional bool isAnimated = 2;
+ repeated string emojis = 3;
+ optional string accessibilityLabel = 4;
+ optional bool isLottie = 5;
+ optional string mimetype = 6;
+ optional int32 premium = 7;
+ }
+
+ optional string stickerPackID = 1;
+ optional string name = 2;
+ optional string publisher = 3;
+ repeated Sticker stickers = 4;
+ optional uint64 fileLength = 5;
+ optional bytes fileSHA256 = 6;
+ optional bytes fileEncSHA256 = 7;
+ optional bytes mediaKey = 8;
+ optional string directPath = 9;
+ optional string caption = 10;
+ optional ContextInfo contextInfo = 11;
+ optional string packDescription = 12;
+ optional int64 mediaKeyTimestamp = 13;
+ optional string trayIconFileName = 14;
+ optional string thumbnailDirectPath = 15;
+ optional bytes thumbnailSHA256 = 16;
+ optional bytes thumbnailEncSHA256 = 17;
+ optional uint32 thumbnailHeight = 18;
+ optional uint32 thumbnailWidth = 19;
+ optional string imageDataHash = 20;
+ optional uint64 stickerPackSize = 21;
+ optional StickerPackOrigin stickerPackOrigin = 22;
+}
+
+message PlaceholderMessage {
+ enum PlaceholderType {
+ MASK_LINKED_DEVICES = 0;
+ }
+
+ optional PlaceholderType type = 1;
+}
+
+message BCallMessage {
+ enum MediaType {
+ UNKNOWN = 0;
+ AUDIO = 1;
+ VIDEO = 2;
+ }
+
+ optional string sessionID = 1;
+ optional MediaType mediaType = 2;
+ optional bytes masterKey = 3;
+ optional string caption = 4;
+}
+
+message CallLogMessage {
+ enum CallOutcome {
+ CONNECTED = 0;
+ MISSED = 1;
+ FAILED = 2;
+ REJECTED = 3;
+ ACCEPTED_ELSEWHERE = 4;
+ ONGOING = 5;
+ SILENCED_BY_DND = 6;
+ SILENCED_UNKNOWN_CALLER = 7;
+ }
+
+ enum CallType {
+ REGULAR = 0;
+ SCHEDULED_CALL = 1;
+ VOICE_CHAT = 2;
+ }
+
+ message CallParticipant {
+ optional string JID = 1;
+ optional CallOutcome callOutcome = 2;
+ }
+
+ optional bool isVideo = 1;
+ optional CallOutcome callOutcome = 2;
+ optional int64 durationSecs = 3;
+ optional CallType callType = 4;
+ repeated CallParticipant participants = 5;
+}
+
+message ScheduledCallEditMessage {
+ enum EditType {
+ UNKNOWN = 0;
+ CANCEL = 1;
+ }
+
+ optional WACommon.MessageKey key = 1;
+ optional EditType editType = 2;
+}
+
+message ScheduledCallCreationMessage {
+ enum CallType {
+ UNKNOWN = 0;
+ VOICE = 1;
+ VIDEO = 2;
+ }
+
+ optional int64 scheduledTimestampMS = 1;
+ optional CallType callType = 2;
+ optional string title = 3;
+}
+
+message EventResponseMessage {
+ enum EventResponseType {
+ UNKNOWN = 0;
+ GOING = 1;
+ NOT_GOING = 2;
+ MAYBE = 3;
+ }
+
+ optional EventResponseType response = 1;
+ optional int64 timestampMS = 2;
+ optional int32 extraGuestCount = 3;
+}
+
+message PinInChatMessage {
+ enum Type {
+ UNKNOWN_TYPE = 0;
+ PIN_FOR_ALL = 1;
+ UNPIN_FOR_ALL = 2;
+ }
+
+ optional WACommon.MessageKey key = 1;
+ optional Type type = 2;
+ optional int64 senderTimestampMS = 3;
+}
+
+message StatusStickerInteractionMessage {
+ enum StatusStickerType {
+ UNKNOWN = 0;
+ REACTION = 1;
+ }
+
+ optional WACommon.MessageKey key = 1;
+ optional string stickerKey = 2;
+ optional StatusStickerType type = 3;
+}
+
+message ButtonsResponseMessage {
+ enum Type {
+ UNKNOWN = 0;
+ DISPLAY_TEXT = 1;
+ }
+
+ oneof response {
+ string selectedDisplayText = 2;
+ }
+
+ optional string selectedButtonID = 1;
+ optional ContextInfo contextInfo = 3;
+ optional Type type = 4;
+}
+
+message ButtonsMessage {
+ enum HeaderType {
+ UNKNOWN = 0;
+ EMPTY = 1;
+ TEXT = 2;
+ DOCUMENT = 3;
+ IMAGE = 4;
+ VIDEO = 5;
+ LOCATION = 6;
+ }
+
+ message Button {
+ enum Type {
+ UNKNOWN = 0;
+ RESPONSE = 1;
+ NATIVE_FLOW = 2;
+ }
+
+ message NativeFlowInfo {
+ optional string name = 1;
+ optional string paramsJSON = 2;
+ }
+
+ message ButtonText {
+ optional string displayText = 1;
+ }
+
+ optional string buttonID = 1;
+ optional ButtonText buttonText = 2;
+ optional Type type = 3;
+ optional NativeFlowInfo nativeFlowInfo = 4;
+ }
+
+ oneof header {
+ string text = 1;
+ DocumentMessage documentMessage = 2;
+ ImageMessage imageMessage = 3;
+ VideoMessage videoMessage = 4;
+ LocationMessage locationMessage = 5;
+ }
+
+ optional string contentText = 6;
+ optional string footerText = 7;
+ optional ContextInfo contextInfo = 8;
+ repeated Button buttons = 9;
+ optional HeaderType headerType = 10;
+}
+
+message ConditionalRevealMessage {
+ enum ConditionalRevealMessageType {
+ UNKNOWN = 0;
+ SCHEDULED_MESSAGE = 1;
+ }
+
+ optional bytes encPayload = 1;
+ optional bytes encIV = 2;
+ optional ConditionalRevealMessageType conditionalRevealMessageType = 3;
+ optional string revealKeyID = 4;
+}
+
+message SecretEncryptedMessage {
+ enum SecretEncType {
+ UNKNOWN = 0;
+ EVENT_EDIT = 1;
+ MESSAGE_EDIT = 2;
+ MESSAGE_SCHEDULE = 3;
+ POLL_EDIT = 4;
+ POLL_ADD_OPTION = 5;
+ }
+
+ optional WACommon.MessageKey targetMessageKey = 1;
+ optional bytes encPayload = 2;
+ optional bytes encIV = 3;
+ optional SecretEncType secretEncType = 4;
+ optional string remoteKeyID = 5;
+}
+
+message RequestLocationUpdateMessage {
+ enum UpdateType {
+ UNKNOWN = 0;
+ CANCEL = 1;
+ }
+
+ optional WACommon.MessageKey key = 1;
+ optional UpdateType updateType = 2;
+ optional int64 senderTimestampMS = 3;
+}
+
+message EventInviteMessage {
+ enum EventStatus {
+ UNKNOWN = 0;
+ ACTIVE = 1;
+ CANCELED = 2;
+ SUSPENDED = 3;
+ DELETED = 4;
+ LEFT_EVENT = 5;
+ REMOVED_FROM_INVITE_LIST = 6;
+ }
+
+ optional ContextInfo contextInfo = 1;
+ optional string eventID = 2;
+ optional string eventTitle = 3;
+ optional bytes JPEGThumbnail = 4;
+ optional int64 startTime = 5;
+ optional string caption = 6;
+ optional bool isCanceled = 7;
+ optional int64 endTime = 8;
+ optional string callLink = 9;
+ optional string coverImageHandle = 10;
+ optional string locationName = 11;
+ optional int64 lastUpdatedTSUsec = 12;
+ optional EventStatus status = 13;
+}
+
+message GroupInviteMessage {
+ enum GroupType {
+ DEFAULT = 0;
+ PARENT = 1;
+ }
+
+ optional string groupJID = 1;
+ optional string inviteCode = 2;
+ optional int64 inviteExpiration = 3;
+ optional string groupName = 4;
+ optional bytes JPEGThumbnail = 5;
+ optional string caption = 6;
+ optional ContextInfo contextInfo = 7;
+ optional GroupType groupType = 8;
+}
+
+message InteractiveResponseMessage {
+ message Body {
+ enum Format {
+ DEFAULT = 0;
+ EXTENSIONS_1 = 1;
+ }
+
+ optional string text = 1;
+ optional Format format = 2;
+ }
+
+ message NativeFlowResponseMessage {
+ optional string name = 1;
+ optional string paramsJSON = 2;
+ optional int32 version = 3;
+ }
+
+ oneof interactiveResponseMessage {
+ NativeFlowResponseMessage nativeFlowResponseMessage = 2;
+ }
+
+ optional Body body = 1;
+ optional ContextInfo contextInfo = 15;
+}
+
+message InteractiveMessage {
+ message CarouselMessage {
+ enum CarouselCardType {
+ UNKNOWN = 0;
+ HSCROLL_CARDS = 1;
+ ALBUM_IMAGE = 2;
+ }
+
+ repeated InteractiveMessage cards = 1;
+ optional int32 messageVersion = 2;
+ optional CarouselCardType carouselCardType = 3;
+ }
+
+ message ShopMessage {
+ enum Surface {
+ UNKNOWN_SURFACE = 0;
+ FB = 1;
+ IG = 2;
+ WA = 3;
+ }
+
+ optional string ID = 1;
+ optional Surface surface = 2;
+ optional int32 messageVersion = 3;
+ }
+
+ message NativeFlowMessage {
+ message NativeFlowButton {
+ optional string name = 1;
+ optional string buttonParamsJSON = 2;
+ }
+
+ repeated NativeFlowButton buttons = 1;
+ optional string messageParamsJSON = 2;
+ optional int32 messageVersion = 3;
+ }
+
+ message CollectionMessage {
+ optional string bizJID = 1;
+ optional string ID = 2;
+ optional int32 messageVersion = 3;
+ }
+
+ message BloksWidget {
+ optional string uuid = 1;
+ optional string data = 2;
+ optional string type = 3;
+ optional string fallback = 4;
+ }
+
+ message Footer {
+ oneof media {
+ AudioMessage audioMessage = 2;
+ }
+
+ optional string text = 1;
+ optional bool hasMediaAttachment = 3;
+ }
+
+ message Body {
+ optional string text = 1;
+ }
+
+ message Header {
+ oneof media {
+ DocumentMessage documentMessage = 3;
+ ImageMessage imageMessage = 4;
+ bytes JPEGThumbnail = 6;
+ VideoMessage videoMessage = 7;
+ LocationMessage locationMessage = 8;
+ ProductMessage productMessage = 9;
+ }
+
+ optional string title = 1;
+ optional string subtitle = 2;
+ optional bool hasMediaAttachment = 5;
+ optional BloksWidget bloksWidget = 10;
+ }
+
+ oneof interactiveMessage {
+ ShopMessage shopStorefrontMessage = 4;
+ CollectionMessage collectionMessage = 5;
+ NativeFlowMessage nativeFlowMessage = 6;
+ CarouselMessage carouselMessage = 7;
+ }
+
+ optional Header header = 1;
+ optional Body body = 2;
+ optional Footer footer = 3;
+ optional BloksWidget bloksWidget = 8;
+ optional ContextInfo contextInfo = 15;
+ optional UrlTrackingMap urlTrackingMap = 16;
+}
+
+message ListResponseMessage {
+ enum ListType {
+ UNKNOWN = 0;
+ SINGLE_SELECT = 1;
+ }
+
+ message SingleSelectReply {
+ optional string selectedRowID = 1;
+ }
+
+ optional string title = 1;
+ optional ListType listType = 2;
+ optional SingleSelectReply singleSelectReply = 3;
+ optional ContextInfo contextInfo = 4;
+ optional string description = 5;
+}
+
+message ListMessage {
+ enum ListType {
+ UNKNOWN = 0;
+ SINGLE_SELECT = 1;
+ PRODUCT_LIST = 2;
+ }
+
+ message ProductListInfo {
+ repeated ProductSection productSections = 1;
+ optional ProductListHeaderImage headerImage = 2;
+ optional string businessOwnerJID = 3;
+ }
+
+ message ProductListHeaderImage {
+ optional string productID = 1;
+ optional bytes JPEGThumbnail = 2;
+ }
+
+ message ProductSection {
+ optional string title = 1;
+ repeated Product products = 2;
+ }
+
+ message Product {
+ optional string productID = 1;
+ }
+
+ message Section {
+ optional string title = 1;
+ repeated Row rows = 2;
+ }
+
+ message Row {
+ optional string title = 1;
+ optional string description = 2;
+ optional string rowID = 3;
+ }
+
+ optional string title = 1;
+ optional string description = 2;
+ optional string buttonText = 3;
+ optional ListType listType = 4;
+ repeated Section sections = 5;
+ optional ProductListInfo productListInfo = 6;
+ optional string footerText = 7;
+ optional ContextInfo contextInfo = 8;
+}
+
+message OrderMessage {
+ enum OrderSurface {
+ CATALOG = 1;
+ }
+
+ enum OrderStatus {
+ INQUIRY = 1;
+ ACCEPTED = 2;
+ DECLINED = 3;
+ }
+
+ optional string orderID = 1;
+ optional bytes thumbnail = 2;
+ optional int32 itemCount = 3;
+ optional OrderStatus status = 4;
+ optional OrderSurface surface = 5;
+ optional string message = 6;
+ optional string orderTitle = 7;
+ optional string sellerJID = 8;
+ optional string token = 9;
+ optional int64 totalAmount1000 = 10;
+ optional string totalCurrencyCode = 11;
+ optional ContextInfo contextInfo = 17;
+ optional int32 messageVersion = 12;
+ optional WACommon.MessageKey orderRequestMessageID = 13;
+ optional string catalogType = 15;
+}
+
+message StatusQuotedMessage {
+ enum StatusQuotedMessageType {
+ QUESTION_ANSWER = 1;
+ }
+
+ optional StatusQuotedMessageType type = 1;
+ optional string text = 2;
+ optional bytes thumbnail = 3;
+ optional WACommon.MessageKey originalStatusID = 4;
+}
+
+message SplitPaymentParticipant {
+ enum SplitPaymentStatus {
+ PENDING = 0;
+ PAID = 1;
+ }
+
+ optional string JID = 1;
+ optional Money amount = 2;
+ optional SplitPaymentStatus status = 3;
+}
+
+message PaymentReminderMessage {
+ enum ReminderStatus {
+ REMINDER_STATUS_UNKNOWN = 0;
+ ACTIVE = 1;
+ CANCELLED_BY_CREATOR = 2;
+ STOPPED_BY_RECEIVER = 3;
+ EXPIRED = 4;
+ PAID = 5;
+ }
+
+ enum ReminderFrequency {
+ REMINDER_FREQUENCY_UNKNOWN = 0;
+ WEEKLY = 1;
+ BI_WEEKLY = 2;
+ MONTHLY = 3;
+ QUARTERLY = 4;
+ }
+
+ optional string reminderID = 1;
+ optional string instanceID = 2;
+ optional string description = 3;
+ optional ReminderFrequency frequency = 4;
+ optional ReminderStatus status = 5;
+ optional string payeeVpa = 6;
+ optional string payeeJID = 7;
+ optional string payerJID = 8;
+ optional Money amount = 9;
+}
+
+message PaymentInviteMessage {
+ enum InviteType {
+ DEFAULT = 0;
+ MAPPER = 1;
+ }
+
+ enum ServiceType {
+ UNKNOWN = 0;
+ FBPAY = 1;
+ NOVI = 2;
+ UPI = 3;
+ PIX = 4;
+ }
+
+ optional ServiceType serviceType = 1;
+ optional int64 expiryTimestamp = 2;
+ optional bool incentiveEligible = 3;
+ optional string referralID = 4;
+ optional InviteType inviteType = 5;
+}
+
+message HighlyStructuredMessage {
+ message HSMLocalizableParameter {
+ message HSMDateTime {
+ message HSMDateTimeComponent {
+ enum CalendarType {
+ GREGORIAN = 1;
+ SOLAR_HIJRI = 2;
+ }
+
+ enum DayOfWeekType {
+ MONDAY = 1;
+ TUESDAY = 2;
+ WEDNESDAY = 3;
+ THURSDAY = 4;
+ FRIDAY = 5;
+ SATURDAY = 6;
+ SUNDAY = 7;
+ }
+
+ optional DayOfWeekType dayOfWeek = 1;
+ optional uint32 year = 2;
+ optional uint32 month = 3;
+ optional uint32 dayOfMonth = 4;
+ optional uint32 hour = 5;
+ optional uint32 minute = 6;
+ optional CalendarType calendar = 7;
+ }
+
+ message HSMDateTimeUnixEpoch {
+ optional int64 timestamp = 1;
+ }
+
+ oneof datetimeOneof {
+ HSMDateTimeComponent component = 1;
+ HSMDateTimeUnixEpoch unixEpoch = 2;
+ }
+ }
+
+ message HSMCurrency {
+ optional string currencyCode = 1;
+ optional int64 amount1000 = 2;
+ }
+
+ oneof paramOneof {
+ HSMCurrency currency = 2;
+ HSMDateTime dateTime = 3;
+ }
+
+ optional string default = 1;
+ }
+
+ optional string namespace = 1;
+ optional string elementName = 2;
+ repeated string params = 3;
+ optional string fallbackLg = 4;
+ optional string fallbackLc = 5;
+ repeated HSMLocalizableParameter localizableParams = 6;
+ optional string deterministicLg = 7;
+ optional string deterministicLc = 8;
+ optional TemplateMessage hydratedHsm = 9;
+}
+
+message PeerDataOperationRequestResponseMessage {
+ message PeerDataOperationResult {
+ enum HistorySyncChunkRetryResponseCode {
+ GENERATION_ERROR = 1;
+ CHUNK_CONSUMED = 2;
+ TIMEOUT = 3;
+ SESSION_EXHAUSTED = 4;
+ CHUNK_EXHAUSTED = 5;
+ DUPLICATED_REQUEST = 6;
+ }
+
+ enum FullHistorySyncOnDemandResponseCode {
+ REQUEST_SUCCESS = 0;
+ REQUEST_TIME_EXPIRED = 1;
+ DECLINED_SHARING_HISTORY = 2;
+ GENERIC_ERROR = 3;
+ ERROR_REQUEST_ON_NON_SMB_PRIMARY = 4;
+ ERROR_HOSTED_DEVICE_NOT_CONNECTED = 5;
+ ERROR_HOSTED_DEVICE_LOGIN_TIME_NOT_SET = 6;
+ ERROR_MULTI_PROVIDER_NOT_CONFIGURED = 7;
+ }
+
+ message FlowResponsesCsvBundle {
+ optional string flowID = 1;
+ optional string galaxyFlowDownloadRequestID = 2;
+ optional string fileName = 3;
+ optional string mimetype = 4;
+ optional bytes fileSHA256 = 5;
+ optional bytes mediaKey = 6;
+ optional bytes fileEncSHA256 = 7;
+ optional string directPath = 8;
+ optional int64 mediaKeyTimestamp = 9;
+ optional uint64 fileLength = 10;
+ }
+
+ message ContactRefreshResponse {
+ repeated string coveredRequestIDs = 1;
+ optional uint64 collectionVersion = 2;
+ optional int64 primaryDurationMS = 3;
+ optional uint32 uniqueContactCount = 4;
+ }
+
+ message BizBroadcastInsightsContactListResponse {
+ optional string campaignID = 1;
+ optional int64 timestampMS = 2;
+ repeated BizBroadcastInsightsContactState contacts = 3;
+ }
+
+ message BizBroadcastInsightsContactState {
+ optional string contactJID = 1;
+ optional InsightDeliveryState state = 2;
+ }
+
+ message HistorySyncChunkRetryResponse {
+ optional HistorySyncType syncType = 1;
+ optional uint32 chunkOrder = 2;
+ optional string requestID = 3;
+ optional HistorySyncChunkRetryResponseCode responseCode = 4;
+ optional bool canRecover = 5;
+ }
+
+ message SyncDSnapshotFatalRecoveryResponse {
+ optional bytes collectionSnapshot = 1;
+ optional bool isCompressed = 2;
+ }
+
+ message CompanionCanonicalUserNonceFetchResponse {
+ optional string nonce = 1;
+ optional string waFbid = 2;
+ optional bool forceRefresh = 3;
+ }
+
+ message CompanionMetaNonceFetchResponse {
+ optional string nonce = 1;
+ }
+
+ message WaffleNonceFetchResponse {
+ optional string nonce = 1;
+ optional string waEntFbid = 2;
+ }
+
+ message FullHistorySyncOnDemandRequestResponse {
+ optional FullHistorySyncOnDemandRequestMetadata requestMetadata = 1;
+ optional FullHistorySyncOnDemandResponseCode responseCode = 2;
+ }
+
+ message PlaceholderMessageResendResponse {
+ optional bytes webMessageInfoBytes = 1;
+ }
+
+ message LinkPreviewResponse {
+ message PaymentLinkPreviewMetadata {
+ optional bool isBusinessVerified = 1;
+ optional string providerName = 2;
+ optional string amount = 3;
+ optional string offset = 4;
+ optional string currency = 5;
+ }
+
+ message LinkPreviewHighQualityThumbnail {
+ optional string directPath = 1;
+ optional string thumbHash = 2;
+ optional string encThumbHash = 3;
+ optional bytes mediaKey = 4;
+ optional int64 mediaKeyTimestampMS = 5;
+ optional int32 thumbWidth = 6;
+ optional int32 thumbHeight = 7;
+ }
+
+ optional string URL = 1;
+ optional string title = 2;
+ optional string description = 3;
+ optional bytes thumbData = 4;
+ optional string matchText = 6;
+ optional string previewType = 7;
+ optional LinkPreviewHighQualityThumbnail hqThumbnail = 8;
+ optional PaymentLinkPreviewMetadata previewMetadata = 9;
+ }
+
+ optional WAMmsRetry.MediaRetryNotification.ResultType mediaUploadResult = 1;
+ optional StickerMessage stickerMessage = 2;
+ optional LinkPreviewResponse linkPreviewResponse = 3;
+ optional PlaceholderMessageResendResponse placeholderMessageResendResponse = 4;
+ optional WaffleNonceFetchResponse waffleNonceFetchRequestResponse = 5;
+ optional FullHistorySyncOnDemandRequestResponse fullHistorySyncOnDemandRequestResponse = 6;
+ optional CompanionMetaNonceFetchResponse companionMetaNonceFetchRequestResponse = 7;
+ optional SyncDSnapshotFatalRecoveryResponse syncdSnapshotFatalRecoveryResponse = 8;
+ optional CompanionCanonicalUserNonceFetchResponse companionCanonicalUserNonceFetchRequestResponse = 9;
+ optional HistorySyncChunkRetryResponse historySyncChunkRetryResponse = 10;
+ optional FlowResponsesCsvBundle flowResponsesCsvBundle = 11;
+ optional BizBroadcastInsightsContactListResponse bizBroadcastInsightsContactListResponse = 12;
+ optional ContactRefreshResponse contactRefreshResponse = 13;
+ }
+
+ optional PeerDataOperationRequestType peerDataOperationRequestType = 1;
+ optional string stanzaID = 2;
+ repeated PeerDataOperationResult peerDataOperationResult = 3;
+}
+
+message PeerDataOperationRequestMessage {
+ message GalaxyFlowAction {
+ enum GalaxyFlowActionType {
+ NOTIFY_LAUNCH = 1;
+ DOWNLOAD_RESPONSES = 2;
+ }
+
+ optional GalaxyFlowActionType type = 1;
+ optional string flowID = 2;
+ optional string stanzaID = 3;
+ optional string galaxyFlowDownloadRequestID = 4;
+ optional string agmID = 5;
+ }
+
+ message BizBroadcastInsightsRefreshRequest {
+ optional string campaignID = 1;
+ }
+
+ message BizBroadcastInsightsContactListRequest {
+ optional string campaignID = 1;
+ }
+
+ message CompanionCanonicalUserNonceFetchRequest {
+ optional string registrationTraceID = 1;
+ }
+
+ message HistorySyncChunkRetryRequest {
+ optional HistorySyncType syncType = 1;
+ optional uint32 chunkOrder = 2;
+ optional string chunkNotificationID = 3;
+ optional bool regenerateChunk = 4;
+ }
+
+ message SyncDCollectionFatalRecoveryRequest {
+ optional string collectionName = 1;
+ optional int64 timestamp = 2;
+ }
+
+ message PlaceholderMessageResendRequest {
+ optional WACommon.MessageKey messageKey = 1;
+ }
+
+ message FullHistorySyncOnDemandRequest {
+ optional FullHistorySyncOnDemandRequestMetadata requestMetadata = 1;
+ optional WACompanionReg.DeviceProps.HistorySyncConfig historySyncConfig = 2;
+ optional FullHistorySyncOnDemandConfig fullHistorySyncOnDemandConfig = 3;
+ }
+
+ message HistorySyncOnDemandRequest {
+ optional string chatJID = 1;
+ optional string oldestMsgID = 2;
+ optional bool oldestMsgFromMe = 3;
+ optional int32 onDemandMsgCount = 4;
+ optional int64 oldestMsgTimestampMS = 5;
+ optional string accountLid = 6;
+ optional bool supportInlineResponse = 7;
+ }
+
+ message RequestUrlPreview {
+ optional string URL = 1;
+ optional bool includeHqThumbnail = 2;
+ }
+
+ message RequestStickerReupload {
+ optional string fileSHA256 = 1;
+ }
+
+ optional PeerDataOperationRequestType peerDataOperationRequestType = 1;
+ repeated RequestStickerReupload requestStickerReupload = 2;
+ repeated RequestUrlPreview requestURLPreview = 3;
+ optional HistorySyncOnDemandRequest historySyncOnDemandRequest = 4;
+ repeated PlaceholderMessageResendRequest placeholderMessageResendRequest = 5;
+ optional FullHistorySyncOnDemandRequest fullHistorySyncOnDemandRequest = 6;
+ optional SyncDCollectionFatalRecoveryRequest syncdCollectionFatalRecoveryRequest = 7;
+ optional HistorySyncChunkRetryRequest historySyncChunkRetryRequest = 8;
+ optional GalaxyFlowAction galaxyFlowAction = 9;
+ optional CompanionCanonicalUserNonceFetchRequest companionCanonicalUserNonceFetchRequest = 10;
+ optional BizBroadcastInsightsContactListRequest bizBroadcastInsightsContactListRequest = 11;
+ optional BizBroadcastInsightsRefreshRequest bizBroadcastInsightsRefreshRequest = 12;
+}
+
+message SharedDeviceContactHashKey {
+ enum Kind {
+ UNKNOWN = 0;
+ LID = 1;
+ PHONE_NUMBER = 2;
+ }
+
+ optional uint32 epoch = 1;
+ optional Kind kind = 2;
+ optional bytes keyData = 3;
+}
+
+message RequestWelcomeMessageMetadata {
+ enum WelcomeTrigger {
+ CHAT_OPEN = 0;
+ COMPANION_PAIRING = 1;
+ }
+
+ enum LocalChatState {
+ EMPTY = 0;
+ NON_EMPTY = 1;
+ }
+
+ optional LocalChatState localChatState = 1;
+ optional WelcomeTrigger welcomeTrigger = 2;
+ optional WAWebProtobufsAICommon.BotAgentMetadata botAgentMetadata = 3;
+}
+
+message ProtocolMessage {
+ enum Type {
+ REVOKE = 0;
+ EPHEMERAL_SETTING = 3;
+ EPHEMERAL_SYNC_RESPONSE = 4;
+ HISTORY_SYNC_NOTIFICATION = 5;
+ APP_STATE_SYNC_KEY_SHARE = 6;
+ APP_STATE_SYNC_KEY_REQUEST = 7;
+ MSG_FANOUT_BACKFILL_REQUEST = 8;
+ INITIAL_SECURITY_NOTIFICATION_SETTING_SYNC = 9;
+ APP_STATE_FATAL_EXCEPTION_NOTIFICATION = 10;
+ SHARE_PHONE_NUMBER = 11;
+ MESSAGE_EDIT = 14;
+ PEER_DATA_OPERATION_REQUEST_MESSAGE = 16;
+ PEER_DATA_OPERATION_REQUEST_RESPONSE_MESSAGE = 17;
+ REQUEST_WELCOME_MESSAGE = 18;
+ BOT_FEEDBACK_MESSAGE = 19;
+ MEDIA_NOTIFY_MESSAGE = 20;
+ CLOUD_API_THREAD_CONTROL_NOTIFICATION = 21;
+ LID_MIGRATION_MAPPING_SYNC = 22;
+ REMINDER_MESSAGE = 23;
+ BOT_MEMU_ONBOARDING_MESSAGE = 24;
+ STATUS_MENTION_MESSAGE = 25;
+ STOP_GENERATION_MESSAGE = 26;
+ LIMIT_SHARING = 27;
+ AI_PSI_METADATA = 28;
+ AI_QUERY_FANOUT = 29;
+ GROUP_MEMBER_LABEL_CHANGE = 30;
+ AI_MEDIA_COLLECTION_MESSAGE = 31;
+ MESSAGE_UNSCHEDULE = 32;
+ CHAT_THEME_SETTING = 34;
+ AI_METADATA_OPERATION = 35;
+ MARK_AS_VERIFIED_ACTION = 36;
+ COEX_STATE_SYNC = 37;
+ ACP2_SETTING = 39;
+ SHARED_DEVICE_CONTACT_HASH_KEY_SHARE = 40;
+ SHARED_DEVICE_CONTACT_HASH_KEY_REQUEST = 41;
+ }
+
+ optional WACommon.MessageKey key = 1;
+ optional Type type = 2;
+ optional uint32 ephemeralExpiration = 4;
+ optional int64 ephemeralSettingTimestamp = 5;
+ optional HistorySyncNotification historySyncNotification = 6;
+ optional AppStateSyncKeyShare appStateSyncKeyShare = 7;
+ optional AppStateSyncKeyRequest appStateSyncKeyRequest = 8;
+ optional InitialSecurityNotificationSettingSync initialSecurityNotificationSettingSync = 9;
+ optional AppStateFatalExceptionNotification appStateFatalExceptionNotification = 10;
+ optional DisappearingMode disappearingMode = 11;
+ optional Message editedMessage = 14;
+ optional int64 timestampMS = 15;
+ optional PeerDataOperationRequestMessage peerDataOperationRequestMessage = 16;
+ optional PeerDataOperationRequestResponseMessage peerDataOperationRequestResponseMessage = 17;
+ optional WAWebProtobufsAICommon.BotFeedbackMessage botFeedbackMessage = 18;
+ optional string invokerJID = 19;
+ optional RequestWelcomeMessageMetadata requestWelcomeMessageMetadata = 20;
+ optional MediaNotifyMessage mediaNotifyMessage = 21;
+ optional CloudAPIThreadControlNotification cloudApiThreadControlNotification = 22;
+ optional LIDMigrationMappingSyncMessage lidMigrationMappingSyncMessage = 23;
+ optional WACommon.LimitSharing limitSharing = 24;
+ optional bytes aiPsiMetadata = 25;
+ optional AIQueryFanout aiQueryFanout = 26;
+ optional MemberLabel memberLabel = 27;
+ optional WAWebProtobufsAICommon.AIMediaCollectionMessage aiMediaCollectionMessage = 28;
+ optional uint32 afterReadDuration = 29;
+ optional ChatThemeSetting chatThemeSetting = 30;
+ optional WAWebProtobufsAICommon.AIMetadataOperation aiMetadataOperation = 31;
+ optional MarkAsVerifiedAction markAsVerifiedAction = 32;
+ optional WAWebProtobufsServerSync.CoexStateSync coexStateSync = 33;
+ optional WACommon.ACP2Setting acp2Setting = 35;
+ optional SharedDeviceContactHashKeyShare sharedDeviceContactHashKeyShare = 36;
+ optional SharedDeviceContactHashKeyRequest sharedDeviceContactHashKeyRequest = 37;
+ repeated string additionalPromptIDs = 38;
+}
+
+message CloudAPIThreadControlNotification {
+ enum CloudAPIThreadControl {
+ UNKNOWN = 0;
+ CONTROL_PASSED = 1;
+ CONTROL_TAKEN = 2;
+ INFO = 3;
+ }
+
+ message CloudAPIThreadControlNotificationContent {
+ optional string handoffNotificationText = 1;
+ optional string extraJSON = 2;
+ }
+
+ optional CloudAPIThreadControl status = 1;
+ optional int64 senderNotificationTimestampMS = 2;
+ optional string consumerLid = 3;
+ optional string consumerPhoneNumber = 4;
+ optional CloudAPIThreadControlNotificationContent notificationContent = 5;
+ optional bool shouldSuppressNotification = 6;
+}
+
+message VideoMessage {
+ enum VideoSourceType {
+ USER_VIDEO = 0;
+ AI_GENERATED = 1;
+ }
+
+ enum Attribution {
+ NONE = 0;
+ GIPHY = 1;
+ TENOR = 2;
+ KLIPY = 3;
+ }
+
+ optional string URL = 1;
+ optional string mimetype = 2;
+ optional bytes fileSHA256 = 3;
+ optional uint64 fileLength = 4;
+ optional uint32 seconds = 5;
+ optional bytes mediaKey = 6;
+ optional string caption = 7;
+ optional bool gifPlayback = 8;
+ optional uint32 height = 9;
+ optional uint32 width = 10;
+ optional bytes fileEncSHA256 = 11;
+ repeated InteractiveAnnotation interactiveAnnotations = 12;
+ optional string directPath = 13;
+ optional int64 mediaKeyTimestamp = 14;
+ optional bytes JPEGThumbnail = 16;
+ optional ContextInfo contextInfo = 17;
+ optional bytes streamingSidecar = 18;
+ optional Attribution gifAttribution = 19;
+ optional bool viewOnce = 20;
+ optional string thumbnailDirectPath = 21;
+ optional bytes thumbnailSHA256 = 22;
+ optional bytes thumbnailEncSHA256 = 23;
+ optional string staticURL = 24;
+ repeated InteractiveAnnotation annotations = 25;
+ optional string accessibilityLabel = 26;
+ repeated ProcessedVideo processedVideos = 27;
+ optional uint32 externalShareFullVideoDurationInSeconds = 28;
+ optional uint64 motionPhotoPresentationOffsetMS = 29;
+ optional string metadataURL = 30;
+ optional VideoSourceType videoSourceType = 31;
+ optional string dashManifestURL = 33;
+ optional int64 smartThumbnailTS = 34;
+}
+
+message MusicMessage {
+ enum MusicMessageStyle {
+ UNKNOWN = 0;
+ VINYL = 1;
+ MESSAGE_BUBBLE = 2;
+ LYRICS = 3;
+ }
+
+ optional EmbeddedMusic embeddedMusic = 1;
+ optional string songUri = 2;
+ optional string artworkUri = 3;
+ optional int32 style = 4;
+ optional ContextInfo contextInfo = 5;
+}
+
+message ExtendedTextMessage {
+ enum InviteLinkGroupType {
+ DEFAULT = 0;
+ PARENT = 1;
+ SUB = 2;
+ DEFAULT_SUB = 3;
+ }
+
+ enum PreviewType {
+ NONE = 0;
+ VIDEO = 1;
+ PLACEHOLDER = 4;
+ IMAGE = 5;
+ PAYMENT_LINKS = 6;
+ PROFILE = 7;
+ }
+
+ enum FontType {
+ SYSTEM = 0;
+ SYSTEM_TEXT = 1;
+ FB_SCRIPT = 2;
+ SYSTEM_BOLD = 6;
+ MORNINGBREEZE_REGULAR = 7;
+ CALISTOGA_REGULAR = 8;
+ EXO2_EXTRABOLD = 9;
+ COURIERPRIME_BOLD = 10;
+ }
+
+ optional string text = 1;
+ optional string matchedText = 2;
+ optional string description = 5;
+ optional string title = 6;
+ optional fixed32 textArgb = 7;
+ optional fixed32 backgroundArgb = 8;
+ optional FontType font = 9;
+ optional PreviewType previewType = 10;
+ optional bytes JPEGThumbnail = 16;
+ optional ContextInfo contextInfo = 17;
+ optional bool doNotPlayInline = 18;
+ optional string thumbnailDirectPath = 19;
+ optional bytes thumbnailSHA256 = 20;
+ optional bytes thumbnailEncSHA256 = 21;
+ optional bytes mediaKey = 22;
+ optional int64 mediaKeyTimestamp = 23;
+ optional uint32 thumbnailHeight = 24;
+ optional uint32 thumbnailWidth = 25;
+ optional InviteLinkGroupType inviteLinkGroupType = 26;
+ optional string inviteLinkParentGroupSubjectV2 = 27;
+ optional bytes inviteLinkParentGroupThumbnailV2 = 28;
+ optional InviteLinkGroupType inviteLinkGroupTypeV2 = 29;
+ optional bool viewOnce = 30;
+ optional uint32 videoHeight = 31;
+ optional uint32 videoWidth = 32;
+ optional MMSThumbnailMetadata faviconMmsMetadata = 33;
+ optional LinkPreviewMetadata linkPreviewMetadata = 34;
+ optional PaymentLinkMetadata paymentLinkMetadata = 35;
+ repeated VideoEndCard endCardTiles = 36;
+ optional string videoContentURL = 37;
+ optional EmbeddedMusic musicMetadata = 38;
+ optional PaymentExtendedMetadata paymentExtendedMetadata = 39;
+}
+
+message LinkPreviewMetadata {
+ enum SocialMediaPostType {
+ NONE = 0;
+ REEL = 1;
+ LIVE_VIDEO = 2;
+ LONG_VIDEO = 3;
+ SINGLE_IMAGE = 4;
+ CAROUSEL = 5;
+ }
+
+ optional PaymentLinkMetadata paymentLinkMetadata = 1;
+ optional URLMetadata urlMetadata = 2;
+ optional uint32 fbExperimentID = 3;
+ optional uint32 linkMediaDuration = 4;
+ optional SocialMediaPostType socialMediaPostType = 5;
+ optional bool linkInlineVideoMuted = 6;
+ optional string videoContentURL = 7;
+ optional EmbeddedMusic musicMetadata = 8;
+ optional string videoContentCaption = 9;
+}
+
+message PaymentLinkMetadata {
+ message PaymentLinkHeader {
+ enum PaymentLinkHeaderType {
+ LINK_PREVIEW = 0;
+ ORDER = 1;
+ }
+
+ optional PaymentLinkHeaderType headerType = 1;
+ }
+
+ message PaymentLinkProvider {
+ optional string paramsJSON = 1;
+ }
+
+ message PaymentLinkButton {
+ optional string displayText = 1;
+ }
+
+ optional PaymentLinkButton button = 1;
+ optional PaymentLinkHeader header = 2;
+ optional PaymentLinkProvider provider = 3;
+}
+
+message StatusNotificationMessage {
+ enum StatusNotificationType {
+ UNKNOWN = 0;
+ STATUS_ADD_YOURS = 1;
+ STATUS_RESHARE = 2;
+ STATUS_QUESTION_ANSWER_RESHARE = 3;
+ STATUS_GROUP_STATUS_REPLY = 4;
+ }
+
+ optional WACommon.MessageKey responseMessageKey = 1;
+ optional WACommon.MessageKey originalMessageKey = 2;
+ optional StatusNotificationType type = 3;
+}
+
+message InvoiceMessage {
+ enum AttachmentType {
+ IMAGE = 0;
+ PDF = 1;
+ }
+
+ optional string note = 1;
+ optional string token = 2;
+ optional AttachmentType attachmentType = 3;
+ optional string attachmentMimetype = 4;
+ optional bytes attachmentMediaKey = 5;
+ optional int64 attachmentMediaKeyTimestamp = 6;
+ optional bytes attachmentFileSHA256 = 7;
+ optional bytes attachmentFileEncSHA256 = 8;
+ optional string attachmentDirectPath = 9;
+ optional bytes attachmentJPEGThumbnail = 10;
+}
+
+message ImageMessage {
+ enum ImageSourceType {
+ USER_IMAGE = 0;
+ AI_GENERATED = 1;
+ AI_MODIFIED = 2;
+ RASTERIZED_TEXT_STATUS = 3;
+ }
+
+ optional string URL = 1;
+ optional string mimetype = 2;
+ optional string caption = 3;
+ optional bytes fileSHA256 = 4;
+ optional uint64 fileLength = 5;
+ optional uint32 height = 6;
+ optional uint32 width = 7;
+ optional bytes mediaKey = 8;
+ optional bytes fileEncSHA256 = 9;
+ repeated InteractiveAnnotation interactiveAnnotations = 10;
+ optional string directPath = 11;
+ optional int64 mediaKeyTimestamp = 12;
+ optional bytes JPEGThumbnail = 16;
+ optional ContextInfo contextInfo = 17;
+ optional bytes firstScanSidecar = 18;
+ optional uint32 firstScanLength = 19;
+ optional uint32 experimentGroupID = 20;
+ optional bytes scansSidecar = 21;
+ repeated uint32 scanLengths = 22;
+ optional bytes midQualityFileSHA256 = 23;
+ optional bytes midQualityFileEncSHA256 = 24;
+ optional bool viewOnce = 25;
+ optional string thumbnailDirectPath = 26;
+ optional bytes thumbnailSHA256 = 27;
+ optional bytes thumbnailEncSHA256 = 28;
+ optional string staticURL = 29;
+ repeated InteractiveAnnotation annotations = 30;
+ optional ImageSourceType imageSourceType = 31;
+ optional string accessibilityLabel = 32;
+ optional string qrURL = 34;
+}
+
+message ContextInfo {
+ enum CrossAppSource {
+ CROSS_APP_SOURCE_UNKNOWN = 0;
+ CROSS_APP_SOURCE_INSTAGRAM = 1;
+ CROSS_APP_SOURCE_FACEBOOK = 2;
+ }
+
+ enum QuotedType {
+ EXPLICIT = 0;
+ AUTO = 1;
+ }
+
+ enum ForwardOrigin {
+ UNKNOWN = 0;
+ CHAT = 1;
+ STATUS = 2;
+ CHANNELS = 3;
+ META_AI = 4;
+ UGC = 5;
+ }
+
+ enum StatusSourceType {
+ IMAGE = 0;
+ VIDEO = 1;
+ GIF = 2;
+ AUDIO = 3;
+ TEXT = 4;
+ MUSIC_STANDALONE = 5;
+ }
+
+ enum PairedMediaType {
+ NOT_PAIRED_MEDIA = 0;
+ SD_VIDEO_PARENT = 1;
+ HD_VIDEO_CHILD = 2;
+ SD_IMAGE_PARENT = 3;
+ HD_IMAGE_CHILD = 4;
+ MOTION_PHOTO_PARENT = 5;
+ MOTION_PHOTO_CHILD = 6;
+ HEVC_VIDEO_PARENT = 7;
+ HEVC_VIDEO_CHILD = 8;
+ AV1_VIDEO_PARENT = 9;
+ AV1_VIDEO_CHILD = 10;
+ STREAMED_VIDEO_PARENT = 11;
+ STREAMED_VIDEO_CHILD = 12;
+ }
+
+ enum StatusAttributionType {
+ NONE = 0;
+ RESHARED_FROM_MENTION = 1;
+ RESHARED_FROM_POST = 2;
+ RESHARED_FROM_POST_MANY_TIMES = 3;
+ FORWARDED_FROM_STATUS = 4;
+ }
+
+ message BusinessInteractionPills {
+ enum EntryPoint {
+ ENTRY_POINT_UNKNOWN = 0;
+ P2P_LINK_SHARE = 1;
+ CONTACT_CARD_SHARING = 2;
+ PHONE_NUMBER = 3;
+ STATUS = 4;
+ IN_THREAD_CONTEXT_CARD = 5;
+ }
+
+ enum PillType {
+ UNKNOWN = 0;
+ VIEW_BUSINESS = 1;
+ CHAT = 2;
+ CALL = 3;
+ CATALOG = 4;
+ CHANNEL = 5;
+ BOOK_APPOINTMENT = 6;
+ OFFERS = 7;
+ BESTSELLERS = 8;
+ MENU = 9;
+ ABOUT = 10;
+ SHOP = 11;
+ ORDER = 12;
+ }
+
+ message UnauthenticatedBusinessMetadata {
+ optional string businessName = 1;
+ optional string businessCategory = 2;
+ optional bool businessIsOpen = 3;
+ optional int64 businessIsOpenSnapshotMS = 4;
+ }
+
+ message SignedPayload {
+ optional string verifiedName = 1;
+ repeated Pill pills = 2;
+ }
+
+ message Pill {
+ optional PillType pillType = 1;
+ optional string actionURL = 2;
+ }
+
+ optional string businessJID = 1;
+ repeated Pill pills = 2;
+ optional EntryPoint entryPoint = 3;
+ optional bytes signedPayload = 4;
+ optional WAWebProtobufsAICommon.BotSignatureVerificationMetadata signatureEnvelope = 5;
+ optional UnauthenticatedBusinessMetadata unauthenticatedBusinessMetadata = 6;
+ }
+
+ message StatusAudienceMetadata {
+ enum AudienceType {
+ UNKNOWN = 0;
+ CLOSE_FRIENDS = 1;
+ }
+
+ optional AudienceType audienceType = 1;
+ optional string listName = 2;
+ optional string listEmoji = 3;
+ }
+
+ message DataSharingContext {
+ enum DataSharingFlags {
+ SHOW_MM_DISCLOSURE_ON_CLICK = 1;
+ SHOW_MM_DISCLOSURE_ON_READ = 2;
+ }
+
+ message Parameters {
+ optional string key = 1;
+ optional string stringData = 2;
+ optional int64 intData = 3;
+ optional float floatData = 4;
+ optional Parameters contents = 5;
+ }
+
+ optional bool showMmDisclosure = 1;
+ optional string encryptedSignalTokenConsented = 2;
+ repeated Parameters parameters = 3;
+ optional int32 dataSharingFlags = 4;
+ }
+
+ message ForwardedNewsletterMessageInfo {
+ enum ContentType {
+ UPDATE = 1;
+ UPDATE_CARD = 2;
+ LINK_CARD = 3;
+ }
+
+ optional string newsletterJID = 1;
+ optional int32 serverMessageID = 2;
+ optional string newsletterName = 3;
+ optional ContentType contentType = 4;
+ optional string accessibilityText = 5;
+ optional string profileName = 6;
+ }
+
+ message ExternalAdReplyInfo {
+ enum AdType {
+ CTWA = 0;
+ CAWC = 1;
+ }
+
+ enum MediaType {
+ NONE = 0;
+ IMAGE = 1;
+ VIDEO = 2;
+ }
+
+ optional string title = 1;
+ optional string body = 2;
+ optional MediaType mediaType = 3;
+ optional string thumbnailURL = 4;
+ optional string mediaURL = 5;
+ optional bytes thumbnail = 6;
+ optional string sourceType = 7;
+ optional string sourceID = 8;
+ optional string sourceURL = 9;
+ optional bool containsAutoReply = 10;
+ optional bool renderLargerThumbnail = 11;
+ optional bool showAdAttribution = 12;
+ optional string ctwaClid = 13;
+ optional string ref = 14;
+ optional bool clickToWhatsappCall = 15;
+ optional bool adContextPreviewDismissed = 16;
+ optional string sourceApp = 17;
+ optional bool automatedGreetingMessageShown = 18;
+ optional string greetingMessageBody = 19;
+ optional string ctaPayload = 20;
+ optional bool disableNudge = 21;
+ optional string originalImageURL = 22;
+ optional string automatedGreetingMessageCtaType = 23;
+ optional bool wtwaAdFormat = 24;
+ optional AdType adType = 25;
+ optional string wtwaWebsiteURL = 26;
+ optional string adPreviewURL = 27;
+ optional bool containsCtwaFlowsAutoReply = 28;
+ optional int32 agmThumbnailStrategy = 29;
+ optional int32 agmTitleStrategy = 30;
+ optional int32 agmSubtitleStrategy = 31;
+ optional int32 agmHeaderInteractionStrategy = 32;
+ optional bool containsCtwaFlowsAutoLabel = 33;
+ optional string productID = 34;
+ optional bool containsCtwaPromo = 35;
+ optional string ctwaPromoResponseID = 36;
+ optional string ctwaPromoOfferID = 37;
+ optional string ctwaPromoAdEntryID = 38;
+ optional uint64 ctwaPromoResponseExpiresAtSeconds = 39;
+ optional uint32 ctwaPromoSchemaVersion = 40;
+ optional string ctwaPromoAdgroupID = 41;
+ }
+
+ message AdReplyInfo {
+ enum MediaType {
+ NONE = 0;
+ IMAGE = 1;
+ VIDEO = 2;
+ }
+
+ optional string advertiserName = 1;
+ optional MediaType mediaType = 2;
+ optional bytes JPEGThumbnail = 16;
+ optional string caption = 17;
+ }
+
+ message InstagramThreadLink {
+ optional string URL = 1;
+ }
+
+ message PartiallySelectedContent {
+ optional string text = 1;
+ }
+
+ message FeatureEligibilities {
+ optional bool cannotBeReactedTo = 1;
+ optional bool cannotBeRanked = 2;
+ optional bool canRequestFeedback = 3;
+ optional bool canBeReshared = 4;
+ optional bool canReceiveMultiReact = 5;
+ }
+
+ message QuestionReplyQuotedMessage {
+ optional int32 serverQuestionID = 1;
+ optional Message quotedQuestion = 2;
+ optional Message quotedResponse = 3;
+ }
+
+ message UTMInfo {
+ optional string utmSource = 1;
+ optional string utmCampaign = 2;
+ }
+
+ message BusinessMessageForwardInfo {
+ optional string businessOwnerJID = 1;
+ }
+
+ optional string stanzaID = 1;
+ optional string participant = 2;
+ optional Message quotedMessage = 3;
+ optional string remoteJID = 4;
+ repeated string mentionedJID = 15;
+ optional string conversionSource = 18;
+ optional bytes conversionData = 19;
+ optional uint32 conversionDelaySeconds = 20;
+ optional uint32 forwardingScore = 21;
+ optional bool isForwarded = 22;
+ optional AdReplyInfo quotedAd = 23;
+ optional WACommon.MessageKey placeholderKey = 24;
+ optional uint32 expiration = 25;
+ optional int64 ephemeralSettingTimestamp = 26;
+ optional bytes ephemeralSharedSecret = 27;
+ optional ExternalAdReplyInfo externalAdReply = 28;
+ optional string entryPointConversionSource = 29;
+ optional string entryPointConversionApp = 30;
+ optional uint32 entryPointConversionDelaySeconds = 31;
+ optional DisappearingMode disappearingMode = 32;
+ optional ActionLink actionLink = 33;
+ optional string groupSubject = 34;
+ optional string parentGroupJID = 35;
+ optional string trustBannerType = 37;
+ optional uint32 trustBannerAction = 38;
+ optional bool isSampled = 39;
+ repeated GroupMention groupMentions = 40;
+ optional UTMInfo utm = 41;
+ optional ForwardedNewsletterMessageInfo forwardedNewsletterMessageInfo = 43;
+ optional BusinessMessageForwardInfo businessMessageForwardInfo = 44;
+ optional string smbClientCampaignID = 45;
+ optional string smbServerCampaignID = 46;
+ optional DataSharingContext dataSharingContext = 47;
+ optional bool alwaysShowAdAttribution = 48;
+ optional FeatureEligibilities featureEligibilities = 49;
+ optional string entryPointConversionExternalSource = 50;
+ optional string entryPointConversionExternalMedium = 51;
+ optional string ctwaSignals = 54;
+ optional bytes ctwaPayload = 55;
+ optional WAWebProtobufsAICommon.ForwardedAIBotMessageInfo forwardedAiBotMessageInfo = 56;
+ optional StatusAttributionType statusAttributionType = 57;
+ optional UrlTrackingMap urlTrackingMap = 58;
+ optional PairedMediaType pairedMediaType = 59;
+ optional uint32 rankingVersion = 60;
+ optional MemberLabel memberLabel = 62;
+ optional bool isQuestion = 63;
+ optional StatusSourceType statusSourceType = 64;
+ repeated WAStatusAttributions.StatusAttribution statusAttributions = 65;
+ optional bool isGroupStatus = 66;
+ optional ForwardOrigin forwardOrigin = 67;
+ optional QuestionReplyQuotedMessage questionReplyQuotedMessage = 68;
+ optional StatusAudienceMetadata statusAudienceMetadata = 69;
+ optional uint32 nonJIDMentions = 70;
+ optional QuotedType quotedType = 71;
+ optional WAWebProtobufsAICommon.BotMessageSharingInfo botMessageSharingInfo = 72;
+ optional bool isSpoiler = 73;
+ optional MediaDomainInfo mediaDomainInfo = 74;
+ optional PartiallySelectedContent partiallySelectedContent = 75;
+ optional uint32 afterReadDuration = 76;
+ optional CrossAppSource crossAppSource = 77;
+ optional BusinessInteractionPills businessInteractionPills = 78;
+ optional string posterStatusID = 79;
+ optional InstagramThreadLink instagramThreadLink = 80;
+ optional WAWebProtobufsAICommon.AIProvenance aiProvenance = 81;
+ repeated uint32 experienceIDs = 82 [packed=true];
+ optional string partnerDeepLinkToken = 83;
+}
+
+message MessageAssociation {
+ enum AssociationType {
+ UNKNOWN = 0;
+ MEDIA_ALBUM = 1;
+ BOT_PLUGIN = 2;
+ EVENT_COVER_IMAGE = 3;
+ STATUS_POLL = 4;
+ HD_VIDEO_DUAL_UPLOAD = 5;
+ STATUS_EXTERNAL_RESHARE = 6;
+ MEDIA_POLL = 7;
+ STATUS_ADD_YOURS = 8;
+ STATUS_NOTIFICATION = 9;
+ HD_IMAGE_DUAL_UPLOAD = 10;
+ STICKER_ANNOTATION = 11;
+ MOTION_PHOTO = 12;
+ STATUS_LINK_ACTION = 13;
+ VIEW_ALL_REPLIES = 14;
+ STATUS_ADD_YOURS_AI_IMAGINE = 15;
+ STATUS_QUESTION = 16;
+ STATUS_ADD_YOURS_DIWALI = 17;
+ STATUS_REACTION = 18;
+ HEVC_VIDEO_DUAL_UPLOAD = 19;
+ POLL_ADD_OPTION = 20;
+ AV1_VIDEO_DUAL_UPLOAD = 21;
+ STREAMED_HD_VIDEO_DUAL_UPLOAD = 22;
+ }
+
+ optional AssociationType associationType = 1;
+ optional WACommon.MessageKey parentMessageKey = 2;
+ optional int32 messageIndex = 3;
+}
+
+message ThreadID {
+ enum ThreadType {
+ UNKNOWN = 0;
+ VIEW_REPLIES = 1;
+ AI_THREAD = 2;
+ }
+
+ optional ThreadType threadType = 1;
+ optional WACommon.MessageKey threadKey = 2;
+}
+
+message MessageContextInfo {
+ enum MessageAddonExpiryType {
+ STATIC = 1;
+ DEPENDENT_ON_PARENT = 2;
+ }
+
+ optional DeviceListMetadata deviceListMetadata = 1;
+ optional int32 deviceListMetadataVersion = 2;
+ optional bytes messageSecret = 3;
+ optional bytes paddingBytes = 4;
+ optional uint32 messageAddOnDurationInSecs = 5;
+ optional bytes botMessageSecret = 6;
+ optional WAWebProtobufsAICommon.BotMetadata botMetadata = 7;
+ optional int32 reportingTokenVersion = 8;
+ optional MessageAddonExpiryType messageAddOnExpiryType = 9;
+ optional MessageAssociation messageAssociation = 10;
+ optional bool capiCreatedGroup = 11;
+ optional string supportPayload = 12;
+ optional WACommon.LimitSharing limitSharing = 13;
+ optional WACommon.LimitSharing limitSharingV2 = 14;
+ repeated ThreadID threadID = 15;
+ optional WebLinkRenderConfig weblinkRenderConfig = 16;
+ optional bytes teeBotMetadata = 17;
+ optional WAWebProtobufsAea.NonE2EEAttestation accountEncryptionAttestation = 18;
+ optional bytes associatedPrimaryIdentityKey = 19;
+ optional string teeContextAnchorMessageID = 20;
+ optional WACommon.ACP2Setting acp2Setting = 21;
+}
+
+message InteractiveAnnotation {
+ enum StatusLinkType {
+ RASTERIZED_LINK_PREVIEW = 1;
+ RASTERIZED_LINK_TRUNCATED = 2;
+ RASTERIZED_LINK_FULL_URL = 3;
+ }
+
+ oneof action {
+ Location location = 2;
+ ContextInfo.ForwardedNewsletterMessageInfo newsletter = 3;
+ bool embeddedAction = 6;
+ TapLinkAction tapAction = 7;
+ }
+
+ repeated Point polygonVertices = 1;
+ optional bool shouldSkipConfirmation = 4;
+ optional EmbeddedContent embeddedContent = 5;
+ optional StatusLinkType statusLinkType = 8;
+}
+
+message HydratedTemplateButton {
+ message HydratedURLButton {
+ enum WebviewPresentationType {
+ FULL = 1;
+ TALL = 2;
+ COMPACT = 3;
+ }
+
+ optional string displayText = 1;
+ optional string URL = 2;
+ optional string consentedUsersURL = 3;
+ optional WebviewPresentationType webviewPresentation = 4;
+ }
+
+ message HydratedCallButton {
+ optional string displayText = 1;
+ optional string phoneNumber = 2;
+ }
+
+ message HydratedQuickReplyButton {
+ optional string displayText = 1;
+ optional string ID = 2;
+ }
+
+ oneof hydratedButton {
+ HydratedQuickReplyButton quickReplyButton = 1;
+ HydratedURLButton urlButton = 2;
+ HydratedCallButton callButton = 3;
+ }
+
+ optional uint32 index = 4;
+}
+
+message PaymentBackground {
+ enum Type {
+ UNKNOWN = 0;
+ DEFAULT = 1;
+ }
+
+ message MediaData {
+ optional bytes mediaKey = 1;
+ optional int64 mediaKeyTimestamp = 2;
+ optional bytes fileSHA256 = 3;
+ optional bytes fileEncSHA256 = 4;
+ optional string directPath = 5;
+ }
+
+ optional string ID = 1;
+ optional uint64 fileLength = 2;
+ optional uint32 width = 3;
+ optional uint32 height = 4;
+ optional string mimetype = 5;
+ optional fixed32 placeholderArgb = 6;
+ optional fixed32 textArgb = 7;
+ optional fixed32 subtextArgb = 8;
+ optional MediaData mediaData = 9;
+ optional Type type = 10;
+}
+
+message DisappearingMode {
+ enum Trigger {
+ UNKNOWN = 0;
+ CHAT_SETTING = 1;
+ ACCOUNT_SETTING = 2;
+ BULK_CHANGE = 3;
+ BIZ_SUPPORTS_FB_HOSTING = 4;
+ UNKNOWN_GROUPS = 5;
+ }
+
+ enum Initiator {
+ CHANGED_IN_CHAT = 0;
+ INITIATED_BY_ME = 1;
+ INITIATED_BY_OTHER = 2;
+ BIZ_UPGRADE_FB_HOSTING = 3;
+ }
+
+ optional Initiator initiator = 1;
+ optional Trigger trigger = 2;
+ optional string initiatorDeviceJID = 3;
+ optional bool initiatedByMe = 4;
+}
+
+message ProcessedVideo {
+ enum VideoQuality {
+ UNDEFINED = 0;
+ LOW = 1;
+ MID = 2;
+ HIGH = 3;
+ }
+
+ optional string directPath = 1;
+ optional bytes fileSHA256 = 2;
+ optional uint32 height = 3;
+ optional uint32 width = 4;
+ optional uint64 fileLength = 5;
+ optional uint32 bitrate = 6;
+ optional VideoQuality quality = 7;
+ repeated string capabilities = 8;
+}
+
+message Message {
+ optional string conversation = 1;
+ optional SenderKeyDistributionMessage senderKeyDistributionMessage = 2;
+ optional ImageMessage imageMessage = 3;
+ optional ContactMessage contactMessage = 4;
+ optional LocationMessage locationMessage = 5;
+ optional ExtendedTextMessage extendedTextMessage = 6;
+ optional DocumentMessage documentMessage = 7;
+ optional AudioMessage audioMessage = 8;
+ optional VideoMessage videoMessage = 9;
+ optional Call call = 10;
+ optional Chat chat = 11;
+ optional ProtocolMessage protocolMessage = 12;
+ optional ContactsArrayMessage contactsArrayMessage = 13;
+ optional HighlyStructuredMessage highlyStructuredMessage = 14;
+ optional SenderKeyDistributionMessage fastRatchetKeySenderKeyDistributionMessage = 15;
+ optional SendPaymentMessage sendPaymentMessage = 16;
+ optional LiveLocationMessage liveLocationMessage = 18;
+ optional RequestPaymentMessage requestPaymentMessage = 22;
+ optional DeclinePaymentRequestMessage declinePaymentRequestMessage = 23;
+ optional CancelPaymentRequestMessage cancelPaymentRequestMessage = 24;
+ optional TemplateMessage templateMessage = 25;
+ optional StickerMessage stickerMessage = 26;
+ optional GroupInviteMessage groupInviteMessage = 28;
+ optional TemplateButtonReplyMessage templateButtonReplyMessage = 29;
+ optional ProductMessage productMessage = 30;
+ optional DeviceSentMessage deviceSentMessage = 31;
+ optional MessageContextInfo messageContextInfo = 35;
+ optional ListMessage listMessage = 36;
+ optional FutureProofMessage viewOnceMessage = 37;
+ optional OrderMessage orderMessage = 38;
+ optional ListResponseMessage listResponseMessage = 39;
+ optional FutureProofMessage ephemeralMessage = 40;
+ optional InvoiceMessage invoiceMessage = 41;
+ optional ButtonsMessage buttonsMessage = 42;
+ optional ButtonsResponseMessage buttonsResponseMessage = 43;
+ optional PaymentInviteMessage paymentInviteMessage = 44;
+ optional InteractiveMessage interactiveMessage = 45;
+ optional ReactionMessage reactionMessage = 46;
+ optional StickerSyncRMRMessage stickerSyncRmrMessage = 47;
+ optional InteractiveResponseMessage interactiveResponseMessage = 48;
+ optional PollCreationMessage pollCreationMessage = 49;
+ optional PollUpdateMessage pollUpdateMessage = 50;
+ optional KeepInChatMessage keepInChatMessage = 51;
+ optional FutureProofMessage documentWithCaptionMessage = 53;
+ optional RequestPhoneNumberMessage requestPhoneNumberMessage = 54;
+ optional FutureProofMessage viewOnceMessageV2 = 55;
+ optional EncReactionMessage encReactionMessage = 56;
+ optional FutureProofMessage editedMessage = 58;
+ optional FutureProofMessage viewOnceMessageV2Extension = 59;
+ optional PollCreationMessage pollCreationMessageV2 = 60;
+ optional ScheduledCallCreationMessage scheduledCallCreationMessage = 61;
+ optional FutureProofMessage groupMentionedMessage = 62;
+ optional PinInChatMessage pinInChatMessage = 63;
+ optional PollCreationMessage pollCreationMessageV3 = 64;
+ optional ScheduledCallEditMessage scheduledCallEditMessage = 65;
+ optional VideoMessage ptvMessage = 66;
+ optional FutureProofMessage botInvokeMessage = 67;
+ optional CallLogMessage callLogMesssage = 69;
+ optional MessageHistoryBundle messageHistoryBundle = 70;
+ optional EncCommentMessage encCommentMessage = 71;
+ optional BCallMessage bcallMessage = 72;
+ optional FutureProofMessage lottieStickerMessage = 74;
+ optional EventMessage eventMessage = 75;
+ optional EncEventResponseMessage encEventResponseMessage = 76;
+ optional CommentMessage commentMessage = 77;
+ optional NewsletterAdminInviteMessage newsletterAdminInviteMessage = 78;
+ optional PlaceholderMessage placeholderMessage = 80;
+ optional SecretEncryptedMessage secretEncryptedMessage = 82;
+ optional AlbumMessage albumMessage = 83;
+ optional FutureProofMessage eventCoverImage = 85;
+ optional StickerPackMessage stickerPackMessage = 86;
+ optional FutureProofMessage statusMentionMessage = 87;
+ optional PollResultSnapshotMessage pollResultSnapshotMessage = 88;
+ optional FutureProofMessage pollCreationOptionImageMessage = 90;
+ optional FutureProofMessage associatedChildMessage = 91;
+ optional FutureProofMessage groupStatusMentionMessage = 92;
+ optional FutureProofMessage pollCreationMessageV4 = 93;
+ optional FutureProofMessage statusAddYours = 95;
+ optional FutureProofMessage groupStatusMessage = 96;
+ optional AIRichResponseMessage richResponseMessage = 97;
+ optional StatusNotificationMessage statusNotificationMessage = 98;
+ optional FutureProofMessage limitSharingMessage = 99;
+ optional FutureProofMessage botTaskMessage = 100;
+ optional FutureProofMessage questionMessage = 101;
+ optional MessageHistoryNotice messageHistoryNotice = 102;
+ optional FutureProofMessage groupStatusMessageV2 = 103;
+ optional FutureProofMessage botForwardedMessage = 104;
+ optional StatusQuestionAnswerMessage statusQuestionAnswerMessage = 105;
+ optional FutureProofMessage questionReplyMessage = 106;
+ optional QuestionResponseMessage questionResponseMessage = 107;
+ optional StatusQuotedMessage statusQuotedMessage = 109;
+ optional StatusStickerInteractionMessage statusStickerInteractionMessage = 110;
+ optional PollCreationMessage pollCreationMessageV5 = 111;
+ optional NewsletterFollowerInviteMessage newsletterFollowerInviteMessageV2 = 113;
+ optional PollResultSnapshotMessage pollResultSnapshotMessageV3 = 115;
+ optional FutureProofMessage newsletterAdminProfileMessage = 116;
+ optional FutureProofMessage spoilerMessage = 118;
+ optional PollCreationMessage pollCreationMessageV6 = 119;
+ optional ConditionalRevealMessage conditionalRevealMessage = 120;
+ optional PollAddOptionMessage pollAddOptionMessage = 121;
+ optional EventInviteMessage eventInviteMessage = 122;
+ optional GroupRootKeyShare groupRootKeyShare = 123;
+ optional PaymentReminderMessage paymentReminderMessage = 124;
+ optional SplitPaymentMessage splitPaymentMessage = 125;
+ optional FutureProofMessage newsletterAdminProfileStatusMessage = 126;
+ optional RootSecretDistributeMessage rootSecretDistributeMessage = 127;
+ optional SplitPaymentUpdateMessage splitPaymentUpdateMessage = 128;
+ optional MusicMessage musicMessage = 129;
+ optional StatusLinkPreviewMetadata statusLinkPreviewMetadata = 130;
+ optional FutureProofMessage botPlatformRegistrationSuccessMessage = 131;
+ optional FutureProofMessage newsletterScheduledMessage = 132;
+ optional FutureProofMessage acp2SettingMessage = 133;
+ optional FutureProofMessage audioStickerMessage = 134;
+ optional ImageMessage instantImageMessage = 135;
+ optional RequestLocationMessage requestLocationMessage = 136;
+ optional FutureProofMessage botGroupParticipantMessage = 137;
+ optional RequestLocationUpdateMessage requestLocationUpdateMessage = 138;
+}
+
+message AlbumMessage {
+ optional uint32 expectedImageCount = 2;
+ optional uint32 expectedVideoCount = 3;
+ optional ContextInfo contextInfo = 17;
+}
+
+message MessageHistoryMetadata {
+ repeated string historyReceivers = 1;
+ optional int64 oldestMessageTimestampInWindow = 2;
+ optional int64 messageCount = 3;
+ repeated string nonHistoryReceivers = 4;
+ optional int64 oldestMessageTimestampInBundle = 5;
+ optional bool includesChatTheme = 6;
+}
+
+message HistoryShareMessageEntry {
+ optional string stanzaID = 1;
+ optional bytes messageSecretProof = 2;
+}
+
+message BotHistoryShareSyncMetadata {
+ optional string botJID = 1;
+ optional int64 historyShareCutoffTimestamp = 2;
+ repeated HistoryShareMessageEntry historyShareMessages = 3;
+}
+
+message MessageHistoryNotice {
+ optional ContextInfo contextInfo = 1;
+ optional MessageHistoryMetadata messageHistoryMetadata = 2;
+ optional BotHistoryShareSyncMetadata botHistoryShareSyncMetadata = 3;
+}
+
+message MessageHistoryBundle {
+ optional string mimetype = 1;
+ optional bytes fileSHA256 = 2;
+ optional bytes mediaKey = 3;
+ optional bytes fileEncSHA256 = 4;
+ optional string directPath = 5;
+ optional int64 mediaKeyTimestamp = 6;
+ optional ContextInfo contextInfo = 7;
+ optional MessageHistoryMetadata messageHistoryMetadata = 8;
+}
+
+message EncEventResponseMessage {
+ optional WACommon.MessageKey eventCreationMessageKey = 1;
+ optional bytes encPayload = 2;
+ optional bytes encIV = 3;
+}
+
+message EventMessage {
+ optional ContextInfo contextInfo = 1;
+ optional bool isCanceled = 2;
+ optional string name = 3;
+ optional string description = 4;
+ optional LocationMessage location = 5;
+ optional string joinLink = 6;
+ optional int64 startTime = 7;
+ optional int64 endTime = 8;
+ optional bool extraGuestsAllowed = 9;
+ optional bool isScheduleCall = 10;
+ optional bool hasReminder = 11;
+ optional int64 reminderOffsetSec = 12;
+}
+
+message CommentMessage {
+ optional Message message = 1;
+ optional WACommon.MessageKey targetMessageKey = 2;
+}
+
+message EncCommentMessage {
+ optional WACommon.MessageKey targetMessageKey = 1;
+ optional bytes encPayload = 2;
+ optional bytes encIV = 3;
+}
+
+message EncReactionMessage {
+ optional WACommon.MessageKey targetMessageKey = 1;
+ optional bytes encPayload = 2;
+ optional bytes encIV = 3;
+}
+
+message KeepInChatMessage {
+ optional WACommon.MessageKey key = 1;
+ optional KeepType keepType = 2;
+ optional int64 timestampMS = 3;
+}
+
+message QuestionResponseMessage {
+ optional WACommon.MessageKey key = 1;
+ optional string text = 2;
+}
+
+message StatusQuestionAnswerMessage {
+ optional WACommon.MessageKey key = 1;
+ optional string text = 2;
+}
+
+message PollResultSnapshotMessage {
+ message PollVote {
+ optional string optionName = 1;
+ optional int64 optionVoteCount = 2;
+ }
+
+ optional string name = 1;
+ repeated PollVote pollVotes = 2;
+ optional ContextInfo contextInfo = 3;
+ optional PollType pollType = 4;
+}
+
+message PollAddOptionMessage {
+ optional WACommon.MessageKey pollCreationMessageKey = 1;
+ optional PollCreationMessage.Option addOption = 2;
+ optional PollUpdateMessageMetadata metadata = 3;
+}
+
+message PollVoteMessage {
+ repeated bytes selectedOptions = 1;
+}
+
+message PollEncValue {
+ optional bytes encPayload = 1;
+ optional bytes encIV = 2;
+}
+
+message PollUpdateMessageMetadata {
+ optional bytes pollNameHash = 1;
+ optional string lastEditStanzaID = 2;
+}
+
+message PollUpdateMessage {
+ optional WACommon.MessageKey pollCreationMessageKey = 1;
+ optional PollEncValue vote = 2;
+ optional PollUpdateMessageMetadata metadata = 3;
+ optional int64 senderTimestampMS = 4;
+}
+
+message PollCreationMessage {
+ message Option {
+ optional string optionName = 1;
+ optional string optionHash = 2;
+ }
+
+ optional bytes encKey = 1;
+ optional string name = 2;
+ repeated Option options = 3;
+ optional uint32 selectableOptionsCount = 4;
+ optional ContextInfo contextInfo = 5;
+ optional PollContentType pollContentType = 6;
+ optional PollType pollType = 7;
+ optional Option correctAnswer = 8;
+ optional int64 endTime = 9;
+ optional bool hideParticipantName = 10;
+ optional bool allowAddOption = 11;
+}
+
+message StickerSyncRMRMessage {
+ repeated string filehash = 1;
+ optional string rmrSource = 2;
+ optional int64 requestTimestamp = 3;
+}
+
+message ReactionMessage {
+ optional WACommon.MessageKey key = 1;
+ optional string text = 2;
+ optional string groupingKey = 3;
+ optional int64 senderTimestampMS = 4;
+}
+
+message FutureProofMessage {
+ optional Message message = 1;
+}
+
+message DeviceSentMessage {
+ optional string destinationJID = 1;
+ optional Message message = 2;
+ optional string phash = 3;
+}
+
+message RequestLocationMessage {
+ optional ContextInfo contextInfo = 1;
+}
+
+message RequestPhoneNumberMessage {
+ optional ContextInfo contextInfo = 1;
+}
+
+message NewsletterFollowerInviteMessage {
+ optional string newsletterJID = 1;
+ optional string newsletterName = 2;
+ optional bytes JPEGThumbnail = 3;
+ optional string caption = 4;
+ optional ContextInfo contextInfo = 5;
+}
+
+message NewsletterAdminInviteMessage {
+ optional string newsletterJID = 1;
+ optional string newsletterName = 2;
+ optional bytes JPEGThumbnail = 3;
+ optional string caption = 4;
+ optional int64 inviteExpiration = 5;
+ optional ContextInfo contextInfo = 6;
+}
+
+message ProductMessage {
+ message ProductSnapshot {
+ optional ImageMessage productImage = 1;
+ optional string productID = 2;
+ optional string title = 3;
+ optional string description = 4;
+ optional string currencyCode = 5;
+ optional int64 priceAmount1000 = 6;
+ optional string retailerID = 7;
+ optional string URL = 8;
+ optional uint32 productImageCount = 9;
+ optional string firstImageID = 11;
+ optional int64 salePriceAmount1000 = 12;
+ optional string signedURL = 13;
+ }
+
+ message CatalogSnapshot {
+ optional ImageMessage catalogImage = 1;
+ optional string title = 2;
+ optional string description = 3;
+ }
+
+ optional ProductSnapshot product = 1;
+ optional string businessOwnerJID = 2;
+ optional CatalogSnapshot catalog = 4;
+ optional string body = 5;
+ optional string footer = 6;
+ optional ContextInfo contextInfo = 17;
+}
+
+message TemplateButtonReplyMessage {
+ optional string selectedID = 1;
+ optional string selectedDisplayText = 2;
+ optional ContextInfo contextInfo = 3;
+ optional uint32 selectedIndex = 4;
+ optional uint32 selectedCarouselCardIndex = 5;
+}
+
+message TemplateMessage {
+ message HydratedFourRowTemplate {
+ oneof title {
+ DocumentMessage documentMessage = 1;
+ string hydratedTitleText = 2;
+ ImageMessage imageMessage = 3;
+ VideoMessage videoMessage = 4;
+ LocationMessage locationMessage = 5;
+ }
+
+ optional string hydratedContentText = 6;
+ optional string hydratedFooterText = 7;
+ repeated HydratedTemplateButton hydratedButtons = 8;
+ optional string templateID = 9;
+ optional bool maskLinkedDevices = 10;
+ }
+
+ message FourRowTemplate {
+ oneof title {
+ DocumentMessage documentMessage = 1;
+ HighlyStructuredMessage highlyStructuredMessage = 2;
+ ImageMessage imageMessage = 3;
+ VideoMessage videoMessage = 4;
+ LocationMessage locationMessage = 5;
+ }
+
+ optional HighlyStructuredMessage content = 6;
+ optional HighlyStructuredMessage footer = 7;
+ repeated TemplateButton buttons = 8;
+ }
+
+ oneof format {
+ FourRowTemplate fourRowTemplate = 1;
+ HydratedFourRowTemplate hydratedFourRowTemplate = 2;
+ InteractiveMessage interactiveMessageTemplate = 5;
+ }
+
+ optional ContextInfo contextInfo = 3;
+ optional HydratedFourRowTemplate hydratedTemplate = 4;
+ optional string templateID = 9;
+}
+
+message StickerMessage {
+ oneof audio {
+ AudioMessage audioMessage = 26;
+ }
+
+ optional string URL = 1;
+ optional bytes fileSHA256 = 2;
+ optional bytes fileEncSHA256 = 3;
+ optional bytes mediaKey = 4;
+ optional string mimetype = 5;
+ optional uint32 height = 6;
+ optional uint32 width = 7;
+ optional string directPath = 8;
+ optional uint64 fileLength = 9;
+ optional int64 mediaKeyTimestamp = 10;
+ optional uint32 firstFrameLength = 11;
+ optional bytes firstFrameSidecar = 12;
+ optional bool isAnimated = 13;
+ optional bytes pngThumbnail = 16;
+ optional ContextInfo contextInfo = 17;
+ optional int64 stickerSentTS = 18;
+ optional bool isAvatar = 19;
+ optional bool isAiSticker = 20;
+ optional bool isLottie = 21;
+ optional string accessibilityLabel = 22;
+ optional int32 premium = 24;
+ optional string emojis = 25;
+}
+
+message LiveLocationMessage {
+ optional double degreesLatitude = 1;
+ optional double degreesLongitude = 2;
+ optional uint32 accuracyInMeters = 3;
+ optional float speedInMps = 4;
+ optional uint32 degreesClockwiseFromMagneticNorth = 5;
+ optional string caption = 6;
+ optional int64 sequenceNumber = 7;
+ optional uint32 timeOffset = 8;
+ optional bytes JPEGThumbnail = 16;
+ optional ContextInfo contextInfo = 17;
+}
+
+message SplitPaymentUpdateMessage {
+ optional string splitID = 1;
+ optional string participantJID = 2;
+}
+
+message SplitPaymentMessage {
+ optional string splitID = 1;
+ optional Money totalAmount = 2;
+ optional string description = 3;
+ optional string requesterJID = 4;
+ repeated SplitPaymentParticipant participants = 5;
+ optional int64 createdAtMS = 6;
+ optional ContextInfo contextInfo = 17;
+}
+
+message CancelPaymentRequestMessage {
+ optional WACommon.MessageKey key = 1;
+}
+
+message DeclinePaymentRequestMessage {
+ optional WACommon.MessageKey key = 1;
+}
+
+message RequestPaymentMessage {
+ optional Message noteMessage = 4;
+ optional string currencyCodeIso4217 = 1;
+ optional uint64 amount1000 = 2;
+ optional string requestFrom = 3;
+ optional int64 expiryTimestamp = 5;
+ optional Money amount = 6;
+ optional PaymentBackground background = 7;
+}
+
+message SendPaymentMessage {
+ optional Message noteMessage = 2;
+ optional WACommon.MessageKey requestMessageKey = 3;
+ optional PaymentBackground background = 4;
+ optional string transactionData = 5;
+}
+
+message ContactsArrayMessage {
+ optional string displayName = 1;
+ repeated ContactMessage contacts = 2;
+ optional ContextInfo contextInfo = 17;
+}
+
+message InitialSecurityNotificationSettingSync {
+ optional bool securityNotificationEnabled = 1;
+}
+
+message FullHistorySyncOnDemandConfig {
+ optional uint64 historyFromTimestamp = 1;
+ optional uint32 historyDurationDays = 2;
+}
+
+message FullHistorySyncOnDemandRequestMetadata {
+ optional string requestID = 1;
+ optional string businessProduct = 2;
+ optional bytes opaqueClientData = 3;
+ optional CoexConnectionDescriptor connection = 4;
+}
+
+message CoexConnectionDescriptor {
+ optional int64 providerID = 1;
+ optional string product = 2;
+}
+
+message AppStateFatalExceptionNotification {
+ repeated string collectionNames = 1;
+ optional int64 timestamp = 2;
+}
+
+message SharedDeviceContactHashKeyRequest {
+ optional uint32 knownEpoch = 1;
+}
+
+message SharedDeviceContactHashKeyShare {
+ repeated SharedDeviceContactHashKey keys = 1;
+}
+
+message AppStateSyncKeyRequest {
+ repeated AppStateSyncKeyId keyIDs = 1;
+}
+
+message AppStateSyncKeyShare {
+ repeated AppStateSyncKey keys = 1;
+}
+
+message AppStateSyncKeyData {
+ optional bytes keyData = 1;
+ optional AppStateSyncKeyFingerprint fingerprint = 2;
+ optional int64 timestamp = 3;
+}
+
+message AppStateSyncKeyFingerprint {
+ optional uint32 rawID = 1;
+ optional uint32 currentIndex = 2;
+ repeated uint32 deviceIndexes = 3 [packed=true];
+}
+
+message AppStateSyncKeyId {
+ optional bytes keyID = 1;
+}
+
+message AppStateSyncKey {
+ optional AppStateSyncKeyId keyID = 1;
+ optional AppStateSyncKeyData keyData = 2;
+}
+
+message HistorySyncNotification {
+ optional bytes fileSHA256 = 1;
+ optional uint64 fileLength = 2;
+ optional bytes mediaKey = 3;
+ optional bytes fileEncSHA256 = 4;
+ optional string directPath = 5;
+ optional HistorySyncType syncType = 6;
+ optional uint32 chunkOrder = 7;
+ optional string originalMessageID = 8;
+ optional uint32 progress = 9;
+ optional int64 oldestMsgInChunkTimestampSec = 10;
+ optional bytes initialHistBootstrapInlinePayload = 11;
+ optional string peerDataRequestSessionID = 12;
+ optional FullHistorySyncOnDemandRequestMetadata fullHistorySyncOnDemandRequestMetadata = 13;
+ optional string encHandle = 14;
+ optional HistorySyncMessageAccessStatus messageAccessStatus = 15;
+}
+
+message HistorySyncMessageAccessStatus {
+ optional bool completeAccessGranted = 1;
+}
+
+message ChatAnimatedWallpaper {
+ optional string animatedWallpaperID = 1;
+ optional float dimLevel = 2;
+}
+
+message ChatStockImageWallpaper {
+ optional string stockImageID = 1;
+ optional float dimLevel = 2;
+}
+
+message ChatSolidColorWallpaper {
+ optional fixed32 backgroundLightArgb = 1;
+ optional fixed32 backgroundDarkArgb = 2;
+ optional bool isDoodleEnabled = 3;
+ optional fixed32 doodleLightArgb = 4;
+ optional fixed32 doodleDarkArgb = 5;
+}
+
+message ChatDefaultWallpaper {
+ optional bool isDoodleEnabled = 1;
+}
+
+message ChatCustomImageWallpaper {
+ optional string directPath = 1;
+ optional bytes mediaKey = 2;
+ optional bytes fileEncSHA256 = 3;
+ optional bytes fileSHA256 = 4;
+ optional float dimLevel = 5;
+}
+
+message ChatThemeSetting {
+ oneof wallpaper {
+ ChatDefaultWallpaper defaultWallpaper = 10;
+ ChatSolidColorWallpaper solidColor = 11;
+ ChatStockImageWallpaper stockImage = 12;
+ ChatCustomImageWallpaper customImage = 13;
+ ChatAnimatedWallpaper animatedWallpaper = 14;
+ }
+
+ optional int64 settingTimestampMS = 1;
+ optional bool clearTheme = 2;
+ optional string colorSchemeID = 3;
+}
+
+message MarkAsVerifiedAction {
+ optional string userJIDString = 1;
+ optional bool verified = 2;
+ optional bytes verifiedIdentityKey = 3;
+ optional uint64 actionSeq = 4;
+}
+
+message Chat {
+ optional string displayName = 1;
+ optional string ID = 2;
+}
+
+message Call {
+ optional bytes callKey = 1;
+ optional string conversionSource = 2;
+ optional bytes conversionData = 3;
+ optional uint32 conversionDelaySeconds = 4;
+ optional string ctwaSignals = 5;
+ optional bytes ctwaPayload = 6;
+ optional ContextInfo contextInfo = 7;
+ optional string nativeFlowCallButtonPayload = 8;
+ optional string deeplinkPayload = 9;
+ optional MessageContextInfo messageContextInfo = 10;
+ optional uint32 callEntryPoint = 11;
+ optional string callReason = 12;
+}
+
+message AudioMessage {
+ optional string URL = 1;
+ optional string mimetype = 2;
+ optional bytes fileSHA256 = 3;
+ optional uint64 fileLength = 4;
+ optional uint32 seconds = 5;
+ optional bool PTT = 6;
+ optional bytes mediaKey = 7;
+ optional bytes fileEncSHA256 = 8;
+ optional string directPath = 9;
+ optional int64 mediaKeyTimestamp = 10;
+ optional ContextInfo contextInfo = 17;
+ optional bytes streamingSidecar = 18;
+ optional bytes waveform = 19;
+ optional fixed32 backgroundArgb = 20;
+ optional bool viewOnce = 21;
+ optional string accessibilityLabel = 22;
+}
+
+message DocumentMessage {
+ optional string URL = 1;
+ optional string mimetype = 2;
+ optional string title = 3;
+ optional bytes fileSHA256 = 4;
+ optional uint64 fileLength = 5;
+ optional uint32 pageCount = 6;
+ optional bytes mediaKey = 7;
+ optional string fileName = 8;
+ optional bytes fileEncSHA256 = 9;
+ optional string directPath = 10;
+ optional int64 mediaKeyTimestamp = 11;
+ optional bool contactVcard = 12;
+ optional string thumbnailDirectPath = 13;
+ optional bytes thumbnailSHA256 = 14;
+ optional bytes thumbnailEncSHA256 = 15;
+ optional bytes JPEGThumbnail = 16;
+ optional ContextInfo contextInfo = 17;
+ optional uint32 thumbnailHeight = 18;
+ optional uint32 thumbnailWidth = 19;
+ optional string caption = 20;
+ optional string accessibilityLabel = 21;
+}
+
+message URLMetadata {
+ optional uint32 fbExperimentID = 1;
+}
+
+message PaymentExtendedMetadata {
+ optional uint32 type = 1;
+ optional string platform = 2;
+ optional string messageParamsJSON = 3;
+}
+
+message MMSThumbnailMetadata {
+ optional string thumbnailDirectPath = 1;
+ optional bytes thumbnailSHA256 = 2;
+ optional bytes thumbnailEncSHA256 = 3;
+ optional bytes mediaKey = 4;
+ optional int64 mediaKeyTimestamp = 5;
+ optional uint32 thumbnailHeight = 6;
+ optional uint32 thumbnailWidth = 7;
+}
+
+message LocationMessage {
+ optional double degreesLatitude = 1;
+ optional double degreesLongitude = 2;
+ optional string name = 3;
+ optional string address = 4;
+ optional string URL = 5;
+ optional bool isLive = 6;
+ optional uint32 accuracyInMeters = 7;
+ optional float speedInMps = 8;
+ optional uint32 degreesClockwiseFromMagneticNorth = 9;
+ optional string comment = 11;
+ optional bytes JPEGThumbnail = 16;
+ optional ContextInfo contextInfo = 17;
+}
+
+message ContactMessage {
+ optional string displayName = 1;
+ optional string vcard = 16;
+ optional ContextInfo contextInfo = 17;
+ optional bool isSelfContact = 18;
+}
+
+message RootSecretDistributeMessage {
+ optional string chatJID = 1;
+}
+
+message SenderKeyDistributionMessage {
+ optional string groupID = 1;
+ optional bytes axolotlSenderKeyDistributionMessage = 2;
+}
+
+message VideoEndCard {
+ required string username = 1;
+ required string caption = 2;
+ required string thumbnailImageURL = 3;
+ required string profilePictureURL = 4;
+}
+
+message MediaDomainInfo {
+ optional MediaKeyDomain mediaKeyDomain = 1;
+ optional bytes e2EeMediaKey = 2;
+}
+
+message DeviceListMetadata {
+ optional bytes senderKeyHash = 1;
+ optional uint64 senderTimestamp = 2;
+ repeated uint32 senderKeyIndexes = 3 [packed=true];
+ optional WAAdv.ADVEncryptionType senderAccountType = 4;
+ optional WAAdv.ADVEncryptionType receiverAccountType = 5;
+ optional bytes recipientKeyHash = 8;
+ optional uint64 recipientTimestamp = 9;
+ repeated uint32 recipientKeyIndexes = 10 [packed=true];
+}
+
+message EmbeddedMessage {
+ optional string stanzaID = 1;
+ optional Message message = 2;
+}
+
+message EmbeddedMusic {
+ optional string musicContentMediaID = 1;
+ optional string songID = 2;
+ optional string author = 3;
+ optional string title = 4;
+ optional string artworkDirectPath = 5;
+ optional bytes artworkSHA256 = 6;
+ optional bytes artworkEncSHA256 = 7;
+ optional string artistAttribution = 8;
+ optional bytes countryBlocklist = 9;
+ optional bool isExplicit = 10;
+ optional bytes artworkMediaKey = 11;
+ optional int64 musicSongStartTimeInMS = 12;
+ optional int64 derivedContentStartTimeInMS = 13;
+ optional int64 overlapDurationInMS = 14;
+}
+
+message EmbeddedContent {
+ oneof content {
+ EmbeddedMessage embeddedMessage = 1;
+ EmbeddedMusic embeddedMusic = 2;
+ }
+}
+
+message TapLinkAction {
+ optional string title = 1;
+ optional string tapURL = 2;
+}
+
+message Point {
+ optional int32 xDeprecated = 1;
+ optional int32 yDeprecated = 2;
+ optional double x = 3;
+ optional double y = 4;
+}
+
+message Location {
+ optional double degreesLatitude = 1;
+ optional double degreesLongitude = 2;
+ optional string name = 3;
+}
+
+message TemplateButton {
+ message CallButton {
+ optional HighlyStructuredMessage displayText = 1;
+ optional HighlyStructuredMessage phoneNumber = 2;
+ }
+
+ message URLButton {
+ optional HighlyStructuredMessage displayText = 1;
+ optional HighlyStructuredMessage URL = 2;
+ }
+
+ message QuickReplyButton {
+ optional HighlyStructuredMessage displayText = 1;
+ optional string ID = 2;
+ }
+
+ oneof button {
+ QuickReplyButton quickReplyButton = 1;
+ URLButton urlButton = 2;
+ CallButton callButton = 3;
+ }
+
+ optional uint32 index = 4;
+}
+
+message Money {
+ optional int64 value = 1;
+ optional uint32 offset = 2;
+ optional string currencyCode = 3;
+}
+
+message ActionLink {
+ optional string URL = 1;
+ optional string buttonTitle = 2;
+}
+
+message GroupMention {
+ optional string groupJID = 1;
+ optional string groupSubject = 2;
+}
+
+message MessageSecretMessage {
+ optional sfixed32 version = 1;
+ optional bytes encIV = 2;
+ optional bytes encPayload = 3;
+}
+
+message MediaNotifyMessage {
+ optional string expressPathURL = 1;
+ optional bytes fileEncSHA256 = 2;
+ optional uint64 fileLength = 3;
+}
+
+message LIDMigrationMappingSyncMessage {
+ optional bytes encodedMappingPayload = 1;
+}
+
+message UrlTrackingMap {
+ message UrlTrackingMapElement {
+ optional string originalURL = 1;
+ optional string unconsentedUsersURL = 2;
+ optional string consentedUsersURL = 3;
+ optional uint32 cardIndex = 4;
+ }
+
+ repeated UrlTrackingMapElement urlTrackingMapElements = 1;
+}
+
+message MemberLabel {
+ optional string label = 1;
+ optional int64 labelTimestamp = 2;
+}
+
+message AIRichResponseMessage {
+ optional WAAICommonDeprecated.AIRichResponseMessageType messageType = 1;
+ repeated WAAICommonDeprecated.AIRichResponseSubMessage submessages = 2;
+ optional WAWebProtobufsAICommon.AIRichResponseUnifiedResponse unifiedResponse = 3;
+ optional ContextInfo contextInfo = 4;
+ optional WAWebProtobufsAICommon.AIRichResponseUnifiedResponse originalRecipientMetadata = 5;
+}
+
+message AIQueryFanout {
+ optional WACommon.MessageKey messageKey = 1;
+ optional Message message = 2;
+ optional int64 timestamp = 3;
+}
+
+message GroupRootKeyShare {
+ repeated GroupRootKeyShareEntry keys = 1;
+}
+
+message GroupRootKeyShareEntry {
+ optional bytes groupRootKey = 1;
+ optional string keyID = 2;
+ optional int64 expiryTimestampMS = 3;
+ optional int64 createdTimestampMS = 4;
+}
diff --git a/crates/whatsmeow_proto/proto/waE2EGuest/WAWebProtobufsE2EGuest.proto b/crates/whatsmeow_proto/proto/waE2EGuest/WAWebProtobufsE2EGuest.proto
new file mode 100644
index 0000000000..417405e05f
--- /dev/null
+++ b/crates/whatsmeow_proto/proto/waE2EGuest/WAWebProtobufsE2EGuest.proto
@@ -0,0 +1,28 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+syntax = "proto2";
+package WAWebProtobufsE2EGuest;
+option go_package = "go.mau.fi/whatsmeow/proto/waE2EGuest";
+
+message Message {
+ message ExtendedTextMessage {
+ optional string text = 1;
+ optional ContextInfo contextInfo = 17;
+ }
+
+ message ContextInfo {
+ optional string stanzaID = 1;
+ optional string participant = 2;
+ optional Message quotedMessage = 3;
+ }
+
+ optional string conversation = 1;
+ optional ExtendedTextMessage extendedTextMessage = 6;
+ optional MessageContextInfo messageContextInfo = 35;
+}
+
+message MessageContextInfo {
+ optional bytes messageSecret = 3;
+}
diff --git a/crates/whatsmeow_proto/proto/waEphemeral/WAWebProtobufsEphemeral.proto b/crates/whatsmeow_proto/proto/waEphemeral/WAWebProtobufsEphemeral.proto
new file mode 100644
index 0000000000..cd689b47de
--- /dev/null
+++ b/crates/whatsmeow_proto/proto/waEphemeral/WAWebProtobufsEphemeral.proto
@@ -0,0 +1,12 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+syntax = "proto2";
+package WAWebProtobufsEphemeral;
+option go_package = "go.mau.fi/whatsmeow/proto/waEphemeral";
+
+message EphemeralSetting {
+ optional sfixed32 duration = 1;
+ optional sfixed64 timestamp = 2;
+}
diff --git a/crates/whatsmeow_proto/proto/waFingerprint/WAFingerprint.proto b/crates/whatsmeow_proto/proto/waFingerprint/WAFingerprint.proto
new file mode 100644
index 0000000000..55504f2113
--- /dev/null
+++ b/crates/whatsmeow_proto/proto/waFingerprint/WAFingerprint.proto
@@ -0,0 +1,27 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+syntax = "proto2";
+package WAFingerprint;
+option go_package = "go.mau.fi/whatsmeow/proto/waFingerprint";
+
+enum HostedState {
+ E2EE = 0;
+ HOSTED = 1;
+}
+
+message FingerprintData {
+ optional bytes publicKey = 1;
+ optional bytes pnIdentifier = 2;
+ optional bytes lidIdentifier = 3;
+ optional bytes usernameIdentifier = 4;
+ optional HostedState hostedState = 5;
+ optional bytes hashedPublicKey = 6;
+}
+
+message CombinedFingerprint {
+ optional uint32 version = 1;
+ optional FingerprintData localFingerprint = 2;
+ optional FingerprintData remoteFingerprint = 3;
+}
diff --git a/crates/whatsmeow_proto/proto/waGroupHistory/WAWebProtobufsGroupHistory.proto b/crates/whatsmeow_proto/proto/waGroupHistory/WAWebProtobufsGroupHistory.proto
new file mode 100644
index 0000000000..deaadca445
--- /dev/null
+++ b/crates/whatsmeow_proto/proto/waGroupHistory/WAWebProtobufsGroupHistory.proto
@@ -0,0 +1,43 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+syntax = "proto2";
+package WAWebProtobufsGroupHistory;
+option go_package = "go.mau.fi/whatsmeow/proto/waGroupHistory";
+
+import "waE2E/WAWebProtobufsE2E.proto";
+import "waCommon/WACommon.proto";
+import "waWeb/WAWebProtobufsWeb.proto";
+
+message GroupHistory {
+ repeated WAWebProtobufsWeb.WebMessageInfo messages = 1;
+ repeated UnCountedAssociatedMessageList uncountedAssociatedMessageLists = 2;
+ repeated WAWebProtobufsWeb.WebMessageInfo commentMessages = 3;
+ repeated WAWebProtobufsWeb.WebMessageInfo outOfWindowPinnedMessages = 4;
+ optional WAWebProtobufsWeb.WebMessageInfo themeMessage = 5;
+}
+
+message UnCountedAssociatedMessageList {
+ repeated WAWebProtobufsWeb.WebMessageInfo messages = 1;
+ optional WACommon.MessageKey parentMessage = 2;
+ optional WAWebProtobufsE2E.MessageAssociation.AssociationType associationType = 3;
+}
+
+message WebMessageInfoWithMessageBytes {
+ optional WACommon.MessageKey key = 1;
+ optional bytes messageBytes = 2;
+}
+
+message UnCountedAssociatedMessageListWithMessageBytes {
+ repeated WebMessageInfoWithMessageBytes messages = 1;
+ optional WACommon.MessageKey parentMessage = 2;
+}
+
+message GroupHistoryWithMessageBytes {
+ repeated WebMessageInfoWithMessageBytes messages = 1;
+ repeated UnCountedAssociatedMessageListWithMessageBytes uncountedAssociatedMessageLists = 2;
+ repeated WebMessageInfoWithMessageBytes commentMessages = 3;
+ repeated WebMessageInfoWithMessageBytes outOfWindowPinnedMessages = 4;
+ optional WebMessageInfoWithMessageBytes themeMessage = 5;
+}
diff --git a/crates/whatsmeow_proto/proto/waHistorySync/WAWebProtobufsHistorySync.proto b/crates/whatsmeow_proto/proto/waHistorySync/WAWebProtobufsHistorySync.proto
new file mode 100644
index 0000000000..9c57829c74
--- /dev/null
+++ b/crates/whatsmeow_proto/proto/waHistorySync/WAWebProtobufsHistorySync.proto
@@ -0,0 +1,283 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+syntax = "proto2";
+package WAWebProtobufsHistorySync;
+option go_package = "go.mau.fi/whatsmeow/proto/waHistorySync";
+
+import "waSyncAction/WAWebProtobufSyncAction.proto";
+import "waChatLockSettings/WAWebProtobufsChatLockSettings.proto";
+import "waE2E/WAWebProtobufsE2E.proto";
+import "waCommon/WACommon.proto";
+import "waWeb/WAWebProtobufsWeb.proto";
+
+enum MediaVisibility {
+ DEFAULT = 0;
+ OFF = 1;
+ ON = 2;
+}
+
+enum PrivacySystemMessage {
+ E2EE_MSG = 1;
+ NE2EE_SELF = 2;
+ NE2EE_OTHER = 3;
+}
+
+message HistorySync {
+ enum BotAIWaitListState {
+ IN_WAITLIST = 0;
+ AI_AVAILABLE = 1;
+ }
+
+ enum HistorySyncType {
+ INITIAL_BOOTSTRAP = 0;
+ INITIAL_STATUS_V3 = 1;
+ FULL = 2;
+ RECENT = 3;
+ PUSH_NAME = 4;
+ NON_BLOCKING_DATA = 5;
+ ON_DEMAND = 6;
+ }
+
+ required HistorySyncType syncType = 1;
+ repeated Conversation conversations = 2;
+ repeated WAWebProtobufsWeb.WebMessageInfo statusV3Messages = 3;
+ optional uint32 chunkOrder = 5;
+ optional uint32 progress = 6;
+ repeated Pushname pushnames = 7;
+ optional GlobalSettings globalSettings = 8;
+ optional bytes threadIDUserSecret = 9;
+ optional uint32 threadDsTimeframeOffset = 10;
+ repeated StickerMetadata recentStickers = 11;
+ repeated PastParticipants pastParticipants = 12;
+ repeated WAWebProtobufSyncAction.CallLogRecord callLogRecords = 13;
+ optional BotAIWaitListState aiWaitListState = 14;
+ repeated PhoneNumberToLIDMapping phoneNumberToLidMappings = 15;
+ optional string companionMetaNonce = 16;
+ optional bytes shareableChatIdentifierEncryptionKey = 17;
+ repeated Account accounts = 18;
+ optional bytes nctSalt = 19;
+ repeated InlineContact inlineContacts = 20;
+ optional bool inlineContactsProvided = 21;
+ repeated StickerMetadata favoriteStickers = 22;
+ repeated RecoverableHistoryConversation omittedConversations = 23;
+ optional bool omittedConversationsProvided = 24;
+}
+
+message Conversation {
+ enum GroupAppealStatus {
+ NO_APPEAL = 0;
+ APPEAL_IN_REVIEW = 1;
+ APPEAL_APPROVED = 2;
+ APPEAL_REJECTED = 3;
+ }
+
+ enum EndOfHistoryTransferType {
+ COMPLETE_BUT_MORE_MESSAGES_REMAIN_ON_PRIMARY = 0;
+ COMPLETE_AND_NO_MORE_MESSAGE_REMAIN_ON_PRIMARY = 1;
+ COMPLETE_ON_DEMAND_SYNC_BUT_MORE_MSG_REMAIN_ON_PRIMARY = 2;
+ COMPLETE_ON_DEMAND_SYNC_WITH_MORE_MSG_ON_PRIMARY_BUT_NO_ACCESS = 3;
+ }
+
+ required string ID = 1;
+ repeated HistorySyncMsg messages = 2;
+ optional string newJID = 3;
+ optional string oldJID = 4;
+ optional uint64 lastMsgTimestamp = 5;
+ optional uint32 unreadCount = 6;
+ optional bool readOnly = 7;
+ optional bool endOfHistoryTransfer = 8;
+ optional uint32 ephemeralExpiration = 9;
+ optional int64 ephemeralSettingTimestamp = 10;
+ optional EndOfHistoryTransferType endOfHistoryTransferType = 11;
+ optional uint64 conversationTimestamp = 12;
+ optional string name = 13;
+ optional string pHash = 14;
+ optional bool notSpam = 15;
+ optional bool archived = 16;
+ optional WAWebProtobufsE2E.DisappearingMode disappearingMode = 17;
+ optional uint32 unreadMentionCount = 18;
+ optional bool markedAsUnread = 19;
+ repeated GroupParticipant participant = 20;
+ optional bytes tcToken = 21;
+ optional uint64 tcTokenTimestamp = 22;
+ optional bytes contactPrimaryIdentityKey = 23;
+ optional uint32 pinned = 24;
+ optional uint64 muteEndTime = 25;
+ optional WallpaperSettings wallpaper = 26;
+ optional MediaVisibility mediaVisibility = 27;
+ optional uint64 tcTokenSenderTimestamp = 28;
+ optional bool suspended = 29;
+ optional bool terminated = 30;
+ optional uint64 createdAt = 31;
+ optional string createdBy = 32;
+ optional string description = 33;
+ optional bool support = 34;
+ optional bool isParentGroup = 35;
+ optional string parentGroupID = 37;
+ optional bool isDefaultSubgroup = 36;
+ optional string displayName = 38;
+ optional string pnJID = 39;
+ optional bool shareOwnPn = 40;
+ optional bool pnhDuplicateLidThread = 41;
+ optional string lidJID = 42;
+ optional string username = 43;
+ optional string lidOriginType = 44;
+ optional uint32 commentsCount = 45;
+ optional bool locked = 46;
+ optional PrivacySystemMessage systemMessageToInsert = 47;
+ optional bool capiCreatedGroup = 48;
+ optional string accountLid = 49;
+ optional bool limitSharing = 50;
+ optional int64 limitSharingSettingTimestamp = 51;
+ optional WACommon.LimitSharing.Trigger limitSharingTrigger = 52;
+ optional bool limitSharingInitiatedByMe = 53;
+ optional bool maibaAiThreadEnabled = 54;
+ optional bool isMarketingMessageThread = 55;
+ optional bool isSenderNewAccount = 56;
+ optional uint32 afterReadDuration = 57;
+ optional bool isSenderSuspicious = 58;
+ optional GroupAppealStatus appealStatus = 59;
+ optional uint64 appealUpdateTime = 60;
+ optional string authAgentParentCompanyName = 61;
+ optional string authAgentObaPhoneNumber = 62;
+ optional IdentityVerificationState identityVerification = 63;
+ optional WACommon.ACP2Setting acp2Setting = 64;
+ optional bool acp2HistoryWithheld = 65;
+}
+
+message GroupParticipant {
+ enum Rank {
+ REGULAR = 0;
+ ADMIN = 1;
+ SUPERADMIN = 2;
+ }
+
+ required string userJID = 1;
+ optional Rank rank = 2;
+ optional WAWebProtobufsE2E.MemberLabel memberLabel = 3;
+}
+
+message PastParticipant {
+ enum LeaveReason {
+ LEFT = 0;
+ REMOVED = 1;
+ }
+
+ optional string userJID = 1;
+ optional LeaveReason leaveReason = 2;
+ optional uint64 leaveTS = 3;
+}
+
+message RecoverableHistoryConversation {
+ optional string historyChatID = 1;
+ optional string accountLid = 2;
+}
+
+message IdentityVerificationState {
+ optional bool verified = 1;
+ optional uint64 actionSeq = 2;
+}
+
+message PhoneNumberToLIDMapping {
+ optional string pnJID = 1;
+ optional string lidJID = 2;
+}
+
+message InlineContact {
+ optional string pnJID = 1;
+ optional string lidJID = 2;
+ optional string fullName = 3;
+ optional string firstName = 4;
+ optional string username = 5;
+}
+
+message Account {
+ optional string lid = 1;
+ optional string username = 2;
+ optional string countryCode = 3;
+ optional bool isUsernameDeleted = 4;
+}
+
+message HistorySyncMsg {
+ optional WAWebProtobufsWeb.WebMessageInfo message = 1;
+ optional uint64 msgOrderID = 2;
+}
+
+message Pushname {
+ optional string ID = 1;
+ optional string pushname = 2;
+}
+
+message WallpaperSettings {
+ optional string filename = 1;
+ optional uint32 opacity = 2;
+ optional bool isGenAi = 3;
+}
+
+message GlobalSettings {
+ optional WallpaperSettings lightThemeWallpaper = 1;
+ optional MediaVisibility mediaVisibility = 2;
+ optional WallpaperSettings darkThemeWallpaper = 3;
+ optional AutoDownloadSettings autoDownloadWiFi = 4;
+ optional AutoDownloadSettings autoDownloadCellular = 5;
+ optional AutoDownloadSettings autoDownloadRoaming = 6;
+ optional bool showIndividualNotificationsPreview = 7;
+ optional bool showGroupNotificationsPreview = 8;
+ optional int32 disappearingModeDuration = 9;
+ optional int64 disappearingModeTimestamp = 10;
+ optional AvatarUserSettings avatarUserSettings = 11;
+ optional int32 fontSize = 12;
+ optional bool securityNotifications = 13;
+ optional bool autoUnarchiveChats = 14;
+ optional int32 videoQualityMode = 15;
+ optional int32 photoQualityMode = 16;
+ optional NotificationSettings individualNotificationSettings = 17;
+ optional NotificationSettings groupNotificationSettings = 18;
+ optional WAWebProtobufsChatLockSettings.ChatLockSettings chatLockSettings = 19;
+ optional int64 chatDbLidMigrationTimestamp = 20;
+}
+
+message AutoDownloadSettings {
+ optional bool downloadImages = 1;
+ optional bool downloadAudio = 2;
+ optional bool downloadVideo = 3;
+ optional bool downloadDocuments = 4;
+}
+
+message StickerMetadata {
+ optional string URL = 1;
+ optional bytes fileSHA256 = 2;
+ optional bytes fileEncSHA256 = 3;
+ optional bytes mediaKey = 4;
+ optional string mimetype = 5;
+ optional uint32 height = 6;
+ optional uint32 width = 7;
+ optional string directPath = 8;
+ optional uint64 fileLength = 9;
+ optional float weight = 10;
+ optional int64 lastStickerSentTS = 11;
+ optional bool isLottie = 12;
+ optional string imageHash = 13;
+ optional bool isAvatarSticker = 14;
+}
+
+message PastParticipants {
+ optional string groupJID = 1;
+ repeated PastParticipant pastParticipants = 2;
+}
+
+message AvatarUserSettings {
+ optional string FBID = 1;
+ optional string password = 2;
+}
+
+message NotificationSettings {
+ optional string messageVibrate = 1;
+ optional string messagePopup = 2;
+ optional string messageLight = 3;
+ optional bool lowPriorityNotifications = 4;
+ optional bool reactionsMuted = 5;
+ optional string callVibrate = 6;
+}
diff --git a/crates/whatsmeow_proto/proto/waLidMigrationSyncPayload/WAWebProtobufLidMigrationSyncPayload.proto b/crates/whatsmeow_proto/proto/waLidMigrationSyncPayload/WAWebProtobufLidMigrationSyncPayload.proto
new file mode 100644
index 0000000000..d8d4499ab2
--- /dev/null
+++ b/crates/whatsmeow_proto/proto/waLidMigrationSyncPayload/WAWebProtobufLidMigrationSyncPayload.proto
@@ -0,0 +1,18 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+syntax = "proto2";
+package WAWebProtobufLidMigrationSyncPayload;
+option go_package = "go.mau.fi/whatsmeow/proto/waLidMigrationSyncPayload";
+
+message LIDMigrationMapping {
+ required uint64 pn = 1;
+ required uint64 assignedLid = 2;
+ optional uint64 latestLid = 3;
+}
+
+message LIDMigrationMappingSyncPayload {
+ repeated LIDMigrationMapping pnToLidMappings = 1;
+ optional uint64 chatDbMigrationTimestamp = 2;
+}
diff --git a/crates/whatsmeow_proto/proto/waMediaEntryData/WAMediaEntryData.proto b/crates/whatsmeow_proto/proto/waMediaEntryData/WAMediaEntryData.proto
new file mode 100644
index 0000000000..c99e316394
--- /dev/null
+++ b/crates/whatsmeow_proto/proto/waMediaEntryData/WAMediaEntryData.proto
@@ -0,0 +1,41 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+syntax = "proto2";
+package WAMediaEntryData;
+option go_package = "go.mau.fi/whatsmeow/proto/waMediaEntryData";
+
+message MediaEntry {
+ message ProgressiveJpegDetails {
+ repeated uint32 scanLengths = 1;
+ optional bytes sidecar = 2;
+ }
+
+ message DownloadableThumbnail {
+ optional bytes fileSHA256 = 1;
+ optional bytes fileEncSHA256 = 2;
+ optional string directPath = 3;
+ optional bytes mediaKey = 4;
+ optional int64 mediaKeyTimestamp = 5;
+ optional string objectID = 6;
+ }
+
+ optional bytes fileSHA256 = 1;
+ optional bytes mediaKey = 2;
+ optional bytes fileEncSHA256 = 3;
+ optional string directPath = 4;
+ optional int64 mediaKeyTimestamp = 5;
+ optional string serverMediaType = 6;
+ optional bytes uploadToken = 7;
+ optional bytes validatedTimestamp = 8;
+ optional bytes sidecar = 9;
+ optional string objectID = 10;
+ optional string FBID = 11;
+ optional DownloadableThumbnail downloadableThumbnail = 12;
+ optional string handle = 13;
+ optional string filename = 14;
+ optional ProgressiveJpegDetails progressiveJPEGDetails = 15;
+ optional int64 size = 16;
+ optional int64 lastDownloadAttemptTimestamp = 17;
+}
diff --git a/crates/whatsmeow_proto/proto/waMediaTransport/WAMediaTransport.proto b/crates/whatsmeow_proto/proto/waMediaTransport/WAMediaTransport.proto
new file mode 100644
index 0000000000..4724d8fd62
--- /dev/null
+++ b/crates/whatsmeow_proto/proto/waMediaTransport/WAMediaTransport.proto
@@ -0,0 +1,197 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+syntax = "proto2";
+package WAMediaTransport;
+option go_package = "go.mau.fi/whatsmeow/proto/waMediaTransport";
+
+import "waCommon/WACommon.proto";
+
+message WAMediaTransport {
+ message Ancillary {
+ message Thumbnail {
+ message DownloadableThumbnail {
+ optional bytes fileSHA256 = 1;
+ optional bytes fileEncSHA256 = 2;
+ optional string directPath = 3;
+ optional bytes mediaKey = 4;
+ optional int64 mediaKeyTimestamp = 5;
+ optional string objectID = 6;
+ optional bytes thumbnailScansSidecar = 7;
+ repeated uint32 thumbnailScanLengths = 8;
+ }
+
+ optional bytes JPEGThumbnail = 1;
+ optional DownloadableThumbnail downloadableThumbnail = 2;
+ optional uint32 thumbnailWidth = 3;
+ optional uint32 thumbnailHeight = 4;
+ }
+
+ optional uint64 fileLength = 1;
+ optional string mimetype = 2;
+ optional Thumbnail thumbnail = 3;
+ optional string objectID = 4;
+ }
+
+ message Integral {
+ optional bytes fileSHA256 = 1;
+ optional bytes mediaKey = 2;
+ optional bytes fileEncSHA256 = 3;
+ optional string directPath = 4;
+ optional int64 mediaKeyTimestamp = 5;
+ }
+
+ optional Integral integral = 1;
+ optional Ancillary ancillary = 2;
+}
+
+message ImageTransport {
+ message Ancillary {
+ enum HdType {
+ NONE = 0;
+ LQ_4K = 1;
+ HQ_4K = 2;
+ }
+
+ optional uint32 height = 1;
+ optional uint32 width = 2;
+ optional bytes scansSidecar = 3;
+ repeated uint32 scanLengths = 4;
+ optional bytes midQualityFileSHA256 = 5;
+ optional HdType hdType = 6;
+ repeated float memoriesConceptScores = 7 [packed=true];
+ repeated uint32 memoriesConceptIDs = 8 [packed=true];
+ }
+
+ message Integral {
+ optional WAMediaTransport transport = 1;
+ }
+
+ optional Integral integral = 1;
+ optional Ancillary ancillary = 2;
+}
+
+message VideoTransport {
+ message Ancillary {
+ enum Attribution {
+ NONE = 0;
+ GIPHY = 1;
+ TENOR = 2;
+ }
+
+ optional uint32 seconds = 1;
+ optional WACommon.MessageText caption = 2;
+ optional bool gifPlayback = 3;
+ optional uint32 height = 4;
+ optional uint32 width = 5;
+ optional bytes sidecar = 6;
+ optional Attribution gifAttribution = 7;
+ optional string accessibilityLabel = 8;
+ optional bool isHd = 9;
+ }
+
+ message Integral {
+ optional WAMediaTransport transport = 1;
+ }
+
+ optional Integral integral = 1;
+ optional Ancillary ancillary = 2;
+}
+
+message AudioTransport {
+ message Ancillary {
+ message AvatarAudio {
+ enum AnimationsType {
+ TALKING_A = 0;
+ IDLE_A = 1;
+ TALKING_B = 2;
+ IDLE_B = 3;
+ BACKGROUND = 4;
+ }
+
+ message DownloadableAvatarAnimations {
+ optional bytes fileSHA256 = 1;
+ optional bytes fileEncSHA256 = 2;
+ optional string directPath = 3;
+ optional bytes mediaKey = 4;
+ optional int64 mediaKeyTimestamp = 5;
+ optional string objectID = 6;
+ optional AnimationsType animationsType = 7;
+ }
+
+ optional uint32 poseID = 1;
+ repeated DownloadableAvatarAnimations avatarAnimations = 2;
+ }
+
+ optional uint32 seconds = 1;
+ optional AvatarAudio avatarAudio = 2;
+ optional string waveformData = 3;
+ optional bytes waveform = 4;
+ }
+
+ message Integral {
+ enum AudioFormat {
+ UNKNOWN = 0;
+ OPUS = 1;
+ }
+
+ optional WAMediaTransport transport = 1;
+ optional AudioFormat audioFormat = 2;
+ }
+
+ optional Integral integral = 1;
+ optional Ancillary ancillary = 2;
+}
+
+message DocumentTransport {
+ message Ancillary {
+ optional uint32 pageCount = 1;
+ }
+
+ message Integral {
+ optional WAMediaTransport transport = 1;
+ }
+
+ optional Integral integral = 1;
+ optional Ancillary ancillary = 2;
+}
+
+message StickerTransport {
+ message Ancillary {
+ optional uint32 pageCount = 1;
+ optional uint32 height = 2;
+ optional uint32 width = 3;
+ optional uint32 firstFrameLength = 4;
+ optional bytes firstFrameSidecar = 5;
+ optional string mustacheText = 6;
+ optional bool isThirdParty = 7;
+ optional string receiverFetchID = 8;
+ optional string accessibilityLabel = 9;
+ }
+
+ message Integral {
+ optional WAMediaTransport transport = 1;
+ optional bool isAnimated = 2;
+ optional string receiverFetchID = 3;
+ }
+
+ optional Integral integral = 1;
+ optional Ancillary ancillary = 2;
+}
+
+message ContactTransport {
+ message Ancillary {
+ optional string displayName = 1;
+ }
+
+ message Integral {
+ oneof contact {
+ string vcard = 1;
+ WAMediaTransport downloadableVcard = 2;
+ }
+ }
+
+ optional Integral integral = 1;
+ optional Ancillary ancillary = 2;
+}
diff --git a/crates/whatsmeow_proto/proto/waMmsRetry/WAMmsRetry.proto b/crates/whatsmeow_proto/proto/waMmsRetry/WAMmsRetry.proto
new file mode 100644
index 0000000000..3fdf6e5419
--- /dev/null
+++ b/crates/whatsmeow_proto/proto/waMmsRetry/WAMmsRetry.proto
@@ -0,0 +1,25 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+syntax = "proto2";
+package WAMmsRetry;
+option go_package = "go.mau.fi/whatsmeow/proto/waMmsRetry";
+
+message MediaRetryNotification {
+ enum ResultType {
+ GENERAL_ERROR = 0;
+ SUCCESS = 1;
+ NOT_FOUND = 2;
+ DECRYPTION_ERROR = 3;
+ }
+
+ optional string stanzaID = 1;
+ optional string directPath = 2;
+ optional ResultType result = 3;
+ optional bytes messageSecret = 4;
+}
+
+message ServerErrorReceipt {
+ optional string stanzaID = 1;
+}
diff --git a/crates/whatsmeow_proto/proto/waMsgApplication/WAMsgApplication.proto b/crates/whatsmeow_proto/proto/waMsgApplication/WAMsgApplication.proto
new file mode 100644
index 0000000000..797bfbe508
--- /dev/null
+++ b/crates/whatsmeow_proto/proto/waMsgApplication/WAMsgApplication.proto
@@ -0,0 +1,100 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+syntax = "proto2";
+package WAMsgApplication;
+option go_package = "go.mau.fi/whatsmeow/proto/waMsgApplication";
+
+import "waCommon/WACommon.proto";
+
+message MessageApplication {
+ message Metadata {
+ enum ThreadType {
+ DEFAULT = 0;
+ VANISH_MODE = 1;
+ DISAPPEARING_MESSAGES = 2;
+ }
+
+ message QuotedMessage {
+ optional string stanzaID = 1;
+ optional string remoteJID = 2;
+ optional string participant = 3;
+ optional Payload payload = 4;
+ }
+
+ message EphemeralSettingMap {
+ optional string chatJID = 1;
+ optional EphemeralSetting ephemeralSetting = 2;
+ }
+
+ oneof ephemeral {
+ EphemeralSetting chatEphemeralSetting = 1;
+ EphemeralSettingMap ephemeralSettingList = 2;
+ bytes ephemeralSharedSecret = 3;
+ }
+
+ optional uint32 forwardingScore = 5;
+ optional bool isForwarded = 6;
+ optional WACommon.SubProtocol businessMetadata = 7;
+ optional bytes frankingKey = 8;
+ optional int32 frankingVersion = 9;
+ optional QuotedMessage quotedMessage = 10;
+ optional ThreadType threadType = 11;
+ optional string readonlyMetadataDataclass = 12;
+ optional string groupID = 13;
+ optional uint32 groupSize = 14;
+ optional uint32 groupIndex = 15;
+ optional string botResponseID = 16;
+ optional string collapsibleID = 17;
+ optional string secondaryOtid = 18;
+ }
+
+ message Payload {
+ oneof content {
+ Content coreContent = 1;
+ Signal signal = 2;
+ ApplicationData applicationData = 3;
+ SubProtocolPayload subProtocol = 4;
+ }
+ }
+
+ message SubProtocolPayload {
+ oneof subProtocol {
+ WACommon.SubProtocol consumerMessage = 2;
+ WACommon.SubProtocol businessMessage = 3;
+ WACommon.SubProtocol paymentMessage = 4;
+ WACommon.SubProtocol multiDevice = 5;
+ WACommon.SubProtocol voip = 6;
+ WACommon.SubProtocol armadillo = 7;
+ }
+
+ optional WACommon.FutureProofBehavior futureProof = 1;
+ }
+
+ message ApplicationData {
+ }
+
+ message Signal {
+ }
+
+ message Content {
+ }
+
+ message EphemeralSetting {
+ enum EphemeralityType {
+ UNKNOWN = 0;
+ SEEN_ONCE = 1;
+ SEEN_BASED_WITH_TIMER = 2;
+ SEND_BASED_WITH_TIMER = 3;
+ }
+
+ optional uint32 ephemeralExpiration = 2;
+ optional int64 ephemeralSettingTimestamp = 3;
+ optional EphemeralityType ephemeralityType = 5;
+ optional bool isEphemeralSettingReset = 4;
+ }
+
+ optional Payload payload = 1;
+ optional Metadata metadata = 2;
+}
diff --git a/crates/whatsmeow_proto/proto/waMsgTransport/WAMsgTransport.proto b/crates/whatsmeow_proto/proto/waMsgTransport/WAMsgTransport.proto
new file mode 100644
index 0000000000..34870c38f5
--- /dev/null
+++ b/crates/whatsmeow_proto/proto/waMsgTransport/WAMsgTransport.proto
@@ -0,0 +1,79 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+syntax = "proto2";
+package WAMsgTransport;
+option go_package = "go.mau.fi/whatsmeow/proto/waMsgTransport";
+
+import "waCommon/WACommon.proto";
+
+message MessageTransport {
+ message Payload {
+ optional WACommon.SubProtocol applicationPayload = 1;
+ optional WACommon.FutureProofBehavior futureProof = 3;
+ }
+
+ message Protocol {
+ message Ancillary {
+ message BackupDirective {
+ enum ActionType {
+ NOOP = 0;
+ UPSERT = 1;
+ DELETE = 2;
+ UPSERT_AND_DELETE = 3;
+ }
+
+ optional string messageID = 1;
+ optional ActionType actionType = 2;
+ optional string supplementalKey = 3;
+ }
+
+ message ICDCParticipantDevices {
+ message ICDCIdentityListDescription {
+ optional int32 seq = 1;
+ optional bytes signingDevice = 2;
+ repeated bytes unknownDevices = 3;
+ repeated int32 unknownDeviceIDs = 4;
+ }
+
+ optional ICDCIdentityListDescription senderIdentity = 1;
+ repeated ICDCIdentityListDescription recipientIdentities = 2;
+ repeated string recipientUserJIDs = 3;
+ }
+
+ message SenderKeyDistributionMessage {
+ optional string groupID = 1;
+ optional bytes axolotlSenderKeyDistributionMessage = 2;
+ }
+
+ optional SenderKeyDistributionMessage skdm = 2;
+ optional DeviceListMetadata deviceListMetadata = 3;
+ optional ICDCParticipantDevices icdc = 4;
+ optional BackupDirective backupDirective = 5;
+ }
+
+ message Integral {
+ message DeviceSentMessage {
+ optional string destinationJID = 1;
+ optional string phash = 2;
+ }
+
+ optional bytes padding = 1;
+ optional DeviceSentMessage DSM = 2;
+ }
+
+ optional Integral integral = 1;
+ optional Ancillary ancillary = 2;
+ }
+
+ optional Payload payload = 1;
+ optional Protocol protocol = 2;
+}
+
+message DeviceListMetadata {
+ optional bytes senderKeyHash = 1;
+ optional uint64 senderTimestamp = 2;
+ optional bytes recipientKeyHash = 8;
+ optional uint64 recipientTimestamp = 9;
+}
diff --git a/crates/whatsmeow_proto/proto/waMultiDevice/WAMultiDevice.proto b/crates/whatsmeow_proto/proto/waMultiDevice/WAMultiDevice.proto
new file mode 100644
index 0000000000..d6329250e3
--- /dev/null
+++ b/crates/whatsmeow_proto/proto/waMultiDevice/WAMultiDevice.proto
@@ -0,0 +1,61 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+syntax = "proto2";
+package WAMultiDevice;
+option go_package = "go.mau.fi/whatsmeow/proto/waMultiDevice";
+
+message MultiDevice {
+ message Metadata {
+ }
+
+ message Payload {
+ oneof payload {
+ ApplicationData applicationData = 1;
+ Signal signal = 2;
+ }
+ }
+
+ message ApplicationData {
+ message AppStateSyncKeyRequestMessage {
+ repeated AppStateSyncKeyId keyIDs = 1;
+ }
+
+ message AppStateSyncKeyShareMessage {
+ repeated AppStateSyncKey keys = 1;
+ }
+
+ message AppStateSyncKey {
+ message AppStateSyncKeyData {
+ message AppStateSyncKeyFingerprint {
+ optional uint32 rawID = 1;
+ optional uint32 currentIndex = 2;
+ repeated uint32 deviceIndexes = 3 [packed=true];
+ }
+
+ optional bytes keyData = 1;
+ optional AppStateSyncKeyFingerprint fingerprint = 2;
+ optional int64 timestamp = 3;
+ }
+
+ optional AppStateSyncKeyId keyID = 1;
+ optional AppStateSyncKeyData keyData = 2;
+ }
+
+ message AppStateSyncKeyId {
+ optional bytes keyID = 1;
+ }
+
+ oneof applicationData {
+ AppStateSyncKeyShareMessage appStateSyncKeyShare = 1;
+ AppStateSyncKeyRequestMessage appStateSyncKeyRequest = 2;
+ }
+ }
+
+ message Signal {
+ }
+
+ optional Payload payload = 1;
+ optional Metadata metadata = 2;
+}
diff --git a/crates/whatsmeow_proto/proto/waQuickPromotionSurfaces/WAWebProtobufsQuickPromotionSurfaces.proto b/crates/whatsmeow_proto/proto/waQuickPromotionSurfaces/WAWebProtobufsQuickPromotionSurfaces.proto
new file mode 100644
index 0000000000..d14fd9f3fc
--- /dev/null
+++ b/crates/whatsmeow_proto/proto/waQuickPromotionSurfaces/WAWebProtobufsQuickPromotionSurfaces.proto
@@ -0,0 +1,44 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+syntax = "proto2";
+package WAWebProtobufsQuickPromotionSurfaces;
+option go_package = "go.mau.fi/whatsmeow/proto/waQuickPromotionSurfaces";
+
+message QP {
+ enum FilterResult {
+ TRUE = 1;
+ FALSE = 2;
+ UNKNOWN = 3;
+ }
+
+ enum FilterClientNotSupportedConfig {
+ PASS_BY_DEFAULT = 1;
+ FAIL_BY_DEFAULT = 2;
+ }
+
+ enum ClauseType {
+ AND = 1;
+ OR = 2;
+ NOR = 3;
+ }
+
+ message FilterClause {
+ required ClauseType clauseType = 1;
+ repeated FilterClause clauses = 2;
+ repeated Filter filters = 3;
+ }
+
+ message Filter {
+ required string filterName = 1;
+ repeated FilterParameters parameters = 2;
+ optional FilterResult filterResult = 3;
+ required FilterClientNotSupportedConfig clientNotSupportedConfig = 4;
+ }
+
+ message FilterParameters {
+ optional string key = 1;
+ optional string value = 2;
+ }
+}
diff --git a/crates/whatsmeow_proto/proto/waReporting/WAWebProtobufsReporting.proto b/crates/whatsmeow_proto/proto/waReporting/WAWebProtobufsReporting.proto
new file mode 100644
index 0000000000..f5e0e26ea2
--- /dev/null
+++ b/crates/whatsmeow_proto/proto/waReporting/WAWebProtobufsReporting.proto
@@ -0,0 +1,27 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+syntax = "proto3";
+package WAWebProtobufsReporting;
+option go_package = "go.mau.fi/whatsmeow/proto/waReporting";
+
+message Reportable {
+ uint32 minVersion = 1;
+ uint32 maxVersion = 2;
+ uint32 notReportableMinVersion = 3;
+ bool never = 4;
+}
+
+message Config {
+ map<uint32, Field> field = 1;
+ uint32 version = 2;
+}
+
+message Field {
+ uint32 minVersion = 1;
+ uint32 maxVersion = 2;
+ uint32 notReportableMinVersion = 3;
+ bool isMessage = 4;
+ map<uint32, Field> subfield = 5;
+}
diff --git a/crates/whatsmeow_proto/proto/waRoutingInfo/WAWebProtobufsRoutingInfo.proto b/crates/whatsmeow_proto/proto/waRoutingInfo/WAWebProtobufsRoutingInfo.proto
new file mode 100644
index 0000000000..3e43d8b7a5
--- /dev/null
+++ b/crates/whatsmeow_proto/proto/waRoutingInfo/WAWebProtobufsRoutingInfo.proto
@@ -0,0 +1,16 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+syntax = "proto2";
+package WAWebProtobufsRoutingInfo;
+option go_package = "go.mau.fi/whatsmeow/proto/waRoutingInfo";
+
+message RoutingInfo {
+ repeated int32 regionID = 1;
+ repeated int32 clusterID = 2;
+ optional int32 taskID = 3;
+ optional bool debug = 4;
+ optional bool tcpBbr = 5;
+ optional bool tcpKeepalive = 6;
+}
diff --git a/crates/whatsmeow_proto/proto/waServerSync/WAWebProtobufsServerSync.proto b/crates/whatsmeow_proto/proto/waServerSync/WAWebProtobufsServerSync.proto
new file mode 100644
index 0000000000..8e18798486
--- /dev/null
+++ b/crates/whatsmeow_proto/proto/waServerSync/WAWebProtobufsServerSync.proto
@@ -0,0 +1,92 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+syntax = "proto2";
+package WAWebProtobufsServerSync;
+option go_package = "go.mau.fi/whatsmeow/proto/waServerSync";
+
+message SyncdMutation {
+ enum SyncdOperation {
+ SET = 0;
+ REMOVE = 1;
+ }
+
+ optional SyncdOperation operation = 1;
+ optional SyncdRecord record = 2;
+}
+
+message SyncdVersion {
+ optional uint64 version = 1;
+}
+
+message ExitCode {
+ optional uint64 code = 1;
+ optional string text = 2;
+}
+
+message SyncdIndex {
+ optional bytes blob = 1;
+}
+
+message SyncdValue {
+ optional bytes blob = 1;
+}
+
+message KeyId {
+ optional bytes ID = 1;
+}
+
+message SyncdRecord {
+ optional SyncdIndex index = 1;
+ optional SyncdValue value = 2;
+ optional KeyId keyID = 3;
+}
+
+message ExternalBlobReference {
+ optional bytes mediaKey = 1;
+ optional string directPath = 2;
+ optional string handle = 3;
+ optional uint64 fileSizeBytes = 4;
+ optional bytes fileSHA256 = 5;
+ optional bytes fileEncSHA256 = 6;
+}
+
+message SyncdSnapshot {
+ optional SyncdVersion version = 1;
+ repeated SyncdRecord records = 2;
+ optional bytes mac = 3;
+ optional KeyId keyID = 4;
+}
+
+message SyncdMutations {
+ repeated SyncdMutation mutations = 1;
+}
+
+message SyncdPatch {
+ optional SyncdVersion version = 1;
+ repeated SyncdMutation mutations = 2;
+ optional ExternalBlobReference externalMutations = 3;
+ optional bytes snapshotMAC = 4;
+ optional bytes patchMAC = 5;
+ optional KeyId keyID = 6;
+ optional ExitCode exitCode = 7;
+ optional uint32 deviceIndex = 8;
+ optional bytes clientDebugData = 9;
+}
+
+message CoexStateSync {
+ message CollectionMutations {
+ optional string collection = 1;
+ repeated Mutation mutations = 2;
+ }
+
+ message Mutation {
+ optional SyncdIndex index = 1;
+ optional SyncdValue value = 2;
+ optional uint64 dirtyVersion = 3;
+ optional SyncdMutation.SyncdOperation operation = 4;
+ }
+
+ repeated CollectionMutations collectionMutations = 1;
+}
diff --git a/crates/whatsmeow_proto/proto/waStatusAttributions/WAStatusAttributions.proto b/crates/whatsmeow_proto/proto/waStatusAttributions/WAStatusAttributions.proto
new file mode 100644
index 0000000000..579080d556
--- /dev/null
+++ b/crates/whatsmeow_proto/proto/waStatusAttributions/WAStatusAttributions.proto
@@ -0,0 +1,110 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+syntax = "proto2";
+package WAStatusAttributions;
+option go_package = "go.mau.fi/whatsmeow/proto/waStatusAttributions";
+
+message StatusAttribution {
+ enum Type {
+ UNKNOWN = 0;
+ RESHARE = 1;
+ EXTERNAL_SHARE = 2;
+ MUSIC = 3;
+ STATUS_MENTION = 4;
+ GROUP_STATUS = 5;
+ RL_ATTRIBUTION = 6;
+ AI_CREATED = 7;
+ LAYOUTS = 8;
+ NEWSLETTER_STATUS = 9;
+ STATUS_CLOSE_SHARING = 10;
+ }
+
+ message AiCreatedAttribution {
+ enum Source {
+ UNKNOWN = 0;
+ STATUS_MIMICRY = 1;
+ }
+
+ optional Source source = 1;
+ }
+
+ message RLAttribution {
+ enum Source {
+ UNKNOWN = 0;
+ RAY_BAN_META_GLASSES = 1;
+ OAKLEY_META_GLASSES = 2;
+ HYPERNOVA_GLASSES = 3;
+ }
+
+ optional Source source = 1;
+ }
+
+ message ExternalShare {
+ enum Source {
+ UNKNOWN = 0;
+ INSTAGRAM = 1;
+ FACEBOOK = 2;
+ MESSENGER = 3;
+ SPOTIFY = 4;
+ YOUTUBE = 5;
+ PINTEREST = 6;
+ THREADS = 7;
+ APPLE_MUSIC = 8;
+ SHARECHAT = 9;
+ GOOGLE_PHOTOS = 10;
+ SOUNDCLOUD = 11;
+ }
+
+ optional string actionURL = 1;
+ optional Source source = 2;
+ optional int32 duration = 3;
+ optional string actionFallbackURL = 4;
+ }
+
+ message StatusReshare {
+ enum Source {
+ UNKNOWN = 0;
+ INTERNAL_RESHARE = 1;
+ MENTION_RESHARE = 2;
+ CHANNEL_RESHARE = 3;
+ FORWARD = 4;
+ }
+
+ message Metadata {
+ optional int32 duration = 1;
+ optional string channelJID = 2;
+ optional int32 channelMessageID = 3;
+ optional bool hasMultipleReshares = 4;
+ }
+
+ optional Source source = 1;
+ optional Metadata metadata = 2;
+ }
+
+ message GroupStatus {
+ optional string authorJID = 1;
+ }
+
+ message Music {
+ optional string authorName = 1;
+ optional string songID = 2;
+ optional string title = 3;
+ optional string author = 4;
+ optional string artistAttribution = 5;
+ optional bool isExplicit = 6;
+ }
+
+ oneof attributionData {
+ StatusReshare statusReshare = 3;
+ ExternalShare externalShare = 4;
+ Music music = 5;
+ GroupStatus groupStatus = 6;
+ RLAttribution rlAttribution = 7;
+ AiCreatedAttribution aiCreatedAttribution = 8;
+ }
+
+ optional Type type = 1;
+ optional string actionURL = 2;
+}
diff --git a/crates/whatsmeow_proto/proto/waSyncAction/WAWebProtobufSyncAction.proto b/crates/whatsmeow_proto/proto/waSyncAction/WAWebProtobufSyncAction.proto
new file mode 100644
index 0000000000..da309802b5
--- /dev/null
+++ b/crates/whatsmeow_proto/proto/waSyncAction/WAWebProtobufSyncAction.proto
@@ -0,0 +1,1184 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+syntax = "proto2";
+package WAWebProtobufSyncAction;
+option go_package = "go.mau.fi/whatsmeow/proto/waSyncAction";
+
+import "waChatLockSettings/WAWebProtobufsChatLockSettings.proto";
+import "waDeviceCapabilities/WAWebProtobufsDeviceCapabilities.proto";
+import "waCommon/WACommon.proto";
+
+enum CollectionName {
+ COLLECTION_NAME_UNKNOWN = 0;
+ REGULAR = 1;
+ REGULAR_LOW = 2;
+ REGULAR_HIGH = 3;
+ CRITICAL_BLOCK = 4;
+ CRITICAL_UNBLOCK_LOW = 5;
+}
+
+enum MutationProps {
+ STAR_ACTION = 2;
+ CONTACT_ACTION = 3;
+ MUTE_ACTION = 4;
+ PIN_ACTION = 5;
+ SECURITY_NOTIFICATION_SETTING = 6;
+ PUSH_NAME_SETTING = 7;
+ QUICK_REPLY_ACTION = 8;
+ RECENT_EMOJI_WEIGHTS_ACTION = 11;
+ LABEL_MESSAGE_ACTION = 13;
+ LABEL_EDIT_ACTION = 14;
+ LABEL_ASSOCIATION_ACTION = 15;
+ LOCALE_SETTING = 16;
+ ARCHIVE_CHAT_ACTION = 17;
+ DELETE_MESSAGE_FOR_ME_ACTION = 18;
+ KEY_EXPIRATION = 19;
+ MARK_CHAT_AS_READ_ACTION = 20;
+ CLEAR_CHAT_ACTION = 21;
+ DELETE_CHAT_ACTION = 22;
+ UNARCHIVE_CHATS_SETTING = 23;
+ PRIMARY_FEATURE = 24;
+ ANDROID_UNSUPPORTED_ACTIONS = 26;
+ AGENT_ACTION = 27;
+ SUBSCRIPTION_ACTION = 28;
+ USER_STATUS_MUTE_ACTION = 29;
+ TIME_FORMAT_ACTION = 30;
+ NUX_ACTION = 31;
+ PRIMARY_VERSION_ACTION = 32;
+ STICKER_ACTION = 33;
+ REMOVE_RECENT_STICKER_ACTION = 34;
+ CHAT_ASSIGNMENT = 35;
+ CHAT_ASSIGNMENT_OPENED_STATUS = 36;
+ PN_FOR_LID_CHAT_ACTION = 37;
+ MARKETING_MESSAGE_ACTION = 38;
+ MARKETING_MESSAGE_BROADCAST_ACTION = 39;
+ EXTERNAL_WEB_BETA_ACTION = 40;
+ PRIVACY_SETTING_RELAY_ALL_CALLS = 41;
+ CALL_LOG_ACTION = 42;
+ UGC_BOT = 43;
+ STATUS_PRIVACY = 44;
+ BOT_WELCOME_REQUEST_ACTION = 45;
+ DELETE_INDIVIDUAL_CALL_LOG = 46;
+ LABEL_REORDERING_ACTION = 47;
+ PAYMENT_INFO_ACTION = 48;
+ CUSTOM_PAYMENT_METHODS_ACTION = 49;
+ LOCK_CHAT_ACTION = 50;
+ CHAT_LOCK_SETTINGS = 51;
+ WAMO_USER_IDENTIFIER_ACTION = 52;
+ PRIVACY_SETTING_DISABLE_LINK_PREVIEWS_ACTION = 53;
+ DEVICE_CAPABILITIES = 54;
+ NOTE_EDIT_ACTION = 55;
+ FAVORITES_ACTION = 56;
+ MERCHANT_PAYMENT_PARTNER_ACTION = 57;
+ WAFFLE_ACCOUNT_LINK_STATE_ACTION = 58;
+ USERNAME_CHAT_START_MODE = 59;
+ NOTIFICATION_ACTIVITY_SETTING_ACTION = 60;
+ LID_CONTACT_ACTION = 61;
+ CTWA_PER_CUSTOMER_DATA_SHARING_ACTION = 62;
+ PAYMENT_TOS_ACTION = 63;
+ PRIVACY_SETTING_CHANNELS_PERSONALISED_RECOMMENDATION_ACTION = 64;
+ BUSINESS_BROADCAST_ASSOCIATION_ACTION = 65;
+ DETECTED_OUTCOMES_STATUS_ACTION = 66;
+ MAIBA_AI_FEATURES_CONTROL_ACTION = 68;
+ BUSINESS_BROADCAST_LIST_ACTION = 69;
+ MUSIC_USER_ID_ACTION = 70;
+ STATUS_POST_OPT_IN_NOTIFICATION_PREFERENCES_ACTION = 71;
+ AVATAR_UPDATED_ACTION = 72;
+ GALAXY_FLOW_ACTION = 73;
+ PRIVATE_PROCESSING_SETTING_ACTION = 74;
+ NEWSLETTER_SAVED_INTERESTS_ACTION = 75;
+ AI_THREAD_RENAME_ACTION = 76;
+ INTERACTIVE_MESSAGE_ACTION = 77;
+ SETTINGS_SYNC_ACTION = 78;
+ OUT_CONTACT_ACTION = 79;
+ NCT_SALT_SYNC_ACTION = 80;
+ BUSINESS_BROADCAST_CAMPAIGN_ACTION = 81;
+ BUSINESS_BROADCAST_INSIGHTS_ACTION = 82;
+ CUSTOMER_DATA_ACTION = 83;
+ SUBSCRIPTIONS_SYNC_V2_ACTION = 84;
+ THREAD_PIN_ACTION = 85;
+ AUTO_ORGANIZE_BUSINESS_CHAT_SETTING = 86;
+ BIZ_AI_SETTINGS_NUDGE_ACTION = 87;
+ COEX_V2_VERSION_ACTION = 88;
+ WASA_ROOT_SECRET_ACTION = 89;
+ BUBBLE_LOCK_MESSAGE_ACTION = 90;
+ LABEL_SUBLIST_ACTION = 91;
+ DEVICE_CAPABILITIES_V2 = 92;
+ CTWA_MESSAGE_RECEIVED_ACTION = 93;
+ SHARED_DEVICE_ALLOWLIST_ACTION = 94;
+ CONTACT_MANAGER_METADATA_ACTION = 95;
+ BUSINESS_FOLDER_ACTIVATION_ACTION = 96;
+ GROUP_HISTORY_TOGGLE_ACTION = 97;
+ BB_PRO_PENDING_CUSTOMER_BASE_ACTION = 98;
+ COMMUNITY_NESTING_STATE_ACTION = 99;
+ SHARED_DEVICE_SECRET_ACTION = 100;
+ SHARE_OWN_PN = 10001;
+ BUSINESS_BROADCAST_ACTION = 10002;
+ AI_THREAD_DELETE_ACTION = 10003;
+}
+
+enum BusinessBroadcastCampaignBBProStatus {
+ BB_PRO_ACTIVE = 1;
+ BB_PRO_COMPLETED = 2;
+ BB_PRO_IN_DRAFT = 3;
+ BB_PRO_IN_REVIEW = 4;
+ BB_PRO_NOT_SENDING = 5;
+ BB_PRO_OFF = 6;
+ BB_PRO_REJECTED = 7;
+ BB_PRO_SCHEDULED = 8;
+ BB_PRO_SENDING_LIMITED = 9;
+ BB_PRO_PROCESSING = 10;
+}
+
+enum BusinessBroadcastCampaignStatus {
+ DRAFT = 1;
+ SCHEDULED = 2;
+ PROCESSING = 3;
+ FAILED = 4;
+ SENT = 5;
+}
+
+message CallLogRecord {
+ enum CallType {
+ REGULAR = 0;
+ SCHEDULED_CALL = 1;
+ VOICE_CHAT = 2;
+ }
+
+ enum SilenceReason {
+ NONE = 0;
+ SCHEDULED = 1;
+ PRIVACY = 2;
+ LIGHTWEIGHT = 3;
+ }
+
+ enum CallResult {
+ CONNECTED = 0;
+ REJECTED = 1;
+ CANCELLED = 2;
+ ACCEPTEDELSEWHERE = 3;
+ MISSED = 4;
+ INVALID = 5;
+ UNAVAILABLE = 6;
+ UPCOMING = 7;
+ FAILED = 8;
+ ABANDONED = 9;
+ ONGOING = 10;
+ }
+
+ message ParticipantInfo {
+ optional string userJID = 1;
+ optional CallResult callResult = 2;
+ optional GuestInfo guestInfo = 3;
+ }
+
+ message GuestInfo {
+ optional string pushName = 1;
+ }
+
+ optional CallResult callResult = 1;
+ optional bool isDndMode = 2;
+ optional SilenceReason silenceReason = 3;
+ optional int64 duration = 4;
+ optional int64 startTime = 5;
+ optional bool isIncoming = 6;
+ optional bool isVideo = 7;
+ optional bool isCallLink = 8;
+ optional string callLinkToken = 9;
+ optional string scheduledCallID = 10;
+ optional string callID = 11;
+ optional string callCreatorJID = 12;
+ optional string groupJID = 13;
+ repeated ParticipantInfo participants = 14;
+ optional CallType callType = 15;
+}
+
+message CommunityNestingStateAction {
+ enum NestingState {
+ NESTING_STATE_UNKNOWN = 0;
+ NESTING_STATE_NESTED = 1;
+ NESTING_STATE_UNNESTED = 2;
+ }
+
+ optional NestingState nestingState = 1;
+}
+
+message GroupHistoryToggleAction {
+ enum GroupHistoryToggleMode {
+ GROUP_HISTORY_TOGGLE_MODE_UNKNOWN = 0;
+ GROUP_HISTORY_TOGGLE_MODE_ON = 1;
+ GROUP_HISTORY_TOGGLE_MODE_OFF = 2;
+ }
+
+ optional GroupHistoryToggleMode groupHistoryToggleMode = 1;
+}
+
+message WASARootSecretAction {
+ message RootSecretEntry {
+ enum Status {
+ INACTIVE = 0;
+ ACTIVE = 1;
+ }
+
+ optional string ID = 1;
+ optional bytes rootSecret = 2;
+ optional int64 epoch = 3;
+ optional Status status = 4;
+ }
+
+ repeated RootSecretEntry secrets = 1;
+}
+
+message SettingsSyncAction {
+ enum MediaQualitySetting {
+ MEDIA_QUALITY_UNKNOWN = 0;
+ STANDARD = 1;
+ HD = 2;
+ }
+
+ enum DisplayMode {
+ DISPLAY_MODE_UNKNOWN = 0;
+ ALWAYS = 1;
+ NEVER = 2;
+ ONLY_WHEN_APP_IS_OPEN = 3;
+ }
+
+ enum SettingKey {
+ SETTING_KEY_UNKNOWN = 0;
+ START_AT_LOGIN = 1;
+ MINIMIZE_TO_TRAY = 2;
+ LANGUAGE = 3;
+ REPLACE_TEXT_WITH_EMOJI = 4;
+ BANNER_NOTIFICATION_DISPLAY_MODE = 5;
+ UNREAD_COUNTER_BADGE_DISPLAY_MODE = 6;
+ IS_MESSAGES_NOTIFICATION_ENABLED = 7;
+ IS_CALLS_NOTIFICATION_ENABLED = 8;
+ IS_REACTIONS_NOTIFICATION_ENABLED = 9;
+ IS_STATUS_REACTIONS_NOTIFICATION_ENABLED = 10;
+ IS_TEXT_PREVIEW_FOR_NOTIFICATION_ENABLED = 11;
+ DEFAULT_NOTIFICATION_TONE_ID = 12;
+ GROUP_DEFAULT_NOTIFICATION_TONE_ID = 13;
+ APP_THEME = 14;
+ WALLPAPER_ID = 15;
+ IS_DOODLE_WALLPAPER_ENABLED = 16;
+ FONT_SIZE = 17;
+ IS_PHOTOS_AUTODOWNLOAD_ENABLED = 18;
+ IS_AUDIOS_AUTODOWNLOAD_ENABLED = 19;
+ IS_VIDEOS_AUTODOWNLOAD_ENABLED = 20;
+ IS_DOCUMENTS_AUTODOWNLOAD_ENABLED = 21;
+ DISABLE_LINK_PREVIEWS = 22;
+ NOTIFICATION_TONE_ID = 23;
+ MEDIA_UPLOAD_QUALITY = 24;
+ IS_SPELL_CHECK_ENABLED = 25;
+ IS_ENTER_TO_SEND_ENABLED = 26;
+ IS_GROUP_MESSAGE_NOTIFICATION_ENABLED = 27;
+ IS_GROUP_REACTIONS_NOTIFICATION_ENABLED = 28;
+ IS_STATUS_NOTIFICATION_ENABLED = 29;
+ STATUS_NOTIFICATION_TONE_ID = 30;
+ SHOULD_PLAY_SOUND_FOR_CALL_NOTIFICATION = 31;
+ CHAT_THEME_ID = 32;
+ COLOR_SCHEME_ID = 33;
+ STOCK_WALLPAPER_IMAGE_ID = 34;
+ }
+
+ enum SettingPlatform {
+ PLATFORM_UNKNOWN = 0;
+ WEB = 1;
+ HYBRID = 2;
+ WINDOWS = 3;
+ MAC = 4;
+ }
+
+ optional bool startAtLogin = 1;
+ optional bool minimizeToTray = 2;
+ optional string language = 3;
+ optional bool replaceTextWithEmoji = 4;
+ optional DisplayMode bannerNotificationDisplayMode = 5;
+ optional DisplayMode unreadCounterBadgeDisplayMode = 6;
+ optional bool isMessagesNotificationEnabled = 7;
+ optional bool isCallsNotificationEnabled = 8;
+ optional bool isReactionsNotificationEnabled = 9;
+ optional bool isStatusReactionsNotificationEnabled = 10;
+ optional bool isTextPreviewForNotificationEnabled = 11;
+ optional int32 defaultNotificationToneID = 12;
+ optional int32 groupDefaultNotificationToneID = 13;
+ optional int32 appTheme = 14;
+ optional int32 wallpaperID = 15;
+ optional bool isDoodleWallpaperEnabled = 16;
+ optional int32 fontSize = 17;
+ optional bool isPhotosAutodownloadEnabled = 18;
+ optional bool isAudiosAutodownloadEnabled = 19;
+ optional bool isVideosAutodownloadEnabled = 20;
+ optional bool isDocumentsAutodownloadEnabled = 21;
+ optional bool disableLinkPreviews = 22;
+ optional int32 notificationToneID = 23;
+ optional MediaQualitySetting mediaUploadQuality = 24;
+ optional bool isSpellCheckEnabled = 25;
+ optional bool isEnterToSendEnabled = 26;
+ optional bool isGroupMessageNotificationEnabled = 27;
+ optional bool isGroupReactionsNotificationEnabled = 28;
+ optional bool isStatusNotificationEnabled = 29;
+ optional int32 statusNotificationToneID = 30;
+ optional bool shouldPlaySoundForCallNotification = 31;
+ optional string chatThemeID = 32;
+ optional string colorSchemeID = 33;
+ optional string stockWallpaperImageID = 34;
+}
+
+message InteractiveMessageAction {
+ enum InteractiveMessageActionMode {
+ DISABLE_CTA = 1;
+ }
+
+ required InteractiveMessageActionMode type = 1;
+ optional string agmID = 2;
+}
+
+message PrivateProcessingSettingAction {
+ enum PrivateProcessingStatus {
+ UNDEFINED = 0;
+ ENABLED = 1;
+ DISABLED = 2;
+ }
+
+ optional PrivateProcessingStatus privateProcessingStatus = 1;
+}
+
+message AvatarUpdatedAction {
+ enum AvatarEventType {
+ UPDATED = 0;
+ CREATED = 1;
+ DELETED = 2;
+ }
+
+ optional AvatarEventType eventType = 1;
+ repeated StickerAction recentAvatarStickers = 2;
+}
+
+message BizAISettingsNudgeAction {
+ enum BizAISettingsCategory {
+ UNKNOWN = 0;
+ INSTRUCTIONS = 1;
+ RESPONSE_SETTINGS = 2;
+ EXAMPLE_RESPONSES = 3;
+ KNOWLEDGE = 4;
+ LEAD_GEN = 5;
+ HANDOFF_REMOVAL_TIMING = 6;
+ }
+
+ optional BizAISettingsCategory category = 1;
+ optional int64 version = 2;
+ optional int64 updatedAtMS = 3;
+}
+
+message MaibaAIFeaturesControlAction {
+ enum MaibaAIReplyMode {
+ MUTED = 0;
+ AI_AGENT = 1;
+ SUGGESTIONS = 2;
+ }
+
+ enum MaibaAIFeatureStatus {
+ ENABLED = 0;
+ ENABLED_HAS_LEARNING = 1;
+ DISABLED = 2;
+ }
+
+ optional MaibaAIFeatureStatus aiFeatureStatus = 1;
+ optional MaibaAIReplyMode aiReplyMode = 2;
+}
+
+message PaymentTosAction {
+ enum PaymentNotice {
+ BR_PAY_PRIVACY_POLICY = 0;
+ }
+
+ required PaymentNotice paymentNotice = 1;
+ required bool accepted = 2;
+}
+
+message NotificationActivitySettingAction {
+ enum NotificationActivitySetting {
+ DEFAULT_ALL_MESSAGES = 0;
+ ALL_MESSAGES = 1;
+ HIGHLIGHTS = 2;
+ DEFAULT_HIGHLIGHTS = 3;
+ }
+
+ optional NotificationActivitySetting notificationActivitySetting = 1;
+}
+
+message WaffleAccountLinkStateAction {
+ enum AccountLinkState {
+ ACTIVE = 0;
+ PAUSED = 1;
+ UNLINKED = 2;
+ }
+
+ optional AccountLinkState linkState = 2;
+}
+
+message MerchantPaymentPartnerAction {
+ enum Status {
+ ACTIVE = 0;
+ INACTIVE = 1;
+ }
+
+ required Status status = 1;
+ required string country = 2;
+ optional string gatewayName = 3;
+ optional string credentialID = 4;
+}
+
+message NoteEditAction {
+ enum NoteType {
+ UNSTRUCTURED = 1;
+ STRUCTURED = 2;
+ }
+
+ optional NoteType type = 1;
+ optional string chatJID = 2;
+ optional int64 createdAt = 3;
+ optional bool deleted = 4;
+ optional string unstructuredContent = 5;
+}
+
+message StatusPrivacyAction {
+ enum StatusDistributionMode {
+ ALLOW_LIST = 0;
+ DENY_LIST = 1;
+ CONTACTS = 2;
+ CLOSE_FRIENDS = 3;
+ CUSTOM_LIST = 4;
+ }
+
+ message CustomList {
+ optional string listID = 1;
+ optional string name = 2;
+ optional string emoji = 3;
+ optional bool isSelected = 4;
+ repeated string userJID = 5;
+ }
+
+ optional StatusDistributionMode mode = 1;
+ repeated string userJID = 2;
+ optional bool shareToFb = 3;
+ optional bool shareToIg = 4;
+ repeated CustomList customLists = 5;
+ repeated StatusDistributionMode modes = 6;
+}
+
+message MarketingMessageAction {
+ enum MarketingMessagePrototypeType {
+ PERSONALIZED = 0;
+ }
+
+ optional string name = 1;
+ optional string message = 2;
+ optional MarketingMessagePrototypeType type = 3;
+ optional int64 createdAt = 4;
+ optional int64 lastSentAt = 5;
+ optional bool isDeleted = 6;
+ optional string mediaID = 7;
+}
+
+message UsernameChatStartModeAction {
+ enum ChatStartMode {
+ LID = 1;
+ PN = 2;
+ }
+
+ optional ChatStartMode chatStartMode = 1;
+}
+
+message LabelEditAction {
+ enum ListType {
+ NONE = 0;
+ UNREAD = 1;
+ GROUPS = 2;
+ FAVORITES = 3;
+ PREDEFINED = 4;
+ CUSTOM = 5;
+ COMMUNITY = 6;
+ SERVER_ASSIGNED = 7;
+ DRAFTED = 8;
+ AI_HANDOFF = 9;
+ CHANNELS = 10;
+ AI_RESPONDING = 11;
+ ARCHIVED = 12;
+ LOCKED = 13;
+ INVITES = 14;
+ THIRD_PARTY = 15;
+ LEAD = 16;
+ MENTIONS_AND_REPLIES = 17;
+ REQUESTS = 18;
+ BUSINESS = 19;
+ ONE_ON_ONE = 20;
+ }
+
+ optional string name = 1;
+ optional int32 color = 2;
+ optional int32 predefinedID = 3;
+ optional bool deleted = 4;
+ optional int32 orderIndex = 5;
+ optional bool isActive = 6;
+ optional ListType type = 7;
+ optional bool isImmutable = 8;
+ optional int64 muteEndTimeMS = 9;
+}
+
+message PatchDebugData {
+ enum Platform {
+ ANDROID = 0;
+ SMBA = 1;
+ IPHONE = 2;
+ SMBI = 3;
+ WEB = 4;
+ UWP = 5;
+ DARWIN = 6;
+ IPAD = 7;
+ WEAROS = 8;
+ WASG = 9;
+ WEARM = 10;
+ CAPI = 11;
+ }
+
+ optional bytes currentLthash = 1;
+ optional bytes newLthash = 2;
+ optional bytes patchVersion = 3;
+ optional bytes collectionName = 4;
+ optional bytes firstFourBytesFromAHashOfSnapshotMACKey = 5;
+ optional bytes newLthashSubtract = 6;
+ optional int32 numberAdd = 7;
+ optional int32 numberRemove = 8;
+ optional int32 numberOverride = 9;
+ optional Platform senderPlatform = 10;
+ optional bool isSenderPrimary = 11;
+}
+
+/*
+enum MutationName {
+ STAR_ACTION = star;
+ CONTACT_ACTION = contact;
+ MUTE_ACTION = mute;
+ PIN_ACTION = pin_v1;
+ SECURITY_NOTIFICATION_SETTING = setting_securityNotification;
+ PUSH_NAME_SETTING = setting_pushName;
+ QUICK_REPLY_ACTION = quick_reply;
+ RECENT_EMOJI_WEIGHTS_ACTION = recent_emoji_weights_action;
+ LABEL_MESSAGE_ACTION = label_message;
+ LABEL_EDIT_ACTION = label_edit;
+ LABEL_ASSOCIATION_ACTION = label_jid;
+ LOCALE_SETTING = setting_locale;
+ ARCHIVE_CHAT_ACTION = archive;
+ DELETE_MESSAGE_FOR_ME_ACTION = deleteMessageForMe;
+ KEY_EXPIRATION = sentinel;
+ MARK_CHAT_AS_READ_ACTION = markChatAsRead;
+ CLEAR_CHAT_ACTION = clearChat;
+ DELETE_CHAT_ACTION = deleteChat;
+ UNARCHIVE_CHATS_SETTING = setting_unarchiveChats;
+ PRIMARY_FEATURE = primary_feature;
+ ANDROID_UNSUPPORTED_ACTIONS = android_unsupported_actions;
+ AGENT_ACTION = deviceAgent;
+ SUBSCRIPTION_ACTION = subscription;
+ USER_STATUS_MUTE_ACTION = userStatusMute;
+ TIME_FORMAT_ACTION = time_format;
+ NUX_ACTION = nux;
+ PRIMARY_VERSION_ACTION = primary_version;
+ STICKER_ACTION = favoriteSticker;
+ REMOVE_RECENT_STICKER_ACTION = removeRecentSticker;
+ CHAT_ASSIGNMENT = agentChatAssignment;
+ CHAT_ASSIGNMENT_OPENED_STATUS = agentChatAssignmentOpenedStatus;
+ PN_FOR_LID_CHAT_ACTION = pnForLidChat;
+ MARKETING_MESSAGE_ACTION = marketingMessage;
+ MARKETING_MESSAGE_BROADCAST_ACTION = marketingMessageBroadcast;
+ EXTERNAL_WEB_BETA_ACTION = external_web_beta;
+ PRIVACY_SETTING_RELAY_ALL_CALLS = setting_relayAllCalls;
+ CALL_LOG_ACTION = call_log;
+ UGC_BOT = ugc_bot;
+ STATUS_PRIVACY = status_privacy;
+ BOT_WELCOME_REQUEST_ACTION = bot_welcome_request;
+ DELETE_INDIVIDUAL_CALL_LOG = delete_individual_call_log;
+ LABEL_REORDERING_ACTION = label_reordering;
+ PAYMENT_INFO_ACTION = payment_info;
+ CUSTOM_PAYMENT_METHODS_ACTION = custom_payment_methods;
+ LOCK_CHAT_ACTION = lock;
+ CHAT_LOCK_SETTINGS = setting_chatLock;
+ WAMO_USER_IDENTIFIER_ACTION = generated_wui;
+ PRIVACY_SETTING_DISABLE_LINK_PREVIEWS_ACTION = setting_disableLinkPreviews;
+ DEVICE_CAPABILITIES = device_capabilities;
+ NOTE_EDIT_ACTION = note_edit;
+ FAVORITES_ACTION = favorites;
+ MERCHANT_PAYMENT_PARTNER_ACTION = merchant_payment_partner;
+ WAFFLE_ACCOUNT_LINK_STATE_ACTION = waffle_account_link_state;
+ USERNAME_CHAT_START_MODE = usernameChatStartMode;
+ NOTIFICATION_ACTIVITY_SETTING_ACTION = notificationActivitySetting;
+ LID_CONTACT_ACTION = lid_contact;
+ CTWA_PER_CUSTOMER_DATA_SHARING_ACTION = ctwaPerCustomerDataSharing;
+ PAYMENT_TOS_ACTION = payment_tos;
+ PRIVACY_SETTING_CHANNELS_PERSONALISED_RECOMMENDATION_ACTION = setting_channels_personalised_recommendation_optout;
+ BUSINESS_BROADCAST_ASSOCIATION_ACTION = broadcast_jid;
+ DETECTED_OUTCOMES_STATUS_ACTION = detected_outcomes_status_action;
+ MAIBA_AI_FEATURES_CONTROL_ACTION = maiba_ai_features_control;
+ BUSINESS_BROADCAST_LIST_ACTION = business_broadcast_list;
+ MUSIC_USER_ID_ACTION = music_user_id;
+ STATUS_POST_OPT_IN_NOTIFICATION_PREFERENCES_ACTION = status_post_opt_in_notification_preferences_action;
+ AVATAR_UPDATED_ACTION = avatar_updated_action;
+ GALAXY_FLOW_ACTION = galaxy_flow_action;
+ PRIVATE_PROCESSING_SETTING_ACTION = private_processing_setting;
+ NEWSLETTER_SAVED_INTERESTS_ACTION = newsletter_saved_interests;
+ AI_THREAD_RENAME_ACTION = ai_thread_rename;
+ INTERACTIVE_MESSAGE_ACTION = interactive_message_action;
+ SETTINGS_SYNC_ACTION = settings_sync;
+ OUT_CONTACT_ACTION = out_contact;
+ NCT_SALT_SYNC_ACTION = nct_salt_sync;
+ BUSINESS_BROADCAST_CAMPAIGN_ACTION = business_broadcast_campaign;
+ BUSINESS_BROADCAST_INSIGHTS_ACTION = business_broadcast_insights_sync;
+ CUSTOMER_DATA_ACTION = customer_data;
+ SUBSCRIPTIONS_SYNC_V2_ACTION = subscriptions_sync_v2;
+ THREAD_PIN_ACTION = thread_pin;
+ AUTO_ORGANIZE_BUSINESS_CHAT_SETTING = setting_autoOrganizeBusinessChat;
+ BIZ_AI_SETTINGS_NUDGE_ACTION = biz_ai_settings_nudge;
+ COEX_V2_VERSION_ACTION = coexV2Version;
+ WASA_ROOT_SECRET_ACTION = wasa_root_secret;
+ BUBBLE_LOCK_MESSAGE_ACTION = lock_message;
+ LABEL_SUBLIST_ACTION = label_sublist;
+ DEVICE_CAPABILITIES_V2 = device_capabilities_v2;
+ CTWA_MESSAGE_RECEIVED_ACTION = ctwa_message_received;
+ SHARED_DEVICE_ALLOWLIST_ACTION = shared_device_allowlist;
+ CONTACT_MANAGER_METADATA_ACTION = contact_manager_metadata;
+ BUSINESS_FOLDER_ACTIVATION_ACTION = business_folder_activation;
+ GROUP_HISTORY_TOGGLE_ACTION = group_history_toggle;
+ BB_PRO_PENDING_CUSTOMER_BASE_ACTION = bb_pro_pending_customer_base_action;
+ COMMUNITY_NESTING_STATE_ACTION = community_nesting_state;
+ SHARED_DEVICE_SECRET_ACTION = shared_device_secret;
+ SHARE_OWN_PN = shareOwnPn;
+ BUSINESS_BROADCAST_ACTION = broadcast;
+ AI_THREAD_DELETE_ACTION = ai_thread_delete;
+}
+*/
+
+/*
+enum CollectionName {
+}
+*/
+
+/*
+enum CollectionNameStr {
+ REGULAR = regular;
+ REGULAR_LOW = regular_low;
+ REGULAR_HIGH = regular_high;
+ CRITICAL_BLOCK = critical_block;
+ CRITICAL_UNBLOCK_LOW = critical_unblock_low;
+}
+*/
+
+message RecentEmojiWeight {
+ optional string emoji = 1;
+ optional float weight = 2;
+}
+
+message SyncActionValue {
+ optional int64 timestamp = 1;
+ optional StarAction starAction = 2;
+ optional ContactAction contactAction = 3;
+ optional MuteAction muteAction = 4;
+ optional PinAction pinAction = 5;
+ optional PushNameSetting pushNameSetting = 7;
+ optional QuickReplyAction quickReplyAction = 8;
+ optional RecentEmojiWeightsAction recentEmojiWeightsAction = 11;
+ optional LabelEditAction labelEditAction = 14;
+ optional LabelAssociationAction labelAssociationAction = 15;
+ optional LocaleSetting localeSetting = 16;
+ optional ArchiveChatAction archiveChatAction = 17;
+ optional DeleteMessageForMeAction deleteMessageForMeAction = 18;
+ optional KeyExpiration keyExpiration = 19;
+ optional MarkChatAsReadAction markChatAsReadAction = 20;
+ optional ClearChatAction clearChatAction = 21;
+ optional DeleteChatAction deleteChatAction = 22;
+ optional UnarchiveChatsSetting unarchiveChatsSetting = 23;
+ optional PrimaryFeature primaryFeature = 24;
+ optional AndroidUnsupportedActions androidUnsupportedActions = 26;
+ optional AgentAction agentAction = 27;
+ optional SubscriptionAction subscriptionAction = 28;
+ optional UserStatusMuteAction userStatusMuteAction = 29;
+ optional TimeFormatAction timeFormatAction = 30;
+ optional NuxAction nuxAction = 31;
+ optional PrimaryVersionAction primaryVersionAction = 32;
+ optional StickerAction stickerAction = 33;
+ optional RemoveRecentStickerAction removeRecentStickerAction = 34;
+ optional ChatAssignmentAction chatAssignment = 35;
+ optional ChatAssignmentOpenedStatusAction chatAssignmentOpenedStatus = 36;
+ optional PnForLidChatAction pnForLidChatAction = 37;
+ optional MarketingMessageAction marketingMessageAction = 38;
+ optional MarketingMessageBroadcastAction marketingMessageBroadcastAction = 39;
+ optional ExternalWebBetaAction externalWebBetaAction = 40;
+ optional PrivacySettingRelayAllCalls privacySettingRelayAllCalls = 41;
+ optional CallLogAction callLogAction = 42;
+ optional UGCBot ugcBot = 43;
+ optional StatusPrivacyAction statusPrivacy = 44;
+ optional BotWelcomeRequestAction botWelcomeRequestAction = 45;
+ optional DeleteIndividualCallLogAction deleteIndividualCallLog = 46;
+ optional LabelReorderingAction labelReorderingAction = 47;
+ optional PaymentInfoAction paymentInfoAction = 48;
+ optional CustomPaymentMethodsAction customPaymentMethodsAction = 49;
+ optional LockChatAction lockChatAction = 50;
+ optional WAWebProtobufsChatLockSettings.ChatLockSettings chatLockSettings = 51;
+ optional WamoUserIdentifierAction wamoUserIdentifierAction = 52;
+ optional PrivacySettingDisableLinkPreviewsAction privacySettingDisableLinkPreviewsAction = 53;
+ optional WAWebProtobufsDeviceCapabilities.DeviceCapabilities deviceCapabilities = 54;
+ optional NoteEditAction noteEditAction = 55;
+ optional FavoritesAction favoritesAction = 56;
+ optional MerchantPaymentPartnerAction merchantPaymentPartnerAction = 57;
+ optional WaffleAccountLinkStateAction waffleAccountLinkStateAction = 58;
+ optional UsernameChatStartModeAction usernameChatStartMode = 59;
+ optional NotificationActivitySettingAction notificationActivitySettingAction = 60;
+ optional LidContactAction lidContactAction = 61;
+ optional CtwaPerCustomerDataSharingAction ctwaPerCustomerDataSharingAction = 62;
+ optional PaymentTosAction paymentTosAction = 63;
+ optional PrivacySettingChannelsPersonalisedRecommendationAction privacySettingChannelsPersonalisedRecommendationAction = 64;
+ optional DetectedOutcomesStatusAction detectedOutcomesStatusAction = 66;
+ optional MaibaAIFeaturesControlAction maibaAiFeaturesControlAction = 68;
+ optional BusinessBroadcastListAction businessBroadcastListAction = 69;
+ optional MusicUserIdAction musicUserIDAction = 70;
+ optional StatusPostOptInNotificationPreferencesAction statusPostOptInNotificationPreferencesAction = 71;
+ optional AvatarUpdatedAction avatarUpdatedAction = 72;
+ optional PrivateProcessingSettingAction privateProcessingSettingAction = 74;
+ optional NewsletterSavedInterestsAction newsletterSavedInterestsAction = 75;
+ optional AiThreadRenameAction aiThreadRenameAction = 76;
+ optional InteractiveMessageAction interactiveMessageAction = 77;
+ optional SettingsSyncAction settingsSyncAction = 78;
+ optional OutContactAction outContactAction = 79;
+ optional NctSaltSyncAction nctSaltSyncAction = 80;
+ optional BusinessBroadcastCampaignAction businessBroadcastCampaignAction = 81;
+ optional BusinessBroadcastInsightsAction businessBroadcastInsightsAction = 82;
+ optional CustomerDataAction customerDataAction = 83;
+ optional SubscriptionsSyncV2Action subscriptionsSyncV2Action = 84;
+ optional ThreadPinAction threadPinAction = 85;
+ optional AutoOrganizeBusinessChatSetting autoOrganizeBusinessChatSetting = 86;
+ optional BizAISettingsNudgeAction bizAiSettingsNudgeAction = 87;
+ optional CoexV2VersionAction coexV2VersionAction = 88;
+ optional WASARootSecretAction wasaRootSecretAction = 89;
+ optional BubbleLockMessageAction bubbleLockMessageAction = 90;
+ optional LabelSublistAction labelSublistAction = 91;
+ optional WAWebProtobufsDeviceCapabilities.DeviceCapabilities deviceCapabilitiesV2 = 92;
+ optional CtwaMessageReceivedAction ctwaMessageReceivedAction = 93;
+ optional SharedDeviceAllowlistAction sharedDeviceAllowlistAction = 94;
+ optional ContactManagerMetadataAction contactManagerMetadataAction = 95;
+ optional BusinessFolderActivationAction businessFolderActivationAction = 96;
+ optional GroupHistoryToggleAction groupHistoryToggleAction = 97;
+ optional BBProPendingCustomerBaseAction bbProPendingCustomerBaseAction = 98;
+ optional CommunityNestingStateAction communityNestingStateAction = 99;
+ optional SharedDeviceSecretAction sharedDeviceSecretAction = 100;
+}
+
+message BBProPendingCustomerBaseAction {
+ optional bool pending = 1;
+}
+
+message BusinessFolderActivationAction {
+ optional bool activated = 1;
+}
+
+message CtwaMessageReceivedAction {
+ optional bool isCtwaMessageReceived = 1;
+}
+
+message CoexV2VersionAction {
+ optional uint64 version = 1;
+}
+
+message SubscriptionsSyncV2Action {
+ message PaidFeature {
+ optional string name = 1;
+ optional bool enabled = 2;
+ optional int32 limit = 3;
+ optional int64 expirationTime = 4;
+ }
+
+ message SubscriptionInfo {
+ optional string ID = 1;
+ optional int32 tier = 2;
+ optional string status = 3;
+ optional int64 startTime = 4;
+ optional int64 endTime = 5;
+ optional bool isPlatformChanged = 6;
+ optional string source = 7;
+ optional int64 creationTime = 8;
+ }
+
+ repeated SubscriptionInfo subscriptions = 1;
+ repeated PaidFeature paidFeature = 2;
+}
+
+message ContactManagerMetadataAction {
+ optional bool isHidden = 1;
+}
+
+message CustomerDataAction {
+ optional string chatJID = 1;
+ optional int32 contactType = 2;
+ optional string email = 3;
+ optional string altPhoneNumbers = 4;
+ optional int64 birthday = 5;
+ optional string address = 6;
+ optional int32 acquisitionSource = 7;
+ optional int32 leadStage = 8;
+ optional int64 lastOrder = 9;
+ optional int64 createdAt = 10;
+ optional int64 modifiedAt = 11;
+}
+
+message BusinessBroadcastInsightsAction {
+ optional int32 recipientCount = 1;
+ optional int32 deliveredCount = 2;
+ optional int32 readCount = 3;
+ optional int32 repliedCount = 4;
+ optional int32 quickReplyCount = 5;
+}
+
+message AutoOrganizeBusinessChatSetting {
+ optional bool autoOrganize = 1;
+}
+
+message NctSaltSyncAction {
+ optional bytes salt = 1;
+}
+
+message ThreadPinAction {
+ optional bool pinned = 1;
+}
+
+message AiThreadRenameAction {
+ optional string newTitle = 1;
+}
+
+message StatusPostOptInNotificationPreferencesAction {
+ optional bool enabled = 1;
+}
+
+message BroadcastListParticipant {
+ required string lidJID = 1;
+ optional string pnJID = 2;
+}
+
+message BusinessBroadcastCampaignAction {
+ optional int32 deviceID = 1;
+ optional string adID = 2;
+ optional string name = 3;
+ optional string msgID = 4;
+ optional string broadcastJID = 5;
+ optional int32 reservedQuota = 6;
+ optional int64 scheduledTimestamp = 7;
+ optional int64 createTimestamp = 8;
+ optional BusinessBroadcastCampaignStatus status = 9;
+ optional BusinessBroadcastCampaignBBProStatus bbProStatus = 10;
+ optional string customAudienceFbid = 11;
+}
+
+message BusinessBroadcastListAction {
+ optional bool deleted = 1;
+ repeated BroadcastListParticipant participants = 2;
+ optional string listName = 3;
+ repeated string labelIDs = 4;
+ optional string audienceExpression = 5;
+ optional string customAudienceFbid = 6;
+}
+
+message BusinessBroadcastAssociationAction {
+ optional bool deleted = 1;
+}
+
+message CtwaPerCustomerDataSharingAction {
+ optional bool isCtwaPerCustomerDataSharingEnabled = 1;
+}
+
+message OutContactAction {
+ optional string fullName = 1;
+ optional string firstName = 2;
+}
+
+message LidContactAction {
+ optional string fullName = 1;
+ optional string firstName = 2;
+ optional string username = 3;
+ optional string birthday = 4;
+}
+
+message FavoritesAction {
+ message Favorite {
+ optional string ID = 1;
+ }
+
+ repeated Favorite favorites = 1;
+}
+
+message PrivacySettingChannelsPersonalisedRecommendationAction {
+ optional bool isUserOptedOut = 1;
+}
+
+message PrivacySettingDisableLinkPreviewsAction {
+ optional bool isPreviewsDisabled = 1;
+}
+
+message WamoUserIdentifierAction {
+ optional string identifier = 1;
+}
+
+message BubbleLockMessageAction {
+ optional bool locked = 1;
+}
+
+message LockChatAction {
+ optional bool locked = 1;
+}
+
+message CustomPaymentMethodsAction {
+ repeated CustomPaymentMethod customPaymentMethods = 1;
+}
+
+message CustomPaymentMethod {
+ required string credentialID = 1;
+ required string country = 2;
+ required string type = 3;
+ repeated CustomPaymentMethodMetadata metadata = 4;
+}
+
+message CustomPaymentMethodMetadata {
+ required string key = 1;
+ required string value = 2;
+}
+
+message PaymentInfoAction {
+ optional string cpi = 1;
+}
+
+message LabelReorderingAction {
+ repeated int32 sortedLabelIDs = 1;
+}
+
+message DeleteIndividualCallLogAction {
+ optional string peerJID = 1;
+ optional bool isIncoming = 2;
+}
+
+message BotWelcomeRequestAction {
+ optional bool isSent = 1;
+}
+
+message NewsletterSavedInterestsAction {
+ optional string newsletterSavedInterests = 1;
+}
+
+message MusicUserIdAction {
+ optional string musicUserID = 1;
+ // TODO switch to proto3 and enable this
+ //optional map<string, string> music_user_id_map = 2;
+}
+
+message UGCBot {
+ optional bytes definition = 1;
+}
+
+message CallLogAction {
+ optional CallLogRecord callLogRecord = 1;
+}
+
+message PrivacySettingRelayAllCalls {
+ optional bool isEnabled = 1;
+}
+
+message DetectedOutcomesStatusAction {
+ optional bool isEnabled = 1;
+}
+
+message ExternalWebBetaAction {
+ optional bool isOptIn = 1;
+}
+
+message MarketingMessageBroadcastAction {
+ optional int32 repliedCount = 1;
+}
+
+message PnForLidChatAction {
+ optional string pnJID = 1;
+}
+
+message ChatAssignmentOpenedStatusAction {
+ optional bool chatOpened = 1;
+}
+
+message ChatAssignmentAction {
+ optional string deviceAgentID = 1;
+}
+
+message StickerAction {
+ optional string URL = 1;
+ optional bytes fileEncSHA256 = 2;
+ optional bytes mediaKey = 3;
+ optional string mimetype = 4;
+ optional uint32 height = 5;
+ optional uint32 width = 6;
+ optional string directPath = 7;
+ optional uint64 fileLength = 8;
+ optional bool isFavorite = 9;
+ optional uint32 deviceIDHint = 10;
+ optional bool isLottie = 11;
+ optional string imageHash = 12;
+ optional bool isAvatarSticker = 13;
+}
+
+message RemoveRecentStickerAction {
+ optional int64 lastStickerSentTS = 1;
+}
+
+message PrimaryVersionAction {
+ optional string version = 1;
+}
+
+message NuxAction {
+ optional bool acknowledged = 1;
+}
+
+message TimeFormatAction {
+ optional bool isTwentyFourHourFormatEnabled = 1;
+}
+
+message UserStatusMuteAction {
+ optional bool muted = 1;
+}
+
+message SubscriptionAction {
+ optional bool isDeactivated = 1;
+ optional bool isAutoRenewing = 2;
+ optional int64 expirationDate = 3;
+}
+
+message AgentAction {
+ optional string name = 1;
+ optional int32 deviceID = 2;
+ optional bool isDeleted = 3;
+}
+
+message AndroidUnsupportedActions {
+ optional bool allowed = 1;
+}
+
+message PrimaryFeature {
+ repeated string flags = 1;
+}
+
+message KeyExpiration {
+ optional int32 expiredKeyEpoch = 1;
+}
+
+message SyncActionMessage {
+ optional WACommon.MessageKey key = 1;
+ optional int64 timestamp = 2;
+}
+
+message SyncActionMessageRange {
+ optional int64 lastMessageTimestamp = 1;
+ optional int64 lastSystemMessageTimestamp = 2;
+ repeated SyncActionMessage messages = 3;
+}
+
+message UnarchiveChatsSetting {
+ optional bool unarchiveChats = 1;
+}
+
+message DeleteChatAction {
+ optional SyncActionMessageRange messageRange = 1;
+}
+
+message ClearChatAction {
+ optional SyncActionMessageRange messageRange = 1;
+}
+
+message MarkChatAsReadAction {
+ optional bool read = 1;
+ optional SyncActionMessageRange messageRange = 2;
+}
+
+message DeleteMessageForMeAction {
+ optional bool deleteMedia = 1;
+ optional int64 messageTimestamp = 2;
+}
+
+message ArchiveChatAction {
+ optional bool archived = 1;
+ optional SyncActionMessageRange messageRange = 2;
+}
+
+message RecentEmojiWeightsAction {
+ repeated RecentEmojiWeight weights = 1;
+}
+
+message LabelSublistAction {
+ optional int32 subListID = 1;
+}
+
+message LabelAssociationAction {
+ optional bool labeled = 1;
+ optional string modelMetaData = 2;
+}
+
+message QuickReplyAction {
+ optional string shortcut = 1;
+ optional string message = 2;
+ repeated string keywords = 3;
+ optional int32 count = 4;
+ optional bool deleted = 5;
+ repeated string associatedLabelIDs = 6;
+}
+
+message LocaleSetting {
+ optional string locale = 1;
+}
+
+message PushNameSetting {
+ optional string name = 1;
+}
+
+message PinAction {
+ optional bool pinned = 1;
+}
+
+message MuteAction {
+ optional bool muted = 1;
+ optional int64 muteEndTimestamp = 2;
+ optional bool autoMuted = 3;
+ optional int64 muteEveryoneMentionEndTimestamp = 4;
+}
+
+message SharedDeviceSecretAction {
+ optional bytes secret = 1;
+ optional int64 ttlMS = 2;
+}
+
+message SharedDeviceAllowlistAction {
+ optional bool allowed = 1;
+}
+
+message ContactAction {
+ optional string fullName = 1;
+ optional string firstName = 2;
+ optional string lidJID = 3;
+ optional bool saveOnPrimaryAddressbook = 4;
+ optional string pnJID = 5;
+ optional string username = 6;
+ optional string birthday = 7;
+}
+
+message StarAction {
+ optional bool starred = 1;
+}
+
+message SyncActionData {
+ optional bytes index = 1;
+ optional SyncActionValue value = 2;
+ optional bytes padding = 3;
+ optional int32 version = 4;
+}
diff --git a/crates/whatsmeow_proto/proto/waSyncdSnapshotRecovery/WAWebProtobufsSyncdSnapshotRecovery.proto b/crates/whatsmeow_proto/proto/waSyncdSnapshotRecovery/WAWebProtobufsSyncdSnapshotRecovery.proto
new file mode 100644
index 0000000000..532a010889
--- /dev/null
+++ b/crates/whatsmeow_proto/proto/waSyncdSnapshotRecovery/WAWebProtobufsSyncdSnapshotRecovery.proto
@@ -0,0 +1,26 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+syntax = "proto2";
+package WAWebProtobufsSyncdSnapshotRecovery;
+option go_package = "go.mau.fi/whatsmeow/proto/waSyncdSnapshotRecovery";
+
+import "waSyncAction/WAWebProtobufSyncAction.proto";
+
+message SyncdSnapshotRecovery {
+ optional SyncdVersion version = 1;
+ optional string collectionName = 2;
+ repeated SyncdPlainTextRecord mutationRecords = 3;
+ optional bytes collectionLthash = 4;
+}
+
+message SyncdPlainTextRecord {
+ optional WAWebProtobufSyncAction.SyncActionData value = 1;
+ optional bytes keyID = 2;
+ optional bytes mac = 3;
+}
+
+message SyncdVersion {
+ optional uint64 version = 1;
+}
diff --git a/crates/whatsmeow_proto/proto/waUserPassword/WAWebProtobufsUserPassword.proto b/crates/whatsmeow_proto/proto/waUserPassword/WAWebProtobufsUserPassword.proto
new file mode 100644
index 0000000000..4ae85e952a
--- /dev/null
+++ b/crates/whatsmeow_proto/proto/waUserPassword/WAWebProtobufsUserPassword.proto
@@ -0,0 +1,37 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+syntax = "proto2";
+package WAWebProtobufsUserPassword;
+option go_package = "go.mau.fi/whatsmeow/proto/waUserPassword";
+
+message UserPassword {
+ enum Transformer {
+ NONE = 0;
+ PBKDF2_HMAC_SHA512 = 1;
+ PBKDF2_HMAC_SHA384 = 2;
+ }
+
+ enum Encoding {
+ UTF8 = 0;
+ UTF8_BROKEN = 1;
+ }
+
+ message TransformerArg {
+ message Value {
+ oneof value {
+ bytes asBlob = 1;
+ uint32 asUnsignedInteger = 2;
+ }
+ }
+
+ optional string key = 1;
+ optional Value value = 2;
+ }
+
+ optional Encoding encoding = 1;
+ optional Transformer transformer = 2;
+ repeated TransformerArg transformerArg = 3;
+ optional bytes transformedData = 4;
+}
diff --git a/crates/whatsmeow_proto/proto/waVnameCert/WAWebProtobufsVnameCert.proto b/crates/whatsmeow_proto/proto/waVnameCert/WAWebProtobufsVnameCert.proto
new file mode 100644
index 0000000000..db8bf04c0c
--- /dev/null
+++ b/crates/whatsmeow_proto/proto/waVnameCert/WAWebProtobufsVnameCert.proto
@@ -0,0 +1,76 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+syntax = "proto2";
+package WAWebProtobufsVnameCert;
+option go_package = "go.mau.fi/whatsmeow/proto/waVnameCert";
+
+message BizAccountLinkInfo {
+ enum AccountType {
+ ENTERPRISE = 0;
+ }
+
+ enum HostStorageType {
+ ON_PREMISE = 0;
+ FACEBOOK = 1;
+ }
+
+ optional uint64 whatsappBizAcctFbid = 1;
+ optional string whatsappAcctNumber = 2;
+ optional uint64 issueTime = 3;
+ optional HostStorageType hostStorage = 4;
+ optional AccountType accountType = 5;
+}
+
+message BizIdentityInfo {
+ enum ActualActorsType {
+ SELF = 0;
+ BSP = 1;
+ }
+
+ enum HostStorageType {
+ ON_PREMISE = 0;
+ FACEBOOK = 1;
+ }
+
+ enum VerifiedLevelValue {
+ UNKNOWN = 0;
+ LOW = 1;
+ HIGH = 2;
+ }
+
+ optional VerifiedLevelValue vlevel = 1;
+ optional VerifiedNameCertificate vnameCert = 2;
+ optional bool signed = 3;
+ optional bool revoked = 4;
+ optional HostStorageType hostStorage = 5;
+ optional ActualActorsType actualActors = 6;
+ optional uint64 privacyModeTS = 7;
+ optional uint64 featureControls = 8;
+}
+
+message LocalizedName {
+ optional string lg = 1;
+ optional string lc = 2;
+ optional string verifiedName = 3;
+}
+
+message VerifiedNameCertificate {
+ message Details {
+ optional uint64 serial = 1;
+ optional string issuer = 2;
+ optional string verifiedName = 4;
+ repeated LocalizedName localizedNames = 8;
+ optional uint64 issueTime = 10;
+ }
+
+ optional bytes details = 1;
+ optional bytes signature = 2;
+ optional bytes serverSignature = 3;
+}
+
+message BizAccountPayload {
+ optional VerifiedNameCertificate vnameCert = 1;
+ optional bytes bizAcctLinkInfo = 2;
+}
diff --git a/crates/whatsmeow_proto/proto/waWa6/WAWebProtobufsWa6.proto b/crates/whatsmeow_proto/proto/waWa6/WAWebProtobufsWa6.proto
new file mode 100644
index 0000000000..e6e5d0fbab
--- /dev/null
+++ b/crates/whatsmeow_proto/proto/waWa6/WAWebProtobufsWa6.proto
@@ -0,0 +1,308 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+syntax = "proto2";
+package WAWebProtobufsWa6;
+option go_package = "go.mau.fi/whatsmeow/proto/waWa6";
+
+message HandshakeMessage {
+ enum HandshakePqMode {
+ HANDSHAKE_PQ_MODE_UNKNOWN = 0;
+ XXKEM = 1;
+ XXKEM_FS = 2;
+ XXKEM_EPH = 9;
+ WA_CLASSICAL = 3;
+ WA_PQ = 4;
+ IKKEM = 5;
+ IKKEM_FS = 6;
+ XXKEM_2 = 7;
+ IKKEM_2 = 8;
+ }
+
+ message ClientFinish {
+ optional bytes static = 1;
+ optional bytes payload = 2;
+ optional bytes extendedCiphertext = 3;
+ optional bytes paddedBytes = 4;
+ optional bool simulateXxkemFs = 5;
+ }
+
+ message ServerHello {
+ optional bytes ephemeral = 1;
+ optional bytes static = 2;
+ optional bytes payload = 3;
+ optional bytes extendedStatic = 4;
+ optional bytes paddingBytes = 5;
+ optional bytes extendedCiphertext = 6;
+ }
+
+ message ClientHello {
+ optional bytes ephemeral = 1;
+ optional bytes static = 2;
+ optional bytes payload = 3;
+ optional bool useExtended = 4;
+ optional bytes extendedCiphertext = 5;
+ optional bytes paddedBytes = 6;
+ optional bool sendServerHelloPaddedBytes = 7;
+ optional bool simulateXxkemFs = 8;
+ optional HandshakePqMode pqMode = 9;
+ optional bytes extendedEphemeral = 10;
+ }
+
+ optional ClientHello clientHello = 2;
+ optional ServerHello serverHello = 3;
+ optional ClientFinish clientFinish = 4;
+}
+
+message ClientPayload {
+ enum TrafficAnonymization {
+ OFF = 0;
+ STANDARD = 1;
+ }
+
+ enum AccountType {
+ DEFAULT = 0;
+ GUEST = 1;
+ }
+
+ enum Product {
+ WHATSAPP = 0;
+ MESSENGER = 1;
+ INTEROP = 2;
+ INTEROP_MSGR = 3;
+ WHATSAPP_LID = 4;
+ }
+
+ enum ConnectType {
+ CELLULAR_UNKNOWN = 0;
+ WIFI_UNKNOWN = 1;
+ CELLULAR_EDGE = 100;
+ CELLULAR_IDEN = 101;
+ CELLULAR_UMTS = 102;
+ CELLULAR_EVDO = 103;
+ CELLULAR_GPRS = 104;
+ CELLULAR_HSDPA = 105;
+ CELLULAR_HSUPA = 106;
+ CELLULAR_HSPA = 107;
+ CELLULAR_CDMA = 108;
+ CELLULAR_1XRTT = 109;
+ CELLULAR_EHRPD = 110;
+ CELLULAR_LTE = 111;
+ CELLULAR_HSPAP = 112;
+ }
+
+ enum ConnectReason {
+ PUSH = 0;
+ USER_ACTIVATED = 1;
+ SCHEDULED = 2;
+ ERROR_RECONNECT = 3;
+ NETWORK_SWITCH = 4;
+ PING_RECONNECT = 5;
+ UNKNOWN = 6;
+ }
+
+ enum IOSAppExtension {
+ SHARE_EXTENSION = 0;
+ SERVICE_EXTENSION = 1;
+ INTENTS_EXTENSION = 2;
+ }
+
+ message DNSSource {
+ enum DNSResolutionMethod {
+ SYSTEM = 0;
+ GOOGLE = 1;
+ HARDCODED = 2;
+ OVERRIDE = 3;
+ FALLBACK = 4;
+ MNS = 5;
+ MNS_SECONDARY = 6;
+ SOCKS_PROXY = 7;
+ }
+
+ optional DNSResolutionMethod dnsMethod = 15;
+ optional bool appCached = 16;
+ }
+
+ message WebInfo {
+ enum WebSubPlatform {
+ WEB_BROWSER = 0;
+ APP_STORE = 1;
+ WIN_STORE = 2;
+ DARWIN = 3;
+ WIN32 = 4;
+ WIN_HYBRID = 5;
+ }
+
+ message WebdPayload {
+ optional bool usesParticipantInKey = 1;
+ optional bool supportsStarredMessages = 2;
+ optional bool supportsDocumentMessages = 3;
+ optional bool supportsURLMessages = 4;
+ optional bool supportsMediaRetry = 5;
+ optional bool supportsE2EImage = 6;
+ optional bool supportsE2EVideo = 7;
+ optional bool supportsE2EAudio = 8;
+ optional bool supportsE2EDocument = 9;
+ optional string documentTypes = 10;
+ optional bytes features = 11;
+ }
+
+ optional string refToken = 1;
+ optional string version = 2;
+ optional WebdPayload webdPayload = 3;
+ optional WebSubPlatform webSubPlatform = 4;
+ optional string browser = 5;
+ optional string browserVersion = 6;
+ }
+
+ message UserAgent {
+ enum DeviceType {
+ PHONE = 0;
+ TABLET = 1;
+ DESKTOP = 2;
+ WEARABLE = 3;
+ VR = 4;
+ }
+
+ enum DistributionChannel {
+ APPSTORE = 0;
+ WEBSITE = 1;
+ TESTFLIGHT = 2;
+ INTERNAL = 3;
+ }
+
+ enum ReleaseChannel {
+ RELEASE = 0;
+ BETA = 1;
+ ALPHA = 2;
+ DEBUG = 3;
+ }
+
+ enum Platform {
+ ANDROID = 0;
+ IOS = 1;
+ WINDOWS_PHONE = 2;
+ BLACKBERRY = 3;
+ BLACKBERRYX = 4;
+ S40 = 5;
+ S60 = 6;
+ PYTHON_CLIENT = 7;
+ TIZEN = 8;
+ ENTERPRISE = 9;
+ SMB_ANDROID = 10;
+ KAIOS = 11;
+ SMB_IOS = 12;
+ WINDOWS = 13;
+ WEB = 14;
+ PORTAL = 15;
+ GREEN_ANDROID = 16;
+ GREEN_IPHONE = 17;
+ BLUE_ANDROID = 18;
+ BLUE_IPHONE = 19;
+ FBLITE_ANDROID = 20;
+ MLITE_ANDROID = 21;
+ IGLITE_ANDROID = 22;
+ PAGE = 23;
+ MACOS = 24;
+ OCULUS_MSG = 25;
+ OCULUS_CALL = 26;
+ MILAN = 27;
+ CAPI = 28;
+ WEAROS = 29;
+ ARDEVICE = 30;
+ VRDEVICE = 31;
+ BLUE_WEB = 32;
+ IPAD = 33;
+ TEST = 34;
+ SMART_GLASSES = 35;
+ BLUE_VR = 36;
+ AR_WRIST = 37;
+ WAIL = 38;
+ WORK_ANDROID = 39;
+ WORK_IOS = 40;
+ AUTOMOTIVE = 41;
+ }
+
+ message AppVersion {
+ optional uint32 primary = 1;
+ optional uint32 secondary = 2;
+ optional uint32 tertiary = 3;
+ optional uint32 quaternary = 4;
+ optional uint32 quinary = 5;
+ }
+
+ optional Platform platform = 1;
+ optional AppVersion appVersion = 2;
+ optional string mcc = 3;
+ optional string mnc = 4;
+ optional string osVersion = 5;
+ optional string manufacturer = 6;
+ optional string device = 7;
+ optional string osBuildNumber = 8;
+ optional string phoneID = 9;
+ optional ReleaseChannel releaseChannel = 10;
+ optional string localeLanguageIso6391 = 11;
+ optional string localeCountryIso31661Alpha2 = 12;
+ optional string deviceBoard = 13;
+ optional string deviceExpID = 14;
+ optional DeviceType deviceType = 15;
+ optional string deviceModelType = 16;
+ optional DistributionChannel distributionChannel = 17;
+ }
+
+ message InteropData {
+ optional uint64 accountID = 1;
+ optional bytes token = 2;
+ optional bool enableReadReceipts = 3;
+ }
+
+ message DevicePairingRegistrationData {
+ optional bytes eRegid = 1;
+ optional bytes eKeytype = 2;
+ optional bytes eIdent = 3;
+ optional bytes eSkeyID = 4;
+ optional bytes eSkeyVal = 5;
+ optional bytes eSkeySig = 6;
+ optional bytes buildHash = 7;
+ optional bytes deviceProps = 8;
+ }
+
+ optional uint64 username = 1;
+ optional bool passive = 3;
+ optional UserAgent userAgent = 5;
+ optional WebInfo webInfo = 6;
+ optional string pushName = 7;
+ optional sfixed32 sessionID = 9;
+ optional bool shortConnect = 10;
+ optional ConnectType connectType = 12;
+ optional ConnectReason connectReason = 13;
+ repeated int32 shards = 14;
+ optional DNSSource dnsSource = 15;
+ optional uint32 connectAttemptCount = 16;
+ optional uint32 device = 18;
+ optional DevicePairingRegistrationData devicePairingData = 19;
+ optional Product product = 20;
+ optional bytes fbCat = 21;
+ optional bytes fbUserAgent = 22;
+ optional bool oc = 23;
+ optional int32 lc = 24;
+ optional IOSAppExtension iosAppExtension = 30;
+ optional uint64 fbAppID = 31;
+ optional bytes fbDeviceID = 32;
+ optional bool pull = 33;
+ optional bytes paddingBytes = 34;
+ optional int32 yearClass = 36;
+ optional int32 memClass = 37;
+ optional InteropData interopData = 38;
+ optional TrafficAnonymization trafficAnonymization = 40;
+ optional bool lidDbMigrated = 41;
+ optional AccountType accountType = 42;
+ optional sfixed32 connectionSequenceInfo = 43;
+ optional bool paaLink = 44;
+ optional int32 preacksCount = 45;
+ optional int32 processingQueueSize = 46;
+ repeated string pairedPeripherals = 47;
+ optional bytes testIsolationID = 48;
+ optional int64 messageSts = 49;
+}
diff --git a/crates/whatsmeow_proto/proto/waWeb/WAWebProtobufsWeb.proto b/crates/whatsmeow_proto/proto/waWeb/WAWebProtobufsWeb.proto
new file mode 100644
index 0000000000..ef406406ce
--- /dev/null
+++ b/crates/whatsmeow_proto/proto/waWeb/WAWebProtobufsWeb.proto
@@ -0,0 +1,689 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+syntax = "proto2";
+package WAWebProtobufsWeb;
+option go_package = "go.mau.fi/whatsmeow/proto/waWeb";
+
+import "waE2E/WAWebProtobufsE2E.proto";
+import "waCommon/WACommon.proto";
+
+message WebMessageInfo {
+ enum BizPrivacyStatus {
+ E2EE = 0;
+ FB = 2;
+ BSP = 1;
+ BSP_AND_FB = 3;
+ }
+
+ enum StubType {
+ UNKNOWN = 0;
+ REVOKE = 1;
+ CIPHERTEXT = 2;
+ FUTUREPROOF = 3;
+ NON_VERIFIED_TRANSITION = 4;
+ UNVERIFIED_TRANSITION = 5;
+ VERIFIED_TRANSITION = 6;
+ VERIFIED_LOW_UNKNOWN = 7;
+ VERIFIED_HIGH = 8;
+ VERIFIED_INITIAL_UNKNOWN = 9;
+ VERIFIED_INITIAL_LOW = 10;
+ VERIFIED_INITIAL_HIGH = 11;
+ VERIFIED_TRANSITION_ANY_TO_NONE = 12;
+ VERIFIED_TRANSITION_ANY_TO_HIGH = 13;
+ VERIFIED_TRANSITION_HIGH_TO_LOW = 14;
+ VERIFIED_TRANSITION_HIGH_TO_UNKNOWN = 15;
+ VERIFIED_TRANSITION_UNKNOWN_TO_LOW = 16;
+ VERIFIED_TRANSITION_LOW_TO_UNKNOWN = 17;
+ VERIFIED_TRANSITION_NONE_TO_LOW = 18;
+ VERIFIED_TRANSITION_NONE_TO_UNKNOWN = 19;
+ GROUP_CREATE = 20;
+ GROUP_CHANGE_SUBJECT = 21;
+ GROUP_CHANGE_ICON = 22;
+ GROUP_CHANGE_INVITE_LINK = 23;
+ GROUP_CHANGE_DESCRIPTION = 24;
+ GROUP_CHANGE_RESTRICT = 25;
+ GROUP_CHANGE_ANNOUNCE = 26;
+ GROUP_PARTICIPANT_ADD = 27;
+ GROUP_PARTICIPANT_REMOVE = 28;
+ GROUP_PARTICIPANT_PROMOTE = 29;
+ GROUP_PARTICIPANT_DEMOTE = 30;
+ GROUP_PARTICIPANT_INVITE = 31;
+ GROUP_PARTICIPANT_LEAVE = 32;
+ GROUP_PARTICIPANT_CHANGE_NUMBER = 33;
+ BROADCAST_CREATE = 34;
+ BROADCAST_ADD = 35;
+ BROADCAST_REMOVE = 36;
+ GENERIC_NOTIFICATION = 37;
+ E2E_IDENTITY_CHANGED = 38;
+ E2E_ENCRYPTED = 39;
+ CALL_MISSED_VOICE = 40;
+ CALL_MISSED_VIDEO = 41;
+ INDIVIDUAL_CHANGE_NUMBER = 42;
+ GROUP_DELETE = 43;
+ GROUP_ANNOUNCE_MODE_MESSAGE_BOUNCE = 44;
+ CALL_MISSED_GROUP_VOICE = 45;
+ CALL_MISSED_GROUP_VIDEO = 46;
+ PAYMENT_CIPHERTEXT = 47;
+ PAYMENT_FUTUREPROOF = 48;
+ PAYMENT_TRANSACTION_STATUS_UPDATE_FAILED = 49;
+ PAYMENT_TRANSACTION_STATUS_UPDATE_REFUNDED = 50;
+ PAYMENT_TRANSACTION_STATUS_UPDATE_REFUND_FAILED = 51;
+ PAYMENT_TRANSACTION_STATUS_RECEIVER_PENDING_SETUP = 52;
+ PAYMENT_TRANSACTION_STATUS_RECEIVER_SUCCESS_AFTER_HICCUP = 53;
+ PAYMENT_ACTION_ACCOUNT_SETUP_REMINDER = 54;
+ PAYMENT_ACTION_SEND_PAYMENT_REMINDER = 55;
+ PAYMENT_ACTION_SEND_PAYMENT_INVITATION = 56;
+ PAYMENT_ACTION_REQUEST_DECLINED = 57;
+ PAYMENT_ACTION_REQUEST_EXPIRED = 58;
+ PAYMENT_ACTION_REQUEST_CANCELLED = 59;
+ BIZ_VERIFIED_TRANSITION_TOP_TO_BOTTOM = 60;
+ BIZ_VERIFIED_TRANSITION_BOTTOM_TO_TOP = 61;
+ BIZ_INTRO_TOP = 62;
+ BIZ_INTRO_BOTTOM = 63;
+ BIZ_NAME_CHANGE = 64;
+ BIZ_MOVE_TO_CONSUMER_APP = 65;
+ BIZ_TWO_TIER_MIGRATION_TOP = 66;
+ BIZ_TWO_TIER_MIGRATION_BOTTOM = 67;
+ OVERSIZED = 68;
+ GROUP_CHANGE_NO_FREQUENTLY_FORWARDED = 69;
+ GROUP_V4_ADD_INVITE_SENT = 70;
+ GROUP_PARTICIPANT_ADD_REQUEST_JOIN = 71;
+ CHANGE_EPHEMERAL_SETTING = 72;
+ E2E_DEVICE_CHANGED = 73;
+ VIEWED_ONCE = 74;
+ E2E_ENCRYPTED_NOW = 75;
+ BLUE_MSG_BSP_FB_TO_BSP_PREMISE = 76;
+ BLUE_MSG_BSP_FB_TO_SELF_FB = 77;
+ BLUE_MSG_BSP_FB_TO_SELF_PREMISE = 78;
+ BLUE_MSG_BSP_FB_UNVERIFIED = 79;
+ BLUE_MSG_BSP_FB_UNVERIFIED_TO_SELF_PREMISE_VERIFIED = 80;
+ BLUE_MSG_BSP_FB_VERIFIED = 81;
+ BLUE_MSG_BSP_FB_VERIFIED_TO_SELF_PREMISE_UNVERIFIED = 82;
+ BLUE_MSG_BSP_PREMISE_TO_SELF_PREMISE = 83;
+ BLUE_MSG_BSP_PREMISE_UNVERIFIED = 84;
+ BLUE_MSG_BSP_PREMISE_UNVERIFIED_TO_SELF_PREMISE_VERIFIED = 85;
+ BLUE_MSG_BSP_PREMISE_VERIFIED = 86;
+ BLUE_MSG_BSP_PREMISE_VERIFIED_TO_SELF_PREMISE_UNVERIFIED = 87;
+ BLUE_MSG_CONSUMER_TO_BSP_FB_UNVERIFIED = 88;
+ BLUE_MSG_CONSUMER_TO_BSP_PREMISE_UNVERIFIED = 89;
+ BLUE_MSG_CONSUMER_TO_SELF_FB_UNVERIFIED = 90;
+ BLUE_MSG_CONSUMER_TO_SELF_PREMISE_UNVERIFIED = 91;
+ BLUE_MSG_SELF_FB_TO_BSP_PREMISE = 92;
+ BLUE_MSG_SELF_FB_TO_SELF_PREMISE = 93;
+ BLUE_MSG_SELF_FB_UNVERIFIED = 94;
+ BLUE_MSG_SELF_FB_UNVERIFIED_TO_SELF_PREMISE_VERIFIED = 95;
+ BLUE_MSG_SELF_FB_VERIFIED = 96;
+ BLUE_MSG_SELF_FB_VERIFIED_TO_SELF_PREMISE_UNVERIFIED = 97;
+ BLUE_MSG_SELF_PREMISE_TO_BSP_PREMISE = 98;
+ BLUE_MSG_SELF_PREMISE_UNVERIFIED = 99;
+ BLUE_MSG_SELF_PREMISE_VERIFIED = 100;
+ BLUE_MSG_TO_BSP_FB = 101;
+ BLUE_MSG_TO_CONSUMER = 102;
+ BLUE_MSG_TO_SELF_FB = 103;
+ BLUE_MSG_UNVERIFIED_TO_BSP_FB_VERIFIED = 104;
+ BLUE_MSG_UNVERIFIED_TO_BSP_PREMISE_VERIFIED = 105;
+ BLUE_MSG_UNVERIFIED_TO_SELF_FB_VERIFIED = 106;
+ BLUE_MSG_UNVERIFIED_TO_VERIFIED = 107;
+ BLUE_MSG_VERIFIED_TO_BSP_FB_UNVERIFIED = 108;
+ BLUE_MSG_VERIFIED_TO_BSP_PREMISE_UNVERIFIED = 109;
+ BLUE_MSG_VERIFIED_TO_SELF_FB_UNVERIFIED = 110;
+ BLUE_MSG_VERIFIED_TO_UNVERIFIED = 111;
+ BLUE_MSG_BSP_FB_UNVERIFIED_TO_BSP_PREMISE_VERIFIED = 112;
+ BLUE_MSG_BSP_FB_UNVERIFIED_TO_SELF_FB_VERIFIED = 113;
+ BLUE_MSG_BSP_FB_VERIFIED_TO_BSP_PREMISE_UNVERIFIED = 114;
+ BLUE_MSG_BSP_FB_VERIFIED_TO_SELF_FB_UNVERIFIED = 115;
+ BLUE_MSG_SELF_FB_UNVERIFIED_TO_BSP_PREMISE_VERIFIED = 116;
+ BLUE_MSG_SELF_FB_VERIFIED_TO_BSP_PREMISE_UNVERIFIED = 117;
+ E2E_IDENTITY_UNAVAILABLE = 118;
+ GROUP_CREATING = 119;
+ GROUP_CREATE_FAILED = 120;
+ GROUP_BOUNCED = 121;
+ BLOCK_CONTACT = 122;
+ EPHEMERAL_SETTING_NOT_APPLIED = 123;
+ SYNC_FAILED = 124;
+ SYNCING = 125;
+ BIZ_PRIVACY_MODE_INIT_FB = 126;
+ BIZ_PRIVACY_MODE_INIT_BSP = 127;
+ BIZ_PRIVACY_MODE_TO_FB = 128;
+ BIZ_PRIVACY_MODE_TO_BSP = 129;
+ DISAPPEARING_MODE = 130;
+ E2E_DEVICE_FETCH_FAILED = 131;
+ ADMIN_REVOKE = 132;
+ GROUP_INVITE_LINK_GROWTH_LOCKED = 133;
+ COMMUNITY_LINK_PARENT_GROUP = 134;
+ COMMUNITY_LINK_SIBLING_GROUP = 135;
+ COMMUNITY_LINK_SUB_GROUP = 136;
+ COMMUNITY_UNLINK_PARENT_GROUP = 137;
+ COMMUNITY_UNLINK_SIBLING_GROUP = 138;
+ COMMUNITY_UNLINK_SUB_GROUP = 139;
+ GROUP_PARTICIPANT_ACCEPT = 140;
+ GROUP_PARTICIPANT_LINKED_GROUP_JOIN = 141;
+ COMMUNITY_CREATE = 142;
+ EPHEMERAL_KEEP_IN_CHAT = 143;
+ GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST = 144;
+ GROUP_MEMBERSHIP_JOIN_APPROVAL_MODE = 145;
+ INTEGRITY_UNLINK_PARENT_GROUP = 146;
+ COMMUNITY_PARTICIPANT_PROMOTE = 147;
+ COMMUNITY_PARTICIPANT_DEMOTE = 148;
+ COMMUNITY_PARENT_GROUP_DELETED = 149;
+ COMMUNITY_LINK_PARENT_GROUP_MEMBERSHIP_APPROVAL = 150;
+ GROUP_PARTICIPANT_JOINED_GROUP_AND_PARENT_GROUP = 151;
+ MASKED_THREAD_CREATED = 152;
+ MASKED_THREAD_UNMASKED = 153;
+ BIZ_CHAT_ASSIGNMENT = 154;
+ CHAT_PSA = 155;
+ CHAT_POLL_CREATION_MESSAGE = 156;
+ CAG_MASKED_THREAD_CREATED = 157;
+ COMMUNITY_PARENT_GROUP_SUBJECT_CHANGED = 158;
+ CAG_INVITE_AUTO_ADD = 159;
+ BIZ_CHAT_ASSIGNMENT_UNASSIGN = 160;
+ CAG_INVITE_AUTO_JOINED = 161;
+ SCHEDULED_CALL_START_MESSAGE = 162;
+ COMMUNITY_INVITE_RICH = 163;
+ COMMUNITY_INVITE_AUTO_ADD_RICH = 164;
+ SUB_GROUP_INVITE_RICH = 165;
+ SUB_GROUP_PARTICIPANT_ADD_RICH = 166;
+ COMMUNITY_LINK_PARENT_GROUP_RICH = 167;
+ COMMUNITY_PARTICIPANT_ADD_RICH = 168;
+ SILENCED_UNKNOWN_CALLER_AUDIO = 169;
+ SILENCED_UNKNOWN_CALLER_VIDEO = 170;
+ GROUP_MEMBER_ADD_MODE = 171;
+ GROUP_MEMBERSHIP_JOIN_APPROVAL_REQUEST_NON_ADMIN_ADD = 172;
+ COMMUNITY_CHANGE_DESCRIPTION = 173;
+ SENDER_INVITE = 174;
+ RECEIVER_INVITE = 175;
+ COMMUNITY_ALLOW_MEMBER_ADDED_GROUPS = 176;
+ PINNED_MESSAGE_IN_CHAT = 177;
+ PAYMENT_INVITE_SETUP_INVITER = 178;
+ PAYMENT_INVITE_SETUP_INVITEE_RECEIVE_ONLY = 179;
+ PAYMENT_INVITE_SETUP_INVITEE_SEND_AND_RECEIVE = 180;
+ LINKED_GROUP_CALL_START = 181;
+ REPORT_TO_ADMIN_ENABLED_STATUS = 182;
+ EMPTY_SUBGROUP_CREATE = 183;
+ SCHEDULED_CALL_CANCEL = 184;
+ SUBGROUP_ADMIN_TRIGGERED_AUTO_ADD_RICH = 185;
+ GROUP_CHANGE_RECENT_HISTORY_SHARING = 186;
+ PAID_MESSAGE_SERVER_CAMPAIGN_ID = 187;
+ GENERAL_CHAT_CREATE = 188;
+ GENERAL_CHAT_ADD = 189;
+ GENERAL_CHAT_AUTO_ADD_DISABLED = 190;
+ SUGGESTED_SUBGROUP_ANNOUNCE = 191;
+ BIZ_BOT_1P_MESSAGING_ENABLED = 192;
+ CHANGE_USERNAME = 193;
+ BIZ_COEX_PRIVACY_INIT_SELF = 194;
+ BIZ_COEX_PRIVACY_TRANSITION_SELF = 195;
+ SUPPORT_AI_EDUCATION = 196;
+ BIZ_BOT_3P_MESSAGING_ENABLED = 197;
+ REMINDER_SETUP_MESSAGE = 198;
+ REMINDER_SENT_MESSAGE = 199;
+ REMINDER_CANCEL_MESSAGE = 200;
+ BIZ_COEX_PRIVACY_INIT = 201;
+ BIZ_COEX_PRIVACY_TRANSITION = 202;
+ GROUP_DEACTIVATED = 203;
+ COMMUNITY_DEACTIVATE_SIBLING_GROUP = 204;
+ EVENT_UPDATED = 205;
+ EVENT_CANCELED = 206;
+ COMMUNITY_OWNER_UPDATED = 207;
+ COMMUNITY_SUB_GROUP_VISIBILITY_HIDDEN = 208;
+ CAPI_GROUP_NE2EE_SYSTEM_MESSAGE = 209;
+ STATUS_MENTION = 210;
+ USER_CONTROLS_SYSTEM_MESSAGE = 211;
+ SUPPORT_SYSTEM_MESSAGE = 212;
+ CHANGE_LID = 213;
+ BIZ_CUSTOMER_3PD_DATA_SHARING_OPT_IN_MESSAGE = 214;
+ BIZ_CUSTOMER_3PD_DATA_SHARING_OPT_OUT_MESSAGE = 215;
+ CHANGE_LIMIT_SHARING = 216;
+ GROUP_MEMBER_LINK_MODE = 217;
+ BIZ_AUTOMATICALLY_LABELED_CHAT_SYSTEM_MESSAGE = 218;
+ PHONE_NUMBER_HIDING_CHAT_DEPRECATED_MESSAGE = 219;
+ QUARANTINED_MESSAGE = 220;
+ GROUP_MEMBER_SHARE_GROUP_HISTORY_MODE = 221;
+ GROUP_OPEN_BOT_ADDED = 222;
+ GROUP_TEE_BOT_ADDED = 223;
+ CONTACT_INFO = 224;
+ SCHEDULED_MESSAGE_CREATED = 225;
+ IDENTITY_TRUST_MARKED = 226;
+ IDENTITY_TRUST_UNMARKED = 227;
+ IDENTITY_TRUST_REVOKED = 228;
+ CTWA_CONSUMER_DISCLOSURE = 230;
+ CHANGE_ACP2_SETTING = 240;
+ BIZ_CALLBACK_DISABLED = 244;
+ BIZ_CALLBACK_ENABLED = 247;
+ EPHEMERAL_CHANGED_FOR_COEX = 248;
+ UGC_BOT_PROFILE_UPDATED = 249;
+ ORDER_EPHEMERAL_EXEMPTION = 250;
+ GROUP_DEFAULT_SUB_GROUP_DEMOTE = 251;
+ BIZ_BUSINESS_BROADCAST_ENTRY_POINT = 252;
+ BOT_INLINE_TOS_CHAT = 253;
+ CAMEO_CHAT_CREATED = 254;
+ SENDER_SIDE_CONTACT_INFO = 255;
+ CAMEO_TRANSITIONED = 256;
+ CAMEO_REGISTERED_WITH_NEW_CHAT = 257;
+ PRIVACY_SYSTEM_MESSAGE = 258;
+ BIZ_AI_LEARNING_ENABLED_DISCLOSURE = 259;
+ BIZ_AI_LEARNING_DISABLED_DISCLOSURE = 260;
+ BIZ_AI_REPLIES_MUTED_HISTORICAL_CHAT = 261;
+ INVITE_FROM_IG = 262;
+ GROUP_ADMIN_FIRST_JOIN_VIA_LINK = 263;
+ GROUP_ADMIN_FLOOD_JOIN_VIA_LINK = 264;
+ BIZ_AI_REPLIES_MUTED_IRRELEVANT_HISTORICAL_CHAT = 265;
+ PENDING_INVITE_CREATED = 266;
+ CAMEO_CHAT_EXPIRED = 267;
+ GROUP_PUSHNAME_SHARED = 270;
+ BIZ_POST_SEND_OPT_OUT = 271;
+ BB_PRO_BROADCAST_CHAT_CARD = 272;
+ BOT_PROACTIVE_MESSAGE_ENABLED = 273;
+ BOT_PROACTIVE_MESSAGE_DISABLED = 274;
+ BOT_PROACTIVE_MESSAGE_FIRST_TIME = 275;
+ DYNAMIC_AUDIENCE_LIST_CREATE = 276;
+ DYNAMIC_AUDIENCE_LIST_UPDATE_LINK = 277;
+ CHAT_WITH_BUSINESS_IN_DIRECTORY = 283;
+ META_AI_THREAD_CREATED = 284;
+ META_AI_CONNECTOR_LINKED = 285;
+ SPLIT_PAYMENT_MARKED_AS_PAID = 289;
+ }
+
+ enum Status {
+ ERROR = 0;
+ PENDING = 1;
+ SERVER_ACK = 2;
+ DELIVERY_ACK = 3;
+ READ = 4;
+ PLAYED = 5;
+ }
+
+ required WACommon.MessageKey key = 1;
+ optional WAWebProtobufsE2E.Message message = 2;
+ optional uint64 messageTimestamp = 3;
+ optional Status status = 4;
+ optional string participant = 5;
+ optional uint64 messageC2STimestamp = 6;
+ optional bool ignore = 16;
+ optional bool starred = 17;
+ optional bool broadcast = 18;
+ optional string pushName = 19;
+ optional bytes mediaCiphertextSHA256 = 20;
+ optional bool multicast = 21;
+ optional bool urlText = 22;
+ optional bool urlNumber = 23;
+ optional StubType messageStubType = 24;
+ optional bool clearMedia = 25;
+ repeated string messageStubParameters = 26;
+ optional uint32 duration = 27;
+ repeated string labels = 28;
+ optional PaymentInfo paymentInfo = 29;
+ optional WAWebProtobufsE2E.LiveLocationMessage finalLiveLocation = 30;
+ optional PaymentInfo quotedPaymentInfo = 31;
+ optional uint64 ephemeralStartTimestamp = 32;
+ optional uint32 ephemeralDuration = 33;
+ optional bool ephemeralOffToOn = 34;
+ optional bool ephemeralOutOfSync = 35;
+ optional BizPrivacyStatus bizPrivacyStatus = 36;
+ optional string verifiedBizName = 37;
+ optional MediaData mediaData = 38;
+ optional PhotoChange photoChange = 39;
+ repeated UserReceipt userReceipt = 40;
+ repeated Reaction reactions = 41;
+ optional MediaData quotedStickerData = 42;
+ optional bytes futureproofData = 43;
+ optional StatusPSA statusPsa = 44;
+ repeated PollUpdate pollUpdates = 45;
+ optional PollAdditionalMetadata pollAdditionalMetadata = 46;
+ optional string agentID = 47;
+ optional bool statusAlreadyViewed = 48;
+ optional bytes messageSecret = 49;
+ optional KeepInChat keepInChat = 50;
+ optional string originalSelfAuthorUserJIDString = 51;
+ optional uint64 revokeMessageTimestamp = 52;
+ optional PinInChat pinInChat = 54;
+ optional PremiumMessageInfo premiumMessageInfo = 55;
+ optional bool is1PBizBotMessage = 56;
+ optional bool isGroupHistoryMessage = 57;
+ optional string botMessageInvokerJID = 58;
+ optional CommentMetadata commentMetadata = 59;
+ repeated EventResponse eventResponses = 61;
+ optional ReportingTokenInfo reportingTokenInfo = 62;
+ optional uint64 newsletterServerID = 63;
+ optional EventAdditionalMetadata eventAdditionalMetadata = 64;
+ optional bool isMentionedInStatus = 65;
+ repeated string statusMentions = 66;
+ optional WACommon.MessageKey targetMessageID = 67;
+ repeated MessageAddOn messageAddOns = 68;
+ optional StatusMentionMessage statusMentionMessageInfo = 69;
+ optional bool isSupportAiMessage = 70;
+ repeated string statusMentionSources = 71;
+ repeated Citation supportAiCitations = 72;
+ optional string botTargetID = 73;
+ optional GroupHistoryIndividualMessageInfo groupHistoryIndividualMessageInfo = 74;
+ optional GroupHistoryBundleInfo groupHistoryBundleInfo = 75;
+ optional InteractiveMessageAdditionalMetadata interactiveMessageAdditionalMetadata = 76;
+ optional QuarantinedMessage quarantinedMessage = 77;
+ optional uint32 nonJIDMentions = 78;
+ optional string hsmTag = 79;
+ optional uint64 ephemeralExpirationTimestamp = 80;
+ optional ScheduledMessageMetadata scheduledMessageMetadata = 81;
+ optional string decisionID = 82;
+ repeated string decisionSources = 83;
+ optional EventInviteAdditionalMetadata eventInviteAdditionalMetadata = 84;
+}
+
+message PaymentInfo {
+ enum TxnStatus {
+ UNKNOWN = 0;
+ PENDING_SETUP = 1;
+ PENDING_RECEIVER_SETUP = 2;
+ INIT = 3;
+ SUCCESS = 4;
+ COMPLETED = 5;
+ FAILED = 6;
+ FAILED_RISK = 7;
+ FAILED_PROCESSING = 8;
+ FAILED_RECEIVER_PROCESSING = 9;
+ FAILED_DA = 10;
+ FAILED_DA_FINAL = 11;
+ REFUNDED_TXN = 12;
+ REFUND_FAILED = 13;
+ REFUND_FAILED_PROCESSING = 14;
+ REFUND_FAILED_DA = 15;
+ EXPIRED_TXN = 16;
+ AUTH_CANCELED = 17;
+ AUTH_CANCEL_FAILED_PROCESSING = 18;
+ AUTH_CANCEL_FAILED = 19;
+ COLLECT_INIT = 20;
+ COLLECT_SUCCESS = 21;
+ COLLECT_FAILED = 22;
+ COLLECT_FAILED_RISK = 23;
+ COLLECT_REJECTED = 24;
+ COLLECT_EXPIRED = 25;
+ COLLECT_CANCELED = 26;
+ COLLECT_CANCELLING = 27;
+ IN_REVIEW = 28;
+ REVERSAL_SUCCESS = 29;
+ REVERSAL_PENDING = 30;
+ REFUND_PENDING = 31;
+ }
+
+ enum Status {
+ UNKNOWN_STATUS = 0;
+ PROCESSING = 1;
+ SENT = 2;
+ NEED_TO_ACCEPT = 3;
+ COMPLETE = 4;
+ COULD_NOT_COMPLETE = 5;
+ REFUNDED = 6;
+ EXPIRED = 7;
+ REJECTED = 8;
+ CANCELLED = 9;
+ WAITING_FOR_PAYER = 10;
+ WAITING = 11;
+ }
+
+ enum Currency {
+ UNKNOWN_CURRENCY = 0;
+ INR = 1;
+ }
+
+ optional Currency currencyDeprecated = 1;
+ optional uint64 amount1000 = 2;
+ optional string receiverJID = 3;
+ optional Status status = 4;
+ optional uint64 transactionTimestamp = 5;
+ optional WACommon.MessageKey requestMessageKey = 6;
+ optional uint64 expiryTimestamp = 7;
+ optional bool futureproofed = 8;
+ optional string currency = 9;
+ optional TxnStatus txnStatus = 10;
+ optional bool useNoviFiatFormat = 11;
+ optional WAWebProtobufsE2E.Money primaryAmount = 12;
+ optional WAWebProtobufsE2E.Money exchangeAmount = 13;
+}
+
+message WebFeatures {
+ enum Flag {
+ NOT_STARTED = 0;
+ FORCE_UPGRADE = 1;
+ DEVELOPMENT = 2;
+ PRODUCTION = 3;
+ }
+
+ optional Flag labelsDisplay = 1;
+ optional Flag voipIndividualOutgoing = 2;
+ optional Flag groupsV3 = 3;
+ optional Flag groupsV3Create = 4;
+ optional Flag changeNumberV2 = 5;
+ optional Flag queryStatusV3Thumbnail = 6;
+ optional Flag liveLocations = 7;
+ optional Flag queryVname = 8;
+ optional Flag voipIndividualIncoming = 9;
+ optional Flag quickRepliesQuery = 10;
+ optional Flag payments = 11;
+ optional Flag stickerPackQuery = 12;
+ optional Flag liveLocationsFinal = 13;
+ optional Flag labelsEdit = 14;
+ optional Flag mediaUpload = 15;
+ optional Flag mediaUploadRichQuickReplies = 18;
+ optional Flag vnameV2 = 19;
+ optional Flag videoPlaybackURL = 20;
+ optional Flag statusRanking = 21;
+ optional Flag voipIndividualVideo = 22;
+ optional Flag thirdPartyStickers = 23;
+ optional Flag frequentlyForwardedSetting = 24;
+ optional Flag groupsV4JoinPermission = 25;
+ optional Flag recentStickers = 26;
+ optional Flag catalog = 27;
+ optional Flag starredStickers = 28;
+ optional Flag voipGroupCall = 29;
+ optional Flag templateMessage = 30;
+ optional Flag templateMessageInteractivity = 31;
+ optional Flag ephemeralMessages = 32;
+ optional Flag e2ENotificationSync = 33;
+ optional Flag recentStickersV2 = 34;
+ optional Flag recentStickersV3 = 36;
+ optional Flag userNotice = 37;
+ optional Flag support = 39;
+ optional Flag groupUiiCleanup = 40;
+ optional Flag groupDogfoodingInternalOnly = 41;
+ optional Flag settingsSync = 42;
+ optional Flag archiveV2 = 43;
+ optional Flag ephemeralAllowGroupMembers = 44;
+ optional Flag ephemeral24HDuration = 45;
+ optional Flag mdForceUpgrade = 46;
+ optional Flag disappearingMode = 47;
+ optional Flag externalMdOptInAvailable = 48;
+ optional Flag noDeleteMessageTimeLimit = 49;
+}
+
+message PinInChat {
+ enum Type {
+ UNKNOWN_TYPE = 0;
+ PIN_FOR_ALL = 1;
+ UNPIN_FOR_ALL = 2;
+ }
+
+ optional Type type = 1;
+ optional WACommon.MessageKey key = 2;
+ optional int64 senderTimestampMS = 3;
+ optional int64 serverTimestampMS = 4;
+ optional MessageAddOnContextInfo messageAddOnContextInfo = 5;
+}
+
+message MessageAddOn {
+ enum MessageAddOnType {
+ UNDEFINED = 0;
+ REACTION = 1;
+ EVENT_RESPONSE = 2;
+ POLL_UPDATE = 3;
+ PIN_IN_CHAT = 4;
+ REQUEST_LOCATION_UPDATE = 5;
+ }
+
+ optional MessageAddOnType messageAddOnType = 1;
+ optional WAWebProtobufsE2E.Message messageAddOn = 2;
+ optional int64 senderTimestampMS = 3;
+ optional int64 serverTimestampMS = 4;
+ optional WebMessageInfo.Status status = 5;
+ optional MessageAddOnContextInfo addOnContextInfo = 6;
+ optional WACommon.MessageKey messageAddOnKey = 7;
+ optional LegacyMessage legacyMessage = 8;
+}
+
+message GroupHistoryBundleInfo {
+ enum ProcessState {
+ NOT_INJECTED = 0;
+ INJECTED = 1;
+ INJECTED_PARTIAL = 2;
+ INJECTION_FAILED = 3;
+ INJECTION_FAILED_NO_RETRY = 4;
+ DEDUPED = 5;
+ }
+
+ optional WAWebProtobufsE2E.MessageHistoryBundle deprecatedMessageHistoryBundle = 1;
+ optional ProcessState processState = 2;
+}
+
+message CommentMetadata {
+ optional WACommon.MessageKey commentParentKey = 1;
+ optional uint32 replyCount = 2;
+}
+
+message WebNotificationsInfo {
+ optional uint64 timestamp = 2;
+ optional uint32 unreadChats = 3;
+ optional uint32 notifyMessageCount = 4;
+ repeated WebMessageInfo notifyMessages = 5;
+}
+
+message NotificationMessageInfo {
+ optional WACommon.MessageKey key = 1;
+ optional WAWebProtobufsE2E.Message message = 2;
+ optional uint64 messageTimestamp = 3;
+ optional string participant = 4;
+}
+
+message ReportingTokenInfo {
+ optional bytes reportingTag = 1;
+ optional uint64 reportingTagTimestamp = 2;
+}
+
+message MediaData {
+ optional string localPath = 1;
+}
+
+message PhotoChange {
+ optional bytes oldPhoto = 1;
+ optional bytes newPhoto = 2;
+ optional uint32 newPhotoID = 3;
+}
+
+message StatusPSA {
+ required uint64 campaignID = 44;
+ optional uint64 campaignExpirationTimestamp = 45;
+}
+
+message UserReceipt {
+ required string userJID = 1;
+ optional int64 receiptTimestamp = 2;
+ optional int64 readTimestamp = 3;
+ optional int64 playedTimestamp = 4;
+ repeated string pendingDeviceJID = 5;
+ repeated string deliveredDeviceJID = 6;
+}
+
+message Reaction {
+ optional WACommon.MessageKey key = 1;
+ optional string text = 2;
+ optional string groupingKey = 3;
+ optional int64 senderTimestampMS = 4;
+ optional bool unread = 5;
+}
+
+message PollUpdate {
+ optional WACommon.MessageKey pollUpdateMessageKey = 1;
+ optional WAWebProtobufsE2E.PollVoteMessage vote = 2;
+ optional int64 senderTimestampMS = 3;
+ optional int64 serverTimestampMS = 4;
+ optional bool unread = 5;
+ optional WAWebProtobufsE2E.PollUpdateMessageMetadata metadata = 6;
+}
+
+message PollAdditionalMetadata {
+ message PollNameHashHistoryEntry {
+ optional string editStanzaID = 1;
+ optional bytes pollNameHash = 2;
+ }
+
+ optional bool pollInvalidated = 1;
+ repeated PollNameHashHistoryEntry pollNameHashHistory = 2;
+ repeated WAWebProtobufsE2E.PollCreationMessage.Option originalOptions = 3;
+}
+
+message InteractiveMessageAdditionalMetadata {
+ optional bool isGalaxyFlowCompleted = 1;
+}
+
+message EventAdditionalMetadata {
+ optional bool isStale = 1;
+}
+
+message EventInviteAdditionalMetadata {
+ optional bool isUpdated = 1;
+}
+
+message KeepInChat {
+ optional WAWebProtobufsE2E.KeepType keepType = 1;
+ optional int64 serverTimestamp = 2;
+ optional WACommon.MessageKey key = 3;
+ optional string deviceJID = 4;
+ optional int64 clientTimestampMS = 5;
+ optional int64 serverTimestampMS = 6;
+}
+
+message MessageAddOnContextInfo {
+ optional uint32 messageAddOnDurationInSecs = 1;
+ optional WAWebProtobufsE2E.MessageContextInfo.MessageAddonExpiryType messageAddOnExpiryType = 2;
+}
+
+message PremiumMessageInfo {
+ optional string serverCampaignID = 1;
+}
+
+message EventResponse {
+ optional WACommon.MessageKey eventResponseMessageKey = 1;
+ optional int64 timestampMS = 2;
+ optional WAWebProtobufsE2E.EventResponseMessage eventResponseMessage = 3;
+ optional bool unread = 4;
+}
+
+message LegacyMessage {
+ optional WAWebProtobufsE2E.EventResponseMessage eventResponseMessage = 1;
+ optional WAWebProtobufsE2E.PollVoteMessage pollVote = 2;
+}
+
+message StatusMentionMessage {
+ optional WAWebProtobufsE2E.Message quotedStatus = 1;
+}
+
+message Citation {
+ required string title = 1;
+ required string subtitle = 2;
+ required string cmsID = 3;
+ required string imageURL = 4;
+}
+
+message GroupHistoryIndividualMessageInfo {
+ optional WACommon.MessageKey bundleMessageKey = 1;
+ optional bool editedAfterReceivedAsHistory = 2;
+}
+
+message QuarantinedMessage {
+ optional bytes originalData = 1;
+ optional string extractedText = 2;
+}
+
+message ScheduledMessageMetadata {
+ optional string revealKeyID = 1;
+ optional bytes revealKey = 2;
+ optional uint64 scheduledTime = 3;
+}
diff --git a/crates/whatsmeow_proto/proto/waWebLabyrinthWaWasm/WAWebLabyrinthWaWasm.proto b/crates/whatsmeow_proto/proto/waWebLabyrinthWaWasm/WAWebLabyrinthWaWasm.proto
new file mode 100644
index 0000000000..f22e9380a0
--- /dev/null
+++ b/crates/whatsmeow_proto/proto/waWebLabyrinthWaWasm/WAWebLabyrinthWaWasm.proto
@@ -0,0 +1,293 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+syntax = "proto2";
+package WAWebLabyrinthWaWasm;
+option go_package = "go.mau.fi/whatsmeow/proto/waWebLabyrinthWaWasm";
+
+message CreateBackupInput {
+ required string recoveryCode = 1;
+ required uint64 userID = 2;
+}
+
+message EncryptMessageInput {
+ required bytes epochRootKey = 1;
+ required bytes mailboxRootKey = 2;
+ required bytes orfClientState = 3;
+ required bytes epochAnonID = 4;
+ required uint64 epochID = 5;
+ required string threadID = 6;
+ required uint64 waCanonicalUserFbid = 7;
+ required uint64 timestampMS = 8;
+ required uint64 backupID = 9;
+ required bytes plaintextPayload = 10;
+ required string stanzaID = 11;
+}
+
+message DecryptMessageInput {
+ required bytes epochRootKey = 1;
+ required bytes epochAnonID = 2;
+ required string threadID = 3;
+ required int32 encryptionVersion = 4;
+ required bytes ciphertext = 5;
+}
+
+message OrfThreadIdInput {
+ required bytes orfClientState = 1;
+ required string threadID = 2;
+}
+
+message DeriveMessageKeyInput {
+ required bytes epochRootKey = 1;
+ required bytes epochAnonID = 2;
+ required string threadID = 3;
+}
+
+message DeriveVirtualDeviceIdInput {
+ required string recoveryCode = 1;
+ required uint64 userID = 2;
+}
+
+message AddDeviceSyncEpochInput {
+ required uint64 epochID = 1;
+ required bytes epochAnonID = 2;
+ optional bytes encryptedEpochKey = 3;
+ required bytes senderAuthPubKey = 4;
+ optional uint64 nextEpochID = 5;
+}
+
+message PrepareAddDeviceInput {
+ required string recoveryCode = 1;
+ required uint64 userID = 2;
+ required string encryptedSecretValuesJSON = 3;
+ required uint64 virtualDeviceBaseEpochID = 4;
+ required uint64 activeEpochID = 5;
+ repeated AddDeviceSyncEpochInput syncEpochs = 6;
+}
+
+message DeviceOutput {
+ required bytes publicKey = 1;
+ required bytes epochAuthPublicKey = 2;
+ required bytes epochAuthPublicKeySig = 3;
+ required bytes epochStoragePublicKey = 4;
+ required bytes epochStoragePublicKeySig = 5;
+ repeated int32 supportedEncryptionVersions = 6;
+ required bytes encryptionVersionSignature = 7;
+ required int32 clientVersion = 8;
+ required bytes ocmfClientState = 9;
+ required bytes epochStoragePrivateKey = 10;
+ required bytes epochAuthPrivateKey = 11;
+ required bytes deviceEpochHmac = 12;
+}
+
+message EncryptedSecretValuesOutput {
+ required bytes encryptedDevicePrivateKey = 1;
+ required bytes encryptedObliviousValidationTokenBlob = 2;
+ required bytes encryptedEpochStoragePrivateKey = 3;
+ required bytes encryptedOcmfClientState = 4;
+ optional bytes encryptedOrfClientStateV2 = 5;
+ required bytes encryptedMailboxRootKeyBlob = 6;
+ required bytes encryptedEpochAnonID = 7;
+ required bytes encryptedEpochRootKey = 8;
+}
+
+message VirtualDeviceOutput {
+ required bytes vdID = 1;
+ required bytes vdPublicKey = 2;
+ required bytes vdEpochStoragePublicKey = 3;
+ required bytes vdEpochStoragePublicKeySig = 4;
+ required bytes ocmfRotationToken = 5;
+ required bytes deviceEpochHmac = 6;
+ required EncryptedSecretValuesOutput encryptedSecretValues = 7;
+}
+
+message Epoch0Output {
+ required uint64 epochFbid = 1;
+ required bytes epochAnonID = 2;
+ required bytes epochRootKeyFingerprint = 6;
+ optional bytes epochRootKey = 7;
+}
+
+message CreateBackupOutput {
+ optional DeviceOutput device = 1;
+ optional VirtualDeviceOutput virtualDevice = 2;
+ optional Epoch0Output epoch0 = 3;
+ optional bytes mailboxRootKey = 4;
+ optional string error = 5;
+}
+
+message EncryptMessageOutput {
+ optional bytes encryptedProtobuf = 1;
+ optional bytes orfThreadID = 2;
+ optional string valueSecretRef = 3;
+ optional uint64 offlineThreadingID = 4;
+ optional uint64 timestampMS = 5;
+ optional string error = 7;
+}
+
+message DecryptMessageOutput {
+ optional bytes plaintextPayload = 1;
+ optional string error = 2;
+}
+
+message OrfThreadIdOutput {
+ optional bytes orfThreadID = 1;
+ optional string error = 2;
+}
+
+message DeriveMessageKeyOutput {
+ optional bytes messageKey = 1;
+ optional string error = 2;
+}
+
+message DeriveVirtualDeviceIdOutput {
+ optional bytes virtualDeviceID = 1;
+ optional string error = 2;
+}
+
+message AddDeviceKeysOutput {
+ required bytes devicePublicKey = 1;
+ required bytes epochAuthPublicKey = 2;
+ required bytes epochAuthPublicKeySig = 3;
+ required bytes epochStoragePublicKey = 4;
+ required bytes epochStoragePublicKeySig = 5;
+ required bytes epochStoragePrivateKey = 6;
+ required bytes orfClientState = 7;
+}
+
+message EpochKey {
+ required uint64 serverEpochID = 1;
+ required bytes epochAnonID = 2;
+ required bytes epochRootKey = 3;
+}
+
+message PrepareAddDeviceOutput {
+ optional AddDeviceKeysOutput deviceKeys = 1;
+ optional EpochKey currentEpoch = 2;
+ optional bytes mailboxRootSalt = 3;
+ optional bytes orfRotationToken = 4;
+ optional bytes deviceEpochHmac = 5;
+ optional bytes epochRootKeyFingerprint = 6;
+ repeated int32 supportedEncryptionVersions = 7;
+ optional bytes encryptionVersionSignature = 8;
+ optional int32 clientVersion = 9;
+ optional string error = 10;
+}
+
+message RotateEpochMemberInput {
+ required uint64 deviceID = 1;
+ required bytes epochStoragePublicKey = 2;
+ required bytes devicePublicKey = 3;
+ required bytes prevDeviceEpochHmac = 4;
+ required bytes epochStoragePublicKeySig = 5;
+}
+
+message RotateEpochInput {
+ required bytes currentEpochRootKey = 1;
+ required bytes currentEpochAnonID = 2;
+ required uint64 currentEpochFbid = 3;
+ required bytes epochStorageAuthPrivateKey = 4;
+ repeated RotateEpochMemberInput members = 5;
+}
+
+message RotateEpochMemberEdge {
+ optional uint64 deviceID = 1;
+ optional bytes encryptedEpochKey = 2;
+ optional bytes deviceEpochHmac = 3;
+}
+
+message BackwardEdge {
+ optional bytes encryptedPrevEpochAnonID = 1;
+ optional bytes encryptedPrevEpochRootKey = 2;
+ optional bytes prevEpochRootKeyFingerprint = 3;
+}
+
+message RotateEpochOutput {
+ optional bytes newEpochRootKey = 1;
+ optional uint64 newEpochAnonID = 2;
+ optional bytes epochAnonID = 3;
+ optional BackwardEdge backwardEdge = 4;
+ repeated RotateEpochMemberEdge memberEdges = 5;
+ optional bytes epochRootKeyFingerprint = 6;
+ optional string error = 7;
+}
+
+message ComputeClientSealTokenInput {
+ required bytes orfClientState = 1;
+ required uint64 backupID = 2;
+}
+
+message ComputeClientSealTokenOutput {
+ optional bytes clientSealToken = 1;
+ optional string error = 2;
+}
+
+message SealThreadIdInput {
+ required bytes epochRootKey = 1;
+ required bytes epochAnonID = 2;
+ required uint64 backupID = 3;
+ required string threadID = 4;
+}
+
+message SealThreadIdOutput {
+ optional bytes sealedThreadID = 1;
+ optional string error = 2;
+}
+
+message OpenSealedThreadIdInput {
+ required uint64 backupID = 1;
+ required bytes sealedThreadID = 2;
+ repeated EpochKey epochs = 3;
+}
+
+message OpenSealedThreadIdOutput {
+ optional string threadID = 1;
+ optional uint32 sealEpochAnonID = 2;
+ optional string error = 3;
+}
+
+message EpochIds {
+ required uint64 serverEpochID = 1;
+ required bytes epochAnonID = 2;
+}
+
+message ForwardEdgeInput {
+ required bytes encryptedEntropy = 1;
+ required bytes authPublicKey = 2;
+}
+
+message EpochDerivationEdge {
+ required EpochIds fromEpoch = 1;
+ required EpochIds toEpoch = 2;
+ optional ForwardEdgeInput forwardEdge = 3;
+ optional bytes backwardEdge = 4;
+}
+
+message DeriveEpochsInput {
+ required bytes epochStoragePrivateKey = 1;
+ repeated EpochKey epochs = 2;
+ repeated EpochDerivationEdge edges = 3;
+}
+
+message DeriveEpochsOutput {
+ repeated EpochKey epochs = 1;
+ optional string error = 2;
+}
+
+message LabyrinthWaCommand {
+ oneof commandInput {
+ CreateBackupInput createBackupInput = 1;
+ EncryptMessageInput encryptMessageInput = 2;
+ DecryptMessageInput decryptMessageInput = 3;
+ OrfThreadIdInput orfThreadIDInput = 4;
+ DeriveMessageKeyInput deriveMessageKeyInput = 5;
+ RotateEpochInput rotateEpochInput = 6;
+ DeriveVirtualDeviceIdInput deriveVirtualDeviceIDInput = 7;
+ PrepareAddDeviceInput prepareAddDeviceInput = 8;
+ ComputeClientSealTokenInput computeClientSealTokenInput = 9;
+ OpenSealedThreadIdInput openSealedThreadIDInput = 10;
+ DeriveEpochsInput deriveEpochsInput = 11;
+ SealThreadIdInput sealThreadIDInput = 12;
+ }
+}
diff --git a/crates/whatsmeow_proto/proto/waWinUIApi/WAWinUIApi.proto b/crates/whatsmeow_proto/proto/waWinUIApi/WAWinUIApi.proto
new file mode 100644
index 0000000000..74d86456b4
--- /dev/null
+++ b/crates/whatsmeow_proto/proto/waWinUIApi/WAWinUIApi.proto
@@ -0,0 +1,82 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+syntax = "proto2";
+package WAWinUIApi;
+option go_package = "go.mau.fi/whatsmeow/proto/waWinUIApi";
+
+enum PositronDataSource {
+ MESSAGES = 1;
+ CHATS = 2;
+ CONTACTS = 3;
+ GROUP_METADATA = 4;
+ GROUP_PARTICIPANTS = 5;
+ REACTIONS = 6;
+}
+
+message PositronMessage {
+ message MsgKey {
+ optional bool fromMe = 1;
+ optional WID remote = 2;
+ optional string ID = 3;
+ optional WID participant = 4;
+ }
+
+ message WID {
+ optional string serialized = 1;
+ }
+
+ optional int64 timestamp = 1;
+ optional string type = 2;
+ optional string body = 3;
+ optional MsgKey ID = 4;
+ optional string JSON = 99;
+}
+
+message PositronChat {
+ optional string ID = 1;
+ optional string name = 2;
+ optional int64 timestamp = 3;
+ optional int64 unreadCount = 4;
+ optional string JSON = 99;
+}
+
+message PositronContact {
+ optional string ID = 1;
+ optional string phoneNumber = 2;
+ optional string name = 3;
+ optional bool isAddressBookContact = 4;
+ optional string JSON = 99;
+}
+
+message PositronGroupMetadata {
+ optional string ID = 1;
+ optional string subject = 2;
+ optional string JSON = 99;
+}
+
+message PositronGroupParticipants {
+ optional string ID = 1;
+ repeated string participants = 2;
+ optional string JSON = 99;
+}
+
+message PositronReaction {
+ optional string ID = 1;
+ optional string parentMsgKey = 2;
+ optional string reactionText = 3;
+ optional int64 timestamp = 4;
+ optional string senderUserJID = 5;
+ optional string JSON = 99;
+}
+
+message PositronData {
+ optional PositronDataSource dataSource = 1;
+ repeated PositronMessage messages = 2;
+ repeated PositronChat chats = 3;
+ repeated PositronContact contacts = 4;
+ repeated PositronGroupMetadata groupMetadata = 5;
+ repeated PositronGroupParticipants groupParticipants = 6;
+ repeated PositronReaction reactions = 7;
+}
diff --git a/crates/whatsmeow_proto/src/lib.rs b/crates/whatsmeow_proto/src/lib.rs
new file mode 100644
index 0000000000..89c7da7912
--- /dev/null
+++ b/crates/whatsmeow_proto/src/lib.rs
@@ -0,0 +1,66 @@
+// This Source Code Form is subject to the terms of the Mozilla Public
+// License, v. 2.0. If a copy of the MPL was not distributed with this
+// file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+//! Protobuf types of the whatsmeow port, generated by prost from the `.proto`
+//! files under `proto/` (copied from whatsmeow's `proto/` tree).
+//!
+//! Modules carry prost's snake_case form of each proto package name. The
+//! aliases at the bottom give every package the directory name whatsmeow's Go
+//! code imports it by (`waE2E` → [`wa_e2e`]), so ported code reads like the Go.
+#![deny(missing_docs)]
+
+#[expect(
+ missing_docs,
+ clippy::large_enum_variant,
+ clippy::module_inception,
+ reason = "prost output for the vendored .proto files; the wire shapes are WhatsApp's"
+)]
+mod generated {
+ include!(concat!(env!("OUT_DIR"), "/_includes.rs"));
+}
+
+pub use generated::*;
+
+/// whatsmeow's `proto/waLidMigrationSyncPayload` package (`WAWebProtobufLidMigrationSyncPayload`).
+pub use wa_web_protobuf_lid_migration_sync_payload as wa_lid_migration_sync_payload;
+/// whatsmeow's `proto/waSyncAction` package (`WAWebProtobufSyncAction`).
+pub use wa_web_protobuf_sync_action as wa_sync_action;
+/// whatsmeow's `proto/waAea` package (`WAWebProtobufsAea`).
+pub use wa_web_protobufs_aea as wa_aea;
+/// whatsmeow's `proto/waAICommon` package (`WAWebProtobufsAICommon`).
+pub use wa_web_protobufs_ai_common as wa_ai_common;
+/// whatsmeow's `proto/waChatLockSettings` package (`WAWebProtobufsChatLockSettings`).
+pub use wa_web_protobufs_chat_lock_settings as wa_chat_lock_settings;
+/// whatsmeow's `proto/waDeviceCapabilities` package (`WAWebProtobufsDeviceCapabilities`).
+pub use wa_web_protobufs_device_capabilities as wa_device_capabilities;
+/// whatsmeow's `proto/waE2E` package (`WAWebProtobufsE2E`).
+pub use wa_web_protobufs_e2e as wa_e2e;
+/// whatsmeow's `proto/waE2EGuest` package (`WAWebProtobufsE2EGuest`).
+pub use wa_web_protobufs_e2e_guest as wa_e2e_guest;
+/// whatsmeow's `proto/waEphemeral` package (`WAWebProtobufsEphemeral`).
+pub use wa_web_protobufs_ephemeral as wa_ephemeral;
+/// whatsmeow's `proto/waGroupHistory` package (`WAWebProtobufsGroupHistory`).
+pub use wa_web_protobufs_group_history as wa_group_history;
+/// whatsmeow's `proto/waHistorySync` package (`WAWebProtobufsHistorySync`).
+pub use wa_web_protobufs_history_sync as wa_history_sync;
+/// whatsmeow's `proto/waQuickPromotionSurfaces` package (`WAWebProtobufsQuickPromotionSurfaces`).
+pub use wa_web_protobufs_quick_promotion_surfaces as wa_quick_promotion_surfaces;
+/// whatsmeow's `proto/waReporting` package (`WAWebProtobufsReporting`).
+pub use wa_web_protobufs_reporting as wa_reporting;
+/// whatsmeow's `proto/waRoutingInfo` package (`WAWebProtobufsRoutingInfo`).
+pub use wa_web_protobufs_routing_info as wa_routing_info;
+/// whatsmeow's `proto/waServerSync` package (`WAWebProtobufsServerSync`).
+pub use wa_web_protobufs_server_sync as wa_server_sync;
+/// whatsmeow's `proto/waSyncdSnapshotRecovery` package (`WAWebProtobufsSyncdSnapshotRecovery`).
+pub use wa_web_protobufs_syncd_snapshot_recovery as wa_syncd_snapshot_recovery;
+/// whatsmeow's `proto/waUserPassword` package (`WAWebProtobufsUserPassword`).
+pub use wa_web_protobufs_user_password as wa_user_password;
+/// whatsmeow's `proto/waVnameCert` package (`WAWebProtobufsVnameCert`).
+pub use wa_web_protobufs_vname_cert as wa_vname_cert;
+/// whatsmeow's `proto/waWa6` package (`WAWebProtobufsWa6`).
+pub use wa_web_protobufs_wa6 as wa_wa6;
+/// whatsmeow's `proto/waWeb` package (`WAWebProtobufsWeb`).
+pub use wa_web_protobufs_web as wa_web;
+/// whatsmeow's `proto/waAICommonDeprecated` package (`WAAICommonDeprecated`).
+pub use waai_common_deprecated as wa_ai_common_deprecated;
diff --git a/crates/workspace-hack/Cargo.toml b/crates/workspace-hack/Cargo.toml
index a7a975014f..188c1c7fbe 100644
--- a/crates/workspace-hack/Cargo.toml
+++ b/crates/workspace-hack/Cargo.toml
@@ -42,12 +42,14 @@ byteorder = { version = "1" }
bytes = { version = "1", features = ["serde"] }
chacha20 = { version = "0.10", default-features = false, features = ["legacy", "rng", "zeroize"] }
chrono = { version = "0.4", features = ["serde"] }
-cipher = { version = "0.5", default-features = false, features = ["block-padding", "rand_core", "stream-wrapper"] }
+cipher-9fbad63c4bcf4a8f = { package = "cipher", version = "0.4", default-features = false, features = ["block-padding", "std"] }
+cipher-d8f496e17d97b5cb = { package = "cipher", version = "0.5", default-features = false, features = ["block-padding", "rand_core", "stream-wrapper"] }
crossbeam-utils = { version = "0.8" }
crypto-bigint = { version = "0.5", features = ["generic-array", "zeroize"] }
crypto-common-6f8ce4dd05d13bba = { package = "crypto-common", version = "0.2", default-features = false, features = ["getrandom"] }
crypto-common-c65f7effa3be6d31 = { package = "crypto-common", version = "0.1", default-features = false, features = ["getrandom", "std"] }
ctutils = { version = "0.4", default-features = false, features = ["subtle"] }
+curve25519-dalek = { version = "4", default-features = false, features = ["alloc", "digest", "precomputed-tables", "zeroize"] }
derive_more = { version = "2", features = ["add", "add_assign", "display", "from"] }
digest-93f6ce9d446188ac = { package = "digest", version = "0.10", features = ["mac", "oid", "std"] }
digest-a6292c17cd707f01 = { package = "digest", version = "0.11", features = ["alloc", "mac", "oid", "rand_core", "zeroize"] }
@@ -70,7 +72,9 @@ futures-task = { version = "0.3" }
futures-util = { version = "0.3", features = ["channel", "io", "sink"] }
generic-array = { version = "0.14", default-features = false, features = ["more_lengths", "zeroize"] }
getrandom-468e82937335b1c9 = { package = "getrandom", version = "0.3", default-features = false, features = ["std"] }
+getrandom-6f8ce4dd05d13bba = { package = "getrandom", version = "0.2", default-features = false, features = ["std"] }
getrandom-9fbad63c4bcf4a8f = { package = "getrandom", version = "0.4", default-features = false, features = ["std", "sys_rng", "wasm_js"] }
+hashbrown-3575ec1268b04181 = { package = "hashbrown", version = "0.15" }
hashbrown-582f2526e08bb6a0 = { package = "hashbrown", version = "0.14", features = ["raw"] }
hashbrown-9067fe90e8c1f593 = { package = "hashbrown", version = "0.17" }
hashbrown-986da7b5efc2b80e = { package = "hashbrown", version = "0.16" }
@@ -81,7 +85,8 @@ hyper = { version = "1", features = ["full"] }
hyper-util = { version = "0.1", features = ["client-legacy", "client-proxy", "http1", "http2", "server", "service"] }
idna = { version = "1" }
indexmap = { version = "2", features = ["serde"] }
-inout = { version = "0.2", default-features = false, features = ["block-padding"] }
+inout-6f8ce4dd05d13bba = { package = "inout", version = "0.2", default-features = false, features = ["block-padding"] }
+inout-c65f7effa3be6d31 = { package = "inout", version = "0.1", default-features = false, features = ["std"] }
insta = { version = "1", features = ["glob", "json"] }
itertools-594e8ee84c453af0 = { package = "itertools", version = "0.13" }
itertools-5ef9efb8ec2df382 = { package = "itertools", version = "0.12" }
@@ -89,6 +94,7 @@ lazy_static = { version = "1", default-features = false, features = ["spin_no_st
libc = { version = "0.2", features = ["extra_traits"] }
libz-sys = { version = "1", features = ["static"] }
log = { version = "0.4", default-features = false, features = ["std"] }
+md-5 = { version = "0.10" }
memchr = { version = "2" }
mime_guess = { version = "2" }
miniz_oxide = { version = "0.8", features = ["simd"] }
@@ -114,7 +120,8 @@ rand-274715c4dabd11b0 = { package = "rand", version = "0.9" }
rand-c38e5c1d305a1b54 = { package = "rand", version = "0.8", features = ["small_rng"] }
rand_core = { version = "0.6", default-features = false, features = ["std"] }
redis = { version = "1", features = ["cluster-async", "tokio-rustls-comp"] }
-regex-automata = { version = "0.4", default-features = false, features = ["dfa-build", "dfa-onepass", "hybrid", "meta", "nfa", "perf", "std", "unicode"] }
+regex = { version = "1" }
+regex-automata = { version = "0.4" }
regex-syntax = { version = "0.8" }
reqwest = { version = "0.13", features = ["form", "gzip", "hickory-dns", "json", "multipart", "query", "stream"] }
rig-agent = { version = "0.41", features = ["test-utils"] }
@@ -194,12 +201,14 @@ bytes = { version = "1", features = ["serde"] }
cc = { version = "1", default-features = false, features = ["parallel"] }
chacha20 = { version = "0.10", default-features = false, features = ["legacy", "rng", "zeroize"] }
chrono = { version = "0.4", features = ["serde"] }
-cipher = { version = "0.5", default-features = false, features = ["block-padding", "rand_core", "stream-wrapper"] }
+cipher-9fbad63c4bcf4a8f = { package = "cipher", version = "0.4", default-features = false, features = ["block-padding", "std"] }
+cipher-d8f496e17d97b5cb = { package = "cipher", version = "0.5", default-features = false, features = ["block-padding", "rand_core", "stream-wrapper"] }
crossbeam-utils = { version = "0.8" }
crypto-bigint = { version = "0.5", features = ["generic-array", "zeroize"] }
crypto-common-6f8ce4dd05d13bba = { package = "crypto-common", version = "0.2", default-features = false, features = ["getrandom"] }
crypto-common-c65f7effa3be6d31 = { package = "crypto-common", version = "0.1", default-features = false, features = ["getrandom", "std"] }
ctutils = { version = "0.4", default-features = false, features = ["subtle"] }
+curve25519-dalek = { version = "4", default-features = false, features = ["alloc", "digest", "precomputed-tables", "zeroize"] }
derive_more = { version = "2", features = ["add", "add_assign", "display", "from"] }
derive_more-impl = { version = "2", features = ["add", "add_assign", "display", "from"] }
digest-93f6ce9d446188ac = { package = "digest", version = "0.10", features = ["mac", "oid", "std"] }
@@ -223,7 +232,9 @@ futures-task = { version = "0.3" }
futures-util = { version = "0.3", features = ["channel", "io", "sink"] }
generic-array = { version = "0.14", default-features = false, features = ["more_lengths", "zeroize"] }
getrandom-468e82937335b1c9 = { package = "getrandom", version = "0.3", default-features = false, features = ["std"] }
+getrandom-6f8ce4dd05d13bba = { package = "getrandom", version = "0.2", default-features = false, features = ["std"] }
getrandom-9fbad63c4bcf4a8f = { package = "getrandom", version = "0.4", default-features = false, features = ["std", "sys_rng", "wasm_js"] }
+hashbrown-3575ec1268b04181 = { package = "hashbrown", version = "0.15" }
hashbrown-582f2526e08bb6a0 = { package = "hashbrown", version = "0.14", features = ["raw"] }
hashbrown-9067fe90e8c1f593 = { package = "hashbrown", version = "0.17" }
hashbrown-986da7b5efc2b80e = { package = "hashbrown", version = "0.16" }
@@ -234,7 +245,8 @@ hyper = { version = "1", features = ["full"] }
hyper-util = { version = "0.1", features = ["client-legacy", "client-proxy", "http1", "http2", "server", "service"] }
idna = { version = "1" }
indexmap = { version = "2", features = ["serde"] }
-inout = { version = "0.2", default-features = false, features = ["block-padding"] }
+inout-6f8ce4dd05d13bba = { package = "inout", version = "0.2", default-features = false, features = ["block-padding"] }
+inout-c65f7effa3be6d31 = { package = "inout", version = "0.1", default-features = false, features = ["std"] }
insta = { version = "1", features = ["glob", "json"] }
itertools-594e8ee84c453af0 = { package = "itertools", version = "0.13" }
itertools-5ef9efb8ec2df382 = { package = "itertools", version = "0.12" }
@@ -242,6 +254,7 @@ lazy_static = { version = "1", default-features = false, features = ["spin_no_st
libc = { version = "0.2", features = ["extra_traits"] }
libz-sys = { version = "1", features = ["static"] }
log = { version = "0.4", default-features = false, features = ["std"] }
+md-5 = { version = "0.10" }
memchr = { version = "2" }
mime_guess = { version = "2" }
miniz_oxide = { version = "0.8", features = ["simd"] }
@@ -269,7 +282,8 @@ rand-274715c4dabd11b0 = { package = "rand", version = "0.9" }
rand-c38e5c1d305a1b54 = { package = "rand", version = "0.8", features = ["small_rng"] }
rand_core = { version = "0.6", default-features = false, features = ["std"] }
redis = { version = "1", features = ["cluster-async", "tokio-rustls-comp"] }
-regex-automata = { version = "0.4", default-features = false, features = ["dfa-build", "dfa-onepass", "hybrid", "meta", "nfa", "perf", "std", "unicode"] }
+regex = { version = "1" }
+regex-automata = { version = "0.4" }
regex-syntax = { version = "0.8" }
reqwest = { version = "0.13", features = ["form", "gzip", "hickory-dns", "json", "multipart", "query", "stream"] }
rig-agent = { version = "0.41", features = ["test-utils"] }
@@ -337,6 +351,7 @@ mio = { version = "1", features = ["net", "os-ext"] }
nix = { version = "0.31", features = ["feature", "mman"] }
once_cell = { version = "1", default-features = false, features = ["critical-section"] }
openssl-sys = { version = "0.9", default-features = false, features = ["vendored"] }
+petgraph = { version = "0.8", default-features = false, features = ["std"] }
rand-93f6ce9d446188ac = { package = "rand", version = "0.10" }
rustix = { version = "1", features = ["event", "fs", "net", "pipe", "process", "system", "time"] }
signal-hook-mio = { version = "0.2", default-features = false, features = ["support-v0_8", "support-v1_0"] }
@@ -360,6 +375,7 @@ mio = { version = "1", features = ["net", "os-ext"] }
nix = { version = "0.31", features = ["feature", "mman"] }
once_cell = { version = "1", default-features = false, features = ["critical-section"] }
openssl-sys = { version = "0.9", default-features = false, features = ["vendored"] }
+petgraph = { version = "0.8", default-features = false, features = ["std"] }
rand-93f6ce9d446188ac = { package = "rand", version = "0.10" }
rustix = { version = "1", features = ["event", "fs", "net", "pipe", "process", "system", "time"] }
signal-hook-mio = { version = "0.2", default-features = false, features = ["support-v0_8", "support-v1_0"] }