witbitz-code 1.15.3__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.
Files changed (121) hide show
  1. {witbitz_code-1.15.3/src/witbitz_code.egg-info → witbitz_code-1.15.4}/PKG-INFO +1 -1
  2. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/pyproject.toml +1 -1
  3. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/src/witbitz_code/__init__.py +1 -1
  4. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/src/witbitz_code/account.py +10 -2
  5. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/src/witbitz_code/auto_runner.py +24 -3
  6. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/src/witbitz_code/codekeys.py +9 -1
  7. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/src/witbitz_code/connector.py +36 -1
  8. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/src/witbitz_code/devicelink.py +8 -2
  9. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/src/witbitz_code/link.py +5 -4
  10. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/src/witbitz_code/pair.py +37 -12
  11. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/src/witbitz_code/pairings.py +51 -0
  12. {witbitz_code-1.15.3 → witbitz_code-1.15.4/src/witbitz_code.egg-info}/PKG-INFO +1 -1
  13. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/tests/test_auto.py +65 -0
  14. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/tests/test_codekeys.py +4 -1
  15. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/tests/test_connector_e2e.py +39 -0
  16. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/tests/test_devicelink.py +42 -0
  17. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/tests/test_files_and_compress.py +9 -0
  18. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/tests/test_pair_flows.py +79 -4
  19. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/LICENSE +0 -0
  20. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/README.md +0 -0
  21. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/setup.cfg +0 -0
  22. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/src/witbitz_code/__main__.py +0 -0
  23. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/src/witbitz_code/_js.py +0 -0
  24. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/src/witbitz_code/app.py +0 -0
  25. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/src/witbitz_code/asks.py +0 -0
  26. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/src/witbitz_code/attachments.py +0 -0
  27. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/src/witbitz_code/auto.py +0 -0
  28. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/src/witbitz_code/browse.py +0 -0
  29. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/src/witbitz_code/browsetree.py +0 -0
  30. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/src/witbitz_code/cli.py +0 -0
  31. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/src/witbitz_code/codetools.py +0 -0
  32. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/src/witbitz_code/compress.py +0 -0
  33. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/src/witbitz_code/computers.py +0 -0
  34. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/src/witbitz_code/confidential.py +0 -0
  35. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/src/witbitz_code/confidential_models.json +0 -0
  36. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/src/witbitz_code/dirs.py +0 -0
  37. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/src/witbitz_code/files.py +0 -0
  38. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/src/witbitz_code/folders.py +0 -0
  39. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/src/witbitz_code/gateway.py +0 -0
  40. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/src/witbitz_code/icons/witbitz-code-wsl.ico +0 -0
  41. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/src/witbitz_code/icons/witbitz-code.ico +0 -0
  42. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/src/witbitz_code/images.py +0 -0
  43. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/src/witbitz_code/keys.py +0 -0
  44. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/src/witbitz_code/mkdir.py +0 -0
  45. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/src/witbitz_code/models.py +0 -0
  46. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/src/witbitz_code/net.py +0 -0
  47. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/src/witbitz_code/offered_models.json +0 -0
  48. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/src/witbitz_code/opencode_plugins/notes-init.md +0 -0
  49. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/src/witbitz_code/opencode_plugins/witbitz-browse-cdp.mjs +0 -0
  50. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/src/witbitz_code/opencode_plugins/witbitz-browse-local.mjs +0 -0
  51. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/src/witbitz_code/opencode_plugins/witbitz-browse-publisher.mjs +0 -0
  52. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/src/witbitz_code/opencode_plugins/witbitz-browse-tree.mjs +0 -0
  53. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/src/witbitz_code/opencode_plugins/witbitz-browser.js +0 -0
  54. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/src/witbitz_code/opencode_plugins/witbitz-media-server.mjs +0 -0
  55. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/src/witbitz_code/opencode_plugins/witbitz-notes.js +0 -0
  56. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/src/witbitz_code/opencode_plugins/witbitz-progress.js +0 -0
  57. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/src/witbitz_code/outputs.py +0 -0
  58. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/src/witbitz_code/payers.py +0 -0
  59. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/src/witbitz_code/plugins.py +0 -0
  60. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/src/witbitz_code/policy.py +0 -0
  61. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/src/witbitz_code/ports.py +0 -0
  62. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/src/witbitz_code/qr.py +0 -0
  63. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/src/witbitz_code/receipt.py +0 -0
  64. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/src/witbitz_code/relay.py +0 -0
  65. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/src/witbitz_code/remind.py +0 -0
  66. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/src/witbitz_code/seccheck.py +0 -0
  67. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/src/witbitz_code/seen.py +0 -0
  68. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/src/witbitz_code/selfupdate.py +0 -0
  69. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/src/witbitz_code/tinfoil_read.py +0 -0
  70. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/src/witbitz_code/tools_catalog.json +0 -0
  71. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/src/witbitz_code/tools_probe.py +0 -0
  72. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/src/witbitz_code/toolsetup.py +0 -0
  73. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/src/witbitz_code/ui.py +0 -0
  74. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/src/witbitz_code/ui_static/app.css +0 -0
  75. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/src/witbitz_code/ui_static/app.js +0 -0
  76. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/src/witbitz_code/ui_static/index.html +0 -0
  77. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/src/witbitz_code/uitools.py +0 -0
  78. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/src/witbitz_code/uninstall.py +0 -0
  79. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/src/witbitz_code/winagent.py +0 -0
  80. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/src/witbitz_code/winbg.py +0 -0
  81. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/src/witbitz_code/winconsole.py +0 -0
  82. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/src/witbitz_code/wizard.py +0 -0
  83. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/src/witbitz_code/wslstart.py +0 -0
  84. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/src/witbitz_code.egg-info/SOURCES.txt +0 -0
  85. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/src/witbitz_code.egg-info/dependency_links.txt +0 -0
  86. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/src/witbitz_code.egg-info/entry_points.txt +0 -0
  87. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/src/witbitz_code.egg-info/requires.txt +0 -0
  88. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/src/witbitz_code.egg-info/top_level.txt +0 -0
  89. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/tests/test_asks.py +0 -0
  90. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/tests/test_attachments.py +0 -0
  91. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/tests/test_browse.py +0 -0
  92. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/tests/test_browsetree.py +0 -0
  93. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/tests/test_cli.py +0 -0
  94. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/tests/test_codetools.py +0 -0
  95. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/tests/test_confidential.py +0 -0
  96. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/tests/test_dirs.py +0 -0
  97. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/tests/test_files.py +0 -0
  98. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/tests/test_folders.py +0 -0
  99. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/tests/test_images.py +0 -0
  100. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/tests/test_outputs.py +0 -0
  101. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/tests/test_plugins.py +0 -0
  102. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/tests/test_policy.py +0 -0
  103. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/tests/test_ports.py +0 -0
  104. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/tests/test_ports_win.py +0 -0
  105. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/tests/test_registry.py +0 -0
  106. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/tests/test_relay_codec.py +0 -0
  107. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/tests/test_remind.py +0 -0
  108. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/tests/test_seccheck.py +0 -0
  109. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/tests/test_selfupdate.py +0 -0
  110. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/tests/test_setup.py +0 -0
  111. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/tests/test_tools_probe.py +0 -0
  112. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/tests/test_toolsetup.py +0 -0
  113. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/tests/test_ui.py +0 -0
  114. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/tests/test_ui_page.py +0 -0
  115. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/tests/test_uitools.py +0 -0
  116. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/tests/test_uninstall.py +0 -0
  117. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/tests/test_winagent.py +0 -0
  118. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/tests/test_winbg.py +0 -0
  119. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/tests/test_winconsole.py +0 -0
  120. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/tests/test_windows_files.py +0 -0
  121. {witbitz_code-1.15.3 → witbitz_code-1.15.4}/tests/test_wslstart.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: witbitz-code
