@capagents/forgeqe 3.0.8 → 3.1.0

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 (214) hide show
  1. package/HOW_TO_USE.md +20 -19
  2. package/bin/bundle.js +3 -3
  3. package/bin/forgeqe.js +3 -3
  4. package/bin/license.js +1 -1
  5. package/dist/docs-site/CREDITS.md +11 -4
  6. package/dist/docs-site/LICENSE.dm-sans.txt +93 -0
  7. package/dist/docs-site/LICENSE.jetbrains-mono.txt +93 -0
  8. package/dist/docs-site/app-look.css +62 -0
  9. package/dist/docs-site/architecture-map/arch-fill.js +56 -0
  10. package/dist/docs-site/architecture-map/arch-theme.css +203 -0
  11. package/dist/docs-site/architecture-map/arch.css +0 -5
  12. package/dist/docs-site/architecture-map/index.html +57 -43
  13. package/dist/docs-site/docs/app-theme.css +166 -0
  14. package/dist/docs-site/docs/architecture/index.html +14 -11
  15. package/dist/docs-site/docs/containers/index.html +14 -11
  16. package/dist/docs-site/docs/cost-architecture/index.html +14 -11
  17. package/dist/docs-site/docs/custom-agents-first-run/index.html +14 -11
  18. package/dist/docs-site/docs/desktop/index.html +14 -11
  19. package/dist/docs-site/docs/desktop-ci/index.html +14 -11
  20. package/dist/docs-site/docs/docs.css +0 -7
  21. package/dist/docs-site/docs/evidence/index.html +14 -11
  22. package/dist/docs-site/docs/feature-test-prompts/index.html +14 -11
  23. package/dist/docs-site/docs/graphify/index.html +14 -11
  24. package/dist/docs-site/docs/guardrails/index.html +14 -11
  25. package/dist/docs-site/docs/index.html +71 -36
  26. package/dist/docs-site/docs/mobile/index.html +56 -18
  27. package/dist/docs-site/docs/model-routing/index.html +14 -11
  28. package/dist/docs-site/docs/product-graph/index.html +14 -11
  29. package/dist/docs-site/docs/product-knowledge/index.html +14 -11
  30. package/dist/docs-site/docs/product-views/index.html +14 -11
  31. package/dist/docs-site/docs/search.js +1 -1
  32. package/dist/docs-site/docs/web-app/index.html +14 -11
  33. package/dist/docs-site/img/wordmark.webp +0 -0
  34. package/dist/docs-site/site-header.css +0 -5
  35. package/dist/forgeqe.js +1889 -1863
  36. package/dist/template.html +14 -14
  37. package/dist/web/assets/AgentWork-C3KdZh5M.js +2 -0
  38. package/dist/web/assets/ApiTests-BLnl7JGO.js +10 -0
  39. package/dist/web/assets/Browse-C-Enjpmd.js +2 -0
  40. package/dist/web/assets/Chat-Bt6jZI68.js +3 -0
  41. package/dist/web/assets/Choices-D5eTFinz.js +3 -0
  42. package/dist/web/assets/{CommandPalette-Cm8lLnfi.js → CommandPalette-D89NM2_E.js} +1 -1
  43. package/dist/web/assets/{Compare-D10RIrFU.js → Compare-YfFYHwfK.js} +1 -1
  44. package/dist/web/assets/Cost-ClaDz0YR.js +1 -0
  45. package/dist/web/assets/Data-jSFgAfej.js +6 -0
  46. package/dist/web/assets/Desktop-BofKeLVf.js +1 -0
  47. package/dist/web/assets/DesktopReview--WjeZh3w.js +1 -0
  48. package/dist/web/assets/Evidence-CJNzSQpY.js +1 -0
  49. package/dist/web/assets/{Explore-DOQ8KddV.js → Explore-BdFvqgF4.js} +2 -2
  50. package/dist/web/assets/Features-CIBbw6PG.js +1 -0
  51. package/dist/web/assets/Flags-B62v4uWR.js +2 -0
  52. package/dist/web/assets/Flaky-Cut1kZw6.js +1 -0
  53. package/dist/web/assets/Impact-jOSl5Q0k.js +3 -0
  54. package/dist/web/assets/Jobs-DMJGgWtQ.js +5 -0
  55. package/dist/web/assets/KindPage-BbQWH5wa.js +6 -0
  56. package/dist/web/assets/Migration-BBgv7xXo.js +2 -0
  57. package/dist/web/assets/PageAgent-txbNoP6u.js +1 -0
  58. package/dist/web/assets/Product-BrXH81Ns.js +7 -0
  59. package/dist/web/assets/Production-CCVtFNGQ.js +1 -0
  60. package/dist/web/assets/Quality-Dxh-60A8.js +1 -0
  61. package/dist/web/assets/Readiness-DyJvSOLN.js +1 -0
  62. package/dist/web/assets/Record-Dnlkimjb.js +1 -0
  63. package/dist/web/assets/Regression-D2DDTwzs.js +5 -0
  64. package/dist/web/assets/Reports-ClcY7M0Q.js +2 -0
  65. package/dist/web/assets/Response-D9FYUvHg.js +9 -0
  66. package/dist/web/assets/RunDiff-CNImaEdz.js +1 -0
  67. package/dist/web/assets/Runs-CFvmdULI.js +2 -0
  68. package/dist/web/assets/{Steps-BoSfaEHJ.js → Steps-BS66s0E1.js} +2 -2
  69. package/dist/web/assets/TestCases-CrQEUtfD.js +1 -0
  70. package/dist/web/assets/TestData-e3IX0xwG.js +2 -0
  71. package/dist/web/assets/TestDebt-tXPoexMF.js +1 -0
  72. package/dist/web/assets/TestManagement-wjGaoZzI.js +1 -0
  73. package/dist/web/assets/Tosca-C5YaMLS0.js +3 -0
  74. package/dist/web/assets/WhatsNew-CwnRbDnd.js +1 -0
  75. package/dist/web/assets/azuredevops-BcQ5AFOM.js +1 -0
  76. package/dist/web/assets/crew-CWfjZIxE.js +1 -0
  77. package/dist/web/assets/{families-D78NUxTI.js → families-DWilSDct.js} +1 -1
  78. package/dist/web/assets/filters-CVzIOjPG.js +1 -0
  79. package/dist/web/assets/{fold-DFcP0iIo.js → fold-tvLGnxD1.js} +1 -1
  80. package/dist/web/assets/frame-Deu1IqzV.js +13 -0
  81. package/dist/web/assets/index-BWMIKyPB.js +76 -0
  82. package/dist/web/assets/index-C2Yq55oT.css +2 -0
  83. package/dist/web/assets/line-icons-C_amZ5-o.js +1 -0
  84. package/dist/web/assets/logos-C1NBtBMc.js +1 -0
  85. package/dist/web/assets/logos-DFyhMw0i.js +1 -0
  86. package/dist/web/assets/{markdown-DIB_8ewG.js → markdown-DC2HA0yZ.js} +7 -7
  87. package/dist/web/assets/paletteCommands-Qxm5DZIs.js +1 -0
  88. package/dist/web/assets/parts-BR6dUwqn.js +1 -0
  89. package/dist/web/assets/{productParts-BYAQJWF9.js → productParts-BxdHuSBa.js} +1 -1
  90. package/dist/web/assets/qualityParts-lz6eYVxC.js +1 -0
  91. package/dist/web/assets/{recordTest-GM1nj_SM.js → recordTest-CcplpTS6.js} +1 -1
  92. package/dist/web/assets/today-DuQFapJM.js +1 -0
  93. package/dist/web/assets/when-CHnpLdYw.js +1 -0
  94. package/dist/web/index.html +12 -6
  95. package/docs/ForgeQE-Client-Overview.pdf +0 -0
  96. package/docs/ForgeQE-Installation-Guide.pdf +0 -0
  97. package/docs/MOBILE.md +42 -7
  98. package/docs/TEST_MANAGEMENT_PLAN.md +186 -15
  99. package/docs/user-guide.html +1 -1
  100. package/package.json +2 -1
  101. package/prompts/README.md +1 -0
  102. package/prompts/brain.md +1 -0
  103. package/prompts/test-linker.md +43 -0
  104. package/py/forgeqe_data/connect.py +3 -1
  105. package/py/forgeqe_data/flows.py +1 -1
  106. package/py/forgeqe_data/service.py +1 -1
  107. package/py/forgeqe_data/streams.py +1 -1
  108. package/py/forgeqe_data/testdata.py +1 -1
  109. package/py/forgeqe_desktop/replay.py +43 -1
  110. package/py/forgeqe_desktop/service.py +2 -0
  111. package/py/forgeqe_desktop/workflow.py +77 -15
  112. package/py/forgeqe_engine/brand.py +1 -1
  113. package/py/forgeqe_engine/browser.py +2 -1
  114. package/py/forgeqe_engine/diagnostics.py +1 -1
  115. package/py/forgeqe_engine/memory.py +2 -1
  116. package/py/forgeqe_engine/neutral_log.py +1 -1
  117. package/py/forgeqe_engine/otp.py +127 -12
  118. package/py/forgeqe_engine/pwlaunch.mjs +1 -1
  119. package/py/forgeqe_engine/recordsession.py +13 -3
  120. package/py/forgeqe_engine/webrecord.py +20 -0
  121. package/py/forgeqe_mobile/appium_driver.py +225 -10
  122. package/py/forgeqe_mobile/locators.py +277 -0
  123. package/py/forgeqe_mobile/maestro.py +28 -1
  124. package/py/forgeqe_mobile/magiclink.py +79 -0
  125. package/py/forgeqe_mobile/record.py +284 -67
  126. package/py/forgeqe_mobile/service.py +9 -0
  127. package/py/forgeqe_mobile/webview.py +142 -0
  128. package/py/forgeqe_testmgmt/__init__.py +1 -0
  129. package/py/forgeqe_testmgmt/pytest_collect.py +56 -0
  130. package/py/forgeqe_tosca/ntir.py +45 -6
  131. package/dist/docs-site/LICENSE.ubuntu.txt +0 -96
  132. package/dist/docs-site/img/icons/api.svg +0 -1
  133. package/dist/docs-site/img/icons/architecture.svg +0 -1
  134. package/dist/docs-site/img/icons/branch.svg +0 -1
  135. package/dist/docs-site/img/icons/browser-agent.svg +0 -1
  136. package/dist/docs-site/img/icons/case.svg +0 -1
  137. package/dist/docs-site/img/icons/container.svg +0 -1
  138. package/dist/docs-site/img/icons/context-engine.svg +0 -1
  139. package/dist/docs-site/img/icons/desktop.svg +0 -1
  140. package/dist/docs-site/img/icons/download.svg +0 -1
  141. package/dist/docs-site/img/icons/explorer.svg +0 -1
  142. package/dist/docs-site/img/icons/feature.svg +0 -1
  143. package/dist/docs-site/img/icons/healer.svg +0 -1
  144. package/dist/docs-site/img/icons/knowledge-base.svg +0 -1
  145. package/dist/docs-site/img/icons/mail.svg +0 -1
  146. package/dist/docs-site/img/icons/mobile.svg +0 -1
  147. package/dist/docs-site/img/icons/model.svg +0 -1
  148. package/dist/docs-site/img/icons/network.svg +0 -1
  149. package/dist/docs-site/img/icons/orchestrator.svg +0 -1
  150. package/dist/docs-site/img/icons/plug.svg +0 -1
  151. package/dist/docs-site/img/icons/pr-reviewer.svg +0 -1
  152. package/dist/docs-site/img/icons/replay.svg +0 -1
  153. package/dist/docs-site/img/icons/report.svg +0 -1
  154. package/dist/docs-site/img/icons/result.svg +0 -1
  155. package/dist/docs-site/img/icons/rule.svg +0 -1
  156. package/dist/docs-site/img/icons/scribe.svg +0 -1
  157. package/dist/docs-site/img/icons/shield.svg +0 -1
  158. package/dist/docs-site/img/icons/specs.svg +0 -1
  159. package/dist/docs-site/img/icons/speed.svg +0 -1
  160. package/dist/docs-site/img/icons/stories.svg +0 -1
  161. package/dist/docs-site/img/icons/terminal.svg +0 -1
  162. package/dist/docs-site/img/icons/test-finder.svg +0 -1
  163. package/dist/docs-site/img/icons/visual.svg +0 -1
  164. package/dist/docs-site/img/icons/web.svg +0 -1
  165. package/dist/docs-site/img/icons/wikis.svg +0 -1
  166. package/dist/web/assets/Agent-BgpsSPrr.js +0 -7
  167. package/dist/web/assets/AgentWork-VRJbVshA.js +0 -2
  168. package/dist/web/assets/ApiTests-DHwAbLqi.js +0 -10
  169. package/dist/web/assets/Browse-BMF56Efz.js +0 -2
  170. package/dist/web/assets/Chat-CaUU-WY7.js +0 -3
  171. package/dist/web/assets/Cost-B_UPdLMv.js +0 -1
  172. package/dist/web/assets/Data-C4H5sYEC.js +0 -6
  173. package/dist/web/assets/Desktop-bLj_WL8M.js +0 -1
  174. package/dist/web/assets/DesktopReview-Bl9TCBkR.js +0 -1
  175. package/dist/web/assets/Evidence-Cp1HUzpL.js +0 -1
  176. package/dist/web/assets/Features-RCBkPcEQ.js +0 -1
  177. package/dist/web/assets/Flags-n0IwBw02.js +0 -2
  178. package/dist/web/assets/Flaky-BfwzLt5Z.js +0 -1
  179. package/dist/web/assets/Impact-DLpuEZSR.js +0 -3
  180. package/dist/web/assets/Jobs-BdXmyaEl.js +0 -5
  181. package/dist/web/assets/KindPage-B3aoqE1U.js +0 -6
  182. package/dist/web/assets/Migration-CZyx2ubc.js +0 -2
  183. package/dist/web/assets/PageAgent-D5ZEQOQe.js +0 -1
  184. package/dist/web/assets/Product-BZe62mCa.js +0 -7
  185. package/dist/web/assets/Production-D0PyJr7i.js +0 -1
  186. package/dist/web/assets/Quality-k-6G5B1k.js +0 -1
  187. package/dist/web/assets/Readiness-InUynp50.js +0 -1
  188. package/dist/web/assets/Record-DIprTx7M.js +0 -1
  189. package/dist/web/assets/Regression-CWk9uEE7.js +0 -5
  190. package/dist/web/assets/RelationGraph-ybf6gf-K.js +0 -1
  191. package/dist/web/assets/Reports-BYOTLZah.js +0 -2
  192. package/dist/web/assets/Response-BC4GgybP.js +0 -9
  193. package/dist/web/assets/RunDiff-B0sRO9OI.js +0 -1
  194. package/dist/web/assets/Runs-Dy_fBhhR.js +0 -2
  195. package/dist/web/assets/TestCases-D4xZlPgR.js +0 -1
  196. package/dist/web/assets/TestData-CXDU1gv4.js +0 -2
  197. package/dist/web/assets/TestDebt-Cc5ODjR-.js +0 -1
  198. package/dist/web/assets/TestManagement-Cdj_o5D6.js +0 -1
  199. package/dist/web/assets/Tosca-CfgkdgcT.js +0 -3
  200. package/dist/web/assets/WhatsNew-DVzuub1d.js +0 -1
  201. package/dist/web/assets/agentTabs-CmOYLCIU.js +0 -1
  202. package/dist/web/assets/dataParts-Bw4pl6JD.js +0 -3
  203. package/dist/web/assets/diff-CRxu9ARd.js +0 -2
  204. package/dist/web/assets/filters-D2j1h_NS.js +0 -1
  205. package/dist/web/assets/frame-Cr9XkzMf.js +0 -13
  206. package/dist/web/assets/index-C5JQ2Q4O.js +0 -69
  207. package/dist/web/assets/index-CpHco9gF.css +0 -2
  208. package/dist/web/assets/line-icons-Cb4JZG1G.js +0 -1
  209. package/dist/web/assets/logos-d0fFqQS2.js +0 -1
  210. package/dist/web/assets/paletteCommands-COA2_LAh.js +0 -1
  211. package/dist/web/assets/parts-Dsb4bByj.js +0 -1
  212. package/dist/web/assets/qualityParts-DyfqNmRK.js +0 -1
  213. package/dist/web/assets/rows-CpFeqs4P.js +0 -1
  214. package/dist/web/assets/segmented-BbcK9lLg.js +0 -1
