offline-protocol-sdk 0.28.0__py3-none-macosx_14_0_arm64.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 (40) hide show
  1. offline_protocol_sdk/__init__.py +22 -0
  2. offline_protocol_sdk/_callback_reentrancy.py +64 -0
  3. offline_protocol_sdk/address_declaration.py +207 -0
  4. offline_protocol_sdk/ble_manager.py +595 -0
  5. offline_protocol_sdk/ble_peripheral.py +673 -0
  6. offline_protocol_sdk/dnssd_bridge.py +614 -0
  7. offline_protocol_sdk/gateway_attach_policy.py +437 -0
  8. offline_protocol_sdk/gateway_manager.py +1217 -0
  9. offline_protocol_sdk/gateway_verdict_tracker.py +97 -0
  10. offline_protocol_sdk/internet_manager.py +1444 -0
  11. offline_protocol_sdk/legacy_store_adoption.py +184 -0
  12. offline_protocol_sdk/libuniffi.dylib +0 -0
  13. offline_protocol_sdk/local_api/__init__.py +34 -0
  14. offline_protocol_sdk/local_api/authz.py +180 -0
  15. offline_protocol_sdk/local_api/cli.py +171 -0
  16. offline_protocol_sdk/local_api/codec.py +210 -0
  17. offline_protocol_sdk/local_api/dispatch.py +537 -0
  18. offline_protocol_sdk/local_api/mux.py +239 -0
  19. offline_protocol_sdk/local_api/server.py +546 -0
  20. offline_protocol_sdk/local_api/session.py +86 -0
  21. offline_protocol_sdk/local_api/table.py +849 -0
  22. offline_protocol_sdk/offline_protocol.py +13508 -0
  23. offline_protocol_sdk/peer_stream_manager.py +1303 -0
  24. offline_protocol_sdk/presence_watch_policy.py +102 -0
  25. offline_protocol_sdk/protocol_manager.py +1108 -0
  26. offline_protocol_sdk/relay_answer_prefixes.py +61 -0
  27. offline_protocol_sdk/secure_storage.py +551 -0
  28. offline_protocol_sdk/services.py +195 -0
  29. offline_protocol_sdk/state_storage.py +452 -0
  30. offline_protocol_sdk/storage_namespace.py +33 -0
  31. offline_protocol_sdk/transport_manager.py +138 -0
  32. offline_protocol_sdk-0.28.0.dist-info/METADATA +519 -0
  33. offline_protocol_sdk-0.28.0.dist-info/RECORD +40 -0
  34. offline_protocol_sdk-0.28.0.dist-info/WHEEL +5 -0
  35. offline_protocol_sdk-0.28.0.dist-info/entry_points.txt +2 -0
  36. offline_protocol_sdk-0.28.0.dist-info/licenses/EXPORT.md +68 -0
  37. offline_protocol_sdk-0.28.0.dist-info/licenses/LICENSE +661 -0
  38. offline_protocol_sdk-0.28.0.dist-info/licenses/LICENSE-COMMERCIAL.md +89 -0
  39. offline_protocol_sdk-0.28.0.dist-info/licenses/THIRD-PARTY-NOTICES.md +6645 -0
  40. offline_protocol_sdk-0.28.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,22 @@
