offline-protocol-sdk 0.28.0__py3-none-win_amd64.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/local_api/__init__.py +34 -0
  13. offline_protocol_sdk/local_api/authz.py +180 -0
  14. offline_protocol_sdk/local_api/cli.py +171 -0
  15. offline_protocol_sdk/local_api/codec.py +210 -0
  16. offline_protocol_sdk/local_api/dispatch.py +537 -0
  17. offline_protocol_sdk/local_api/mux.py +239 -0
  18. offline_protocol_sdk/local_api/server.py +546 -0
  19. offline_protocol_sdk/local_api/session.py +86 -0
  20. offline_protocol_sdk/local_api/table.py +849 -0
  21. offline_protocol_sdk/offline_protocol.py +13508 -0
  22. offline_protocol_sdk/peer_stream_manager.py +1303 -0
  23. offline_protocol_sdk/presence_watch_policy.py +102 -0
  24. offline_protocol_sdk/protocol_manager.py +1108 -0
  25. offline_protocol_sdk/relay_answer_prefixes.py +61 -0
  26. offline_protocol_sdk/secure_storage.py +551 -0
  27. offline_protocol_sdk/services.py +195 -0
  28. offline_protocol_sdk/state_storage.py +452 -0
  29. offline_protocol_sdk/storage_namespace.py +33 -0
  30. offline_protocol_sdk/transport_manager.py +138 -0
  31. offline_protocol_sdk/uniffi.dll +0 -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,437 @@