3
- Version: 1.15.3
3
+ Version: 1.15.4
4
4
  Summary: Reach OpenCode on this computer from the Witbitz Spaces Code section, through an end-to-end sealed relay.
5
5
  Author: Witbitz
6
6
  License-Expression: MIT
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "witbitz-code"
7
- version = "1.15.3"
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"
@@ -4,4 +4,4 @@ The Python implementation of tools/witbitz-code.mjs (docs/opencode-relay.md phas
4
4
  vectors and cross-implementation tests.
5
5
  """
6
6
 
7
- __version__ = "1.15.3"
7
+ __version__ = "1.15.4"
@@ -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) or req["id"] in self._handled:
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
- return {"live": False, "why": "revoked"}
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": int(time.time() * 1000), "caps": ["auto", "attachments", "outputs", "tools", "seen", "asks", "folders", "remind", "files"], "auto": self.auto.sessions(),
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:
@@ -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
 
@@ -149,14 +149,15 @@ async def link_node(*, life_ms: float | None = None, poll_s: float = POLL_S, ori
149
149
  await client.aclose()
150
150
 
151
151
 
152
- def _reporter(priv, reply: dict, origin: str) -> Callable[[bool, str], Awaitable[None]]:
152
+ def _reporter(priv, reply: dict, origin: str) -> Callable[..., Awaitable[None]]:
153
153
  """The report back to the giving phone (devicelink.seal_link_ack): best effort, on a client of its own — the link's is
154
- closed by the time pairing ends. A phone that hears nothing says this computer has the keys."""
155
- async def report(ok: bool, why: str = "") -> None:
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:
156
157
  client = None
157
158
  try:
158
159
  client = net.new_client()
159
- 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))
160
161
  except Exception: # noqa: BLE001 — the pairing's own outcome stands either way
161
162
  pass
162
163
  finally:
@@ -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
- err(f"witbitz-code: ✖ this computer got no coding keys: {e} — nothing changed.")
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
- if not await _publish_entry(call, u["entry"], out, err):
306
- await keys.revoke(entry) # nothing is left live for a pairing that did not happen
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
- codekeys.save(entry)
311
- pp.write_pairings(u["doc"])
312
- await _report(account, True) # the phone says "Added"
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))
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: witbitz-code
3
- Version: 1.15.3
3
+ Version: 1.15.4
4
4
  Summary: Reach OpenCode on this computer from the Witbitz Spaces Code section, through an end-to-end sealed relay.
5
5
  Author: Witbitz
6
6
  License-Expression: MIT
@@ -557,6 +557,71 @@ def test_loop_a_refusal_held_behind_a_persons_card_is_sent_once_that_card_is_ans
557
557
  with_runner(tmp_path, body, reviewer_text='{"decision":"ask","severity":55,"rule":"ask:push","reason":"not requested"}')
558
558
 
559
559
 
560
+ # ── State machines pass 9 (docs/state-machines.md § Pass 9, C) — the twins of tools/code-auto-runner.test.mjs ──────────
561
+ def test_loop_an_ask_left_for_the_person_is_not_reviewed_again_when_the_30_minutes_pass(tmp_path):
562
+ """9·C#1: `handled` forgot an id after 30 minutes whether or not the ask still waited — a second review could allow it."""
563
+ clock = {"t": 1_000_000}
564
+ oc = LoopOpenCode(reviewer_text='{"decision":"ask","severity":55,"rule":"ask:push","reason":"not requested"}')
565
+ verdicts: list[dict] = []
566
+
567
+ async def go():
568
+ async with httpx.AsyncClient(trust_env=False) as client:
569
+ runner = AutoRunner(base=oc.url, auth=lambda: {}, client=client, state_path=tmp_path / "auto.json",
570
+ log_path=tmp_path / "auto-log.jsonl", poll_ms=20, home="/home/u", on_verdict=verdicts.append,
571
+ now=lambda: clock["t"])
572
+ runner.start()
573
+ try:
574
+ runner.set_auto("ses_main", DIR, True)
575
+ oc.ask(permission="bash", patterns=["git push"], metadata={"command": "git push origin main"})
576
+ assert await until(lambda: verdicts, 6)
577
+ assert len(oc.calls("POST", "/session")) == 1
578
+ for _ in range(4): # 40 minutes, polls all along
579
+ clock["t"] += 10 * 60_000
580
+ await asyncio.sleep(0.12)
581
+ assert len(oc.calls("POST", "/session")) == 1, "still one review"
582
+ assert oc.replies() == [], "and nothing answered for the person"
583
+ finally:
584
+ runner.stop()
585
+
586
+ try:
587
+ run(go(), timeout=60)
588
+ finally:
589
+ oc.close()
590
+
591
+
592
+ def test_loop_auto_switched_off_while_its_review_is_in_flight_allows_nothing(tmp_path):
593
+ """9·C#2: the answer that came back after the switch still allowed the command."""
594
+ async def body(oc, runner, verdicts, make, client):
595
+ runner.set_auto("ses_main", DIR, True)
596
+ oc.ask(permission="bash", patterns=["npm test"], metadata={"command": "npm test"})
597
+ assert await until(lambda: oc.calls("POST", r"/session/ses_rev\d+/message"), 6), "the review is running"
598
+ runner.set_auto("ses_main", DIR, False)
599
+ assert await until(lambda: verdicts, 6)
600
+ await asyncio.sleep(0.15)
601
+ assert oc.replies() == [], 'no "once" after Auto went off'
602
+ assert verdicts[0]["action"] == "ask" and "switched off" in verdicts[0]["reason"]
603
+ with_runner(tmp_path, body, reviewer_delay=0.3)
604
+
605
+
606
+ def test_loop_auto_switched_off_while_it_holds_a_refusal_hands_it_back_and_never_sends_it(tmp_path):
607
+ """9·C#2: a held refusal was neither sent nor handed back — the page had dropped its card, the turn hung."""
608
+ async def body(oc, runner, verdicts, make, client):
609
+ runner.set_auto("ses_main", DIR, True)
610
+ oc.ask(permission="bash", patterns=["rm -rf ~"], metadata={"command": "rm -rf ~"})
611
+ oc.ask(permission="bash", patterns=["git push"], metadata={"command": "git push"})
612
+ assert await until(lambda: any(v["action"] == "deny" and v["answered"] is None for v in verdicts)
613
+ and any(v["action"] == "ask" for v in verdicts), 6)
614
+ runner.set_auto("ses_main", DIR, False)
615
+ back = [v for v in verdicts if v["action"] == "deny"][-1]
616
+ assert back["answered"] is False, "the page is told the refusal did not land: its card comes back"
617
+ with oc.lock:
618
+ oc.pending[:] = [p for p in oc.pending if p["patterns"][0] != "git push"]
619
+ runner.set_auto("ses_other", DIR, True) # another Auto session in the folder keeps the loop polling it
620
+ await asyncio.sleep(0.3)
621
+ assert oc.replies() == [], "Auto rejects nothing for a session it was switched off in"
622
+ with_runner(tmp_path, body, reviewer_text='{"decision":"ask","severity":55,"rule":"ask:push","reason":"not requested"}')
623
+
624
+
560
625
  def _agent_rules(bash: str) -> list[dict]:
561
626
  return [{"permission": "*", "pattern": "*", "action": "allow"}, {"permission": "bash", "pattern": "*", "action": bash},
562
627
  {"permission": "edit", "pattern": "*", "action": "deny"}, {"permission": "webfetch", "pattern": "*", "action": "ask"},
@@ -129,7 +129,8 @@ def test_live_keys_follow_what_the_server_says():
129
129
  assert live.credential("cmp_1") == {"trustedrouter": "sk-tr-made-up-cmp_1", "tinfoil": "tk_made_up_cmp_1"}
130
130
  assert live.credential("cmp_missing") == {"refuse": codekeys.REVOKED_TEXT}
131
131
  assert live.credential(None) is None
132
- answers = iter([httpx.Response(200, json={"data": {"live": False, "why": "paused"}}), httpx.Response(200, json={"data": {"live": True}}), httpx.Response(404, json={})])
132
+ answers = iter([httpx.Response(200, json={"data": {"live": False, "why": "paused"}}), httpx.Response(200, json={"data": {"live": True}}), httpx.Response(404, json={"message": "Not Found"}),
133
+ httpx.Response(404, json={"error": {"code": "not_found", "message": "no such coding key"}})])
133
134
  said = []
134
135
 
135
136
  async def check():
@@ -139,6 +140,8 @@ def test_live_keys_follow_what_the_server_says():
139
140
  assert live.credential("cmp_1") == {"refuse": codekeys.PAUSED_TEXT}
140
141
  run(check())
141
142
  assert live.credential("cmp_1")["trustedrouter"] and "back on" in said[-1]
143
+ run(check()) # pass 9, C#5: a 404 that is NOT the account's "no such coding key" (a gateway's route miss) is not a revocation
144
+ assert live.credential("cmp_1")["trustedrouter"] and codekeys.for_computer("cmp_1") is not None, "the keys stay"
142
145
  run(check())
143
146
  assert live.credential("cmp_1") == {"refuse": codekeys.REVOKED_TEXT} and codekeys.for_computer("cmp_1") is None, "revoked: forgotten here too"
144
147
 
@@ -942,3 +942,42 @@ def test_the_python_connector_answers_this_computers_security_check(monkeypatch)
942
942
  await client.peer.aclose()
943
943
  await connector.stop()
944
944
  run(go())
945
+
946
+
947
+ # ── state machines pass 9, 9·C#10: the hello's ts never steps back ────────────────────────────────────────────────────
948
+ def test_9c10_the_hello_clock_never_steps_back_nor_across_a_restart(tmp_path):
949
+ """= tools/opencode-connector.test.mjs "9·C#10 …": a page drops a hello whose ts is not after the last it heard."""
950
+ path = tmp_path / "hello-cmp.json"
951
+ now = [5_000_000]
952
+ clock = conn.hello_clock(path, now=lambda: now[0])
953
+ a = clock()
954
+ now[0] -= 120_000
955
+ b = clock()
956
+ assert b > a, "the clock stepped back; the hello did not"
957
+ assert conn.hello_clock(path, now=lambda: now[0])() > b, "nor across a restart"
958
+
959
+
960
+ @pytest.mark.parametrize("make", CONNECTORS)
961
+ def test_9c10_a_connector_restarted_behind_its_last_hello_still_says_hello_after_it(make, tmp_path):
962
+ """Both connectors read the same high-water file (hello-<computerId>.json beside auto-<computerId>.json): one left by a
963
+ process whose clock was ahead puts the next hello after it, so an open page takes it."""
964
+ import time as _time
965
+
966
+ auto = tmp_path / "auto"
967
+ auto.mkdir()
968
+ ahead = int(_time.time() * 1000) + 600_000
969
+ (auto / "hello-cmp_test.json").write_text(json.dumps({"v": 1, "upTo": ahead}))
970
+
971
+ async def go():
972
+ async with Rig() as rig:
973
+ connector = make(rig, 30_000, autoDir=str(auto))
974
+ await connector.start()
975
+ client = PyClient(rig.secret, rig.relay.url)
976
+ try:
977
+ await client.start()
978
+ assert client.hellos()[-1]["ts"] > ahead
979
+ finally:
980
+ await client.peer.aclose()
981
+ await connector.stop()
982
+
983
+ run(go())
@@ -246,3 +246,45 @@ def test_link_node_names_the_app_whose_relay_answered(tmp_path):
246
246
  get_json=get_json, post_json=nopost, challenge=ch, svg_path=tmp_path / "q.svg",
247
247
  out=lambda *a, **k: None, err=lambda *a: None))
