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,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
|