papersearch 0.7.3 → 0.8.1

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 (204) hide show
  1. package/NOTICE +8 -37
  2. package/README.fr.md +265 -0
  3. package/README.ja.md +265 -0
  4. package/README.ko.md +265 -0
  5. package/README.md +149 -148
  6. package/README.zh-Hant.md +265 -0
  7. package/README.zh.md +265 -0
  8. package/dist/capabilities/download/batch/batch.d.ts +20 -1
  9. package/dist/capabilities/download/batch/batch.d.ts.map +1 -1
  10. package/dist/capabilities/download/batch/batch.js +1057 -208
  11. package/dist/capabilities/download/batch/batch.js.map +1 -1
  12. package/dist/capabilities/download/batch/batchFolder.d.ts.map +1 -1
  13. package/dist/capabilities/download/batch/batchFolder.js +3 -2
  14. package/dist/capabilities/download/batch/batchFolder.js.map +1 -1
  15. package/dist/capabilities/download/batch/networkLoss.d.ts +11 -2
  16. package/dist/capabilities/download/batch/networkLoss.d.ts.map +1 -1
  17. package/dist/capabilities/download/batch/networkLoss.js +24 -3
  18. package/dist/capabilities/download/batch/networkLoss.js.map +1 -1
  19. package/dist/capabilities/download/batch/resume.d.ts +7 -0
  20. package/dist/capabilities/download/batch/resume.d.ts.map +1 -1
  21. package/dist/capabilities/download/batch/resume.js +50 -9
  22. package/dist/capabilities/download/batch/resume.js.map +1 -1
  23. package/dist/capabilities/download/batch/windowPlan.d.ts +96 -0
  24. package/dist/capabilities/download/batch/windowPlan.d.ts.map +1 -0
  25. package/dist/capabilities/download/batch/windowPlan.js +196 -0
  26. package/dist/capabilities/download/batch/windowPlan.js.map +1 -0
  27. package/dist/capabilities/download/content/markdown/pro.d.ts +6 -0
  28. package/dist/capabilities/download/content/markdown/pro.d.ts.map +1 -1
  29. package/dist/capabilities/download/content/markdown/pro.js.map +1 -1
  30. package/dist/capabilities/download/content/markdown/shortfall.d.ts +8 -5
  31. package/dist/capabilities/download/content/markdown/shortfall.d.ts.map +1 -1
  32. package/dist/capabilities/download/content/markdown/shortfall.js +22 -10
  33. package/dist/capabilities/download/content/markdown/shortfall.js.map +1 -1
  34. package/dist/capabilities/download/content/markdown/step.d.ts +9 -0
  35. package/dist/capabilities/download/content/markdown/step.d.ts.map +1 -1
  36. package/dist/capabilities/download/content/markdown/step.js +46 -3
  37. package/dist/capabilities/download/content/markdown/step.js.map +1 -1
  38. package/dist/capabilities/download/content/markdown/types.d.ts +10 -1
  39. package/dist/capabilities/download/content/markdown/types.d.ts.map +1 -1
  40. package/dist/capabilities/download/content/pdf/open/tiers/scihub.d.ts.map +1 -1
  41. package/dist/capabilities/download/content/pdf/open/tiers/scihub.js +3 -1
  42. package/dist/capabilities/download/content/pdf/open/tiers/scihub.js.map +1 -1
  43. package/dist/capabilities/download/handler.d.ts.map +1 -1
  44. package/dist/capabilities/download/handler.js +13 -5
  45. package/dist/capabilities/download/handler.js.map +1 -1
  46. package/dist/capabilities/download/outputLayout.d.ts.map +1 -1
  47. package/dist/capabilities/download/outputLayout.js +3 -1
  48. package/dist/capabilities/download/outputLayout.js.map +1 -1
  49. package/dist/capabilities/download/tools.js +2 -2
  50. package/dist/capabilities/download/tools.js.map +1 -1
  51. package/dist/capabilities/download/types.d.ts +9 -1
  52. package/dist/capabilities/download/types.d.ts.map +1 -1
  53. package/dist/cli.js +3 -1
  54. package/dist/cli.js.map +1 -1
  55. package/dist/infrastructure/http/hostGate.d.ts +24 -0
  56. package/dist/infrastructure/http/hostGate.d.ts.map +1 -0
  57. package/dist/infrastructure/http/hostGate.js +72 -0
  58. package/dist/infrastructure/http/hostGate.js.map +1 -0
  59. package/dist/infrastructure/pdf/PdfDownload.d.ts +1 -0
  60. package/dist/infrastructure/pdf/PdfDownload.d.ts.map +1 -1
  61. package/dist/infrastructure/pdf/PdfDownload.js +6 -1
  62. package/dist/infrastructure/pdf/PdfDownload.js.map +1 -1
  63. package/dist/infrastructure/runlog/RunLedger.d.ts +14 -0
  64. package/dist/infrastructure/runlog/RunLedger.d.ts.map +1 -1
  65. package/dist/infrastructure/runlog/RunLedger.js +30 -4
  66. package/dist/infrastructure/runlog/RunLedger.js.map +1 -1
  67. package/dist/infrastructure/runlog/failureClass.d.ts +2 -1
  68. package/dist/infrastructure/runlog/failureClass.d.ts.map +1 -1
  69. package/dist/infrastructure/runlog/failureClass.js +27 -4
  70. package/dist/infrastructure/runlog/failureClass.js.map +1 -1
  71. package/dist/infrastructure/school/SchoolAttempt.d.ts +11 -0
  72. package/dist/infrastructure/school/SchoolAttempt.d.ts.map +1 -1
  73. package/dist/infrastructure/school/SchoolAttempt.js +48 -5
  74. package/dist/infrastructure/school/SchoolAttempt.js.map +1 -1
  75. package/dist/infrastructure/school/SchoolMcpClient.d.ts +13 -2
  76. package/dist/infrastructure/school/SchoolMcpClient.d.ts.map +1 -1
  77. package/dist/infrastructure/school/SchoolMcpClient.js +138 -15
  78. package/dist/infrastructure/school/SchoolMcpClient.js.map +1 -1
  79. package/dist/infrastructure/school/SchoolProgress.d.ts +2 -0
  80. package/dist/infrastructure/school/SchoolProgress.d.ts.map +1 -1
  81. package/dist/infrastructure/school/SchoolProgress.js +2 -0
  82. package/dist/infrastructure/school/SchoolProgress.js.map +1 -1
  83. package/dist/infrastructure/school/SchoolReadiness.d.ts +9 -0
  84. package/dist/infrastructure/school/SchoolReadiness.d.ts.map +1 -1
  85. package/dist/infrastructure/school/SchoolReadiness.js +10 -0
  86. package/dist/infrastructure/school/SchoolReadiness.js.map +1 -1
  87. package/dist/infrastructure/school/SchoolResultNormalizer.d.ts.map +1 -1
  88. package/dist/infrastructure/school/SchoolResultNormalizer.js +4 -0
  89. package/dist/infrastructure/school/SchoolResultNormalizer.js.map +1 -1
  90. package/dist/infrastructure/school/index.d.ts +2 -2
  91. package/dist/infrastructure/school/index.d.ts.map +1 -1
  92. package/dist/infrastructure/school/index.js +1 -1
  93. package/dist/infrastructure/school/index.js.map +1 -1
  94. package/dist/infrastructure/school/types.d.ts +73 -1
  95. package/dist/infrastructure/school/types.d.ts.map +1 -1
  96. package/dist/infrastructure/school/types.js.map +1 -1
  97. package/dist/infrastructure/security/SecurityUtils.d.ts.map +1 -1
  98. package/dist/infrastructure/security/SecurityUtils.js +6 -2
  99. package/dist/infrastructure/security/SecurityUtils.js.map +1 -1
  100. package/dist/management/failures/index.d.ts +23 -0
  101. package/dist/management/failures/index.d.ts.map +1 -1
  102. package/dist/management/failures/index.js +68 -20
  103. package/dist/management/failures/index.js.map +1 -1
  104. package/dist/management/school/autoUpdate.d.ts.map +1 -1
  105. package/dist/management/school/autoUpdate.js +9 -1
  106. package/dist/management/school/autoUpdate.js.map +1 -1
  107. package/dist/management/school/cliProgress.d.ts.map +1 -1
  108. package/dist/management/school/cliProgress.js +3 -1
  109. package/dist/management/school/cliProgress.js.map +1 -1
  110. package/package.json +8 -3
  111. package/school/NOTICE +3 -2
  112. package/school/paper_search_school/adapters/__init__.py +2 -0
  113. package/school/paper_search_school/adapters/aps/__init__.py +3 -6
  114. package/school/paper_search_school/adapters/base.py +19 -2
  115. package/school/paper_search_school/adapters/copernicus/__init__.py +2 -7
  116. package/school/paper_search_school/adapters/elsevier/__init__.py +50 -1
  117. package/school/paper_search_school/adapters/frontiers/__init__.py +41 -2
  118. package/school/paper_search_school/adapters/ieee/__init__.py +6 -4
  119. package/school/paper_search_school/adapters/iop/__init__.py +8 -0
  120. package/school/paper_search_school/adapters/jama/__init__.py +8 -0
  121. package/school/paper_search_school/adapters/lww/__init__.py +14 -6
  122. package/school/paper_search_school/adapters/mdpi/__init__.py +12 -7
  123. package/school/paper_search_school/adapters/neurology/__init__.py +5 -2
  124. package/school/paper_search_school/adapters/optica/__init__.py +52 -13
  125. package/school/paper_search_school/adapters/oup/__init__.py +7 -4
  126. package/school/paper_search_school/adapters/platforms/__init__.py +4 -1
  127. package/school/paper_search_school/adapters/platforms/atypon/__init__.py +12 -3
  128. package/school/paper_search_school/adapters/platforms/figshare/__init__.py +23 -4
  129. package/school/paper_search_school/adapters/platforms/jstage/__init__.py +64 -0
  130. package/school/paper_search_school/adapters/taylor_francis/__init__.py +0 -3
  131. package/school/paper_search_school/adapters/thieme/__init__.py +2 -9
  132. package/school/paper_search_school/api_keys.py +63 -13
  133. package/school/paper_search_school/assets/api_keys.json +14 -0
  134. package/school/paper_search_school/assets/capsule.html +526 -147
  135. package/school/paper_search_school/assets/capsule_en.json +140 -49
  136. package/school/paper_search_school/assets/capsule_fr.json +141 -50
  137. package/school/paper_search_school/assets/capsule_ja.json +140 -49
  138. package/school/paper_search_school/assets/capsule_ko.json +140 -49
  139. package/school/paper_search_school/assets/capsule_zh-Hant.json +134 -48
  140. package/school/paper_search_school/browser/backend.py +125 -4
  141. package/school/paper_search_school/browser/batch_session.py +189 -8
  142. package/school/paper_search_school/browser/challenge/__init__.py +12 -9
  143. package/school/paper_search_school/browser/challenge/continuation.py +83 -0
  144. package/school/paper_search_school/browser/challenge/handlers/__init__.py +1 -0
  145. package/school/paper_search_school/browser/challenge/handlers/aws_waf.py +260 -0
  146. package/school/paper_search_school/browser/challenge/handlers/recaptcha_hcaptcha.py +167 -0
  147. package/school/paper_search_school/browser/challenge/handlers/text_captcha.py +128 -0
  148. package/school/paper_search_school/browser/challenge/handlers/turnstile.py +174 -0
  149. package/school/paper_search_school/browser/challenge/kinds.py +203 -0
  150. package/school/paper_search_school/browser/challenge/local/__init__.py +1 -0
  151. package/school/paper_search_school/browser/challenge/{interaction.py → local/interaction.py} +94 -13
  152. package/school/paper_search_school/browser/challenge/{pointer.py → local/pointer.py} +2 -2
  153. package/school/paper_search_school/browser/challenge/local/prompt.py +283 -0
  154. package/school/paper_search_school/browser/challenge/local/submission.py +33 -0
  155. package/school/paper_search_school/browser/challenge/pro.py +24 -0
  156. package/school/paper_search_school/browser/challenge/services/__init__.py +1 -0
  157. package/school/paper_search_school/browser/challenge/services/solver.py +292 -0
  158. package/school/paper_search_school/browser/engine.py +4 -1
  159. package/school/paper_search_school/browser/user_turn.py +126 -0
  160. package/school/paper_search_school/browser/watchdog.py +213 -60
  161. package/school/paper_search_school/cli_config.py +10 -5
  162. package/school/paper_search_school/config.py +16 -10
  163. package/school/paper_search_school/download_diagnostics.py +7 -2
  164. package/school/paper_search_school/engine/access_rules.py +12 -3
  165. package/school/paper_search_school/engine/batch.py +52 -18
  166. package/school/paper_search_school/engine/batch_access.py +62 -16
  167. package/school/paper_search_school/engine/batch_capture.py +260 -31
  168. package/school/paper_search_school/engine/batch_common.py +3 -0
  169. package/school/paper_search_school/engine/batch_diagnostics.py +25 -5
  170. package/school/paper_search_school/engine/batch_institution.py +52 -3
  171. package/school/paper_search_school/engine/batch_login.py +398 -36
  172. package/school/paper_search_school/engine/batch_pdf_urls.py +38 -7
  173. package/school/paper_search_school/engine/batch_user.py +48 -3
  174. package/school/paper_search_school/engine/batch_waits.py +221 -14
  175. package/school/paper_search_school/engine/bridge.py +29 -6
  176. package/school/paper_search_school/engine/fulltext_page.py +55 -8
  177. package/school/paper_search_school/engine/router.py +16 -1
  178. package/school/paper_search_school/engine/supplements.py +7 -1
  179. package/school/paper_search_school/entitlements.py +29 -1
  180. package/school/paper_search_school/pdf_utils.py +25 -16
  181. package/school/paper_search_school/progress_capsule.py +69 -11
  182. package/school/paper_search_school/progress_reporter.py +243 -11
  183. package/school/paper_search_school/progress_view.py +205 -91
  184. package/school/paper_search_school/publishers/builtin/iop.json +2 -1
  185. package/school/paper_search_school/publishers/builtin/neurology.json +4 -2
  186. package/school/paper_search_school/publishers/site.py +12 -4
  187. package/school/paper_search_school/rate_limit.py +24 -1
  188. package/school/paper_search_school/school_login.py +170 -8
  189. package/school/paper_search_school/school_test.py +1 -1
  190. package/school/paper_search_school/server.py +179 -23
  191. package/school/paper_search_school/user_settings.py +46 -4
  192. package/school/pyproject.toml +1 -0
  193. package/skills/paper-search/SKILL.md +107 -107
  194. package/skills/paper-search/references/browser-download.md +102 -99
  195. package/skills/paper-search/references/capability-routing.md +89 -89
  196. package/skills/paper-search/references/cli-contract.md +78 -78
  197. package/skills/paper-search/references/federation-support.md +172 -172
  198. package/skills/paper-search/references/management-layer.md +78 -78
  199. package/skills/paper-search/references/publisher-support.md +38 -38
  200. package/skills/paper-search/references/school-setup.md +56 -55
  201. package/skills/paper-search/references/setup.md +20 -20
  202. package/skills/paper-search/references/troubleshooting.md +12 -12
  203. package/README.en.md +0 -264
  204. package/school/paper_search_school/browser/challenge/prompt.py +0 -154