248
248
  assert account and account["origin"] == "https://b.test"
249
+
250
+
251
+ def _open_ack(ch: devicelink.LinkChallenge, reply: dict, ack: dict) -> dict:
252
+ """What the giving device reads: the ack key is the same ECDH secret from either side (deviceLink.js openLinkAck)."""
253
+ key = devicelink._shared_key(ch.priv, devicelink._import_pub(reply["epk"]), reply["ref"], devicelink._ACK_INFO)
254
+ raw = _js.unb64u_loose(ack["ack"])
255
+ return json.loads(key.decrypt(raw[:12], raw[12:], None))
256
+
257
+
258
+ def test_9c3_the_ack_names_the_computer_it_paired_and_only_a_well_formed_one():
259
+ """State machines pass 9, 9·C#3 (a): a computer that paired names its computerId in its report to the giving phone, which
260
+ then confirms exactly it in the account's sealed list. A failure names nothing; a malformed id is dropped."""
261
+ ch = devicelink.new_link_challenge()
262
+ reply = devicelink.seal_to_challenge(devicelink.parse_challenge(ch.text), {"v": 1, "master": "M"})
263
+ back = {"ref": reply["ref"], "epk": reply["epk"]}
264
+ assert _open_ack(ch, reply, devicelink.seal_link_ack(ch.priv, back, True, "", cid="cmp_lenovo01")) == {"v": 1, "ok": True, "cid": "cmp_lenovo01"}
265
+ assert _open_ack(ch, reply, devicelink.seal_link_ack(ch.priv, back, True)) == {"v": 1, "ok": True}
266
+ for bad in ["short", "a b c d e f g h", "x" * 65, "../../etc/pw", 123, None]:
267
+ assert _open_ack(ch, reply, devicelink.seal_link_ack(ch.priv, back, True, "", cid=bad)) == {"v": 1, "ok": True}, bad
268
+ assert _open_ack(ch, reply, devicelink.seal_link_ack(ch.priv, back, False, "no keys", cid="cmp_lenovo01")) == {"v": 1, "ok": False, "why": "no keys"}
269
+
270
+
271
+ def test_9c3_link_reporter_passes_the_computer_id(monkeypatch):
272
+ sent = []
273
+
274
+ class Client:
275
+ async def aclose(self):
276
+ pass
277
+
278
+ monkeypatch.setattr(link.net, "new_client", lambda: Client())
279
+
280
+ def make_post_json(_client):
281
+ async def post(url, body):
282
+ sent.append((url, body))
283
+ return post
284
+ monkeypatch.setattr(link.net, "make_post_json", make_post_json)
285
+ ch = devicelink.new_link_challenge()
286
+ reply = devicelink.seal_to_challenge(devicelink.parse_challenge(ch.text), {"v": 1, "master": "M"})
287
+ report = link._reporter(ch.priv, {"ref": reply["ref"], "epk": reply["epk"]}, "https://relay.example")
288
+ asyncio.run(report(True, "", "cmp_lenovo01"))
289
+ assert sent[0][0] == "https://relay.example/api/link"
290
+ assert _open_ack(ch, reply, sent[0][1]) == {"v": 1, "ok": True, "cid": "cmp_lenovo01"}
@@ -203,3 +203,12 @@ def test_minting_the_password_into_an_existing_world_readable_or_symlinked_env_f
203
203
  assert pp.env_path().is_symlink(), "the user's symlink is kept"