@@ -135,7 +135,9 @@ def rds_ca() -> str:
135
135
  path = _home() / "data" / "certs" / "rds-global-bundle.pem"
136
136
  if not path.exists():
137
137
  path.parent.mkdir(parents=True, exist_ok=True)
138
- with urllib.request.urlopen(RDS_CA_URL, timeout=30, context=ssl_lib.create_default_context()) as res:
138
+ ctx = ssl_lib.create_default_context() # verified, and never below TLS 1.2 (Python 3.9 still offers 1.0)
139
+ ctx.minimum_version = ssl_lib.TLSVersion.TLSv1_2
140
+ with urllib.request.urlopen(RDS_CA_URL, timeout=30, context=ctx) as res:
139
141
  body = res.read()
140
142
  if b"BEGIN CERTIFICATE" not in body:
141
143
  raise ConnectError("The Amazon RDS CA bundle download did not contain certificates")
@@ -419,7 +419,7 @@ def _naive(v: Any) -> Optional[dt.datetime]:
419
419
  def check(f: Flow, src: Reader, dst: Reader, *, now: Optional[dt.datetime] = None, began: Optional[dt.datetime] = None,
420
420
  mask: Callable[[str], bool] = lambda _: False, log: Callable[[str], None] = lambda _: None) -> Dict[str, Any]:
