shellzapy 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (345) hide show
  1. shellzapy-0.1.0.dist-info/METADATA +112 -0
  2. shellzapy-0.1.0.dist-info/RECORD +345 -0
  3. shellzapy-0.1.0.dist-info/WHEEL +4 -0
  4. shellzapy-0.1.0.dist-info/licenses/LICENSE +21 -0
  5. shellzapy-0.1.0.dist-info/licenses/NOTICE +9 -0
  6. zapy/__init__.py +58 -0
  7. zapy/_appstate/__init__.py +59 -0
  8. zapy/_appstate/constants.py +82 -0
  9. zapy/_appstate/crypto/__init__.py +17 -0
  10. zapy/_appstate/crypto/app_state_crypto.py +401 -0
  11. zapy/_appstate/parsers/__init__.py +23 -0
  12. zapy/_appstate/parsers/encoding.py +157 -0
  13. zapy/_appstate/parsers/response_parser.py +135 -0
  14. zapy/_appstate/sync/__init__.py +11 -0
  15. zapy/_appstate/sync/sync_client.py +1559 -0
  16. zapy/_appstate/types.py +137 -0
  17. zapy/_appstate/utils.py +100 -0
  18. zapy/_auth/__init__.py +3 -0
  19. zapy/_auth/auth_client.py +618 -0
  20. zapy/_auth/credentials_flow.py +290 -0
  21. zapy/_auth/pairing/__init__.py +3 -0
  22. zapy/_auth/pairing/companion_host.py +239 -0
  23. zapy/_auth/pairing/flow.py +808 -0
  24. zapy/_auth/pairing/pairing_code_crypto.py +143 -0
  25. zapy/_auth/pairing/qr_flow.py +123 -0
  26. zapy/_auth/pairing/shortcake_crypto.py +122 -0
  27. zapy/_auth/pairing/shortcake_flow.py +393 -0
  28. zapy/_auth/types.py +110 -0
  29. zapy/_client/__init__.py +26 -0
  30. zapy/_client/client.py +972 -0
  31. zapy/_client/connection/__init__.py +6 -0
  32. zapy/_client/connection/manager.py +525 -0
  33. zapy/_client/connection/receipt_queue.py +74 -0
  34. zapy/_client/coordinators/__init__.py +81 -0
  35. zapy/_client/coordinators/ab_props.py +260 -0
  36. zapy/_client/coordinators/app_state_mutation.py +2538 -0
  37. zapy/_client/coordinators/bot.py +830 -0
  38. zapy/_client/coordinators/broadcast_list.py +101 -0
  39. zapy/_client/coordinators/business.py +247 -0
  40. zapy/_client/coordinators/email.py +158 -0
  41. zapy/_client/coordinators/group.py +1478 -0
  42. zapy/_client/coordinators/incoming_node.py +758 -0
  43. zapy/_client/coordinators/low_level.py +119 -0
  44. zapy/_client/coordinators/message.py +1153 -0
  45. zapy/_client/coordinators/message_dispatch.py +1637 -0
  46. zapy/_client/coordinators/newsletter.py +110 -0
  47. zapy/_client/coordinators/offline_resume.py +271 -0
  48. zapy/_client/coordinators/passive_tasks.py +447 -0
  49. zapy/_client/coordinators/presence.py +103 -0
  50. zapy/_client/coordinators/privacy.py +623 -0
  51. zapy/_client/coordinators/profile.py +1024 -0
  52. zapy/_client/coordinators/retry.py +1878 -0
  53. zapy/_client/coordinators/status.py +132 -0
  54. zapy/_client/coordinators/stream_control.py +260 -0
  55. zapy/_client/coordinators/trusted_contact_token.py +417 -0
  56. zapy/_client/events/__init__.py +266 -0
  57. zapy/_client/events/abprops.py +58 -0
  58. zapy/_client/events/appstate_mutation.py +248 -0
  59. zapy/_client/events/business.py +565 -0
  60. zapy/_client/events/call.py +144 -0
  61. zapy/_client/events/chatstate.py +41 -0
  62. zapy/_client/events/devices.py +122 -0
  63. zapy/_client/events/dirty.py +384 -0
  64. zapy/_client/events/group.py +655 -0
  65. zapy/_client/events/identity.py +40 -0
  66. zapy/_client/events/incoming.py +1079 -0
  67. zapy/_client/events/mex_notification.py +317 -0
  68. zapy/_client/events/offline.py +123 -0
  69. zapy/_client/events/picture.py +67 -0
  70. zapy/_client/events/presence.py +74 -0
  71. zapy/_client/events/privacy.py +187 -0
  72. zapy/_client/events/privacy_token.py +72 -0
  73. zapy/_client/events/receipt.py +109 -0
  74. zapy/_client/events/registration.py +70 -0
  75. zapy/_client/events/username.py +76 -0
  76. zapy/_client/factory.py +2020 -0
  77. zapy/_client/media.py +829 -0
  78. zapy/_client/newsletter/__init__.py +90 -0
  79. zapy/_client/newsletter/admin.py +323 -0
  80. zapy/_client/newsletter/content.py +499 -0
  81. zapy/_client/newsletter/discovery.py +233 -0
  82. zapy/_client/newsletter/messaging.py +396 -0
  83. zapy/_client/newsletter/mex.py +99 -0
  84. zapy/_client/newsletter/parse.py +406 -0
  85. zapy/_client/newsletter/types.py +393 -0
  86. zapy/_client/persistence/__init__.py +89 -0
  87. zapy/_client/persistence/companion_host.py +133 -0
  88. zapy/_client/persistence/ephemeral_setting.py +245 -0
  89. zapy/_client/persistence/group_history.py +361 -0
  90. zapy/_client/persistence/history_blob.py +169 -0
  91. zapy/_client/persistence/history_sync.py +646 -0
  92. zapy/_client/persistence/mailbox.py +232 -0
  93. zapy/_client/persistence/write_behind_persistence.py +368 -0
  94. zapy/_client/plugins/__init__.py +23 -0
  95. zapy/_client/plugins/define.py +44 -0
  96. zapy/_client/plugins/install.py +254 -0
  97. zapy/_client/plugins/types.py +64 -0
  98. zapy/_client/tokens/__init__.py +21 -0
  99. zapy/_client/tokens/cs_token.py +47 -0
  100. zapy/_client/tokens/tc_token.py +43 -0
  101. zapy/_client/types.py +988 -0
  102. zapy/_crypto/__init__.py +65 -0
  103. zapy/_crypto/core/__init__.py +62 -0
  104. zapy/_crypto/core/hkdf.py +41 -0
  105. zapy/_crypto/core/keys.py +51 -0
  106. zapy/_crypto/core/nonce.py +25 -0
  107. zapy/_crypto/core/primitives.py +179 -0
  108. zapy/_crypto/core/random.py +32 -0
  109. zapy/_crypto/core/xeddsa.py +72 -0
  110. zapy/_crypto/curves/__init__.py +3 -0
  111. zapy/_crypto/curves/constants.py +10 -0
  112. zapy/_crypto/curves/ed25519.py +61 -0
  113. zapy/_crypto/curves/types.py +18 -0
  114. zapy/_crypto/curves/x25519.py +117 -0
  115. zapy/_crypto/math/__init__.py +3 -0
  116. zapy/_crypto/math/constants.py +35 -0
  117. zapy/_crypto/math/edwards.py +174 -0
  118. zapy/_crypto/math/fe.py +120 -0
  119. zapy/_crypto/math/le.py +13 -0
  120. zapy/_crypto/math/mod.py +15 -0
  121. zapy/_crypto/math/prime.py +11 -0
  122. zapy/_crypto/math/types.py +25 -0
  123. zapy/_crypto/native_backend.py +40 -0
  124. zapy/_infra/__init__.py +3 -0
  125. zapy/_infra/log.py +142 -0
  126. zapy/_infra/perf.py +77 -0
  127. zapy/_media/__init__.py +64 -0
  128. zapy/_media/constants.py +133 -0
  129. zapy/_media/container.py +110 -0
  130. zapy/_media/crypto/__init__.py +19 -0
  131. zapy/_media/crypto/crypto.py +633 -0
  132. zapy/_media/crypto/media_retry.py +107 -0
  133. zapy/_media/processor.py +100 -0
  134. zapy/_media/sticker/__init__.py +8 -0
  135. zapy/_media/sticker/pack.py +188 -0
  136. zapy/_media/transfer/__init__.py +15 -0
  137. zapy/_media/transfer/client.py +635 -0
  138. zapy/_media/transfer/conn.py +48 -0
  139. zapy/_media/types.py +169 -0
  140. zapy/_message/__init__.py +121 -0
  141. zapy/_message/addons/__init__.py +5 -0
  142. zapy/_message/addons/link_preview/__init__.py +54 -0
  143. zapy/_message/addons/link_preview/builder.py +56 -0
  144. zapy/_message/addons/link_preview/detect.py +72 -0
  145. zapy/_message/addons/link_preview/fetcher.py +553 -0
  146. zapy/_message/addons/link_preview/types.py +100 -0
  147. zapy/_message/client.py +486 -0
  148. zapy/_message/context_info.py +424 -0
  149. zapy/_message/crypto/__init__.py +71 -0
  150. zapy/_message/crypto/addon_crypto.py +656 -0
  151. zapy/_message/crypto/icdc.py +138 -0
  152. zapy/_message/crypto/phash.py +87 -0
  153. zapy/_message/crypto/reporting_token.py +498 -0
  154. zapy/_message/crypto/use_case_secret.py +113 -0
  155. zapy/_message/encode/__init__.py +84 -0
  156. zapy/_message/encode/content.py +636 -0
  157. zapy/_message/encode/device_sent.py +88 -0
  158. zapy/_message/encode/media_payload.py +122 -0
  159. zapy/_message/encode/padding.py +27 -0
  160. zapy/_message/kinds/__init__.py +1 -0
  161. zapy/_message/kinds/bot.py +179 -0
  162. zapy/_message/kinds/group_history.py +206 -0
  163. zapy/_message/kinds/newsletter.py +388 -0
  164. zapy/_message/kinds/sticker_pack.py +74 -0
  165. zapy/_message/messaging/__init__.py +336 -0
  166. zapy/_message/messaging/companion_host.py +117 -0
  167. zapy/_message/messaging/fanout.py +311 -0
  168. zapy/_message/messaging/group_metadata.py +444 -0
  169. zapy/_message/messaging/ignore_key.py +264 -0
  170. zapy/_message/messaging/key_protocol.py +217 -0
  171. zapy/_message/messaging/link_preview.py +448 -0
  172. zapy/_message/messaging/messages.py +1429 -0
  173. zapy/_message/primitives/__init__.py +1 -0
  174. zapy/_message/primitives/ack.py +232 -0
  175. zapy/_message/primitives/incoming.py +1141 -0
  176. zapy/_message/primitives/media_retry.py +451 -0
  177. zapy/_message/primitives/peer_data_operation.py +271 -0
  178. zapy/_message/types.py +434 -0
  179. zapy/_proto/WAProto_pb2.py +2584 -0
  180. zapy/_proto/__init__.py +1 -0
  181. zapy/_protocol/__init__.py +3 -0
  182. zapy/_protocol/abprops_spec.py +6216 -0
  183. zapy/_protocol/auth.py +17 -0
  184. zapy/_protocol/browser.py +57 -0
  185. zapy/_protocol/defaults.py +38 -0
  186. zapy/_protocol/device_identity.py +54 -0
  187. zapy/_protocol/jid.py +241 -0
  188. zapy/_protocol/message.py +127 -0
  189. zapy/_protocol/nodes.py +144 -0
  190. zapy/_protocol/notification.py +18 -0
  191. zapy/_retry/__init__.py +77 -0
  192. zapy/_retry/codec.py +209 -0
  193. zapy/_retry/constants.py +28 -0
  194. zapy/_retry/parse.py +132 -0
  195. zapy/_retry/reason.py +65 -0
  196. zapy/_retry/replay.py +483 -0
  197. zapy/_retry/tracker.py +161 -0
  198. zapy/_retry/types.py +122 -0
  199. zapy/_signal/__init__.py +171 -0
  200. zapy/_signal/api/__init__.py +133 -0
  201. zapy/_signal/api/codec.py +164 -0
  202. zapy/_signal/api/constants.py +14 -0
  203. zapy/_signal/api/device_sync.py +915 -0
  204. zapy/_signal/api/digest_sync.py +363 -0
  205. zapy/_signal/api/identity_sync.py +250 -0
  206. zapy/_signal/api/missing_pre_keys_sync.py +267 -0
  207. zapy/_signal/api/prekeys.py +191 -0
  208. zapy/_signal/api/result_map.py +40 -0
  209. zapy/_signal/api/rotate_key.py +111 -0
  210. zapy/_signal/api/session_sync.py +297 -0
  211. zapy/_signal/attestation.py +145 -0
  212. zapy/_signal/constants.py +22 -0
  213. zapy/_signal/encoding.py +78 -0
  214. zapy/_signal/group/__init__.py +35 -0
  215. zapy/_signal/group/chain.py +139 -0
  216. zapy/_signal/group/codec.py +78 -0
  217. zapy/_signal/group/encoding.py +166 -0
  218. zapy/_signal/group/manager.py +361 -0
  219. zapy/_signal/registration/__init__.py +44 -0
  220. zapy/_signal/registration/keygen.py +46 -0
  221. zapy/_signal/registration/reg_encoding.py +66 -0
  222. zapy/_signal/registration/reg_utils.py +52 -0
  223. zapy/_signal/session/__init__.py +114 -0
  224. zapy/_signal/session/encoding.py +385 -0
  225. zapy/_signal/session/protocol.py +590 -0
  226. zapy/_signal/session/ratchet.py +381 -0
  227. zapy/_signal/session/resolver.py +630 -0
  228. zapy/_signal/session/serializer.py +96 -0
  229. zapy/_signal/session/session.py +272 -0
  230. zapy/_signal/types.py +214 -0
  231. zapy/_store/__init__.py +118 -0
  232. zapy/_store/cache/__init__.py +166 -0
  233. zapy/_store/cache/identity.py +130 -0
  234. zapy/_store/cache/privacy_token.py +116 -0
  235. zapy/_store/cache/sender_key.py +168 -0
  236. zapy/_store/cache/session.py +142 -0
  237. zapy/_store/contracts/__init__.py +84 -0
  238. zapy/_store/contracts/appstate.py +82 -0
  239. zapy/_store/contracts/auth.py +16 -0
  240. zapy/_store/contracts/chat_metadata.py +29 -0
  241. zapy/_store/contracts/contact.py +31 -0
  242. zapy/_store/contracts/device_list.py +35 -0
  243. zapy/_store/contracts/group_metadata.py +33 -0
  244. zapy/_store/contracts/identity.py +18 -0
  245. zapy/_store/contracts/message.py +36 -0
  246. zapy/_store/contracts/message_secret.py +41 -0
  247. zapy/_store/contracts/pre_key.py +32 -0
  248. zapy/_store/contracts/privacy_token.py +32 -0
  249. zapy/_store/contracts/retry.py +47 -0
  250. zapy/_store/contracts/sender_key.py +37 -0
  251. zapy/_store/contracts/session.py +21 -0
  252. zapy/_store/contracts/signal.py +23 -0
  253. zapy/_store/contracts/thread.py +35 -0
  254. zapy/_store/create_store.py +890 -0
  255. zapy/_store/locks.py +1154 -0
  256. zapy/_store/memory/__init__.py +40 -0
  257. zapy/_store/memory/appstate.py +200 -0
  258. zapy/_store/memory/auth.py +24 -0
  259. zapy/_store/memory/chat_metadata.py +124 -0
  260. zapy/_store/memory/contact.py +125 -0
  261. zapy/_store/memory/device_list.py +161 -0
  262. zapy/_store/memory/group_metadata.py +125 -0
  263. zapy/_store/memory/identity.py +86 -0
  264. zapy/_store/memory/message.py +85 -0
  265. zapy/_store/memory/message_secret.py +145 -0
  266. zapy/_store/memory/pre_key.py +112 -0
  267. zapy/_store/memory/privacy_token.py +103 -0
  268. zapy/_store/memory/retry.py +250 -0
  269. zapy/_store/memory/sender_key.py +162 -0
  270. zapy/_store/memory/session.py +111 -0
  271. zapy/_store/memory/signal.py +45 -0
  272. zapy/_store/memory/thread.py +66 -0
  273. zapy/_store/noop.py +279 -0
  274. zapy/_transport/__init__.py +3 -0
  275. zapy/_transport/binary/__init__.py +77 -0
  276. zapy/_transport/binary/constants.py +80 -0
  277. zapy/_transport/binary/decoder.py +260 -0
  278. zapy/_transport/binary/encoder.py +279 -0
  279. zapy/_transport/binary/tokens.py +1289 -0
  280. zapy/_transport/comms.py +759 -0
  281. zapy/_transport/keepalive/__init__.py +3 -0
  282. zapy/_transport/keepalive/keep_alive.py +252 -0
  283. zapy/_transport/node/__init__.py +3 -0
  284. zapy/_transport/node/builders/__init__.py +9 -0
  285. zapy/_transport/node/builders/abprops.py +33 -0
  286. zapy/_transport/node/builders/account_sync.py +120 -0
  287. zapy/_transport/node/builders/bot.py +56 -0
  288. zapy/_transport/node/builders/business.py +261 -0
  289. zapy/_transport/node/builders/chatstate.py +74 -0
  290. zapy/_transport/node/builders/community.py +116 -0
  291. zapy/_transport/node/builders/device.py +30 -0
  292. zapy/_transport/node/builders/email.py +181 -0
  293. zapy/_transport/node/builders/global_.py +74 -0
  294. zapy/_transport/node/builders/group.py +279 -0
  295. zapy/_transport/node/builders/media.py +21 -0
  296. zapy/_transport/node/builders/message.py +436 -0
  297. zapy/_transport/node/builders/mobile.py +227 -0
  298. zapy/_transport/node/builders/newsletter.py +293 -0
  299. zapy/_transport/node/builders/offline.py +20 -0
  300. zapy/_transport/node/builders/pairing.py +130 -0
  301. zapy/_transport/node/builders/passive.py +28 -0
  302. zapy/_transport/node/builders/prekeys.py +215 -0
  303. zapy/_transport/node/builders/presence.py +100 -0
  304. zapy/_transport/node/builders/privacy.py +243 -0
  305. zapy/_transport/node/builders/privacy_token.py +94 -0
  306. zapy/_transport/node/builders/profile.py +176 -0
  307. zapy/_transport/node/builders/retry.py +156 -0
  308. zapy/_transport/node/builders/shortcake.py +87 -0
  309. zapy/_transport/node/builders/tos.py +92 -0
  310. zapy/_transport/node/builders/usync.py +185 -0
  311. zapy/_transport/node/helpers.py +201 -0
  312. zapy/_transport/node/orchestrator.py +210 -0
  313. zapy/_transport/node/query.py +82 -0
  314. zapy/_transport/node/transport.py +105 -0
  315. zapy/_transport/node/usync.py +33 -0
  316. zapy/_transport/node/xml.py +38 -0
  317. zapy/_transport/noise/__init__.py +7 -0
  318. zapy/_transport/noise/cert.py +85 -0
  319. zapy/_transport/noise/client_payload.py +344 -0
  320. zapy/_transport/noise/constants.py +12 -0
  321. zapy/_transport/noise/frame_codec.py +120 -0
  322. zapy/_transport/noise/handshake.py +92 -0
  323. zapy/_transport/noise/session.py +493 -0
  324. zapy/_transport/noise/socket.py +45 -0
  325. zapy/_transport/noise/types.py +66 -0
  326. zapy/_transport/noise/version.json +3 -0
  327. zapy/_transport/proxy.py +35 -0
  328. zapy/_transport/types.py +19 -0
  329. zapy/_transport/wa_version_fetcher.py +159 -0
  330. zapy/_transport/web_socket.py +602 -0
  331. zapy/_util/__init__.py +3 -0
  332. zapy/_util/bytes.py +131 -0
  333. zapy/_util/coercion.py +29 -0
  334. zapy/_util/collections.py +45 -0
  335. zapy/_util/primitives.py +49 -0
  336. zapy/client.py +840 -0
  337. zapy/errors.py +148 -0
  338. zapy/events.py +564 -0
  339. zapy/jid.py +140 -0
  340. zapy/py.typed +0 -0
  341. zapy/stores/__init__.py +50 -0
  342. zapy/stores/base.py +1627 -0
  343. zapy/stores/json_file.py +359 -0
  344. zapy/stores/memory.py +322 -0
  345. zapy/stores/sqlite.py +343 -0
