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,82 @@
1
+ """App-state sync constants (mirrors ``src/appstate/constants.ts``).
2
+
3
+ The ``WA_APP_STATE_*`` tables are verbatim copies of
4
+ ``src/protocol/appstate.ts``. They live here (rather than
5
+ ``zapy._protocol``) because the app-state layer is the only consumer and
6
+ the scope of this port forbids touching sibling packages.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ APP_STATE_DERIVED_KEY_LENGTH: int = 160
12
+ APP_STATE_DERIVED_INDEX_KEY_END: int = 32
13
+ APP_STATE_DERIVED_VALUE_ENCRYPTION_KEY_END: int = 64
14
+ APP_STATE_DERIVED_VALUE_MAC_KEY_END: int = 96
15
+ APP_STATE_DERIVED_SNAPSHOT_MAC_KEY_END: int = 128
16
+ APP_STATE_DERIVED_PATCH_MAC_KEY_END: int = 160
17
+
18
+ APP_STATE_VALUE_MAC_LENGTH: int = 32
19
+ APP_STATE_MAC_OCTET_LENGTH: int = 8
20
+ APP_STATE_IV_LENGTH: int = 16
21
+ APP_STATE_LT_HASH_SIZE: int = 128
22
+ APP_STATE_POINT_SIZE: int = 2
23
+
24
+ APP_STATE_EMPTY_LT_HASH: bytes = bytes(APP_STATE_LT_HASH_SIZE)
25
+ APP_STATE_DEFAULT_COLLECTION_VERSION: int = 0
26
+
27
+ # Verbatim ``src/protocol/appstate.ts``.
28
+ WA_APP_STATE_COLLECTIONS: dict[str, str] = {
29
+ "REGULAR": "regular",
30
+ "REGULAR_LOW": "regular_low",
31
+ "REGULAR_HIGH": "regular_high",
32
+ "CRITICAL_BLOCK": "critical_block",
33
+ "CRITICAL_UNBLOCK_LOW": "critical_unblock_low",
34
+ }
35
+
36
+ # Verbatim ``src/protocol/appstate.ts``.
37
+ WA_APP_STATE_COLLECTION_STATES: dict[str, str] = {
38
+ "SUCCESS": "success",
39
+ "SUCCESS_HAS_MORE": "success_has_more",
40
+ "CONFLICT": "conflict",
41
+ "CONFLICT_HAS_MORE": "conflict_has_more",
42
+ "ERROR_RETRY": "error_retry",
43
+ "ERROR_FATAL": "error_fatal",
44
+ "BLOCKED": "blocked",
45
+ }
46
+
47
+ # Verbatim ``src/protocol/appstate.ts``.
48
+ WA_APP_STATE_ERROR_CODES: dict[str, str] = {
49
+ "CONFLICT": "409",
50
+ "BAD_REQUEST": "400",
51
+ "NOT_FOUND": "404",
52
+ "NOT_ALLOWED": "405",
53
+ "NOT_ACCEPTABLE": "406",
54
+ }
55
+
56
+ # Verbatim ``src/protocol/appstate.ts``.
57
+ WA_APP_STATE_SYNC_DATA_TYPE: dict[str, str] = {
58
+ "PATCH": "Patch",
59
+ "SNAPSHOT": "Snapshot",
60
+ "LOCAL": "Local",
61
+ }
62
+
63
+ # Verbatim ``src/protocol/appstate.ts``.
64
+ WA_APP_STATE_KEY_TYPES: dict[str, str] = {
65
+ "MD_APP_STATE": "md-app-state",
66
+ "MD_MSG_HIST": "md-msg-hist",
67
+ }
68
+
69
+ # Verbatim ``src/protocol/appstate.ts`` (``TEXT_ENCODER.encode(...)``).
70
+ WA_APP_STATE_KDF_INFO: dict[str, bytes] = {
71
+ "MUTATION_KEYS": b"WhatsApp Mutation Keys",
72
+ "PATCH_INTEGRITY": b"WhatsApp Patch Integrity",
73
+ }
74
+
75
+ APP_STATE_DEFAULT_COLLECTIONS: tuple[str, ...] = (
76
+ WA_APP_STATE_COLLECTIONS["CRITICAL_UNBLOCK_LOW"],
77
+ WA_APP_STATE_COLLECTIONS["CRITICAL_BLOCK"],
78
+ WA_APP_STATE_COLLECTIONS["REGULAR_LOW"],
79
+ WA_APP_STATE_COLLECTIONS["REGULAR"],
80
+ WA_APP_STATE_COLLECTIONS["REGULAR_HIGH"],
81
+ )
82
+ """Default sync scope (verbatim ``APP_STATE_DEFAULT_COLLECTIONS``)."""
@@ -0,0 +1,17 @@
1
+ """App-state mutation crypto (mirrors ``src/appstate/crypto/``)."""
2
+
3
+ from zapy._appstate.crypto.app_state_crypto import (
4
+ WaAppStateCrypto,
5
+ WaAppStateDecryptedMutation,
6
+ WaAppStateDerivedKeys,
7
+ WaAppStateEncryptedMutation,
8
+ WaAppStateLtHashUpdate,
9
+ )
10
+
11
+ __all__ = [
12
+ "WaAppStateCrypto",
13
+ "WaAppStateDecryptedMutation",
14
+ "WaAppStateDerivedKeys",
15
+ "WaAppStateEncryptedMutation",
16
+ "WaAppStateLtHashUpdate",
17
+ ]
@@ -0,0 +1,401 @@
1
+ """App-state mutation cryptography (mirrors ``WaAppStateCrypto.ts``).
2
+
3
+ # DEVIATION: the oracle's crypto methods are ``async`` only because the
4
+ # sync client ``await``s them; the work itself is synchronous (HKDF/AES/HMAC
5
+ # over in-memory buffers, one CSPRNG draw). They are plain ``def`` here per
6
+ # the porting rules for sync crypto, and the randomness comes from the sync
7
+ # ``random_bytes`` helper (the ``_async`` suffix is dropped).
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from collections.abc import Callable, Mapping, Sequence
13
+ from dataclasses import dataclass
14
+ from typing import Any
15
+
16
+ from zapy._appstate.constants import (
17
+ APP_STATE_DERIVED_INDEX_KEY_END,
18
+ APP_STATE_DERIVED_KEY_LENGTH,
19
+ APP_STATE_DERIVED_PATCH_MAC_KEY_END,
20
+ APP_STATE_DERIVED_SNAPSHOT_MAC_KEY_END,
21
+ APP_STATE_DERIVED_VALUE_ENCRYPTION_KEY_END,
22
+ APP_STATE_DERIVED_VALUE_MAC_KEY_END,
23
+ APP_STATE_EMPTY_LT_HASH,
24
+ APP_STATE_IV_LENGTH,
25
+ APP_STATE_MAC_OCTET_LENGTH,
26
+ APP_STATE_POINT_SIZE,
27
+ APP_STATE_VALUE_MAC_LENGTH,
28
+ WA_APP_STATE_KDF_INFO,
29
+ )
30
+ from zapy._crypto.core.hkdf import hkdf
31
+ from zapy._crypto.core.primitives import (
32
+ aes_cbc_decrypt,
33
+ aes_cbc_encrypt,
34
+ hmac_sha256_sign,
35
+ hmac_sha512_sign,
36
+ )
37
+ from zapy._crypto.core.random import random_bytes
38
+ from zapy._proto import WAProto_pb2
39
+ from zapy._util.bytes import (
40
+ bytes_to_base64,
41
+ concat_bytes,
42
+ encode_utf8_text,
43
+ int_to_bytes,
44
+ uint8_timing_safe_equal,
45
+ )
46
+ from zapy._util.collections import set_bounded_map_entry
47
+ from zapy._util.primitives import normalize_non_negative_integer
48
+
49
+ DEFAULT_DERIVED_KEYS_CACHE_MAX_SIZE: int = 256
50
+
51
+
52
+ @dataclass(frozen=True, slots=True)
53
+ class WaAppStateDerivedKeys:
54
+ """Index/value/snapshot/patch keys derived from one sync key."""
55
+
56
+ index_hmac_key: bytes
57
+ value_encryption_aes_key: bytes
58
+ value_mac_hmac_key: bytes
59
+ snapshot_mac_hmac_key: bytes
60
+ patch_mac_hmac_key: bytes
61
+
62
+
63
+ @dataclass(frozen=True, slots=True)
64
+ class WaAppStateEncryptedMutation:
65
+ """Encrypted mutation: index MAC plus the IV‖ciphertext‖MAC value blob."""
66
+
67
+ index_mac: bytes
68
+ value_blob: bytes
69
+ value_mac: bytes
70
+
71
+
72
+ @dataclass(frozen=True, slots=True)
73
+ class WaAppStateLtHashUpdate:
74
+ """Result of a combined subtract+add LT-hash update."""
75
+
76
+ hash: bytes
77
+ subtract_result: bytes
78
+
79
+
80
+ @dataclass(frozen=True, slots=True)
81
+ class WaAppStateDecryptedMutation:
82
+ """Verified and decrypted mutation with its MACs echoed back."""
83
+
84
+ index: str
85
+ value: Any | None
86
+ version: int
87
+ index_mac: bytes
88
+ value_mac: bytes
89
+
90
+
91
+ def _valid_operation(operation: int) -> bool:
92
+ ops = WAProto_pb2.SyncdMutation
93
+ return operation in (ops.SET, ops.REMOVE)
94
+
95
+
96
+ class WaAppStateCrypto:
97
+ """HKDF key derivation (bounded LRU cache), mutation encrypt/decrypt,
98
+ snapshot/patch MAC generation, and LT-hash collection arithmetic."""
99
+
100
+ def __init__(
101
+ self,
102
+ derived_keys_cache_max_size: int | float | None = None,
103
+ skip_mac_verification: bool = False,
104
+ ) -> None:
105
+ self._derived_keys_cache: dict[str, WaAppStateDerivedKeys] = {}
106
+ self._derived_keys_cache_max_size = normalize_non_negative_integer(
107
+ derived_keys_cache_max_size, DEFAULT_DERIVED_KEYS_CACHE_MAX_SIZE
108
+ )
109
+ self._skip_mac_verification = skip_mac_verification
110
+
111
+ @property
112
+ def is_mac_verification_skipped(self) -> bool:
113
+ """Whether MAC checks are bypassed (test/primary-device path)."""
114
+ return self._skip_mac_verification
115
+
116
+ def clear_cache(self) -> None:
117
+ """Empty the derived-keys LRU cache (e.g. after a session reset)."""
118
+ self._derived_keys_cache.clear()
119
+
120
+ def derive_keys(self, key_data: bytes | bytearray) -> WaAppStateDerivedKeys:
121
+ """Derive the index/value/snapshot/patch keys from a sync key."""
122
+ cache_key = bytes_to_base64(key_data)
123
+ cached = self._derived_keys_cache.get(cache_key)
124
+ if cached is not None:
125
+ self._touch_derived_keys_cache_entry(cache_key, cached)
126
+ return cached
127
+ derived = hkdf(
128
+ bytes(key_data),
129
+ None,
130
+ WA_APP_STATE_KDF_INFO["MUTATION_KEYS"],
131
+ APP_STATE_DERIVED_KEY_LENGTH,
132
+ )
133
+ index_end = APP_STATE_DERIVED_INDEX_KEY_END
134
+ value_enc_end = APP_STATE_DERIVED_VALUE_ENCRYPTION_KEY_END
135
+ value_mac_end = APP_STATE_DERIVED_VALUE_MAC_KEY_END
136
+ snapshot_end = APP_STATE_DERIVED_SNAPSHOT_MAC_KEY_END
137
+ patch_end = APP_STATE_DERIVED_PATCH_MAC_KEY_END
138
+ keys = WaAppStateDerivedKeys(
139
+ index_hmac_key=derived[:index_end],
140
+ value_encryption_aes_key=derived[index_end:value_enc_end],
141
+ value_mac_hmac_key=derived[value_enc_end:value_mac_end],
142
+ snapshot_mac_hmac_key=derived[value_mac_end:snapshot_end],
143
+ patch_mac_hmac_key=derived[snapshot_end:patch_end],
144
+ )
145
+ self._touch_derived_keys_cache_entry(cache_key, keys)
146
+ return keys
147
+
148
+ def generate_index_mac(
149
+ self, index_hmac_key: bytes | bytearray, index_bytes: bytes | bytearray
150
+ ) -> bytes:
151
+ """Compute the HMAC-SHA-256 index MAC over ``index_bytes``."""
152
+ return hmac_sha256_sign(index_hmac_key, bytes(index_bytes))
153
+
154
+ def encrypt_mutation(
155
+ self,
156
+ *,
157
+ operation: int,
158
+ key_id: bytes | bytearray,
159
+ key_data: bytes | bytearray,
160
+ index: str,
161
+ value: Any | None,
162
+ version: int,
163
+ iv: bytes | bytearray | None = None,
164
+ ) -> WaAppStateEncryptedMutation:
165
+ """Encrypt one mutation value with AES-CBC plus an HMAC value-MAC."""
166
+ derived_keys = self.derive_keys(key_data)
167
+ index_bytes = encode_utf8_text(index)
168
+ if value is None:
169
+ encoded = WAProto_pb2.SyncActionData(
170
+ index=index_bytes, padding=b"", version=version
171
+ ).SerializeToString()
172
+ elif isinstance(value, Mapping):
173
+ encoded = WAProto_pb2.SyncActionData(
174
+ index=index_bytes, value=dict(value), padding=b"", version=version
175
+ ).SerializeToString()
176
+ else:
177
+ action = WAProto_pb2.SyncActionData(index=index_bytes, padding=b"")
178
+ action.value.CopyFrom(value)
179
+ action.version = version
180
+ encoded = action.SerializeToString()
181
+
182
+ iv_bytes = bytes(random_bytes(APP_STATE_IV_LENGTH)) if iv is None else bytes(iv)
183
+ if len(iv_bytes) != APP_STATE_IV_LENGTH:
184
+ raise ValueError(f"invalid IV length {len(iv_bytes)}")
185
+
186
+ index_mac = self.generate_index_mac(derived_keys.index_hmac_key, index_bytes)
187
+ cipher_text = aes_cbc_encrypt(
188
+ derived_keys.value_encryption_aes_key, iv_bytes, encoded
189
+ )
190
+ associated_data = self._generate_associated_data(operation, key_id)
191
+ value_mac = self._generate_value_mac(
192
+ derived_keys.value_mac_hmac_key, associated_data, iv_bytes, cipher_text
193
+ )
194
+ return WaAppStateEncryptedMutation(
195
+ index_mac=index_mac,
196
+ value_blob=concat_bytes([iv_bytes, cipher_text, value_mac]),
197
+ value_mac=value_mac,
198
+ )
199
+
200
+ def decrypt_mutation(
201
+ self,
202
+ *,
203
+ operation: int,
204
+ key_id: bytes | bytearray,
205
+ key_data: bytes | bytearray,
206
+ index_mac: bytes | bytearray,
207
+ value_blob: bytes | bytearray,
208
+ ) -> WaAppStateDecryptedMutation:
209
+ """Verify and decrypt one app-state mutation."""
210
+ blob = bytes(value_blob)
211
+ if len(blob) < APP_STATE_IV_LENGTH + APP_STATE_VALUE_MAC_LENGTH:
212
+ raise ValueError("invalid mutation value blob")
213
+
214
+ derived_keys = self.derive_keys(key_data)
215
+ iv = blob[:APP_STATE_IV_LENGTH]
216
+ mac = blob[len(blob) - APP_STATE_VALUE_MAC_LENGTH :]
217
+ cipher_text = blob[APP_STATE_IV_LENGTH : len(blob) - APP_STATE_VALUE_MAC_LENGTH]
218
+
219
+ if not self._skip_mac_verification:
220
+ associated_data = self._generate_associated_data(operation, key_id)
221
+ expected_mac = self._generate_value_mac(
222
+ derived_keys.value_mac_hmac_key, associated_data, iv, cipher_text
223
+ )
224
+ if not uint8_timing_safe_equal(mac, expected_mac):
225
+ raise ValueError("mutation value MAC mismatch")
226
+
227
+ plaintext = aes_cbc_decrypt(
228
+ derived_keys.value_encryption_aes_key, iv, cipher_text
229
+ )
230
+ sync_action_data = WAProto_pb2.SyncActionData.FromString(plaintext)
231
+ if not sync_action_data.index:
232
+ raise ValueError("missing sync action index")
233
+ if not sync_action_data.HasField("version"):
234
+ raise ValueError("missing sync action version")
235
+
236
+ if not self._skip_mac_verification:
237
+ generated_index_mac = self.generate_index_mac(
238
+ derived_keys.index_hmac_key, bytes(sync_action_data.index)
239
+ )
240
+ if not uint8_timing_safe_equal(generated_index_mac, bytes(index_mac)):
241
+ raise ValueError("mutation index MAC mismatch")
242
+
243
+ has_value = sync_action_data.HasField("value")
244
+ value_message = sync_action_data.value if has_value else None
245
+ return WaAppStateDecryptedMutation(
246
+ index=bytes(sync_action_data.index).decode("utf-8", errors="replace"),
247
+ value=value_message,
248
+ version=sync_action_data.version,
249
+ index_mac=bytes(index_mac),
250
+ value_mac=mac,
251
+ )
252
+
253
+ def generate_snapshot_mac(
254
+ self,
255
+ key_data: bytes | bytearray,
256
+ lt_hash: bytes | bytearray,
257
+ version: int,
258
+ collection_name: str,
259
+ ) -> bytes:
260
+ """Generate the HMAC-SHA-256 snapshot MAC over LT-hash‖version‖name."""
261
+ derived_keys = self.derive_keys(key_data)
262
+ return hmac_sha256_sign(
263
+ derived_keys.snapshot_mac_hmac_key,
264
+ [
265
+ bytes(lt_hash),
266
+ int_to_bytes(8, version),
267
+ encode_utf8_text(collection_name),
268
+ ],
269
+ )
270
+
271
+ def generate_patch_mac(
272
+ self,
273
+ key_data: bytes | bytearray,
274
+ snapshot_mac: bytes | bytearray,
275
+ value_macs: Sequence[bytes | bytearray],
276
+ version: int,
277
+ collection_name: str,
278
+ ) -> bytes:
279
+ """Generate the HMAC-SHA-256 patch MAC binding mutations to a version."""
280
+ derived_keys = self.derive_keys(key_data)
281
+ return hmac_sha256_sign(
282
+ derived_keys.patch_mac_hmac_key,
283
+ [
284
+ bytes(snapshot_mac),
285
+ *(bytes(item) for item in value_macs),
286
+ int_to_bytes(8, version),
287
+ encode_utf8_text(collection_name),
288
+ ],
289
+ )
290
+
291
+ def lt_hash_add(
292
+ self, base: bytes | bytearray, add_values: Sequence[bytes | bytearray]
293
+ ) -> bytes:
294
+ """Add value MACs into the running LT-hash digest for a collection."""
295
+ return self._lt_hash_apply(base, add_values, lambda left, right: left + right)
296
+
297
+ def lt_hash_subtract(
298
+ self, base: bytes | bytearray, remove_values: Sequence[bytes | bytearray]
299
+ ) -> bytes:
300
+ """Remove value MACs from the running LT-hash digest."""
301
+ return self._lt_hash_apply(
302
+ base, remove_values, lambda left, right: left - right
303
+ )
304
+
305
+ def lt_hash_subtract_then_add(
306
+ self,
307
+ base: bytes | bytearray,
308
+ add_values: Sequence[bytes | bytearray],
309
+ remove_values: Sequence[bytes | bytearray],
310
+ ) -> WaAppStateLtHashUpdate:
311
+ """Combined subtract+add LT-hash update used on in-place value changes."""
312
+ subtract_result = self.lt_hash_subtract(base, remove_values)
313
+ result_hash = self.lt_hash_add(subtract_result, add_values)
314
+ return WaAppStateLtHashUpdate(hash=result_hash, subtract_result=subtract_result)
315
+
316
+ def _lt_hash_apply(
317
+ self,
318
+ base: bytes | bytearray,
319
+ values: Sequence[bytes | bytearray],
320
+ combine: Callable[[int, int], int],
321
+ ) -> bytes:
322
+ base_bytes = bytes(base)
323
+ if not values:
324
+ return base_bytes
325
+ expanded = [
326
+ hkdf(
327
+ bytes(value),
328
+ None,
329
+ WA_APP_STATE_KDF_INFO["PATCH_INTEGRITY"],
330
+ len(APP_STATE_EMPTY_LT_HASH),
331
+ )
332
+ for value in values
333
+ ]
334
+ out = bytearray(len(base_bytes))
335
+ self._pointwise_with_overflow(base_bytes, expanded[0], combine, out)
336
+ for index in range(1, len(expanded)):
337
+ current = bytes(out)
338
+ self._pointwise_with_overflow(current, expanded[index], combine, out)
339
+ return bytes(out)
340
+
341
+ def _pointwise_with_overflow(
342
+ self,
343
+ left: bytes | bytearray,
344
+ right: bytes | bytearray,
345
+ combine: Callable[[int, int], int],
346
+ out: bytearray | None = None,
347
+ ) -> bytes:
348
+ left_bytes = bytes(left)
349
+ right_bytes = bytes(right)
350
+ if len(left_bytes) != len(right_bytes):
351
+ raise ValueError("lt hash input length mismatch")
352
+ if len(left_bytes) % APP_STATE_POINT_SIZE != 0:
353
+ raise ValueError("lt hash input alignment mismatch")
354
+ target = out if out is not None else bytearray(len(left_bytes))
355
+ if len(target) != len(left_bytes):
356
+ raise ValueError("lt hash output length mismatch")
357
+ for offset in range(0, len(left_bytes), APP_STATE_POINT_SIZE):
358
+ value = combine(
359
+ left_bytes[offset] | (left_bytes[offset + 1] << 8),
360
+ right_bytes[offset] | (right_bytes[offset + 1] << 8),
361
+ )
362
+ wrapped = value & 0xFFFF
363
+ target[offset] = wrapped & 0xFF
364
+ target[offset + 1] = (wrapped >> 8) & 0xFF
365
+ return bytes(target)
366
+
367
+ def _generate_associated_data(
368
+ self, operation: int, key_id: bytes | bytearray
369
+ ) -> bytes:
370
+ if not _valid_operation(operation):
371
+ raise ValueError(f"unsupported syncd operation {operation}")
372
+ key_bytes = bytes(key_id)
373
+ out = bytearray(1 + len(key_bytes))
374
+ out[0] = operation + 1
375
+ out[1:] = key_bytes
376
+ return bytes(out)
377
+
378
+ def _generate_value_mac(
379
+ self,
380
+ value_mac_hmac_key: bytes | bytearray,
381
+ associated_data: bytes | bytearray,
382
+ iv: bytes | bytearray,
383
+ cipher_text: bytes | bytearray,
384
+ ) -> bytes:
385
+ associated = bytes(associated_data)
386
+ octet_length = bytearray(APP_STATE_MAC_OCTET_LENGTH)
387
+ octet_length[len(octet_length) - 1] = len(associated) & 0xFF
388
+ full = hmac_sha512_sign(
389
+ value_mac_hmac_key,
390
+ [associated, bytes(iv), bytes(cipher_text), bytes(octet_length)],
391
+ )
392
+ return full[:APP_STATE_VALUE_MAC_LENGTH]
393
+
394
+ def _touch_derived_keys_cache_entry(
395
+ self, cache_key: str, keys: WaAppStateDerivedKeys
396
+ ) -> None:
397
+ if self._derived_keys_cache_max_size <= 0:
398
+ return
399
+ set_bounded_map_entry(
400
+ self._derived_keys_cache, cache_key, keys, self._derived_keys_cache_max_size
401
+ )
@@ -0,0 +1,23 @@
1
+ """App-state sync parsers (mirrors ``src/appstate/parsers/``)."""
2
+
3
+ from zapy._appstate.parsers.encoding import (
4
+ decode_app_state_collections,
5
+ decode_app_state_fingerprint,
6
+ decode_app_state_sync_keys,
7
+ encode_app_state_fingerprint,
8
+ )
9
+ from zapy._appstate.parsers.response_parser import (
10
+ CollectionResponsePayload,
11
+ parse_collection_state,
12
+ parse_sync_response,
13
+ )
14
+
15
+ __all__ = [
16
+ "CollectionResponsePayload",
17
+ "decode_app_state_collections",
18
+ "decode_app_state_fingerprint",
19
+ "decode_app_state_sync_keys",
20
+ "encode_app_state_fingerprint",
21
+ "parse_collection_state",
22
+ "parse_sync_response",
23
+ ]
@@ -0,0 +1,157 @@
1
+ """App-state store row codecs (mirrors ``parsers/encoding.ts``).
2
+
3
+ The ``_as_*`` coercion helpers below are local mirrors of ``asNumber`` /
4
+ ``asBytes`` / ``asString`` / ``asOptionalBytes`` from
5
+ ``src/util/coercion.ts`` with the IDENTICAL error messages; they live here
6
+ (rather than ``zapy._util.coercion``) because that module does not expose
7
+ them yet. Keep the messages in sync if they are ever unified.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import math
13
+ from collections.abc import Mapping
14
+ from typing import Any
15
+
16
+ from collections.abc import Sequence
17
+
18
+ from zapy._appstate.types import (
19
+ WaAppStateCollectionVersion,
20
+ WaAppStateSyncKey,
21
+ )
22
+ from zapy._proto import WAProto_pb2
23
+ from zapy._util.primitives import to_error
24
+
25
+ StoreRow = Mapping[str, Any]
26
+ """One SQL result row (mirrors the ``StoreRow`` alias)."""
27
+
28
+ _MAX_SAFE_INTEGER = 2**53 - 1
29
+
30
+
31
+ def _row_get(row: StoreRow, key: str) -> Any:
32
+ try:
33
+ return row[key]
34
+ except (KeyError, IndexError, TypeError):
35
+ return None
36
+
37
+
38
+ def _as_number(value: object, field: str) -> int:
39
+ """Coerce to a safe integer or throw ``ValueError`` like TS ``asNumber``."""
40
+ if isinstance(value, bool):
41
+ raise ValueError(f"invalid number value for {field}")
42
+ if isinstance(value, int):
43
+ numeric = value
44
+ elif isinstance(value, float):
45
+ if not math.isfinite(value) or int(value) != value:
46
+ raise ValueError(f"invalid {field}: {value}")
47
+ numeric = int(value)
48
+ else:
49
+ raise ValueError(f"invalid number value for {field}")
50
+ if abs(numeric) > _MAX_SAFE_INTEGER:
51
+ raise ValueError(f"invalid {field}: {value}")
52
+ return numeric
53
+
54
+
55
+ def _as_string(value: object, field: str) -> str:
56
+ """Require ``str`` or throw ``ValueError`` like TS ``asString``."""
57
+ if not isinstance(value, str):
58
+ raise ValueError(f"invalid string value for {field}")
59
+ return value
60
+
61
+
62
+ def _as_bytes(value: object, field: str) -> bytes:
63
+ """Coerce bytes-like to ``bytes`` or throw like TS ``asBytes``."""
64
+ if isinstance(value, (bytes, bytearray, memoryview)):
65
+ return bytes(value)
66
+ raise ValueError(f"invalid bytes value for {field}")
67
+
68
+
69
+ def _as_optional_bytes(value: object, field: str) -> bytes | None:
70
+ """``None`` stays ``None``; otherwise :func:`_as_bytes`."""
71
+ if value is None:
72
+ return None
73
+ return _as_bytes(value, field)
74
+
75
+
76
+ def encode_app_state_fingerprint(fingerprint: Any | None) -> bytes | None:
77
+ """Serialize a sync key fingerprint to protobuf bytes, ``None`` when absent."""
78
+ if fingerprint is None:
79
+ return None
80
+ if isinstance(fingerprint, Mapping):
81
+ message = WAProto_pb2.Message.AppStateSyncKeyFingerprint(**dict(fingerprint))
82
+ else:
83
+ message = WAProto_pb2.Message.AppStateSyncKeyFingerprint()
84
+ message.CopyFrom(fingerprint)
85
+ return bytes(message.SerializeToString())
86
+
87
+
88
+ def decode_app_state_fingerprint(raw: Any) -> Any | None:
89
+ """Inverse of :func:`encode_app_state_fingerprint`; throws on malformed input."""
90
+ raw_bytes = _as_optional_bytes(raw, "appstate_sync_keys.fingerprint")
91
+ if raw_bytes is None:
92
+ return None
93
+ try:
94
+ return WAProto_pb2.Message.AppStateSyncKeyFingerprint.FromString(raw_bytes)
95
+ except Exception as error:
96
+ raise ValueError(
97
+ "invalid appstate_sync_keys.fingerprint protobuf payload: "
98
+ f"{to_error(error)}"
99
+ ) from None
100
+
101
+
102
+ def decode_app_state_sync_keys(rows: Sequence[StoreRow]) -> list[WaAppStateSyncKey]:
103
+ """Decode app-state sync-key SQL rows into :class:`WaAppStateSyncKey` records."""
104
+ decoded: list[WaAppStateSyncKey] = []
105
+ for row in rows:
106
+ decoded.append(
107
+ WaAppStateSyncKey(
108
+ key_id=_as_bytes(_row_get(row, "key_id"), "appstate_sync_keys.key_id"),
109
+ key_data=_as_bytes(
110
+ _row_get(row, "key_data"), "appstate_sync_keys.key_data"
111
+ ),
112
+ timestamp=_as_number(
113
+ _row_get(row, "timestamp"), "appstate_sync_keys.timestamp"
114
+ ),
115
+ fingerprint=decode_app_state_fingerprint(_row_get(row, "fingerprint")),
116
+ )
117
+ )
118
+ return decoded
119
+
120
+
121
+ def decode_app_state_collections(
122
+ version_rows: Sequence[StoreRow],
123
+ value_rows: Sequence[StoreRow],
124
+ ) -> dict[str, WaAppStateCollectionVersion]:
125
+ """Join collection-version and index-value SQL rows into the ``collections``
126
+ shape used by the in-memory app-state store."""
127
+ value_map_by_collection: dict[str, dict[str, bytes]] = {}
128
+ for row in value_rows:
129
+ collection = _as_string(
130
+ _row_get(row, "collection"), "appstate_collection_index_values.collection"
131
+ )
132
+ by_index = value_map_by_collection.get(collection)
133
+ if by_index is None:
134
+ by_index = {}
135
+ value_map_by_collection[collection] = by_index
136
+ by_index[
137
+ _as_string(
138
+ _row_get(row, "index_mac_hex"),
139
+ "appstate_collection_index_values.index_mac_hex",
140
+ )
141
+ ] = _as_bytes(
142
+ _row_get(row, "value_mac"), "appstate_collection_index_values.value_mac"
143
+ )
144
+
145
+ collections: dict[str, WaAppStateCollectionVersion] = {}
146
+ for row in version_rows:
147
+ collection = _as_string(
148
+ _row_get(row, "collection"), "appstate_collection_versions.collection"
149
+ )
150
+ collections[collection] = WaAppStateCollectionVersion(
151
+ version=_as_number(
152
+ _row_get(row, "version"), "appstate_collection_versions.version"
153
+ ),
154
+ hash=_as_bytes(_row_get(row, "hash"), "appstate_collection_versions.hash"),
155
+ index_value_map=value_map_by_collection.get(collection, {}),
156
+ )
157
+ return collections