421
421
  """One flow's checks; ok when nothing is missing, wrong, late or duplicated."""
422
- now = now or dt.datetime.utcnow()
422
+ now = now or dt.datetime.now(dt.timezone.utc).replace(tzinfo=None)
423
423
  began = began or now
424
424
  result: Dict[str, Any] = {"flow": f.name, "from": f.src.label, "to": f.dst.label, "mode": f.mode}
425
425
 
@@ -531,7 +531,7 @@ def handle_flows(req: Mapping[str, Any], events: Events, env: Mapping[str, str])
531
531
  problems[n].append(f"ready.sql does not run on {f.dst.db} (write table names as that database knows them, without the database's name): {_error(err)}")
532
532
  return {"ok": not any(problems.values()), "problems": {n: p for n, p in problems.items() if p}}
533
533
  if op == "flow_check":
534
- began = dt.datetime.utcnow()
534
+ began = dt.datetime.now(dt.timezone.utc).replace(tzinfo=None)
535
535
  results = []
536
536
  for name, f in all_flows.items():
537
537
  problems = flows.check_names(f, catalog(f.src.db), catalog(f.dst.db))
@@ -250,7 +250,7 @@ def _at(value: Any, path: str) -> Any:
250
250
  def _when(v: Any) -> Optional[dt.datetime]:
251
251
  """When a record changed, from an API's JSON: an ISO date and time, or seconds (or milliseconds) since 1970; UTC, naive."""
252
252
  if isinstance(v, (int, float)) and not isinstance(v, bool):
253
- return dt.datetime.utcfromtimestamp(v / 1000 if v > 1e11 else v)
253
+ return dt.datetime.fromtimestamp(v / 1000 if v > 1e11 else v, dt.timezone.utc).replace(tzinfo=None)
254
254
  if isinstance(v, str) and v.strip():
255
255
  try:
256
256
  t = dt.datetime.fromisoformat(v.strip().replace("Z", "+00:00"))