@@ -0,0 +1,1559 @@
1
+ """App-state synchronization client (mirrors ``WaAppStateSyncClient.ts``).
2
+
3
+ Owns the sync key inventory, processes snapshots/patches, encrypts pending
4
+ mutations, and persists the resulting collection state in the
5
+ :class:`WaAppStateStore`.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import asyncio
11
+ from collections.abc import Awaitable, Callable, Mapping, Sequence
12
+ from dataclasses import dataclass, field
13
+ from typing import Any
14
+
15
+ from zapy._appstate.constants import (
16
+ APP_STATE_DEFAULT_COLLECTION_VERSION,
17
+ APP_STATE_DEFAULT_COLLECTIONS,
18
+ APP_STATE_EMPTY_LT_HASH,
19
+ WA_APP_STATE_COLLECTION_STATES,
20
+ )
21
+ from zapy._appstate.crypto.app_state_crypto import (
22
+ WaAppStateCrypto,
23
+ WaAppStateDecryptedMutation,
24
+ )
25
+ from zapy._appstate.parsers.response_parser import (
26
+ CollectionResponsePayload,
27
+ parse_sync_response,
28
+ )
29
+ from zapy._appstate.types import (
30
+ OnMissingKeys,
31
+ WaAppStateCollectionSyncResult,
32
+ WaAppStateMissingKeyError,
33
+ WaAppStateMissingKeysEvent,
34
+ WaAppStateMutation,
35
+ WaAppStateMutationInput,
36
+ WaAppStateSyncKey,
37
+ WaAppStateSyncOptions,
38
+ WaAppStateSyncResult,
39
+ )
40
+ from zapy._crypto.core.random import random_bytes, random_int
41
+ from zapy._infra.log import Logger
42
+ from zapy._message.messaging import ServerClock
43
+ from zapy._proto import WAProto_pb2
44
+ from zapy._protocol.defaults import HOST_DOMAIN
45
+ from zapy._protocol.jid import normalize_device_jid, parse_signal_address_from_jid
46
+ from zapy._protocol.nodes import WA_IQ_TYPES, WA_NODE_TAGS, WA_XMLNS
47
+ from zapy._store.contracts.appstate import (
48
+ WaAppStateCollectionStateUpdate,
49
+ WaAppStateStore,
50
+ )
51
+ from zapy._transport.node.query import assert_iq_result
52
+ from zapy._transport.types import BinaryNode
53
+ from zapy._util.bytes import bytes_to_hex, decode_proto_bytes, uint8_timing_safe_equal
54
+ from zapy._util.primitives import to_error
55
+
56
+ # Verbatim ``src/protocol/defaults.ts`` (the full ``WA_DEFAULTS`` table lands
57
+ # with the protocol layer).
58
+ APP_STATE_SYNC_TIMEOUT_MS: float = 30_000
59
+
60
+ _MAX_SAFE_INTEGER = 2**53 - 1
61
+ _MAX_SYNC_ITERATIONS = 5
62
+
63
+
64
+ @dataclass(frozen=True, slots=True)
65
+ class IncomingAppStateKeyEventContext:
66
+ """Message-key context for incoming app-state key protocol messages."""
67
+
68
+ remote_jid: str | None = None
69
+ id: str | None = None
70
+ participant: str | None = None
71
+ sender_device: int = 0
72
+
73
+
74
+ @dataclass
75
+ class _SyncCollectionState:
76
+ """Mutable per-collection sync state held for one sync round."""
77
+
78
+ initialized: bool = False
79
+ version: int = APP_STATE_DEFAULT_COLLECTION_VERSION
80
+ hash: bytes = APP_STATE_EMPTY_LT_HASH
81
+ index_value_map: dict[str, bytes] = field(default_factory=dict)
82
+
83
+
84
+ @dataclass
85
+ class _OutgoingPatchContext:
86
+ collection: str
87
+ patch_version: int
88
+ next_hash: bytes
89
+ next_index_value_map: dict[str, bytes]
90
+
91
+
92
+ @dataclass(frozen=True, slots=True)
93
+ class _MacMutation:
94
+ operation: int
95
+ index_mac: bytes
96
+ value_mac: bytes
97
+
98
+
99
+ @dataclass
100
+ class _DecryptedPatchMutation:
101
+ collection: str
102
+ operation: str
103
+ source: str
104
+ operation_code: int
105
+ index: str
106
+ value: Any | None
107
+ version: int
108
+ index_mac: bytes
109
+ value_mac: bytes
110
+ key_id: bytes
111
+ timestamp: int
112
+
113
+
114
+ @dataclass
115
+ class _CollectionOutcome:
116
+ collection: str
117
+ should_refetch: bool
118
+ state_changed: bool
119
+ result: WaAppStateCollectionSyncResult
120
+ missing_key_id: bytes | None = None
121
+
122
+
123
+ @dataclass
124
+ class _SyncContext:
125
+ keys: dict[str, bytes | None] = field(default_factory=dict)
126
+ collections: dict[str, _SyncCollectionState] = field(default_factory=dict)
127
+ dirty_collections: set[str] = field(default_factory=set)
128
+
129
+
130
+ def _normalize_proto_long(value: Any, field: str) -> int:
131
+ """Coerce a protobuf long-ish value to a safe int (``None`` means ``0``)."""
132
+ if value is None:
133
+ return 0
134
+ if isinstance(value, bool) or not isinstance(value, int):
135
+ raise ValueError(f"invalid {field}: invalid long numeric value: {value}")
136
+ if abs(value) > _MAX_SAFE_INTEGER:
137
+ raise ValueError(f"invalid {field}: invalid long numeric value: {value}")
138
+ return value
139
+
140
+
141
+ def _coerce_sync_key(raw: Any) -> WaAppStateSyncKey:
142
+ """View a store key record as the canonical :class:`WaAppStateSyncKey`."""
143
+ if isinstance(raw, WaAppStateSyncKey):
144
+ return raw
145
+ return WaAppStateSyncKey(
146
+ key_id=bytes(raw.key_id),
147
+ key_data=bytes(raw.key_data),
148
+ timestamp=int(raw.timestamp),
149
+ fingerprint=raw.fingerprint,
150
+ )
151
+
152
+
153
+ def _apply_device_to_jid(user_jid: str, device: int | None) -> str:
154
+ """Append ``:device`` to a bare user JID (mirrors ``applyDeviceToJid``)."""
155
+ if not device:
156
+ return user_jid
157
+ user, server, _current = parse_signal_address_from_jid(user_jid)
158
+ return f"{user}:{device}@{server or HOST_DOMAIN}"
159
+
160
+
161
+ class WaAppStateSyncClient:
162
+ """App-state sync client: key inventory, snapshots/patches, and pending
163
+ mutation uploads persisted through the :class:`WaAppStateStore`."""
164
+
165
+ def __init__(
166
+ self,
167
+ *,
168
+ logger: Logger,
169
+ query: Callable[[BinaryNode, float], Awaitable[BinaryNode]],
170
+ store: WaAppStateStore,
171
+ server_clock: ServerClock,
172
+ get_current_me_jid: Callable[[], str | None] | None = None,
173
+ host_domain: str | None = None,
174
+ default_timeout_ms: float | None = None,
175
+ on_missing_keys: OnMissingKeys | None = None,
176
+ is_own_account_device: Callable[[str], bool] | None = None,
177
+ send_key_share: (
178
+ Callable[
179
+ [str, Sequence[WaAppStateSyncKey], Sequence[bytes]],
180
+ Awaitable[None],
181
+ ]
182
+ | None
183
+ ) = None,
184
+ trigger_sync: Callable[[], Awaitable[None]] | None = None,
185
+ mobile_primary: Callable[[], bool] | None = None,
186
+ skip_mac_verification: bool = False,
187
+ ) -> None:
188
+ self._logger = logger
189
+ self._query = query
190
+ self._store = store
191
+ self._server_clock = server_clock
192
+ self._get_current_me_jid = get_current_me_jid
193
+ self._host_domain = host_domain or HOST_DOMAIN
194
+ self._default_timeout_ms = (
195
+ default_timeout_ms
196
+ if default_timeout_ms is not None
197
+ else APP_STATE_SYNC_TIMEOUT_MS
198
+ )
199
+ self._on_missing_keys = on_missing_keys
200
+ self._is_own_account_device = is_own_account_device
201
+ self._send_key_share = send_key_share
202
+ self._trigger_sync = trigger_sync
203
+ self._mobile_primary = mobile_primary or (lambda: False)
204
+ self._crypto = WaAppStateCrypto(None, skip_mac_verification is True)
205
+ self._sync_context: _SyncContext | None = None
206
+ self._sync_task: asyncio.Task[WaAppStateSyncResult] | None = None
207
+
208
+ async def ensure_initial_sync_key(self) -> WaAppStateSyncKey:
209
+ """Return the active sync key, minting and persisting one when empty.
210
+
211
+ The key id mirrors the primary device layout: 2 big-endian bytes of
212
+ device id followed by a 4 big-endian byte epoch.
213
+ """
214
+ existing = await self._store.get_active_sync_key()
215
+ if existing is not None:
216
+ return _coerce_sync_key(existing)
217
+ device_id = self._resolve_device_index() or 0
218
+ epoch = random_int(1, 65_537)
219
+ key_id = bytes(
220
+ [
221
+ (device_id >> 8) & 0xFF,
222
+ device_id & 0xFF,
223
+ (epoch >> 24) & 0xFF,
224
+ (epoch >> 16) & 0xFF,
225
+ (epoch >> 8) & 0xFF,
226
+ epoch & 0xFF,
227
+ ]
228
+ )
229
+ key_data = random_bytes(32)
230
+ raw_id = random_int(0, 0xFFFF_FFFF)
231
+ key = WaAppStateSyncKey(
232
+ key_id=key_id,
233
+ key_data=key_data,
234
+ timestamp=self._server_clock.now_ms(),
235
+ fingerprint=WAProto_pb2.Message.AppStateSyncKeyFingerprint(
236
+ rawId=raw_id, currentIndex=0, deviceIndexes=[0]
237
+ ),
238
+ )
239
+ await self._store.upsert_sync_keys([key])
240
+ self._crypto.clear_cache()
241
+ self._logger.info(
242
+ "app-state initial sync key generated (mobile primary)",
243
+ {"keyId": bytes_to_hex(key_id), "epoch": epoch, "rawId": raw_id},
244
+ )
245
+ return key
246
+
247
+ async def import_sync_keys(self, keys: Sequence[WaAppStateSyncKey]) -> int:
248
+ """Import peer-shared sync keys; return the count actually added."""
249
+ self._logger.debug("app-state importing sync keys", {"count": len(keys)})
250
+ inserted = await self._store.upsert_sync_keys(keys)
251
+ if inserted > 0:
252
+ self._crypto.clear_cache()
253
+ self._logger.info("app-state sync keys persisted", {"inserted": inserted})
254
+ return inserted
255
+
256
+ async def handle_incoming_key_share(
257
+ self,
258
+ context: IncomingAppStateKeyEventContext,
259
+ protocol_message: Any,
260
+ ) -> None:
261
+ """Handle an ``AppStateSyncKeyShare`` protocol message."""
262
+ log = self._logger.child({"id": context.id, "from": context.remote_jid})
263
+ has_share = False
264
+ try:
265
+ has_share = bool(protocol_message.HasField("appStateSyncKeyShare"))
266
+ except (ValueError, AttributeError):
267
+ has_share = False
268
+ share = protocol_message.appStateSyncKeyShare if has_share else None
269
+ if share is None:
270
+ log.warn("incoming app-state key share protocol message without payload")
271
+ return
272
+ try:
273
+ imported = await self.import_sync_key_share(share)
274
+ log.info(
275
+ "imported app-state sync key share from protocol message",
276
+ {"imported": imported},
277
+ )
278
+ if imported > 0 and self._trigger_sync is not None:
279
+ trigger_sync = self._trigger_sync
280
+ task_log = log
281
+
282
+ async def _run_trigger() -> None:
283
+ try:
284
+ await trigger_sync()
285
+ except Exception as error:
286
+ task_log.warn(
287
+ "failed to sync app-state after key share import",
288
+ {"message": str(to_error(error))},
289
+ )
290
+
291
+ asyncio.get_running_loop().create_task(_run_trigger())
292
+ except Exception as error:
293
+ log.warn(
294
+ "failed to import app-state sync key share from protocol message",
295
+ {"message": str(to_error(error))},
296
+ )
297
+
298
+ async def handle_incoming_key_request(
299
+ self,
300
+ context: IncomingAppStateKeyEventContext,
301
+ protocol_message: Any,
302
+ ) -> None:
303
+ """Handle an ``AppStateSyncKeyRequest`` protocol message."""
304
+ log = self._logger.child({"id": context.id, "from": context.remote_jid})
305
+ has_request = False
306
+ try:
307
+ has_request = bool(protocol_message.HasField("appStateSyncKeyRequest"))
308
+ except (ValueError, AttributeError):
309
+ has_request = False
310
+ request = protocol_message.appStateSyncKeyRequest if has_request else None
311
+ if request is None:
312
+ log.warn("incoming app-state key request protocol message without payload")
313
+ return
314
+
315
+ sender_jid = context.participant or context.remote_jid
316
+ if not sender_jid:
317
+ log.warn("incoming app-state key request missing sender jid")
318
+ return
319
+
320
+ try:
321
+ requester_raw = _apply_device_to_jid(sender_jid, context.sender_device)
322
+ requester_device_jid = normalize_device_jid(requester_raw)
323
+ except Exception as error:
324
+ log.warn(
325
+ "incoming app-state key request has malformed sender jid",
326
+ {"senderJid": sender_jid, "message": str(to_error(error))},
327
+ )
328
+ return
329
+
330
+ device_log = log.child({"to": requester_device_jid})
331
+ if self._is_own_account_device is not None and not self._is_own_account_device(
332
+ requester_device_jid
333
+ ):
334
+ device_log.warn(
335
+ "incoming app-state key request ignored: sender is not own account"
336
+ )
337
+ return
338
+
339
+ requested_key_ids = self._extract_key_request_ids(request)
340
+ if not requested_key_ids:
341
+ device_log.warn("incoming app-state key request has no valid key ids")
342
+ return
343
+
344
+ if self._send_key_share is None:
345
+ device_log.warn(
346
+ "incoming app-state key request received but no sendKeyShare wired"
347
+ )
348
+ return
349
+
350
+ requested_keys = await self._store.get_sync_keys_batch(requested_key_ids)
351
+ available_keys: list[WaAppStateSyncKey] = []
352
+ missing_key_ids: list[bytes] = []
353
+ for index, key in enumerate(requested_keys):
354
+ if key is not None:
355
+ available_keys.append(_coerce_sync_key(key))
356
+ else:
357
+ missing_key_ids.append(requested_key_ids[index])
358
+
359
+ try:
360
+ await self._send_key_share(
361
+ requester_device_jid, available_keys, missing_key_ids
362
+ )
363
+ device_log.info(
364
+ "responded to app-state key request",
365
+ {
366
+ "requested": len(requested_key_ids),
367
+ "shared": len(available_keys),
368
+ "missing": len(missing_key_ids),
369
+ },
370
+ )
371
+ except Exception as error:
372
+ device_log.warn(
373
+ "failed to respond to app-state key request",
374
+ {
375
+ "requested": len(requested_key_ids),
376
+ "shared": len(available_keys),
377
+ "missing": len(missing_key_ids),
378
+ "message": str(to_error(error)),
379
+ },
380
+ )
381
+
382
+ def _extract_key_request_ids(self, request: Any) -> list[bytes]:
383
+ deduped: dict[str, bytes] = {}
384
+ for key in request.keyIds or []:
385
+ try:
386
+ raw = key.keyId if key.HasField("keyId") else None
387
+ key_id = decode_proto_bytes(
388
+ raw, "appStateSyncKeyRequest.keyIds[].keyId"
389
+ )
390
+ key_hex = bytes_to_hex(key_id)
391
+ if key_hex in deduped:
392
+ continue
393
+ deduped[key_hex] = key_id
394
+ except Exception as error:
395
+ self._logger.trace(
396
+ "ignoring malformed app-state key id request entry",
397
+ {"message": str(to_error(error))},
398
+ )
399
+ return list(deduped.values())
400
+
401
+ async def import_sync_key_share(self, share: Any) -> int:
402
+ """Import the keys from a decoded ``AppStateSyncKeyShare`` message."""
403
+ keys: list[WaAppStateSyncKey] = []
404
+ for item in share.keys or []:
405
+ key_id = decode_proto_bytes(
406
+ item.keyId.keyId if item.HasField("keyId") else None,
407
+ "appStateSyncKeyShare.keys[].keyId.keyId",
408
+ )
409
+ has_data = item.HasField("keyData") if hasattr(item, "HasField") else True
410
+ key_data_raw = item.keyData.keyData if has_data else b""
411
+ if not key_data_raw:
412
+ self._logger.debug(
413
+ "app-state sync key share entry missing key data",
414
+ {"keyId": bytes_to_hex(key_id)},
415
+ )
416
+ continue
417
+ key_data = decode_proto_bytes(
418
+ key_data_raw, "appStateSyncKeyShare.keys[].keyData.keyData"
419
+ )
420
+ timestamp_raw = item.keyData.timestamp if has_data else None
421
+ keys.append(
422
+ WaAppStateSyncKey(
423
+ key_id=key_id,
424
+ key_data=key_data,
425
+ timestamp=(
426
+ self._server_clock.now_ms()
427
+ if timestamp_raw is None
428
+ else _normalize_proto_long(
429
+ timestamp_raw,
430
+ "appStateSyncKeyShare.keys[].keyData.timestamp",
431
+ )
432
+ ),
433
+ fingerprint=(
434
+ item.keyData.fingerprint
435
+ if has_data and item.keyData.HasField("fingerprint")
436
+ else None
437
+ ),
438
+ )
439
+ )
440
+ return await self.import_sync_keys(keys)
441
+
442
+ async def sync(
443
+ self, options: WaAppStateSyncOptions | None = None
444
+ ) -> WaAppStateSyncResult:
445
+ """Run one app-state sync round. Concurrent calls join the in-flight run."""
446
+ if self._sync_task is not None and not self._sync_task.done():
447
+ self._logger.debug("app-state sync already in flight, joining existing run")
448
+ return await self._sync_task
449
+ task = asyncio.get_running_loop().create_task(
450
+ self._sync_once(options or WaAppStateSyncOptions())
451
+ )
452
+ self._sync_task = task
453
+ try:
454
+ return await task
455
+ finally:
456
+ if self._sync_task is task:
457
+ self._sync_task = None
458
+
459
+ async def _sync_once(self, options: WaAppStateSyncOptions) -> WaAppStateSyncResult:
460
+ context = _SyncContext()
461
+ self._sync_context = context
462
+ collections = list(
463
+ dict.fromkeys(options.collections or APP_STATE_DEFAULT_COLLECTIONS)
464
+ )
465
+ try:
466
+ initial_states = await self._store.get_collection_states(collections)
467
+ for index, collection in enumerate(collections):
468
+ state = initial_states[index]
469
+ context.collections[collection] = _SyncCollectionState(
470
+ initialized=state.initialized,
471
+ version=state.version,
472
+ hash=bytes(state.hash),
473
+ index_value_map=dict(state.index_value_map),
474
+ )
475
+
476
+ self._logger.debug(
477
+ "app-state sync start",
478
+ {
479
+ "collections": len(collections),
480
+ "pendingMutations": len(options.pending_mutations or ()),
481
+ },
482
+ )
483
+ pending_by_collection = self._group_pending_mutations(
484
+ options.pending_mutations or ()
485
+ )
486
+ result_map: dict[str, WaAppStateCollectionSyncResult] = {}
487
+ state_changed = False
488
+ collections_to_sync = list(collections)
489
+ missing_keys_handler = options.on_missing_keys or self._on_missing_keys
490
+ sync_iteration = 0
491
+
492
+ while collections_to_sync:
493
+ sync_iteration += 1
494
+ if sync_iteration > _MAX_SYNC_ITERATIONS:
495
+ self._logger.warn(
496
+ "app-state sync reached max iterations",
497
+ {
498
+ "maxSyncIterations": _MAX_SYNC_ITERATIONS,
499
+ "remainingCollections": collections_to_sync,
500
+ },
501
+ )
502
+ for collection in collections_to_sync:
503
+ result_map[collection] = WaAppStateCollectionSyncResult(
504
+ collection=collection,
505
+ state=WA_APP_STATE_COLLECTION_STATES["ERROR_RETRY"],
506
+ )
507
+ break
508
+
509
+ round_result = await self._sync_collections_round(
510
+ collections_to_sync, pending_by_collection, options
511
+ )
512
+ state_changed = state_changed or round_result["state_changed"]
513
+ for result in round_result["results"]:
514
+ result_map[result.collection] = result
515
+ if (
516
+ missing_keys_handler is not None
517
+ and round_result["missing_key_ids"]
518
+ and round_result["blocked_collections"]
519
+ ):
520
+ await self._notify_missing_keys(
521
+ on_missing_keys=missing_keys_handler,
522
+ key_ids=round_result["missing_key_ids"],
523
+ collections=round_result["blocked_collections"],
524
+ )
525
+
526
+ collections_to_sync = list(round_result["collections_to_refetch"])
527
+ if collections_to_sync:
528
+ self._logger.debug(
529
+ "app-state scheduling refetch for collections",
530
+ {
531
+ "iteration": sync_iteration,
532
+ "collections": collections_to_sync,
533
+ },
534
+ )
535
+
536
+ if state_changed and context.dirty_collections:
537
+ await self._persist_collection_updates()
538
+ self._logger.debug("app-state sync persisted updated state")
539
+
540
+ ordered_results = [
541
+ result_map.get(
542
+ collection,
543
+ WaAppStateCollectionSyncResult(
544
+ collection=collection,
545
+ state=WA_APP_STATE_COLLECTION_STATES["ERROR_RETRY"],
546
+ ),
547
+ )
548
+ for collection in collections
549
+ ]
550
+
551
+ self._logger.debug(
552
+ "app-state sync finished",
553
+ {"collections": len(ordered_results), "stateChanged": state_changed},
554
+ )
555
+ return WaAppStateSyncResult(collections=ordered_results)
556
+ finally:
557
+ if self._sync_context is context:
558
+ self._sync_context = None
559
+
560
+ async def _sync_collections_round(
561
+ self,
562
+ collections: Sequence[str],
563
+ pending_by_collection: Mapping[str, Sequence[WaAppStateMutationInput]],
564
+ options: WaAppStateSyncOptions,
565
+ ) -> dict[str, Any]:
566
+ active_raw = await self._store.get_active_sync_key()
567
+ active_sync_key = (
568
+ _coerce_sync_key(active_raw) if active_raw is not None else None
569
+ )
570
+ requests = [
571
+ await self._build_collection_sync_request(
572
+ collection, pending_by_collection, active_sync_key
573
+ )
574
+ for collection in collections
575
+ ]
576
+ collection_nodes: list[BinaryNode] = []
577
+ outgoing_contexts: dict[str, _OutgoingPatchContext] = {}
578
+ skipped_upload_collections: set[str] = set()
579
+ for request in requests:
580
+ collection_nodes.append(request["node"])
581
+ if request["outgoing_context"] is not None:
582
+ outgoing_contexts[request["collection"]] = request["outgoing_context"]
583
+ if request["skipped_upload"]:
584
+ skipped_upload_collections.add(request["collection"])
585
+ iq_node = self._build_sync_iq_node(collection_nodes)
586
+ payload_by_collection = await self._fetch_sync_payload_by_collection(
587
+ iq_node, options.timeout_ms or self._default_timeout_ms
588
+ )
589
+ outcomes = [
590
+ await self._process_collection_round(
591
+ collection=collection,
592
+ payload_by_collection=payload_by_collection,
593
+ pending_by_collection=pending_by_collection,
594
+ options=options,
595
+ outgoing_contexts=outgoing_contexts,
596
+ skipped_upload_collections=skipped_upload_collections,
597
+ )
598
+ for collection in collections
599
+ ]
600
+ results: list[WaAppStateCollectionSyncResult] = []
601
+ collections_to_refetch: list[str] = []
602
+ blocked_collections: list[str] = []
603
+ missing_key_ids: list[bytes] = []
604
+ missing_key_hexes: set[str] = set()
605
+ state_changed = False
606
+ for entry in outcomes:
607
+ results.append(entry.result)
608
+ if entry.should_refetch:
609
+ collections_to_refetch.append(entry.collection)
610
+ if entry.state_changed:
611
+ state_changed = True
612
+ if entry.result.state == WA_APP_STATE_COLLECTION_STATES["BLOCKED"]:
613
+ blocked_collections.append(entry.collection)
614
+ if entry.missing_key_id is not None:
615
+ key_hex = bytes_to_hex(entry.missing_key_id)
616
+ if key_hex not in missing_key_hexes:
617
+ missing_key_hexes.add(key_hex)
618
+ missing_key_ids.append(entry.missing_key_id)
619
+ return {
620
+ "results": results,
621
+ "collections_to_refetch": collections_to_refetch,
622
+ "state_changed": state_changed,
623
+ "missing_key_ids": missing_key_ids,
624
+ "blocked_collections": blocked_collections,
625
+ }
626
+
627
+ async def _build_collection_sync_request(
628
+ self,
629
+ collection: str,
630
+ pending_by_collection: Mapping[str, Sequence[WaAppStateMutationInput]],
631
+ active_sync_key: WaAppStateSyncKey | None,
632
+ ) -> dict[str, Any]:
633
+ collection_state = await self._get_collection_state(collection)
634
+ has_persisted_state = collection_state.initialized
635
+ request_snapshot = not self._mobile_primary() and not has_persisted_state
636
+ attrs: dict[str, str] = {
637
+ "name": collection,
638
+ "version": str(
639
+ collection_state.version
640
+ if has_persisted_state
641
+ else APP_STATE_DEFAULT_COLLECTION_VERSION
642
+ ),
643
+ "return_snapshot": "true" if request_snapshot else "false",
644
+ }
645
+
646
+ children: list[BinaryNode] = []
647
+ pending_mutations = list(pending_by_collection.get(collection, ()))
648
+ outgoing_context: _OutgoingPatchContext | None = None
649
+ skipped_upload = False
650
+ if pending_mutations:
651
+ if not has_persisted_state and not self._mobile_primary():
652
+ skipped_upload = True
653
+ self._logger.debug(
654
+ "app-state skipped outgoing patch upload until snapshot bootstrap",
655
+ {
656
+ "collection": collection,
657
+ "pendingMutations": len(pending_mutations),
658
+ },
659
+ )
660
+ else:
661
+ outgoing = await self._build_outgoing_patch(
662
+ collection, collection_state, pending_mutations, active_sync_key
663
+ )
664
+ outgoing_context = outgoing["context"]
665
+ children.append(
666
+ BinaryNode(
667
+ tag=WA_NODE_TAGS["PATCH"],
668
+ attrs={},
669
+ content=outgoing["encoded_patch"],
670
+ )
671
+ )
672
+
673
+ return {
674
+ "collection": collection,
675
+ "outgoing_context": outgoing_context,
676
+ "skipped_upload": skipped_upload,
677
+ "node": BinaryNode(
678
+ tag=WA_NODE_TAGS["COLLECTION"],
679
+ attrs=attrs,
680
+ content=children if children else None,
681
+ ),
682
+ }
683
+
684
+ def _build_sync_iq_node(self, collection_nodes: Sequence[BinaryNode]) -> BinaryNode:
685
+ return BinaryNode(
686
+ tag=WA_NODE_TAGS["IQ"],
687
+ attrs={
688
+ "to": self._host_domain,
689
+ "type": WA_IQ_TYPES["SET"],
690
+ "xmlns": WA_XMLNS["APP_STATE_SYNC"],
691
+ },
692
+ content=[
693
+ BinaryNode(
694
+ tag=WA_NODE_TAGS["SYNC"],
695
+ attrs={"data_namespace": "3"} if self._mobile_primary() else {},
696
+ content=list(collection_nodes),
697
+ )
698
+ ],
699
+ )
700
+
701
+ async def _fetch_sync_payload_by_collection(
702
+ self, iq_node: BinaryNode, timeout_ms: float
703
+ ) -> dict[str, CollectionResponsePayload]:
704
+ response_node = await self._query(iq_node, timeout_ms)
705
+ self._logger.debug(
706
+ "app-state sync iq response received",
707
+ {"tag": response_node.tag, "type": response_node.attrs.get("type")},
708
+ )
709
+ assert_iq_result(response_node, "app-state sync")
710
+ payloads = parse_sync_response(response_node)
711
+ self._logger.debug("app-state sync payloads parsed", {"count": len(payloads)})
712
+ return {payload.collection: payload for payload in payloads}
713
+
714
+ async def _process_collection_round(
715
+ self,
716
+ *,
717
+ collection: str,
718
+ payload_by_collection: Mapping[str, CollectionResponsePayload],
719
+ pending_by_collection: Mapping[str, Sequence[WaAppStateMutationInput]],
720
+ options: WaAppStateSyncOptions,
721
+ outgoing_contexts: Mapping[str, _OutgoingPatchContext],
722
+ skipped_upload_collections: set[str],
723
+ ) -> _CollectionOutcome:
724
+ collection_logger = self._logger.child({"collection": collection})
725
+ payload = payload_by_collection.get(collection)
726
+ should_refetch = False
727
+ collection_state_changed = False
728
+
729
+ if payload is None:
730
+ collection_logger.warn("app-state sync response missing collection payload")
731
+ return self._create_collection_outcome(
732
+ collection, WA_APP_STATE_COLLECTION_STATES["ERROR_RETRY"]
733
+ )
734
+
735
+ if payload.state in (
736
+ WA_APP_STATE_COLLECTION_STATES["ERROR_FATAL"],
737
+ WA_APP_STATE_COLLECTION_STATES["ERROR_RETRY"],
738
+ ):
739
+ return self._create_collection_outcome(
740
+ collection, payload.state, payload.version
741
+ )
742
+
743
+ pending_mutations_count = len(pending_by_collection.get(collection, ()))
744
+ is_conflict = payload.state in (
745
+ WA_APP_STATE_COLLECTION_STATES["CONFLICT"],
746
+ WA_APP_STATE_COLLECTION_STATES["CONFLICT_HAS_MORE"],
747
+ )
748
+ if is_conflict:
749
+ should_refetch = (
750
+ payload.state == WA_APP_STATE_COLLECTION_STATES["CONFLICT_HAS_MORE"]
751
+ or pending_mutations_count > 0
752
+ )
753
+
754
+ try:
755
+ applied_mutations: list[WaAppStateMutation] = []
756
+ if payload.snapshot_reference is not None and self._mobile_primary():
757
+ collection_logger.debug(
758
+ "app-state ignoring server snapshot on primary device"
759
+ )
760
+ elif payload.snapshot_reference is not None:
761
+ downloader = options.download_external_blob
762
+ if downloader is None:
763
+ raise ValueError(
764
+ f"snapshot for {payload.collection}"
765
+ " requires external blob downloader"
766
+ )
767
+ snapshot_bytes = await downloader(
768
+ payload.collection, "snapshot", payload.snapshot_reference
769
+ )
770
+ snapshot = self._validate_snapshot(
771
+ payload.collection,
772
+ WAProto_pb2.SyncdSnapshot.FromString(snapshot_bytes),
773
+ )
774
+ snapshot_mutations = await self._apply_snapshot(
775
+ payload.collection, snapshot
776
+ )
777
+ applied_mutations.extend(snapshot_mutations)
778
+ collection_state_changed = True
779
+
780
+ if payload.patches:
781
+ ready_patches = await self._resolve_ready_patches(payload, options)
782
+ for ready_patch in ready_patches:
783
+ patch_mutations = await self._apply_patch(
784
+ payload.collection, ready_patch
785
+ )
786
+ applied_mutations.extend(patch_mutations)
787
+ collection_state_changed = True
788
+ else:
789
+ outgoing_context = outgoing_contexts.get(payload.collection)
790
+ if (
791
+ outgoing_context is not None
792
+ and payload.state == WA_APP_STATE_COLLECTION_STATES["SUCCESS"]
793
+ and payload.version == outgoing_context.patch_version
794
+ ):
795
+ self._set_collection_state(
796
+ payload.collection,
797
+ outgoing_context.patch_version,
798
+ outgoing_context.next_hash,
799
+ outgoing_context.next_index_value_map,
800
+ )
801
+ collection_state_changed = True
802
+
803
+ current_collection_state = await self._get_collection_state(collection)
804
+ if (
805
+ not current_collection_state.initialized
806
+ and payload.state == WA_APP_STATE_COLLECTION_STATES["SUCCESS"]
807
+ ):
808
+ self._set_collection_state(
809
+ collection,
810
+ (
811
+ payload.version
812
+ if payload.version is not None
813
+ else current_collection_state.version
814
+ ),
815
+ current_collection_state.hash,
816
+ dict(current_collection_state.index_value_map),
817
+ )
818
+ collection_state_changed = True
819
+
820
+ should_refetch = (
821
+ should_refetch
822
+ or payload.state == WA_APP_STATE_COLLECTION_STATES["SUCCESS_HAS_MORE"]
823
+ or (
824
+ payload.state == WA_APP_STATE_COLLECTION_STATES["SUCCESS"]
825
+ and collection in skipped_upload_collections
826
+ )
827
+ )
828
+
829
+ if not is_conflict:
830
+ resolved_state = payload.state
831
+ elif payload.state == WA_APP_STATE_COLLECTION_STATES["CONFLICT"]:
832
+ resolved_state = (
833
+ WA_APP_STATE_COLLECTION_STATES["CONFLICT"]
834
+ if pending_mutations_count > 0
835
+ else WA_APP_STATE_COLLECTION_STATES["SUCCESS"]
836
+ )
837
+ else:
838
+ resolved_state = payload.state
839
+
840
+ collection_logger.debug(
841
+ "app-state collection processed",
842
+ {
843
+ "state": resolved_state,
844
+ "version": payload.version,
845
+ "appliedMutations": len(applied_mutations),
846
+ },
847
+ )
848
+ return self._create_collection_outcome(
849
+ collection,
850
+ resolved_state,
851
+ payload.version,
852
+ should_refetch,
853
+ collection_state_changed,
854
+ applied_mutations,
855
+ )
856
+ except WaAppStateMissingKeyError as error:
857
+ collection_logger.debug(
858
+ "app-state blocked by missing key", {"message": str(error)}
859
+ )
860
+ return self._create_collection_outcome(
861
+ collection,
862
+ WA_APP_STATE_COLLECTION_STATES["BLOCKED"],
863
+ payload.version,
864
+ should_refetch,
865
+ collection_state_changed,
866
+ None,
867
+ error.key_id,
868
+ )
869
+ except Exception as error:
870
+ collection_logger.debug(
871
+ "app-state collection processing failed",
872
+ {"message": str(to_error(error))},
873
+ )
874
+ return self._create_collection_outcome(
875
+ collection,
876
+ WA_APP_STATE_COLLECTION_STATES["ERROR_RETRY"],
877
+ payload.version,
878
+ True,
879
+ collection_state_changed,
880
+ )
881
+
882
+ def _create_collection_outcome(
883
+ self,
884
+ collection: str,
885
+ state: str,
886
+ version: int | None = None,
887
+ should_refetch: bool = False,
888
+ state_changed: bool = False,
889
+ mutations: Sequence[WaAppStateMutation] | None = None,
890
+ missing_key_id: bytes | None = None,
891
+ ) -> _CollectionOutcome:
892
+ return _CollectionOutcome(
893
+ collection=collection,
894
+ should_refetch=should_refetch,
895
+ state_changed=state_changed,
896
+ missing_key_id=missing_key_id,
897
+ result=WaAppStateCollectionSyncResult(
898
+ collection=collection,
899
+ state=state,
900
+ version=version,
901
+ mutations=list(mutations) if mutations is not None else None,
902
+ ),
903
+ )
904
+
905
+ async def _notify_missing_keys(
906
+ self,
907
+ *,
908
+ on_missing_keys: OnMissingKeys,
909
+ key_ids: Sequence[bytes],
910
+ collections: Sequence[str],
911
+ ) -> None:
912
+ if not key_ids or not collections:
913
+ return
914
+ key_ids_hex = [bytes_to_hex(key_id) for key_id in key_ids]
915
+ request_logger = self._logger.child(
916
+ {"keys": len(key_ids_hex), "collections": ",".join(collections)}
917
+ )
918
+ request_logger.debug(
919
+ "app-state requesting missing sync keys",
920
+ {"keyIds": ",".join(key_ids_hex)},
921
+ )
922
+ try:
923
+ await on_missing_keys(
924
+ WaAppStateMissingKeysEvent(
925
+ key_ids=list(key_ids), collections=list(collections)
926
+ )
927
+ )
928
+ except Exception as error:
929
+ request_logger.warn(
930
+ "app-state missing key callback failed",
931
+ {"message": str(to_error(error))},
932
+ )
933
+
934
+ async def _resolve_ready_patches(
935
+ self, payload: CollectionResponsePayload, options: WaAppStateSyncOptions
936
+ ) -> list[Any]:
937
+ versions = {
938
+ id(patch): self._parse_collection_patch_version(payload.collection, patch)
939
+ for patch in payload.patches
940
+ }
941
+ sorted_patches = sorted(payload.patches, key=lambda patch: versions[id(patch)])
942
+ ready: list[Any] = []
943
+ for patch in sorted_patches:
944
+ ready_patch = patch
945
+ if not ready_patch.mutations and ready_patch.HasField("externalMutations"):
946
+ downloader = options.download_external_blob
947
+ if downloader is None:
948
+ raise ValueError(
949
+ f"external patch for {payload.collection}"
950
+ " requires external blob downloader"
951
+ )
952
+ patch_bytes = await downloader(
953
+ payload.collection, "patch", ready_patch.externalMutations
954
+ )
955
+ decoded_mutations = WAProto_pb2.SyncdMutations.FromString(patch_bytes)
956
+ merged = WAProto_pb2.SyncdPatch()
957
+ merged.CopyFrom(ready_patch)
958
+ del merged.mutations[:]
959
+ merged.mutations.extend(decoded_mutations.mutations)
960
+ merged.ClearField("externalMutations")
961
+ ready_patch = merged
962
+ ready.append(self._validate_patch(payload.collection, ready_patch))
963
+ return ready
964
+
965
+ def _validate_snapshot(self, collection: str, snapshot: Any) -> Any:
966
+ if not (snapshot.HasField("version") and snapshot.version.version):
967
+ raise ValueError(f"snapshot for {collection} is missing version")
968
+ if not self._crypto.is_mac_verification_skipped:
969
+ if not snapshot.mac:
970
+ raise ValueError(f"snapshot for {collection} is missing mac")
971
+ if not (snapshot.HasField("keyId") and snapshot.keyId.id):
972
+ raise ValueError(f"snapshot for {collection} is missing keyId")
973
+ return snapshot
974
+
975
+ def _parse_collection_patch_version(self, collection: str, patch: Any) -> int:
976
+ parsed = _normalize_proto_long(
977
+ patch.version.version if patch.HasField("version") else None,
978
+ f"patch.version.version ({collection})",
979
+ )
980
+ if parsed <= 0:
981
+ raise ValueError(f"patch for {collection} has invalid version {parsed}")
982
+ return parsed
983
+
984
+ def _validate_patch(self, collection: str, patch: Any) -> Any:
985
+ if not (patch.HasField("version") and patch.version.version):
986
+ raise ValueError(f"patch for {collection} is missing version")
987
+ if not self._crypto.is_mac_verification_skipped:
988
+ if not patch.snapshotMac:
989
+ raise ValueError(f"patch for {collection} is missing snapshotMac")
990
+ if not patch.patchMac:
991
+ raise ValueError(f"patch for {collection} is missing patchMac")
992
+ if not (patch.HasField("keyId") and patch.keyId.id):
993
+ raise ValueError(f"patch for {collection} is missing keyId")
994
+ if patch.mutations and patch.HasField("externalMutations"):
995
+ raise ValueError(
996
+ f"patch for {collection} has inline and external mutations together"
997
+ )
998
+ if patch.HasField("exitCode") and patch.exitCode.code != 0:
999
+ raise ValueError(
1000
+ f"patch for {collection} has terminal exitCode"
1001
+ f" {patch.exitCode.code}: {patch.exitCode.text or ''}"
1002
+ )
1003
+ return patch
1004
+
1005
+ async def _apply_snapshot(
1006
+ self, collection: str, snapshot: Any
1007
+ ) -> list[WaAppStateMutation]:
1008
+ version = _normalize_proto_long(
1009
+ snapshot.version.version if snapshot.HasField("version") else None,
1010
+ f"snapshot.version.version ({collection})",
1011
+ )
1012
+ key_data: bytes | None = None
1013
+ if not self._crypto.is_mac_verification_skipped:
1014
+ key_id = decode_proto_bytes(
1015
+ snapshot.keyId.id if snapshot.HasField("keyId") else None,
1016
+ f"snapshot.keyId.id ({collection})",
1017
+ )
1018
+ key_data = await self._get_key_data(key_id)
1019
+ if key_data is None:
1020
+ raise WaAppStateMissingKeyError(
1021
+ f"missing snapshot key {bytes_to_hex(key_id)} for {collection}",
1022
+ key_id,
1023
+ collection,
1024
+ )
1025
+
1026
+ index_value_map: dict[str, bytes] = {}
1027
+ mutations: list[WaAppStateMutation] = []
1028
+ decrypted_records = await self._decrypt_snapshot_records(collection, snapshot)
1029
+ for decrypted, record_key_id in decrypted_records:
1030
+ index_mac_hex = bytes_to_hex(decrypted.index_mac)
1031
+ index_value_map[index_mac_hex] = decrypted.value_mac
1032
+ timestamp_raw = (
1033
+ decrypted.value.timestamp
1034
+ if decrypted.value is not None and decrypted.value.HasField("timestamp")
1035
+ else None
1036
+ )
1037
+ mutations.append(
1038
+ WaAppStateMutation(
1039
+ collection=collection,
1040
+ operation="set",
1041
+ source="snapshot",
1042
+ index=decrypted.index,
1043
+ value=decrypted.value,
1044
+ version=decrypted.version,
1045
+ index_mac=decrypted.index_mac,
1046
+ value_mac=decrypted.value_mac,
1047
+ key_id=record_key_id,
1048
+ timestamp=_normalize_proto_long(
1049
+ timestamp_raw,
1050
+ f"snapshot.record.value.timestamp ({collection})",
1051
+ ),
1052
+ )
1053
+ )
1054
+
1055
+ lt_hash_input = list(index_value_map.values())
1056
+ lt_hash = self._crypto.lt_hash_add(APP_STATE_EMPTY_LT_HASH, lt_hash_input)
1057
+ if key_data is not None:
1058
+ expected_snapshot_mac = self._crypto.generate_snapshot_mac(
1059
+ key_data, lt_hash, version, collection
1060
+ )
1061
+ if not uint8_timing_safe_equal(
1062
+ expected_snapshot_mac,
1063
+ snapshot.mac if snapshot.HasField("mac") else b"",
1064
+ ):
1065
+ # Poisoned server-side snapshot (MAC unverifiable by any
1066
+ # client): keep partial state instead of throwing, which would
1067
+ # loop refetch forever.
1068
+ self._logger.warn(
1069
+ "snapshot LT-hash verification failed,"
1070
+ " continuing with partial state",
1071
+ {"collection": collection, "version": version},
1072
+ )
1073
+ self._set_collection_state(collection, version, lt_hash, index_value_map)
1074
+ return mutations
1075
+
1076
+ async def _apply_patch(
1077
+ self, collection: str, patch: Any
1078
+ ) -> list[WaAppStateMutation]:
1079
+ patch_version = _normalize_proto_long(
1080
+ patch.version.version if patch.HasField("version") else None,
1081
+ f"patch.version.version ({collection})",
1082
+ )
1083
+ current = await self._get_collection_state(collection)
1084
+ if current.version != patch_version - 1:
1085
+ raise ValueError(
1086
+ f"patch version mismatch for {collection}:"
1087
+ f" local={current.version}, incoming={patch_version}"
1088
+ )
1089
+
1090
+ patch_key_data: bytes | None = None
1091
+ if not self._crypto.is_mac_verification_skipped:
1092
+ patch_key_id = decode_proto_bytes(
1093
+ patch.keyId.id if patch.HasField("keyId") else None,
1094
+ f"patch.keyId.id ({collection})",
1095
+ )
1096
+ patch_key_data = await self._get_key_data(patch_key_id)
1097
+ if patch_key_data is None:
1098
+ raise WaAppStateMissingKeyError(
1099
+ f"missing patch key {bytes_to_hex(patch_key_id)} for {collection}",
1100
+ patch_key_id,
1101
+ collection,
1102
+ )
1103
+
1104
+ decrypted_mutations = await self._decrypt_patch_mutations(collection, patch)
1105
+ mac_mutations = [
1106
+ _MacMutation(
1107
+ operation=mutation.operation_code,
1108
+ index_mac=mutation.index_mac,
1109
+ value_mac=mutation.value_mac,
1110
+ )
1111
+ for mutation in decrypted_mutations
1112
+ ]
1113
+ value_macs = [mutation.value_mac for mutation in decrypted_mutations]
1114
+ next_state = await self._compute_next_collection_state(
1115
+ current.hash,
1116
+ current.index_value_map,
1117
+ mac_mutations,
1118
+ collection,
1119
+ )
1120
+ if patch_key_data is not None:
1121
+ await self._assert_patch_macs_match(
1122
+ patch,
1123
+ collection,
1124
+ patch_key_data,
1125
+ patch_version,
1126
+ next_state["hash"],
1127
+ value_macs,
1128
+ )
1129
+ self._set_collection_state(
1130
+ collection, patch_version, next_state["hash"], next_state["index_value_map"]
1131
+ )
1132
+ return [
1133
+ WaAppStateMutation(
1134
+ collection=mutation.collection,
1135
+ operation=mutation.operation,
1136
+ source=mutation.source,
1137
+ index=mutation.index,
1138
+ value=mutation.value,
1139
+ version=mutation.version,
1140
+ index_mac=mutation.index_mac,
1141
+ value_mac=mutation.value_mac,
1142
+ key_id=mutation.key_id,
1143
+ timestamp=mutation.timestamp,
1144
+ )
1145
+ for mutation in decrypted_mutations
1146
+ ]
1147
+
1148
+ async def _decrypt_snapshot_records(
1149
+ self, collection: str, snapshot: Any
1150
+ ) -> list[tuple[WaAppStateDecryptedMutation, bytes]]:
1151
+ raw_records = list(snapshot.records or [])
1152
+ parsed: list[tuple[bytes, bytes, bytes]] = []
1153
+ for record in raw_records:
1154
+ record_key_id = decode_proto_bytes(
1155
+ record.keyId.id if record.HasField("keyId") else None,
1156
+ f"snapshot.record.keyId.id ({collection})",
1157
+ )
1158
+ parsed.append(
1159
+ (
1160
+ decode_proto_bytes(
1161
+ record.index.blob if record.HasField("index") else None,
1162
+ f"snapshot.record.index.blob ({collection})",
1163
+ ),
1164
+ decode_proto_bytes(
1165
+ record.value.blob if record.HasField("value") else None,
1166
+ f"snapshot.record.value.blob ({collection})",
1167
+ ),
1168
+ record_key_id,
1169
+ )
1170
+ )
1171
+ await self._preload_key_data([record_key_id for _, _, record_key_id in parsed])
1172
+
1173
+ async def _decrypt_one(
1174
+ index_mac: bytes, value_blob: bytes, record_key_id: bytes
1175
+ ) -> tuple[WaAppStateDecryptedMutation, bytes]:
1176
+ record_key_data = await self._get_key_data(record_key_id)
1177
+ if record_key_data is None:
1178
+ raise WaAppStateMissingKeyError(
1179
+ f"missing snapshot mutation key {bytes_to_hex(record_key_id)}"
1180
+ f" for {collection}",
1181
+ record_key_id,
1182
+ collection,
1183
+ )
1184
+ decrypted = self._crypto.decrypt_mutation(
1185
+ operation=WAProto_pb2.SyncdMutation.SET,
1186
+ key_id=record_key_id,
1187
+ key_data=record_key_data,
1188
+ index_mac=index_mac,
1189
+ value_blob=value_blob,
1190
+ )
1191
+ return decrypted, record_key_id
1192
+
1193
+ return list(
1194
+ await asyncio.gather(
1195
+ *[
1196
+ _decrypt_one(index_mac, value_blob, record_key_id)
1197
+ for index_mac, value_blob, record_key_id in parsed
1198
+ ]
1199
+ )
1200
+ )
1201
+
1202
+ async def _decrypt_patch_mutations(
1203
+ self, collection: str, patch: Any
1204
+ ) -> list[_DecryptedPatchMutation]:
1205
+ raw_mutations = list(patch.mutations or [])
1206
+ parsed: list[tuple[int, bytes, bytes, bytes]] = []
1207
+ for mutation in raw_mutations:
1208
+ has_operation = mutation.HasField("operation")
1209
+ operation_code = mutation.operation if has_operation else None
1210
+ if operation_code is None:
1211
+ raise ValueError(f"patch mutation is missing operation ({collection})")
1212
+ if not mutation.HasField("record"):
1213
+ raise ValueError(f"patch mutation is missing record ({collection})")
1214
+ record = mutation.record
1215
+ record_key_id = decode_proto_bytes(
1216
+ record.keyId.id if record.HasField("keyId") else None,
1217
+ f"patch.record.keyId.id ({collection})",
1218
+ )
1219
+ parsed.append(
1220
+ (
1221
+ operation_code,
1222
+ decode_proto_bytes(
1223
+ record.index.blob if record.HasField("index") else None,
1224
+ f"patch.record.index.blob ({collection})",
1225
+ ),
1226
+ decode_proto_bytes(
1227
+ record.value.blob if record.HasField("value") else None,
1228
+ f"patch.record.value.blob ({collection})",
1229
+ ),
1230
+ record_key_id,
1231
+ )
1232
+ )
1233
+ await self._preload_key_data(
1234
+ [record_key_id for _, _, _, record_key_id in parsed]
1235
+ )
1236
+
1237
+ async def _decrypt_one(
1238
+ operation_code: int,
1239
+ index_mac: bytes,
1240
+ value_blob: bytes,
1241
+ record_key_id: bytes,
1242
+ ) -> _DecryptedPatchMutation:
1243
+ record_key_data = await self._get_key_data(record_key_id)
1244
+ if record_key_data is None:
1245
+ raise WaAppStateMissingKeyError(
1246
+ f"missing mutation key {bytes_to_hex(record_key_id)}"
1247
+ f" for {collection}",
1248
+ record_key_id,
1249
+ collection,
1250
+ )
1251
+ decrypted = self._crypto.decrypt_mutation(
1252
+ operation=operation_code,
1253
+ key_id=record_key_id,
1254
+ key_data=record_key_data,
1255
+ index_mac=index_mac,
1256
+ value_blob=value_blob,
1257
+ )
1258
+ timestamp_raw = (
1259
+ decrypted.value.timestamp
1260
+ if decrypted.value is not None and decrypted.value.HasField("timestamp")
1261
+ else None
1262
+ )
1263
+ return _DecryptedPatchMutation(
1264
+ collection=collection,
1265
+ operation=(
1266
+ "remove"
1267
+ if operation_code == WAProto_pb2.SyncdMutation.REMOVE
1268
+ else "set"
1269
+ ),
1270
+ source="patch",
1271
+ operation_code=operation_code,
1272
+ index=decrypted.index,
1273
+ value=decrypted.value,
1274
+ version=decrypted.version,
1275
+ index_mac=decrypted.index_mac,
1276
+ value_mac=decrypted.value_mac,
1277
+ key_id=record_key_id,
1278
+ timestamp=_normalize_proto_long(
1279
+ timestamp_raw, f"patch.record.value.timestamp ({collection})"
1280
+ ),
1281
+ )
1282
+
1283
+ return list(
1284
+ await asyncio.gather(
1285
+ *[
1286
+ _decrypt_one(operation_code, index_mac, value_blob, record_key_id)
1287
+ for operation_code, index_mac, value_blob, record_key_id in parsed
1288
+ ]
1289
+ )
1290
+ )
1291
+
1292
+ async def _assert_patch_macs_match(
1293
+ self,
1294
+ patch: Any,
1295
+ collection: str,
1296
+ patch_key_data: bytes,
1297
+ patch_version: int,
1298
+ next_hash: bytes,
1299
+ value_macs: Sequence[bytes],
1300
+ ) -> None:
1301
+ snapshot_mac = decode_proto_bytes(
1302
+ patch.snapshotMac if patch.HasField("snapshotMac") else None,
1303
+ f"patch.snapshotMac ({collection})",
1304
+ )
1305
+ expected_snapshot_mac = self._crypto.generate_snapshot_mac(
1306
+ patch_key_data, next_hash, patch_version, collection
1307
+ )
1308
+ # Non-fatal: wa-mob/wa-web tolerate this — patchMac below covers integrity.
1309
+ if not uint8_timing_safe_equal(expected_snapshot_mac, snapshot_mac):
1310
+ self._logger.debug(
1311
+ "patch snapshot MAC mismatch (tolerated)",
1312
+ {"collection": collection, "patchVersion": patch_version},
1313
+ )
1314
+
1315
+ patch_mac = decode_proto_bytes(
1316
+ patch.patchMac if patch.HasField("patchMac") else None,
1317
+ f"patch.patchMac ({collection})",
1318
+ )
1319
+ expected_patch_mac = self._crypto.generate_patch_mac(
1320
+ patch_key_data, snapshot_mac, value_macs, patch_version, collection
1321
+ )
1322
+ if not uint8_timing_safe_equal(expected_patch_mac, patch_mac):
1323
+ raise ValueError(f"patch MAC mismatch for {collection}")
1324
+
1325
+ async def _build_outgoing_patch(
1326
+ self,
1327
+ collection: str,
1328
+ snapshot: _SyncCollectionState,
1329
+ pending_mutations: Sequence[WaAppStateMutationInput],
1330
+ active_key: WaAppStateSyncKey | None,
1331
+ ) -> dict[str, Any]:
1332
+ if active_key is None:
1333
+ raise WaAppStateMissingKeyError(
1334
+ f"no sync key available to upload {collection}", None, collection
1335
+ )
1336
+
1337
+ encrypted_mutations: list[Any] = []
1338
+ mac_mutations: list[_MacMutation] = []
1339
+ value_macs: list[bytes] = []
1340
+ for mutation in pending_mutations:
1341
+ value = mutation.value if mutation.operation == "set" else None
1342
+ operation_code = (
1343
+ WAProto_pb2.SyncdMutation.REMOVE
1344
+ if mutation.operation == "remove"
1345
+ else WAProto_pb2.SyncdMutation.SET
1346
+ )
1347
+ encrypted = self._crypto.encrypt_mutation(
1348
+ operation=operation_code,
1349
+ key_id=active_key.key_id,
1350
+ key_data=active_key.key_data,
1351
+ index=mutation.index,
1352
+ value=value,
1353
+ version=mutation.version,
1354
+ )
1355
+ record_message = WAProto_pb2.SyncdMutation()
1356
+ record_message.operation = operation_code
1357
+ record_message.record.keyId.id = bytes(active_key.key_id)
1358
+ record_message.record.index.blob = encrypted.index_mac
1359
+ record_message.record.value.blob = encrypted.value_blob
1360
+ encrypted_mutations.append(record_message)
1361
+ mac_mutations.append(
1362
+ _MacMutation(
1363
+ operation=operation_code,
1364
+ index_mac=encrypted.index_mac,
1365
+ value_mac=encrypted.value_mac,
1366
+ )
1367
+ )
1368
+ value_macs.append(encrypted.value_mac)
1369
+
1370
+ next_state = await self._compute_next_collection_state(
1371
+ snapshot.hash,
1372
+ snapshot.index_value_map,
1373
+ mac_mutations,
1374
+ collection,
1375
+ )
1376
+ patch_version = snapshot.version + 1
1377
+ snapshot_mac = self._crypto.generate_snapshot_mac(
1378
+ active_key.key_data, next_state["hash"], patch_version, collection
1379
+ )
1380
+ patch_mac = self._crypto.generate_patch_mac(
1381
+ active_key.key_data, snapshot_mac, value_macs, patch_version, collection
1382
+ )
1383
+ device_index = self._resolve_device_index()
1384
+
1385
+ patch_message = WAProto_pb2.SyncdPatch()
1386
+ patch_message.mutations.extend(encrypted_mutations)
1387
+ patch_message.snapshotMac = snapshot_mac
1388
+ patch_message.patchMac = patch_mac
1389
+ patch_message.keyId.id = bytes(active_key.key_id)
1390
+ if device_index is not None:
1391
+ patch_message.deviceIndex = device_index
1392
+ return {
1393
+ "encoded_patch": patch_message.SerializeToString(),
1394
+ "context": _OutgoingPatchContext(
1395
+ collection=collection,
1396
+ patch_version=patch_version,
1397
+ next_hash=next_state["hash"],
1398
+ next_index_value_map=next_state["index_value_map"],
1399
+ ),
1400
+ }
1401
+
1402
+ def _resolve_device_index(self) -> int | None:
1403
+ me_jid = self._get_current_me_jid() if self._get_current_me_jid else None
1404
+ if not me_jid:
1405
+ return None
1406
+ try:
1407
+ _user, _server, device = parse_signal_address_from_jid(me_jid)
1408
+ return device
1409
+ except Exception as error:
1410
+ self._logger.debug(
1411
+ "app-state could not parse device index from me jid",
1412
+ {"meJid": me_jid, "message": str(to_error(error))},
1413
+ )
1414
+ return None
1415
+
1416
+ async def _compute_next_collection_state(
1417
+ self,
1418
+ base_hash: bytes,
1419
+ base_map: Mapping[str, bytes],
1420
+ mutations: Sequence[_MacMutation],
1421
+ collection: str,
1422
+ ) -> dict[str, Any]:
1423
+ index_value_map = dict(base_map)
1424
+ add_values: list[bytes] = []
1425
+ remove_values: list[bytes] = []
1426
+ missing_remove_count = 0
1427
+ for mutation in mutations:
1428
+ index_mac_hex = bytes_to_hex(mutation.index_mac)
1429
+ existing = index_value_map.get(index_mac_hex)
1430
+ if mutation.operation == WAProto_pb2.SyncdMutation.REMOVE:
1431
+ if existing is None:
1432
+ missing_remove_count += 1
1433
+ continue
1434
+ del index_value_map[index_mac_hex]
1435
+ remove_values.append(existing)
1436
+ continue
1437
+ if existing is not None:
1438
+ remove_values.append(existing)
1439
+ index_value_map[index_mac_hex] = mutation.value_mac
1440
+ add_values.append(mutation.value_mac)
1441
+ if missing_remove_count > 0:
1442
+ self._logger.warn(
1443
+ "app-state mutation remove index mac not found",
1444
+ {"collection": collection, "missingRemoveCount": missing_remove_count},
1445
+ )
1446
+
1447
+ next_hash = self._crypto.lt_hash_subtract_then_add(
1448
+ base_hash, add_values, remove_values
1449
+ )
1450
+ return {"hash": next_hash.hash, "index_value_map": index_value_map}
1451
+
1452
+ def _group_pending_mutations(
1453
+ self, pending_mutations: Sequence[WaAppStateMutationInput]
1454
+ ) -> dict[str, list[WaAppStateMutationInput]]:
1455
+ grouped: dict[str, list[WaAppStateMutationInput]] = {}
1456
+ for mutation in pending_mutations:
1457
+ items = grouped.get(mutation.collection)
1458
+ if items is not None:
1459
+ items.append(mutation)
1460
+ else:
1461
+ grouped[mutation.collection] = [mutation]
1462
+
1463
+ compacted: dict[str, list[WaAppStateMutationInput]] = {}
1464
+ for collection, items in grouped.items():
1465
+ seen_indexes: set[str] = set()
1466
+ reversed_items: list[WaAppStateMutationInput] = []
1467
+ for index in range(len(items) - 1, -1, -1):
1468
+ mutation = items[index]
1469
+ if mutation.index in seen_indexes:
1470
+ continue
1471
+ seen_indexes.add(mutation.index)
1472
+ reversed_items.append(mutation)
1473
+ compacted[collection] = list(reversed(reversed_items))
1474
+ return compacted
1475
+
1476
+ async def _preload_key_data(self, key_ids: Sequence[bytes]) -> None:
1477
+ if not key_ids:
1478
+ return
1479
+ context = self._require_sync_context()
1480
+ missing_key_ids: list[bytes] = []
1481
+ missing_key_hexes: set[str] = set()
1482
+ for key_id in key_ids:
1483
+ key_hex = bytes_to_hex(key_id)
1484
+ if key_hex in context.keys or key_hex in missing_key_hexes:
1485
+ continue
1486
+ missing_key_hexes.add(key_hex)
1487
+ missing_key_ids.append(key_id)
1488
+ if not missing_key_ids:
1489
+ return
1490
+ loaded = await self._store.get_sync_key_data_batch(missing_key_ids)
1491
+ for index, key_id in enumerate(missing_key_ids):
1492
+ value = loaded[index]
1493
+ context.keys[bytes_to_hex(key_id)] = (
1494
+ bytes(value) if value is not None else None
1495
+ )
1496
+
1497
+ async def _get_key_data(self, key_id: bytes) -> bytes | None:
1498
+ context = self._require_sync_context()
1499
+ key_hex = bytes_to_hex(key_id)
1500
+ if key_hex in context.keys:
1501
+ return context.keys[key_hex]
1502
+ value = await self._store.get_sync_key_data(key_id)
1503
+ context.keys[key_hex] = bytes(value) if value is not None else None
1504
+ return context.keys[key_hex]
1505
+
1506
+ async def _get_collection_state(self, collection: str) -> _SyncCollectionState:
1507
+ context = self._require_sync_context()
1508
+ cached = context.collections.get(collection)
1509
+ if cached is not None:
1510
+ return cached
1511
+ state = await self._store.get_collection_state(collection)
1512
+ fresh = _SyncCollectionState(
1513
+ initialized=state.initialized,
1514
+ version=state.version,
1515
+ hash=bytes(state.hash),
1516
+ index_value_map=dict(state.index_value_map),
1517
+ )
1518
+ context.collections[collection] = fresh
1519
+ return fresh
1520
+
1521
+ def _set_collection_state(
1522
+ self,
1523
+ collection: str,
1524
+ version: int,
1525
+ collection_hash: bytes,
1526
+ index_value_map: Mapping[str, bytes],
1527
+ ) -> None:
1528
+ context = self._require_sync_context()
1529
+ context.collections[collection] = _SyncCollectionState(
1530
+ initialized=True,
1531
+ version=version,
1532
+ hash=bytes(collection_hash),
1533
+ index_value_map=dict(index_value_map),
1534
+ )
1535
+ context.dirty_collections.add(collection)
1536
+
1537
+ async def _persist_collection_updates(self) -> None:
1538
+ context = self._require_sync_context()
1539
+ updates: list[WaAppStateCollectionStateUpdate] = []
1540
+ for collection in context.dirty_collections:
1541
+ state = context.collections.get(collection)
1542
+ if state is None:
1543
+ continue
1544
+ updates.append(
1545
+ WaAppStateCollectionStateUpdate(
1546
+ collection=collection,
1547
+ version=state.version,
1548
+ hash=state.hash,
1549
+ index_value_map=dict(state.index_value_map),
1550
+ )
1551
+ )
1552
+ if not updates:
1553
+ return
1554
+ await self._store.set_collection_states(updates)
1555
+
1556
+ def _require_sync_context(self) -> _SyncContext:
1557
+ if self._sync_context is None:
1558
+ raise ValueError("app-state sync context is not initialized")
1559
+ return self._sync_context