204
204
  assert real.stat().st_mode & 0o777 == 0o600 and real.read_text().startswith("OTHER=1\nOPENCODE_SERVER_PASSWORD=")
205
205
  assert [p.name for p in tmp_path.iterdir() if p.name.startswith(".real.env")] == [], "no temp file left behind"
206
+
207
+
208
+ def test_the_new_pairing_lands_on_the_file_as_it_is_now_an_account_unpaired_during_the_scan_stays_out():
209
+ """State machines pass 9, 9·C#6 (tools/opencode-pair.test.mjs has the twin)."""
210
+ before = pp.upsert_pairing(pp.upsert_pairing(None, account="a@x", idx=IDX)["doc"], account="b@y", idx=IDX2)["doc"]
211
+ u = pp.upsert_pairing(before, account="c@z", idx={"room": "sp-third", "mk": "MK3"})
212
+ now = pp.remove_pairings(before, "a@x")["doc"]
213
+ assert [p["account"] for p in u["doc"]["pairings"]] == ["a@x", "b@y", "c@z"], "what the tool used to write"
214
+ assert [p["account"] for p in pp.with_entry(now, u["entry"])["pairings"]] == ["b@y", "c@z"]
@@ -33,6 +33,18 @@ def test_publish_refuses_without_a_definitive_read_and_writes_nothing():
33
33
  assert api.writes == []