@@ -727,7 +727,7 @@ def write_files(g: Generated, out_dir: Path, fmt: str, *, engine: Any = None, sc
727
727
  r = {k: v for k, v in r.items() if k not in omit.get(t, set())}
728
728
  stmt = insert(table).values(**r).compile(dialect=dialect, compile_kwargs={"literal_binds": True})
729
729
  # The key the database makes is not read back by a script: no RETURNING.
730
- lines.append(re.sub(r"\s+RETURNING\s+[^;]*$", "", str(stmt)) + ";")
730
+ lines.append(re.sub(r"(?<!\s)\s+RETURNING\s+[^;]*$", "", str(stmt)) + ";")
731
731
  path.write_text("\n".join(lines) + "\n", encoding="utf-8")
732
732
  files.append(str(path))
733
733
  return files
@@ -49,6 +49,8 @@ class StepResult:
49
49
  error: str = ""
50
50
  healed_target: Optional[Dict[str, Any]] = None
51
51
  attempts: int = 1
52
+ # Which of the target's locators found its control (mobile): 0 its own, n its n-th fallback, when its own failed.
53
+ found_by: int = 0
52
54
  # Labels of the dialogs dismissed while this step ran.
53
55
  dismissed: List[str] = field(default_factory=list)
54
56
  # A dismiss control found but not clicked, with the reason: told with the step's error, never dropped.
@@ -83,6 +85,10 @@ STALE_RETRIES = 2
83
85
  LAUNCH_SETTLE = 1.5
84
86
 
85
87
 
88
+ # How long a checkbox or switch is given to show its new state after a tap.
89
+ CHECKED_SECONDS = 3.0
90
+
91
+
86
92
  def _label(target: Mapping[str, Any]) -> str:
87
93
  return str(target.get("name") or target.get("automation_id") or "")
88
94
 
@@ -104,6 +110,7 @@ def replay(
104
110
  clock: Callable[[], float] = time.time,
105
111
  keep_open: bool = False,
106
112
  secret_aliases: Optional[Mapping[str, str]] = None,
113
+ open_link: Optional[Callable[[str, float], None]] = None,
107
114
  ) -> ReplayResult:
108
115
  wf = validate(dict(workflow))
109
116
  spec = resolve_app(wf["app"], apps, must_exist=must_exist)
@@ -134,6 +141,9 @@ def replay(
134
141
 
135
142
  runner = _Runner(driver, spec, values, allowed_secret, wf.get("timeout", find_timeout), wf.get("dismiss") or [], sleep, clock, compare_image)
136
143
  runner.mobile = wf["format"] == MOBILE_FORMAT
144
+ runner.open_link = open_link
145
+ if any(s["op"] == "open_link" for s in wf["steps"]) and open_link is None:
146
+ raise WorkflowError("this workflow opens a magic link, and this replay has no mailbox to read it from")
137
147
  retry_ops = MOBILE_RETRY_OPS if runner.mobile else RETRY_OPS
138
148
  default_retries = int(wf.get("retries", 0))
139
149
  result = ReplayResult(ok=True)
@@ -146,6 +156,8 @@ def replay(
146
156
  op = step["op"]
147
157
  res = StepResult(index=i, op=op, ok=True, ms=0)
148
158
  runner.res = res
159
+ # A magic link is the one sent since the step before it started (the step that asked for it).
160
+ runner.prev_started, runner.started = runner.started, started
149
161
  tries = 1 + (int(step.get("retries", default_retries)) if op in retry_ops else 0)
150
162
  error: Optional[Exception] = None
151
163
  attempt = failures = stale = 0
@@ -223,6 +235,9 @@ class _Runner:
223
235
  self.timeout, self.dismiss, self.sleep, self.clock, self.compare_image = timeout, dismiss, sleep, clock, compare_image
224
236
  self.res = StepResult(index=0, op="", ok=True, ms=0)
225
237
  self.mobile = False
238
+ self.open_link: Optional[Callable[[str, float], None]] = None
239
+ self.started: Optional[float] = None
240
+ self.prev_started: Optional[float] = None
226
241
 
227
242
  def dismiss_dialogs(self) -> bool:
228
243
  """Click every ``dismiss`` control that is on screen now; whether any was."""
@@ -253,6 +268,9 @@ class _Runner:
253
268
  started = self.clock()
254
269
  try:
255
270
  control = self.driver.find(target, timeout)
271
+ by = getattr(self.driver, "found_by", 0)
272
+ if isinstance(by, int) and by > 0:
273
+ self.res.found_by = max(self.res.found_by, by)
256
274
  wait_ready = getattr(self.driver, "wait_ready", None)
257
275
  if ready and wait_ready is not None:
258
276
  wait_ready(control, max(0.0, timeout - (self.clock() - started)))
@@ -281,6 +299,10 @@ class _Runner:
281
299
  self.dismiss_dialogs()
282
300
  elif op == "close":
283
301
  driver.close()
302
+ elif op == "open_link":
303
+ if self.open_link is None:
304
+ raise WorkflowError("this replay has no mailbox to read a magic link from")
305
+ self.open_link(step["login"], self.prev_started if self.prev_started is not None else self.started or self.clock())
284
306
  elif op == "wait":
285
307
  self.sleep(float(step["seconds"]))
286
308
  elif op == "keys" and self.mobile:
@@ -302,6 +324,10 @@ class _Runner:
302
324
  driver.scroll(step["direction"], control) # type: ignore[attr-defined]
303
325
  elif op == "scroll_to":
304
326
  self._scroll_to(step, timeout)
327
+ elif op in ("tap", "double_tap", "long_press") and "at" in step:
328
+ # A point inside the control (what the app draws there has no control of its own).
329
+ control = self.find(step["target"], timeout, ready=True)
330
+ driver.tap_point(control, step["at"], double=op == "double_tap", hold=op == "long_press") # type: ignore[attr-defined]
305
331
  elif op in ("tap", "double_tap"):
306
332
  driver.click(self.find(step["target"], timeout, ready=True), double=op == "double_tap")
307
333
  elif op == "long_press":
@@ -311,13 +337,17 @@ class _Runner:
311
337
  elif op == "expect_image":
312
338
  self._expect_image(index, step, timeout)
313
339
  else:
314
- control = self.find(step["target"], timeout, ready=op in ("click", "double_click", "type", "select"))
340
+ control = self.find(step["target"], timeout, ready=op in ("click", "double_click", "type", "select", "set_checked"))
315
341
  if op in ("click", "double_click"):
316
342
  driver.click(control, double=op == "double_click")
317
343
  elif op == "type":
318
344
  driver.type_text(control, fill(step["text"], self.values, self.secret))
319
345
  elif op == "select":
320
346
  driver.select(control, fill(step["value"], self.values, self.secret))
347
+ elif op == "set_checked":
348
+ self._set_checked(control, bool(step["checked"]), timeout)
349
+ elif op == "expect" and "checked" in step and driver.is_checked(control) != bool(step["checked"]): # type: ignore[attr-defined]
350
+ raise AssertionError(f"expected {_label(step['target'])!r} to be {'on' if step['checked'] else 'off'}, it is {'off' if step['checked'] else 'on'}")
321
351
  elif op == "expect" and "text" in step:
322
352
  want = fill(step["text"], self.values, self.secret)
323
353
  got = driver.text_of(control)
@@ -326,6 +356,18 @@ class _Runner:
326
356
  raise AssertionError("the control's text does not contain the expected value (it holds a secret, so it is not shown)")
327
357
  raise AssertionError(f"expected {want!r} in the control's text, found {got!r}")
328
358
 
359
+ def _set_checked(self, control: Any, want: bool, timeout: float) -> None:
360
+ """A checkbox, switch or radio button left ``want``: tapped only when it is not so already, then confirmed."""
361
+ driver = self.driver
362
+ if driver.is_checked(control) == want: # type: ignore[attr-defined]
363
+ return
364
+ driver.click(control)
365
+ deadline = self.clock() + min(timeout, CHECKED_SECONDS)
366
+ while driver.is_checked(control) != want: # type: ignore[attr-defined]
367
+ if self.clock() >= deadline:
368
+ raise AssertionError(f"it was tapped but stayed {'off' if want else 'on'}")
369
+ self.sleep(POLL_SECONDS)
370
+
329
371
  def _scroll_to(self, step: Mapping[str, Any], timeout: float) -> None:
330
372
  """Scroll (default: down the page) until the target is on screen, up to the timeout or MAX_SCROLLS."""
331
373
  direction = step.get("direction", "down")
@@ -76,6 +76,8 @@ def _model(req: Mapping[str, Any], events: Events, model_factory: Optional[Calla
76
76
 
77
77
  def _step_fields(res: Any) -> Dict[str, Any]:
78
78
  out = {"index": res.index, "op": res.op, "ok": res.ok, "ms": res.ms, "error": res.error, "healed_target": res.healed_target}
79
+ if res.found_by:
80
+ out["found_by"] = res.found_by
79
81
  if res.attempts > 1:
80
82
  out["attempts"] = res.attempts
81
83
  if res.dismissed:
@@ -34,20 +34,26 @@ MAX_DISMISS = 10
34
34
  RETRY_OPS = ("click", "double_click", "type", "select", "keys", "expect", "expect_image")
35
35
  TIMEOUT_OPS = ("launch", *TARGET_OPS, "expect_image", "long_press", "double_tap", "tap", "scroll_to", "drag")
36
36
 
37
- MOBILE_OPS = ("launch", "tap", "double_tap", "long_press", "type", "select", "expect", "expect_image", "swipe", "scroll", "scroll_to", "drag", "back", "hide_keyboard", "keys", "wait", "wait_for", "close")
38
- MOBILE_TARGET_OPS = ("tap", "double_tap", "long_press", "type", "select", "expect", "wait_for", "scroll_to", "drag")
39
- MOBILE_RETRY_OPS = ("tap", "double_tap", "long_press", "type", "select", "expect", "expect_image", "swipe", "scroll", "scroll_to", "drag", "keys")
37
+ MOBILE_OPS = ("launch", "open_link", "tap", "double_tap", "long_press", "type", "select", "set_checked", "expect", "expect_image", "swipe", "scroll", "scroll_to", "drag", "back", "hide_keyboard", "keys", "wait", "wait_for", "close")
38
+ MOBILE_TARGET_OPS = ("tap", "double_tap", "long_press", "type", "select", "set_checked", "expect", "wait_for", "scroll_to", "drag")
39
+ MOBILE_RETRY_OPS = ("tap", "double_tap", "long_press", "type", "select", "set_checked", "expect", "expect_image", "swipe", "scroll", "scroll_to", "drag", "keys")
40
40
  MOBILE_KEYS = ("enter", "back", "tab", "delete", "search")
41
41
  SWIPE_DIRECTIONS = ("up", "down", "left", "right")
42
42
  _MOBILE_STEP_KEYS = {
43
43
  "launch": set(),
44
- "tap": {"target"},
45
- "double_tap": {"target"},
46
- "long_press": {"target"},
44
+ # The newest magic link the login's site sent to its mailbox, opened on the device (forgeqe_mobile/magiclink.py).
45
+ "open_link": {"login"},
46
+ # at: [x, y] inside the target in thousandths of its width and height, for what the app draws with no control.
47
+ "tap": {"target", "at"},
48
+ "double_tap": {"target", "at"},
49
+ "long_press": {"target", "at"},
47
50
  "type": {"target", "text"},
48
51
  # Opens the target (a drop-down) and picks the item that shows `value`.
49
52
  "select": {"target", "value"},
50
- "expect": {"target", "text"},
53
+ # A checkbox, switch or radio button left on (checked: true) or off: tapped only when it is not so already.
54
+ "set_checked": {"target", "checked"},
55
+ # checked: the control is on (true) or off (false), as well as or instead of showing a text.
56
+ "expect": {"target", "text", "checked"},
51
57
  "expect_image": {"target", "image", "tolerance", "ignore"},
52
58
  "swipe": {"direction", "target"},
53
59
  # Moves the content (down: shows what is further down) of the target, or of the screen's scrolling view.
@@ -62,7 +68,7 @@ _MOBILE_STEP_KEYS = {
62
68
  "wait_for": {"target", "text", "gone"},
63
69
  "close": set(),
64
70
  }
65
- _MOBILE_REQUIRED = {"type": {"target", "text"}, "select": {"target", "value"}, "keys": {"keys"}, "wait": {"seconds"}, "expect_image": {"image"}, "swipe": {"direction"}, "scroll": {"direction"}, "drag": {"target", "to"}}
71
+ _MOBILE_REQUIRED = {"open_link": {"login"}, "type": {"target", "text"}, "select": {"target", "value"}, "set_checked": {"target", "checked"}, "keys": {"keys"}, "wait": {"seconds"}, "expect_image": {"image"}, "swipe": {"direction"}, "scroll": {"direction"}, "drag": {"target", "to"}}
66
72
  IMAGE_NAME = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_-]{0,99}\.png$")
67
73
  MAX_IGNORE = 20
68
74
 
@@ -123,12 +129,44 @@ def parse_chord(chord: str) -> List[str]:
123
129
  return [*mods, key]
124
130
 
125
131
 
126
- def _check_target(where: str, target: Any) -> Dict[str, Any]:
132
+ # A mobile target's alternatives a replay tries in order (forgeqe_mobile/locators.py), and how many at most.
133
+ MOBILE_LOCATOR_KEYS = ("within", "fallbacks", "web")
134
+ MAX_FALLBACKS = 4
135
+ _ANCHOR_KEYS = ("automation_id", "name")
136
+
137
+
138
+ def _check_target(where: str, target: Any, mobile: bool = False, fallback: bool = False) -> Dict[str, Any]:
127
139
  if not isinstance(target, dict):
128
140
  raise WorkflowError(f"{where}: target must be a mapping of UIA properties")
129
- unknown = set(target) - set(LOCATOR_KEYS)
141
+ allowed = set(LOCATOR_KEYS) | ({"within", "web"} | (set() if fallback else {"fallbacks"}) if mobile else set())
142
+ unknown = set(target) - allowed
130
143
  if unknown:
131
- raise WorkflowError(f"{where}: unknown target keys {sorted(unknown)}; use {', '.join(LOCATOR_KEYS)}")
144
+ raise WorkflowError(f"{where}: unknown target keys {sorted(unknown)}; use {', '.join(sorted(allowed, key=lambda k: (k not in LOCATOR_KEYS, k)))}")
145
+ out_extra: Dict[str, Any] = {}
146
+ if "within" in target:
147
+ # The ancestor a relative locator starts from: plain properties only, never a path or a query.
148
+ anchor = target["within"]
149
+ if not isinstance(anchor, dict) or not anchor or set(anchor) - set(_ANCHOR_KEYS) or not all(isinstance(v, str) and v.strip() and not any(ord(c) < 32 or ord(c) == 127 for c in v) for v in anchor.values()):
150
+ raise WorkflowError(f"{where}: target.within must be {{automation_id}} or {{name}}: the ancestor it is found inside")
151
+ out_extra["within"] = dict(anchor)
152
+ if "web" in target:
153
+ # An element of a web page inside the app, by plain properties only (forgeqe_mobile/webview.py builds the query).
154
+ from forgeqe_mobile.webview import WEB_KEYS, clean_web
155
+
156
+ web = clean_web(target["web"])
157
+ if web is None:
158
+ raise WorkflowError(f"{where}: target.web must be plain properties of a web element ({', '.join(WEB_KEYS)}), one line each")
159
+ if set(target) - {"web", "fallbacks"}:
160
+ raise WorkflowError(f"{where}: a web element's target has only web (and fallbacks)")
161
+ out_extra["web"] = web
162
+ if "fallbacks" in target:
163
+ rest = target["fallbacks"]
164
+ if not isinstance(rest, list) or not rest or len(rest) > MAX_FALLBACKS:
165
+ raise WorkflowError(f"{where}: target.fallbacks must be a list of 1 to {MAX_FALLBACKS} targets")
166
+ out_extra["fallbacks"] = [_check_target(f"{where} (fallback {i})", f, mobile=True, fallback=True) for i, f in enumerate(rest, 1)]
167
+ target = {k: v for k, v in target.items() if k not in MOBILE_LOCATOR_KEYS}
168
+ if "web" in out_extra:
169
+ return {**target, **out_extra}
132
170
  if not str(target.get("automation_id") or "").strip() and not str(target.get("name") or "").strip():
133
171
  raise WorkflowError(f"{where}: target needs an automation_id or a name")
134
172
  for k in ("automation_id", "name", "control_type", "class_name"):
@@ -140,7 +178,7 @@ def _check_target(where: str, target: Any) -> Dict[str, Any]:
140
178
  path = target["path"]
141
179
  if not isinstance(path, list) or not all(isinstance(p, dict) and set(p) <= {"control_type", "name"} for p in path):
142
180
  raise WorkflowError(f"{where}: target.path must be a list of {{control_type, name}}")
143
- return dict(target)
181
+ return {**dict(target), **out_extra}
144
182
 
145
183
 
146
184
  def _seconds(where: str, value: Any, most: float) -> float:
@@ -214,14 +252,27 @@ def validate(doc: Any) -> Dict[str, Any]:
214
252
  raise WorkflowError(f"{where} ({op}) needs {', '.join(sorted(missing))}")
215
253
  clean: Dict[str, Any] = {"op": op}
216
254
  if "target" in step:
217
- clean["target"] = _check_target(where, step["target"])
255
+ clean["target"] = _check_target(where, step["target"], mobile)
218
256
  if "to" in step:
219
- clean["to"] = _check_target(f"{where} (to)", step["to"])
257
+ clean["to"] = _check_target(f"{where} (to)", step["to"], mobile)
220
258
  for k in ("text", "value"):
221
259
  if k in step:
222
260
  if not isinstance(step[k], (str, int, float)) or isinstance(step[k], bool):
223
261
  raise WorkflowError(f"{where}: {k} must be text")
224
262
  clean[k] = str(step[k])
263
+ if "at" in step:
264
+ at = step["at"]
265
+ if not (isinstance(at, list) and len(at) == 2 and all(isinstance(n, int) and not isinstance(n, bool) and 0 <= n <= 1000 for n in at)):
266
+ raise WorkflowError(f"{where}: at is [x, y] inside the control, each a whole number from 0 to 1000 (thousandths of its size)")
267
+ clean["at"] = list(at)
268
+ if op == "open_link":
269
+ if not isinstance(step["login"], str) or not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]{0,63}", step["login"]):
270
+ raise WorkflowError(f"{where}: login is the name of a saved login (letters, digits and _)")
271
+ clean["login"] = step["login"]
272
+ if "checked" in step:
273
+ if not isinstance(step["checked"], bool):
274
+ raise WorkflowError(f"{where}: checked must be true or false")
275
+ clean["checked"] = step["checked"]
225
276
  if op == "keys" and mobile:
226
277
  key = str(step["keys"]).strip().lower()
227
278
  if key not in MOBILE_KEYS:
@@ -271,7 +322,7 @@ def validate(doc: Any) -> Dict[str, Any]:
271
322
  dismiss = doc["dismiss"]
272
323
  if not isinstance(dismiss, list) or len(dismiss) > MAX_DISMISS:
273
324
  raise WorkflowError(f"dismiss must be a list of at most {MAX_DISMISS} targets (the buttons that close a dialog in the way)")
274
- result["dismiss"] = [_check_target(f"dismiss {i}", t) for i, t in enumerate(dismiss, 1)]
325
+ result["dismiss"] = [_check_target(f"dismiss {i}", t, mobile) for i, t in enumerate(dismiss, 1)]
275
326
  return result
276
327
 
277
328
 
@@ -335,6 +386,17 @@ def fill_targets(workflow: Mapping[str, Any], variables: Mapping[str, Any]) -> D
335
386
  out[k] = fill(out[k], variables, no_secret)
336
387
  if isinstance(out.get("path"), list):
337
388
  out["path"] = [{**p, **({"name": fill(p["name"], variables, no_secret)} if isinstance(p.get("name"), str) else {})} for p in out["path"]]
389
+ if isinstance(out.get("web"), Mapping):
390
+ from forgeqe_mobile.webview import clean_web
391
+
392
+ filled = {k: fill(v, variables, no_secret) if isinstance(v, str) and k not in ("attr", "tag") else v for k, v in out["web"].items()}
393
+ if clean_web(filled) is None:
394
+ raise WorkflowError("a web element's locator holds a variable whose value is not one plain line of text")
395
+ out["web"] = filled
396
+ if isinstance(out.get("within"), Mapping):
397
+ out["within"] = {k: fill(v, variables, no_secret) if isinstance(v, str) else v for k, v in out["within"].items()}
398
+ if isinstance(out.get("fallbacks"), list):
399
+ out["fallbacks"] = [one(f) for f in out["fallbacks"] if isinstance(f, Mapping)]
338
400
  return out
339
401
 
340
402
  wf = dict(workflow)
@@ -381,7 +381,7 @@ def _pattern_words(pattern: Any, is_regex: Any = None) -> str:
381
381
  s = _REGEX_GAP.sub(" … ", s)
382
382
  s = _REGEX_SPACE.sub(" ", s)
383
383
  s = re.sub(r"\\([^a-zA-Z0-9])", r"\1", s)
384
- s = re.sub(r"^\^|(?<!\\)\$$", "", s.strip())
384
+ s = re.sub(r"(?:^\^)|(?:(?<!\\)\$$)", "", s.strip())
385
385
  s = re.sub(r"\s*…\s*", " … ", s)
386
386
  return re.sub(r"\s+", " ", s).strip() or str(pattern or "")
387
387
 
@@ -7,6 +7,7 @@ import atexit
7
7
  import contextlib
8
8
  import json
9
9
  import logging
10
+ import math
10
11
  import os
11
12
  import sys
12
13
  import time
@@ -178,7 +179,7 @@ def devtools_wait_seconds() -> float:
178
179
  value = float((os.getenv("FORGEQE_ENGINE_BROWSER_START_SECONDS") or "").strip())
179
180
  except ValueError:
180
181
  return DEVTOOLS_WAIT_SECONDS
181
- return min(600.0, max(15.0, value)) if value == value else DEVTOOLS_WAIT_SECONDS
182
+ return DEVTOOLS_WAIT_SECONDS if math.isnan(value) else min(600.0, max(15.0, value))
182
183
 
183
184
 
184
185
  start_logger = logging.getLogger("forgeqe_engine.browser_start")
@@ -137,7 +137,7 @@ L10N_MEASURE = r"""((full) => {
137
137
  const vw = window.innerWidth;
138
138
  const out = {lang: html.getAttribute('lang') || '', dir: getComputedStyle(html).direction, pageScroll: html.scrollWidth > vw + 2,
139
139
  truncated: [], overflow: [], keys: [], english: [], checked: 0};
140
- const key = /^[a-z][a-z0-9_-]*(\.[a-z0-9_-]+){2,}$|\{\{\s*[\w.$-]+\s*\}\}|\[missing ["'][^\]]+["'] translation\]|missing[ _]translation|^__[\w.]+__$|\$t\(|%\(?[sd]\)?s?$/i;
140
+ const key = /^[a-z][a-z0-9_-]*(\.[a-z0-9_-]+){2,}$|\{\{\s*[\w.$-]+\s*\}\}|\[missing ["'][^\]]+["'] translation\]|missing[ _]translation|^__[\w.]+__$|\$t\(|%%\(?[sd]\)?s?$/i;
141
141
  const common = /\b(the|and|your|you|please|click|submit|cancel|save|delete|search|sign in|log in|password|continue|back|next|error|required|welcome)\b/gi;
142
142
  const english = full && out.lang && !/^en\b/i.test(out.lang);
143
143
  const seen = new Set();
@@ -165,7 +165,8 @@ def playwright_role_ok(tag: str, attrs: Dict[str, str], role: str) -> bool:
165
165
 
166
166
 
167
167
  def _sha(text: str, n: int) -> str:
168
- return hashlib.sha1(text.encode("utf-8")).hexdigest()[:n]
168
+ # A short id for a memory entry, not a security check; SHA-1 keeps existing ids the same.
169
+ return hashlib.sha1(text.encode("utf-8"), usedforsecurity=False).hexdigest()[:n]
169
170
 
170
171
 
171
172
  # Classes a page sets for a state, not for what an element is: the item under the pointer or chosen (active, selected,
@@ -13,7 +13,7 @@ import re
13
13
  from typing import Any
14
14
 
15
15
  _LIBRARY = "browser_use"
16
- _PROJECT_LINK = re.compile(r"\s*\(?\bhttps?://(?:[\w.-]*\.)?(?:github\.com/browser-use|browser-use\.com)\S*\)?", re.IGNORECASE)
16
+ _PROJECT_LINK = re.compile(r"(?<!\s)\s*\(?\bhttps?://(?:[\w.-]*\.)?(?:github\.com/browser-use|browser-use\.com)\S*\)?", re.IGNORECASE)
17
17
  _NAME = re.compile(r"\bbrowser[-_ ]?use\b", re.IGNORECASE)
18
18
  # A session's contents as the library prints them: storage_state=..., or a cookie's value, to the end of the line.
19
19
  _SESSION = re.compile(r"(\bstorage_state\s*[=:]\s*)(?=[{\[(\'\"]).*", re.IGNORECASE)
@@ -6,6 +6,10 @@ What arrives is untrusted: a message's text is never logged, shown to the model
6
6
  it, by the login's pattern (a capture group), and only when it looks like a code (letters, digits and -, 3 to 12).
7
7
  Every connection checks TLS (the system's trust, never turned off); a test environment's endpoint is https, or http on
8
8
  this computer only. Credentials come from environment variables named in the login, never from the request.
9
+
10
+ A magic link (a sign-in or verification link sent by email) is read from the same mailbox (``fetch_link``): only an
11
+ https link to one of the login's own sites (``link_in``), never with a user name in it; it is opened, never logged,
12
+ shown or kept.
9
13
  """
10
14
  from __future__ import annotations
11
15
 
@@ -13,6 +17,7 @@ import base64
13
17
  import email
14
18
  import email.policy
15
19
  import email.utils
20
+ import html
16
21
  import imaplib
17
22
  import json
18
23
  import os
@@ -144,9 +149,16 @@ def _text_of(msg: Any) -> str:
144
149
  return " ".join(parts)[:MAX_MESSAGE]
145
150
 
146
151
 
147
- def read_email(src: CodeSource, since: float, env: Mapping[str, str], imap: Callable[..., Any] = imaplib.IMAP4_SSL) -> Optional[str]:
148
- """The code of the newest message since `since` (from `sender`, to `to` when given), read-only."""
149
- box = imap(src.host, 993, ssl_context=ssl.create_default_context())
152
+ def tls_context() -> ssl.SSLContext:
153
+ """Verified TLS (certificate and host name), 1.2 or newer: Python 3.9's default context still offers 1.0 and 1.1."""
154
+ ctx = ssl.create_default_context()
155
+ ctx.minimum_version = ssl.TLSVersion.TLSv1_2
156
+ return ctx
157
+
158
+
159
+ def _messages(src: CodeSource, since: float, env: Mapping[str, str], imap: Callable[..., Any]) -> Any:
160
+ """The mailbox's messages since `since` (from `sender`, to `to` when given), newest first, read-only."""
161
+ box = imap(src.host, 993, ssl_context=tls_context())
150
162
  try:
151
163
  box.login(_env(src.user_env, env), _env(src.secret_env, env))
152
164
  box.select(_quote(src.folder), readonly=True)
@@ -158,7 +170,7 @@ def read_email(src: CodeSource, since: float, env: Mapping[str, str], imap: Call
158
170
  query += ["TO", _quote(src.to)]
159
171
  status, data = box.search(None, *query)
160
172
  if status != "OK" or not data or not data[0]:
161
- return None
173
+ return
162
174
  for num in reversed(data[0].split()[-MAX_MESSAGES:]):
163
175
  status, parts = box.fetch(num, f"(BODY.PEEK[]<0.{MAX_MESSAGE}>)")
164
176
  raw = next((p[1] for p in parts or [] if isinstance(p, tuple) and len(p) > 1), None)
@@ -169,12 +181,8 @@ def read_email(src: CodeSource, since: float, env: Mapping[str, str], imap: Call
169
181
  sent = email.utils.parsedate_to_datetime(str(msg.get("date"))).timestamp()
170
182
  except Exception:
171
183
  continue
172
- if sent < since - SKEW:
173
- continue
174
- code = code_in(_text_of(msg), src.pattern)
175
- if code:
176
- return code
177
- return None
184
+ if sent >= since - SKEW:
185
+ yield msg
178
186
  finally:
179
187
  try:
180
188
  box.logout()
@@ -182,6 +190,15 @@ def read_email(src: CodeSource, since: float, env: Mapping[str, str], imap: Call
182
190
  pass
183
191
 
184
192
 
193
+ def read_email(src: CodeSource, since: float, env: Mapping[str, str], imap: Callable[..., Any] = imaplib.IMAP4_SSL) -> Optional[str]:
194
+ """The code of the newest message since `since` (from `sender`, to `to` when given), read-only."""
195
+ for msg in _messages(src, since, env, imap):
196
+ code = code_in(_text_of(msg), src.pattern)
197
+ if code:
198
+ return code
199
+ return None
200
+
201
+
185
202
  def _quote(s: str) -> str:
186
203
  return '"' + s.replace("\\", "\\\\").replace('"', '\\"') + '"'
187
204
 
@@ -201,8 +218,7 @@ class _NoRedirect(urllib.request.HTTPRedirectHandler):
201
218
 
202
219
 
203
220
  def _opener() -> Callable[..., Any]:
204
- ctx = ssl.create_default_context()
205
- return urllib.request.build_opener(_NoRedirect(), urllib.request.HTTPSHandler(context=ctx)).open
221
+ return urllib.request.build_opener(_NoRedirect(), urllib.request.HTTPSHandler(context=tls_context())).open
206
222
 
207
223
 
208
224
  def read_sms(src: CodeSource, since: float, env: Mapping[str, str], opener: Optional[Callable[..., Any]] = None) -> Optional[str]:
@@ -301,3 +317,102 @@ def fetch_code(
301
317
  where = {"email": f"the mailbox on {src.host}", "sms": f"the text messages to {src.to}", "http": "the test environment's address"}[src.kind]
302
318
  raise CodeError(f"No new code arrived in {where} within {src.wait} s" + (f" (the last try failed: {last})" if last else ""))
303
319
  sleep(3)
320
+
321
+
322
+ # A magic link: the longest kept, and how a link is found in a message's plain text and its HTML.
323
+ MAX_LINK = 2048
324
+ _PLAIN_LINK = re.compile(r"https://[^\s<>\"'()]+", re.I)
325
+ _HREF = re.compile(r"""href\s*=\s*(?:"([^"]*)"|'([^']*)')""", re.I)
326
+
327
+
328
+ def _site_of(host: str, hosts: List[str]) -> bool:
329
+ """One of the login's sites: a host exactly, or a subdomain only of a ``*.`` pattern (shop.example's, never .com's)."""
330
+ for h in hosts:
331
+ if h.startswith("*."):
332
+ base = h[2:]
333
+ if base.count(".") >= 1 and (host == base or host.endswith("." + base)):
334
+ return True
335
+ elif h and host == h:
336
+ return True
337
+ return False
338
+
339
+
340
+ def link_in(msg: Any, hosts: List[str]) -> Optional[str]:
341
+ """
342
+ The first https link of a message (its HTML links, then its plain text) to one of ``hosts`` or their subdomains,
343
+ with no user name, at most MAX_LINK long and on one line; None when it has none. The message is data.
344
+ """
345
+ hosts = [h.lower().rstrip(".") for h in hosts if h]
346
+ found: List[str] = []
347
+ for part in msg.walk() if msg.is_multipart() else [msg]:
348
+ ctype = part.get_content_type()
349
+ if ctype not in ("text/plain", "text/html") or part.get_filename():
350
+ continue
351
+ try:
352
+ body = str(part.get_content())[:MAX_MESSAGE]
353
+ except Exception:
354
+ continue
355
+ if ctype == "text/html":
356
+ # In HTML only its links: a scan of its text could cut a link short where the href was refused.
357
+ found += [html.unescape(a or b) for a, b in _HREF.findall(body)]
358
+ else:
359
+ found += _PLAIN_LINK.findall(body)
360
+ for raw in found:
361
+ link = raw.strip().rstrip(".,;")
362
+ if not link or len(link) > MAX_LINK or re.search(r"[\x00-\x20\x7f]", link):
363
+ continue
364
+ try:
365
+ u = urllib.parse.urlsplit(link)
366
+ except ValueError:
367
+ continue
368
+ if u.scheme.lower() != "https" or not u.hostname or u.username or u.password:
369
+ continue
370
+ if _site_of(u.hostname.lower(), hosts):
371
+ return link
372
+ return None
373
+
374
+
375
+ def read_email_link(src: CodeSource, since: float, env: Mapping[str, str], hosts: List[str], imap: Callable[..., Any] = imaplib.IMAP4_SSL) -> Optional[str]:
376
+ """The magic link of the newest message since `since` (from `sender`, to `to` when given), read-only."""
377
+ for msg in _messages(src, since, env, imap):
378
+ link = link_in(msg, hosts)
379
+ if link:
380
+ return link
381
+ return None
382
+
383
+
384
+ def fetch_link(
385
+ src: CodeSource,
386
+ hosts: List[str],
387
+ since: float,
388
+ env: Optional[Mapping[str, str]] = None,
389
+ *,
390
+ used: Optional[List[str]] = None,
391
+ sleep: Callable[[float], None] = time.sleep,
392
+ clock: Callable[[], float] = time.time,
393
+ reader: Optional[Callable[..., Optional[str]]] = None,
394
+ ) -> str:
395
+ """
396
+ The magic link sent since `since` to the login's mailbox, waiting for it up to the login's wait; a link in `used`
397
+ (opened already in this run) is skipped. Raises CodeError when none came; its message never holds a link.
398
+ """
399
+ if src.kind != "email":
400
+ raise CodeError("a magic link is read from the login's mailbox: its code: settings must be email")
401
+ if not hosts:
402
+ raise CodeError("the login names no sites, so no link in a message could be trusted")
403
+ env = os.environ if env is None else env
404
+ deadline = clock() + src.wait
405
+ last: Optional[str] = None
406
+ while True:
407
+ try:
408
+ link = (reader or read_email_link)(src, since, env, hosts)
409
+ except CodeError:
410
+ raise
411
+ except Exception as ex:
412
+ last = type(ex).__name__
413
+ link = None
414
+ if link and link not in (used or []):
415
+ return link
416
+ if clock() >= deadline:
417
+ raise CodeError(f"No new link to the login's sites arrived in the mailbox on {src.host} within {src.wait} s" + (f" (the last try failed: {last})" if last else ""))
418
+ sleep(3)
@@ -46,7 +46,7 @@ async function start(line) {
46
46
  const file = path.join(String(req.userDataDir), "DevToolsActivePort")
47
47
  const until = Date.now() + 30000
48
48
  while (!existsSync(file) && Date.now() < until) await new Promise((r) => setTimeout(r, 100))
49
- const port = existsSync(file) ? Number(readFileSync(file, "utf8").split(/\r?\n/)[0]) : NaN
49
+ const port = existsSync(file) ? Number(readFileSync(file, "utf8").split(/\r?\n/)[0]) : Number.NaN
50
50
  if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error("the browser started but wrote no DevTools port")
51
51
  say({ port })
52
52
  }