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,184 @@
1
+ """Whether an account may inherit the pre-namespace secure store.
2
+
3
+ Scoping the store to ``(app_id, user_id)`` renamed it. Left alone, the first
4
+ launch after an upgrade would find an empty store, mint a *new* MLS signing
5
+ identity, and abandon every session, group, and TOFU pin the install already
6
+ had — peers still holding the old pin would then reject it. So the new store
7
+ adopts the old one instead.
8
+
9
+ Adoption is read-through rather than a bulk copy on purpose. The legacy store's
10
+ key types are not a closed set (OpenMLS contributes its own labels, and the
11
+ ``keyring`` backends cannot enumerate at all), so there is no reliable way to
12
+ walk it. A miss in the new store consults the legacy one and promotes what it
13
+ finds, which is naturally idempotent and resumable.
14
+
15
+ The legacy store was shared by every account on the install, so at most one
16
+ account can inherit it. The first to launch writes a claim *and reads it back* —
17
+ an unverified claim is not an adoption, see :func:`confirm_claim`; a second
18
+ account seeing a foreign claim gets a fresh identity — correct, because the
19
+ legacy store never held a separable identity for it — but must say so out loud
20
+ rather than rotate silently.
21
+
22
+ Read-through is also what the SDK's *protocol-state* adoption sweep rides on:
23
+ pre-split delivery state sits in this same un-namespaced store, and the sweep
24
+ enumerates the namespaced handle. So a conflict costs more than the MLS
25
+ identity — that account also comes up with an empty outbox, an empty pending
26
+ queue, and an empty **block list**, every previously blocked peer unblocked.
27
+ Say all of it, not just the identity.
28
+
29
+ Keep this policy in sync with ``LegacyStoreAdoption.swift`` and
30
+ ``LegacyStoreAdoption.kt``.
31
+ """
32
+
33
+ from __future__ import annotations
34
+
35
+ from dataclasses import dataclass
36
+ from enum import Enum
37
+
38
+ #: Key under which an adopting account records its claim in the *legacy* store.
39
+ #: Namespaced away from any real key type so it can never collide with MLS
40
+ #: material, and filtered out of read-through and listing.
41
+ CLAIM_KEY_TYPE = "__offline_protocol_migration__"
42
+ CLAIM_KEY_ID = "claimed_by"
43
+
44
+ #: Key type under which a *namespaced* store records that a legacy copy
45
+ #: survived its own deletion.
46
+ #:
47
+ #: ``SecureStorage.delete`` removes both copies, because read-through would
48
+ #: otherwise hand back key material the caller believes is gone. The legacy
49
+ #: removal can fail on its own — a backend that refuses the delete, a locked
50
+ #: credential store — and it cannot be reported by failing the delete: core
51
+ #: treats a storage delete as fatal almost everywhere (OpenMLS aborts Welcome
52
+ #: processing and every commit merge on one), and there is no retry anywhere to
53
+ #: fall back on. So a failed legacy removal is recorded instead: a tombstone
54
+ #: makes read-through treat that key as absent, which is the guarantee
55
+ #: ``delete`` actually owes its caller. The corpse in the legacy store is inert.
56
+ #:
57
+ #: Tombstones live only in the namespaced store, are never promoted, and are
58
+ #: never reported as key material.
59
+ TOMBSTONE_KEY_TYPE = "__offline_protocol_tombstone__"
60
+
61
+
62
+ def tombstone_key_id(key_type: str, key_id: str) -> str:
63
+ """The tombstone entry naming one legacy key.
64
+
65
+ Joined exactly like the stores' own account keys, so it inherits their
66
+ existing (accepted) ambiguity between ``("a", "b:c")`` and ``("a:b", "c")``
67
+ rather than introducing a new one. A collision would over-suppress a legacy
68
+ read — degraded, never a resurrection.
69
+ """
70
+
71
+ return f"{key_type}:{key_id}"
72
+
73
+
74
+ class TombstoneState(Enum):
75
+ """What a tombstone read established about one legacy key.
76
+
77
+ Three-way for the same reason the wipe's claim classification is: the two
78
+ non-``ABSENT`` answers authorise different things. Both suppress
79
+ read-through, because a read that failed cannot prove read-through is safe.
80
+ Only ``RECORDED`` additionally authorises *deleting* the legacy copy, and
81
+ that asymmetry is the point — a failed read is not evidence that a tombstone
82
+ exists, so deleting on it would destroy the last copy of a key that was
83
+ legitimately inheritable, which on a first post-upgrade launch can be the
84
+ MLS signing identity. Suppression costs a read-through until the store
85
+ recovers and the next read heals it; the deletion cannot be walked back.
86
+ """
87
+
88
+ #: A tombstone is recorded: this key's legacy copy outlived a delete.
89
+ RECORDED = "recorded"
90
+ #: No tombstone recorded. Read-through may proceed.
91
+ ABSENT = "absent"
92
+ #: The tombstone could not be read, so it is unknown either way.
93
+ UNREADABLE = "unreadable"
94
+
95
+ @property
96
+ def suppresses_read_through(self) -> bool:
97
+ """Whether the legacy store must not be consulted for this key."""
98
+
99
+ return self is not TombstoneState.ABSENT
100
+
101
+ @property
102
+ def allows_removal_retry(self) -> bool:
103
+ """Whether the legacy copy may be deleted on sight. Only a *confirmed*
104
+ tombstone: see the class note."""
105
+
106
+ return self is TombstoneState.RECORDED
107
+
108
+
109
+ @dataclass(frozen=True)
110
+ class Decision:
111
+ """Outcome of resolving one account's claim on the legacy store."""
112
+
113
+ #: ``"adopt"`` (unclaimed — claim it), ``"resume"`` (already ours),
114
+ #: ``"conflict"`` (another account owns it), ``"claim_unverified"`` (the
115
+ #: claim could not be recorded), or ``"none"`` (nothing to inherit).
116
+ kind: str
117
+ claimed_by: str | None = None
118
+
119
+ @property
120
+ def allows_read_through(self) -> bool:
121
+ return self.kind in ("adopt", "resume")
122
+
123
+
124
+ ADOPT = Decision("adopt")
125
+ RESUME = Decision("resume")
126
+ NONE = Decision("none")
127
+ CLAIM_UNVERIFIED = Decision("claim_unverified")
128
+
129
+
130
+ def decide(existing_claim: str | None, namespace: str) -> Decision:
131
+ if not existing_claim:
132
+ return ADOPT
133
+ if existing_claim == namespace:
134
+ return RESUME
135
+ return Decision("conflict", claimed_by=existing_claim)
136
+
137
+
138
+ def confirm_claim(read_back: str | None, namespace: str) -> Decision:
139
+ """Confirm a claim by what the legacy store reports *after* the write.
140
+
141
+ :func:`decide` returning ``ADOPT`` only means the store looked unclaimed;
142
+ it is the recorded claim that makes inheritance exclusive. A write whose
143
+ result is not read back is therefore not an adoption: if it silently
144
+ failed, the next account to launch also finds the store unclaimed, also
145
+ adopts, and the two end up sharing one MLS signing identity — and with it
146
+ each other's sessions and group state. That is strictly worse than the
147
+ conflict this claim exists to produce, so an unproven claim fails closed to
148
+ ``CLAIM_UNVERIFIED``.
149
+
150
+ The cost is a fresh identity for a launch that hit a transient store
151
+ failure. Accepted deliberately: confidentiality between two accounts on one
152
+ device outranks the sessions of an install whose credential store is
153
+ failing writes — and the same failure would break every other write this
154
+ session anyway.
155
+
156
+ *read_back* is what the legacy store reports for the claim entry once the
157
+ write returned, or ``None`` when the write raised or the read back failed.
158
+ """
159
+
160
+ if not read_back:
161
+ return CLAIM_UNVERIFIED
162
+ if read_back == namespace:
163
+ return ADOPT
164
+ return Decision("conflict", claimed_by=read_back)
165
+
166
+
167
+ def is_claim_entry(key_type: str) -> bool:
168
+ """True for the reserved claim entry, which must never be promoted into the
169
+ new store or reported by ``list_keys``."""
170
+
171
+ return key_type == CLAIM_KEY_TYPE
172
+
173
+
174
+ def is_reserved_entry(key_type: str) -> bool:
175
+ """True for either reserved entry — the legacy store's claim and the
176
+ namespaced store's tombstones.
177
+
178
+ Both are the provider's own bookkeeping rather than key material, so
179
+ neither may reach a caller: read-through skips them, ``load`` reports them
180
+ absent, and ``list_keys`` never names them. The provider reads its own
181
+ tombstones through the private primitives, which are not gated.
182
+ """
183
+
184
+ return key_type in (CLAIM_KEY_TYPE, TOMBSTONE_KEY_TYPE)
@@ -0,0 +1,34 @@
1
+ """The reference server for the local API (``docs/spec/local-api.md``).
2
+
3
+ One process owns one engine and serves any number of local applications over
4
+ JSON-RPC 2.0 on a WebSocket, on a Unix domain socket by default. See
5
+ :class:`LocalApiServer`, and ``offline-protocol-service`` for the shell entry
6
+ point.
7
+ """
8
+
9
+ from .authz import METHOD_GROUPS, Policy, ServiceOwnership # noqa: F401
10
+ from .codec import RpcError # noqa: F401
11
+ from .dispatch import BEFORE_HELLO, EXPOSED, ID_RESULTS, PLATFORM, SESSION_METHODS # noqa: F401
12
+ from .mux import HELD_TAGS, HOLD_CAPACITY, EventRouter # noqa: F401
13
+ from .server import API_VERSION, MAX_MESSAGE_SIZE, SERVER_NAME, LocalApiServer # noqa: F401
14
+ from .session import Session # noqa: F401
15
+
16
+ __all__ = [
17
+ "API_VERSION",
18
+ "BEFORE_HELLO",
19
+ "EXPOSED",
20
+ "EventRouter",
21
+ "HELD_TAGS",
22
+ "HOLD_CAPACITY",
23
+ "ID_RESULTS",
24
+ "LocalApiServer",
25
+ "MAX_MESSAGE_SIZE",
26
+ "METHOD_GROUPS",
27
+ "PLATFORM",
28
+ "Policy",
29
+ "RpcError",
30
+ "SERVER_NAME",
31
+ "SESSION_METHODS",
32
+ "ServiceOwnership",
33
+ "Session",
34
+ ]
@@ -0,0 +1,180 @@
1
+ """The three server-side rules that separate the applications behind one
2
+ identity: service ownership, space scoping and method groups.
3
+
4
+ Each is applied before a call reaches the engine, each refuses with the
5
+ engine's ``PermissionDenied``, and none has any representation on the mesh
6
+ (chapter, "Server-side rules"; bridge rule L3). The engine sees one identity
7
+ registering services and syncing spaces, exactly as it would from one
8
+ application.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from dataclasses import dataclass, field
14
+ from fnmatch import fnmatchcase
15
+ from typing import Any
16
+
17
+ from .codec import taxonomy_error
18
+
19
+ #: The named method groups an operator may deny to an application id. A
20
+ #: policy entry that is not a group name is a single method's wire name.
21
+ METHOD_GROUPS: dict[str, frozenset[str]] = {
22
+ "sign_data": frozenset({"sign_data"}),
23
+ "manual_mls": frozenset(
24
+ {
25
+ "mls_generate_key_package",
26
+ "mls_get_or_create_key_package",
27
+ "mls_import_key_package",
28
+ "mls_get_pending_key_packages",
29
+ "mls_mark_key_package_synced",
30
+ "mls_create_session",
31
+ "mls_join_session",
32
+ "mls_encrypt_for_user",
33
+ "mls_decrypt_from_user",
34
+ "mls_get_pending_welcome",
35
+ "mls_clear_pending_welcome",
36
+ "mls_decrypt",
37
+ "mls_process_welcome",
38
+ }
39
+ ),
40
+ "tuning": frozenset(
41
+ {
42
+ "set_relay_priority",
43
+ "update_relay_config",
44
+ "force_transport",
45
+ "release_transport_lock",
46
+ "update_dors_config",
47
+ "update_ack_config",
48
+ "update_retry_config",
49
+ "update_dedup_config",
50
+ }
51
+ ),
52
+ }
53
+
54
+
55
+ @dataclass
56
+ class Policy:
57
+ """The operator's configuration of the optional rules.
58
+
59
+ ``spaces`` maps an application id to the glob patterns over space ids it
60
+ may open; an application with no entry may open every space. ``denied``
61
+ maps an application id to method group names and single method names it
62
+ may not call; nothing is denied by default. ``applications`` lists ids
63
+ that have no rule of their own but are still admitted once a rule exists;
64
+ on its own it configures nothing.
65
+
66
+ An application id is self-declared per connection, so a rule keyed by
67
+ id separates applications from each other's mistakes, never from a
68
+ hostile local process, which is inside the socket boundary already.
69
+ What keeps a rule from being stepped around by a reconnect under
70
+ another name is the chapter's unlisted-id rule: once a space allow-list
71
+ or a method deny is configured, ``hello`` with an id no entry names is
72
+ refused. With neither configured, every id is admitted. Service
73
+ ownership is a runtime shadow, never a configured rule, and never counts.
74
+ """
75
+
76
+ spaces: dict[str, list[str]] = field(default_factory=dict)
77
+ denied: dict[str, list[str]] = field(default_factory=dict)
78
+ applications: list[str] = field(default_factory=list)
79
+
80
+ @classmethod
81
+ def from_dict(cls, raw: dict[str, Any] | None) -> "Policy":
82
+ raw = raw or {}
83
+ unknown = sorted(set(raw) - {"spaces", "denied", "applications"})
84
+ if unknown:
85
+ raise ValueError(f"policy has no section {unknown[0]!r}")
86
+ spaces = {str(k): [str(p) for p in v] for k, v in (raw.get("spaces") or {}).items()}
87
+ denied = {str(k): [str(m) for m in v] for k, v in (raw.get("denied") or {}).items()}
88
+ applications = [str(a) for a in (raw.get("applications") or [])]
89
+ # Imported here: dispatch imports this module. A deny that names
90
+ # nothing on the wire would otherwise deny nothing and say nothing,
91
+ # and an operator who misspelled `sign_data` would believe the
92
+ # signing oracle denied while every application still held it.
93
+ from .dispatch import EXPOSED
94
+
95
+ for app_id, names in denied.items():
96
+ for name in names:
97
+ if name not in METHOD_GROUPS and name not in EXPOSED:
98
+ raise ValueError(
99
+ f"policy denies {name!r} for {app_id!r}: not a method group "
100
+ f"({', '.join(sorted(METHOD_GROUPS))}) or an exposed method"
101
+ )
102
+ return cls(spaces=spaces, denied=denied, applications=applications)
103
+
104
+ def restricts(self) -> bool:
105
+ """Whether a space allow-list or a method deny is configured."""
106
+ return bool(self.spaces or self.denied)
107
+
108
+ def admits(self, app_id: str) -> bool:
109
+ """Whether ``hello`` may declare ``app_id``."""
110
+ if not self.restricts():
111
+ return True
112
+ return app_id in self.spaces or app_id in self.denied or app_id in self.applications
113
+
114
+ def check_admission(self, app_id: str) -> None:
115
+ if not self.admits(app_id):
116
+ raise taxonomy_error(
117
+ "PermissionDenied",
118
+ f"no rule names application {app_id!r}; rules are configured, so unnamed ids are refused",
119
+ )
120
+
121
+ def allows_space(self, app_id: str, space_id: str) -> bool:
122
+ patterns = self.spaces.get(app_id)
123
+ if patterns is None:
124
+ return True
125
+ return any(fnmatchcase(space_id, pattern) for pattern in patterns)
126
+
127
+ def denies(self, app_id: str, method: str) -> bool:
128
+ for name in self.denied.get(app_id, ()):
129
+ if name == method or method in METHOD_GROUPS.get(name, ()):
130
+ return True
131
+ return False
132
+
133
+ def check_space(self, app_id: str, space_id: str) -> None:
134
+ if not self.allows_space(app_id, space_id):
135
+ raise taxonomy_error(
136
+ "PermissionDenied",
137
+ f"space {space_id!r} is outside what {app_id!r} may open",
138
+ )
139
+
140
+ def check_method(self, app_id: str, method: str) -> None:
141
+ if self.denies(app_id, method):
142
+ raise taxonomy_error("PermissionDenied", f"{method} is denied to {app_id!r}")
143
+
144
+
145
+ class ServiceOwnership:
146
+ """A shadow of the engine's service registry, keyed by application id.
147
+
148
+ The engine has no owner on a registration and no way to enumerate them,
149
+ so this is rebuilt from the clients' calls and is empty after a restart
150
+ until they register again. An id another application already holds is
151
+ refused, which is the collision the registry exists to catch: without it
152
+ the second registration silently replaces the first in the engine and
153
+ the first application's requests start arriving at the second.
154
+ """
155
+
156
+ def __init__(self) -> None:
157
+ self._owner: dict[str, str] = {}
158
+
159
+ def owner(self, service_id: str) -> str | None:
160
+ return self._owner.get(service_id)
161
+
162
+ def claim(self, service_id: str, app_id: str) -> None:
163
+ holder = self._owner.get(service_id)
164
+ if holder is not None and holder != app_id:
165
+ raise taxonomy_error(
166
+ "PermissionDenied",
167
+ f"service {service_id!r} is registered by another application",
168
+ )
169
+ self._owner[service_id] = app_id
170
+
171
+ def release(self, service_id: str) -> None:
172
+ self._owner.pop(service_id, None)
173
+
174
+ def check(self, service_id: str, app_id: str) -> None:
175
+ holder = self._owner.get(service_id)
176
+ if holder is not None and holder != app_id:
177
+ raise taxonomy_error(
178
+ "PermissionDenied",
179
+ f"service {service_id!r} belongs to another application",
180
+ )
@@ -0,0 +1,171 @@
1
+ """``offline-protocol-service``: run the reference server from the shell.
2
+
3
+ The process owns one engine over the built-in file stores (or the platform
4
+ keyring with ``--keyring``), serves the local API on a Unix domain socket by
5
+ default, and runs until it is told to stop.
6
+
7
+ Importing this module loads the native library, because the package's own
8
+ ``__init__`` does; ``--help`` therefore needs the library present.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import argparse
14
+ import asyncio
15
+ import json
16
+ import logging
17
+ import os
18
+ import signal
19
+ import sys
20
+ from pathlib import Path
21
+ from typing import Any
22
+
23
+ from ..gateway_manager import DEFAULT_DAEMON_ADDRESS
24
+ from ..protocol_manager import ProtocolManager
25
+ from . import codec
26
+ from .authz import Policy
27
+ from .server import LocalApiServer
28
+
29
+ DEFAULT_STORE_KEY_ENV = "OFFLINE_PROTOCOL_STORE_KEY"
30
+
31
+
32
+ def default_socket_path() -> Path:
33
+ runtime = os.environ.get("XDG_RUNTIME_DIR")
34
+ base = Path(runtime) if runtime else Path.home() / ".offline-protocol"
35
+ return base / "offline-protocol" / "api.sock" if runtime else base / "api.sock"
36
+
37
+
38
+ def _load_json(path: str, what: str) -> Any:
39
+ try:
40
+ with open(path, encoding="utf-8") as handle:
41
+ return json.load(handle)
42
+ except OSError as exc:
43
+ raise SystemExit(f"cannot read the {what} at {path}: {exc}") from None
44
+ except ValueError as exc:
45
+ raise SystemExit(f"the {what} at {path} is not JSON: {exc}") from None
46
+
47
+
48
+ def build_parser() -> argparse.ArgumentParser:
49
+ parser = argparse.ArgumentParser(
50
+ prog="offline-protocol-service",
51
+ description="Serve one Offline Protocol engine to local applications over the local API.",
52
+ )
53
+ parser.add_argument("--config", required=True, help="JSON file with the ProtocolConfig fields")
54
+ carrier = parser.add_mutually_exclusive_group()
55
+ carrier.add_argument("--socket", help=f"Unix socket path (default: {default_socket_path()})")
56
+ carrier.add_argument("--tcp", type=int, metavar="PORT", help="serve on loopback TCP instead, with a token")
57
+ parser.add_argument("--tcp-host", default="127.0.0.1", help="loopback address for --tcp (127.0.0.1 or ::1)")
58
+ parser.add_argument("--token-file", help="where --tcp writes the per-launch token (mode 0600)")
59
+ stores = parser.add_argument_group("storage")
60
+ stores.add_argument("--mls-root", help="the sealed MLS store's directory (or OFFLINE_PROTOCOL_MLS_ROOT)")
61
+ stores.add_argument("--state-root", help="the protocol-state directory (or OFFLINE_PROTOCOL_STATE_ROOT)")
62
+ stores.add_argument(
63
+ "--store-key-env",
64
+ default=DEFAULT_STORE_KEY_ENV,
65
+ help=f"environment variable holding the 32-byte store key (default: {DEFAULT_STORE_KEY_ENV})",
66
+ )
67
+ stores.add_argument(
68
+ "--keyring",
69
+ action="store_true",
70
+ help="use the platform keyring and the application state store instead of the file stores",
71
+ )
72
+ mesh = parser.add_argument_group("peer stream")
73
+ mesh.add_argument("--listen", metavar="HOST:PORT", help="where the peer-stream transport accepts streams")
74
+ mesh.add_argument("--peer", action="append", default=[], metavar="ENTRY", help="a peer to keep a stream to: host:port or off1...@host:port")
75
+ parser.add_argument(
76
+ "--gateway",
77
+ metavar="HOST:PORT",
78
+ help=f"the gateway daemon to attach to when the config enables reticulum (default: {DEFAULT_DAEMON_ADDRESS})",
79
+ )
80
+ parser.add_argument("--policy", help="JSON file with the space allow-lists and method denials")
81
+ parser.add_argument("--no-health", action="store_true", help="do not answer GET /health")
82
+ parser.add_argument("--log-level", default="INFO")
83
+ return parser
84
+
85
+
86
+ def build_manager(args: argparse.Namespace) -> ProtocolManager:
87
+ raw = _load_json(args.config, "config")
88
+ try:
89
+ config = codec.decode("ProtocolConfig", raw, "config")
90
+ except codec.RpcError as exc:
91
+ raise SystemExit(f"config: {exc.message}") from None
92
+ if args.keyring:
93
+ manager = ProtocolManager(config, state_root=args.state_root)
94
+ else:
95
+ try:
96
+ manager = ProtocolManager(
97
+ config,
98
+ mls_root=args.mls_root,
99
+ state_root=args.state_root,
100
+ store_key_env=args.store_key_env,
101
+ )
102
+ except ValueError as exc:
103
+ raise SystemExit(str(exc)) from None
104
+ if manager.peer_stream is not None and (args.listen or args.peer):
105
+ listen_host, listen_port = None, ...
106
+ if args.listen:
107
+ host, _, port = args.listen.rpartition(":")
108
+ if not host or not port.isdigit():
109
+ raise SystemExit("--listen takes HOST:PORT")
110
+ listen_host, listen_port = host.strip("[]"), int(port)
111
+ manager.peer_stream.configure(listen_host=listen_host, listen_port=listen_port, peers=args.peer)
112
+ if manager.gateway is not None:
113
+ try:
114
+ manager.gateway.configure(daemon_address=args.gateway or DEFAULT_DAEMON_ADDRESS)
115
+ except ValueError as exc:
116
+ raise SystemExit(f"--gateway: {exc}") from None
117
+ elif args.gateway:
118
+ raise SystemExit("--gateway needs reticulum_enabled in the config")
119
+ return manager
120
+
121
+
122
+ def build_server(args: argparse.Namespace, manager: ProtocolManager) -> LocalApiServer:
123
+ policy = Policy.from_dict(_load_json(args.policy, "policy")) if args.policy else Policy()
124
+ if args.tcp is not None:
125
+ if not args.token_file:
126
+ raise SystemExit("--tcp requires --token-file")
127
+ return LocalApiServer(
128
+ manager,
129
+ policy=policy,
130
+ tcp_port=args.tcp,
131
+ tcp_host=args.tcp_host,
132
+ token_path=args.token_file,
133
+ health=not args.no_health,
134
+ )
135
+ return LocalApiServer(
136
+ manager,
137
+ policy=policy,
138
+ socket_path=args.socket or default_socket_path(),
139
+ health=not args.no_health,
140
+ )
141
+
142
+
143
+ async def run(server: LocalApiServer) -> None:
144
+ stop = asyncio.Event()
145
+ loop = asyncio.get_running_loop()
146
+ for sig in (signal.SIGINT, signal.SIGTERM):
147
+ try:
148
+ loop.add_signal_handler(sig, stop.set)
149
+ except (NotImplementedError, RuntimeError):
150
+ signal.signal(sig, lambda *_: stop.set())
151
+ await server.start()
152
+ try:
153
+ await stop.wait()
154
+ finally:
155
+ await server.stop()
156
+
157
+
158
+ def main(argv: list[str] | None = None) -> int:
159
+ args = build_parser().parse_args(argv)
160
+ logging.basicConfig(level=args.log_level.upper(), format="%(asctime)s %(levelname)s %(name)s: %(message)s")
161
+ manager = build_manager(args)
162
+ try:
163
+ server = build_server(args, manager)
164
+ except ValueError as exc:
165
+ raise SystemExit(str(exc)) from None
166
+ asyncio.run(run(server))
167
+ return 0
168
+
169
+
170
+ if __name__ == "__main__":
171
+ sys.exit(main())