34
34
 
35
35
 
36
+ def test_a_computer_the_account_removed_does_not_put_itself_back_without_a_scan():
37
+ """State machines pass 9, 9·C#3 (tools/opencode-pair.test.mjs has the twin)."""
38
+ removed = {"v": 1, "computers": {"cmp_desk_01": {"removed": True, "mod": 900}}}
39
+ api = MockApi(docs={"computers": removed})
40
+ r = run(acct.publish_computer(call=api.call, idx=IDX, computer_id="cmp_desk_01", name="desk", relay=RELAY, secret="N" * 43, now=1000))
41
+ assert r["ok"] is False and r["removed"] is True and "removed" in r["why"]
42
+ assert api.writes == [], "nothing written over the tombstone"
43
+ scan = run(acct.publish_computer(call=api.call, idx=IDX, computer_id="cmp_desk_01", name="desk", relay=RELAY, secret="N" * 43,
44
+ now=1000, revive=True))
45
+ assert scan["ok"], scan
46
+
47
+
36
48
  def test_publish_adds_beside_the_others_and_verifies():
37
49
  other = with_computer(None, "cmp_laptop_1", {"name": "laptop", "relay": RELAY, "secret": "L" * 43}, 500)
38
50
  api = MockApi(docs={"computers": other})
@@ -446,8 +458,8 @@ def test_the_phone_that_sent_the_keys_hears_how_pairing_went(monkeypatch):
446
458
  def scan(origin="https://witbitz-spaces.pages.dev", **extra):