1
+ """The gateway daemon contract's decisions and frame shapes, with no socket
2
+ and no FFI, so they can be unit-tested.
3
+
4
+ A port of ``GatewayAttachPolicy.swift`` and ``GatewayAttachPolicy.kt``. The
5
+ manager (``gateway_manager.py``) owns the socket, the tasks and the
6
+ lifecycle; everything here is a function of its arguments. See
7
+ ``docs/spec/gateway-contract.md``.
8
+
9
+ **What is deliberately not here: the signed proof.** The bytes a device
10
+ signs to attach are built and signed in the core, behind
11
+ ``gateway_address_declaration(challenge)``. The relay's equivalent had to
12
+ live on the binding side because it commits the relay's account name, which
13
+ only a bridge knows. This one commits our own address, so it exists once,
14
+ where the conformance vectors can pin it, and a Rust guard refuses the
15
+ signing domain's name in this file. What is left here is the framing around
16
+ it.
17
+
18
+ The numbers below are hand-mirrored in three languages with no compiler
19
+ between them (C5). ``test_gateway_attach_policy.py`` pins each as a literal,
20
+ and the Rust guard ``gateway_manager_constants_match_across_both_bridges``
21
+ reads this file beside the Swift and Kotlin policies and holds the verdict
22
+ timeout under the core's own expiry.
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import base64
28
+ import binascii
29
+ import json
30
+ import re
31
+ from dataclasses import dataclass
32
+ from enum import Enum
33
+ from typing import Any
34
+
35
+ # -- Wire constants ----------------------------------------------------------
36
+
37
+ #: The contract version this client speaks, sent on ``Identify``.
38
+ PROTOCOL_VERSION = 1
39
+
40
+ #: Bytes of challenge the gateway mints per connection. A declaration is not
41
+ #: attempted for anything else: the core refuses to sign it, and finding that
42
+ #: out from a raised error is worse than not asking.
43
+ CHALLENGE_LENGTH = 32
44
+
45
+ #: How long the whole handshake may take, in seconds, from ``Identify`` to
46
+ #: ``StatusUpdate(connected)``.
47
+ #:
48
+ #: Far shorter than the 60 s connection timeout, and deliberately so: TCP to
49
+ #: the daemon is a LAN hop, and a gateway that has accepted the socket but
50
+ #: not finished the handshake is not slow, it is broken or wedged. Waiting a
51
+ #: minute to find that out means a minute of a carrier the selector has been
52
+ #: told nothing about.
53
+ ATTACH_TIMEOUT = 10.0
54
+
55
+ #: How long, in seconds, a submitted frame may go without a verdict before
56
+ #: this client treats the gateway's silence as a failure.
57
+ #:
58
+ #: **Must stay below the core's 120 s pending-confirmation timeout**, which
59
+ #: is the other clock on the same frame. If this were the longer of the two,
60
+ #: the core would expire the frame first and count it a failure, and the
61
+ #: verdict arriving afterwards would confirm or fail a message id the core
62
+ #: had already settled. The Rust guard pins both this number and that
63
+ #: relationship.
64
+ VERDICT_TIMEOUT = 60.0
65
+
66
+ #: Frames submitted but not yet answered. The gateway answers every
67
+ #: submission, so this bounds nothing but memory and the size of the loss
68
+ #: when a connection dies; it is also roughly what the core's own session
69
+ #: bootstrap bursts, so a smaller number would throttle the one case that
70
+ #: matters most.
71
+ MAX_IN_FLIGHT = 8
72
+
73
+ #: Longest line this client will assemble before abandoning the stream.
74
+ #:
75
+ #: A frame at the gateway's cap arrives base64-encoded, so 4/3 of its size
76
+ #: plus the JSON around it, and the buffer has to hold the largest one the
77
+ #: gateway can legitimately send. Past this the stream is not
78
+ #: resynchronisable: the rest of the over-long line would be read as a fresh
79
+ #: one, so the connection goes rather than the line.
80
+ MAX_LINE_BYTES = 1 << 20
81
+
82
+ #: Capability bounds, matching the relay's, which is what the contract points
83
+ #: at rather than inventing a second pair.
84
+ MAX_CAPABILITY_TOKENS = 64
85
+ MAX_CAPABILITY_TOKEN_BYTES = 128
86
+
87
+ #: Peers a gateway answers per ``CheckPresence``. Asking about more only
88
+ #: guarantees silence for the ones past the cap.
89
+ MAX_PRESENCE_PEERS = 64
90
+
91
+ #: Longest ``AddressDeclared`` echo a manager hands to the core. An address
92
+ #: is 44 characters; the bound is what keeps a hostile echo, which may be as
93
+ #: long as a line, out of the core's log and security event.
94
+ MAX_ADDRESS_BYTES = 128
95
+
96
+ #: Longest remote-chosen reason text a diagnostic carries. The core bounds
97
+ #: what it logs the same way; a diagnostic is a second log.
98
+ MAX_DIAGNOSTIC_REASON_CHARS = 256
99
+
100
+ # -- The core's failure-reason vocabulary ------------------------------------
101
+ #
102
+ # Exact literals the core classifies on (``SEND_FAIL_REASON_*`` in the engine).
103
+ # ``recipient_unreachable`` is matched by prefix and the gateway's own text
104
+ # may follow it; the other three are matched exactly and carry nothing.
105
+
106
+ #: The verdict prefix that parks a message and offers it to the mesh.
107
+ RECIPIENT_UNREACHABLE = "recipient_unreachable"
108
+ #: ``MessageSent { pushed: true }``: accepted, handed to a device push, not
109
+ #: delivered to a session. Parks a plain DM; never a failure.
110
+ RELAY_PUSHED = "relay_pushed"
111
+ #: ``DeliveryError { stored: true }``: the socket write missed but the
112
+ #: gateway's mailbox holds the frame and re-sends it on the recipient's next
113
+ #: attach. The unreachable verdict, parked without a reachability probe.
114
+ RELAY_STORED = "relay_stored"
115
+ #: ``MessageSent { pushed: true, stored: true }``: both of the above.
116
+ RELAY_PUSHED_STORED = "relay_pushed_stored"
117
+ #: What a frame the gateway never answered is failed with. The core
118
+ #: classifies it to its generic transport failure and retries.
119
+ GATEWAY_SILENT = f"gateway_silent: no verdict within {int(VERDICT_TIMEOUT)}s"
120
+
121
+
122
+ # -- Remote strings ----------------------------------------------------------
123
+
124
+
125
+ def utf8_bytes(text: str) -> bytes | None:
126
+ """``text`` as UTF-8, or ``None`` when it cannot be encoded.
127
+
128
+ ``json.loads`` accepts a lone surrogate escape (``"\\ud800"``) and hands
129
+ back a ``str`` that ``encode("utf-8")`` refuses, and the generated FFI
130
+ refuses it the same way when a string is lowered. A gateway can put one
131
+ in any string field, so every remote string is passed through here
132
+ before it is measured or handed to the core: a frame that carries one
133
+ is malformed and is skipped, and it must never cost more than that.
134
+ """
135
+ try:
136
+ return text.encode("utf-8")
137
+ except UnicodeEncodeError:
138
+ return None
139
+
140
+
141
+ # -- Attach ------------------------------------------------------------------
142
+
143
+
144
+ class SkipReason:
145
+ """Why a declaration was not attempted. Reported as a diagnostic; the
146
+ carrier stays unavailable either way."""
147
+
148
+ ADDRESS_UNAVAILABLE = "address_unavailable"
149
+ CHALLENGE_ABSENT = "challenge_absent"
150
+ CHALLENGE_MALFORMED = "challenge_malformed"
151
+ CHALLENGE_WRONG_SIZE = "challenge_wrong_size"
152
+ SIGNING_FAILED = "signing_failed"
153
+ FRAME_UNSERIALIZABLE = "frame_unserializable"
154
+
155
+
156
+ @dataclass(frozen=True)
157
+ class Declare:
158
+ """A ``Challenge`` frame yielded a challenge worth signing."""
159
+
160
+ challenge: bytes
161
+
162
+
163
+ @dataclass(frozen=True)
164
+ class Skip:
165
+ """A ``Challenge`` frame that cannot be answered, and why."""
166
+
167
+ reason: str
168
+
169
+
170
+ class BindingOutcome(Enum):
171
+ """What a gateway's ``AddressDeclared`` echo says about this device.
172
+
173
+ The same three answers the core reports on, decided again here because
174
+ the two act on different things: the core emits the security warning,
175
+ and the manager decides whether this carrier can be offered at all.
176
+ """
177
+
178
+ #: The gateway bound the address we declared. The session is proven.
179
+ BOUND = "bound"
180
+ #: It bound something else. A security event, not a retry.
181
+ MISMATCH = "mismatch"
182
+ #: We hold no address to compare against, so nothing here was ever
183
+ #: declared by us.
184
+ UNKNOWN_LOCAL = "unknown_local"
185
+
186
+
187
+ def decode_challenge(frame: dict[str, Any]) -> Declare | Skip:
188
+ """Reads the challenge out of a ``Challenge`` frame.
189
+
190
+ The size is checked here as well as in the core because the two refusals
191
+ mean different things to the reader: this one says the gateway is not
192
+ speaking the contract, and the core's says something asked it to sign a
193
+ payload it should not.
194
+ """
195
+ encoded = frame.get("challenge")
196
+ if not isinstance(encoded, str) or not encoded:
197
+ return Skip(SkipReason.CHALLENGE_ABSENT)
198
+ try:
199
+ challenge = base64.b64decode(encoded, validate=True)
200
+ except (binascii.Error, ValueError):
201
+ return Skip(SkipReason.CHALLENGE_MALFORMED)
202
+ if len(challenge) != CHALLENGE_LENGTH:
203
+ return Skip(SkipReason.CHALLENGE_WRONG_SIZE)
204
+ return Declare(challenge)
205
+
206
+
207
+ def binding_outcome(declared: str, local: str | None) -> BindingOutcome:
208
+ """Compares the gateway's echo with this device's own address."""
209
+ if not local:
210
+ return BindingOutcome.UNKNOWN_LOCAL
211
+ return BindingOutcome.BOUND if declared == local else BindingOutcome.MISMATCH
212
+
213
+
214
+ def capability_tokens(frame: dict[str, Any]) -> list[str]:
215
+ """The capability tokens worth storing, bounded on the way in.
216
+
217
+ Oversized tokens are dropped **before** the count is applied, so a
218
+ gateway cannot pad its list to evict the tokens that matter.
219
+ """
220
+ raw = frame.get("tokens")
221
+ if not isinstance(raw, list):
222
+ return []
223
+ kept: list[str] = []
224
+ for token in raw:
225
+ if not isinstance(token, str) or not token:
226
+ continue
227
+ encoded = utf8_bytes(token)
228
+ if encoded is None or len(encoded) > MAX_CAPABILITY_TOKEN_BYTES:
229
+ continue
230
+ kept.append(token)
231
+ return kept[:MAX_CAPABILITY_TOKENS]
232
+
233
+
234
+ # -- Message ids -------------------------------------------------------------
235
+
236
+ _MESSAGE_ID_RE = re.compile(r"[A-Za-z0-9._-]{1,64}")
237
+
238
+
239
+ def sanitize_message_id(candidate: str | None) -> str | None:
240
+ """The gateway's own rule for a client-supplied id: 1 to 64 characters
241
+ of ``[A-Za-z0-9._-]``.
242
+
243
+ Applied before sending, not after: an id the gateway would refuse is
244
+ replaced *there* by one it mints, and the verdict then comes back under
245
+ a name nothing here is waiting on. Message ids are UUIDs, which pass;
246
+ this is what keeps that from being an assumption.
247
+ """
248
+ if not candidate:
249
+ return None
250
+ return candidate if _MESSAGE_ID_RE.fullmatch(candidate) else None
251
+
252
+
253
+ # -- Frames this client sends ------------------------------------------------
254
+
255
+
256
+ def _serialize(frame: dict[str, Any]) -> str:
257
+ return json.dumps(frame, separators=(",", ":"))
258
+
259
+
260
+ def identify_json(device_id: str) -> str:
261
+ return _serialize(
262
+ {
263
+ "type": "Identify",
264
+ "device_id": device_id,
265
+ "protocol_version": PROTOCOL_VERSION,
266
+ }
267
+ )
268
+
269
+
270
+ def declaration_json(address: str, public_key: bytes, signature: bytes) -> str:
271
+ return _serialize(
272
+ {
273
+ "type": "DeclareAddress",
274
+ "address": address,
275
+ "public_key": base64.b64encode(public_key).decode("ascii"),
276
+ "signature": base64.b64encode(signature).decode("ascii"),
277
+ }
278
+ )
279
+
280
+
281
+ def send_message_json(
282
+ message_id: str, recipient: str, content: str, reply_to_msg: str | None
283
+ ) -> str:
284
+ frame: dict[str, Any] = {
285
+ "type": "SendMessage",
286
+ "recipient": recipient,
287
+ "content": content,
288
+ "encoding": "base64",
289
+ "message_id": message_id,
290
+ }
291
+ if reply_to_msg:
292
+ frame["reply_to_msg"] = reply_to_msg
293
+ return _serialize(frame)
294
+
295
+
296
+ def check_presence_json(peers: list[str]) -> str | None:
297
+ """One frame for the whole batch, which is the shape the contract takes
298
+ and the opposite of the relay's one-peer-per-frame ``CheckPresence``."""
299
+ asked = list(peers[:MAX_PRESENCE_PEERS])
300
+ if not asked:
301
+ return None
302
+ return _serialize({"type": "CheckPresence", "peers": asked})
303
+
304
+
305
+ # -- Frames this client reads ------------------------------------------------
306
+
307
+
308
+ @dataclass(frozen=True)
309
+ class Verdict:
310
+ """A verdict: the id it settles, and the reason if it is a refusal."""
311
+
312
+ message_id: str
313
+ #: ``None`` for ``MessageSent``, the gateway's own text for
314
+ #: ``DeliveryError``. Passed to the core verbatim: the classifier matches
315
+ #: the ``recipient_unreachable`` prefix and discards the rest, so nothing
316
+ #: here needs to understand it.
317
+ reason: str | None
318
+ recipient: str | None
319
+ #: ``MessageSent { pushed: true }``: accepted, but handed to a device
320
+ #: push rather than a session. Absent reads as ``False``, never unknown.
321
+ pushed: bool = False
322
+ #: The gateway's mailbox holds this one frame and will re-send it. A
323
+ #: statement about the named id alone, never about the recipient.
324
+ stored: bool = False
325
+
326
+ @property
327
+ def sent(self) -> bool:
328
+ return self.reason is None
329
+
330
+
331
+ def parse_verdict(frame: dict[str, Any], frame_type: str) -> Verdict | None:
332
+ message_id = frame.get("message_id")
333
+ if not isinstance(message_id, str) or not message_id:
334
+ # Nothing to settle. The gateway mints an id for a submission that
335
+ # carried none, but this client always sends one, so a verdict
336
+ # without an id is not ours to act on.
337
+ return None
338
+ recipient = frame.get("recipient")
339
+ # A recipient the core cannot be handed (a lone surrogate) is no
340
+ # recipient: the verdict still settles its id, and nobody is watched.
341
+ if not isinstance(recipient, str) or not recipient or utf8_bytes(recipient) is None:
342
+ recipient = None
343
+ # ``is True``: the contract makes both optional booleans that default to
344
+ # false when absent, and a non-boolean is not a claim the gateway made.
345
+ pushed = frame.get("pushed") is True
346
+ stored = frame.get("stored") is True
347
+ if frame_type == "MessageSent":
348
+ return Verdict(message_id, None, recipient, pushed=pushed, stored=stored)
349
+ reason = frame.get("reason")
350
+ # A reason the core cannot be handed is reported as the bare failure,
351
+ # which the core reads as a retry: the gateway's wording was never
352
+ # load-bearing past the `recipient_unreachable` prefix, and a lone
353
+ # surrogate cannot be part of that prefix.
354
+ if not isinstance(reason, str) or not reason or utf8_bytes(reason) is None:
355
+ reason = "DeliveryError"
356
+ return Verdict(message_id, reason, recipient, pushed=False, stored=stored)
357
+
358
+
359
+ @dataclass(frozen=True)
360
+ class VerdictReport:
361
+ """What a settled verdict tells the core, decided here so the mapping
362
+ from the wire's two flags to the core's four tokens is testable without
363
+ a socket.
364
+
365
+ ``reason`` is ``None`` for a plain ``MessageSent``, which the core hears
366
+ as a confirmation; every other verdict is a reported failure under
367
+ ``reason``. ``watch_recipient`` says the recipient is worth a presence
368
+ watch and an offline presence fact: the gateway pushes a
369
+ ``PresenceStatus`` when a watched peer attaches, and that answer is what
370
+ un-parks the message this verdict just parked.
371
+ """
372
+
373
+ reason: str | None
374
+ watch_recipient: bool
375
+
376
+ @property
377
+ def confirmed(self) -> bool:
378
+ return self.reason is None
379
+
380
+
381
+ def verdict_report(verdict: Verdict) -> VerdictReport:
382
+ """The core's token for a verdict.
383
+
384
+ The relay client's own mapping, so a gateway that implements a mailbox
385
+ or a push is read the way the relay is:
386
+
387
+ * ``MessageSent`` with neither flag confirms the frame.
388
+ * ``MessageSent { pushed }`` is ``relay_pushed``, or
389
+ ``relay_pushed_stored`` with ``stored`` as well: a park, never a
390
+ failure, so a connection request is not fast-failed for a frame the
391
+ push may have delivered.
392
+ * ``DeliveryError { stored }`` is ``relay_stored``: the unreachable
393
+ verdict for the one frame the gateway holds, parked without the
394
+ reachability probe its own redelivery makes pointless.
395
+ * Any other ``DeliveryError`` carries the gateway's reason verbatim; the
396
+ core classifies on the ``recipient_unreachable`` prefix and drops the
397
+ rest at that boundary.
398
+ """
399
+ if verdict.sent:
400
+ if not verdict.pushed:
401
+ return VerdictReport(None, False)
402
+ token = RELAY_PUSHED_STORED if verdict.stored else RELAY_PUSHED
403
+ return VerdictReport(token, True)
404
+ if verdict.stored:
405
+ return VerdictReport(RELAY_STORED, True)
406
+ reason = verdict.reason or "DeliveryError"
407
+ return VerdictReport(reason, reason.startswith(RECIPIENT_UNREACHABLE))
408
+
409
+
410
+ @dataclass(frozen=True)
411
+ class PresenceAnswer:
412
+ peer: str
413
+ online: bool
414
+ last_seen_ms: int | None
415
+
416
+
417
+ def parse_presence(frame: dict[str, Any]) -> PresenceAnswer | None:
418
+ peer = frame.get("peer")
419
+ if not isinstance(peer, str) or not peer or utf8_bytes(peer) is None:
420
+ return None
421
+ # A missing or non-boolean ``online`` is not readable as "offline": that
422
+ # would manufacture a claim the gateway did not make.
423
+ online = frame.get("online")
424
+ if not isinstance(online, bool):
425
+ return None
426
+ raw_seen = frame.get("last_seen_ms")
427
+ last_seen: int | None
428
+ if isinstance(raw_seen, bool) or not isinstance(raw_seen, (int, float)):
429
+ last_seen = None
430
+ else:
431
+ last_seen = int(raw_seen)
432
+ return PresenceAnswer(peer, online, last_seen)
433
+
434
+
435
+ def bounded_reason(reason: str) -> str:
436
+ """Remote-chosen text, cut to what a diagnostic may carry."""
437
+ return reason[:MAX_DIAGNOSTIC_REASON_CHARS]