witbitz-code 1.15.2__tar.gz → 1.15.4__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.2/src/witbitz_code.egg-info → witbitz_code-1.15.4}/PKG-INFO +1 -1
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/pyproject.toml +1 -1
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/src/witbitz_code/__init__.py +1 -1
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/src/witbitz_code/account.py +10 -2
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/src/witbitz_code/auto_runner.py +24 -3
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/src/witbitz_code/codekeys.py +9 -1
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/src/witbitz_code/connector.py +65 -18
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/src/witbitz_code/devicelink.py +8 -2
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/src/witbitz_code/link.py +18 -10
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/src/witbitz_code/opencode_plugins/witbitz-browse-publisher.mjs +47 -5
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/src/witbitz_code/pair.py +37 -12
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/src/witbitz_code/pairings.py +51 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/src/witbitz_code/ui_static/app.js +1 -1
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/src/witbitz_code/wizard.py +0 -1
- {witbitz_code-1.15.2 → witbitz_code-1.15.4/src/witbitz_code.egg-info}/PKG-INFO +1 -1
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/tests/test_auto.py +65 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/tests/test_codekeys.py +4 -1
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/tests/test_connector_e2e.py +39 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/tests/test_devicelink.py +47 -1
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/tests/test_files_and_compress.py +9 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/tests/test_pair_flows.py +79 -4
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/tests/test_remind.py +73 -2
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/LICENSE +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/README.md +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/setup.cfg +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/src/witbitz_code/__main__.py +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/src/witbitz_code/_js.py +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/src/witbitz_code/app.py +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/src/witbitz_code/asks.py +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/src/witbitz_code/attachments.py +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/src/witbitz_code/auto.py +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/src/witbitz_code/browse.py +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/src/witbitz_code/browsetree.py +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/src/witbitz_code/cli.py +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/src/witbitz_code/codetools.py +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/src/witbitz_code/compress.py +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/src/witbitz_code/computers.py +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/src/witbitz_code/confidential.py +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/src/witbitz_code/confidential_models.json +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/src/witbitz_code/dirs.py +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/src/witbitz_code/files.py +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/src/witbitz_code/folders.py +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/src/witbitz_code/gateway.py +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/src/witbitz_code/icons/witbitz-code-wsl.ico +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/src/witbitz_code/icons/witbitz-code.ico +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/src/witbitz_code/images.py +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/src/witbitz_code/keys.py +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/src/witbitz_code/mkdir.py +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/src/witbitz_code/models.py +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/src/witbitz_code/net.py +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/src/witbitz_code/offered_models.json +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/src/witbitz_code/opencode_plugins/notes-init.md +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/src/witbitz_code/opencode_plugins/witbitz-browse-cdp.mjs +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/src/witbitz_code/opencode_plugins/witbitz-browse-local.mjs +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/src/witbitz_code/opencode_plugins/witbitz-browse-tree.mjs +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/src/witbitz_code/opencode_plugins/witbitz-browser.js +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/src/witbitz_code/opencode_plugins/witbitz-media-server.mjs +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/src/witbitz_code/opencode_plugins/witbitz-notes.js +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/src/witbitz_code/opencode_plugins/witbitz-progress.js +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/src/witbitz_code/outputs.py +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/src/witbitz_code/payers.py +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/src/witbitz_code/plugins.py +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/src/witbitz_code/policy.py +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/src/witbitz_code/ports.py +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/src/witbitz_code/qr.py +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/src/witbitz_code/receipt.py +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/src/witbitz_code/relay.py +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/src/witbitz_code/remind.py +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/src/witbitz_code/seccheck.py +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/src/witbitz_code/seen.py +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/src/witbitz_code/selfupdate.py +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/src/witbitz_code/tinfoil_read.py +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/src/witbitz_code/tools_catalog.json +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/src/witbitz_code/tools_probe.py +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/src/witbitz_code/toolsetup.py +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/src/witbitz_code/ui.py +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/src/witbitz_code/ui_static/app.css +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/src/witbitz_code/ui_static/index.html +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/src/witbitz_code/uitools.py +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/src/witbitz_code/uninstall.py +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/src/witbitz_code/winagent.py +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/src/witbitz_code/winbg.py +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/src/witbitz_code/winconsole.py +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/src/witbitz_code/wslstart.py +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/src/witbitz_code.egg-info/SOURCES.txt +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/src/witbitz_code.egg-info/dependency_links.txt +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/src/witbitz_code.egg-info/entry_points.txt +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/src/witbitz_code.egg-info/requires.txt +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/src/witbitz_code.egg-info/top_level.txt +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/tests/test_asks.py +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/tests/test_attachments.py +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/tests/test_browse.py +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/tests/test_browsetree.py +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/tests/test_cli.py +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/tests/test_codetools.py +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/tests/test_confidential.py +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/tests/test_dirs.py +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/tests/test_files.py +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/tests/test_folders.py +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/tests/test_images.py +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/tests/test_outputs.py +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/tests/test_plugins.py +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/tests/test_policy.py +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/tests/test_ports.py +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/tests/test_ports_win.py +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/tests/test_registry.py +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/tests/test_relay_codec.py +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/tests/test_seccheck.py +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/tests/test_selfupdate.py +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/tests/test_setup.py +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/tests/test_tools_probe.py +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/tests/test_toolsetup.py +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/tests/test_ui.py +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/tests/test_ui_page.py +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/tests/test_uitools.py +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/tests/test_uninstall.py +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/tests/test_winagent.py +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/tests/test_winbg.py +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/tests/test_winconsole.py +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/tests/test_windows_files.py +0 -0
- {witbitz_code-1.15.2 → witbitz_code-1.15.4}/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.4"
|
|
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
|
|
|
@@ -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 {}
|
|
@@ -69,6 +69,40 @@ def default_auto_dir() -> Path:
|
|
|
69
69
|
return Path(os.environ.get("WITBITZ_CODE_AUTO_DIR") or app.code_dir())
|
|
70
70
|
|
|
71
71
|
|
|
72
|
+
def hello_clock(path: Path, *, now: Callable[[], float] | None = None, reserve_ms: int = 60_000) -> Callable[[], int]:
|
|
73
|
+
"""THE HELLO'S CLOCK NEVER STEPS BACK (state machines pass 9, C#10; tools/opencode-connector.mjs helloClock). A page
|
|
74
|
+
drops a hello whose ts is not after the last one it heard (codeTransport.js — a replayed OLD hello must not move it back
|
|
75
|
+
onto a dead nonce), and ts was the wall clock: after a backward step every open page read this computer "offline" and
|
|
76
|
+
kept a nonce that got 409 on every request, until the clock caught up. Now ts = max(clock, last + 1), and the high-water
|
|
77
|
+
mark is kept in `path` RESERVED a minute ahead (written at most once a minute), so a restart behind the clock still
|
|
78
|
+
starts after every hello the last process sent. Same file and shape as the JS connector."""
|
|
79
|
+
clock = now or (lambda: time.time() * 1000)
|
|
80
|
+
state = {"reserved": 0, "last": 0}
|
|
81
|
+
try:
|
|
82
|
+
state["reserved"] = int(_js.to_number(json.loads(path.read_text(encoding="utf-8")).get("upTo")) or 0)
|
|
83
|
+
except (OSError, ValueError, AttributeError, TypeError, OverflowError):
|
|
84
|
+
state["reserved"] = 0
|
|
85
|
+
state["last"] = state["reserved"]
|
|
86
|
+
|
|
87
|
+
def next_ts() -> int:
|
|
88
|
+
ts = max(int(clock()), state["last"] + 1)
|
|
89
|
+
state["last"] = ts
|
|
90
|
+
if ts > state["reserved"]:
|
|
91
|
+
state["reserved"] = ts + reserve_ms
|
|
92
|
+
try:
|
|
93
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
94
|
+
tmp = path.with_name(path.name + ".tmp")
|
|
95
|
+
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
|
96
|
+
with os.fdopen(fd, "w", encoding="utf-8") as f:
|
|
97
|
+
f.write(json.dumps({"v": 1, "upTo": state["reserved"]}) + "\n")
|
|
98
|
+
os.replace(tmp, path)
|
|
99
|
+
except OSError:
|
|
100
|
+
pass # memory still orders this process's hellos
|
|
101
|
+
return ts
|
|
102
|
+
|
|
103
|
+
return next_ts
|
|
104
|
+
|
|
105
|
+
|
|
72
106
|
def _round(x: float) -> int:
|
|
73
107
|
return math.floor(x + 0.5) # Math.round, not banker's rounding
|
|
74
108
|
|
|
@@ -226,6 +260,7 @@ class PairingServer:
|
|
|
226
260
|
self._output_log = auto_dir / "output-log.jsonl" # each preview fetch: a digest of the path, never the path
|
|
227
261
|
self._seen_path = auto_dir / f"seen-{safe_id}.json" # what the person has seen, shared by their devices (seen.py)
|
|
228
262
|
self._seen: dict | None = None
|
|
263
|
+
self._hello_ts = hello_clock(auto_dir / f"hello-{safe_id}.json") # never steps back (pass 9, C#10)
|
|
229
264
|
self.auto = AutoRunner(base=self.base, auth=self._auth, client=client, poll_ms=auto_poll_ms, log=log,
|
|
230
265
|
state_path=auto_dir / f"auto-{safe_id}.json", log_path=auto_dir / "auto-log.jsonl",
|
|
231
266
|
on_verdict=lambda v: self.peer.send({"t": "autoverdict", **v, "ts": int(time.time() * 1000)}),
|
|
@@ -321,7 +356,7 @@ class PairingServer:
|
|
|
321
356
|
self._browse_said = json.dumps(browse, sort_keys=True)
|
|
322
357
|
# caps: what this connector can do beyond the requests — a page shows the Auto switch only when `auto` is here.
|
|
323
358
|
return self.peer.send({"t": "hello", "ver": VERSION, "name": self.name, "computerId": self.pairing.get("computerId") or "",
|
|
324
|
-
"k": self.nonce, "ts":
|
|
359
|
+
"k": self.nonce, "ts": self._hello_ts(), "caps": ["auto", "attachments", "outputs", "tools", "seen", "asks", "folders", "remind", "files"], "auto": self.auto.sessions(),
|
|
325
360
|
**({"browse": browse} if browse else {})})
|
|
326
361
|
|
|
327
362
|
def _auth(self) -> dict:
|
|
@@ -594,23 +629,35 @@ class PairingServer:
|
|
|
594
629
|
"""Each waiting approval: a tickle at one minute and a reminder at ten, to the device whose prompt led to it."""
|
|
595
630
|
if not self._asks_live:
|
|
596
631
|
return
|
|
597
|
-
for
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
632
|
+
# One `due` for every folder (state machines pass 8, K#1): `due` forgets the asks it is not shown, so asked per folder
|
|
633
|
+
# with asks waiting in two, each call forgot the other folder's and neither ever reminded.
|
|
634
|
+
dir_of: dict[str, str] = {}
|
|
635
|
+
everything: list[dict] = []
|
|
636
|
+
for d in self._asks.directories():
|
|
637
|
+
for a in self._asks.list(d):
|
|
638
|
+
if isinstance(a, dict) and isinstance(a.get("id"), str) and a["id"] not in dir_of:
|
|
639
|
+
dir_of[a["id"]] = d
|
|
640
|
+
everything.append(a)
|
|
641
|
+
for ask, stage in self._remind.due(everything):
|
|
642
|
+
directory = dir_of[ask["id"]]
|
|
643
|
+
# A stage is spent only by a tickle that went out (2026-11-08, docs/state-machines.md I16 / C#14): marked before the
|
|
644
|
+
# lookup and the POST, no device yet, a network error or a 5xx used it up. The Node connector does the same.
|
|
645
|
+
owner = await self._remind_owner(ask["sessionID"], directory)
|
|
646
|
+
e = self._remind.who(owner) if owner else None
|
|
647
|
+
if not e:
|
|
648
|
+
continue
|
|
649
|
+
n = seal_remind(e["key"], {"where": self.name, "what": detail_of(ask) or str(ask.get("permission") or ""),
|
|
650
|
+
"computer": self.pairing.get("computerId") or "", "session": owner})
|
|
651
|
+
try:
|
|
652
|
+
r = await self._client.post(e["url"], json={"op": "coderemind", "grant": e["grant"], "n": n}, timeout=15)
|
|
653
|
+
if 200 <= r.status_code < 300 or r.status_code == 410:
|
|
654
|
+
self._remind.sent(ask["id"], stage)
|
|
655
|
+
if r.status_code == 410:
|
|
656
|
+
self._remind.note(owner, {}) # that device's address is gone: nothing more to it
|
|
657
|
+
except asyncio.CancelledError:
|
|
658
|
+
raise
|
|
659
|
+
except Exception:
|
|
660
|
+
pass # offline: the same stage tries again at the next tick
|
|
614
661
|
|
|
615
662
|
def _own_review(self, session: str, start: bool) -> None:
|
|
616
663
|
if not self._payers:
|
|
@@ -28,6 +28,9 @@ LINK_PREFIX = "wbzlink1:"
|
|
|
28
28
|
_LINK_INFO = b"witbitz-device-link-v1"
|
|
29
29
|
_ACK_INFO = b"witbitz-device-link-ack-v1" # the report back to the giver (⇄ spaces/public/deviceLink.js ACK_INFO)
|
|
30
30
|
_WHY_MAX = 300
|
|
31
|
+
# THE COMPUTER IT PAIRED: a paired computer names its computerId in its report, so the giving device copies exactly that
|
|
32
|
+
# computer into the account's sealed list (deviceLink.js CID; the shape is computers.py's id — state machines pass 9, C#3).
|
|
33
|
+
_CID = re.compile(r"[A-Za-z0-9_-]{8,64}")
|
|
31
34
|
_BACKUP_SALT = b"witbitz-spaces-backup-v1"
|
|
32
35
|
|
|
33
36
|
|
|
@@ -93,14 +96,17 @@ def seal_to_challenge(challenge: dict, payload: Any) -> dict:
|
|
|
93
96
|
return {"ref": challenge["ref"], "epk": _export_pub(mine.public_key()), "blob": b64u(iv + ct)}
|
|
94
97
|
|
|
95
98
|
|
|
96
|
-
def seal_link_ack(priv: ec.EllipticCurvePrivateKey, reply: dict, ok: bool, why: str = "") -> dict:
|
|
99
|
+
def seal_link_ack(priv: ec.EllipticCurvePrivateKey, reply: dict, ok: bool, why: str = "", cid: Any = "") -> dict:
|
|
97
100
|
"""THE REPORT BACK TO THE GIVER (the owner, 2026-10-23: the phone said "Sent ✓" while this computer refused the other app's
|
|
98
101
|
code): {ok, why} sealed under a second key from the same exchange → {ref, ack} to POST to /api/link. Only the phone that
|
|
99
|
-
sealed the reply can open it (deviceLink.js openLinkAck).
|
|
102
|
+
sealed the reply can open it (deviceLink.js openLinkAck). `cid`: on success, the computer this pairing put in the account —
|
|
103
|
+
that phone then confirms exactly it in the account's sealed list (state machines pass 9, C#3); a malformed one is dropped."""
|
|
100
104
|
key = _shared_key(priv, _import_pub(reply.get("epk")), reply.get("ref"), _ACK_INFO)
|
|
101
105
|
body: dict = {"v": 1, "ok": bool(ok)}
|
|
102
106
|
if why:
|
|
103
107
|
body["why"] = str(why)[:_WHY_MAX]
|
|
108
|
+
if ok and isinstance(cid, str) and _CID.fullmatch(cid):
|
|
109
|
+
body["cid"] = cid
|
|
104
110
|
iv = os.urandom(12)
|
|
105
111
|
return {"ref": reply.get("ref"), "ack": b64u(iv + key.encrypt(iv, _js.stringify(body).encode("utf-8"), None))}
|
|
106
112
|
|
|
@@ -68,9 +68,16 @@ def _node_base64(s: str) -> bytes:
|
|
|
68
68
|
return _js.atob(body)
|
|
69
69
|
|
|
70
70
|
|
|
71
|
-
|
|
71
|
+
# The account backup's home — every app's /space-config names it (vaultApi). The old same-origin `/api/backup` (Cloudflare KV)
|
|
72
|
+
# is retired (docs/TODO.md, 2026-11-07); its release tokens were the old home's own, so a token the app mints today never
|
|
73
|
+
# opened anything there.
|
|
74
|
+
VAULT_API = (os.environ.get("WITBITZ_VAULT_API") or "https://api.witbitz.chat/v1/vault").rstrip("/")
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
async def pull_index_room(account: Any, homes: list[str], post_json: net.PostJson) -> dict | None:
|
|
72
78
|
"""GAP-CLOSER: the link carried no index-room pointer → derive the backup location from the master, read the gated
|
|
73
|
-
backup with the release token, and take its indexRoom {room, mk}.
|
|
79
|
+
backup with the release token, and take its indexRoom {room, mk}. `homes`: the backup homes to ask (a vault API base
|
|
80
|
+
each, `<base>/release`); the pointer or None."""
|
|
74
81
|
if not isinstance(account, dict) or not truthy(account.get("master")):
|
|
75
82
|
return None
|
|
76
83
|
try:
|
|
@@ -82,15 +89,15 @@ async def pull_index_room(account: Any, origins: list[str], post_json: net.PostJ
|
|
|
82
89
|
loc = devicelink.derive_keys_from_secret(master)
|
|
83
90
|
rel = account.get("rel")
|
|
84
91
|
token = rel.get("token") if isinstance(rel, dict) else None
|
|
85
|
-
for
|
|
92
|
+
for home in homes:
|
|
86
93
|
blob = None
|
|
87
94
|
if truthy(token):
|
|
88
95
|
try:
|
|
89
|
-
r = await post_json(f"{
|
|
96
|
+
r = await post_json(f"{home}/release", {"token": token, "id": loc["id"]})
|
|
90
97
|
if isinstance(r, dict) and truthy(r.get("ok")) and truthy(r.get("blob")):
|
|
91
98
|
blob = r["blob"]
|
|
92
99
|
except Exception:
|
|
93
|
-
pass # try the next
|
|
100
|
+
pass # try the next home
|
|
94
101
|
if not blob:
|
|
95
102
|
continue
|
|
96
103
|
try:
|
|
@@ -142,14 +149,15 @@ async def link_node(*, life_ms: float | None = None, poll_s: float = POLL_S, ori
|
|
|
142
149
|
await client.aclose()
|
|
143
150
|
|
|
144
151
|
|
|
145
|
-
def _reporter(priv, reply: dict, origin: str) -> Callable[
|
|
152
|
+
def _reporter(priv, reply: dict, origin: str) -> Callable[..., Awaitable[None]]:
|
|
146
153
|
"""The report back to the giving phone (devicelink.seal_link_ack): best effort, on a client of its own — the link's is
|
|
147
|
-
closed by the time pairing ends. A phone that hears nothing says this computer has the keys.
|
|
148
|
-
|
|
154
|
+
closed by the time pairing ends. A phone that hears nothing says this computer has the keys. `cid`: once paired, this
|
|
155
|
+
computer's id, so that phone confirms exactly it in the account's sealed list (state machines pass 9, C#3)."""
|
|
156
|
+
async def report(ok: bool, why: str = "", cid: str = "") -> None:
|
|
149
157
|
client = None
|
|
150
158
|
try:
|
|
151
159
|
client = net.new_client()
|
|
152
|
-
await net.make_post_json(client)(f"{origin}/api/link", devicelink.seal_link_ack(priv, reply, ok, why))
|
|
160
|
+
await net.make_post_json(client)(f"{origin}/api/link", devicelink.seal_link_ack(priv, reply, ok, why, cid))
|
|
153
161
|
except Exception: # noqa: BLE001 — the pairing's own outcome stands either way
|
|
154
162
|
pass
|
|
155
163
|
finally:
|
|
@@ -216,7 +224,7 @@ async def _link(life_ms, poll_s, origins, get_json, post_json, challenge, svg_pa
|
|
|
216
224
|
out("witbitz-code: no index pointer in the link — recovering it from your account backup… ", end="")
|
|
217
225
|
idx = None
|
|
218
226
|
try:
|
|
219
|
-
idx = await pull_index_room(account,
|
|
227
|
+
idx = await pull_index_room(account, [VAULT_API], post_json)
|
|
220
228
|
except Exception:
|
|
221
229
|
pass
|
|
222
230
|
if idx:
|
|
@@ -983,20 +983,27 @@ var closing = false;
|
|
|
983
983
|
var first = { out: false, in: false, frame: false };
|
|
984
984
|
var tellControl = async (path, body) => {
|
|
985
985
|
try {
|
|
986
|
-
await fetch(CTL + path, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
|
|
986
|
+
const r = await fetch(CTL + path, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
|
|
987
|
+
if (!r.ok) log("control", path, "refused:", r.status);
|
|
988
|
+
return r.ok;
|
|
987
989
|
} catch (e) {
|
|
988
990
|
log("control", path, "failed:", String(e).slice(0, 80));
|
|
991
|
+
return false;
|
|
989
992
|
}
|
|
990
993
|
};
|
|
991
994
|
var said = null;
|
|
992
995
|
var holderVid = null;
|
|
996
|
+
var statusAsk = 0;
|
|
997
|
+
var takeGen = 0;
|
|
993
998
|
var tellTheViewerWhoHasTheControls = async (why) => {
|
|
994
999
|
let st = null;
|
|
1000
|
+
const ask = ++statusAsk, gen = takeGen;
|
|
995
1001
|
try {
|
|
996
1002
|
st = await (await fetch(CTL + "/status")).json();
|
|
997
1003
|
} catch {
|
|
998
1004
|
return;
|
|
999
1005
|
}
|
|
1006
|
+
if (ask !== statusAsk || gen !== takeGen) return;
|
|
1000
1007
|
held = !!st.takeover;
|
|
1001
1008
|
if (!held && cast && cast.incognito && cast.incognito()) closeIncognito("the controls lapsed");
|
|
1002
1009
|
if (!held) holderVid = null;
|
|
@@ -1019,9 +1026,19 @@ var tellTheViewerWhoHasTheControls = async (why) => {
|
|
|
1019
1026
|
st.web ? "on" : "off"
|
|
1020
1027
|
);
|
|
1021
1028
|
};
|
|
1029
|
+
var HOLDER_SILENT_MS = Number(process.env.WB_BROWSE_HOLDER_SILENT_MS) || 6e4;
|
|
1022
1030
|
setInterval(() => {
|
|
1023
|
-
|
|
1031
|
+
const h = holderVid && castViewers.get(holderVid);
|
|
1032
|
+
if (h && h.beats && Date.now() - h.at > HOLDER_SILENT_MS) holderLeft("the holder went silent");
|
|
1033
|
+
if (peers > 1 || held || holderVid) tellTheViewerWhoHasTheControls("poll");
|
|
1024
1034
|
}, 5e3);
|
|
1035
|
+
function holderLeft(why) {
|
|
1036
|
+
if (!holderVid) return;
|
|
1037
|
+
castViewers.delete(holderVid);
|
|
1038
|
+
assigned.delete(holderVid);
|
|
1039
|
+
log("take-over:", why, "\u2014 the enclave's grace decides");
|
|
1040
|
+
closeIncognito(why).finally(() => tellControl("/takeover", { on: false, gone: true }));
|
|
1041
|
+
}
|
|
1025
1042
|
var expectHello = false;
|
|
1026
1043
|
var strays = 0;
|
|
1027
1044
|
var isHello = (b) => b.byteLength === 12 && b[0] === 82 && b[1] === 70 && b[2] === 66 && b[3] === 32 && b[11] === 10;
|
|
@@ -1386,9 +1403,16 @@ function connectRelay() {
|
|
|
1386
1403
|
if (!c) return;
|
|
1387
1404
|
if (c.wb === "takeover") {
|
|
1388
1405
|
if (!c.on) await closeIncognito("the controls were given back");
|
|
1389
|
-
|
|
1406
|
+
takeGen++;
|
|
1407
|
+
if (!await tellControl("/takeover", { on: !!c.on })) {
|
|
1408
|
+
said = null;
|
|
1409
|
+
await tellTheViewerWhoHasTheControls("refused");
|
|
1410
|
+
return;
|
|
1411
|
+
}
|
|
1390
1412
|
held = !!c.on;
|
|
1391
1413
|
holderVid = c.on && typeof c.vid === "string" ? c.vid.slice(0, 64) : null;
|
|
1414
|
+
said = null;
|
|
1415
|
+
if (holderVid && castViewers.has(holderVid)) castViewers.get(holderVid).at = Date.now();
|
|
1392
1416
|
log("take-over", c.on ? "ON \u2014 the agent's CDP session is being closed" : "released");
|
|
1393
1417
|
if (cast) await cast.setController(c.on ? norm(c.view) || largestView() : null).catch(() => {
|
|
1394
1418
|
});
|
|
@@ -1417,12 +1441,30 @@ function connectRelay() {
|
|
|
1417
1441
|
const mode = await cast.setSiteMode(c.mode).catch(() => siteNow());
|
|
1418
1442
|
log("site: the", mode, "site, for everyone");
|
|
1419
1443
|
if (relay && relay.readyState === 1) relay.send(await sealCtl(key, { wb: "site", mode }));
|
|
1444
|
+
} else if (c.wb === "leave" && typeof c.vid === "string") {
|
|
1445
|
+
const v = c.vid.slice(0, 64);
|
|
1446
|
+
if (v === holderVid) holderLeft("the holder's page went away");
|
|
1447
|
+
else {
|
|
1448
|
+
castViewers.delete(v);
|
|
1449
|
+
assigned.delete(v);
|
|
1450
|
+
}
|
|
1451
|
+
} else if (c.wb === "hello" && c.hb && typeof c.vid === "string" && castViewers.has(c.vid.slice(0, 64))) {
|
|
1452
|
+
castViewers.get(c.vid.slice(0, 64)).at = Date.now();
|
|
1420
1453
|
} else if (c.wb === "hello" && c.cast && typeof c.vid === "string" && CDP) {
|
|
1421
1454
|
const known = castViewers.has(c.vid);
|
|
1422
1455
|
const mine = held && c.driving && (!holderVid || c.vid.slice(0, 64) === holderVid);
|
|
1423
|
-
castViewers.set(c.vid.slice(0, 64), { view: norm(c.view), at: Date.now(), driving: !!mine });
|
|
1424
|
-
|
|
1456
|
+
castViewers.set(c.vid.slice(0, 64), { view: norm(c.view), at: Date.now(), driving: !!mine, beats: !!c.beat });
|
|
1457
|
+
assigned.delete(c.vid.slice(0, 64));
|
|
1458
|
+
if (castViewers.size > 8) {
|
|
1459
|
+
const old = castViewers.keys().next().value;
|
|
1460
|
+
castViewers.delete(old);
|
|
1461
|
+
assigned.delete(old);
|
|
1462
|
+
}
|
|
1425
1463
|
if (!known) log("cast: a viewer said hello \u2014", JSON.stringify(norm(c.view)));
|
|
1464
|
+
if (mine && !known) {
|
|
1465
|
+
await tellControl("/takeover", { on: true });
|
|
1466
|
+
log("take-over: the holder came back \u2014 the controls stay theirs");
|
|
1467
|
+
}
|
|
1426
1468
|
if (relay && relay.readyState === 1) relay.send(await sealCtl(key, { wb: "cast", on: true, close: true }));
|
|
1427
1469
|
await startCast();
|
|
1428
1470
|
if (mine && cast) await cast.setController(norm(c.view)).catch(() => {
|
|
@@ -97,10 +97,10 @@ def ensure_local_password(out: Callable[[str], Any] = _out) -> None:
|
|
|
97
97
|
out(f"witbitz-code: ✓ minted a local OpenCode password in {path} (0600) — it never leaves this computer")
|
|
98
98
|
|
|
99
99
|
|
|
100
|
-
async def _publish_entry(call: net.ApiCall, e: dict, out: Callable, err: Callable) -> bool:
|
|
100
|
+
async def _publish_entry(call: net.ApiCall, e: dict, out: Callable, err: Callable, *, revive: bool = False) -> bool:
|
|
101
101
|
call = net.call_for(call, e.get("origin")) # this account's app (the hosted app's rooms refuse the regular one)
|
|
102
102
|
r = await acct.publish_computer(call=call, idx=e["idx"], computer_id=e["computerId"], name=e["name"], relay=e["relay"],
|
|
103
|
-
secret=e["secret"])
|
|
103
|
+
secret=e["secret"], revive=revive)
|
|
104
104
|
who = e["account"] or "account"
|
|
105
105
|
if not r["ok"]:
|
|
106
106
|
err(f"witbitz-code: ✖ {who}: {r['why']}")
|
|
@@ -130,13 +130,14 @@ async def _link_by_qr(link_fn: LinkFn | None, out: Callable, err: Callable) -> d
|
|
|
130
130
|
return account
|
|
131
131
|
|
|
132
132
|
|
|
133
|
-
async def _report(account: dict | None, ok: bool, why: str = "") -> None:
|
|
133
|
+
async def _report(account: dict | None, ok: bool, why: str = "", cid: str = "") -> None:
|
|
134
134
|
"""Tell the phone that sent the keys how pairing went (link.py's reporter; the owner, 2026-10-23: it said "Sent ✓" while
|
|
135
|
-
this computer refused the code). Best effort — never changes the outcome.
|
|
135
|
+
this computer refused the code). Best effort — never changes the outcome. `cid`: on success, this computer's id, so that
|
|
136
|
+
phone confirms exactly it in the account's sealed list (state machines pass 9, C#3)."""
|
|
136
137
|
r = account.get("_report") if isinstance(account, dict) else None
|
|
137
138
|
if callable(r):
|
|
138
139
|
try:
|
|
139
|
-
await r(ok, why)
|
|
140
|
+
await r(ok, why, cid)
|
|
140
141
|
except Exception: # noqa: BLE001
|
|
141
142
|
pass
|
|
142
143
|
|
|
@@ -186,6 +187,11 @@ async def main(argv: list[str], *, call: net.ApiCall | None = None, link_fn: Lin
|
|
|
186
187
|
await http.aclose()
|
|
187
188
|
|
|
188
189
|
|
|
190
|
+
# The server's refusals that come BEFORE it retires anything (codeKeys.mjs mintFor): after any other failure a refresh's
|
|
191
|
+
# working keys may already be gone, and "nothing changed" would be untrue (state machines pass 9, C#4; = opencode-pair.mjs).
|
|
192
|
+
_NOTHING_RETIRED = frozenset({"not_invited", "code_keys_off", "revoked", "signin_stale", "not_signed_in"})
|
|
193
|
+
|
|
194
|
+
|
|
189
195
|
class _KeyCalls:
|
|
190
196
|
"""codekeys.py's three calls on one client."""
|
|
191
197
|
|
|
@@ -287,9 +293,13 @@ async def _run(args: Args, call: Any, link_fn: LinkFn | None, out: Callable, err
|
|
|
287
293
|
"Code → Computers → Add a computer.")
|
|
288
294
|
return 1
|
|
289
295
|
port = None if args.opencode_url else pp.next_port(doc, account["idx"]["room"]) # another account: its own OpenCode
|
|
296
|
+
room = account["idx"]["room"]
|
|
297
|
+
pending = pp.pending_id(room) # an earlier attempt's id (C#4)
|
|
290
298
|
u = pp.upsert_pairing(doc, account=account.get("email") or "", idx=account["idx"], name=args.name,
|
|
291
299
|
opencode_url=args.opencode_url or (f"http://127.0.0.1:{port}" if port else UNDEFINED),
|
|
292
|
-
origin=account.get("origin") or UNDEFINED)
|
|
300
|
+
origin=account.get("origin") or UNDEFINED, mint_id=lambda: pending or pp.new_computer_id())
|
|
301
|
+
if u["isNew"] and u["entry"]["computerId"] != pending:
|
|
302
|
+
pp.note_pending(room, u["entry"]["computerId"]) # before the mint: its answer can be lost (C#4)
|
|
293
303
|
# THIS COMPUTER'S CODING KEYS from the account (codekeys.py; docs/code-account-keys.md) — the only way it gets model
|
|
294
304
|
# keys. Asked with the sign-in the scan carried, before anything is published: an account that cannot give keys (not
|
|
295
305
|
# invited, too many computers, …) leaves nothing behind.
|
|
@@ -298,18 +308,33 @@ async def _run(args: Args, call: Any, link_fn: LinkFn | None, out: Callable, err
|
|
|
298
308
|
entry = await keys.mint(id_token=str(anchor.get("token") or ""), account=u["entry"]["account"],
|
|
299
309
|
computer_id=u["entry"]["computerId"], name=u["entry"]["name"])
|
|
300
310
|
except codekeys.CodeKeyRefusal as e:
|
|
301
|
-
|
|
311
|
+
# A REFRESH's working keys are retired by the mint, before it can fail (or its answer be lost): say so (C#4)
|
|
312
|
+
retired = not u["isNew"] and e.code not in _NOTHING_RETIRED
|
|
313
|
+
tail = ("if Witbitz got the request, the coding keys this computer had are already replaced: scan again to get the new ones."
|
|
314
|
+
if retired else "nothing changed.")
|
|
315
|
+
err(f"witbitz-code: ✖ this computer got no coding keys: {e} — {tail}")
|
|
302
316
|
await _report(account, False, f"it got no coding keys: {e}")
|
|
303
317
|
return 1
|
|
304
318
|
ensure_local_password(out)
|
|
305
|
-
|
|
306
|
-
|
|
319
|
+
# A REFRESH (this computer already paired with the account, same id): the mint has just retired its working keys, so the
|
|
320
|
+
# new ones are kept whatever the publish does — giving them back left a dead entry in the keys file while the tool said
|
|
321
|
+
# "nothing saved" (state machines pass 9, C#4). Its entry in the account is unchanged by a failed publish.
|
|
322
|
+
if not u["isNew"]:
|
|
323
|
+
codekeys.save(entry)
|
|
324
|
+
if not await _publish_entry(call, u["entry"], out, err, revive=True): # a scan: the person added it (pass 9, C#3)
|
|
325
|
+
if not u["isNew"]:
|
|
326
|
+
err("witbitz-code: this computer keeps its pairing and its renewed coding keys; its entry in your account is unchanged — scan again to retry.")
|
|
327
|
+
await _report(account, False, "it could not update itself in your account (offline?). It still works. Scan again to retry.")
|
|
328
|
+
return 1
|
|
329
|
+
await keys.revoke(entry) # nothing is left live for a pairing that did not happen (offline: the retry's mint retires it, C#4)
|
|
307
330
|
err("witbitz-code: nothing saved locally — scan again to retry.")
|
|
308
331
|
await _report(account, False, "it could not add itself to your account (offline?). Scan again to retry.")
|
|
309
332
|
return 1
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
333
|
+
if u["isNew"]:
|
|
334
|
+
codekeys.save(entry)
|
|
335
|
+
pp.write_pairings(pp.with_entry(pp.read_pairings(), u["entry"])) # onto the file as it is NOW, not as read before the scan (C#6)
|
|
336
|
+
pp.clear_pending(room)
|
|
337
|
+
await _report(account, True, "", u["entry"]["computerId"]) # the phone says "Added" — and confirms this computer (pass 9, C#3)
|
|
313
338
|
e = u["entry"]
|
|
314
339
|
out(f"witbitz-code: ✓ {'paired' if u['isNew'] else 'refreshed'} \"{e['name']}\" with {e['account'] or 'your account'} ({pp.pairings_path()})")
|
|
315
340
|
caps = entry.get("caps") or {}
|
|
@@ -116,6 +116,20 @@ def norm_pairings(doc: Any) -> dict:
|
|
|
116
116
|
return {"v": 1, "pairings": [p for p in lst if _usable(p)] if isinstance(lst, list) else []}
|
|
117
117
|
|
|
118
118
|
|
|
119
|
+
def with_entry(fresh: Any, entry: dict) -> dict:
|
|
120
|
+
"""One entry put into the pairings AS THEY ARE NOW (state machines pass 9, C#6; tools/opencode-pair.mjs withEntry).
|
|
121
|
+
`pair` read the file, waited minutes for the scan, and wrote back what it had read plus the new entry — an account
|
|
122
|
+
unpaired meanwhile (the manager page) returned to the file with its relay secret and index-room key. Pure."""
|
|
123
|
+
cur = norm_pairings(fresh)
|
|
124
|
+
pairings = list(cur["pairings"])
|
|
125
|
+
i = next((k for k, p in enumerate(pairings) if strict_eq(p["idx"].get("room"), entry["idx"].get("room"))), -1)
|
|
126
|
+
if i >= 0:
|
|
127
|
+
pairings[i] = entry
|
|
128
|
+
else:
|
|
129
|
+
pairings.append(entry)
|
|
130
|
+
return {"v": 1, "pairings": pairings}
|
|
131
|
+
|
|
132
|
+
|
|
119
133
|
def upsert_pairing(doc: Any, *, idx: dict, account: str = "", name: str = "", relay: Any = UNDEFINED,
|
|
120
134
|
opencode_url: Any = UNDEFINED, origin: Any = UNDEFINED, rotate: bool = False,
|
|
121
135
|
mint_id: Callable[[], str] = new_computer_id, mint_secret: Callable[[], str] = new_relay_secret) -> dict:
|
|
@@ -284,6 +298,43 @@ def write_pairings(doc: dict, path: Path | None = None) -> None:
|
|
|
284
298
|
write_private(path or pairings_path(), serialize_pairings(doc))
|
|
285
299
|
|
|
286
300
|
|
|
301
|
+
# A NEW PAIRING'S COMPUTER ID, WRITTEN DOWN BEFORE THE MINT (state machines pass 9, C#4; tools/opencode-pair.mjs pendingId).
|
|
302
|
+
# A mint whose answer was lost, or a pairing whose publish and give-back both failed offline, left a live key row on the
|
|
303
|
+
# server for an id no file named; the retry minted ANOTHER id and the free tier refused it ("already codes on <this
|
|
304
|
+
# computer>"). Now the retry asks for the same id, and the server's mint retires that id's old row itself. One id per
|
|
305
|
+
# account index room; it goes when the pairing lands. Same file and shape as the JS tool.
|
|
306
|
+
def pending_path() -> Path:
|
|
307
|
+
return pairings_path().parent / "pairing-pending.json"
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def _read_pending() -> dict:
|
|
311
|
+
try:
|
|
312
|
+
d = json.loads(pending_path().read_text(encoding="utf-8"))
|
|
313
|
+
except (OSError, ValueError):
|
|
314
|
+
return {}
|
|
315
|
+
pend = d.get("pending") if isinstance(d, dict) else None
|
|
316
|
+
return dict(pend) if isinstance(pend, dict) else {}
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def _write_pending(pending: dict) -> None:
|
|
320
|
+
write_private(pending_path(), _js.stringify({"v": 1, "pending": pending}, 1) + "\n")
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
def pending_id(room: str) -> str:
|
|
324
|
+
v = _read_pending().get(room)
|
|
325
|
+
return v if isinstance(v, str) and v else ""
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def note_pending(room: str, computer_id: str) -> None:
|
|
329
|
+
_write_pending({**_read_pending(), room: computer_id})
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
def clear_pending(room: str) -> None:
|
|
333
|
+
cur = _read_pending()
|
|
334
|
+
if room in cur:
|
|
335
|
+
_write_pending({k: v for k, v in cur.items() if k != room})
|
|
336
|
+
|
|
337
|
+
|
|
287
338
|
def load_pairings(path: Path | None = None, log: Callable[[str], Any] | None = None) -> list[dict]:
|
|
288
339
|
"""The connector's view: the list (empty when absent). Entries without a secret are skipped, loudly."""
|
|
289
340
|
log = log or (lambda m: print(m, file=sys.stderr, flush=True))
|
|
@@ -307,7 +307,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
|
|
307
307
|
}
|
|
308
308
|
// ANOTHER ACCOUNT ON THIS COMPUTER: a new code beside the pairings there are (pairings.json holds one per account, on the
|
|
309
309
|
// same OpenCode); nothing is unpaired. Code here pauses while the code is up and comes back when it is scanned or cancelled.
|
|
310
|
-
$('pairAdd').onclick = () => act('/api/pair', {}, 'Add another account? A new code appears — scan it from the other account:
|
|
310
|
+
$('pairAdd').onclick = () => act('/api/pair', {}, 'Add another account? A new code appears — scan it (or paste it) from the other account: Spaces → Settings → Privacy & security → Add a device. Code on this computer pauses until it is scanned or cancelled.')
|
|
311
311
|
$('pairCancel').onclick = () => act('/api/pair/cancel', {})
|
|
312
312
|
$('pairCopy').onclick = async () => {
|
|
313
313
|
const b = $('pairCopy')
|