447
459
  heard = []
448
460
 
449
- async def report(ok, why=""):
450
- heard.append((ok, why))
461
+ async def report(ok, why="", cid=""):
462
+ heard.append((ok, why, cid))
451
463
 
452
464
  async def link_fn():
453
465
  return {"email": "me@x", "idx": IDX, "master": "M" * 43, "anchor": ANCHOR, "origin": origin, "_report": report, **extra}
@@ -455,7 +467,8 @@ def test_the_phone_that_sent_the_keys_hears_how_pairing_went(monkeypatch):
455
467
 
456
468
  link_fn, heard = scan()
457
469
  assert run(pair.main(["--name", "desk"], call=MockApi().call, link_fn=link_fn, keys=FakeKeys(), **Capture().kw())) == 0
458
- assert heard == [(True, "")]
470
+ # …and names the computer it paired, so that phone confirms exactly it in the account's sealed list (pass 9, 9·C#3)
471
+ assert heard == [(True, "", pp.read_pairings()["pairings"][0]["computerId"])]
459
472
  assert "_report" not in pp.read_pairings()["pairings"][0], "the reporter is never saved"
460
473
 
461
474
  link_fn, heard = scan("https://spaces.witbitz.chat") # this install is the regular app's
@@ -465,8 +478,70 @@ def test_the_phone_that_sent_the_keys_hears_how_pairing_went(monkeypatch):
465
478
  link_fn, heard = scan()
