rigsby-core 0.3.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.
File without changes
rigsby_core/apps.py ADDED
@@ -0,0 +1,69 @@
1
+ """Finding installed apps on the phone by name (used by the agent's find_app and `rigsby phone apps`)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import difflib
6
+
7
+ from .phone import Phone
8
+
9
+
10
+ class AppCatalog:
11
+ """Resolves app names to packages using the phone's launcher list (fetched lazily)."""
12
+
13
+ def __init__(self, phone: Phone):
14
+ self.phone = phone
15
+ self._apps: list[dict[str, str]] | None = None
16
+
17
+ @property
18
+ def apps(self) -> list[dict[str, str]]:
19
+ if self._apps is None:
20
+ self._apps = self.phone.list_apps()
21
+ return self._apps
22
+
23
+ def search(self, query: str | None, limit: int = 15) -> str:
24
+ """Human/model-readable list of installed apps matching the query (all apps if empty)."""
25
+ apps = self.apps
26
+ if not query:
27
+ listing = "; ".join(f"{a['label']} ({a['package']})" for a in apps[:400])
28
+ return f"{len(apps)} installed apps: {listing}"
29
+ q = query.strip().lower()
30
+ words = q.split()
31
+ matches = [
32
+ a for a in apps
33
+ if q in a["label"].lower() or q in a["package"].lower()
34
+ or all(w in f"{a['label']} {a['package']}".lower() for w in words)
35
+ ]
36
+ if not matches:
37
+ labels = {a["label"].lower(): a for a in apps}
38
+ matches = [labels[c] for c in difflib.get_close_matches(q, list(labels), n=5, cutoff=0.5)]
39
+ if not matches:
40
+ return f"No installed app matches '{query}'. Call find_app with no query to list all apps."
41
+ listing = "; ".join(f"{a['label']} ({a['package']})" for a in matches[:limit])
42
+ more = f" (+{len(matches) - limit} more)" if len(matches) > limit else ""
43
+ return f"Apps matching '{query}': {listing}{more}"
44
+
45
+ def resolve(self, query: str) -> tuple[str | None, str]:
46
+ """Returns (package, message). package is None when the name is unknown or ambiguous."""
47
+ q = query.strip().lower()
48
+ apps = self.apps
49
+ for app in apps:
50
+ if app["package"].lower() == q:
51
+ return app["package"], app["label"]
52
+ exact = [a for a in apps if a["label"].lower() == q]
53
+ if len(exact) == 1:
54
+ return exact[0]["package"], exact[0]["label"]
55
+ partial = exact or [a for a in apps if q in a["label"].lower() or q in a["package"].lower()]
56
+ if len(partial) == 1:
57
+ return partial[0]["package"], partial[0]["label"]
58
+ if len(partial) > 1:
59
+ names = ", ".join(f"{a['label']} ({a['package']})" for a in partial[:8])
60
+ return None, f"'{query}' matches several apps: {names}. Use the exact package or ask the user."
61
+ labels = {a["label"].lower(): a for a in apps}
62
+ close = difflib.get_close_matches(q, list(labels), n=5, cutoff=0.6)
63
+ if len(close) == 1:
64
+ app = labels[close[0]]
65
+ return app["package"], app["label"]
66
+ if close:
67
+ names = ", ".join(f"{labels[c]['label']} ({labels[c]['package']})" for c in close)
68
+ return None, f"No app named '{query}'. Similar: {names}."
69
+ return None, f"No installed app matches '{query}'."
rigsby_core/channel.py ADDED
@@ -0,0 +1,207 @@
1
+ """A sealed, two-way RPC channel between a laptop and the Rigsby server, over a WebSocket.
2
+
3
+ Every frame is AES-256-GCM under the laptop's pairing key, with associated data binding it to this
4
+ connection's challenge, its direction and its sequence number (crypto.channel_aad). So even a proxy
5
+ that terminates TLS cannot read, forge, replay, reorder or reflect messages.
6
+
7
+ Messages (the plaintext of each frame):
8
+ {"t": "req", "id": "...", "m": "run.start", "p": {...}} a request; answered by exactly one res
9
+ {"t": "res", "id": "...", "ok": true, "r": ...} success
10
+ {"t": "res", "id": "...", "ok": false, "e": {"kind", "code", "message"}}
11
+ {"t": "ev", "n": "ui.info", "p": {...}} a one-way event
12
+
13
+ Either side may send requests. Incoming requests run on their own thread, because some block for a
14
+ long time (the laptop waiting for the user to approve).
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import json
20
+ import threading
21
+ import time
22
+ import uuid
23
+ from typing import Any, Callable
24
+
25
+ from cryptography.exceptions import InvalidTag
26
+
27
+ from rigsby_core import crypto
28
+
29
+
30
+ class ChannelClosed(Exception):
31
+ pass
32
+
33
+
34
+ class Cancelled(Exception):
35
+ """The caller's cancel event was set while waiting for an answer."""
36
+
37
+
38
+ class RemoteError(Exception):
39
+ """The other side handled the request and reported a failure."""
40
+
41
+ def __init__(self, kind: str, message: str, code: str = ""):
42
+ super().__init__(message)
43
+ self.kind = kind
44
+ self.code = code
45
+ self.message = message
46
+
47
+ def to_json(self) -> dict[str, str]:
48
+ return {"kind": self.kind, "code": self.code, "message": self.message}
49
+
50
+
51
+ Handler = Callable[[dict[str, Any]], Any]
52
+
53
+
54
+ class Peer:
55
+ def __init__(self, ws, key: bytes, challenge_b64: str, *, sending: str, receiving: str,
56
+ handlers: dict[str, Handler] | None = None,
57
+ on_event: Callable[[str, dict[str, Any]], None] | None = None,
58
+ on_close: Callable[["Peer"], None] | None = None):
59
+ self.ws = ws
60
+ self.key = key
61
+ self.challenge = challenge_b64
62
+ self.sending = sending
63
+ self.receiving = receiving
64
+ self.handlers = handlers or {}
65
+ self.on_event = on_event
66
+ self.on_close = on_close
67
+ self.closed = threading.Event()
68
+ self._send_lock = threading.Lock()
69
+ self._send_seq = 0
70
+ self._recv_seq = 0
71
+ self._pending: dict[str, tuple[threading.Event, list]] = {}
72
+ self._pending_lock = threading.Lock()
73
+
74
+ # --- sending --------------------------------------------------------------------------------
75
+
76
+ def _send(self, message: dict[str, Any]) -> None:
77
+ if self.closed.is_set():
78
+ raise ChannelClosed("the connection is closed")
79
+ with self._send_lock:
80
+ nonce = crypto.new_nonce()
81
+ ct = crypto.seal(self.key, nonce, json.dumps(message).encode(),
82
+ crypto.channel_aad(self.sending, self.challenge, self._send_seq))
83
+ self._send_seq += 1
84
+ try:
85
+ self.ws.send(json.dumps({"n": crypto.b64(nonce), "c": crypto.b64(ct)}))
86
+ except Exception as e: # noqa: BLE001 - any send failure means the connection is gone
87
+ self._closed()
88
+ raise ChannelClosed(str(e)) from e
89
+
90
+ def notify(self, name: str, params: dict[str, Any] | None = None) -> None:
91
+ self._send({"t": "ev", "n": name, "p": params or {}})
92
+
93
+ def request(self, method: str, params: dict[str, Any] | None = None, timeout: float | None = 60.0,
94
+ cancel: threading.Event | None = None) -> Any:
95
+ """Send a request and wait for its result. Raises RemoteError, ChannelClosed, TimeoutError, or
96
+ Cancelled when `cancel` is set while waiting."""
97
+ request_id = uuid.uuid4().hex[:12]
98
+ done, box = threading.Event(), []
99
+ with self._pending_lock:
100
+ self._pending[request_id] = (done, box)
101
+ try:
102
+ self._send({"t": "req", "id": request_id, "m": method, "p": params or {}})
103
+ deadline = None if timeout is None else time.monotonic() + timeout
104
+ while not done.wait(0.25 if cancel is not None else timeout):
105
+ if cancel is not None and cancel.is_set():
106
+ raise Cancelled(method)
107
+ if deadline is not None and time.monotonic() >= deadline:
108
+ raise TimeoutError(f"{method} got no answer within {timeout:g}s")
109
+ finally:
110
+ with self._pending_lock:
111
+ self._pending.pop(request_id, None)
112
+ message = box[0]
113
+ if message is None:
114
+ raise ChannelClosed("the connection closed before an answer arrived")
115
+ if message.get("ok"):
116
+ return message.get("r")
117
+ err = message.get("e") or {}
118
+ raise RemoteError(err.get("kind", "error"), err.get("message", ""), err.get("code", ""))
119
+
120
+ # --- receiving ------------------------------------------------------------------------------
121
+
122
+ def start(self) -> threading.Thread:
123
+ thread = threading.Thread(target=self.run, name=f"rigsby-channel-{self.receiving}", daemon=True)
124
+ thread.start()
125
+ return thread
126
+
127
+ def run(self) -> None:
128
+ """Read frames until the connection closes (call from a dedicated thread)."""
129
+ try:
130
+ while True:
131
+ try:
132
+ frame = self.ws.recv()
133
+ except Exception: # noqa: BLE001 - closed, reset, or timed out: all end the channel
134
+ return
135
+ if isinstance(frame, bytes):
136
+ return # this channel carries text frames only
137
+ try:
138
+ env = json.loads(frame)
139
+ plaintext = crypto.open_(self.key, crypto.unb64(env["n"]), crypto.unb64(env["c"]),
140
+ crypto.channel_aad(self.receiving, self.challenge, self._recv_seq))
141
+ message = json.loads(plaintext)
142
+ except (InvalidTag, ValueError, KeyError, TypeError):
143
+ return # forged, replayed or out-of-order: drop the connection
144
+ self._recv_seq += 1
145
+ self._dispatch(message)
146
+ finally:
147
+ self._closed()
148
+ try:
149
+ self.ws.close()
150
+ except Exception: # noqa: BLE001
151
+ pass
152
+
153
+ def _dispatch(self, message: dict[str, Any]) -> None:
154
+ kind = message.get("t")
155
+ if kind == "res":
156
+ with self._pending_lock:
157
+ waiter = self._pending.get(message.get("id", ""))
158
+ if waiter is not None:
159
+ waiter[1].append(message)
160
+ waiter[0].set()
161
+ elif kind == "ev":
162
+ if self.on_event is not None:
163
+ try:
164
+ self.on_event(message.get("n", ""), message.get("p") or {})
165
+ except Exception: # noqa: BLE001 - a bad event handler must not kill the channel
166
+ pass
167
+ elif kind == "req":
168
+ threading.Thread(target=self._serve, args=(message,), daemon=True).start()
169
+
170
+ def _serve(self, message: dict[str, Any]) -> None:
171
+ request_id = message.get("id", "")
172
+ handler = self.handlers.get(message.get("m", ""))
173
+ try:
174
+ if handler is None:
175
+ raise RemoteError("unknown_method", f"unknown method {message.get('m')!r}")
176
+ reply = {"t": "res", "id": request_id, "ok": True, "r": handler(message.get("p") or {})}
177
+ except RemoteError as e:
178
+ reply = {"t": "res", "id": request_id, "ok": False, "e": e.to_json()}
179
+ except Exception as e: # noqa: BLE001 - report, never crash the reader
180
+ reply = {"t": "res", "id": request_id, "ok": False,
181
+ "e": {"kind": "internal", "code": type(e).__name__, "message": str(e)}}
182
+ try:
183
+ self._send(reply)
184
+ except ChannelClosed:
185
+ pass
186
+
187
+ def _closed(self) -> None:
188
+ if self.closed.is_set():
189
+ return
190
+ self.closed.set()
191
+ with self._pending_lock:
192
+ waiters = list(self._pending.values())
193
+ for done, box in waiters:
194
+ box.append(None)
195
+ done.set()
196
+ if self.on_close is not None:
197
+ try:
198
+ self.on_close(self)
199
+ except Exception: # noqa: BLE001
200
+ pass
201
+
202
+ def close(self) -> None:
203
+ try:
204
+ self.ws.close()
205
+ except Exception: # noqa: BLE001
206
+ pass
207
+ self._closed()
rigsby_core/config.py ADDED
@@ -0,0 +1,25 @@
1
+ """Local configuration and run-log locations.
2
+
3
+ Everything lives under ~/.config/rigsby (and ~/.local/share/rigsby/runs). Set RIGSBY_HOME to keep
4
+ everything under one directory instead, e.g. to run a test server and client side by side.
5
+
6
+ On the server: server/devices.json (paired phone and laptops), connector setups, memory, run logs.
7
+ On a laptop: server.json (the server URL and this laptop's key), overlay and trigger settings.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import os
13
+ from pathlib import Path
14
+
15
+
16
+ def config_dir() -> Path:
17
+ if home := os.environ.get("RIGSBY_HOME"):
18
+ return Path(home) / "config"
19
+ return Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config")) / "rigsby"
20
+
21
+
22
+ def runs_dir() -> Path:
23
+ if home := os.environ.get("RIGSBY_HOME"):
24
+ return Path(home) / "runs"
25
+ return Path(os.environ.get("XDG_DATA_HOME", Path.home() / ".local" / "share")) / "rigsby" / "runs"
@@ -0,0 +1,112 @@
1
+ """The operator command protocol, independent of transport.
2
+
3
+ Every command to the phone is sealed with AES-256-GCM under the phone's pairing key; the associated
4
+ data binds it to the endpoint and a timestamp, and the phone rejects replays. Responses are sealed
5
+ and bound to the request that produced them. The phone dials out to the Rigsby server, which sends
6
+ these envelopes over that WebSocket (rigsby_server.phone_link); a laptop reaches the phone through
7
+ the server (rigsby_client.server_link). Both implement `Connection`.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ import struct
14
+ import time
15
+ import uuid
16
+ from dataclasses import dataclass
17
+ from typing import Any, Protocol
18
+
19
+ from cryptography.exceptions import InvalidTag
20
+
21
+ from rigsby_core import crypto
22
+
23
+
24
+ class OperatorError(Exception):
25
+ """Transport-level failure: unreachable phone, bad auth, malformed response."""
26
+
27
+
28
+ class OperatorUnreachable(OperatorError):
29
+ pass
30
+
31
+
32
+ class OperatorAuthError(OperatorError):
33
+ pass
34
+
35
+
36
+ class CommandError(Exception):
37
+ """The phone received the command and reported that it failed."""
38
+
39
+ def __init__(self, code: str, message: str):
40
+ super().__init__(f"{code}: {message}")
41
+ self.code = code
42
+ self.message = message
43
+
44
+
45
+ class Connection(Protocol):
46
+ def call(self, path: str, payload: dict[str, Any] | None = None, *, binary: bool = False,
47
+ retries: int = 0, timeout: float | None = None) -> Any:
48
+ """Send a command. Returns `data` (JSON) or `(meta, bytes)` when binary=True.
49
+ Only pass retries > 0 for read-only commands: a retried tap could tap twice."""
50
+ ...
51
+
52
+ def health(self) -> dict[str, Any]: ...
53
+
54
+ def close(self) -> None: ...
55
+
56
+
57
+ @dataclass
58
+ class SealedCommand:
59
+ request_id: str
60
+ nonce_b64: str
61
+ envelope: dict[str, Any] # {"v", "ts", "nonce", "ct"}
62
+
63
+
64
+ def seal_command(key: bytes, path: str, payload: dict[str, Any]) -> SealedCommand:
65
+ request_id = f"req_{uuid.uuid4().hex[:12]}"
66
+ body = json.dumps({"request_id": request_id, **payload}).encode()
67
+ ts = int(time.time() * 1000)
68
+ nonce = crypto.new_nonce()
69
+ nonce_b64 = crypto.b64(nonce)
70
+ ct = crypto.seal(key, nonce, body, crypto.request_aad("POST", path, ts))
71
+ return SealedCommand(request_id, nonce_b64, {"v": 1, "ts": ts, "nonce": nonce_b64, "ct": crypto.b64(ct)})
72
+
73
+
74
+ def open_json_reply(key: bytes, command: SealedCommand, env: dict[str, Any], path: str) -> Any:
75
+ """The phone's sealed JSON response -> `data`, or raises CommandError / OperatorAuthError."""
76
+ if "error" in env and "ct" not in env:
77
+ # Errors before authentication are plain.
78
+ err = env.get("error") or {}
79
+ code, message = err.get("code", "error"), err.get("message", "")
80
+ if code in ("unauthorized", "not_paired", "replay"):
81
+ raise OperatorAuthError(f"{code}: {message}")
82
+ raise OperatorError(f"{code}: {message}")
83
+ try:
84
+ plaintext = crypto.open_(key, crypto.unb64(env["nonce"]), crypto.unb64(env["ct"]),
85
+ crypto.response_aad(command.nonce_b64))
86
+ result = json.loads(plaintext)
87
+ except InvalidTag as e:
88
+ raise OperatorAuthError("Response failed authentication (wrong pairing key?)") from e
89
+ except (ValueError, KeyError) as e:
90
+ raise OperatorError(f"Malformed response from {path}: {e}") from e
91
+ if result.get("request_id") != command.request_id:
92
+ raise OperatorAuthError("Response does not match the request")
93
+ if not result.get("success"):
94
+ err = result.get("error") or {}
95
+ raise CommandError(err.get("code", "unknown"), err.get("message", ""))
96
+ return result.get("data", {})
97
+
98
+
99
+ def open_binary_reply(key: bytes, command: SealedCommand, raw: bytes, path: str) -> tuple[dict[str, Any], bytes]:
100
+ """nonce(12) || AES-GCM(u32 meta_len || meta JSON || bytes) -> (meta, bytes)."""
101
+ try:
102
+ plaintext = crypto.open_(key, raw[: crypto.NONCE_LEN], raw[crypto.NONCE_LEN:],
103
+ crypto.binary_response_aad(command.nonce_b64))
104
+ (meta_len,) = struct.unpack(">I", plaintext[:4])
105
+ meta = json.loads(plaintext[4: 4 + meta_len])
106
+ except InvalidTag as e:
107
+ raise OperatorAuthError("Response failed authentication (wrong pairing key?)") from e
108
+ except (ValueError, struct.error) as e:
109
+ raise OperatorError(f"Malformed response from {path}: {e}") from e
110
+ if meta.get("request_id") != command.request_id:
111
+ raise OperatorAuthError("Response does not match the request")
112
+ return meta, plaintext[4 + meta_len:]
@@ -0,0 +1,46 @@
1
+ """What a profile's Slack, GitHub and Atlas keys must look like, checked the same on the laptop (where
2
+ they are kept) and on the server (which only borrows them for a run).
3
+
4
+ slack {"user_token": "xoxp-...", "bot_token": "xoxb-...", "app_token": "xapp-...", "signoff": "..."}
5
+ (the app token never leaves the laptop: it is for Socket Mode there)
6
+ github {"token": "...", "default_repo": "owner/name"}
7
+ atlas {"url": "https://...", "token": "..."}
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import ipaddress
13
+ import re
14
+ from typing import Any
15
+ from urllib.parse import urlparse
16
+
17
+ SLACK_TOKEN = re.compile(r"^xox[bp]-[A-Za-z0-9-]{10,250}$|^xapp-[A-Za-z0-9-]{10,250}$")
18
+ MAX_TOKEN = 500
19
+
20
+
21
+ def valid_slack_token(token: Any, prefix: str) -> bool:
22
+ """A Slack token of one kind: "xoxb-" (bot), "xoxp-" (user) or "xapp-" (app, for Socket Mode)."""
23
+ return isinstance(token, str) and token.strip().startswith(prefix) and bool(SLACK_TOKEN.match(token.strip()))
24
+
25
+
26
+ def valid_token(token: Any) -> bool:
27
+ return isinstance(token, str) and 0 < len(token.strip()) <= MAX_TOKEN and not any(c.isspace() for c in token.strip())
28
+
29
+
30
+ def valid_atlas_url(url: Any) -> bool:
31
+ """https on a named, public host: never localhost, a bare IP address or a .local/.internal name, so
32
+ a profile can't point the server at something on the server's own network."""
33
+ try:
34
+ parsed = urlparse(str(url or "").strip())
35
+ host = (parsed.hostname or "").lower()
36
+ except ValueError:
37
+ return False
38
+ if parsed.scheme != "https" or not host or "." not in host or parsed.username or parsed.password:
39
+ return False
40
+ if host == "localhost" or host.endswith((".localhost", ".local", ".internal", ".lan", ".home", ".arpa")):
41
+ return False
42
+ try:
43
+ ipaddress.ip_address(host.strip("[]"))
44
+ return False
45
+ except ValueError:
46
+ return True
rigsby_core/crypto.py ADDED
@@ -0,0 +1,102 @@
1
+ """Wire-level cryptography. Must stay byte-for-byte compatible with
2
+ android/.../security/RigsbyCrypto.kt (shared test vectors live in both test suites)."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import base64
7
+ import hashlib
8
+ import hmac
9
+ import os
10
+ import secrets
11
+
12
+ from cryptography.hazmat.primitives.ciphers.aead import AESGCM
13
+
14
+ PROTOCOL = "rigsby-v1"
15
+ KDF_ITERATIONS = 200_000
16
+ KDF_SALT = b"rigsby-pairing-v1"
17
+ NONCE_LEN = 12
18
+ CODE_LEN = 12
19
+ CODE_ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"
20
+
21
+ _CONFUSABLE = str.maketrans({"O": "0", "I": "1", "L": "1"})
22
+
23
+
24
+ class PairingCodeError(ValueError):
25
+ pass
26
+
27
+
28
+ def generate_code() -> str:
29
+ """A pairing code like ABCD-EFGH-JKMN (same format as the phone's)."""
30
+ chars = "".join(secrets.choice(CODE_ALPHABET) for _ in range(CODE_LEN))
31
+ return "-".join(chars[i:i + 4] for i in range(0, CODE_LEN, 4))
32
+
33
+
34
+ def normalize_code(code: str) -> str:
35
+ return "".join(c for c in code.upper() if c.isalnum()).translate(_CONFUSABLE)
36
+
37
+
38
+ def derive_key(code: str) -> bytes:
39
+ normalized = normalize_code(code)
40
+ if len(normalized) != CODE_LEN or any(c not in CODE_ALPHABET for c in normalized):
41
+ raise PairingCodeError(f"Pairing code must be {CODE_LEN} characters like ABCD-EFGH-JKMN")
42
+ return hashlib.pbkdf2_hmac("sha256", normalized.encode(), KDF_SALT, KDF_ITERATIONS, dklen=32)
43
+
44
+
45
+ def key_id(key: bytes) -> str:
46
+ return hashlib.sha256(key).digest()[:4].hex()
47
+
48
+
49
+ def new_nonce() -> bytes:
50
+ return os.urandom(NONCE_LEN)
51
+
52
+
53
+ def seal(key: bytes, nonce: bytes, plaintext: bytes, aad: bytes) -> bytes:
54
+ return AESGCM(key).encrypt(nonce, plaintext, aad)
55
+
56
+
57
+ def open_(key: bytes, nonce: bytes, ciphertext: bytes, aad: bytes) -> bytes:
58
+ """Raises cryptography.exceptions.InvalidTag on tampering or a wrong key."""
59
+ return AESGCM(key).decrypt(nonce, ciphertext, aad)
60
+
61
+
62
+ def request_aad(method: str, path: str, timestamp_ms: int) -> bytes:
63
+ return f"{PROTOCOL}\nREQ\n{method}\n{path}\n{timestamp_ms}".encode()
64
+
65
+
66
+ def response_aad(request_nonce_b64: str) -> bytes:
67
+ return f"{PROTOCOL}\nRES\n{request_nonce_b64}".encode()
68
+
69
+
70
+ def binary_response_aad(request_nonce_b64: str) -> bytes:
71
+ return f"{PROTOCOL}\nRESBIN\n{request_nonce_b64}".encode()
72
+
73
+
74
+ def b64(data: bytes) -> str:
75
+ return base64.b64encode(data).decode()
76
+
77
+
78
+ def unb64(text: str) -> bytes:
79
+ return base64.b64decode(text)
80
+
81
+
82
+ # --- Connecting to the Rigsby server ------------------------------------------------------------
83
+ # A device (the phone or a laptop) proves it holds its pairing key by answering the server's random
84
+ # challenge with an HMAC; the server answers back the same way, so both sides are authenticated
85
+ # before anything else is sent.
86
+
87
+ def hello_proof(key: bytes, role: str, challenge_b64: str) -> str:
88
+ return b64(hmac.new(key, f"{PROTOCOL}\nHELLO\n{role}\n{challenge_b64}".encode(), hashlib.sha256).digest())
89
+
90
+
91
+ def welcome_proof(key: bytes, role: str, challenge_b64: str) -> str:
92
+ return b64(hmac.new(key, f"{PROTOCOL}\nWELCOME\n{role}\n{challenge_b64}".encode(), hashlib.sha256).digest())
93
+
94
+
95
+ def proofs_equal(a: str, b: str) -> bool:
96
+ return hmac.compare_digest(a.encode(), b.encode())
97
+
98
+
99
+ def channel_aad(direction: str, challenge_b64: str, seq: int) -> bytes:
100
+ """Laptop <-> server messages: bound to the connection (challenge), direction ("up" from the
101
+ laptop, "down" from the server) and position, so they cannot be replayed, reordered or reflected."""
102
+ return f"{PROTOCOL}\nCHAN\n{direction}\n{challenge_b64}\n{seq}".encode()