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.
- shellzapy-0.1.0.dist-info/METADATA +112 -0
- shellzapy-0.1.0.dist-info/RECORD +345 -0
- shellzapy-0.1.0.dist-info/WHEEL +4 -0
- shellzapy-0.1.0.dist-info/licenses/LICENSE +21 -0
- shellzapy-0.1.0.dist-info/licenses/NOTICE +9 -0
- zapy/__init__.py +58 -0
- zapy/_appstate/__init__.py +59 -0
- zapy/_appstate/constants.py +82 -0
- zapy/_appstate/crypto/__init__.py +17 -0
- zapy/_appstate/crypto/app_state_crypto.py +401 -0
- zapy/_appstate/parsers/__init__.py +23 -0
- zapy/_appstate/parsers/encoding.py +157 -0
- zapy/_appstate/parsers/response_parser.py +135 -0
- zapy/_appstate/sync/__init__.py +11 -0
- zapy/_appstate/sync/sync_client.py +1559 -0
- zapy/_appstate/types.py +137 -0
- zapy/_appstate/utils.py +100 -0
- zapy/_auth/__init__.py +3 -0
- zapy/_auth/auth_client.py +618 -0
- zapy/_auth/credentials_flow.py +290 -0
- zapy/_auth/pairing/__init__.py +3 -0
- zapy/_auth/pairing/companion_host.py +239 -0
- zapy/_auth/pairing/flow.py +808 -0
- zapy/_auth/pairing/pairing_code_crypto.py +143 -0
- zapy/_auth/pairing/qr_flow.py +123 -0
- zapy/_auth/pairing/shortcake_crypto.py +122 -0
- zapy/_auth/pairing/shortcake_flow.py +393 -0
- zapy/_auth/types.py +110 -0
- zapy/_client/__init__.py +26 -0
- zapy/_client/client.py +972 -0
- zapy/_client/connection/__init__.py +6 -0
- zapy/_client/connection/manager.py +525 -0
- zapy/_client/connection/receipt_queue.py +74 -0
- zapy/_client/coordinators/__init__.py +81 -0
- zapy/_client/coordinators/ab_props.py +260 -0
- zapy/_client/coordinators/app_state_mutation.py +2538 -0
- zapy/_client/coordinators/bot.py +830 -0
- zapy/_client/coordinators/broadcast_list.py +101 -0
- zapy/_client/coordinators/business.py +247 -0
- zapy/_client/coordinators/email.py +158 -0
- zapy/_client/coordinators/group.py +1478 -0
- zapy/_client/coordinators/incoming_node.py +758 -0
- zapy/_client/coordinators/low_level.py +119 -0
- zapy/_client/coordinators/message.py +1153 -0
- zapy/_client/coordinators/message_dispatch.py +1637 -0
- zapy/_client/coordinators/newsletter.py +110 -0
- zapy/_client/coordinators/offline_resume.py +271 -0
- zapy/_client/coordinators/passive_tasks.py +447 -0
- zapy/_client/coordinators/presence.py +103 -0
- zapy/_client/coordinators/privacy.py +623 -0
- zapy/_client/coordinators/profile.py +1024 -0
- zapy/_client/coordinators/retry.py +1878 -0
- zapy/_client/coordinators/status.py +132 -0
- zapy/_client/coordinators/stream_control.py +260 -0
- zapy/_client/coordinators/trusted_contact_token.py +417 -0
- zapy/_client/events/__init__.py +266 -0
- zapy/_client/events/abprops.py +58 -0
- zapy/_client/events/appstate_mutation.py +248 -0
- zapy/_client/events/business.py +565 -0
- zapy/_client/events/call.py +144 -0
- zapy/_client/events/chatstate.py +41 -0
- zapy/_client/events/devices.py +122 -0
- zapy/_client/events/dirty.py +384 -0
- zapy/_client/events/group.py +655 -0
- zapy/_client/events/identity.py +40 -0
- zapy/_client/events/incoming.py +1079 -0
- zapy/_client/events/mex_notification.py +317 -0
- zapy/_client/events/offline.py +123 -0
- zapy/_client/events/picture.py +67 -0
- zapy/_client/events/presence.py +74 -0
- zapy/_client/events/privacy.py +187 -0
- zapy/_client/events/privacy_token.py +72 -0
- zapy/_client/events/receipt.py +109 -0
- zapy/_client/events/registration.py +70 -0
- zapy/_client/events/username.py +76 -0
- zapy/_client/factory.py +2020 -0
- zapy/_client/media.py +829 -0
- zapy/_client/newsletter/__init__.py +90 -0
- zapy/_client/newsletter/admin.py +323 -0
- zapy/_client/newsletter/content.py +499 -0
- zapy/_client/newsletter/discovery.py +233 -0
- zapy/_client/newsletter/messaging.py +396 -0
- zapy/_client/newsletter/mex.py +99 -0
- zapy/_client/newsletter/parse.py +406 -0
- zapy/_client/newsletter/types.py +393 -0
- zapy/_client/persistence/__init__.py +89 -0
- zapy/_client/persistence/companion_host.py +133 -0
- zapy/_client/persistence/ephemeral_setting.py +245 -0
- zapy/_client/persistence/group_history.py +361 -0
- zapy/_client/persistence/history_blob.py +169 -0
- zapy/_client/persistence/history_sync.py +646 -0
- zapy/_client/persistence/mailbox.py +232 -0
- zapy/_client/persistence/write_behind_persistence.py +368 -0
- zapy/_client/plugins/__init__.py +23 -0
- zapy/_client/plugins/define.py +44 -0
- zapy/_client/plugins/install.py +254 -0
- zapy/_client/plugins/types.py +64 -0
- zapy/_client/tokens/__init__.py +21 -0
- zapy/_client/tokens/cs_token.py +47 -0
- zapy/_client/tokens/tc_token.py +43 -0
- zapy/_client/types.py +988 -0
- zapy/_crypto/__init__.py +65 -0
- zapy/_crypto/core/__init__.py +62 -0
- zapy/_crypto/core/hkdf.py +41 -0
- zapy/_crypto/core/keys.py +51 -0
- zapy/_crypto/core/nonce.py +25 -0
- zapy/_crypto/core/primitives.py +179 -0
- zapy/_crypto/core/random.py +32 -0
- zapy/_crypto/core/xeddsa.py +72 -0
- zapy/_crypto/curves/__init__.py +3 -0
- zapy/_crypto/curves/constants.py +10 -0
- zapy/_crypto/curves/ed25519.py +61 -0
- zapy/_crypto/curves/types.py +18 -0
- zapy/_crypto/curves/x25519.py +117 -0
- zapy/_crypto/math/__init__.py +3 -0
- zapy/_crypto/math/constants.py +35 -0
- zapy/_crypto/math/edwards.py +174 -0
- zapy/_crypto/math/fe.py +120 -0
- zapy/_crypto/math/le.py +13 -0
- zapy/_crypto/math/mod.py +15 -0
- zapy/_crypto/math/prime.py +11 -0
- zapy/_crypto/math/types.py +25 -0
- zapy/_crypto/native_backend.py +40 -0
- zapy/_infra/__init__.py +3 -0
- zapy/_infra/log.py +142 -0
- zapy/_infra/perf.py +77 -0
- zapy/_media/__init__.py +64 -0
- zapy/_media/constants.py +133 -0
- zapy/_media/container.py +110 -0
- zapy/_media/crypto/__init__.py +19 -0
- zapy/_media/crypto/crypto.py +633 -0
- zapy/_media/crypto/media_retry.py +107 -0
- zapy/_media/processor.py +100 -0
- zapy/_media/sticker/__init__.py +8 -0
- zapy/_media/sticker/pack.py +188 -0
- zapy/_media/transfer/__init__.py +15 -0
- zapy/_media/transfer/client.py +635 -0
- zapy/_media/transfer/conn.py +48 -0
- zapy/_media/types.py +169 -0
- zapy/_message/__init__.py +121 -0
- zapy/_message/addons/__init__.py +5 -0
- zapy/_message/addons/link_preview/__init__.py +54 -0
- zapy/_message/addons/link_preview/builder.py +56 -0
- zapy/_message/addons/link_preview/detect.py +72 -0
- zapy/_message/addons/link_preview/fetcher.py +553 -0
- zapy/_message/addons/link_preview/types.py +100 -0
- zapy/_message/client.py +486 -0
- zapy/_message/context_info.py +424 -0
- zapy/_message/crypto/__init__.py +71 -0
- zapy/_message/crypto/addon_crypto.py +656 -0
- zapy/_message/crypto/icdc.py +138 -0
- zapy/_message/crypto/phash.py +87 -0
- zapy/_message/crypto/reporting_token.py +498 -0
- zapy/_message/crypto/use_case_secret.py +113 -0
- zapy/_message/encode/__init__.py +84 -0
- zapy/_message/encode/content.py +636 -0
- zapy/_message/encode/device_sent.py +88 -0
- zapy/_message/encode/media_payload.py +122 -0
- zapy/_message/encode/padding.py +27 -0
- zapy/_message/kinds/__init__.py +1 -0
- zapy/_message/kinds/bot.py +179 -0
- zapy/_message/kinds/group_history.py +206 -0
- zapy/_message/kinds/newsletter.py +388 -0
- zapy/_message/kinds/sticker_pack.py +74 -0
- zapy/_message/messaging/__init__.py +336 -0
- zapy/_message/messaging/companion_host.py +117 -0
- zapy/_message/messaging/fanout.py +311 -0
- zapy/_message/messaging/group_metadata.py +444 -0
- zapy/_message/messaging/ignore_key.py +264 -0
- zapy/_message/messaging/key_protocol.py +217 -0
- zapy/_message/messaging/link_preview.py +448 -0
- zapy/_message/messaging/messages.py +1429 -0
- zapy/_message/primitives/__init__.py +1 -0
- zapy/_message/primitives/ack.py +232 -0
- zapy/_message/primitives/incoming.py +1141 -0
- zapy/_message/primitives/media_retry.py +451 -0
- zapy/_message/primitives/peer_data_operation.py +271 -0
- zapy/_message/types.py +434 -0
- zapy/_proto/WAProto_pb2.py +2584 -0
- zapy/_proto/__init__.py +1 -0
- zapy/_protocol/__init__.py +3 -0
- zapy/_protocol/abprops_spec.py +6216 -0
- zapy/_protocol/auth.py +17 -0
- zapy/_protocol/browser.py +57 -0
- zapy/_protocol/defaults.py +38 -0
- zapy/_protocol/device_identity.py +54 -0
- zapy/_protocol/jid.py +241 -0
- zapy/_protocol/message.py +127 -0
- zapy/_protocol/nodes.py +144 -0
- zapy/_protocol/notification.py +18 -0
- zapy/_retry/__init__.py +77 -0
- zapy/_retry/codec.py +209 -0
- zapy/_retry/constants.py +28 -0
- zapy/_retry/parse.py +132 -0
- zapy/_retry/reason.py +65 -0
- zapy/_retry/replay.py +483 -0
- zapy/_retry/tracker.py +161 -0
- zapy/_retry/types.py +122 -0
- zapy/_signal/__init__.py +171 -0
- zapy/_signal/api/__init__.py +133 -0
- zapy/_signal/api/codec.py +164 -0
- zapy/_signal/api/constants.py +14 -0
- zapy/_signal/api/device_sync.py +915 -0
- zapy/_signal/api/digest_sync.py +363 -0
- zapy/_signal/api/identity_sync.py +250 -0
- zapy/_signal/api/missing_pre_keys_sync.py +267 -0
- zapy/_signal/api/prekeys.py +191 -0
- zapy/_signal/api/result_map.py +40 -0
- zapy/_signal/api/rotate_key.py +111 -0
- zapy/_signal/api/session_sync.py +297 -0
- zapy/_signal/attestation.py +145 -0
- zapy/_signal/constants.py +22 -0
- zapy/_signal/encoding.py +78 -0
- zapy/_signal/group/__init__.py +35 -0
- zapy/_signal/group/chain.py +139 -0
- zapy/_signal/group/codec.py +78 -0
- zapy/_signal/group/encoding.py +166 -0
- zapy/_signal/group/manager.py +361 -0
- zapy/_signal/registration/__init__.py +44 -0
- zapy/_signal/registration/keygen.py +46 -0
- zapy/_signal/registration/reg_encoding.py +66 -0
- zapy/_signal/registration/reg_utils.py +52 -0
- zapy/_signal/session/__init__.py +114 -0
- zapy/_signal/session/encoding.py +385 -0
- zapy/_signal/session/protocol.py +590 -0
- zapy/_signal/session/ratchet.py +381 -0
- zapy/_signal/session/resolver.py +630 -0
- zapy/_signal/session/serializer.py +96 -0
- zapy/_signal/session/session.py +272 -0
- zapy/_signal/types.py +214 -0
- zapy/_store/__init__.py +118 -0
- zapy/_store/cache/__init__.py +166 -0
- zapy/_store/cache/identity.py +130 -0
- zapy/_store/cache/privacy_token.py +116 -0
- zapy/_store/cache/sender_key.py +168 -0
- zapy/_store/cache/session.py +142 -0
- zapy/_store/contracts/__init__.py +84 -0
- zapy/_store/contracts/appstate.py +82 -0
- zapy/_store/contracts/auth.py +16 -0
- zapy/_store/contracts/chat_metadata.py +29 -0
- zapy/_store/contracts/contact.py +31 -0
- zapy/_store/contracts/device_list.py +35 -0
- zapy/_store/contracts/group_metadata.py +33 -0
- zapy/_store/contracts/identity.py +18 -0
- zapy/_store/contracts/message.py +36 -0
- zapy/_store/contracts/message_secret.py +41 -0
- zapy/_store/contracts/pre_key.py +32 -0
- zapy/_store/contracts/privacy_token.py +32 -0
- zapy/_store/contracts/retry.py +47 -0
- zapy/_store/contracts/sender_key.py +37 -0
- zapy/_store/contracts/session.py +21 -0
- zapy/_store/contracts/signal.py +23 -0
- zapy/_store/contracts/thread.py +35 -0
- zapy/_store/create_store.py +890 -0
- zapy/_store/locks.py +1154 -0
- zapy/_store/memory/__init__.py +40 -0
- zapy/_store/memory/appstate.py +200 -0
- zapy/_store/memory/auth.py +24 -0
- zapy/_store/memory/chat_metadata.py +124 -0
- zapy/_store/memory/contact.py +125 -0
- zapy/_store/memory/device_list.py +161 -0
- zapy/_store/memory/group_metadata.py +125 -0
- zapy/_store/memory/identity.py +86 -0
- zapy/_store/memory/message.py +85 -0
- zapy/_store/memory/message_secret.py +145 -0
- zapy/_store/memory/pre_key.py +112 -0
- zapy/_store/memory/privacy_token.py +103 -0
- zapy/_store/memory/retry.py +250 -0
- zapy/_store/memory/sender_key.py +162 -0
- zapy/_store/memory/session.py +111 -0
- zapy/_store/memory/signal.py +45 -0
- zapy/_store/memory/thread.py +66 -0
- zapy/_store/noop.py +279 -0
- zapy/_transport/__init__.py +3 -0
- zapy/_transport/binary/__init__.py +77 -0
- zapy/_transport/binary/constants.py +80 -0
- zapy/_transport/binary/decoder.py +260 -0
- zapy/_transport/binary/encoder.py +279 -0
- zapy/_transport/binary/tokens.py +1289 -0
- zapy/_transport/comms.py +759 -0
- zapy/_transport/keepalive/__init__.py +3 -0
- zapy/_transport/keepalive/keep_alive.py +252 -0
- zapy/_transport/node/__init__.py +3 -0
- zapy/_transport/node/builders/__init__.py +9 -0
- zapy/_transport/node/builders/abprops.py +33 -0
- zapy/_transport/node/builders/account_sync.py +120 -0
- zapy/_transport/node/builders/bot.py +56 -0
- zapy/_transport/node/builders/business.py +261 -0
- zapy/_transport/node/builders/chatstate.py +74 -0
- zapy/_transport/node/builders/community.py +116 -0
- zapy/_transport/node/builders/device.py +30 -0
- zapy/_transport/node/builders/email.py +181 -0
- zapy/_transport/node/builders/global_.py +74 -0
- zapy/_transport/node/builders/group.py +279 -0
- zapy/_transport/node/builders/media.py +21 -0
- zapy/_transport/node/builders/message.py +436 -0
- zapy/_transport/node/builders/mobile.py +227 -0
- zapy/_transport/node/builders/newsletter.py +293 -0
- zapy/_transport/node/builders/offline.py +20 -0
- zapy/_transport/node/builders/pairing.py +130 -0
- zapy/_transport/node/builders/passive.py +28 -0
- zapy/_transport/node/builders/prekeys.py +215 -0
- zapy/_transport/node/builders/presence.py +100 -0
- zapy/_transport/node/builders/privacy.py +243 -0
- zapy/_transport/node/builders/privacy_token.py +94 -0
- zapy/_transport/node/builders/profile.py +176 -0
- zapy/_transport/node/builders/retry.py +156 -0
- zapy/_transport/node/builders/shortcake.py +87 -0
- zapy/_transport/node/builders/tos.py +92 -0
- zapy/_transport/node/builders/usync.py +185 -0
- zapy/_transport/node/helpers.py +201 -0
- zapy/_transport/node/orchestrator.py +210 -0
- zapy/_transport/node/query.py +82 -0
- zapy/_transport/node/transport.py +105 -0
- zapy/_transport/node/usync.py +33 -0
- zapy/_transport/node/xml.py +38 -0
- zapy/_transport/noise/__init__.py +7 -0
- zapy/_transport/noise/cert.py +85 -0
- zapy/_transport/noise/client_payload.py +344 -0
- zapy/_transport/noise/constants.py +12 -0
- zapy/_transport/noise/frame_codec.py +120 -0
- zapy/_transport/noise/handshake.py +92 -0
- zapy/_transport/noise/session.py +493 -0
- zapy/_transport/noise/socket.py +45 -0
- zapy/_transport/noise/types.py +66 -0
- zapy/_transport/noise/version.json +3 -0
- zapy/_transport/proxy.py +35 -0
- zapy/_transport/types.py +19 -0
- zapy/_transport/wa_version_fetcher.py +159 -0
- zapy/_transport/web_socket.py +602 -0
- zapy/_util/__init__.py +3 -0
- zapy/_util/bytes.py +131 -0
- zapy/_util/coercion.py +29 -0
- zapy/_util/collections.py +45 -0
- zapy/_util/primitives.py +49 -0
- zapy/client.py +840 -0
- zapy/errors.py +148 -0
- zapy/events.py +564 -0
- zapy/jid.py +140 -0
- zapy/py.typed +0 -0
- zapy/stores/__init__.py +50 -0
- zapy/stores/base.py +1627 -0
- zapy/stores/json_file.py +359 -0
- zapy/stores/memory.py +322 -0
- zapy/stores/sqlite.py +343 -0
|
@@ -0,0 +1,493 @@
|
|
|
1
|
+
"""Noise session orchestrator: XX / IK-resume / XX-fallback handshakes.
|
|
2
|
+
|
|
3
|
+
``asyncio``-native: a lock serializes frame encryption (the TS write chain),
|
|
4
|
+
and handshake frames are awaited through a future with the configured
|
|
5
|
+
timeout. Post-handshake frames that arrive early are decrypted once the
|
|
6
|
+
socket exists.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import asyncio
|
|
12
|
+
import inspect
|
|
13
|
+
from collections.abc import Awaitable, Callable
|
|
14
|
+
|
|
15
|
+
from zapy._crypto.curves.x25519 import X25519
|
|
16
|
+
from zapy._infra.log import Logger, get_logger
|
|
17
|
+
from zapy._crypto.curves.types import SignalKeyPair
|
|
18
|
+
from zapy._protocol import defaults as _defaults
|
|
19
|
+
from zapy._proto import WAProto_pb2
|
|
20
|
+
from zapy._transport.noise import constants as _c
|
|
21
|
+
from zapy._transport.noise.cert import WaNoiseRootCa, verify_noise_certificate_chain
|
|
22
|
+
from zapy._transport.noise.client_payload import (
|
|
23
|
+
build_login_payload,
|
|
24
|
+
build_registration_payload,
|
|
25
|
+
)
|
|
26
|
+
from zapy._transport.noise.frame_codec import WaFrameCodec
|
|
27
|
+
from zapy._transport.noise.handshake import WaNoiseHandshake
|
|
28
|
+
from zapy._transport.noise.socket import WaNoiseSocket
|
|
29
|
+
from zapy._transport.noise.types import WaNoiseConfig
|
|
30
|
+
|
|
31
|
+
async def _resolve_payload(
|
|
32
|
+
payload: bytes
|
|
33
|
+
| bytearray
|
|
34
|
+
| Callable[[], bytes | bytearray | Awaitable[bytes | bytearray]],
|
|
35
|
+
) -> bytes:
|
|
36
|
+
if callable(payload):
|
|
37
|
+
produced = payload()
|
|
38
|
+
if inspect.isawaitable(produced):
|
|
39
|
+
produced = await produced
|
|
40
|
+
return bytes(produced)
|
|
41
|
+
return bytes(payload)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
async def _resolve_handshake_payload(config: WaNoiseConfig) -> bytes:
|
|
45
|
+
if config.is_registered:
|
|
46
|
+
if config.login_payload is not None:
|
|
47
|
+
return await _resolve_payload(config.login_payload)
|
|
48
|
+
if config.login_payload_config is not None:
|
|
49
|
+
return build_login_payload(config.login_payload_config)
|
|
50
|
+
raise ValueError("noise login payload is missing")
|
|
51
|
+
if config.registration_payload is not None:
|
|
52
|
+
return await _resolve_payload(config.registration_payload)
|
|
53
|
+
if config.registration_payload_config is not None:
|
|
54
|
+
return build_registration_payload(config.registration_payload_config)
|
|
55
|
+
raise ValueError("noise registration payload is missing")
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _build_routing_info_prefix(routing_info: bytes) -> bytes:
|
|
59
|
+
prefix = bytearray(2 + 2 + 1 + 2 + len(routing_info))
|
|
60
|
+
prefix[0] = 0x45
|
|
61
|
+
prefix[1] = 0x44
|
|
62
|
+
prefix[2] = 0x00
|
|
63
|
+
prefix[3] = 0x01
|
|
64
|
+
prefix[4] = (len(routing_info) >> 16) & 0xFF
|
|
65
|
+
prefix[5] = (len(routing_info) >> 8) & 0xFF
|
|
66
|
+
prefix[6] = len(routing_info) & 0xFF
|
|
67
|
+
prefix[7:] = routing_info
|
|
68
|
+
return bytes(prefix)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class WaNoiseSession:
|
|
72
|
+
"""Runs one Noise handshake over a frame codec, then carries the channel."""
|
|
73
|
+
|
|
74
|
+
def __init__(
|
|
75
|
+
self,
|
|
76
|
+
send_wire: Callable[[bytes], Awaitable[None] | None],
|
|
77
|
+
logger: Logger | None = None,
|
|
78
|
+
handshake_frame_timeout_ms: float | None = None,
|
|
79
|
+
) -> None:
|
|
80
|
+
self._send_wire = send_wire
|
|
81
|
+
if logger is not None:
|
|
82
|
+
self._logger = logger
|
|
83
|
+
else:
|
|
84
|
+
self._logger = get_logger("zapy._transport.noise")
|
|
85
|
+
self._handshake_frame_timeout_ms = (
|
|
86
|
+
_defaults.CONNECT_TIMEOUT_MS
|
|
87
|
+
if handshake_frame_timeout_ms is None
|
|
88
|
+
else handshake_frame_timeout_ms
|
|
89
|
+
)
|
|
90
|
+
self._write_lock = asyncio.Lock()
|
|
91
|
+
self._frame_codec: WaFrameCodec | None = None
|
|
92
|
+
self._handshake_inbox: list[bytes] = []
|
|
93
|
+
self._handshake_inbox_head = 0
|
|
94
|
+
self._handshake_waiter: asyncio.Future[bytes] | None = None
|
|
95
|
+
self._handshake_rejecter: Callable[[Exception], None] | None = None
|
|
96
|
+
self._pending_decrypted_frames: list[bytes] = []
|
|
97
|
+
self._closed_error: Exception | None = None
|
|
98
|
+
self._noise_socket: WaNoiseSocket | None = None
|
|
99
|
+
self._server_static_key: bytes | None = None
|
|
100
|
+
self._trusted_root_ca: WaNoiseRootCa | None = None
|
|
101
|
+
|
|
102
|
+
def start(self, config: WaNoiseConfig) -> Awaitable[None]:
|
|
103
|
+
"""Run the handshake (full XX, or IK resume with XX-fallback).
|
|
104
|
+
|
|
105
|
+
A regular method (not ``async``) so the synchronous prefix — reset,
|
|
106
|
+
codec setup — runs at call time, exactly like the TS ``async`` method
|
|
107
|
+
whose body runs synchronously up to its first ``await``.
|
|
108
|
+
"""
|
|
109
|
+
self.reset()
|
|
110
|
+
self._logger.debug(
|
|
111
|
+
"noise session start",
|
|
112
|
+
{
|
|
113
|
+
"is_registered": config.is_registered,
|
|
114
|
+
"has_server_static_key": bool(config.server_static_key),
|
|
115
|
+
},
|
|
116
|
+
)
|
|
117
|
+
protocol_header = (
|
|
118
|
+
bytes(config.protocol_header)
|
|
119
|
+
if config.protocol_header is not None
|
|
120
|
+
else bytes(_c.WA_PROTO_HEADER)
|
|
121
|
+
)
|
|
122
|
+
if config.routing_info:
|
|
123
|
+
intro_frame = (
|
|
124
|
+
_build_routing_info_prefix(bytes(config.routing_info)) + protocol_header
|
|
125
|
+
)
|
|
126
|
+
else:
|
|
127
|
+
intro_frame = protocol_header
|
|
128
|
+
|
|
129
|
+
self._frame_codec = WaFrameCodec(intro_frame)
|
|
130
|
+
return self._run_start(config, protocol_header)
|
|
131
|
+
|
|
132
|
+
async def _run_start(self, config: WaNoiseConfig, protocol_header: bytes) -> None:
|
|
133
|
+
ephemeral_key_pair = X25519.generate_key_pair()
|
|
134
|
+
payload = await _resolve_handshake_payload(config)
|
|
135
|
+
verify_certificates = config.verify_certificate_chain
|
|
136
|
+
self._trusted_root_ca = config.trusted_root_ca
|
|
137
|
+
|
|
138
|
+
if config.server_static_key is not None and len(config.server_static_key) == 32:
|
|
139
|
+
self._logger.debug("noise session attempting resume handshake (IK)")
|
|
140
|
+
self._noise_socket = await self._resume_handshake(
|
|
141
|
+
bytes(config.server_static_key),
|
|
142
|
+
config.client_static_key_pair,
|
|
143
|
+
ephemeral_key_pair,
|
|
144
|
+
payload,
|
|
145
|
+
protocol_header,
|
|
146
|
+
verify_certificates,
|
|
147
|
+
)
|
|
148
|
+
await self._decode_buffered_post_handshake_frames()
|
|
149
|
+
self._logger.info(
|
|
150
|
+
"noise session established", {"mode": "resume_or_fallback"}
|
|
151
|
+
)
|
|
152
|
+
return
|
|
153
|
+
|
|
154
|
+
self._logger.debug("noise session starting full handshake (XX)")
|
|
155
|
+
self._noise_socket = await self._full_handshake(
|
|
156
|
+
config.client_static_key_pair,
|
|
157
|
+
ephemeral_key_pair,
|
|
158
|
+
payload,
|
|
159
|
+
protocol_header,
|
|
160
|
+
verify_certificates,
|
|
161
|
+
)
|
|
162
|
+
await self._decode_buffered_post_handshake_frames()
|
|
163
|
+
self._logger.info("noise session established", {"mode": "full"})
|
|
164
|
+
|
|
165
|
+
async def encrypt_frame(self, frame: bytes | bytearray) -> bytes:
|
|
166
|
+
"""Encrypt and frame-encode one post-handshake frame, in send order."""
|
|
167
|
+
socket = self._noise_socket
|
|
168
|
+
codec = self._frame_codec
|
|
169
|
+
if socket is None or codec is None:
|
|
170
|
+
raise ValueError("noise session is not established")
|
|
171
|
+
async with self._write_lock:
|
|
172
|
+
return codec.encode_frame(socket.encrypt(bytes(frame)))
|
|
173
|
+
|
|
174
|
+
def push_wire_chunk(self, chunk: bytes | bytearray) -> list[bytes]:
|
|
175
|
+
"""Feed wire bytes; returns decrypted application frames plus any pending."""
|
|
176
|
+
codec = self._frame_codec
|
|
177
|
+
if codec is None:
|
|
178
|
+
return []
|
|
179
|
+
out: list[bytes] = []
|
|
180
|
+
if self._pending_decrypted_frames:
|
|
181
|
+
out.extend(self._pending_decrypted_frames)
|
|
182
|
+
self._pending_decrypted_frames = []
|
|
183
|
+
frames = codec.push_wire_chunk(bytes(chunk))
|
|
184
|
+
if self._noise_socket is None:
|
|
185
|
+
for frame in frames:
|
|
186
|
+
waiter = self._handshake_waiter
|
|
187
|
+
rejecter = self._handshake_rejecter
|
|
188
|
+
if waiter is not None and rejecter is not None:
|
|
189
|
+
self._handshake_waiter = None
|
|
190
|
+
self._handshake_rejecter = None
|
|
191
|
+
if not waiter.done():
|
|
192
|
+
waiter.set_result(frame)
|
|
193
|
+
continue
|
|
194
|
+
self._handshake_inbox.append(frame)
|
|
195
|
+
return out
|
|
196
|
+
if frames:
|
|
197
|
+
out.extend(self._decrypt_frames_batch(self._noise_socket, frames))
|
|
198
|
+
return out
|
|
199
|
+
|
|
200
|
+
def on_socket_closed(self, error: Exception | None = None) -> None:
|
|
201
|
+
"""Fail any pending handshake wait with the socket error."""
|
|
202
|
+
if error is not None:
|
|
203
|
+
close_error = error
|
|
204
|
+
else:
|
|
205
|
+
close_error = ConnectionError("noise session socket closed")
|
|
206
|
+
self._logger.debug("noise session socket closed", {"message": str(close_error)})
|
|
207
|
+
self._closed_error = close_error
|
|
208
|
+
rejecter = self._handshake_rejecter
|
|
209
|
+
if rejecter is not None:
|
|
210
|
+
self._handshake_rejecter = None
|
|
211
|
+
self._handshake_waiter = None
|
|
212
|
+
rejecter(close_error)
|
|
213
|
+
|
|
214
|
+
def reset(self) -> None:
|
|
215
|
+
"""Drop all handshake and channel state."""
|
|
216
|
+
self._logger.trace("noise session reset")
|
|
217
|
+
self._frame_codec = None
|
|
218
|
+
self._handshake_inbox = []
|
|
219
|
+
self._handshake_inbox_head = 0
|
|
220
|
+
self._handshake_waiter = None
|
|
221
|
+
self._handshake_rejecter = None
|
|
222
|
+
self._pending_decrypted_frames = []
|
|
223
|
+
self._closed_error = None
|
|
224
|
+
self._noise_socket = None
|
|
225
|
+
self._server_static_key = None
|
|
226
|
+
self._trusted_root_ca = None
|
|
227
|
+
|
|
228
|
+
def get_server_static_key(self) -> bytes | None:
|
|
229
|
+
"""The server static key learned during the handshake, if any."""
|
|
230
|
+
return self._server_static_key
|
|
231
|
+
|
|
232
|
+
def _decrypt_frames_batch(
|
|
233
|
+
self, socket: WaNoiseSocket, frames: list[bytes]
|
|
234
|
+
) -> list[bytes]:
|
|
235
|
+
return [socket.decrypt(frame) for frame in frames]
|
|
236
|
+
|
|
237
|
+
async def _full_handshake(
|
|
238
|
+
self,
|
|
239
|
+
client_static_key_pair: SignalKeyPair | None,
|
|
240
|
+
ephemeral_key_pair: SignalKeyPair,
|
|
241
|
+
payload: bytes,
|
|
242
|
+
protocol_header: bytes,
|
|
243
|
+
verify_certificates: bool,
|
|
244
|
+
) -> WaNoiseSocket:
|
|
245
|
+
self._logger.trace("noise full handshake: send client hello")
|
|
246
|
+
handshake = WaNoiseHandshake()
|
|
247
|
+
handshake.start(_c.NOISE_XX_NAME, protocol_header)
|
|
248
|
+
handshake.authenticate(ephemeral_key_pair.pub_key)
|
|
249
|
+
client_hello = WAProto_pb2.HandshakeMessage(
|
|
250
|
+
clientHello=WAProto_pb2.HandshakeMessage.ClientHello(
|
|
251
|
+
ephemeral=ephemeral_key_pair.pub_key
|
|
252
|
+
)
|
|
253
|
+
).SerializeToString()
|
|
254
|
+
server_hello_frame = await self._send_and_receive_handshake_frame(client_hello)
|
|
255
|
+
return await self._continue_full_handshake(
|
|
256
|
+
handshake,
|
|
257
|
+
server_hello_frame,
|
|
258
|
+
client_static_key_pair,
|
|
259
|
+
ephemeral_key_pair,
|
|
260
|
+
payload,
|
|
261
|
+
verify_certificates,
|
|
262
|
+
)
|
|
263
|
+
|
|
264
|
+
async def _resume_handshake(
|
|
265
|
+
self,
|
|
266
|
+
server_static_key: bytes,
|
|
267
|
+
client_static_key_pair: SignalKeyPair | None,
|
|
268
|
+
ephemeral_key_pair: SignalKeyPair,
|
|
269
|
+
payload: bytes,
|
|
270
|
+
protocol_header: bytes,
|
|
271
|
+
verify_certificates: bool,
|
|
272
|
+
) -> WaNoiseSocket:
|
|
273
|
+
result = await self._try_resume_handshake_with_ik(
|
|
274
|
+
server_static_key,
|
|
275
|
+
client_static_key_pair,
|
|
276
|
+
ephemeral_key_pair,
|
|
277
|
+
payload,
|
|
278
|
+
protocol_header,
|
|
279
|
+
)
|
|
280
|
+
if result[0] is not None:
|
|
281
|
+
return result[0]
|
|
282
|
+
self._logger.debug("noise resume handshake fallback to XX")
|
|
283
|
+
return await self._resume_handshake_with_fallback(
|
|
284
|
+
client_static_key_pair,
|
|
285
|
+
ephemeral_key_pair,
|
|
286
|
+
payload,
|
|
287
|
+
protocol_header,
|
|
288
|
+
result[1],
|
|
289
|
+
verify_certificates,
|
|
290
|
+
)
|
|
291
|
+
|
|
292
|
+
async def _try_resume_handshake_with_ik(
|
|
293
|
+
self,
|
|
294
|
+
server_static_key: bytes,
|
|
295
|
+
client_static_key_pair: SignalKeyPair | None,
|
|
296
|
+
ephemeral_key_pair: SignalKeyPair,
|
|
297
|
+
payload: bytes,
|
|
298
|
+
protocol_header: bytes,
|
|
299
|
+
) -> tuple[WaNoiseSocket | None, bytes | None]:
|
|
300
|
+
self._logger.trace("noise resume handshake: send IK client hello")
|
|
301
|
+
if client_static_key_pair is None:
|
|
302
|
+
raise ValueError("noise resume handshake requires a client static key pair")
|
|
303
|
+
handshake = WaNoiseHandshake()
|
|
304
|
+
handshake.start(_c.NOISE_IK_NAME, protocol_header)
|
|
305
|
+
handshake.authenticate(server_static_key)
|
|
306
|
+
handshake.authenticate(ephemeral_key_pair.pub_key)
|
|
307
|
+
|
|
308
|
+
agreement1 = X25519.scalar_mult(
|
|
309
|
+
ephemeral_key_pair.priv_key, server_static_key
|
|
310
|
+
)
|
|
311
|
+
agreement2 = X25519.scalar_mult(
|
|
312
|
+
client_static_key_pair.priv_key, server_static_key
|
|
313
|
+
)
|
|
314
|
+
handshake.mix_into_key(agreement1)
|
|
315
|
+
encrypted_client_static = handshake.encrypt(client_static_key_pair.pub_key)
|
|
316
|
+
handshake.mix_into_key(agreement2)
|
|
317
|
+
encrypted_payload = handshake.encrypt(payload)
|
|
318
|
+
|
|
319
|
+
client_hello = WAProto_pb2.HandshakeMessage(
|
|
320
|
+
clientHello=WAProto_pb2.HandshakeMessage.ClientHello(
|
|
321
|
+
ephemeral=ephemeral_key_pair.pub_key,
|
|
322
|
+
payload=encrypted_payload,
|
|
323
|
+
static=encrypted_client_static,
|
|
324
|
+
)
|
|
325
|
+
).SerializeToString()
|
|
326
|
+
server_hello_frame = await self._send_and_receive_handshake_frame(client_hello)
|
|
327
|
+
parsed = WAProto_pb2.HandshakeMessage.FromString(server_hello_frame)
|
|
328
|
+
if not parsed.HasField("serverHello"):
|
|
329
|
+
raise ValueError("noise resume handshake missing serverHello")
|
|
330
|
+
server_hello = parsed.serverHello
|
|
331
|
+
if server_hello.static:
|
|
332
|
+
return None, server_hello_frame
|
|
333
|
+
if not server_hello.ephemeral:
|
|
334
|
+
raise ValueError("noise resume handshake missing server ephemeral")
|
|
335
|
+
if not server_hello.payload:
|
|
336
|
+
raise ValueError("noise resume handshake missing certificate payload")
|
|
337
|
+
|
|
338
|
+
server_ephemeral = bytes(server_hello.ephemeral)
|
|
339
|
+
handshake.authenticate(server_ephemeral)
|
|
340
|
+
dh1 = X25519.scalar_mult(ephemeral_key_pair.priv_key, server_ephemeral)
|
|
341
|
+
dh2 = X25519.scalar_mult(client_static_key_pair.priv_key, server_ephemeral)
|
|
342
|
+
handshake.mix_into_key(dh1)
|
|
343
|
+
handshake.mix_into_key(dh2)
|
|
344
|
+
handshake.decrypt(bytes(server_hello.payload))
|
|
345
|
+
self._server_static_key = server_static_key
|
|
346
|
+
self._logger.debug("noise resume handshake successful without fallback")
|
|
347
|
+
return handshake.finish(), None
|
|
348
|
+
|
|
349
|
+
async def _resume_handshake_with_fallback(
|
|
350
|
+
self,
|
|
351
|
+
client_static_key_pair: SignalKeyPair | None,
|
|
352
|
+
ephemeral_key_pair: SignalKeyPair,
|
|
353
|
+
payload: bytes,
|
|
354
|
+
protocol_header: bytes,
|
|
355
|
+
server_hello_frame: bytes | None,
|
|
356
|
+
verify_certificates: bool,
|
|
357
|
+
) -> WaNoiseSocket:
|
|
358
|
+
if server_hello_frame is None:
|
|
359
|
+
raise ValueError("noise resume handshake missing serverHello")
|
|
360
|
+
fallback = WaNoiseHandshake()
|
|
361
|
+
fallback.start(_c.NOISE_XX_FALLBACK_NAME, protocol_header)
|
|
362
|
+
fallback.authenticate(ephemeral_key_pair.pub_key)
|
|
363
|
+
return await self._continue_full_handshake(
|
|
364
|
+
fallback,
|
|
365
|
+
server_hello_frame,
|
|
366
|
+
client_static_key_pair,
|
|
367
|
+
ephemeral_key_pair,
|
|
368
|
+
payload,
|
|
369
|
+
verify_certificates,
|
|
370
|
+
)
|
|
371
|
+
|
|
372
|
+
async def _continue_full_handshake(
|
|
373
|
+
self,
|
|
374
|
+
handshake: WaNoiseHandshake,
|
|
375
|
+
server_hello_frame: bytes,
|
|
376
|
+
client_static_key_pair: SignalKeyPair | None,
|
|
377
|
+
ephemeral_key_pair: SignalKeyPair,
|
|
378
|
+
payload: bytes,
|
|
379
|
+
verify_certificates: bool,
|
|
380
|
+
) -> WaNoiseSocket:
|
|
381
|
+
self._logger.trace("noise continue full handshake")
|
|
382
|
+
parsed = WAProto_pb2.HandshakeMessage.FromString(server_hello_frame)
|
|
383
|
+
if not parsed.HasField("serverHello"):
|
|
384
|
+
raise ValueError("noise full handshake missing server hello fields")
|
|
385
|
+
server_hello = parsed.serverHello
|
|
386
|
+
has_all_fields = (
|
|
387
|
+
server_hello.ephemeral and server_hello.static and server_hello.payload
|
|
388
|
+
)
|
|
389
|
+
if not has_all_fields:
|
|
390
|
+
raise ValueError("noise full handshake missing server hello fields")
|
|
391
|
+
if client_static_key_pair is None:
|
|
392
|
+
raise ValueError("noise handshake requires a client static key pair")
|
|
393
|
+
|
|
394
|
+
server_ephemeral = bytes(server_hello.ephemeral)
|
|
395
|
+
handshake.authenticate(server_ephemeral)
|
|
396
|
+
handshake.mix_into_key(
|
|
397
|
+
X25519.scalar_mult(ephemeral_key_pair.priv_key, server_ephemeral)
|
|
398
|
+
)
|
|
399
|
+
server_static = handshake.decrypt(bytes(server_hello.static))
|
|
400
|
+
handshake.mix_into_key(
|
|
401
|
+
X25519.scalar_mult(ephemeral_key_pair.priv_key, server_static)
|
|
402
|
+
)
|
|
403
|
+
certificate = handshake.decrypt(bytes(server_hello.payload))
|
|
404
|
+
if verify_certificates:
|
|
405
|
+
verify_noise_certificate_chain(
|
|
406
|
+
certificate, server_static, self._trusted_root_ca
|
|
407
|
+
)
|
|
408
|
+
self._logger.trace("noise certificate chain verified")
|
|
409
|
+
self._server_static_key = server_static
|
|
410
|
+
|
|
411
|
+
encrypted_client_static = handshake.encrypt(client_static_key_pair.pub_key)
|
|
412
|
+
handshake.mix_into_key(
|
|
413
|
+
X25519.scalar_mult(client_static_key_pair.priv_key, server_ephemeral)
|
|
414
|
+
)
|
|
415
|
+
encrypted_payload = handshake.encrypt(payload)
|
|
416
|
+
client_finish = WAProto_pb2.HandshakeMessage(
|
|
417
|
+
clientFinish=WAProto_pb2.HandshakeMessage.ClientFinish(
|
|
418
|
+
static=encrypted_client_static, payload=encrypted_payload
|
|
419
|
+
)
|
|
420
|
+
).SerializeToString()
|
|
421
|
+
await self._send_handshake_frame(client_finish)
|
|
422
|
+
self._logger.trace("noise full handshake client finish sent")
|
|
423
|
+
return handshake.finish()
|
|
424
|
+
|
|
425
|
+
async def _send_handshake_frame(self, frame: bytes) -> None:
|
|
426
|
+
codec = self._frame_codec
|
|
427
|
+
if codec is None:
|
|
428
|
+
raise ValueError("noise frame codec is not initialized")
|
|
429
|
+
self._logger.trace("noise send handshake frame", {"byte_length": len(frame)})
|
|
430
|
+
result = self._send_wire(codec.encode_frame(frame))
|
|
431
|
+
if inspect.isawaitable(result):
|
|
432
|
+
await result
|
|
433
|
+
|
|
434
|
+
async def _send_and_receive_handshake_frame(self, frame: bytes) -> bytes:
|
|
435
|
+
await self._send_handshake_frame(frame)
|
|
436
|
+
return await self._wait_handshake_frame()
|
|
437
|
+
|
|
438
|
+
async def _wait_handshake_frame(self) -> bytes:
|
|
439
|
+
if self._closed_error is not None:
|
|
440
|
+
raise self._closed_error
|
|
441
|
+
if self._handshake_inbox_head < len(self._handshake_inbox):
|
|
442
|
+
frame = self._handshake_inbox[self._handshake_inbox_head]
|
|
443
|
+
self._handshake_inbox_head += 1
|
|
444
|
+
if self._handshake_inbox_head == len(self._handshake_inbox):
|
|
445
|
+
self._handshake_inbox = []
|
|
446
|
+
self._handshake_inbox_head = 0
|
|
447
|
+
self._logger.trace("noise handshake frame consumed from queue")
|
|
448
|
+
return frame
|
|
449
|
+
self._logger.trace("noise waiting handshake frame")
|
|
450
|
+
loop = asyncio.get_running_loop()
|
|
451
|
+
waiter: asyncio.Future[bytes] = loop.create_future()
|
|
452
|
+
|
|
453
|
+
def reject(error: Exception) -> None:
|
|
454
|
+
if not waiter.done():
|
|
455
|
+
waiter.set_exception(error)
|
|
456
|
+
|
|
457
|
+
self._handshake_waiter = waiter
|
|
458
|
+
self._handshake_rejecter = reject
|
|
459
|
+
timeout_s = self._handshake_frame_timeout_ms / 1000
|
|
460
|
+
try:
|
|
461
|
+
return await asyncio.wait_for(asyncio.shield(waiter), timeout_s)
|
|
462
|
+
except asyncio.TimeoutError:
|
|
463
|
+
if self._handshake_waiter is waiter:
|
|
464
|
+
self._handshake_waiter = None
|
|
465
|
+
self._handshake_rejecter = None
|
|
466
|
+
raise TimeoutError(
|
|
467
|
+
"noise handshake frame timeout after "
|
|
468
|
+
f"{_format_ms(self._handshake_frame_timeout_ms)}ms"
|
|
469
|
+
) from None
|
|
470
|
+
|
|
471
|
+
async def _decode_buffered_post_handshake_frames(self) -> None:
|
|
472
|
+
if self._noise_socket is None or self._handshake_inbox_head >= len(
|
|
473
|
+
self._handshake_inbox
|
|
474
|
+
):
|
|
475
|
+
return
|
|
476
|
+
self._logger.debug(
|
|
477
|
+
"decoding buffered post-handshake frames",
|
|
478
|
+
{"count": len(self._handshake_inbox) - self._handshake_inbox_head},
|
|
479
|
+
)
|
|
480
|
+
frames = self._handshake_inbox[self._handshake_inbox_head :]
|
|
481
|
+
if frames:
|
|
482
|
+
self._pending_decrypted_frames.extend(
|
|
483
|
+
self._decrypt_frames_batch(self._noise_socket, frames)
|
|
484
|
+
)
|
|
485
|
+
self._handshake_inbox = []
|
|
486
|
+
self._handshake_inbox_head = 0
|
|
487
|
+
|
|
488
|
+
|
|
489
|
+
def _format_ms(value: float) -> str:
|
|
490
|
+
return str(int(value)) if float(value).is_integer() else str(value)
|
|
491
|
+
|
|
492
|
+
|
|
493
|
+
__all__ = ["WaNoiseSession"]
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"""Post-handshake symmetric channel: AES-GCM with per-direction counters."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from zapy._crypto import aes_gcm_decrypt, aes_gcm_encrypt, write_nonce_counter
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class WaNoiseSocket:
|
|
9
|
+
"""Encrypts outbound frames and decrypts inbound ones, nonces from counters."""
|
|
10
|
+
|
|
11
|
+
def __init__(
|
|
12
|
+
self, encrypt_key: bytes | bytearray, decrypt_key: bytes | bytearray
|
|
13
|
+
) -> None:
|
|
14
|
+
self._encrypt_key = bytes(encrypt_key)
|
|
15
|
+
self._decrypt_key = bytes(decrypt_key)
|
|
16
|
+
self._write_counter = 0
|
|
17
|
+
self._read_counter = 0
|
|
18
|
+
self._write_nonce = bytearray(12)
|
|
19
|
+
self._read_nonce = bytearray(12)
|
|
20
|
+
|
|
21
|
+
def encrypt(
|
|
22
|
+
self, frame: bytes | bytearray, additional_data: bytes | bytearray = b""
|
|
23
|
+
) -> bytes:
|
|
24
|
+
"""Encrypt an outbound frame with the next write nonce."""
|
|
25
|
+
write_nonce_counter(self._write_nonce, self._write_counter)
|
|
26
|
+
self._write_counter += 1
|
|
27
|
+
return aes_gcm_encrypt(
|
|
28
|
+
self._encrypt_key,
|
|
29
|
+
bytes(self._write_nonce),
|
|
30
|
+
bytes(frame),
|
|
31
|
+
bytes(additional_data),
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
def decrypt(
|
|
35
|
+
self, frame: bytes | bytearray, additional_data: bytes | bytearray = b""
|
|
36
|
+
) -> bytes:
|
|
37
|
+
"""Decrypt an inbound frame with the next read nonce."""
|
|
38
|
+
write_nonce_counter(self._read_nonce, self._read_counter)
|
|
39
|
+
self._read_counter += 1
|
|
40
|
+
return aes_gcm_decrypt(
|
|
41
|
+
self._decrypt_key,
|
|
42
|
+
bytes(self._read_nonce),
|
|
43
|
+
bytes(frame),
|
|
44
|
+
bytes(additional_data),
|
|
45
|
+
)
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"""Noise handshake configuration shapes (mirrors ``src/transport/noise/types.ts``)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Awaitable, Callable
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from zapy._crypto.curves.types import SignalKeyPair
|
|
10
|
+
from zapy._signal.types import RegistrationInfo, SignedPreKeyRecord
|
|
11
|
+
from zapy._transport.noise.cert import WaNoiseRootCa
|
|
12
|
+
|
|
13
|
+
PayloadSource = bytes | Callable[[], "bytes | Awaitable[bytes]"]
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass(frozen=True, slots=True)
|
|
17
|
+
class WaPayloadCommonConfig:
|
|
18
|
+
"""Fields shared by login and registration payload configs."""
|
|
19
|
+
|
|
20
|
+
version_base: str | None = None
|
|
21
|
+
device_browser: str | None = None
|
|
22
|
+
device_os_display_name: str | None = None
|
|
23
|
+
device_os_version: str | None = None
|
|
24
|
+
passive: bool = False
|
|
25
|
+
pull: bool | None = None
|
|
26
|
+
user_agent: Any = None
|
|
27
|
+
web_info: Any = None
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass(frozen=True, slots=True)
|
|
31
|
+
class WaLoginPayloadConfig(WaPayloadCommonConfig):
|
|
32
|
+
"""Config for the login (returning-device) handshake payload."""
|
|
33
|
+
|
|
34
|
+
username: int = 0
|
|
35
|
+
device: int | None = None
|
|
36
|
+
lid_db_migrated: bool = False
|
|
37
|
+
login_counter: int | None = None
|
|
38
|
+
connect_attempt_count: int | None = None
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@dataclass(frozen=True, slots=True)
|
|
42
|
+
class WaRegistrationPayloadConfig(WaPayloadCommonConfig):
|
|
43
|
+
"""Config for the first-pairing registration payload."""
|
|
44
|
+
|
|
45
|
+
registration_info: RegistrationInfo | None = None
|
|
46
|
+
signed_pre_key: SignedPreKeyRecord | None = None
|
|
47
|
+
build_hash: bytes | None = None
|
|
48
|
+
device_props: bytes | None = None
|
|
49
|
+
require_full_sync: bool = False
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@dataclass(frozen=True, slots=True)
|
|
53
|
+
class WaNoiseConfig:
|
|
54
|
+
"""Everything ``WaNoiseSession.start`` needs for one handshake."""
|
|
55
|
+
|
|
56
|
+
client_static_key_pair: SignalKeyPair | None = None
|
|
57
|
+
is_registered: bool = False
|
|
58
|
+
login_payload: PayloadSource | None = None
|
|
59
|
+
registration_payload: PayloadSource | None = None
|
|
60
|
+
login_payload_config: WaLoginPayloadConfig | None = None
|
|
61
|
+
registration_payload_config: WaRegistrationPayloadConfig | None = None
|
|
62
|
+
server_static_key: bytes | None = None
|
|
63
|
+
routing_info: bytes | None = None
|
|
64
|
+
protocol_header: bytes | None = None
|
|
65
|
+
verify_certificate_chain: bool = True
|
|
66
|
+
trusted_root_ca: WaNoiseRootCa | None = None
|
zapy/_transport/proxy.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"""Proxy transport narrowing (subset of ``src/transport/proxy.ts``).
|
|
2
|
+
|
|
3
|
+
Only the dispatcher/agent shape guards used by the comms config live here;
|
|
4
|
+
TCP CONNECT tunneling and endpoint resolution land with the proxy layer.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def is_proxy_dispatcher(value: object) -> bool:
|
|
13
|
+
"""``True`` for undici-style proxy dispatchers (has a ``dispatch`` method)."""
|
|
14
|
+
if isinstance(value, dict):
|
|
15
|
+
return callable(value.get("dispatch"))
|
|
16
|
+
return callable(getattr(value, "dispatch", None))
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def is_proxy_agent(value: object) -> bool:
|
|
20
|
+
"""``True`` for Node http.Agent-style proxies (has an ``addRequest`` method)."""
|
|
21
|
+
return hasattr(value, "addRequest") and callable(getattr(value, "addRequest"))
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def to_proxy_dispatcher(proxy: Any | None) -> Any | None:
|
|
25
|
+
"""Narrow ``proxy`` to a dispatcher, or ``None``."""
|
|
26
|
+
if proxy is None or not is_proxy_dispatcher(proxy):
|
|
27
|
+
return None
|
|
28
|
+
return proxy
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def to_proxy_agent(proxy: Any | None) -> Any | None:
|
|
32
|
+
"""Narrow ``proxy`` to an agent, or ``None``."""
|
|
33
|
+
if proxy is None or not is_proxy_agent(proxy):
|
|
34
|
+
return None
|
|
35
|
+
return proxy
|
zapy/_transport/types.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"""Binary node tree (mirrors ``src/transport/types.ts``)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@dataclass(frozen=True, slots=True)
|
|
9
|
+
class BinaryNode:
|
|
10
|
+
"""A WhatsApp binary-protocol node.
|
|
11
|
+
|
|
12
|
+
``content`` is ``bytes`` for binary payloads, ``str`` for hand-built text,
|
|
13
|
+
a list of child nodes, or ``None`` when absent. Decoded nodes always carry
|
|
14
|
+
``bytes`` (never ``str``), matching the TS decoder.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
tag: str
|
|
18
|
+
attrs: dict[str, str] = field(default_factory=dict)
|
|
19
|
+
content: bytes | str | list["BinaryNode"] | None = None
|