466
479
  keys = FakeKeys(refuse=("not_invited", "me@x is not on the list"))
467
480
  assert run(pair.main([], call=MockApi().call, link_fn=link_fn, keys=keys, **Capture().kw())) == 1
468
- assert heard == [(False, "it got no coding keys: me@x is not on the list")]
481
+ assert heard == [(False, "it got no coding keys: me@x is not on the list", "")]
469
482
 
470
483
  link_fn, heard = scan()
471
484
  assert run(pair.main([], call=MockApi(read_status=503).call, link_fn=link_fn, keys=FakeKeys(), **Capture().kw())) == 1
472
485
  assert heard and heard[0][0] is False and "Scan again" in heard[0][1]
486
+
487
+
488
+ # ── state machines pass 9, 9·C#4: a pairing that failed after the mint was not undone ─────────────────────────────────
489
+ class ServerKeys(FakeKeys):
490
+ """FakeKeys with the server's rows: a mint retires this computer's live rows first (codeKeys.mjs mintFor); `lost` = the
491
+ mint reached the server but its answer never came back."""
492
+
493
+ def __init__(self, lost: bool = False, revoke_ok: bool = True) -> None:
494
+ super().__init__(revoke_ok=revoke_ok)
495
+ self.live: set = set()
496
+ self.lost = lost
497
+
498
+ async def mint(self, **kw):
499
+ self.live = {r for r in self.live if r[0] != kw["computer_id"]}
500
+ entry = await super().mint(**kw)
501
+ self.live.add((entry["computerId"], entry["keyId"]))
502
+ if self.lost:
503
+ raise codekeys.CodeKeyRefusal("unreachable", "could not reach Witbitz (timeout)")
504
+ return entry
505
+
506
+ async def revoke(self, entry):
507
+ ok = await super().revoke(entry)
508
+ if ok:
509
+ self.live.discard((entry["computerId"], entry["keyId"]))
510
+ return ok
511
+
512
+
513
+ async def _scan():
514
+ return {"email": "me@x", "idx": IDX, "master": "m", "anchor": ANCHOR}
515
+
516
+
517
+ def test_9c4_a_refresh_whose_publish_fails_keeps_the_new_keys_the_mint_retired_the_working_ones():
518
+ api, keys = MockApi(), ServerKeys()
519
+ assert run(pair.main([], call=api.call, link_fn=_scan, keys=keys, **Capture().kw())) == 0
520
+ cid = pp.read_pairings()["pairings"][0]["computerId"]
521
+ cap = Capture()
522
+ assert run(pair.main([], call=MockApi(read_status=503).call, link_fn=_scan, keys=keys, **cap.kw())) == 1
523
+ assert keys.minted[1]["computerId"] == cid, "a refresh asks for the same computer"
524
+ assert keys.revoked == [], "the new keys are not given back: they are the only live ones"
525
+ held = codekeys.for_computer(cid)
526
+ assert held and (cid, held["keyId"]) in keys.live, "the keys file names a LIVE key, not the retired one"
527
+ assert pp.read_pairings()["pairings"][0]["computerId"] == cid and "nothing saved locally" not in cap.text()
528
+
529
+
530
+ def test_9c4_a_new_pairing_whose_mint_answer_is_lost_retries_with_the_same_computer():
531
+ api, keys = MockApi(), ServerKeys(lost=True)
532
+ assert run(pair.main([], call=api.call, link_fn=_scan, keys=keys, **Capture().kw())) == 1
533
+ assert not pp.pairings_path().exists()
534
+ keys.lost = False
535
+ assert run(pair.main([], call=api.call, link_fn=_scan, keys=keys, **Capture().kw())) == 0
536
+ assert keys.minted[1]["computerId"] == keys.minted[0]["computerId"], "the retry reuses the id the lost mint was for"
537
+ assert len(keys.live) == 1, "no live key row is left that no file names"
538
+ assert pp.pending_id(IDX["room"]) == "", "done: the note goes"
539
+
540
+
541
+ def test_9c4_a_new_pairing_whose_publish_and_give_back_both_fail_retries_with_the_same_computer():
542
+ keys = ServerKeys(revoke_ok=False)
543
+ assert run(pair.main([], call=MockApi(read_status=503).call, link_fn=_scan, keys=keys, **Capture().kw())) == 1
544
+ assert len(keys.live) == 1
545
+ assert run(pair.main([], call=MockApi().call, link_fn=_scan, keys=keys, **Capture().kw())) == 0
546
+ assert keys.minted[1]["computerId"] == keys.minted[0]["computerId"]
547
+ assert len(keys.live) == 1, "the orphan was retired by the retry's mint"
File without changes
File without changes
File without changes