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,381 @@
1
+ """Double-ratchet encrypt/decrypt (mirrors ``src/signal/session/SignalRatchet.ts``).
2
+
3
+ Pure key derivation plus AES-CBC payload crypto; synchronous throughout
4
+ (the oracle is only async for its crypto thread pool). Errors match the
5
+ oracle strings exactly.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from collections.abc import Callable
11
+ from dataclasses import dataclass, replace
12
+
13
+ from zapy._crypto.core.hkdf import hkdf
14
+ from zapy._crypto.core.keys import prepend_version, to_serialized_pub_key
15
+ from zapy._crypto.core.primitives import (
16
+ aes_cbc_decrypt,
17
+ aes_cbc_encrypt,
18
+ hmac_sha256_sign,
19
+ )
20
+ from zapy._proto import WAProto_pb2
21
+ from zapy._signal.session import (
22
+ CHAIN_KEY_LABEL,
23
+ FUTURE_MESSAGES_MAX,
24
+ MAX_TRACKED_RECV_CHAINS,
25
+ MAX_UNUSED_KEYS,
26
+ MESSAGE_KEY_LABEL,
27
+ SIGNAL_MAC_SIZE,
28
+ SIGNAL_VERSION,
29
+ WHISPER_MESSAGE_KEYS_INFO,
30
+ ParsedPreKeySignalMessage,
31
+ ParsedSignalMessage,
32
+ SignalMessageKey,
33
+ SignalRecvChain,
34
+ SignalSessionRecord,
35
+ )
36
+ from zapy._signal.session.encoding import (
37
+ decode_signal_message_key,
38
+ decode_signal_recv_chain,
39
+ decode_signal_session_snapshot,
40
+ encode_signal_recv_chain,
41
+ encode_signal_session_snapshot,
42
+ )
43
+ from zapy._signal.session.session import (
44
+ calculate_ratchet,
45
+ generate_serialized_key_pair,
46
+ snapshot_to_record,
47
+ )
48
+ from zapy._util.bytes import uint8_equal, uint8_timing_safe_equal
49
+
50
+
51
+ @dataclass(frozen=True, slots=True)
52
+ class DerivedMsgKey:
53
+ """Next chain key plus the message key derived at one index."""
54
+
55
+ next_chain_key: bytes
56
+ message_key: SignalMessageKey
57
+
58
+
59
+ @dataclass(frozen=True, slots=True)
60
+ class SelectedMessageKey:
61
+ """The key for a counter plus the chain advanced past it."""
62
+
63
+ message_key: SignalMessageKey
64
+ updated_chain: SignalRecvChain
65
+
66
+
67
+ @dataclass(frozen=True, slots=True)
68
+ class EncryptedMessage:
69
+ """Ratchet ciphertext plus its envelope kind (``msg`` or ``pkmsg``)."""
70
+
71
+ type: str
72
+ ciphertext: bytes
73
+
74
+
75
+ @dataclass(frozen=True, slots=True)
76
+ class NewSessionInfo:
77
+ """Session-rotation facts produced when a decrypt creates a session."""
78
+
79
+ new_identity: bytes | None
80
+ base_session: SignalSessionRecord
81
+ used_pre_key: int | None
82
+
83
+
84
+ @dataclass(frozen=True, slots=True)
85
+ class DecryptOutcome:
86
+ """Updated session, plaintext, and optional rotation facts."""
87
+
88
+ updated_session: SignalSessionRecord
89
+ plaintext: bytes
90
+ new_session_info: NewSessionInfo | None
91
+
92
+
93
+ def _split_msg_key(index: int, key_bytes: bytes) -> SignalMessageKey:
94
+ if len(key_bytes) < 80:
95
+ raise ValueError("invalid message key length")
96
+ return SignalMessageKey(
97
+ index=index,
98
+ cipher_key=key_bytes[0:32],
99
+ mac_key=key_bytes[32:64],
100
+ iv=key_bytes[64:80],
101
+ )
102
+
103
+
104
+ def _derive_msg_key_from_chain_key(
105
+ index: int, chain_key: bytes | bytearray
106
+ ) -> DerivedMsgKey:
107
+ next_chain_raw = hmac_sha256_sign(bytes(chain_key), CHAIN_KEY_LABEL)
108
+ message_input_key = hmac_sha256_sign(bytes(chain_key), MESSAGE_KEY_LABEL)
109
+ expanded = hkdf(message_input_key, None, WHISPER_MESSAGE_KEYS_INFO, 80)
110
+ return DerivedMsgKey(
111
+ next_chain_key=next_chain_raw[0:32],
112
+ message_key=_split_msg_key(index, expanded),
113
+ )
114
+
115
+
116
+ def derive_msg_key(index: int, chain_key: bytes | bytearray) -> DerivedMsgKey:
117
+ """Derive the message key at ``index`` and the next chain key."""
118
+ return _derive_msg_key_from_chain_key(index, chain_key)
119
+
120
+
121
+ def select_message_key(
122
+ chain: SignalRecvChain, target_counter: int
123
+ ) -> SelectedMessageKey:
124
+ """Advance ``chain`` to ``target_counter``, stashing skipped keys."""
125
+ delta = target_counter - chain.next_msg_index
126
+ if delta > FUTURE_MESSAGES_MAX:
127
+ raise ValueError("message too far in future")
128
+ unused = chain.unused_msg_keys
129
+ if delta < 0:
130
+ found = next(
131
+ (
132
+ position
133
+ for position, entry in enumerate(unused)
134
+ if entry.HasField("index") and entry.index == target_counter
135
+ ),
136
+ None,
137
+ )
138
+ if found is None:
139
+ raise ValueError("duplicate message")
140
+ message_key = decode_signal_message_key(
141
+ unused[found], f"unusedMsgKeys[{found}]"
142
+ )
143
+ remaining = tuple(entry for i, entry in enumerate(unused) if i != found)
144
+ return SelectedMessageKey(
145
+ message_key=message_key,
146
+ updated_chain=SignalRecvChain(
147
+ ratchet_pub_key=chain.ratchet_pub_key,
148
+ next_msg_index=chain.next_msg_index,
149
+ chain_key=chain.chain_key,
150
+ unused_msg_keys=remaining,
151
+ ),
152
+ )
153
+ chain_key = chain.chain_key
154
+ first = _derive_msg_key_from_chain_key(chain.next_msg_index, chain_key)
155
+ current_message_key = first.message_key
156
+ chain_key = first.next_chain_key
157
+ if delta == 0:
158
+ return SelectedMessageKey(
159
+ message_key=current_message_key,
160
+ updated_chain=SignalRecvChain(
161
+ ratchet_pub_key=chain.ratchet_pub_key,
162
+ next_msg_index=target_counter + 1,
163
+ chain_key=chain_key,
164
+ unused_msg_keys=unused,
165
+ ),
166
+ )
167
+ next_unused = list(unused)
168
+ overflow = delta + len(unused) - MAX_UNUSED_KEYS
169
+ if overflow > 0:
170
+ del next_unused[0:overflow]
171
+ overflow -= len(unused)
172
+ for counter in range(chain.next_msg_index + 1, target_counter + 1):
173
+ if overflow > 0:
174
+ overflow -= 1
175
+ else:
176
+ stashed = WAProto_pb2.SessionStructure.Chain.MessageKey()
177
+ stashed.index = current_message_key.index
178
+ stashed.cipherKey = current_message_key.cipher_key
179
+ stashed.macKey = current_message_key.mac_key
180
+ stashed.iv = current_message_key.iv
181
+ next_unused.append(stashed)
182
+ derived = _derive_msg_key_from_chain_key(counter, chain_key)
183
+ current_message_key = derived.message_key
184
+ chain_key = derived.next_chain_key
185
+ return SelectedMessageKey(
186
+ message_key=current_message_key,
187
+ updated_chain=SignalRecvChain(
188
+ ratchet_pub_key=chain.ratchet_pub_key,
189
+ next_msg_index=target_counter + 1,
190
+ chain_key=chain_key,
191
+ unused_msg_keys=tuple(next_unused),
192
+ ),
193
+ )
194
+
195
+
196
+ def encrypt_msg(
197
+ session: SignalSessionRecord, plaintext: bytes | bytearray
198
+ ) -> tuple[SignalSessionRecord, EncryptedMessage]:
199
+ """Encrypt one message, advancing the send chain (``pkmsg`` when fresh)."""
200
+ derived = derive_msg_key(
201
+ session.send_chain.next_msg_index, session.send_chain.chain_key
202
+ )
203
+ message_key = derived.message_key
204
+ ciphertext = aes_cbc_encrypt(
205
+ message_key.cipher_key, message_key.iv, bytes(plaintext)
206
+ )
207
+ signal_payload = WAProto_pb2.SignalMessage()
208
+ signal_payload.ratchetKey = session.send_chain.ratchet_key.pub_key
209
+ signal_payload.counter = message_key.index
210
+ signal_payload.previousCounter = session.prev_send_chain_highest_index
211
+ signal_payload.ciphertext = ciphertext
212
+ versioned = prepend_version(signal_payload.SerializeToString(), SIGNAL_VERSION)
213
+ mac = hmac_sha256_sign(
214
+ message_key.mac_key,
215
+ [session.local.pub_key, session.remote.pub_key, versioned],
216
+ )
217
+ signal_message = versioned + mac[0:SIGNAL_MAC_SIZE]
218
+ kind = "msg"
219
+ output = signal_message
220
+ if session.initial_exchange_info is not None:
221
+ pre_key_payload = WAProto_pb2.PreKeySignalMessage()
222
+ pre_key_payload.registrationId = session.local.reg_id
223
+ if session.initial_exchange_info.remote_one_time_id is not None:
224
+ pre_key_payload.preKeyId = session.initial_exchange_info.remote_one_time_id
225
+ pre_key_payload.signedPreKeyId = session.initial_exchange_info.remote_signed_id
226
+ pre_key_payload.baseKey = session.initial_exchange_info.local_one_time_pub_key
227
+ pre_key_payload.identityKey = session.local.pub_key
228
+ pre_key_payload.message = signal_message
229
+ kind = "pkmsg"
230
+ output = prepend_version(pre_key_payload.SerializeToString(), SIGNAL_VERSION)
231
+ updated = replace(
232
+ session,
233
+ send_chain=replace(
234
+ session.send_chain,
235
+ next_msg_index=message_key.index + 1,
236
+ chain_key=derived.next_chain_key,
237
+ ),
238
+ )
239
+ return updated, EncryptedMessage(type=kind, ciphertext=output)
240
+
241
+
242
+ def decrypt_msg(
243
+ session: SignalSessionRecord | None,
244
+ parsed: ParsedSignalMessage,
245
+ on_prev_session_decrypt_error: Callable[[Exception, int], None] | None = None,
246
+ ) -> DecryptOutcome:
247
+ """Decrypt with the current session, falling back to previous sessions."""
248
+ if session is None:
249
+ raise ValueError("signal session not found")
250
+ try:
251
+ updated_session, plaintext = decrypt_msg_from_session(session, parsed)
252
+ return DecryptOutcome(
253
+ updated_session=updated_session,
254
+ plaintext=plaintext,
255
+ new_session_info=None,
256
+ )
257
+ except Exception:
258
+ for index, raw_prev in enumerate(session.prev_sessions):
259
+ try:
260
+ decoded_prev = decode_signal_session_snapshot(
261
+ raw_prev, f"prevSessions[{index}]"
262
+ )
263
+ prev_session = snapshot_to_record(decoded_prev)
264
+ updated_prev, plaintext = decrypt_msg_from_session(prev_session, parsed)
265
+ merged_prev_sessions: tuple[WAProto_pb2.SessionStructure, ...] = (
266
+ encode_signal_session_snapshot(session),
267
+ *(
268
+ prev
269
+ for i, prev in enumerate(session.prev_sessions)
270
+ if i != index
271
+ ),
272
+ )
273
+ updated_session = replace(
274
+ updated_prev, prev_sessions=merged_prev_sessions
275
+ )
276
+ return DecryptOutcome(
277
+ updated_session=updated_session,
278
+ plaintext=plaintext,
279
+ new_session_info=NewSessionInfo(
280
+ new_identity=None
281
+ if uint8_equal(
282
+ updated_session.remote.pub_key, session.remote.pub_key
283
+ )
284
+ else updated_session.remote.pub_key,
285
+ base_session=prev_session,
286
+ used_pre_key=None,
287
+ ),
288
+ )
289
+ except Exception as prev_error:
290
+ if on_prev_session_decrypt_error is not None:
291
+ on_prev_session_decrypt_error(prev_error, index)
292
+ continue
293
+ raise
294
+
295
+
296
+ def decrypt_msg_from_session(
297
+ session: SignalSessionRecord,
298
+ message: ParsedSignalMessage | ParsedPreKeySignalMessage,
299
+ ) -> tuple[SignalSessionRecord, bytes]:
300
+ """Decrypt one envelope against a single session, ratcheting as needed."""
301
+ ratchet_pub_key = to_serialized_pub_key(message.ratchet_pub_key)
302
+ recv_chain_index = next(
303
+ (
304
+ index
305
+ for index, key in enumerate(session.recv_chains)
306
+ if key.senderRatchetKey
307
+ and uint8_equal(bytes(key.senderRatchetKey), ratchet_pub_key)
308
+ ),
309
+ -1,
310
+ )
311
+ if recv_chain_index == -1:
312
+ recv_ratchet = calculate_ratchet(
313
+ session.root_key, session.send_chain.ratchet_key, ratchet_pub_key
314
+ )
315
+ selected = select_message_key(
316
+ SignalRecvChain(
317
+ ratchet_pub_key=ratchet_pub_key,
318
+ next_msg_index=0,
319
+ chain_key=recv_ratchet.chain_key,
320
+ unused_msg_keys=(),
321
+ ),
322
+ message.counter,
323
+ )
324
+ new_send_ratchet = generate_serialized_key_pair()
325
+ send_ratchet = calculate_ratchet(
326
+ recv_ratchet.root_key, new_send_ratchet, ratchet_pub_key
327
+ )
328
+ next_recv_chains = list(session.recv_chains[-MAX_TRACKED_RECV_CHAINS:])
329
+ next_recv_chains.append(encode_signal_recv_chain(selected.updated_chain))
330
+ updated_session = replace(
331
+ session,
332
+ root_key=send_ratchet.root_key,
333
+ recv_chains=tuple(next_recv_chains),
334
+ send_chain=replace(
335
+ session.send_chain,
336
+ ratchet_key=new_send_ratchet,
337
+ next_msg_index=0,
338
+ chain_key=send_ratchet.chain_key,
339
+ ),
340
+ initial_exchange_info=None,
341
+ prev_send_chain_highest_index=max(session.send_chain.next_msg_index - 1, 0),
342
+ )
343
+ else:
344
+ decoded = decode_signal_recv_chain(
345
+ session.recv_chains[recv_chain_index], f"recvChains[{recv_chain_index}]"
346
+ )
347
+ selected = select_message_key(decoded, message.counter)
348
+ next_recv_chains = list(session.recv_chains)
349
+ next_recv_chains[recv_chain_index] = encode_signal_recv_chain(
350
+ selected.updated_chain
351
+ )
352
+ updated_session = replace(session, recv_chains=tuple(next_recv_chains))
353
+ selected_message_key = selected.message_key
354
+ payload_without_mac = message.version_content_mac[:-SIGNAL_MAC_SIZE]
355
+ expected_mac = hmac_sha256_sign(
356
+ selected_message_key.mac_key,
357
+ [session.remote.pub_key, session.local.pub_key, payload_without_mac],
358
+ )
359
+ received_mac = message.version_content_mac[-SIGNAL_MAC_SIZE:]
360
+ if not uint8_timing_safe_equal(expected_mac[0:SIGNAL_MAC_SIZE], received_mac):
361
+ raise ValueError("invalid message mac")
362
+ plaintext = aes_cbc_decrypt(
363
+ selected_message_key.cipher_key,
364
+ selected_message_key.iv,
365
+ message.ciphertext,
366
+ )
367
+ return updated_session, plaintext
368
+
369
+
370
+ __all__ = [
371
+ "DecryptOutcome",
372
+ "DerivedMsgKey",
373
+ "EncryptedMessage",
374
+ "NewSessionInfo",
375
+ "SelectedMessageKey",
376
+ "decrypt_msg",
377
+ "decrypt_msg_from_session",
378
+ "derive_msg_key",
379
+ "encrypt_msg",
380
+ "select_message_key",
381
+ ]