1
+ """Offline Protocol SDK — Python bindings for offline-first mesh networking."""
2
+
3
+ # Re-export all UniFFI-generated types (available after build-desktop.sh runs)
4
+ from .offline_protocol import * # noqa: F401, F403
5
+
6
+ # Before anything registers a callback: see the module for the hang it prevents.
7
+ from . import offline_protocol as _generated
8
+ from ._callback_reentrancy import make_handle_maps_reentrant as _make_reentrant
9
+
10
+ _make_reentrant(_generated)
11
+ del _generated, _make_reentrant
12
+
13
+ # Platform managers
14
+ from .secure_storage import SecureStorage # noqa: F401
15
+ from .state_storage import AppStateStorage # noqa: F401
16
+ from .storage_namespace import account_storage_namespace # noqa: F401
17
+ from .transport_manager import TransportManager, TransportState # noqa: F401
18
+ from .internet_manager import InternetManager # noqa: F401
19
+ from .peer_stream_manager import PeerEntry, PeerStreamManager # noqa: F401
20
+ from .ble_manager import BleManager # noqa: F401
21
+ from .ble_peripheral import BlePeripheral # noqa: F401
22
+ from .protocol_manager import ProtocolManager # noqa: F401
@@ -0,0 +1,64 @@
1
+ """Makes the generated callback handle map safe to re-enter.
2
+
3
+ The invariant: freeing a core object must never block, wherever the
4
+ interpreter decides to free it.
5
+
6
+ The generated bindings keep every callback object in one handle map, guarded
7
+ by a ``threading.Lock``. Rust takes that lock through the map on every
8
+ callback it makes (a lookup), and once more when it drops a callback (a
9
+ removal). The collector runs between any two bytecodes, the ones inside that
10
+ critical section included. When it finalizes a core object there, the core's
11
+ drop releases the callbacks it holds, each release calls back into the map,
12
+ and the map's lock is already held by the very thread that is asking for it.
13
+ A plain lock does not let its own holder in again, so the thread waits for
14
+ itself and the process hangs.
15
+
16
+ A core object reaches the collector whenever it is part of a reference
17
+ cycle: an event handler that is a method of the object owning the manager,
18
+ or an exception whose traceback names the manager. None of that is unusual.
19
+
20
+ A re-entrant lock removes the wait. Re-entry here is removal only (a
21
+ finalizer drops callbacks, it never registers one), and each of the map's
22
+ critical sections is a single dictionary operation, or a read followed by an
23
+ insert under a fresh handle, so an inner removal cannot leave an outer
24
+ operation looking at a half-changed map.
25
+
26
+ The generated file cannot carry this itself: it is regenerated from the UDL,
27
+ and the drift gate compares it byte for byte.
28
+ """
29
+
30
+ from __future__ import annotations
31
+
32
+ import threading
33
+ from types import ModuleType
34
+ from typing import Any
35
+
36
+
37
+ def handle_maps(generated: ModuleType) -> list[Any]:
38
+ """Every handle map the generated module holds, at module level or as a
39
+ class attribute."""
40
+ kind = getattr(generated, "_UniffiHandleMap", None)
41
+ if kind is None:
42
+ return []
43
+ found: list[Any] = []
44
+ for value in list(vars(generated).values()):
45
+ if isinstance(value, kind):
46
+ found.append(value)
47
+ elif isinstance(value, type):
48
+ found.extend(
49
+ attribute
50
+ for attribute in list(vars(value).values())
51
+ if isinstance(attribute, kind)
52
+ )
53
+ return found
54
+
55
+
56
+ def make_handle_maps_reentrant(generated: ModuleType) -> int:
57
+ """Gives every handle map a re-entrant lock. Returns how many it found.
58
+
59
+ Called once, when the package is imported, before any callback exists.
60
+ """
61
+ maps = handle_maps(generated)
62
+ for handle_map in maps:
63
+ handle_map._lock = threading.RLock()
64
+ return len(maps)
@@ -0,0 +1,207 @@
1
+ """Whether this connection proves its ``off1…`` address to the relay, and the
2
+ exact bytes it signs to do it.
3
+
4
+ Mirrors ``bindings/react-native/ios/AddressDeclarationPolicy.swift`` and
5
+ ``android/src/main/java/com/offlineprotocol/AddressDeclarationPolicy.kt``.
6
+ Keep the three in sync.
7
+
8
+ Why the declaration exists
9
+ --------------------------
10
+
11
+ The relay authenticates a JWT and knows the connection by its *account name*,
12
+ but since the addressing cutover the core stamps ``Message.sender`` with
13
+ ``local_address()``. A relay that attributes an inbound frame by account name
14
+ therefore hands the receiver a ``transport_peer_id`` that cannot match the
15
+ sender it is strict-matched against in ``validate_transport_sender``, and every
16
+ security-gated control frame (``__MLS_KEY_PKG__``, ``__MLS_WELCOME__``) is
17
+ rejected, so no MLS session can be established over the relay at all. Declaring
18
+ closes that, and is also what makes an ``off1…`` recipient resolvable in the
19
+ relay's registry.
20
+
21
+ Why the account name is inside the signed bytes
22
+ -----------------------------------------------
23
+
24
+ The signing key here is the identity key that also signs mesh control frames
25
+ under ``offline-ctrl-v1``. If the proof were a signature over a bare
26
+ relay-chosen challenge, a hostile relay could hand out a challenge shaped like a
27
+ control-frame payload and harvest a signature that replays as a control frame
28
+ from this peer. Binding the domain *and* the account makes the signature
29
+ meaningful only as "this account, on this relay, holds this key": it cannot be
30
+ replayed under another account, nor onto another connection, since the challenge
31
+ is minted per connection.
32
+
33
+ The layout is fixed by the relay's ``address_binding::address_proof_payload``
34
+ and pinned there by a hex vector, which
35
+ ``test_address_declaration.py::test_proof_payload_matches_the_pinned_relay_vector``
36
+ mirrors byte for byte. Neither side may change it alone.
37
+
38
+ Why every failure is a skip rather than an error
39
+ ------------------------------------------------
40
+
41
+ A connection that does not declare keeps working exactly as it did before
42
+ addresses existed: the relay attributes it by account name, which is the legacy
43
+ path and still the only path an older relay has. So the absence of a capability,
44
+ of a challenge, or of a local identity is a reason to stay quiet, not to fail a
45
+ connection that is otherwise fine.
46
+ """
47
+
48
+ from __future__ import annotations
49
+
50
+ import base64
51
+ import json
52
+ from dataclasses import dataclass
53
+ from typing import Any, Union
54
+
55
+ # The relay capability token gating the whole exchange. A relay that does not
56
+ # advertise it also omits ``address_challenge``, and would parse a
57
+ # ``DeclareAddress`` into nothing and answer nothing, so the token is the tell,
58
+ # not a timeout.
59
+ CAPABILITY = "address_routing_v1"
60
+
61
+ # Domain separator prefixing the signed payload. Must not prefix, nor be
62
+ # prefixed by, **either** of the core's control-frame domains,
63
+ # ``offline-ctrl-v1`` and ``offline-ctrl-v2``; the relay pins that relation in
64
+ # ``the_proof_domain_cannot_collide_with_control_message_signing``.
65
+ PROOF_DOMAIN = b"offline-relay-addr-v1"
66
+
67
+ # The relay mints exactly this many challenge bytes. A frame carrying any other
68
+ # length is malformed, and signing it would produce a proof that cannot verify,
69
+ # so it is better to skip and say so.
70
+ CHALLENGE_LENGTH = 32
71
+
72
+
73
+ class Reason:
74
+ """Stable diagnostic reasons, shared with the Swift and Kotlin mirrors so a
75
+ field report reproduces under the same string on all three platforms.
76
+
77
+ The vocabulary diverges at two points, both deliberate. Swift and Kotlin
78
+ also define ``frame_unserializable``, which Python cannot reach:
79
+ ``json.dumps`` over three ``str`` values is total, where
80
+ ``JSONSerialization`` and ``JSONObject`` are fallible, so the constant
81
+ would be a token nothing can ever emit. Going the other way,
82
+ ``connection_replaced`` is Python-only: the other two bridges make the same
83
+ stale-socket check but return from it silently, so there is no shared
84
+ string to match.
85
+ """
86
+
87
+ #: The relay does not advertise ``address_routing_v1``, an older
88
+ #: deployment. Expected, and the reason this is not an error.
89
+ CAPABILITY_ABSENT = "capability_absent"
90
+ #: Capability advertised but no ``address_challenge`` came with it.
91
+ CHALLENGE_ABSENT = "challenge_absent"
92
+ #: The challenge was not standard base64, or did not decode to exactly
93
+ #: :data:`CHALLENGE_LENGTH` bytes.
94
+ CHALLENGE_MALFORMED = "challenge_malformed"
95
+ #: The ``Authenticated`` frame carried no account name to bind the proof
96
+ #: to. Never sign a locally-chosen substitute here: the relay verifies
97
+ #: against the name *it* resolved, so a guess produces a signature that
98
+ #: cannot verify and is indistinguishable, in the relay's logs, from an
99
+ #: attack.
100
+ ACCOUNT_ABSENT = "account_absent"
101
+ #: ``local_address()`` was None, so MLS is not initialized and there is no
102
+ #: identity to prove. An app running with encryption disabled stays in
103
+ #: account-name space by construction.
104
+ ADDRESS_UNAVAILABLE = "address_unavailable"
105
+ #: The identity key or the signature could not be produced.
106
+ SIGNING_FAILED = "signing_failed"
107
+ #: The socket that was handed the challenge is no longer the live one.
108
+ #: Its successor carries its own ``Authenticated`` frame, and its own
109
+ #: challenge, so this connection has nothing to prove.
110
+ CONNECTION_REPLACED = "connection_replaced"
111
+
112
+
113
+ @dataclass(frozen=True)
114
+ class Declare:
115
+ """Sign :func:`proof_payload` for these values and send the declaration."""
116
+
117
+ account: str
118
+ challenge: bytes
119
+
120
+
121
+ @dataclass(frozen=True)
122
+ class Skip:
123
+ """Send nothing. ``reason`` is one of :class:`Reason`."""
124
+
125
+ reason: str
126
+
127
+
128
+ Outcome = Union[Declare, Skip]
129
+
130
+
131
+ def decide(
132
+ capabilities: Any,
133
+ address_challenge: str | None,
134
+ username: str | None,
135
+ ) -> Outcome:
136
+ """Decide whether this connection can declare, from the ``Authenticated``
137
+ frame alone.
138
+
139
+ Deliberately does **not** take the local address: this runs before any FFI
140
+ call so that the common skip (an older relay) costs no acquisition of the
141
+ protocol mutex. The caller fetches the address only after a :class:`Declare`
142
+ and reports :attr:`Reason.ADDRESS_UNAVAILABLE` if it is None.
143
+
144
+ :param capabilities: the ``capabilities`` field, verbatim and untrusted.
145
+ :param address_challenge: the ``address_challenge`` field, base64 of the raw
146
+ challenge bytes, absent on relays without the capability.
147
+ :param username: the ``username`` field **as the relay sent it**. Callers
148
+ must not substitute a local fallback (see :attr:`Reason.ACCOUNT_ABSENT`).
149
+ """
150
+ # A relay is free to send anything. `in` over a str is a substring test, so
151
+ # a scalar "not_address_routing_v1" would satisfy a bare membership check;
152
+ # require the JSON array the schema promises.
153
+ if not isinstance(capabilities, list) or CAPABILITY not in capabilities:
154
+ return Skip(Reason.CAPABILITY_ABSENT)
155
+ if not address_challenge:
156
+ return Skip(Reason.CHALLENGE_ABSENT)
157
+ try:
158
+ # Standard alphabet, padding required: the relay decodes with the same,
159
+ # and rejects base64url or unpadded input. `validate=True` is what makes
160
+ # this a rejection rather than a silent discard of stray characters.
161
+ challenge = base64.b64decode(address_challenge, validate=True)
162
+ except Exception:
163
+ return Skip(Reason.CHALLENGE_MALFORMED)
164
+ if len(challenge) != CHALLENGE_LENGTH:
165
+ return Skip(Reason.CHALLENGE_MALFORMED)
166
+ if not username:
167
+ return Skip(Reason.ACCOUNT_ABSENT)
168
+ return Declare(account=username, challenge=challenge)
169
+
170
+
171
+ def proof_payload(account: str, challenge: bytes) -> bytes:
172
+ """The exact bytes the relay verifies the signature over.
173
+
174
+ ``"offline-relay-addr-v1" || u32be(len(account.utf8)) || account.utf8 || challenge``
175
+
176
+ No separators, no terminators. The length prefix is what makes the
177
+ concatenation unambiguous: without it, an account name ending in bytes that
178
+ look like the start of a challenge could be re-split, so two different
179
+ (account, challenge) pairs would share one payload.
180
+ """
181
+ account_bytes = account.encode("utf-8")
182
+ # Big-endian, and of the UTF-8 *byte* count, not the character count, which
183
+ # differs for any non-ASCII account name.
184
+ return (
185
+ PROOF_DOMAIN
186
+ + len(account_bytes).to_bytes(4, "big")
187
+ + account_bytes
188
+ + challenge
189
+ )
190
+
191
+
192
+ def declaration_json(address: str, public_key: bytes, signature: bytes) -> str:
193
+ """The ``DeclareAddress`` frame, serialized.
194
+
195
+ Owns the base64 encoding so the wire contract lives in one place per
196
+ platform: standard alphabet, padded, no line breaks. A 32-byte key encodes
197
+ to 44 characters and a 64-byte signature to 88. The relay decodes with a
198
+ strict engine and refuses anything else.
199
+ """
200
+ return json.dumps(
201
+ {
202
+ "type": "DeclareAddress",
203
+ "address": address,
204
+ "public_key": base64.b64encode(public_key).decode("ascii"),
205
+ "signature": base64.b64encode(signature).decode("ascii"),
206
+ }
207
+ )