@capagents/forgeqe 2.10.1 → 2.10.3
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.
- package/dist/forgeqe.js +1703 -1669
- package/dist/web/assets/{Agent-DQeWzsWG.js → Agent-DyyAZPKr.js} +1 -1
- package/dist/web/assets/{ApiTests-DrQBxtra.js → ApiTests-p_cbulD4.js} +1 -1
- package/dist/web/assets/{Browse-CXqsKgMN.js → Browse-DOAlK-ox.js} +2 -2
- package/dist/web/assets/{Chat-rChaK9vu.js → Chat-BCV5OsEz.js} +1 -1
- package/dist/web/assets/{CommandPalette-LNTJ2Pie.js → CommandPalette-o9PuLas2.js} +1 -1
- package/dist/web/assets/{Compare-CP24uSyS.js → Compare-Bf1LhXmj.js} +1 -1
- package/dist/web/assets/{Cost-Cz6F4MAu.js → Cost-r7D19VSG.js} +1 -1
- package/dist/web/assets/{Data-RSpfLC9W.js → Data-CRttp4iM.js} +1 -1
- package/dist/web/assets/{Desktop-C0VftUUl.js → Desktop-DcaKyfKA.js} +1 -1
- package/dist/web/assets/{DesktopReview-BTYnwZKB.js → DesktopReview-BjplTYfH.js} +1 -1
- package/dist/web/assets/{Evidence-DxfTgGLn.js → Evidence-BAAKcK0h.js} +1 -1
- package/dist/web/assets/{Explore-BKAnJ0AP.js → Explore-D_RZhVAc.js} +1 -1
- package/dist/web/assets/{Features-YYcKT5mB.js → Features-B6azjGtN.js} +1 -1
- package/dist/web/assets/{Flags-B23vWmDR.js → Flags-BQR4dRaK.js} +1 -1
- package/dist/web/assets/{Flaky-kuhde8PW.js → Flaky-Ci1bvglt.js} +1 -1
- package/dist/web/assets/{Impact-DetuURYY.js → Impact-CPB7NjQF.js} +1 -1
- package/dist/web/assets/{Jobs-BTiCqtr9.js → Jobs-CR8SxpWA.js} +1 -1
- package/dist/web/assets/{KindPage-BbL7COME.js → KindPage-Bl7q-2b8.js} +1 -1
- package/dist/web/assets/{Migration-CPv7gDC-.js → Migration-BecNlszU.js} +1 -1
- package/dist/web/assets/{Product-DcrBguCI.js → Product-AMUC5arL.js} +1 -1
- package/dist/web/assets/{Production-N11W9Ckr.js → Production-CZ-EG3t2.js} +1 -1
- package/dist/web/assets/{Quality-DzXW1cvp.js → Quality-k2U9v2Dn.js} +1 -1
- package/dist/web/assets/{Readiness-BbHO8wa2.js → Readiness-D3_S6lDT.js} +1 -1
- package/dist/web/assets/Record-Ba6XRn7c.js +2 -0
- package/dist/web/assets/{Regression-BOSQ2Pxp.js → Regression-jpkQRkt_.js} +1 -1
- package/dist/web/assets/{Reports-BA1VdwoC.js → Reports-BHKtb9Oi.js} +1 -1
- package/dist/web/assets/{Response-0i0ww7OC.js → Response-CVNWGdun.js} +1 -1
- package/dist/web/assets/{RunDiff-D-4tB7Is.js → RunDiff-dbcFibiJ.js} +1 -1
- package/dist/web/assets/{Runs-DW7dZh2j.js → Runs-ij-80l3A.js} +1 -1
- package/dist/web/assets/{TestCases-BfPkdwR6.js → TestCases-BW8laQ_8.js} +1 -1
- package/dist/web/assets/{TestData-DRoJc7Me.js → TestData-0f1XzLdc.js} +1 -1
- package/dist/web/assets/{TestDebt-ly8BsLSJ.js → TestDebt-C-2y3RTV.js} +1 -1
- package/dist/web/assets/{Tosca-CzrCAhEs.js → Tosca-DnfpS6Zf.js} +1 -1
- package/dist/web/assets/{WhatsNew-Cd8D1O1X.js → WhatsNew-C1HUalPw.js} +1 -1
- package/dist/web/assets/{dataParts-DzHf4K4-.js → dataParts-DWD2uUxL.js} +1 -1
- package/dist/web/assets/{fold-CyU-Mjqe.js → fold-o_l3hXTU.js} +1 -1
- package/dist/web/assets/frame-CdUL-UeQ.js +4 -0
- package/dist/web/assets/{index-Bv3atkwB.js → index-BmJOj6t1.js} +5 -5
- package/dist/web/assets/index-DP3riJZe.css +2 -0
- package/dist/web/assets/{logos-cftOc5MX.js → logos-CMkTgBD8.js} +1 -1
- package/dist/web/assets/{palette-D_SCreF2.js → palette-D-wSuihi.js} +1 -1
- package/dist/web/assets/{qualityParts-50E_QRTX.js → qualityParts-DS83Q0nG.js} +1 -1
- package/dist/web/assets/{rows-JZ5MvdCQ.js → rows-DYYObxPx.js} +1 -1
- package/dist/web/assets/{thread-CrExMoMY.js → thread-Cnjdo5ve.js} +1 -1
- package/dist/web/assets/{usePageChat-DpnA7edC.js → usePageChat-DWmmQrbC.js} +1 -1
- package/dist/web/index.html +3 -3
- package/package.json +1 -1
- package/py/forgeqe_engine/capture.py +14 -1
- package/py/forgeqe_engine/memory.py +18 -4
- package/py/forgeqe_engine/recordsession.py +211 -15
- package/py/forgeqe_engine/varying.py +120 -0
- package/py/forgeqe_engine/webrecord.py +115 -32
- package/py/forgeqe_engine/webrecord_page.py +199 -29
- package/py/forgeqe_engine/workflow_yaml.py +18 -1
- package/dist/web/assets/Record-P7TKcE5d.js +0 -2
- package/dist/web/assets/frame-DUo0M0VF.js +0 -4
- package/dist/web/assets/index-DwUumNPZ.css +0 -2
|
@@ -33,7 +33,8 @@ from typing import Any, Awaitable, Callable, Dict, List, Optional, Tuple
|
|
|
33
33
|
from .capture import capture_element, locate_check
|
|
34
34
|
from .memory import BASE, KEPT_ATTRS, candidate_locators, confidence, looks_generated, state_class, within_locator
|
|
35
35
|
from . import dynamic
|
|
36
|
-
from .
|
|
36
|
+
from .varying import SeenElements, mark as mark_varying
|
|
37
|
+
from .webrecord import CAPTCHA_FRAMES, MAX_SCROLL_END, MAX_UPLOAD_FILES, Target, WebRecorder, auto_name, captcha_of, describe, download_name, keep_upload, secret_env_for, upload_path
|
|
37
38
|
from .webrecord_page import recorder_js
|
|
38
39
|
|
|
39
40
|
|
|
@@ -145,6 +146,10 @@ class RecordSession:
|
|
|
145
146
|
self.shadow_key = secrets.token_hex(12)
|
|
146
147
|
self.binding = f"__fqe_{tag}"
|
|
147
148
|
self.pages: Dict[str, Dict[str, Any]] = {}
|
|
149
|
+
# What each element of each page looked like the load before, so a value the page makes fresh is seen for what
|
|
150
|
+
# it is (varying.py), not guessed at from its shape. Counted up on every load of a tab's own page.
|
|
151
|
+
self.seen = SeenElements()
|
|
152
|
+
self._load = 0
|
|
148
153
|
# Cross-origin frames: each one Chrome runs as a target of its own (an out-of-process iframe), by its session,
|
|
149
154
|
# with the session it was found in (its parent) and the tab it belongs to.
|
|
150
155
|
self.frames: Dict[str, Dict[str, Any]] = {}
|
|
@@ -180,6 +185,12 @@ class RecordSession:
|
|
|
180
185
|
# Sites that asked for the browser's own sign-in (basic auth), by origin: the saved login that signs in there.
|
|
181
186
|
self.logins: List[Any] = []
|
|
182
187
|
self.http_auth: Dict[str, Dict[str, str]] = {}
|
|
188
|
+
# New tabs being attached by the recorder itself (_created): each once.
|
|
189
|
+
self._attaching: set = set()
|
|
190
|
+
# The saved logins' password fingerprints for this recording, for the page script (password_prints).
|
|
191
|
+
self.pw_prints: Dict[str, Any] = {}
|
|
192
|
+
# Browser permissions each site had while recording (origin -> names of PERMISSIONS), for the replay.
|
|
193
|
+
self.permissions: Dict[str, List[str]] = {}
|
|
183
194
|
# The browser was closed once the recording stopped (release_browser), and its facts read just before.
|
|
184
195
|
self.released = False
|
|
185
196
|
self.profile: Optional[Dict[str, Any]] = None
|
|
@@ -230,6 +241,9 @@ class RecordSession:
|
|
|
230
241
|
|
|
231
242
|
def _queue(self, kind: str) -> Callable[[Any, Optional[str]], None]:
|
|
232
243
|
def handler(event: Any, session_id: Optional[str] = None) -> None:
|
|
244
|
+
# When it happened: a click handled late (its page navigating) is still before the back that followed it.
|
|
245
|
+
if isinstance(event, dict):
|
|
246
|
+
event.setdefault("_at", time.monotonic())
|
|
233
247
|
self.queue.put_nowait((kind, event, session_id))
|
|
234
248
|
|
|
235
249
|
return handler
|
|
@@ -247,6 +261,7 @@ class RecordSession:
|
|
|
247
261
|
self.logins = logins
|
|
248
262
|
login_values = {env: os.environ.get(env, "") for env in text_envs() if os.environ.get(env)}
|
|
249
263
|
login_passwords = {",".join(l.hosts()): l.password_env for l in logins if l.password_env}
|
|
264
|
+
self.pw_prints = password_prints(logins)
|
|
250
265
|
self.rec = WebRecorder(self.start_url, self.name, login_values=login_values, login_passwords=login_passwords, clock=time.monotonic, case_steps=self.case_steps)
|
|
251
266
|
|
|
252
267
|
brand.install()
|
|
@@ -262,12 +277,14 @@ class RecordSession:
|
|
|
262
277
|
await self.client.start()
|
|
263
278
|
reg = self.client.register
|
|
264
279
|
reg.Target.attachedToTarget(self._queue("attached"))
|
|
280
|
+
reg.Target.targetCreated(self._queue("created"))
|
|
265
281
|
reg.Target.detachedFromTarget(self._queue("detached"))
|
|
266
282
|
reg.Runtime.bindingCalled(self._queue("binding"))
|
|
267
283
|
reg.Runtime.executionContextCreated(self._queue("context"))
|
|
268
284
|
reg.Page.frameNavigated(self._queue("navigated"))
|
|
269
285
|
reg.Page.navigatedWithinDocument(self._queue("navigated_same"))
|
|
270
286
|
reg.Page.frameRequestedNavigation(self._queue("requested"))
|
|
287
|
+
reg.Page.frameStartedLoading(self._queue("started_loading"))
|
|
271
288
|
reg.Page.javascriptDialogOpening(self._dialog("dialog_open"))
|
|
272
289
|
reg.Page.javascriptDialogClosed(self._dialog("dialog_closed"))
|
|
273
290
|
reg.Browser.downloadWillBegin(self._queue("download_begin"))
|
|
@@ -275,6 +292,9 @@ class RecordSession:
|
|
|
275
292
|
reg.Network.requestWillBeSent(self._queue("request"))
|
|
276
293
|
reg.Network.responseReceived(self._queue("response"))
|
|
277
294
|
await self.send("Target.setAutoAttach", {"autoAttach": True, "waitForDebuggerOnStart": True, "flatten": True})
|
|
295
|
+
# A window a page opens (a link with target=_blank, window.open) is not attached by the browser on its own:
|
|
296
|
+
# told of each new tab, the recorder attaches to it, and the steps go on there.
|
|
297
|
+
await self.send("Target.setDiscoverTargets", {"discover": True})
|
|
278
298
|
# A file the page downloads lands in the recording's downloads/ folder, and this connection is told of it.
|
|
279
299
|
self.downloads.mkdir(parents=True, exist_ok=True)
|
|
280
300
|
try:
|
|
@@ -411,6 +431,8 @@ class RecordSession:
|
|
|
411
431
|
try:
|
|
412
432
|
if kind == "attached":
|
|
413
433
|
await self._attached(event, sid)
|
|
434
|
+
elif kind == "created":
|
|
435
|
+
await self._created(event)
|
|
414
436
|
elif kind == "context":
|
|
415
437
|
c = event.get("context") or {}
|
|
416
438
|
aux = c.get("auxData") or {}
|
|
@@ -421,10 +443,22 @@ class RecordSession:
|
|
|
421
443
|
elif kind == "detached":
|
|
422
444
|
self._detached(event)
|
|
423
445
|
elif kind == "binding":
|
|
424
|
-
|
|
446
|
+
if self.rec is not None:
|
|
447
|
+
at = event.get("_at") if isinstance(event, dict) else None
|
|
448
|
+
self.rec.event_at = at if isinstance(at, float) else None
|
|
449
|
+
try:
|
|
450
|
+
await self._binding(event, sid)
|
|
451
|
+
finally:
|
|
452
|
+
if self.rec is not None:
|
|
453
|
+
self.rec.event_at = None
|
|
425
454
|
elif kind == "requested":
|
|
426
455
|
if sid in self.pages and event.get("frameId") == self.pages[sid].get("frame"):
|
|
427
456
|
self.pages[sid]["renderer"] = True
|
|
457
|
+
elif kind == "started_loading":
|
|
458
|
+
# When the tab's page began to load: a back the page's own script did starts at once after the click.
|
|
459
|
+
if sid in self.pages and self.rec is not None and event.get("frameId") == self.pages[sid].get("frame"):
|
|
460
|
+
at = event.get("_at")
|
|
461
|
+
self.pages[sid]["started"] = at if isinstance(at, float) else self.rec.clock()
|
|
428
462
|
elif kind in ("navigated", "navigated_same"):
|
|
429
463
|
await self._navigated(event, sid, same=kind == "navigated_same")
|
|
430
464
|
elif kind == "request":
|
|
@@ -474,6 +508,19 @@ class RecordSession:
|
|
|
474
508
|
if msg:
|
|
475
509
|
self._changed(msg)
|
|
476
510
|
|
|
511
|
+
def _permission(self, url: str, name: Any) -> None:
|
|
512
|
+
"""A permission a site has in the browser: its name only, of PERMISSIONS, for that site's origin."""
|
|
513
|
+
origin = http_origin(url)
|
|
514
|
+
if not origin or name not in PERMISSIONS:
|
|
515
|
+
return
|
|
516
|
+
names = self.permissions.get(origin)
|
|
517
|
+
if names is None:
|
|
518
|
+
if len(self.permissions) >= 10:
|
|
519
|
+
return
|
|
520
|
+
names = self.permissions[origin] = []
|
|
521
|
+
if name not in names:
|
|
522
|
+
names.append(str(name))
|
|
523
|
+
|
|
477
524
|
def _http_auth(self, event: Dict[str, Any]) -> None:
|
|
478
525
|
"""
|
|
479
526
|
A page that answered 401 asking for the browser's own sign-in (basic or digest): the person types it in the
|
|
@@ -532,6 +579,19 @@ class RecordSession:
|
|
|
532
579
|
|
|
533
580
|
# -- pages ----------------------------------------------------------------------------------------------------
|
|
534
581
|
|
|
582
|
+
async def _created(self, event: Dict[str, Any]) -> None:
|
|
583
|
+
"""A new tab a page opened: attached (once), so a window a page opened is recorded as the first one is."""
|
|
584
|
+
info = event.get("targetInfo") or {}
|
|
585
|
+
tid = info.get("targetId")
|
|
586
|
+
# Only a tab a recorded page opened (it names its opener): the browser's own tabs are left as they were.
|
|
587
|
+
if info.get("type") != "page" or not tid or not info.get("openerId") or any(p.get("target") == tid for p in self.pages.values()) or tid in self._attaching:
|
|
588
|
+
return
|
|
589
|
+
self._attaching.add(tid)
|
|
590
|
+
try:
|
|
591
|
+
await self.send("Target.attachToTarget", {"targetId": tid, "flatten": True})
|
|
592
|
+
except Exception as ex:
|
|
593
|
+
logger.debug("record: a new tab was not attached: %s", ex)
|
|
594
|
+
|
|
535
595
|
async def _attached(self, event: Dict[str, Any], parent: Optional[str] = None) -> None:
|
|
536
596
|
sid = event.get("sessionId")
|
|
537
597
|
info = event.get("targetInfo") or {}
|
|
@@ -543,24 +603,36 @@ class RecordSession:
|
|
|
543
603
|
return
|
|
544
604
|
if info.get("type") != "page":
|
|
545
605
|
return
|
|
606
|
+
# A tab already recorded (attached by the browser and by _created both): one session records it.
|
|
607
|
+
if info.get("targetId") and any(p.get("target") == info.get("targetId") for p in self.pages.values()):
|
|
608
|
+
return
|
|
546
609
|
await self.send("Page.enable", None, sid)
|
|
547
610
|
# Binding calls are Runtime events: the domain must be on for them to arrive.
|
|
548
611
|
await self.send("Runtime.enable", None, sid)
|
|
549
612
|
await self.send("Runtime.addBinding", {"name": self.binding, "executionContextName": self.world}, sid)
|
|
550
613
|
# The page's own calls to its server, kept by step (only method, path and status: never a query or a body).
|
|
551
614
|
await self.send("Network.enable", None, sid)
|
|
552
|
-
js = recorder_js(self.binding, KEPT_ATTRS, leader=self.leader, badge=self.payload.get("panel") == "badge")
|
|
615
|
+
js = recorder_js(self.binding, KEPT_ATTRS, leader=self.leader, badge=self.payload.get("panel") == "badge", pw=self.pw_prints or None)
|
|
553
616
|
await self.send("Page.addScriptToEvaluateOnNewDocument", {"source": open_shadow_js(self.shadow_key)}, sid)
|
|
554
617
|
await self.send("Page.addScriptToEvaluateOnNewDocument", {"source": js, "worldName": self.world}, sid)
|
|
555
618
|
# Its cross-origin frames are targets of their own: attached as they start, held until the script is in.
|
|
556
619
|
await self.send("Target.setAutoAttach", {"autoAttach": True, "waitForDebuggerOnStart": True, "flatten": True}, sid)
|
|
557
620
|
tree = await self.send("Page.getFrameTree", None, sid)
|
|
558
|
-
|
|
621
|
+
top = (tree.get("frameTree") or {}).get("frame") or {}
|
|
622
|
+
frame = top.get("id")
|
|
559
623
|
self.pages[sid] = {"target": info.get("targetId"), "frame": frame, "opener": bool(info.get("openerId")), "history": None}
|
|
560
|
-
# The page open now: its document was loaded before the script
|
|
561
|
-
|
|
624
|
+
# The page open now (its address now, not when the tab was made): its document was loaded before the script
|
|
625
|
+
# above was added.
|
|
626
|
+
now = str(top.get("url") or info.get("url") or "")
|
|
627
|
+
if frame and now.startswith("http"):
|
|
562
628
|
world = await self.send("Page.createIsolatedWorld", {"frameId": frame, "worldName": self.world}, sid)
|
|
563
629
|
await self.send("Runtime.evaluate", {"expression": js, "contextId": world.get("executionContextId")}, sid)
|
|
630
|
+
# A window a page opened, loaded before the recorder came to it: the steps go on there.
|
|
631
|
+
if info.get("openerId") and self.rec is not None:
|
|
632
|
+
self.pages[sid]["seen"] = True
|
|
633
|
+
self.pages[sid]["history"] = None
|
|
634
|
+
self.rec.on_navigate(now, "page")
|
|
635
|
+
self.active = sid
|
|
564
636
|
finally:
|
|
565
637
|
try:
|
|
566
638
|
await self.send("Runtime.runIfWaitingForDebugger", None, sid)
|
|
@@ -574,7 +646,7 @@ class RecordSession:
|
|
|
574
646
|
await self.send("Page.enable", None, sid)
|
|
575
647
|
await self.send("Runtime.enable", None, sid)
|
|
576
648
|
await self.send("Runtime.addBinding", {"name": self.binding, "executionContextName": self.world}, sid)
|
|
577
|
-
js = recorder_js(self.binding, KEPT_ATTRS, leader=self.leader, badge=self.payload.get("panel") == "badge")
|
|
649
|
+
js = recorder_js(self.binding, KEPT_ATTRS, leader=self.leader, badge=self.payload.get("panel") == "badge", pw=self.pw_prints or None)
|
|
578
650
|
await self.send("Page.addScriptToEvaluateOnNewDocument", {"source": open_shadow_js(self.shadow_key)}, sid)
|
|
579
651
|
await self.send("Page.addScriptToEvaluateOnNewDocument", {"source": js, "worldName": self.world}, sid)
|
|
580
652
|
await self.send("Target.setAutoAttach", {"autoAttach": True, "waitForDebuggerOnStart": True, "flatten": True}, sid)
|
|
@@ -607,6 +679,10 @@ class RecordSession:
|
|
|
607
679
|
page["frame"] = frame.get("id") or page.get("frame")
|
|
608
680
|
page["ctx"] = None
|
|
609
681
|
url = str(frame.get("url") or "")
|
|
682
|
+
# A load of this tab's own page: an element read after it is read on a later load than one read before it,
|
|
683
|
+
# which is what tells a value the page made fresh from one that held (varying.py).
|
|
684
|
+
self._load += 1
|
|
685
|
+
page["load"] = self._load
|
|
610
686
|
# A page loaded in the tab the video follows: Chrome drops a screencast when the tab moves to another
|
|
611
687
|
# process (the first page of a site, often), so it is asked for again.
|
|
612
688
|
if self.video is not None and sid == self._video_sid:
|
|
@@ -616,6 +692,7 @@ class RecordSession:
|
|
|
616
692
|
logger.debug("record: no screencast of the page: %s", ex)
|
|
617
693
|
how = await self._how(sid, page)
|
|
618
694
|
renderer = page.pop("renderer", False)
|
|
695
|
+
started = page.pop("started", None)
|
|
619
696
|
if page.pop("initial", False) or (page.get("opener") and not page.get("seen")):
|
|
620
697
|
how = "page"
|
|
621
698
|
page["seen"] = True
|
|
@@ -624,7 +701,8 @@ class RecordSession:
|
|
|
624
701
|
return
|
|
625
702
|
if renderer and how not in ("back", "forward"):
|
|
626
703
|
how = "page"
|
|
627
|
-
|
|
704
|
+
when = event.get("_at") if isinstance(event.get("_at"), float) else None
|
|
705
|
+
msg = self.rec.on_navigate(url, "" if how == "new" else how, started=started, by_page=renderer, at=when)
|
|
628
706
|
self.active = sid
|
|
629
707
|
if msg:
|
|
630
708
|
self._changed(msg)
|
|
@@ -723,7 +801,10 @@ class RecordSession:
|
|
|
723
801
|
if kind == "click":
|
|
724
802
|
t = await target(data)
|
|
725
803
|
hover = await target(data["hover"]) if isinstance(data.get("hover"), dict) else None
|
|
726
|
-
|
|
804
|
+
held = data.get("held")
|
|
805
|
+
held = held if isinstance(held, int) and not isinstance(held, bool) and 600 <= held <= 10000 else None
|
|
806
|
+
outer = [await target(o) for o in (data.get("outer_hovers") or [])[:2] if isinstance(o, dict)] if isinstance(data.get("outer_hovers"), list) and hover is not None else []
|
|
807
|
+
msg = rec.on_click(t, hover=hover, right=data.get("button") == "right", held=held, outer_hovers=outer)
|
|
727
808
|
elif kind == "drag":
|
|
728
809
|
# An element moved: the one taken and, when it was let go on another, that one (each with a point in it).
|
|
729
810
|
if not isinstance(data.get("source"), dict):
|
|
@@ -735,9 +816,16 @@ class RecordSession:
|
|
|
735
816
|
msg = rec.on_dblclick(await target(data))
|
|
736
817
|
elif kind == "fill":
|
|
737
818
|
t = await target(data)
|
|
738
|
-
|
|
819
|
+
secret_env = self._password_env_of(data, t.url) if data.get("password") else None
|
|
820
|
+
value = None if data.get("password") else str(data.get("value") or "")
|
|
821
|
+
# A text the person kept from the page, typed into a password field: only when it is that variable's text.
|
|
822
|
+
if data.get("kept") is True and value is not None and value not in {v for v in rec.variables.values() if v}:
|
|
823
|
+
value, secret_env = None, None
|
|
824
|
+
data = {**data, "password": True}
|
|
825
|
+
msg = rec.on_fill(t, value, password=bool(data.get("password")), secret_env=secret_env)
|
|
739
826
|
elif kind == "select":
|
|
740
|
-
|
|
827
|
+
opts = data.get("options")
|
|
828
|
+
msg = rec.on_select(await target(data), str(data.get("text") or ""), options=opts if isinstance(opts, list) else None)
|
|
741
829
|
elif kind == "press":
|
|
742
830
|
msg = rec.on_press(str(data.get("keys") or ""), in_field=bool(data.get("in_field")), autocomplete=bool(data.get("autocomplete")))
|
|
743
831
|
elif kind == "upload":
|
|
@@ -750,7 +838,17 @@ class RecordSession:
|
|
|
750
838
|
if not isinstance(pages, (int, float)) or isinstance(pages, bool) or not 0 < pages <= 50:
|
|
751
839
|
return
|
|
752
840
|
box = await target(data["box"]) if isinstance(data.get("box"), dict) else None
|
|
753
|
-
|
|
841
|
+
# Where it ended, in pixels from the top: a replay goes back there, wherever the steps before left it.
|
|
842
|
+
end = data.get("end")
|
|
843
|
+
end = end if isinstance(end, int) and not isinstance(end, bool) and 0 <= end <= MAX_SCROLL_END else None
|
|
844
|
+
msg = rec.on_scroll(data.get("down") is not False, float(pages), box, end=end, small=data.get("small") is True)
|
|
845
|
+
elif kind == "permission":
|
|
846
|
+
# A browser permission the site has: kept by name for its origin (never what it gave the page).
|
|
847
|
+
self._permission(str(data.get("url") or rec.url), data.get("name"))
|
|
848
|
+
return
|
|
849
|
+
elif kind == "leave":
|
|
850
|
+
# The pointer left the page through its top, and the page showed something for it.
|
|
851
|
+
msg = rec.on_leave()
|
|
754
852
|
elif kind == "hover":
|
|
755
853
|
# The hover command: what the pointer is on, kept as a step (what it shows can be checked after it).
|
|
756
854
|
msg = rec.on_hover(await target(data))
|
|
@@ -769,6 +867,21 @@ class RecordSession:
|
|
|
769
867
|
if msg:
|
|
770
868
|
self._changed(msg)
|
|
771
869
|
|
|
870
|
+
def _password_env_of(self, data: Dict[str, Any], url: str) -> Optional[str]:
|
|
871
|
+
"""
|
|
872
|
+
The variable a typed password is read from in the test, as the page script matched its fingerprint
|
|
873
|
+
(password_prints): the saved login it is, else the site's own (secret_env_for), never another login's. None when
|
|
874
|
+
the page could not tell (the site's saved login is assumed, as before). Only a variable this recording handed out.
|
|
875
|
+
"""
|
|
876
|
+
from urllib.parse import urlparse
|
|
877
|
+
|
|
878
|
+
env = data.get("secret_env")
|
|
879
|
+
if isinstance(env, str) and env in {p["env"] for p in self.pw_prints.get("logins", [])}:
|
|
880
|
+
return env
|
|
881
|
+
if data.get("secret_mismatch") is True:
|
|
882
|
+
return secret_env_for((urlparse(url).hostname or "").lower())
|
|
883
|
+
return None
|
|
884
|
+
|
|
772
885
|
def _frame_contexts(self, tab: str) -> List[Tuple[str, int]]:
|
|
773
886
|
"""The recorder's world in each frame of a tab (same-origin frames in its session, cross-origin ones in theirs)."""
|
|
774
887
|
page_frame = (self.pages.get(tab) or {}).get("frame")
|
|
@@ -858,12 +971,43 @@ class RecordSession:
|
|
|
858
971
|
if target is live and _best_kind(fallback) > _best_kind(live) and not await self._shows(sid, int(backend)):
|
|
859
972
|
logger.debug("record: the element is hidden since the event: its locators as the page script counted them")
|
|
860
973
|
target = fallback
|
|
974
|
+
# Gone since the event (a "Delete" that removes itself, one of several): checked now, a locator finds
|
|
975
|
+
# only the others, so it can look unique. What the page script counted at the event stands.
|
|
976
|
+
if target is live and isinstance(data.get("matches"), dict) and not await self._shows(sid, int(backend)):
|
|
977
|
+
target = Target(url, live.facts, counted_at_event(live.locators, data["matches"]), live.frames, closed_shadow=closed)
|
|
861
978
|
# None of its own locators unique: the one anchored on its container (the page script counted it), where there is one.
|
|
862
979
|
anchored = within_locator(data.get("anchor"))
|
|
863
|
-
if anchored and not any(l.get("
|
|
980
|
+
if anchored and generic_name(target.facts) and not any(l.get("type") in ("test_id", "id") and l.get("verified") for l in target.locators):
|
|
981
|
+
# A name many controls share ("Close" of a toast): another like it may show on a replay; its container first.
|
|
982
|
+
locs = [anchored] + [l for l in target.locators if l.get("type") != "within"]
|
|
983
|
+
target = Target(target.url, target.facts, locs, target.frames, closed_shadow=target.closed_shadow)
|
|
984
|
+
elif anchored and not any(l.get("verified") and l.get("matches") == 1 and l.get("type") in STRONG_ALONE for l in target.locators):
|
|
864
985
|
locs = sorted(target.locators + [anchored], key=lambda l: (not l.get("verified"), -int(l.get("confidence") or 0)))
|
|
865
986
|
target = Target(target.url, target.facts, locs, target.frames, closed_shadow=target.closed_shadow)
|
|
866
|
-
|
|
987
|
+
target = await self._steady(sid, target, data.get("matches") if isinstance(data.get("matches"), dict) else {}, ctx=ctx)
|
|
988
|
+
return self._varying(sid, target)
|
|
989
|
+
|
|
990
|
+
def _varying(self, sid: str, t: Target) -> Target:
|
|
991
|
+
"""
|
|
992
|
+
Locators whose value this page made fresh. The same element was read on an earlier load of the same address
|
|
993
|
+
and held another id, another name, another message: that is not a guess about what the value looks like
|
|
994
|
+
(dynamic.py), it is the value seen being different, so the locator is marked and read down (memory.py
|
|
995
|
+
confidence). The first sight of an element marks nothing; nor does a page loaded only once.
|
|
996
|
+
"""
|
|
997
|
+
load = int((self.pages.get(sid) or {}).get("load") or 0)
|
|
998
|
+
try:
|
|
999
|
+
kinds = self.seen.compare(t.url, load, t.facts, t.locators, t.frames)
|
|
1000
|
+
except Exception as ex:
|
|
1001
|
+
logger.debug("record: elements of this page not compared with the load before: %s", ex)
|
|
1002
|
+
return t
|
|
1003
|
+
if not mark_varying(t.locators, kinds):
|
|
1004
|
+
return t
|
|
1005
|
+
logger.debug("record: %s made fresh on this load, for %s", ", ".join(sorted(kinds)), t.facts.get("name") or t.facts.get("tag"))
|
|
1006
|
+
for loc in t.locators:
|
|
1007
|
+
if loc.get("varies"):
|
|
1008
|
+
loc["confidence"] = confidence(loc)
|
|
1009
|
+
locs = sorted(t.locators, key=lambda l: (not l.get("verified"), bool(l.get("varies")), bool(l.get("live_data")), -int(l.get("confidence") or 0)))
|
|
1010
|
+
return Target(t.url, t.facts, locs, t.frames, closed_shadow=t.closed_shadow)
|
|
867
1011
|
|
|
868
1012
|
async def _shows(self, sid: str, backend: int) -> bool:
|
|
869
1013
|
"""Whether an element shows on the page now (it has a box); True when it cannot tell."""
|
|
@@ -1570,6 +1714,7 @@ class RecordSession:
|
|
|
1570
1714
|
"skipped": list(rec.skipped),
|
|
1571
1715
|
"signed_in": bool(self.payload.get("signed_in")),
|
|
1572
1716
|
**({"http_auth": list(self.http_auth.values())} if self.http_auth else {}),
|
|
1717
|
+
**({"permissions": [{"origin": o, "names": n} for o, n in self.permissions.items() if n]} if any(self.permissions.values()) else {}),
|
|
1573
1718
|
**({"work_dir": str(self.payload["work_dir"])} if any(s.get("op") == "upload" for s in steps) and self.payload.get("work_dir") else {}),
|
|
1574
1719
|
**({"case_id": self.case_id, "case_gaps": rec.case_gaps()} if rec.case_steps else {}),
|
|
1575
1720
|
},
|
|
@@ -1643,6 +1788,30 @@ OPEN_SHADOW_JS = r"""(() => {
|
|
|
1643
1788
|
})()"""
|
|
1644
1789
|
|
|
1645
1790
|
|
|
1791
|
+
PW_ROUNDS = 100_000
|
|
1792
|
+
|
|
1793
|
+
|
|
1794
|
+
def password_prints(logins: List[Any]) -> Dict[str, Any]:
|
|
1795
|
+
"""
|
|
1796
|
+
What the page script needs to tell which saved login a typed password is, never a password: a salt made for this
|
|
1797
|
+
recording and each saved login's password through PBKDF2-SHA256 with it, with the login's variable and sites. Empty
|
|
1798
|
+
when no saved login has a password set.
|
|
1799
|
+
"""
|
|
1800
|
+
import hashlib
|
|
1801
|
+
|
|
1802
|
+
salt = secrets.token_bytes(16)
|
|
1803
|
+
out = []
|
|
1804
|
+
for l in logins:
|
|
1805
|
+
value = (os.environ.get(l.password_env) or "").strip() if getattr(l, "password_env", None) else ""
|
|
1806
|
+
if value:
|
|
1807
|
+
out.append({"env": l.password_env, "hosts": list(l.hosts()), "fp": hashlib.pbkdf2_hmac("sha256", value.encode(), salt, PW_ROUNDS).hex()})
|
|
1808
|
+
return {"salt": salt.hex(), "rounds": PW_ROUNDS, "logins": out} if out else {}
|
|
1809
|
+
|
|
1810
|
+
|
|
1811
|
+
# The browser permissions a recording keeps, by name (Playwright's names for them too).
|
|
1812
|
+
PERMISSIONS = ("geolocation", "notifications", "clipboard-read", "clipboard-write", "camera", "microphone")
|
|
1813
|
+
|
|
1814
|
+
|
|
1646
1815
|
def http_origin(url: str) -> str:
|
|
1647
1816
|
"""A web address's origin (scheme, host and port), http(s) only, with no user or password in it; "" for any other."""
|
|
1648
1817
|
from urllib.parse import urlparse
|
|
@@ -1686,7 +1855,7 @@ def _frame_parent(tree: Dict[str, Any], fid: str, parent: Optional[str] = None)
|
|
|
1686
1855
|
# What names an <iframe> in the document that holds it: its attributes, and its place among the frames there (the
|
|
1687
1856
|
# fallback when it has none). Read as data: a page can put anything in them.
|
|
1688
1857
|
_FRAME_FN = r"""function() {
|
|
1689
|
-
const out = { index: [...this.ownerDocument.querySelectorAll('iframe, frame')].indexOf(this) };
|
|
1858
|
+
const out = { index: [...this.ownerDocument.querySelectorAll('iframe, frame')].indexOf(this), frameset: this.tagName === 'FRAME' };
|
|
1690
1859
|
for (const k of ['id', 'name', 'title', 'src']) { const v = this.getAttribute(k); if (v) out[k] = v.slice(0, 300); }
|
|
1691
1860
|
return out;
|
|
1692
1861
|
}"""
|
|
@@ -1718,6 +1887,9 @@ def clean_frame(raw: Any) -> Dict[str, Any]:
|
|
|
1718
1887
|
out[k] = v
|
|
1719
1888
|
if isinstance(raw.get("index"), int) and not isinstance(raw.get("index"), bool) and 0 <= raw["index"] < 1000:
|
|
1720
1889
|
out["index"] = raw["index"]
|
|
1890
|
+
# A <frame> of a frameset (an older page's), not an <iframe>: the replay names it by its own tag.
|
|
1891
|
+
if raw.get("frameset") is True:
|
|
1892
|
+
out["frameset"] = True
|
|
1721
1893
|
return out
|
|
1722
1894
|
|
|
1723
1895
|
|
|
@@ -1726,6 +1898,30 @@ def _best_kind(t: Target) -> float:
|
|
|
1726
1898
|
return max((BASE.get(str(l.get("type")), 0) for l in t.locators if l.get("verified")), default=-1)
|
|
1727
1899
|
|
|
1728
1900
|
|
|
1901
|
+
GENERIC_NAMES = frozenset({"close", "×", "x", "✕", "ok", "cancel", "delete", "remove", "edit", "dismiss", "more", "yes", "no", "save", "next", "back", "view", "open"})
|
|
1902
|
+
|
|
1903
|
+
|
|
1904
|
+
def generic_name(facts: Dict[str, Any]) -> bool:
|
|
1905
|
+
"""A control named as many are ("Close", "×", "Delete"): found by its container when it has one."""
|
|
1906
|
+
return str(facts.get("name") or facts.get("text") or "").strip().lower() in GENERIC_NAMES
|
|
1907
|
+
|
|
1908
|
+
|
|
1909
|
+
def counted_at_event(locs: List[Dict[str, Any]], counted: Dict[str, Any]) -> List[Dict[str, Any]]:
|
|
1910
|
+
"""
|
|
1911
|
+
Locators checked after the element went away, put right by what the page script counted when the person acted: one
|
|
1912
|
+
it found more than once then is not unique, however few it finds now. Sorted as a target's are.
|
|
1913
|
+
"""
|
|
1914
|
+
out = []
|
|
1915
|
+
for loc in locs:
|
|
1916
|
+
n = _count(loc, counted)
|
|
1917
|
+
if n is not None and n > 1:
|
|
1918
|
+
loc = {**loc, "verified": False, "matches": n}
|
|
1919
|
+
loc["confidence"] = confidence(loc)
|
|
1920
|
+
out.append(loc)
|
|
1921
|
+
out.sort(key=lambda l: (not l.get("verified"), -int(l.get("confidence") or 0), -BASE.get(str(l.get("type")), 0)))
|
|
1922
|
+
return out
|
|
1923
|
+
|
|
1924
|
+
|
|
1729
1925
|
def fallback_target(url: str, facts: Dict[str, Any], counted: Optional[Dict[str, Any]] = None) -> Target:
|
|
1730
1926
|
"""
|
|
1731
1927
|
A target from the facts the page script read, for an element the page took away before ForgeQE could look at it.
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Values a page makes fresh on every load: an id a framework generates ("Challenging DOM"), a label that reads like an
|
|
3
|
+
ordinary name but is different each time, a message picked at random from a few ("Notification Message").
|
|
4
|
+
|
|
5
|
+
``dynamic.py`` reads one value and sees what *looks* like data: a price, a date, an order number. It cannot see a
|
|
6
|
+
random id that looks like a word, or a message that is a plain sentence. This reads the same element on two loads of
|
|
7
|
+
the same page and sees what *is* different, whatever it looks like. That is evidence, not a guess, so a locator it
|
|
8
|
+
marks is trusted less than one ``dynamic.py`` only suspects.
|
|
9
|
+
|
|
10
|
+
- ``identity(facts, frames)``: what names one element across loads, from the parts a page does not make fresh.
|
|
11
|
+
- ``SeenElements.compare(...)``: the kinds whose value differs from the load before, for one element.
|
|
12
|
+
|
|
13
|
+
Nothing here reaches a page or a browser: it is given the facts a load read and answers from what it was given before.
|
|
14
|
+
"""
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import hashlib
|
|
18
|
+
import json
|
|
19
|
+
from typing import Any, Dict, List, Optional, Sequence, Set, Tuple
|
|
20
|
+
|
|
21
|
+
# A kind that holds one value for one element on one load: a second value on another load of the same page is proof
|
|
22
|
+
# the page makes it fresh. "role" carries the element's accessible name after a "|", so a name that changes shows here.
|
|
23
|
+
VARYING_KINDS: Tuple[str, ...] = ("id", "test_id", "name", "href", "role", "label", "placeholder", "text", "title", "alt", "css")
|
|
24
|
+
# A pattern locator is cut from this load's name or text (recordsession.py _steady): when that varies, the stem it was
|
|
25
|
+
# cut from varies with it, so it is marked too.
|
|
26
|
+
FOLLOWS: Dict[str, str] = {"role": "role_pattern", "text": "text_pattern"}
|
|
27
|
+
# How many elements one recording keeps, and how long a value is kept for comparing.
|
|
28
|
+
MAX_SEEN = 500
|
|
29
|
+
MAX_VALUE = 300
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def page_key(url: str) -> str:
|
|
33
|
+
"""
|
|
34
|
+
The page an element was on, as this compares them: the exact address without its fragment. Not the page template
|
|
35
|
+
(memory.py page_id), which would put /item/1 and /item/2 together and read one item's own name as a name that
|
|
36
|
+
changes. Only the same address loaded again is compared.
|
|
37
|
+
"""
|
|
38
|
+
u = str(url or "").strip()
|
|
39
|
+
if not u:
|
|
40
|
+
return ""
|
|
41
|
+
return u.split("#", 1)[0][:1000]
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def identity(facts: Dict[str, Any], frames: Optional[Sequence[Dict[str, Any]]] = None) -> str:
|
|
45
|
+
"""
|
|
46
|
+
What names one element across loads of a page, built only from parts a page does not make fresh: where it sits
|
|
47
|
+
(its XPath), what it is (its tag) and what it does (its role). Its id, its name and its text are left out — those
|
|
48
|
+
are the values being judged. Empty when there is no XPath to place it by (inside a shadow root), so nothing is
|
|
49
|
+
compared and nothing is guessed.
|
|
50
|
+
"""
|
|
51
|
+
xpath = str(facts.get("xpath") or "")
|
|
52
|
+
if not xpath:
|
|
53
|
+
return ""
|
|
54
|
+
where = [str((f or {}).get("index", "")) + ":" + str((f or {}).get("name") or (f or {}).get("id") or "") for f in (frames or [])]
|
|
55
|
+
basis = json.dumps([xpath, str(facts.get("tag") or ""), str(facts.get("role") or ""), where], sort_keys=True)
|
|
56
|
+
return hashlib.sha256(basis.encode("utf-8")).hexdigest()[:16]
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def values_of(locators: Sequence[Dict[str, Any]]) -> Dict[str, str]:
|
|
60
|
+
"""The one value each varying kind has on this load, for the kinds this element has a locator of."""
|
|
61
|
+
out: Dict[str, str] = {}
|
|
62
|
+
for loc in locators or []:
|
|
63
|
+
kind, value = loc.get("type"), loc.get("value")
|
|
64
|
+
if kind in VARYING_KINDS and isinstance(value, str) and value and kind not in out:
|
|
65
|
+
out[kind] = value[:MAX_VALUE]
|
|
66
|
+
return out
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def mark(locators: List[Dict[str, Any]], kinds: Set[str]) -> bool:
|
|
70
|
+
"""
|
|
71
|
+
Marks every locator of a kind that varies, and the pattern locator cut from it. Returns whether anything changed.
|
|
72
|
+
The locator keeps its base: what the kind is worth is unchanged, and `varies` is what reads it down (memory.py
|
|
73
|
+
confidence), so marking twice says the same thing as marking once.
|
|
74
|
+
"""
|
|
75
|
+
if not kinds:
|
|
76
|
+
return False
|
|
77
|
+
follows = {FOLLOWS[k] for k in kinds if k in FOLLOWS}
|
|
78
|
+
changed = False
|
|
79
|
+
for loc in locators:
|
|
80
|
+
if loc.get("type") in kinds or loc.get("type") in follows:
|
|
81
|
+
if not loc.get("varies"):
|
|
82
|
+
loc["varies"] = True
|
|
83
|
+
changed = True
|
|
84
|
+
return changed
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
class SeenElements:
|
|
88
|
+
"""
|
|
89
|
+
What each element of each page looked like the last time this recording loaded that page. One recording's own: it
|
|
90
|
+
is never written to disk and never read back, so nothing a person could edit reaches it.
|
|
91
|
+
"""
|
|
92
|
+
|
|
93
|
+
def __init__(self, limit: int = MAX_SEEN) -> None:
|
|
94
|
+
self._seen: Dict[Tuple[str, str], Dict[str, Any]] = {}
|
|
95
|
+
self._limit = limit
|
|
96
|
+
|
|
97
|
+
def compare(self, url: str, load: int, facts: Dict[str, Any], locators: Sequence[Dict[str, Any]], frames: Optional[Sequence[Dict[str, Any]]] = None) -> Set[str]:
|
|
98
|
+
"""
|
|
99
|
+
The kinds whose value differs from the last load of this page, and remembers this load's values. Empty on the
|
|
100
|
+
first sight of an element, when the page has not been loaded again since (the same load answers nothing), and
|
|
101
|
+
when the element cannot be placed across loads.
|
|
102
|
+
"""
|
|
103
|
+
page = page_key(url)
|
|
104
|
+
who = identity(facts or {}, frames)
|
|
105
|
+
if not page or not who:
|
|
106
|
+
return set()
|
|
107
|
+
key = (page, who)
|
|
108
|
+
now = values_of(locators)
|
|
109
|
+
was = self._seen.get(key)
|
|
110
|
+
self._seen[key] = {"load": load, "values": now}
|
|
111
|
+
if len(self._seen) > self._limit:
|
|
112
|
+
self._seen.pop(next(iter(self._seen)), None)
|
|
113
|
+
if not was or was.get("load") == load:
|
|
114
|
+
# The same load says nothing: one element read twice is the same read twice.
|
|
115
|
+
return set()
|
|
116
|
+
before = was.get("values") or {}
|
|
117
|
+
# Kinds the element had on both loads, with a different value on each.
|
|
118
|
+
varies = {k for k, v in now.items() if k in before and before[k] != v}
|
|
119
|
+
# A kind it had before and has no longer is not proof: the page may simply not write it this time.
|
|
120
|
+
return varies
|