witbitz-code 1.15.4__tar.gz → 1.15.6__tar.gz
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.
- {witbitz_code-1.15.4/src/witbitz_code.egg-info → witbitz_code-1.15.6}/PKG-INFO +1 -1
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/pyproject.toml +1 -1
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/src/witbitz_code/__init__.py +1 -1
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/src/witbitz_code/cli.py +11 -2
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/src/witbitz_code/connector.py +72 -2
- witbitz_code-1.15.6/src/witbitz_code/device.py +283 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/src/witbitz_code/devicelink.py +3 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/src/witbitz_code/link.py +31 -3
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/src/witbitz_code/offered_models.json +1 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/src/witbitz_code/pair.py +39 -4
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/src/witbitz_code/ui.py +1 -1
- {witbitz_code-1.15.4 → witbitz_code-1.15.6/src/witbitz_code.egg-info}/PKG-INFO +1 -1
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/src/witbitz_code.egg-info/SOURCES.txt +2 -0
- witbitz_code-1.15.6/tests/test_device.py +365 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/LICENSE +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/README.md +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/setup.cfg +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/src/witbitz_code/__main__.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/src/witbitz_code/_js.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/src/witbitz_code/account.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/src/witbitz_code/app.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/src/witbitz_code/asks.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/src/witbitz_code/attachments.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/src/witbitz_code/auto.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/src/witbitz_code/auto_runner.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/src/witbitz_code/browse.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/src/witbitz_code/browsetree.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/src/witbitz_code/codekeys.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/src/witbitz_code/codetools.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/src/witbitz_code/compress.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/src/witbitz_code/computers.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/src/witbitz_code/confidential.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/src/witbitz_code/confidential_models.json +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/src/witbitz_code/dirs.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/src/witbitz_code/files.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/src/witbitz_code/folders.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/src/witbitz_code/gateway.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/src/witbitz_code/icons/witbitz-code-wsl.ico +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/src/witbitz_code/icons/witbitz-code.ico +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/src/witbitz_code/images.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/src/witbitz_code/keys.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/src/witbitz_code/mkdir.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/src/witbitz_code/models.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/src/witbitz_code/net.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/src/witbitz_code/opencode_plugins/notes-init.md +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/src/witbitz_code/opencode_plugins/witbitz-browse-cdp.mjs +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/src/witbitz_code/opencode_plugins/witbitz-browse-local.mjs +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/src/witbitz_code/opencode_plugins/witbitz-browse-publisher.mjs +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/src/witbitz_code/opencode_plugins/witbitz-browse-tree.mjs +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/src/witbitz_code/opencode_plugins/witbitz-browser.js +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/src/witbitz_code/opencode_plugins/witbitz-media-server.mjs +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/src/witbitz_code/opencode_plugins/witbitz-notes.js +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/src/witbitz_code/opencode_plugins/witbitz-progress.js +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/src/witbitz_code/outputs.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/src/witbitz_code/pairings.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/src/witbitz_code/payers.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/src/witbitz_code/plugins.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/src/witbitz_code/policy.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/src/witbitz_code/ports.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/src/witbitz_code/qr.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/src/witbitz_code/receipt.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/src/witbitz_code/relay.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/src/witbitz_code/remind.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/src/witbitz_code/seccheck.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/src/witbitz_code/seen.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/src/witbitz_code/selfupdate.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/src/witbitz_code/tinfoil_read.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/src/witbitz_code/tools_catalog.json +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/src/witbitz_code/tools_probe.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/src/witbitz_code/toolsetup.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/src/witbitz_code/ui_static/app.css +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/src/witbitz_code/ui_static/app.js +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/src/witbitz_code/ui_static/index.html +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/src/witbitz_code/uitools.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/src/witbitz_code/uninstall.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/src/witbitz_code/winagent.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/src/witbitz_code/winbg.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/src/witbitz_code/winconsole.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/src/witbitz_code/wizard.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/src/witbitz_code/wslstart.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/src/witbitz_code.egg-info/dependency_links.txt +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/src/witbitz_code.egg-info/entry_points.txt +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/src/witbitz_code.egg-info/requires.txt +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/src/witbitz_code.egg-info/top_level.txt +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/tests/test_asks.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/tests/test_attachments.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/tests/test_auto.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/tests/test_browse.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/tests/test_browsetree.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/tests/test_cli.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/tests/test_codekeys.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/tests/test_codetools.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/tests/test_confidential.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/tests/test_connector_e2e.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/tests/test_devicelink.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/tests/test_dirs.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/tests/test_files.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/tests/test_files_and_compress.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/tests/test_folders.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/tests/test_images.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/tests/test_outputs.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/tests/test_pair_flows.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/tests/test_plugins.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/tests/test_policy.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/tests/test_ports.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/tests/test_ports_win.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/tests/test_registry.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/tests/test_relay_codec.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/tests/test_remind.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/tests/test_seccheck.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/tests/test_selfupdate.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/tests/test_setup.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/tests/test_tools_probe.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/tests/test_toolsetup.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/tests/test_ui.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/tests/test_ui_page.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/tests/test_uitools.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/tests/test_uninstall.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/tests/test_winagent.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/tests/test_winbg.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/tests/test_winconsole.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/tests/test_windows_files.py +0 -0
- {witbitz_code-1.15.4 → witbitz_code-1.15.6}/tests/test_wslstart.py +0 -0
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "witbitz-code"
|
|
7
|
-
version = "1.15.
|
|
7
|
+
version = "1.15.6"
|
|
8
8
|
description = "Reach OpenCode on this computer from the Witbitz Spaces Code section, through an end-to-end sealed relay."
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.10"
|
|
@@ -297,9 +297,17 @@ async def serve(args: list[str], *, stop: Any = None, live_out: dict | None = No
|
|
|
297
297
|
if child is not None:
|
|
298
298
|
_err("witbitz-code: model calls are paid by each account's own coding keys; confidential models are enforced (min_privacy + verified receipts)")
|
|
299
299
|
# Auto mode's reviewer asks the policy of the model proxy directly (auto_runner.REVIEW_MODELS), billed like the session.
|
|
300
|
+
signed_out = {"all": False} # every pairing here was signed out of its account (device.py): stop, and say so
|
|
301
|
+
|
|
302
|
+
def all_signed_out() -> None:
|
|
303
|
+
_err("witbitz-code: no pairing left to serve here — stopping")
|
|
304
|
+
signed_out["all"] = True
|
|
305
|
+
stop.event.set()
|
|
306
|
+
|
|
300
307
|
connector = await start_connector(pairings, payers=payers, model_url=f"http://127.0.0.1:{proxy.port}/v1" if proxy else "",
|
|
301
308
|
browse_probe=browser.probe if browser else None,
|
|
302
|
-
browse_private=browser.set_private if browser else None
|
|
309
|
+
browse_private=browser.set_private if browser else None,
|
|
310
|
+
on_all_signed_out=all_signed_out)
|
|
303
311
|
live["status"] = asyncio.ensure_future(_check_keys_every(live_keys, keys_http))
|
|
304
312
|
live["connector"] = connector
|
|
305
313
|
if live_out is not None:
|
|
@@ -309,7 +317,8 @@ async def serve(args: list[str], *, stop: Any = None, live_out: dict | None = No
|
|
|
309
317
|
served = ", ".join(f'"{p.get("name")}" → {p.get("account") or "account"}' for p in pairings)
|
|
310
318
|
_err(f"witbitz-code: serving {served} through the sealed relay (Ctrl-C to stop)")
|
|
311
319
|
try:
|
|
312
|
-
|
|
320
|
+
code = await _wait_for_stop(stop, child)
|
|
321
|
+
return 1 if signed_out["all"] else code
|
|
313
322
|
finally:
|
|
314
323
|
live["status"].cancel()
|
|
315
324
|
if live_out is not None:
|
|
@@ -45,6 +45,7 @@ from .payers import SessionPayers
|
|
|
45
45
|
from .seen import SEEN_ROUTE, merge_seen, norm_seen
|
|
46
46
|
from .dirs import DIRS_ROUTE, list_dirs
|
|
47
47
|
from . import seccheck
|
|
48
|
+
from . import device as device_mod # signed out of the account → stop (account recovery v2)
|
|
48
49
|
from .seccheck import SECURITY_ROUTE
|
|
49
50
|
from .mkdir import MKDIR_ROUTE, mkdir_in
|
|
50
51
|
from .pairings import DEFAULT_OPENCODE_URL, hostname, read_env_password
|
|
@@ -249,6 +250,8 @@ class PairingServer:
|
|
|
249
250
|
# must carry the CURRENT one: a recording from before a restart or reconnect carries a nonce nobody accepts.
|
|
250
251
|
self.nonce = ""
|
|
251
252
|
self.relay_state = "connecting" # the relay socket's last state — the page (ui.py) shows "online" when every one is open
|
|
253
|
+
self.on_page: Callable[[], Any] | None = None # a page connected — start_connector asks the account's service again (device.py)
|
|
254
|
+
self._pages_before = 0
|
|
252
255
|
self.peer = RelayPeer(secret=pairing["secret"], role="computer", relay=pairing.get("relay") or RELAY_URL,
|
|
253
256
|
on_state=self._on_state, on_peers=self._on_peers, on_message=self._on_message, connect=connect,
|
|
254
257
|
# A page socket fell out of the replay window: its recorded frames would open again — rotate the
|
|
@@ -320,6 +323,9 @@ class PairingServer:
|
|
|
320
323
|
self.hello()
|
|
321
324
|
|
|
322
325
|
def _on_peers(self, n: int) -> None:
|
|
326
|
+
if n >= 2 and self._pages_before < 2 and self.on_page is not None:
|
|
327
|
+
self.on_page()
|
|
328
|
+
self._pages_before = n
|
|
323
329
|
if n >= 2:
|
|
324
330
|
self.hello()
|
|
325
331
|
else:
|
|
@@ -1003,6 +1009,9 @@ class PairingServer:
|
|
|
1003
1009
|
self._unsubscribe(p, _ALL)
|
|
1004
1010
|
|
|
1005
1011
|
|
|
1012
|
+
_DEFAULT_DEVICES = object() # start_connector: the real key file / service — tests pass their own, or None
|
|
1013
|
+
|
|
1014
|
+
|
|
1006
1015
|
class _Aborted(Exception):
|
|
1007
1016
|
pass
|
|
1008
1017
|
|
|
@@ -1012,12 +1021,19 @@ class Connector:
|
|
|
1012
1021
|
servers: list[PairingServer]
|
|
1013
1022
|
client: httpx.AsyncClient
|
|
1014
1023
|
payers: SessionPayers | None = None
|
|
1024
|
+
watchers: list = field(default_factory=list) # device.DeviceWatch per pairing the account's service registered
|
|
1025
|
+
|
|
1026
|
+
async def device_checks(self) -> list:
|
|
1027
|
+
"""The first status check of every registered pairing (tests wait on it)."""
|
|
1028
|
+
return list(await asyncio.gather(*(w.ready for w in self.watchers if w.ready is not None)))
|
|
1015
1029
|
|
|
1016
1030
|
@property
|
|
1017
1031
|
def peers(self) -> list[RelayPeer]:
|
|
1018
1032
|
return [s.peer for s in self.servers]
|
|
1019
1033
|
|
|
1020
1034
|
def stop(self) -> None:
|
|
1035
|
+
for w in self.watchers:
|
|
1036
|
+
w.stop()
|
|
1021
1037
|
for s in self.servers:
|
|
1022
1038
|
s.stop()
|
|
1023
1039
|
|
|
@@ -1033,6 +1049,8 @@ class Connector:
|
|
|
1033
1049
|
asyncio.ensure_future(s.peer.send({"t": "progress", **ev, "ts": int(time.time() * 1000)}))
|
|
1034
1050
|
|
|
1035
1051
|
async def aclose(self) -> None:
|
|
1052
|
+
for w in self.watchers:
|
|
1053
|
+
w.stop()
|
|
1036
1054
|
for s in self.servers:
|
|
1037
1055
|
await s.aclose()
|
|
1038
1056
|
await self.client.aclose()
|
|
@@ -1057,7 +1075,8 @@ async def start_connector(pairings: list[dict], *, flush_ms: float = 120, log: C
|
|
|
1057
1075
|
notes_plugin_path: Path | None = None, payers: SessionPayers | None = None,
|
|
1058
1076
|
model_url: str = "", remind_times: dict | None = None,
|
|
1059
1077
|
browse_probe: Callable[[], dict | None] | None = None,
|
|
1060
|
-
browse_private: Callable[[bool], Awaitable[bool]] | None = None, screens_root: Path | None = None
|
|
1078
|
+
browse_private: Callable[[bool], Awaitable[bool]] | None = None, screens_root: Path | None = None,
|
|
1079
|
+
devices: Any = _DEFAULT_DEVICES, on_all_signed_out: Callable[[], Any] | None = None) -> Connector:
|
|
1061
1080
|
"""Serve the given pairings until stop()/aclose(). Options exist for tests: flush_ms, log, client, connect,
|
|
1062
1081
|
request_timeout_ms, max_senders, max_response_bytes, auto_dir, auto_poll_ms."""
|
|
1063
1082
|
client = client or local_client()
|
|
@@ -1076,4 +1095,55 @@ async def start_connector(pairings: list[dict], *, flush_ms: float = 120, log: C
|
|
|
1076
1095
|
browse_probe=browse_probe, browse_private=browse_private, screens_root=screens_root)
|
|
1077
1096
|
await s.start()
|
|
1078
1097
|
servers.append(s)
|
|
1079
|
-
|
|
1098
|
+
c = Connector(servers, client, payers)
|
|
1099
|
+
_watch_devices(c, devices, log, on_all_signed_out)
|
|
1100
|
+
return c
|
|
1101
|
+
|
|
1102
|
+
|
|
1103
|
+
class _DefaultDevices:
|
|
1104
|
+
"""The real ones: device.py's key file, status check and wipe."""
|
|
1105
|
+
every_s = device_mod.CHECK_EVERY_S
|
|
1106
|
+
floor_s = device_mod.CHECK_FLOOR_S
|
|
1107
|
+
|
|
1108
|
+
@staticmethod
|
|
1109
|
+
def key_for(cid: str) -> dict | None:
|
|
1110
|
+
return device_mod.device_key_for(cid)
|
|
1111
|
+
|
|
1112
|
+
@staticmethod
|
|
1113
|
+
async def check(rec: dict) -> str:
|
|
1114
|
+
return await device_mod.device_state(rec)
|
|
1115
|
+
|
|
1116
|
+
@staticmethod
|
|
1117
|
+
async def wipe(cid: str, log: Callable[[str], Any]) -> None:
|
|
1118
|
+
await device_mod.wipe_signed_out(cid, log=log)
|
|
1119
|
+
|
|
1120
|
+
|
|
1121
|
+
def _watch_devices(c: Connector, devices: Any, log: Callable[[str], Any], on_all_signed_out: Callable[[], Any] | None) -> None:
|
|
1122
|
+
"""SIGNED OUT OF THE ACCOUNT (account recovery v2, § 8.5; device.py): a pairing whose computer the account's service
|
|
1123
|
+
registered is asked about now, hourly, and when a page connects. Signed out → that pairing stops and the account's keys
|
|
1124
|
+
here are wiped; nothing else changes on any other answer (offline, an error, a key the service does not know)."""
|
|
1125
|
+
dev = _DefaultDevices if devices is _DEFAULT_DEVICES else devices
|
|
1126
|
+
if dev is None:
|
|
1127
|
+
return
|
|
1128
|
+
for s in list(c.servers):
|
|
1129
|
+
rec = dev.key_for(s._cid) if s._cid else None
|
|
1130
|
+
if not rec:
|
|
1131
|
+
continue
|
|
1132
|
+
|
|
1133
|
+
async def revoked(s: PairingServer = s) -> None:
|
|
1134
|
+
log(f'witbitz-code: "{s.name}" → {s.pairing.get("account") or "your account"}: {device_mod.SIGNED_OUT_TEXT}')
|
|
1135
|
+
if s in c.servers:
|
|
1136
|
+
c.servers.remove(s)
|
|
1137
|
+
await s.aclose()
|
|
1138
|
+
try:
|
|
1139
|
+
await dev.wipe(s._cid, log)
|
|
1140
|
+
except Exception as e: # noqa: BLE001 — said, and the pairing has stopped either way
|
|
1141
|
+
log(f"witbitz-code: could not wipe everything of that account here ({e})")
|
|
1142
|
+
if not c.servers and on_all_signed_out is not None:
|
|
1143
|
+
on_all_signed_out()
|
|
1144
|
+
|
|
1145
|
+
w = device_mod.DeviceWatch(lambda rec=rec: dev.check(rec), revoked, every_s=getattr(dev, "every_s", device_mod.CHECK_EVERY_S),
|
|
1146
|
+
floor_s=getattr(dev, "floor_s", device_mod.CHECK_FLOOR_S))
|
|
1147
|
+
s.on_page = w.poke
|
|
1148
|
+
w.start()
|
|
1149
|
+
c.watchers.append(w)
|
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
"""THIS COMPUTER AS ONE OF THE ACCOUNT'S DEVICES on the new account service (account recovery v2;
|
|
2
|
+
docs/account-recovery-protocol.md § 8.5, § 8.6) — tools/code-device.mjs, the same file and the same formats.
|
|
3
|
+
|
|
4
|
+
At pairing the computer makes a DEVICE KEY (P-256) and leaves its HELLO beside its code ({spk, label} at helloRef(ref),
|
|
5
|
+
deviceLink.js helloPost — the apps' new devices do the same), so a giver on the new service registers the computer with the
|
|
6
|
+
service (the check code both screens show, an email code or a security key) BEFORE it sends the account's keys. The code is
|
|
7
|
+
unchanged: an older phone pairs it as before. Once paired, the key is kept here (device-keys.json, 0600) with the account's
|
|
8
|
+
service, and `serve` asks the service now and then whether this computer is still one of the account's devices (a
|
|
9
|
+
device-signed GET /v2/account/device, § 8.5). Signed out → the account's keys this computer holds are wiped and its pairing
|
|
10
|
+
stops. A service that cannot be reached, an error, an `unknown` key — nothing changes (never a wipe on a network error).
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import asyncio
|
|
16
|
+
import hashlib
|
|
17
|
+
import os
|
|
18
|
+
import time
|
|
19
|
+
from collections.abc import Awaitable, Callable
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
from typing import Any
|
|
22
|
+
from urllib.parse import quote
|
|
23
|
+
|
|
24
|
+
import httpx
|
|
25
|
+
from cryptography.hazmat.primitives import hashes
|
|
26
|
+
from cryptography.hazmat.primitives.asymmetric import ec
|
|
27
|
+
from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat
|
|
28
|
+
|
|
29
|
+
from . import _js, codekeys, net
|
|
30
|
+
from . import pairings as pp
|
|
31
|
+
from ._js import b64u, unb64u_loose
|
|
32
|
+
|
|
33
|
+
SIGNED_OUT_TEXT = "This computer was signed out of your account. Pair it again from the app."
|
|
34
|
+
CHECK_EVERY_S = 3600 # hourly while serving (each check is signed: it says the computer is in use)
|
|
35
|
+
CHECK_FLOOR_S = 600 # a page connecting asks again, at most this often
|
|
36
|
+
_LABEL_MAX = 64
|
|
37
|
+
# The account service a computer may ask: one of the two the apps use (spaces/public/acctV2Switch.js) — never an address a
|
|
38
|
+
# link names.
|
|
39
|
+
SERVICES = ("https://api.witbitz.chat/v1", "https://wvevotytx5.execute-api.eu-central-1.amazonaws.com")
|
|
40
|
+
_STATES = ("active", "provisional", "revoked", "unknown")
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def device_keys_path() -> Path:
|
|
44
|
+
"""Beside the pairings."""
|
|
45
|
+
env = os.environ.get("WITBITZ_CODE_DEVICE_KEYS")
|
|
46
|
+
return Path(env) if env else pp.pairings_path().parent / "device-keys.json"
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def allowed_base(b: Any) -> bool:
|
|
50
|
+
return isinstance(b, str) and b in SERVICES
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def hello_label(name: str = "") -> str:
|
|
54
|
+
"""This computer's name on the account's device list: what the computers list shows already (the pairing's name)."""
|
|
55
|
+
n = _js.trim(str(name or "")) or pp.hostname()
|
|
56
|
+
return _js.utf16_slice("Code on " + n, 0, _LABEL_MAX)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def new_device_key() -> dict:
|
|
60
|
+
"""→ {spk (the public point, b64url — what the service registers), jwk (the private key, kept here)}."""
|
|
61
|
+
k = ec.generate_private_key(ec.SECP256R1())
|
|
62
|
+
pub = k.public_key().public_numbers()
|
|
63
|
+
return {
|
|
64
|
+
"spk": b64u(k.public_key().public_bytes(Encoding.X962, PublicFormat.UncompressedPoint)),
|
|
65
|
+
"jwk": {"kty": "EC", "crv": "P-256", "x": b64u(pub.x.to_bytes(32, "big")), "y": b64u(pub.y.to_bytes(32, "big")),
|
|
66
|
+
"d": b64u(k.private_numbers().private_value.to_bytes(32, "big"))},
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _private_key(rec: dict) -> ec.EllipticCurvePrivateKey:
|
|
71
|
+
return ec.derive_private_key(int.from_bytes(unb64u_loose(rec["jwk"]["d"]), "big"), ec.SECP256R1())
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
# ── the hello (deviceLink.js helloRef / helloPost / checkDigits) ─────────────────────────────────────────────────────
|
|
75
|
+
def hello_ref(ref: str) -> str:
|
|
76
|
+
return hashlib.sha256(("witbitz-link-hello|" + str(ref)).encode("utf-8")).digest()[:16].hex()
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def hello_post(ref: str, pub: str, spk: str, label: str = "") -> dict:
|
|
80
|
+
"""What to POST to /api/link for a code (ref, pub): the relay wants an epk — the code's own public key."""
|
|
81
|
+
body = _js.stringify({"v": 1, "spk": spk, "label": _js.utf16_slice(str(label), 0, _LABEL_MAX)})
|
|
82
|
+
return {"ref": hello_ref(ref), "epk": pub, "blob": b64u(body.encode("utf-8"))}
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def check_digits(spk: str) -> str:
|
|
86
|
+
"""The 4 digits both screens show for the device being added."""
|
|
87
|
+
h = hashlib.sha256(("witbitz-add-device|" + str(spk)).encode("utf-8")).digest()
|
|
88
|
+
return str(((h[0] << 16) | (h[1] << 8) | h[2]) % 10000).zfill(4)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
# ── the keys file: {v: 1, keys: {<computerId>: {spk, jwk, acct, base, origin, label, at}}} ────────────────────────────
|
|
92
|
+
def _ok_rec(r: Any) -> bool:
|
|
93
|
+
return (isinstance(r, dict) and isinstance(r.get("spk"), str) and isinstance(r.get("jwk"), dict)
|
|
94
|
+
and isinstance(r["jwk"].get("d"), str) and isinstance(r.get("acct"), str) and bool(r["acct"])
|
|
95
|
+
and isinstance(r.get("base"), str) and bool(r["base"]))
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def read_device_keys() -> dict:
|
|
99
|
+
try:
|
|
100
|
+
d = _js.parse(device_keys_path().read_text(encoding="utf-8"))
|
|
101
|
+
return {"v": 1, "keys": d["keys"] if isinstance(d, dict) and isinstance(d.get("keys"), dict) else {}}
|
|
102
|
+
except (OSError, ValueError):
|
|
103
|
+
return {"v": 1, "keys": {}}
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _write(doc: dict) -> None:
|
|
107
|
+
pp.write_private(device_keys_path(), _js.stringify(doc, 1) + "\n")
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def device_key_for(computer_id: str) -> dict | None:
|
|
111
|
+
r = read_device_keys()["keys"].get(computer_id)
|
|
112
|
+
return r if _ok_rec(r) else None
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def save_device_key(computer_id: str, rec: dict) -> None:
|
|
116
|
+
d = read_device_keys()
|
|
117
|
+
d["keys"] = {**d["keys"], computer_id: rec}
|
|
118
|
+
_write(d)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def forget_device_key(computer_id: str) -> bool:
|
|
122
|
+
d = read_device_keys()
|
|
123
|
+
if computer_id not in d["keys"]:
|
|
124
|
+
return False
|
|
125
|
+
_write({"v": 1, "keys": {k: v for k, v in d["keys"].items() if k != computer_id}})
|
|
126
|
+
return True
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def device_record(*, device: dict, v2: dict, origin: Any = "", label: str = "", at: int | None = None) -> dict:
|
|
130
|
+
"""What pairing keeps, once the account's device registered this computer (`v2` from the link: {acct, base})."""
|
|
131
|
+
rec = {"spk": device["spk"], "jwk": device["jwk"], "acct": str(v2["acct"]), "base": str(v2["base"])}
|
|
132
|
+
if net.app_origin(origin):
|
|
133
|
+
rec["origin"] = net.app_origin(origin)
|
|
134
|
+
rec["label"] = _js.utf16_slice(str(label or ""), 0, _LABEL_MAX)
|
|
135
|
+
rec["at"] = at if at is not None else int(time.time() * 1000)
|
|
136
|
+
return rec
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
# ── § 5.4 the device-signed request, § 8.5 the status check ──────────────────────────────────────────────────────────
|
|
140
|
+
def _jcs(v: Any) -> str:
|
|
141
|
+
"""RFC 8785 for what the request bytes carry (strings, safe integers, plain objects)."""
|
|
142
|
+
if isinstance(v, dict):
|
|
143
|
+
return "{" + ",".join(_js.stringify(k) + ":" + _jcs(v[k]) for k in sorted(v)) + "}"
|
|
144
|
+
if isinstance(v, bool) or v is None:
|
|
145
|
+
raise ValueError("jcs: unsupported value")
|
|
146
|
+
if isinstance(v, int):
|
|
147
|
+
return str(v)
|
|
148
|
+
return _js.stringify(v)
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def _enc3986(s: str) -> str:
|
|
152
|
+
return quote(str(s), safe="-_.~")
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def canonical_query(q: dict) -> str:
|
|
156
|
+
pairs = sorted((_enc3986(k), _enc3986(v)) for k, v in q.items())
|
|
157
|
+
return "&".join(k + "=" + v for k, v in pairs)
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def device_request_bytes(*, method: str, path: str, query: str = "", body: bytes = b"", ts: int, nonce: str) -> bytes:
|
|
161
|
+
obj = {"method": method.upper(), "path": path, "query": query, "body_sha256": hashlib.sha256(body).hexdigest(), "ts": ts, "nonce": nonce}
|
|
162
|
+
return b"witbitz-device-v1\x00" + _jcs(obj).encode("utf-8")
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def signed_headers(rec: dict, *, method: str, path: str, query: str = "", body: bytes = b"", now: float | None = None) -> dict:
|
|
166
|
+
ts = int(now if now is not None else time.time())
|
|
167
|
+
nonce = b64u(os.urandom(9))
|
|
168
|
+
sig = _private_key(rec).sign(device_request_bytes(method=method, path=path, query=query, body=body, ts=ts, nonce=nonce), ec.ECDSA(hashes.SHA256()))
|
|
169
|
+
return {"x-dev-spk": rec["spk"], "x-dev-ts": str(ts), "x-dev-nonce": nonce, "x-dev-sig": b64u(sig)} # DER, as the service verifies
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
async def device_state(rec: dict, *, client: httpx.AsyncClient | None = None, allow_base: Callable[[Any], bool] = allowed_base,
|
|
173
|
+
timeout_s: float = 20) -> str:
|
|
174
|
+
"""'active' | 'provisional' | 'revoked' | 'unknown' (a key the service does not know) | 'error' (no answer, a refusal, an
|
|
175
|
+
answer that does not name this key and this request's nonce, a service not allowed). Only 'revoked' removes anything.
|
|
176
|
+
The account's app is named by the Origin it was paired from (a hosted account's scope on the service)."""
|
|
177
|
+
if not _ok_rec(rec) or not allow_base(rec.get("base")):
|
|
178
|
+
return "error"
|
|
179
|
+
own = client is None
|
|
180
|
+
http = client or httpx.AsyncClient(timeout=httpx.Timeout(timeout_s), follow_redirects=False)
|
|
181
|
+
try:
|
|
182
|
+
path = "/v2/account/device"
|
|
183
|
+
nonce = b64u(os.urandom(9))
|
|
184
|
+
query = canonical_query({"nonce": nonce})
|
|
185
|
+
headers = {"content-type": "application/json", **signed_headers(rec, method="GET", path=path, query=query)}
|
|
186
|
+
origin = net.app_origin(rec.get("origin"))
|
|
187
|
+
if origin:
|
|
188
|
+
headers["origin"] = origin
|
|
189
|
+
r = await http.get(rec["base"].rstrip("/") + path + "?" + query, headers=headers, timeout=timeout_s)
|
|
190
|
+
try:
|
|
191
|
+
j = r.json()
|
|
192
|
+
except ValueError:
|
|
193
|
+
return "error"
|
|
194
|
+
if r.status_code != 200 or not isinstance(j, dict) or j.get("ok") is not True:
|
|
195
|
+
return "error"
|
|
196
|
+
if j.get("spk") != rec["spk"] or j.get("nonce") != nonce: # not an answer to THIS request for THIS key
|
|
197
|
+
return "error"
|
|
198
|
+
return j["state"] if j.get("state") in _STATES else "error"
|
|
199
|
+
except (httpx.HTTPError, OSError, ValueError, KeyError):
|
|
200
|
+
return "error"
|
|
201
|
+
finally:
|
|
202
|
+
if own:
|
|
203
|
+
await http.aclose()
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
async def wipe_signed_out(computer_id: str, *, revoke: Callable[[dict], Awaitable[bool]] | None = None,
|
|
207
|
+
log: Callable[[str], Any] = lambda _m: None) -> None:
|
|
208
|
+
"""SIGNED OUT: the account's keys this computer holds go — its pairing (the account room's key and the relay secret), its
|
|
209
|
+
coding keys (given back first, best effort: a signed-out computer may be offline), its device key. Its OpenCode sessions
|
|
210
|
+
are this computer's own files and stay."""
|
|
211
|
+
entry = codekeys.for_computer(computer_id)
|
|
212
|
+
if entry:
|
|
213
|
+
try:
|
|
214
|
+
if revoke is not None:
|
|
215
|
+
await revoke(entry)
|
|
216
|
+
else:
|
|
217
|
+
async with httpx.AsyncClient(timeout=httpx.Timeout(20.0)) as c:
|
|
218
|
+
await codekeys.revoke(c, entry)
|
|
219
|
+
except Exception: # noqa: BLE001 — gone anyway, below
|
|
220
|
+
pass
|
|
221
|
+
codekeys.forget(computer_id)
|
|
222
|
+
try:
|
|
223
|
+
cur = pp.read_pairings()
|
|
224
|
+
nxt = pp.remove_pairings(cur, computer_id=computer_id)
|
|
225
|
+
if nxt.get("removed"):
|
|
226
|
+
pp.write_pairings(nxt["doc"])
|
|
227
|
+
except OSError as e:
|
|
228
|
+
log(f"witbitz-code: could not remove the pairing ({e})")
|
|
229
|
+
forget_device_key(computer_id)
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
class DeviceWatch:
|
|
233
|
+
"""Asks the service about one pairing: now, every `every_s`, and on poke() (a page connected) at most every `floor_s`.
|
|
234
|
+
`check()` → device_state; on 'revoked' it stops and calls `on_revoked()` once."""
|
|
235
|
+
|
|
236
|
+
def __init__(self, check: Callable[[], Awaitable[str]], on_revoked: Callable[[], Awaitable[None]], *,
|
|
237
|
+
every_s: float = CHECK_EVERY_S, floor_s: float = CHECK_FLOOR_S, now: Callable[[], float] = time.monotonic) -> None:
|
|
238
|
+
self._check, self._on_revoked = check, on_revoked
|
|
239
|
+
self._every, self._floor, self._now = every_s, floor_s, now
|
|
240
|
+
self._last = -float("inf")
|
|
241
|
+
self._busy: asyncio.Future | None = None
|
|
242
|
+
self.stopped = False
|
|
243
|
+
self._timer: asyncio.Task | None = None
|
|
244
|
+
self.ready: asyncio.Future | None = None
|
|
245
|
+
|
|
246
|
+
def start(self) -> None:
|
|
247
|
+
self.ready = self.run()
|
|
248
|
+
self._timer = asyncio.get_running_loop().create_task(self._tick())
|
|
249
|
+
|
|
250
|
+
async def _tick(self) -> None:
|
|
251
|
+
while not self.stopped:
|
|
252
|
+
await asyncio.sleep(self._every)
|
|
253
|
+
if not self.stopped:
|
|
254
|
+
await self.run()
|
|
255
|
+
|
|
256
|
+
def run(self) -> asyncio.Future:
|
|
257
|
+
if self.stopped:
|
|
258
|
+
f = asyncio.get_running_loop().create_future()
|
|
259
|
+
f.set_result("stopped")
|
|
260
|
+
return f
|
|
261
|
+
if self._busy is not None and not self._busy.done():
|
|
262
|
+
return self._busy
|
|
263
|
+
self._last = self._now()
|
|
264
|
+
self._busy = asyncio.ensure_future(self._one())
|
|
265
|
+
return self._busy
|
|
266
|
+
|
|
267
|
+
async def _one(self) -> str:
|
|
268
|
+
try:
|
|
269
|
+
st = await self._check()
|
|
270
|
+
except Exception: # noqa: BLE001 — never a wipe on an error
|
|
271
|
+
st = "error"
|
|
272
|
+
if st == "revoked" and not self.stopped:
|
|
273
|
+
self.stop()
|
|
274
|
+
await self._on_revoked()
|
|
275
|
+
return st
|
|
276
|
+
|
|
277
|
+
def poke(self) -> asyncio.Future | None:
|
|
278
|
+
return self.run() if self._now() - self._last >= self._floor else None
|
|
279
|
+
|
|
280
|
+
def stop(self) -> None:
|
|
281
|
+
self.stopped = True
|
|
282
|
+
if self._timer is not None and self._timer is not asyncio.current_task():
|
|
283
|
+
self._timer.cancel()
|
|
@@ -154,6 +154,9 @@ def read_link_payload(p: Any) -> dict | None:
|
|
|
154
154
|
"pipes": _ptr(p.get("pipes")),
|
|
155
155
|
"msgs": _ptr(p.get("msgs")), # the message room (deviceLink.js since b27a27d0)
|
|
156
156
|
"anchor": anchor,
|
|
157
|
+
# § 8.6 — an account on the NEW service: where this computer (registered by the giver first) is one of its devices
|
|
158
|
+
**({"v2": {"acct": v2["acct"], "base": v2["base"]}} if isinstance(v2 := p.get("v2"), dict)
|
|
159
|
+
and isinstance(v2.get("acct"), str) and v2["acct"] and isinstance(v2.get("base"), str) and v2["base"] else {}),
|
|
157
160
|
}
|
|
158
161
|
|
|
159
162
|
|
|
@@ -25,6 +25,7 @@ from ._js import truthy
|
|
|
25
25
|
|
|
26
26
|
DEFAULT_ORIGINS = "https://spaces.witbitz.chat,https://witbitz-spaces.pages.dev"
|
|
27
27
|
POLL_S = 2.5
|
|
28
|
+
HELLO_AGAIN_S = 60 # the hello is left again this often while the code waits (the relay keeps one two minutes)
|
|
28
29
|
LIFE_MS = 300_000 # the ref stays valid until a seal is posted, so a slow (Google-failed → email-code) verification fits
|
|
29
30
|
|
|
30
31
|
|
|
@@ -58,6 +59,10 @@ def account_from_payload(pay: Any) -> dict | None:
|
|
|
58
59
|
"rel": orelse(pay.get("rel"), None),
|
|
59
60
|
"pipes": orelse(pay.get("pipes"), None),
|
|
60
61
|
"anchor": orelse(anchor, None),
|
|
62
|
+
# an account on the NEW service: the giver registered this computer's device key there first (§ 8.6) — where to ask
|
|
63
|
+
# whether it still is one of the account's devices (device.py). Absent = an old-service account, or an older giver.
|
|
64
|
+
**({"v2": {"acct": pay["v2"]["acct"], "base": pay["v2"]["base"]}} if isinstance(pay.get("v2"), dict)
|
|
65
|
+
and truthy(pay["v2"].get("acct")) and truthy(pay["v2"].get("base")) else {}),
|
|
61
66
|
}
|
|
62
67
|
|
|
63
68
|
|
|
@@ -129,7 +134,7 @@ def _err(*a: Any) -> None:
|
|
|
129
134
|
async def link_node(*, life_ms: float | None = None, poll_s: float = POLL_S, origins: list[str] | None = None,
|
|
130
135
|
get_json: net.GetJson | None = None, post_json: net.PostJson | None = None,
|
|
131
136
|
challenge: devicelink.LinkChallenge | None = None, svg_path: Path | None = None,
|
|
132
|
-
out: Callable = _out, err: Callable = _err) -> dict | None:
|
|
137
|
+
out: Callable = _out, err: Callable = _err, device: dict | None = None) -> dict | None:
|
|
133
138
|
"""Show the device-link QR and wait for a signed-in device to seal the account to this computer. Returns the account,
|
|
134
139
|
or None when it did not complete (expired, or a reply that would not open) — never exits the process."""
|
|
135
140
|
if origins is None:
|
|
@@ -143,7 +148,7 @@ async def link_node(*, life_ms: float | None = None, poll_s: float = POLL_S, ori
|
|
|
143
148
|
get_json = get_json or net.make_get_json(client)
|
|
144
149
|
post_json = post_json or net.make_post_json(client)
|
|
145
150
|
try:
|
|
146
|
-
return await _link(life_ms, poll_s, origins, get_json, post_json, challenge, svg_path, out, err)
|
|
151
|
+
return await _link(life_ms, poll_s, origins, get_json, post_json, challenge, svg_path, out, err, device)
|
|
147
152
|
finally:
|
|
148
153
|
if client is not None:
|
|
149
154
|
await client.aclose()
|
|
@@ -166,10 +171,30 @@ def _reporter(priv, reply: dict, origin: str) -> Callable[..., Awaitable[None]]:
|
|
|
166
171
|
return report
|
|
167
172
|
|
|
168
173
|
|
|
169
|
-
async def
|
|
174
|
+
async def _leave_hello(origins: list[str], post_json: net.PostJson, hello: dict) -> None:
|
|
175
|
+
for origin in origins:
|
|
176
|
+
try:
|
|
177
|
+
await post_json(f"{origin}/api/link", hello)
|
|
178
|
+
except Exception: # noqa: BLE001 — that relay is down (or still holds it: 409)
|
|
179
|
+
pass
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
async def _link(life_ms, poll_s, origins, get_json, post_json, challenge, svg_path, out, err, device=None) -> dict | None:
|
|
170
183
|
ch = challenge or devicelink.new_link_challenge()
|
|
184
|
+
# THE HELLO (`device` = {spk, label}; device.py): this computer's device key and name, left beside its code at every relay
|
|
185
|
+
# polled, so a giver on the new account service registers it before sending anything (§ 8.6) — the hello the apps' new
|
|
186
|
+
# devices leave (deviceLink.js helloPost). The relay keeps it two minutes: it is left again while we wait (a 409 — still
|
|
187
|
+
# there, or collected — is fine). The code is unchanged: an older phone pairs it as before.
|
|
188
|
+
from . import device as device_mod # noqa: PLC0415 — device.py imports pairings, which this module does not need otherwise
|
|
189
|
+
|
|
190
|
+
hello = device_mod.hello_post(ch.ref, ch.pub, device["spk"], device.get("label") or "") if isinstance(device, dict) and device.get("spk") else None
|
|
191
|
+
if hello:
|
|
192
|
+
await _leave_hello(origins, post_json, hello)
|
|
193
|
+
hello_at = time.monotonic()
|
|
171
194
|
out(f"witbitz-code: pairing this computer with your account · polling {', '.join(origins)}\n")
|
|
172
195
|
out(qr.qr_ansi(ch.text) + "\n")
|
|
196
|
+
if hello:
|
|
197
|
+
out(f" Check code {device_mod.check_digits(device['spk'])} — the device that scans this shows it too. Continue there only if they match.\n")
|
|
173
198
|
svg = svg_path or Path.home() / ".witbitz-rc.link.svg"
|
|
174
199
|
try:
|
|
175
200
|
_write_private(svg, qr.qr_svg(ch.text) + "\n")
|
|
@@ -183,6 +208,9 @@ async def _link(life_ms, poll_s, origins, get_json, post_json, challenge, svg_pa
|
|
|
183
208
|
found = ""
|
|
184
209
|
while time.monotonic() < until:
|
|
185
210
|
await asyncio.sleep(poll_s)
|
|
211
|
+
if hello and time.monotonic() - hello_at >= HELLO_AGAIN_S:
|
|
212
|
+
hello_at = time.monotonic()
|
|
213
|
+
await _leave_hello(origins, post_json, hello)
|
|
186
214
|
r = None
|
|
187
215
|
for origin in origins:
|
|
188
216
|
try:
|