@@ -0,0 +1,283 @@
1
+ """Publisher checkbox and outer-form controls shared by verification handlers.
2
+
3
+ Only native controls are clicked; no response tokens are read or replayed.
4
+ A checked provider widget permits submitting its enclosing verification form.
5
+ The engine alone decides whether the publisher has actually allowed access.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import os
10
+ import re
11
+ import time
12
+ from typing import Any, Literal
13
+
14
+ from . import pointer
15
+
16
+ #: Provider frames and the one control each shows before any puzzle.
17
+ _FRAMES: tuple[tuple[str, re.Pattern[str], str], ...] = (
18
+ ("reCAPTCHA", re.compile(r"^https://(?:www\.)?(?:google\.com|recaptcha\.net)/recaptcha/"
19
+ r"(?:api2|enterprise)/anchor"), "#recaptcha-anchor, .recaptcha-checkbox"),
20
+ ("hCaptcha", re.compile(r"^https://(?:[a-z0-9-]+\.)*hcaptcha\.com/captcha/"), "#checkbox"),
21
+ # Friendly Captcha's box is in its own widget frame: one press starts its
22
+ # proof-of-work, and the page goes on by itself once that is done.
23
+ ("Friendly Captcha", re.compile(r"^https://(?:[a-z0-9-]+\.)*frcapi\.com/api/v2/captcha/widget"),
24
+ "[role=checkbox], .frc-checkbox"),
25
+ )
26
+ #: The longest one press may take, including its approach.
27
+ PRESS_LIMIT_SEC = 3.0
28
+ #: How long to keep looking for the control after a page turns out to be a
29
+ #: verification. Some providers arm their widget a few seconds after the article
30
+ #: page opens, so a single early look can find no button and hand the page out.
31
+ AWAIT_LIMIT_SEC = 12.0
32
+ #: How often to look again while its widget is shown but no control is there.
33
+ AWAIT_STEP_SEC = 1.0
34
+
35
+
36
+ def enabled() -> bool:
37
+ """Whether pressing another provider's own confirmation control is allowed.
38
+
39
+ On unless ``PAPER_SEARCH_AUTO_CONFIRM`` is 0 (user, 2026-11-18: these
40
+ controls are pressed as well). Only the confirmation control is pressed —
41
+ the puzzle behind it stays the user's, and ``needs_manual_verification``
42
+ hands that over as before.
43
+ """
44
+ value = os.environ.get("PAPER_SEARCH_AUTO_CONFIRM", "").strip().lower()
45
+ return value not in {"0", "false", "no", "off"}
46
+
47
+
48
+ def _unchecked(control: Any) -> bool:
49
+ """Not already pressed: ``aria-checked`` false, or no such attribute."""
50
+ try:
51
+ state = (control.get_attribute("aria-checked") or "").strip().lower()
52
+ except Exception: # noqa: BLE001 - a read that fails leaves the control alone
53
+ state = "true"
54
+ return state in {"false", ""}
55
+
56
+
57
+ def _press(page: Any, control: Any, *, box: dict[str, Any] | None,
58
+ remaining_ms: int) -> bool:
59
+ """Approach the control, then let its own actionable click press it."""
60
+ if box:
61
+ pointer.approach(page, box, limit_sec=pointer.budget_for(remaining_ms))
62
+ control.click(timeout=remaining_ms, no_wait_after=True)
63
+ return True
64
+
65
+
66
+ def click_confirm_control(page: Any, *, timeout_ms: int, checkpoint: Any = None,
67
+ observation: Any = None) -> Literal["absent", "clicked", "unavailable"]:
68
+ """One press on the first visible confirmation control of a known provider."""
69
+ from ...driver import Error, TimeoutError
70
+
71
+ def note(reason: str) -> None:
72
+ if observation is not None:
73
+ observation(reason)
74
+
75
+ until = time.monotonic() + max(0.0, timeout_ms) / 1000
76
+ unavailable = False
77
+ # Friendly Captcha's box sits in a frame of its own widget, which the frame
78
+ # list below does not carry: it is reached through the widget element.
79
+ widget_frame = getattr(page, "frame_locator", None)
80
+ try:
81
+ widget = widget_frame(".frc-captcha iframe") if widget_frame is not None else None
82
+ control = widget.locator("[role=checkbox], .frc-checkbox").first if widget is not None else None
83
+ if (control is not None and control.count() and control.is_visible()
84
+ and control.is_enabled() and _unchecked(control)):
85
+ remaining_ms = int((until - time.monotonic()) * 1000)
86
+ if remaining_ms > 500:
87
+ _press(page, control, box=control.bounding_box(), remaining_ms=remaining_ms)
88
+ note("Friendly Captcha: control pressed")
89
+ return "clicked"
90
+ except TimeoutError:
91
+ unavailable = True
92
+ except Error as exc:
93
+ if not any(text in str(exc).lower() for text in (
94
+ "frame was detached", "element is not attached", "execution context was destroyed")):
95
+ raise
96
+ frames = getattr(page, "frames", ())
97
+ frames = frames if isinstance(frames, (list, tuple)) else ()
98
+ for frame in frames:
99
+ if checkpoint is not None:
100
+ checkpoint()
101
+ if time.monotonic() >= until:
102
+ return "unavailable" if unavailable else "absent"
103
+ url = str(getattr(frame, "url", "") or "")
104
+ for name, pattern, selector in _FRAMES:
105
+ if not pattern.search(url):
106
+ continue
107
+ try:
108
+ controls = frame.locator(selector)
109
+ count = controls.count()
110
+ if not count:
111
+ continue
112
+ control = controls.first
113
+ if not control.is_visible() or not control.is_enabled() or not _unchecked(control):
114
+ note(f"{name}: not actionable")
115
+ unavailable = True
116
+ continue
117
+ remaining_ms = int((until - time.monotonic()) * 1000)
118
+ if remaining_ms <= 0:
119
+ return "unavailable"
120
+ _press(page, control, box=control.bounding_box(), remaining_ms=remaining_ms)
121
+ note(f"{name}: control pressed")
122
+ return "clicked"
123
+ except TimeoutError:
124
+ note(f"{name}: actionability timeout")
125
+ unavailable = True
126
+ except Error as exc:
127
+ if any(text in str(exc).lower() for text in (
128
+ "frame was detached", "frame has been detached", "element is not attached",
129
+ "execution context was destroyed")):
130
+ unavailable = True
131
+ continue
132
+ raise
133
+
134
+ return "unavailable" if unavailable else "absent"
135
+
136
+
137
+ #: The interstitial's own forward control, pressed once the provider's box is checked.
138
+ #: JAMA's crawl-prevention page needs "Take me to my Content" within one minute of the
139
+ #: box being checked; without it the token expires while the wait goes on.
140
+ _FORWARD_TEXTS: tuple[str, ...] = ("Take me to my Content", "Continue", "Proceed", "Submit", "Verify", "Confirm", "I agree")
141
+ FORWARD_LIMIT_SEC = 3.0
142
+ #: Measured on JAMA 2026-11-23: the box read checked 22s after the press.
143
+ CHECKED_LIMIT_SEC = 30.0
144
+ #: The page opens already "expired" more often than not; its own refresh brings the box back.
145
+ REFRESH_LIMIT = 2
146
+
147
+
148
+ def confirm_checked(page: Any) -> bool:
149
+ """Whether a known provider's confirmation control reads checked.
150
+
151
+ Reads ``aria-checked`` only: the response token is never read, stored or replayed.
152
+ """
153
+ frames = getattr(page, "frames", ())
154
+ if not isinstance(frames, (list, tuple)):
155
+ return False
156
+ for _name, pattern, selector in _FRAMES:
157
+ for frame in frames:
158
+ try:
159
+ if not pattern.search(str(getattr(frame, "url", "") or "")):
160
+ continue
161
+ locator = frame.locator(selector)
162
+ if locator.count() != 1:
163
+ continue
164
+ state = (locator.first.get_attribute("aria-checked", timeout=500) or "").strip().lower()
165
+ if state == "true":
166
+ return True
167
+ except Exception: # noqa: BLE001 - a frame that cannot be read is not checked
168
+ continue
169
+ return False
170
+
171
+
172
+ def _checked_form_submit(page: Any) -> tuple[bool, Any]:
173
+ """Find one native submit associated with a checked widget, independent of text.
174
+
175
+ A form with visible editable fields or multiple submit controls is ambiguous.
176
+ Do not fall back to page-wide labels when such a form exists.
177
+ """
178
+ frames = getattr(page, "frames", ())
179
+ if not isinstance(frames, (list, tuple)):
180
+ return False, None
181
+ for frame in frames:
182
+ for _name, pattern, selector in _FRAMES:
183
+ if not pattern.search(str(frame.url or "")):
184
+ continue
185
+ controls = frame.locator(selector)
186
+ if controls.count() != 1 or controls.first.get_attribute("aria-checked", timeout=500) != "true":
187
+ continue
188
+ form = frame.frame_element().query_selector("xpath=ancestor::form[1]")
189
+ if form is None:
190
+ continue
191
+ if form.evaluate('''el => [...el.querySelectorAll(
192
+ 'input:not([type=hidden]):not([type=submit]):not([type=button]), textarea, select, [contenteditable=true]'
193
+ )].some(el => el.getClientRects().length && getComputedStyle(el).visibility !== 'hidden')'''):
194
+ return True, None
195
+ candidates = [el for el in form.query_selector_all('button, input[type=submit], input[type=image]')
196
+ if el.is_visible() and el.evaluate("el => el.form !== null && ['submit','image'].includes(el.type)")]
197
+ return True, candidates[0] if len(candidates) == 1 else None
198
+ return False, None
199
+
200
+
201
+ def press_forward(page: Any, *, timeout_ms: int,
202
+ observation: Any = None) -> Literal["absent", "pressed", "unavailable"]:
203
+ """One press on the interstitial's own forward button, when it is there to press.
204
+
205
+ Prefer the unique native submit of the checked widget's form, regardless of
206
+ its label. Legacy non-form interstitials use known forward labels. Ambiguous
207
+ or disabled form controls stay untouched; a click is never proof of access.
208
+ """
209
+ note = observation or (lambda _reason: None)
210
+ from ...driver import Error
211
+ try:
212
+ found_form, submit = _checked_form_submit(page)
213
+ if found_form:
214
+ if submit is None or not submit.is_enabled():
215
+ note("forward form: ambiguous or not actionable")
216
+ return "unavailable"
217
+ _press(page, submit, box=submit.bounding_box(), remaining_ms=timeout_ms)
218
+ note("forward pressed: checked widget form submit")
219
+ return "pressed"
220
+ except Error as exc:
221
+ note(f"forward form: {type(exc).__name__}")
222
+ return "unavailable"
223
+ seen = False
224
+ for text in _FORWARD_TEXTS:
225
+ button = None
226
+ try:
227
+ role = page.get_by_role("button", name=text, exact=True)
228
+ if role.count():
229
+ seen = True
230
+ button = role.first
231
+ except Exception as exc: # noqa: BLE001
232
+ note(f"forward role {text}: {type(exc).__name__}")
233
+ if button is None:
234
+ try:
235
+ locator = page.get_by_text(text, exact=True)
236
+ if locator.count():
237
+ seen = True
238
+ button = locator.first
239
+ except Exception as exc: # noqa: BLE001
240
+ note(f"forward text {text}: {type(exc).__name__}")
241
+ if button is None:
242
+ continue
243
+ try:
244
+ if not (button.is_visible() and button.is_enabled()):
245
+ note(f"forward {text}: not actionable")
246
+ continue
247
+ box = button.bounding_box()
248
+ if box:
249
+ pointer.approach(page, box, limit_sec=pointer.budget_for(timeout_ms))
250
+ button.click(timeout=timeout_ms, no_wait_after=True)
251
+ note(f"forward pressed: {text}")
252
+ return "pressed"
253
+ except Exception as exc: # noqa: BLE001
254
+ note(f"forward {text}: {type(exc).__name__}")
255
+ return "unavailable" if seen else "absent"
256
+
257
+
258
+ def expired(page: Any) -> bool:
259
+ """The interstitial says the verification expired and offers its own refresh."""
260
+ try:
261
+ return bool(page.get_by_text("verification has expired", exact=False).count())
262
+ except Exception: # noqa: BLE001
263
+ return False
264
+
265
+
266
+ def press_refresh(page: Any, *, timeout_ms: int, observation: Any = None) -> bool:
267
+ """Press the interstitial's own "Refresh verification" once, before pressing again."""
268
+ note = observation or (lambda _reason: None)
269
+ try:
270
+ locator = page.get_by_role("button", name="Refresh verification", exact=True)
271
+ if not locator.count():
272
+ locator = page.get_by_text("Refresh verification", exact=True)
273
+ if not locator.count():
274
+ return False
275
+ button = locator.first
276
+ if not (button.is_visible() and button.is_enabled()):
277
+ return False
278
+ button.click(timeout=timeout_ms, no_wait_after=True)
279
+ note("refresh pressed")
280
+ return True
281
+ except Exception as exc: # noqa: BLE001
282
+ note(f"refresh: {type(exc).__name__}")
283
+ return False
@@ -0,0 +1,33 @@
1
+ """Find action controls within one verification form or local container."""
2
+
3
+ CANDIDATES = r'''(form, scope) => {
4
+ const shown = el => el.getClientRects().length > 0 && getComputedStyle(el).visibility !== "hidden";
5
+ const label=el=>{
6
+ const ids=(el.getAttribute('aria-labelledby')||'').split(/\s+/).filter(Boolean);
7
+ const labelled=ids.map(id=>document.getElementById(id)?.textContent||'').join(' ').trim();
8
+ return (labelled || el.getAttribute('aria-label') ||
9
+ (el.tagName==='INPUT' ? el.getAttribute('value') || el.getAttribute('alt') : el.textContent) || '')
10
+ .normalize('NFKC').trim().replace(/\s+/g,' ').replace(/[\s.!!。::>→»]+$/g,'');
11
+ };
12
+ const forward=/^(?:(?:submit|verify|validate|check|confirm)(?: (?:the )?(?:code|captcha|answer))?|continue|proceed|next|提交|验证|驗證|确认|確認|继续|繼續|下一步|提交验证|提交驗證|送信|検証|認証|続行|확인|검증|제출|계속|vérifier|valider|confirmer|continuer|envoyer|suivant)$/i;
13
+ const other=/^(?:refresh|reload|reset|cancel|back|new (?:code|captcha|challenge)|try again|刷新|换一张|換一張|重置|取消|返回)$/i;
14
+ const candidates=[...document.querySelectorAll('button,input[type=submit],input[type=image],input[type=button],[role=button],[onclick],a[href],[tabindex]')]
15
+ .filter(el=>shown(el) && (form
16
+ ? (el.form ? el.form===form : scope.contains(el) && el.closest('form')===form)
17
+ : scope.contains(el) && !el.form && !el.closest('form')))
18
+ .filter(el=>{
19
+ if((el.tagName==='INPUT' && !['button','submit','image'].includes(el.type)) ||
20
+ ['TEXTAREA','SELECT','OPTION'].includes(el.tagName) || el.isContentEditable)return false;
21
+ const name=label(el);
22
+ if(el.type==='reset' || other.test(name))return false;
23
+ // Browser-resolved type includes buttons whose type attribute is omitted.
24
+ const native=['BUTTON','INPUT'].includes(el.tagName) && el.form===form &&
25
+ !!form && ['submit','image'].includes(el.type);
26
+ const link=el.tagName==='A' && /^(?:#?|javascript:\s*(?:void\(0\);?|;))$/i.test((el.getAttribute('href')||'').trim());
27
+ const clickable=['BUTTON','INPUT'].includes(el.tagName) || el.getAttribute('role')==='button' ||
28
+ el.hasAttribute('onclick') || link || (el.tagName!=='A' && el.tabIndex>=0 && el.getAttribute('contenteditable')!=='true');
29
+ return native || (clickable && forward.test(name));
30
+ });
31
+ const submits=candidates.filter(el=>!candidates.some(child=>child!==el && el.contains(child)));
32
+ return submits;
33
+ }'''
@@ -0,0 +1,24 @@
1
+ """Versioned optional Pro strategies, loaded through the existing Pro access boundary."""
2
+ import logging
3
+ from ... import school_login
4
+
5
+ log = logging.getLogger(__name__)
6
+ API = 1
7
+
8
+
9
+ def verification():
10
+ """None preserves the public behavior when Pro is absent or incompatible."""
11
+ try:
12
+ module = school_login.module()
13
+ extension = getattr(module, "verification_api", None)
14
+ if extension is None:
15
+ return None
16
+ if (getattr(extension, "API", None) != API
17
+ or not callable(getattr(extension, "read_code", None))
18
+ or not isinstance(getattr(extension, "HANDLERS", None), dict)):
19
+ log.warning("PaperSearch Pro verification interface is incompatible; using public handlers")
20
+ return None
21
+ return extension
22
+ except Exception as exc:
23
+ log.warning("PaperSearch Pro verification did not load (%s); using public handlers", type(exc).__name__)
24
+ return None
@@ -0,0 +1 @@
1
+ """Image recognition service transport and response decoding; no browser actions."""
@@ -0,0 +1,292 @@
1
+ """Verification requests and decoded answers; browser actions live in handlers."""
2
+ from __future__ import annotations
3
+
4
+ import base64
5
+ import logging
6
+ import re
7
+ import os
8
+ import time
9
+ import threading
10
+ from dataclasses import dataclass
11
+ from urllib.parse import urlsplit
12
+ from pathlib import Path
13
+ from typing import Any, Callable
14
+
15
+ log = logging.getLogger(__name__)
16
+
17
+ DEFAULT_ENDPOINT = "https://cn.yescaptcha.com"
18
+ DEFAULT_TIMEOUT = 90
19
+ DEFAULT_MAX_PER_RUN = 20
20
+ KEY_FILE = Path.home() / ".config" / "paper-search-cli" / "yescaptcha.key"
21
+ SOFT_ID = 149362
22
+ IMAGE_TASK = "ImageToTextTaskOcrBase"
23
+ #: The image task that takes requirements (``math``: a sum's result answered; ``numeric``: 1 digits only, 2 no digits;
24
+ #: ``maxLength``), asynchronous and 4 points against 2 (docs.yescaptcha.com/zh/tasks/image-to-text, 2026-11-26).
25
+ #: Used for school sign-in codes whose page states them.
26
+ OPTIONS_TASK = "ImageToTextTask"
27
+ M1_TASK = "ImageToTextTaskM1"
28
+ GRID_TASK = "AwsClassification"
29
+ TASKS = {
30
+ "image_code": IMAGE_TASK,
31
+ "awswaf": GRID_TASK,
32
+ "bcaptcha": "bCaptchaClassification",
33
+ "recaptcha": "ReCaptchaV2Classification",
34
+ "hcaptcha": "HCaptchaClassification",
35
+ }
36
+
37
+
38
+ def service(config: dict[str, Any] | None) -> str:
39
+ return str((config or {}).get("captcha_service") or "none").strip().lower()
40
+
41
+
42
+ def endpoint(config: dict[str, Any] | None) -> str:
43
+ return str((config or {}).get("captcha_service_url") or DEFAULT_ENDPOINT).strip().rstrip("/")
44
+
45
+
46
+ def key(config: dict[str, Any] | None) -> str:
47
+ """Read the key from config, environment, then the local key file."""
48
+ value = str((config or {}).get("captcha_key") or "").strip()
49
+ if value:
50
+ return value
51
+ value = os.environ.get("YESCAPTCHA_KEY", "").strip()
52
+ if value:
53
+ return value
54
+ try:
55
+ return KEY_FILE.read_text(encoding="utf-8").strip()
56
+ except OSError:
57
+ return ""
58
+
59
+
60
+ def configured(config: dict[str, Any] | None) -> bool:
61
+ return service(config) == "yescaptcha" and bool(key(config))
62
+
63
+
64
+ def _mask(value: str) -> str:
65
+ return "***" if value else ""
66
+
67
+
68
+ def _post(url: str, payload: dict[str, Any], timeout: int,
69
+ post: Callable[..., Any] | None = None) -> dict[str, Any] | None:
70
+ """Post JSON; return None on transport or response errors."""
71
+ sender = post
72
+ if sender is None:
73
+ import requests
74
+
75
+ sender = requests.post
76
+ try:
77
+ response = sender(url, json=payload, timeout=timeout)
78
+ data = response.json()
79
+ except Exception: # noqa: BLE001 - the caller records transport or response errors
80
+ return None
81
+ return data if isinstance(data, dict) else None
82
+
83
+
84
+ class Budget:
85
+ """Thread-safe request budget shared by a downloader."""
86
+
87
+ def __init__(self, limit: int | None = None, config: dict[str, Any] | None = None) -> None:
88
+ raw = limit if limit is not None else int((config or {}).get("captcha_max_per_run", DEFAULT_MAX_PER_RUN) or 0)
89
+ self.limit = max(0, int(raw))
90
+ self.used = 0
91
+ self._lock = threading.Lock()
92
+
93
+ def take(self) -> bool:
94
+ with self._lock:
95
+ if self.used >= self.limit:
96
+ return False
97
+ self.used += 1
98
+ return True
99
+
100
+
101
+ def get_balance(config: dict[str, Any] | None, *, post: Callable[..., Any] | None = None,
102
+ timeout: int | None = None) -> float | None:
103
+ """Read the balance without creating a task."""
104
+ token = key(config)
105
+ if service(config) != "yescaptcha" or not token:
106
+ return None
107
+ seconds = int(timeout or (config or {}).get("captcha_timeout") or DEFAULT_TIMEOUT)
108
+ data = _post(f"{endpoint(config)}/getBalance", {"clientKey": token, "softID": SOFT_ID}, seconds, post)
109
+ if not data or data.get("errorId"):
110
+ return None
111
+ try:
112
+ return float(data.get("balance"))
113
+ except (TypeError, ValueError):
114
+ return None
115
+
116
+
117
+ def solve_image(image: bytes, config: dict[str, Any] | None, *,
118
+ post: Callable[..., Any] | None = None,
119
+ timeout: float | None = None, checkpoint: Any = None,
120
+ math: bool = False, numeric: int = 0, max_length: int = 0, m1: bool = False) -> str | None:
121
+ """Return recognized characters, or None on failure. ``math``: the picture is a sum, its result returned;
122
+ ``numeric`` (1 digits only, 2 no digits) and ``max_length``: what the answer may be. Any of them asks
123
+ OPTIONS_TASK; none, the plain IMAGE_TASK as before. ``m1`` opts into M1 with case preserved,
124
+ including requirements."""
125
+ if not image:
126
+ return None
127
+ body = base64.b64encode(image).decode("ascii")
128
+ task: dict[str, Any] = {"type": IMAGE_TASK, "body": body}
129
+ if m1 or math or numeric or max_length:
130
+ task = {"type": M1_TASK if m1 else OPTIONS_TASK, "body": body}
131
+ if m1:
132
+ task["case"] = True
133
+ if math:
134
+ task["math"] = True
135
+ if numeric in (1, 2):
136
+ task["numeric"] = numeric
137
+ if max_length > 0:
138
+ task["maxLength"] = int(max_length)
139
+ solution = _solve_task(task, config, timeout=timeout, post=post, checkpoint=checkpoint)
140
+ if not solution or not isinstance(solution.get("text"), str):
141
+ return None
142
+ return solution["text"].strip() or None
143
+
144
+
145
+ @dataclass(frozen=True, repr=False)
146
+ class TurnstileAnswer:
147
+ token: str
148
+ user_agent: str
149
+
150
+
151
+ def solve_turnstile(origin: str, sitekey: str, config: dict | None, *,
152
+ action: str = "", timeout: float | None = None,
153
+ checkpoint: Any = None, post: Callable[..., Any] | None = None) -> TurnstileAnswer | None:
154
+ """Send only the public origin and widget settings, never a session URL."""
155
+ parsed = urlsplit(origin)
156
+ if (parsed.scheme != "https" or not parsed.hostname or parsed.username or parsed.password
157
+ or parsed.path not in {"", "/"} or parsed.query or parsed.fragment
158
+ or not re.fullmatch(r"0x[A-Za-z0-9_-]{10,100}", sitekey)
159
+ or (action and not re.fullmatch(r"[A-Za-z0-9_-]{1,32}", action))):
160
+ return None
161
+ task = {"type": "TurnstileTaskProxyless", "websiteURL": origin, "websiteKey": sitekey}
162
+ if action:
163
+ task["pageAction"] = action
164
+ solution = _solve_task(task, config, timeout=timeout, checkpoint=checkpoint, post=post)
165
+ if not solution:
166
+ return None
167
+ token, agent = solution.get("token"), solution.get("userAgent")
168
+ if (not isinstance(token, str) or not 1 <= len(token) <= 4096 or re.search(r"\s", token)
169
+ or not isinstance(agent, str) or not 1 <= len(agent) <= 1024
170
+ or any(ord(c) < 32 or ord(c) > 126 for c in agent)):
171
+ return None
172
+ return TurnstileAnswer(token, agent)
173
+
174
+
175
+ def solve_grid(image: bytes, question: str, config: dict[str, Any] | None, *,
176
+ post: Callable[..., Any] | None = None,
177
+ timeout: int | None = None, kind: str = "awswaf") -> list[tuple[float, float]]:
178
+ """Return click coordinates for a supported whole-grid image task."""
179
+ # Each provider has a different wire format. Never default an unknown kind
180
+ # (or a non-grid provider) to an AWS task.
181
+ if not image or kind not in {"awswaf", "bcaptcha"}:
182
+ return []
183
+ task = {"type": TASKS[kind], "queries": base64.b64encode(image).decode("ascii"),
184
+ "question": str(question).strip()}
185
+ return _points(_solve_task(task, config, timeout=timeout, post=post))
186
+
187
+
188
+ def _solve_task(task: dict, config: dict | None, *, timeout: float | None = None,
189
+ post: Callable[..., Any] | None = None, checkpoint: Any = None) -> dict | None:
190
+ """One deadline includes creation and all result polls; late answers are ignored."""
191
+ if not configured(config):
192
+ return None
193
+ seconds = float(timeout if timeout is not None else (config or {}).get("captcha_timeout", DEFAULT_TIMEOUT))
194
+ deadline = time.monotonic() + max(0, seconds)
195
+ def request(path: str, body: dict) -> dict | None:
196
+ if checkpoint:
197
+ checkpoint()
198
+ left = deadline - time.monotonic()
199
+ if left <= 0:
200
+ return None
201
+ data = _post(f"{endpoint(config)}/{path}",
202
+ {"clientKey": key(config), "softID": SOFT_ID, **body}, left, post)
203
+ if checkpoint:
204
+ checkpoint()
205
+ return data if time.monotonic() < deadline else None
206
+ queries = task.get("queries")
207
+ image_count = len(queries) if isinstance(queries, list) else int(any(k in task for k in ('queries', 'body', 'image')))
208
+ log.info("captcha service request: task=%s images=%d examples=%d", task["type"], image_count, len(task.get("anchors", [])))
209
+ data = request("createTask", {"task": task})
210
+ while data and not data.get("errorId"):
211
+ if str(data.get("status", "")).lower() == "ready" or not data.get("taskId"):
212
+ value = data.get("solution")
213
+ log.info("captcha service result: task=%s status=%s", task["type"],
214
+ "ready" if isinstance(value, dict) else "invalid_solution")
215
+ return value if isinstance(value, dict) else None
216
+ task_id = data["taskId"]
217
+ left = deadline - time.monotonic()
218
+ if left <= 5:
219
+ return None
220
+ # Short sleeps allow cancellation while waiting for the next poll.
221
+ for _ in range(10):
222
+ if checkpoint:
223
+ checkpoint()
224
+ time.sleep(0.5)
225
+ data = request("getTaskResult", {"taskId": task_id})
226
+ if data and not data.get("taskId") and data.get("status") == "processing":
227
+ data["taskId"] = task_id
228
+ error = str((data or {}).get("errorCode") or "network_or_format")
229
+ if not re.fullmatch(r"[A-Za-z0-9_]{1,80}", error):
230
+ error = "service_error"
231
+ log.info("captcha service result: task=%s failure=%s", task["type"], error)
232
+ return None
233
+
234
+
235
+ def solve_tiles(images: list[bytes], question: str, config: dict | None, *,
236
+ kind: str, count: int, timeout: float, anchors: list[bytes] = (),
237
+ post: Callable[..., Any] | None = None, checkpoint: Any = None) -> list[int] | None:
238
+ """Provider-specific image tasks; None is failure, [] is a valid empty answer."""
239
+ if not images or not all(images) or not question:
240
+ return None
241
+ encode = lambda image: base64.b64encode(image).decode("ascii")
242
+ if kind == "hcaptcha" and len(images) == count == 9:
243
+ task = {"type": TASKS[kind], "queries": [encode(im) for im in images], "question": question}
244
+ if anchors:
245
+ task["anchors"] = [encode(im) for im in anchors]
246
+ elif kind == "recaptcha" and len(images) == 1 and count in (9, 16) and question.startswith("/m/"):
247
+ task = {"type": TASKS[kind], "image": encode(images[0]), "question": question, "confidence": 0.5}
248
+ else:
249
+ return None
250
+ solution = _solve_task(task, config, timeout=timeout, post=post, checkpoint=checkpoint)
251
+ if not solution or solution.get("type") in {"drag", "single"}:
252
+ return None
253
+ objects = solution.get("objects")
254
+ if not isinstance(objects, list):
255
+ return None
256
+ if kind == "hcaptcha":
257
+ if len(objects) != count or any(type(v) is not bool for v in objects):
258
+ return None
259
+ return [i for i, hit in enumerate(objects) if hit]
260
+ if any(type(i) is not int or not 0 <= i < count for i in objects):
261
+ return None
262
+ return sorted(set(objects))
263
+
264
+
265
+ def _points(solution: Any) -> list[tuple[float, float]]:
266
+ """The answer's points: ``clicks`` (pixels of the picture), ``objects`` (nine
267
+ tile booleans, in reading order) or ``box`` (pixel pairs), whichever it gives."""
268
+ if not isinstance(solution, dict):
269
+ return []
270
+ clicks = solution.get("clicks")
271
+ if isinstance(clicks, list):
272
+ points: list[tuple[float, float]] = []
273
+ for item in clicks:
274
+ try:
275
+ points.append((float(item["x"]), float(item["y"])))
276
+ except (KeyError, TypeError, ValueError):
277
+ continue
278
+ if points:
279
+ return points
280
+ objects = solution.get("objects")
281
+ if isinstance(objects, list) and len(objects) == 9 and all(isinstance(flag, bool) for flag in objects):
282
+ return [(float(index % 3), float(index // 3)) for index, flag in enumerate(objects) if flag]
283
+ box = solution.get("box")
284
+ if isinstance(box, list):
285
+ numbers: list[float] = []
286
+ for value in box:
287
+ try:
288
+ numbers.append(float(value))
289
+ except (TypeError, ValueError):
290
+ continue
291
+ return list(zip(numbers[::2], numbers[1::2]))
292
+ return []
@@ -162,7 +162,10 @@ _atexit.register(_reap_browsers_at_exit)
162
162
 
163
163
  def _build_browser_args(config: dict[str, Any] | None = None) -> list[str]:
164
164
  """Build Chromium launch args from config (proxy, flags, etc.)."""
165
- args = ["--disable-features=CrossOriginOpenerPolicy"]
165
+ # HttpsFirstBalancedModeAutoEnable (user, 2026-11-28): Chrome 158 turns HTTPS-First's balanced mode on by
166
+ # itself, and in a browser a program drives a school's login page on plain http (two schools' login pages: no
167
+ # https there) is tried on https, blocked with ERR_BLOCKED_BY_CLIENT, and never opened on http.
168
+ args = ["--disable-features=CrossOriginOpenerPolicy,HttpsFirstBalancedModeAutoEnable"]
166
169
  if config:
167
170
  proxy = config.get("browser_static_proxy", "")
168
171
  if proxy: