witbitz-code 1.15.3__tar.gz → 1.15.5__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.3/src/witbitz_code.egg-info → witbitz_code-1.15.5}/PKG-INFO +1 -1
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/pyproject.toml +1 -1
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/src/witbitz_code/__init__.py +1 -1
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/src/witbitz_code/account.py +10 -2
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/src/witbitz_code/auto_runner.py +24 -3
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/src/witbitz_code/cli.py +11 -2
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/src/witbitz_code/codekeys.py +9 -1
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/src/witbitz_code/connector.py +108 -3
- witbitz_code-1.15.5/src/witbitz_code/device.py +283 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/src/witbitz_code/devicelink.py +11 -2
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/src/witbitz_code/link.py +36 -7
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/src/witbitz_code/offered_models.json +1 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/src/witbitz_code/pair.py +60 -15
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/src/witbitz_code/pairings.py +51 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5/src/witbitz_code.egg-info}/PKG-INFO +1 -1
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/src/witbitz_code.egg-info/SOURCES.txt +2 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/tests/test_auto.py +65 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/tests/test_codekeys.py +4 -1
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/tests/test_connector_e2e.py +39 -0
- witbitz_code-1.15.5/tests/test_device.py +323 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/tests/test_devicelink.py +42 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/tests/test_files_and_compress.py +9 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/tests/test_pair_flows.py +79 -4
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/LICENSE +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/README.md +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/setup.cfg +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/src/witbitz_code/__main__.py +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/src/witbitz_code/_js.py +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/src/witbitz_code/app.py +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/src/witbitz_code/asks.py +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/src/witbitz_code/attachments.py +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/src/witbitz_code/auto.py +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/src/witbitz_code/browse.py +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/src/witbitz_code/browsetree.py +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/src/witbitz_code/codetools.py +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/src/witbitz_code/compress.py +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/src/witbitz_code/computers.py +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/src/witbitz_code/confidential.py +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/src/witbitz_code/confidential_models.json +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/src/witbitz_code/dirs.py +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/src/witbitz_code/files.py +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/src/witbitz_code/folders.py +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/src/witbitz_code/gateway.py +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/src/witbitz_code/icons/witbitz-code-wsl.ico +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/src/witbitz_code/icons/witbitz-code.ico +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/src/witbitz_code/images.py +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/src/witbitz_code/keys.py +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/src/witbitz_code/mkdir.py +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/src/witbitz_code/models.py +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/src/witbitz_code/net.py +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/src/witbitz_code/opencode_plugins/notes-init.md +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/src/witbitz_code/opencode_plugins/witbitz-browse-cdp.mjs +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/src/witbitz_code/opencode_plugins/witbitz-browse-local.mjs +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/src/witbitz_code/opencode_plugins/witbitz-browse-publisher.mjs +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/src/witbitz_code/opencode_plugins/witbitz-browse-tree.mjs +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/src/witbitz_code/opencode_plugins/witbitz-browser.js +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/src/witbitz_code/opencode_plugins/witbitz-media-server.mjs +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/src/witbitz_code/opencode_plugins/witbitz-notes.js +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/src/witbitz_code/opencode_plugins/witbitz-progress.js +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/src/witbitz_code/outputs.py +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/src/witbitz_code/payers.py +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/src/witbitz_code/plugins.py +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/src/witbitz_code/policy.py +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/src/witbitz_code/ports.py +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/src/witbitz_code/qr.py +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/src/witbitz_code/receipt.py +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/src/witbitz_code/relay.py +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/src/witbitz_code/remind.py +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/src/witbitz_code/seccheck.py +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/src/witbitz_code/seen.py +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/src/witbitz_code/selfupdate.py +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/src/witbitz_code/tinfoil_read.py +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/src/witbitz_code/tools_catalog.json +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/src/witbitz_code/tools_probe.py +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/src/witbitz_code/toolsetup.py +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/src/witbitz_code/ui.py +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/src/witbitz_code/ui_static/app.css +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/src/witbitz_code/ui_static/app.js +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/src/witbitz_code/ui_static/index.html +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/src/witbitz_code/uitools.py +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/src/witbitz_code/uninstall.py +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/src/witbitz_code/winagent.py +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/src/witbitz_code/winbg.py +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/src/witbitz_code/winconsole.py +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/src/witbitz_code/wizard.py +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/src/witbitz_code/wslstart.py +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/src/witbitz_code.egg-info/dependency_links.txt +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/src/witbitz_code.egg-info/entry_points.txt +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/src/witbitz_code.egg-info/requires.txt +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/src/witbitz_code.egg-info/top_level.txt +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/tests/test_asks.py +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/tests/test_attachments.py +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/tests/test_browse.py +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/tests/test_browsetree.py +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/tests/test_cli.py +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/tests/test_codetools.py +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/tests/test_confidential.py +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/tests/test_dirs.py +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/tests/test_files.py +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/tests/test_folders.py +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/tests/test_images.py +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/tests/test_outputs.py +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/tests/test_plugins.py +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/tests/test_policy.py +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/tests/test_ports.py +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/tests/test_ports_win.py +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/tests/test_registry.py +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/tests/test_relay_codec.py +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/tests/test_remind.py +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/tests/test_seccheck.py +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/tests/test_selfupdate.py +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/tests/test_setup.py +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/tests/test_tools_probe.py +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/tests/test_toolsetup.py +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/tests/test_ui.py +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/tests/test_ui_page.py +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/tests/test_uitools.py +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/tests/test_uninstall.py +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/tests/test_winagent.py +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/tests/test_winbg.py +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/tests/test_winconsole.py +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/tests/test_windows_files.py +0 -0
- {witbitz_code-1.15.3 → witbitz_code-1.15.5}/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.5"
|
|
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"
|
|
@@ -55,12 +55,20 @@ def _write_body(idx: dict, name: str, patch: Any, summary: str) -> dict:
|
|
|
55
55
|
|
|
56
56
|
|
|
57
57
|
async def publish_computer(*, call: ApiCall, idx: dict, computer_id: str, name: str, relay: str, secret: str,
|
|
58
|
-
now: float | None = None) -> dict:
|
|
59
|
-
"""Put (or refresh) this computer in the account's registry.
|
|
58
|
+
now: float | None = None, revive: bool = False) -> dict:
|
|
59
|
+
"""Put (or refresh) this computer in the account's registry.
|
|
60
|
+
|
|
61
|
+
A COMPUTER THE ACCOUNT REMOVED DOES NOT PUT ITSELF BACK (state machines pass 9, C#3; tools/opencode-pair.mjs
|
|
62
|
+
publishComputer): `rotate`, a rename and setup's WSL rename publish with no scan, and the live entry they wrote
|
|
63
|
+
outranked the removal's tombstone on every device. Only a scan passes `revive`."""
|
|
60
64
|
now = _now_ms() if now is None else now
|
|
61
65
|
rd = await read_doc(call, idx, COMPUTERS_DOC)
|
|
62
66
|
if not rd["ok"]:
|
|
63
67
|
return rd
|
|
68
|
+
was = norm_registry(rd["state"])["computers"].get(computer_id)
|
|
69
|
+
if was and was.get("removed") and not revive:
|
|
70
|
+
return {"ok": False, "removed": True,
|
|
71
|
+
"why": "this computer was removed from the account — pair it again (scan the code) to add it back"}
|
|
64
72
|
nxt = with_computer(rd["state"], computer_id, {"name": name, "relay": relay, "secret": secret}, now)
|
|
65
73
|
wr = await call(_write_body(idx, COMPUTERS_DOC, wrap_index_state({**nxt, "at": now}), "computer paired"))
|
|
66
74
|
if wr.status != 200:
|
|
@@ -430,12 +430,17 @@ class AutoRunner:
|
|
|
430
430
|
verdict, model, note = await self._review(req, directory, owner, folders)
|
|
431
431
|
action = det["decision"] if det else action_for(verdict)
|
|
432
432
|
reason_given = (verdict or {}).get("reason") or ""
|
|
433
|
-
rec = log_record(req=req, stage=stage, verdict=verdict, action=action, model=model, ms=self._now() - t0, at=t0)
|
|
434
433
|
reason = reason_given or note or ""
|
|
434
|
+
# AUTO WAS SWITCHED OFF WHILE THIS WAS DECIDED (state machines pass 9, C#2): a review takes up to 45 s and the person's
|
|
435
|
+
# card is on screen after 2.5 — the answer that came back still allowed the command (or held a refusal nobody would
|
|
436
|
+
# send). Whatever was decided, an ask whose session is no longer in Auto is the person's.
|
|
437
|
+
if action != "ask" and not await self._owner_of(req["sessionID"], directory):
|
|
438
|
+
action, reason = "ask", "Auto mode was switched off before this was decided."
|
|
439
|
+
rec = log_record(req=req, stage=stage, verdict=verdict, action=action, model=model, ms=self._now() - t0, at=t0)
|
|
435
440
|
if action == "deny":
|
|
436
441
|
# HELD, not sent (see the module docstring). The page hears it now (answered None) and again when it lands.
|
|
437
442
|
self._held.setdefault(req["sessionID"], {})[req["id"]] = {
|
|
438
|
-
"req": req, "dir": directory, "stage": stage, "rec": rec, "reason": reason,
|
|
443
|
+
"req": req, "dir": directory, "owner": owner or req["sessionID"], "stage": stage, "rec": rec, "reason": reason,
|
|
439
444
|
"message": f"{reason_given or 'Refused by Auto mode.'} {REFUSAL_SUFFIX}"}
|
|
440
445
|
self._emit(req, stage, action, rec, reason, None)
|
|
441
446
|
return
|
|
@@ -493,7 +498,12 @@ class AutoRunner:
|
|
|
493
498
|
if pending is None:
|
|
494
499
|
continue
|
|
495
500
|
for req in pending:
|
|
496
|
-
if not isinstance(req, dict) or not isinstance(req.get("id"), str)
|
|
501
|
+
if not isinstance(req, dict) or not isinstance(req.get("id"), str):
|
|
502
|
+
continue
|
|
503
|
+
# STILL WAITING = STILL HANDLED (pass 9, C#1): the 30 minutes forget asks that are GONE. An ask Auto left for
|
|
504
|
+
# the person was forgotten while it waited, reviewed again, and a second "allow" ran it with nobody at the card.
|
|
505
|
+
if req["id"] in self._handled:
|
|
506
|
+
self._handled[req["id"]] = self._now()
|
|
497
507
|
continue
|
|
498
508
|
sid = req.get("sessionID")
|
|
499
509
|
if not isinstance(sid, str):
|
|
@@ -542,6 +552,17 @@ class AutoRunner:
|
|
|
542
552
|
self._auto[session_id] = {"dir": directory, "at": self._now()} # an existing key keeps its place, as Map.set does
|
|
543
553
|
else:
|
|
544
554
|
self._auto.pop(session_id, None)
|
|
555
|
+
# WHAT AUTO WAS HOLDING GOES BACK TO THE PERSON (pass 9, C#2): a refusal held for this session (its own asks and
|
|
556
|
+
# its subagents') was never sent once the loop stopped looking at the folder — and the page had dropped its card
|
|
557
|
+
# at the held verdict. `answered: False` gives the card back; nothing is sent in Auto's name any more.
|
|
558
|
+
for sid in list(self._held):
|
|
559
|
+
refusals = self._held.get(sid) or {}
|
|
560
|
+
for h in [x for x in list(refusals.values()) if x.get("owner") == session_id]:
|
|
561
|
+
refusals.pop(h["req"]["id"], None)
|
|
562
|
+
self._append_log({**h["rec"], "answered": False})
|
|
563
|
+
self._emit(h["req"], h["stage"], "deny", h["rec"], h["reason"], False)
|
|
564
|
+
if not refusals:
|
|
565
|
+
self._held.pop(sid, None)
|
|
545
566
|
self._save()
|
|
546
567
|
return True
|
|
547
568
|
|
|
@@ -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:
|
|
@@ -287,8 +287,16 @@ async def status(client: httpx.AsyncClient, entry: dict) -> dict:
|
|
|
287
287
|
"""{live, why?, month?} — and a Tinfoil key minted or renewed server-side is opened into the entry (the caller saves).
|
|
288
288
|
live None: the answer could not be had, and `why` says why."""
|
|
289
289
|
r = await _signed_post(client, "/status", "status", entry)
|
|
290
|
+
# ONLY THE ACCOUNT'S OWN "no such coding key" IS A REVOCATION (state machines pass 9, C#5). Any 404 was read as one — a
|
|
291
|
+
# gateway's route miss during a deploy, a wrong WITBITZ_CODE_KEYS_API — and `check` then DELETED the entry, the signing
|
|
292
|
+
# key with it: every serving computer "must be paired again" after the server was back. Another 404 is "unknown".
|
|
290
293
|
if r.status_code == 404:
|
|
291
|
-
|
|
294
|
+
try:
|
|
295
|
+
code = str(((r.json() or {}).get("error") or {}).get("code") or "")
|
|
296
|
+
except ValueError:
|
|
297
|
+
code = "" # not JSON: not the account's answer
|
|
298
|
+
if code == "not_found":
|
|
299
|
+
return {"live": False, "why": "revoked"}
|
|
292
300
|
if r.status_code != 200:
|
|
293
301
|
return {"live": None, "why": _why(r)} # unknown — keep going as before, and say why
|
|
294
302
|
d = (r.json() or {}).get("data") or {}
|
|
@@ -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
|
|
@@ -69,6 +70,40 @@ def default_auto_dir() -> Path:
|
|
|
69
70
|
return Path(os.environ.get("WITBITZ_CODE_AUTO_DIR") or app.code_dir())
|
|
70
71
|
|
|
71
72
|
|
|
73
|
+
def hello_clock(path: Path, *, now: Callable[[], float] | None = None, reserve_ms: int = 60_000) -> Callable[[], int]:
|
|
74
|
+
"""THE HELLO'S CLOCK NEVER STEPS BACK (state machines pass 9, C#10; tools/opencode-connector.mjs helloClock). A page
|
|
75
|
+
drops a hello whose ts is not after the last one it heard (codeTransport.js — a replayed OLD hello must not move it back
|
|
76
|
+
onto a dead nonce), and ts was the wall clock: after a backward step every open page read this computer "offline" and
|
|
77
|
+
kept a nonce that got 409 on every request, until the clock caught up. Now ts = max(clock, last + 1), and the high-water
|
|
78
|
+
mark is kept in `path` RESERVED a minute ahead (written at most once a minute), so a restart behind the clock still
|
|
79
|
+
starts after every hello the last process sent. Same file and shape as the JS connector."""
|
|
80
|
+
clock = now or (lambda: time.time() * 1000)
|
|
81
|
+
state = {"reserved": 0, "last": 0}
|
|
82
|
+
try:
|
|
83
|
+
state["reserved"] = int(_js.to_number(json.loads(path.read_text(encoding="utf-8")).get("upTo")) or 0)
|
|
84
|
+
except (OSError, ValueError, AttributeError, TypeError, OverflowError):
|
|
85
|
+
state["reserved"] = 0
|
|
86
|
+
state["last"] = state["reserved"]
|
|
87
|
+
|
|
88
|
+
def next_ts() -> int:
|
|
89
|
+
ts = max(int(clock()), state["last"] + 1)
|
|
90
|
+
state["last"] = ts
|
|
91
|
+
if ts > state["reserved"]:
|
|
92
|
+
state["reserved"] = ts + reserve_ms
|
|
93
|
+
try:
|
|
94
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
95
|
+
tmp = path.with_name(path.name + ".tmp")
|
|
96
|
+
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
|
97
|
+
with os.fdopen(fd, "w", encoding="utf-8") as f:
|
|
98
|
+
f.write(json.dumps({"v": 1, "upTo": state["reserved"]}) + "\n")
|
|
99
|
+
os.replace(tmp, path)
|
|
100
|
+
except OSError:
|
|
101
|
+
pass # memory still orders this process's hellos
|
|
102
|
+
return ts
|
|
103
|
+
|
|
104
|
+
return next_ts
|
|
105
|
+
|
|
106
|
+
|
|
72
107
|
def _round(x: float) -> int:
|
|
73
108
|
return math.floor(x + 0.5) # Math.round, not banker's rounding
|
|
74
109
|
|
|
@@ -215,6 +250,8 @@ class PairingServer:
|
|
|
215
250
|
# must carry the CURRENT one: a recording from before a restart or reconnect carries a nonce nobody accepts.
|
|
216
251
|
self.nonce = ""
|
|
217
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
|
|
218
255
|
self.peer = RelayPeer(secret=pairing["secret"], role="computer", relay=pairing.get("relay") or RELAY_URL,
|
|
219
256
|
on_state=self._on_state, on_peers=self._on_peers, on_message=self._on_message, connect=connect,
|
|
220
257
|
# A page socket fell out of the replay window: its recorded frames would open again — rotate the
|
|
@@ -226,6 +263,7 @@ class PairingServer:
|
|
|
226
263
|
self._output_log = auto_dir / "output-log.jsonl" # each preview fetch: a digest of the path, never the path
|
|
227
264
|
self._seen_path = auto_dir / f"seen-{safe_id}.json" # what the person has seen, shared by their devices (seen.py)
|
|
228
265
|
self._seen: dict | None = None
|
|
266
|
+
self._hello_ts = hello_clock(auto_dir / f"hello-{safe_id}.json") # never steps back (pass 9, C#10)
|
|
229
267
|
self.auto = AutoRunner(base=self.base, auth=self._auth, client=client, poll_ms=auto_poll_ms, log=log,
|
|
230
268
|
state_path=auto_dir / f"auto-{safe_id}.json", log_path=auto_dir / "auto-log.jsonl",
|
|
231
269
|
on_verdict=lambda v: self.peer.send({"t": "autoverdict", **v, "ts": int(time.time() * 1000)}),
|
|
@@ -285,6 +323,9 @@ class PairingServer:
|
|
|
285
323
|
self.hello()
|
|
286
324
|
|
|
287
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
|
|
288
329
|
if n >= 2:
|
|
289
330
|
self.hello()
|
|
290
331
|
else:
|
|
@@ -321,7 +362,7 @@ class PairingServer:
|
|
|
321
362
|
self._browse_said = json.dumps(browse, sort_keys=True)
|
|
322
363
|
# caps: what this connector can do beyond the requests — a page shows the Auto switch only when `auto` is here.
|
|
323
364
|
return self.peer.send({"t": "hello", "ver": VERSION, "name": self.name, "computerId": self.pairing.get("computerId") or "",
|
|
324
|
-
"k": self.nonce, "ts":
|
|
365
|
+
"k": self.nonce, "ts": self._hello_ts(), "caps": ["auto", "attachments", "outputs", "tools", "seen", "asks", "folders", "remind", "files"], "auto": self.auto.sessions(),
|
|
325
366
|
**({"browse": browse} if browse else {})})
|
|
326
367
|
|
|
327
368
|
def _auth(self) -> dict:
|
|
@@ -968,6 +1009,9 @@ class PairingServer:
|
|
|
968
1009
|
self._unsubscribe(p, _ALL)
|
|
969
1010
|
|
|
970
1011
|
|
|
1012
|
+
_DEFAULT_DEVICES = object() # start_connector: the real key file / service — tests pass their own, or None
|
|
1013
|
+
|
|
1014
|
+
|
|
971
1015
|
class _Aborted(Exception):
|
|
972
1016
|
pass
|
|
973
1017
|
|
|
@@ -977,12 +1021,19 @@ class Connector:
|
|
|
977
1021
|
servers: list[PairingServer]
|
|
978
1022
|
client: httpx.AsyncClient
|
|
979
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)))
|
|
980
1029
|
|
|
981
1030
|
@property
|
|
982
1031
|
def peers(self) -> list[RelayPeer]:
|
|
983
1032
|
return [s.peer for s in self.servers]
|
|
984
1033
|
|
|
985
1034
|
def stop(self) -> None:
|
|
1035
|
+
for w in self.watchers:
|
|
1036
|
+
w.stop()
|
|
986
1037
|
for s in self.servers:
|
|
987
1038
|
s.stop()
|
|
988
1039
|
|
|
@@ -998,6 +1049,8 @@ class Connector:
|
|
|
998
1049
|
asyncio.ensure_future(s.peer.send({"t": "progress", **ev, "ts": int(time.time() * 1000)}))
|
|
999
1050
|
|
|
1000
1051
|
async def aclose(self) -> None:
|
|
1052
|
+
for w in self.watchers:
|
|
1053
|
+
w.stop()
|
|
1001
1054
|
for s in self.servers:
|
|
1002
1055
|
await s.aclose()
|
|
1003
1056
|
await self.client.aclose()
|
|
@@ -1022,7 +1075,8 @@ async def start_connector(pairings: list[dict], *, flush_ms: float = 120, log: C
|
|
|
1022
1075
|
notes_plugin_path: Path | None = None, payers: SessionPayers | None = None,
|
|
1023
1076
|
model_url: str = "", remind_times: dict | None = None,
|
|
1024
1077
|
browse_probe: Callable[[], dict | None] | None = None,
|
|
1025
|
-
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:
|
|
1026
1080
|
"""Serve the given pairings until stop()/aclose(). Options exist for tests: flush_ms, log, client, connect,
|
|
1027
1081
|
request_timeout_ms, max_senders, max_response_bytes, auto_dir, auto_poll_ms."""
|
|
1028
1082
|
client = client or local_client()
|
|
@@ -1041,4 +1095,55 @@ async def start_connector(pairings: list[dict], *, flush_ms: float = 120, log: C
|
|
|
1041
1095
|
browse_probe=browse_probe, browse_private=browse_private, screens_root=screens_root)
|
|
1042
1096
|
await s.start()
|
|
1043
1097
|
servers.append(s)
|
|
1044
|
-
|
|
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()
|