papersearch 0.7.3 → 0.8.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 (170) hide show
  1. package/LICENSE-paper-search-mcp-nodejs +24 -0
  2. package/NOTICE +8 -37
  3. package/README.en.md +7 -3
  4. package/README.fr.md +268 -0
  5. package/README.ja.md +268 -0
  6. package/README.ko.md +268 -0
  7. package/README.md +7 -3
  8. package/README.zh-Hant.md +268 -0
  9. package/dist/capabilities/download/batch/batch.d.ts +16 -1
  10. package/dist/capabilities/download/batch/batch.d.ts.map +1 -1
  11. package/dist/capabilities/download/batch/batch.js +389 -56
  12. package/dist/capabilities/download/batch/batch.js.map +1 -1
  13. package/dist/capabilities/download/batch/batchFolder.d.ts.map +1 -1
  14. package/dist/capabilities/download/batch/batchFolder.js +3 -2
  15. package/dist/capabilities/download/batch/batchFolder.js.map +1 -1
  16. package/dist/capabilities/download/batch/networkLoss.d.ts +11 -2
  17. package/dist/capabilities/download/batch/networkLoss.d.ts.map +1 -1
  18. package/dist/capabilities/download/batch/networkLoss.js +24 -3
  19. package/dist/capabilities/download/batch/networkLoss.js.map +1 -1
  20. package/dist/capabilities/download/batch/resume.d.ts +7 -0
  21. package/dist/capabilities/download/batch/resume.d.ts.map +1 -1
  22. package/dist/capabilities/download/batch/resume.js +50 -9
  23. package/dist/capabilities/download/batch/resume.js.map +1 -1
  24. package/dist/capabilities/download/content/markdown/pro.d.ts +6 -0
  25. package/dist/capabilities/download/content/markdown/pro.d.ts.map +1 -1
  26. package/dist/capabilities/download/content/markdown/pro.js.map +1 -1
  27. package/dist/capabilities/download/content/markdown/shortfall.d.ts +8 -5
  28. package/dist/capabilities/download/content/markdown/shortfall.d.ts.map +1 -1
  29. package/dist/capabilities/download/content/markdown/shortfall.js +22 -10
  30. package/dist/capabilities/download/content/markdown/shortfall.js.map +1 -1
  31. package/dist/capabilities/download/content/markdown/step.d.ts +9 -0
  32. package/dist/capabilities/download/content/markdown/step.d.ts.map +1 -1
  33. package/dist/capabilities/download/content/markdown/step.js +42 -2
  34. package/dist/capabilities/download/content/markdown/step.js.map +1 -1
  35. package/dist/capabilities/download/content/markdown/types.d.ts +10 -1
  36. package/dist/capabilities/download/content/markdown/types.d.ts.map +1 -1
  37. package/dist/capabilities/download/handler.d.ts.map +1 -1
  38. package/dist/capabilities/download/handler.js +13 -5
  39. package/dist/capabilities/download/handler.js.map +1 -1
  40. package/dist/capabilities/download/outputLayout.d.ts.map +1 -1
  41. package/dist/capabilities/download/outputLayout.js +3 -1
  42. package/dist/capabilities/download/outputLayout.js.map +1 -1
  43. package/dist/capabilities/download/tools.js +2 -2
  44. package/dist/capabilities/download/tools.js.map +1 -1
  45. package/dist/capabilities/download/types.d.ts +9 -1
  46. package/dist/capabilities/download/types.d.ts.map +1 -1
  47. package/dist/cli.js +3 -1
  48. package/dist/cli.js.map +1 -1
  49. package/dist/infrastructure/runlog/RunLedger.d.ts +7 -0
  50. package/dist/infrastructure/runlog/RunLedger.d.ts.map +1 -1
  51. package/dist/infrastructure/runlog/RunLedger.js +13 -0
  52. package/dist/infrastructure/runlog/RunLedger.js.map +1 -1
  53. package/dist/infrastructure/runlog/failureClass.d.ts +2 -1
  54. package/dist/infrastructure/runlog/failureClass.d.ts.map +1 -1
  55. package/dist/infrastructure/runlog/failureClass.js +27 -4
  56. package/dist/infrastructure/runlog/failureClass.js.map +1 -1
  57. package/dist/infrastructure/school/SchoolAttempt.d.ts +11 -0
  58. package/dist/infrastructure/school/SchoolAttempt.d.ts.map +1 -1
  59. package/dist/infrastructure/school/SchoolAttempt.js +48 -5
  60. package/dist/infrastructure/school/SchoolAttempt.js.map +1 -1
  61. package/dist/infrastructure/school/SchoolMcpClient.d.ts +1 -0
  62. package/dist/infrastructure/school/SchoolMcpClient.d.ts.map +1 -1
  63. package/dist/infrastructure/school/SchoolMcpClient.js +18 -6
  64. package/dist/infrastructure/school/SchoolMcpClient.js.map +1 -1
  65. package/dist/infrastructure/school/SchoolProgress.d.ts +2 -0
  66. package/dist/infrastructure/school/SchoolProgress.d.ts.map +1 -1
  67. package/dist/infrastructure/school/SchoolProgress.js +2 -0
  68. package/dist/infrastructure/school/SchoolProgress.js.map +1 -1
  69. package/dist/infrastructure/school/SchoolReadiness.d.ts +2 -0
  70. package/dist/infrastructure/school/SchoolReadiness.d.ts.map +1 -1
  71. package/dist/infrastructure/school/SchoolReadiness.js +2 -0
  72. package/dist/infrastructure/school/SchoolReadiness.js.map +1 -1
  73. package/dist/infrastructure/school/SchoolResultNormalizer.d.ts.map +1 -1
  74. package/dist/infrastructure/school/SchoolResultNormalizer.js +4 -0
  75. package/dist/infrastructure/school/SchoolResultNormalizer.js.map +1 -1
  76. package/dist/infrastructure/school/index.d.ts +2 -2
  77. package/dist/infrastructure/school/index.d.ts.map +1 -1
  78. package/dist/infrastructure/school/index.js +1 -1
  79. package/dist/infrastructure/school/index.js.map +1 -1
  80. package/dist/infrastructure/school/types.d.ts +42 -0
  81. package/dist/infrastructure/school/types.d.ts.map +1 -1
  82. package/dist/infrastructure/school/types.js.map +1 -1
  83. package/dist/management/failures/index.d.ts +23 -0
  84. package/dist/management/failures/index.d.ts.map +1 -1
  85. package/dist/management/failures/index.js +63 -18
  86. package/dist/management/failures/index.js.map +1 -1
  87. package/package.json +7 -2
  88. package/school/NOTICE +3 -2
  89. package/school/paper_search_school/adapters/__init__.py +2 -0
  90. package/school/paper_search_school/adapters/aps/__init__.py +3 -6
  91. package/school/paper_search_school/adapters/base.py +16 -2
  92. package/school/paper_search_school/adapters/copernicus/__init__.py +2 -7
  93. package/school/paper_search_school/adapters/elsevier/__init__.py +50 -1
  94. package/school/paper_search_school/adapters/frontiers/__init__.py +41 -2
  95. package/school/paper_search_school/adapters/ieee/__init__.py +6 -4
  96. package/school/paper_search_school/adapters/iop/__init__.py +8 -0
  97. package/school/paper_search_school/adapters/jama/__init__.py +8 -0
  98. package/school/paper_search_school/adapters/lww/__init__.py +14 -6
  99. package/school/paper_search_school/adapters/mdpi/__init__.py +12 -7
  100. package/school/paper_search_school/adapters/neurology/__init__.py +5 -2
  101. package/school/paper_search_school/adapters/optica/__init__.py +2 -9
  102. package/school/paper_search_school/adapters/oup/__init__.py +7 -4
  103. package/school/paper_search_school/adapters/platforms/__init__.py +4 -1
  104. package/school/paper_search_school/adapters/platforms/atypon/__init__.py +8 -0
  105. package/school/paper_search_school/adapters/platforms/jstage/__init__.py +64 -0
  106. package/school/paper_search_school/adapters/taylor_francis/__init__.py +0 -3
  107. package/school/paper_search_school/adapters/thieme/__init__.py +2 -9
  108. package/school/paper_search_school/api_keys.py +63 -13
  109. package/school/paper_search_school/assets/api_keys.json +14 -0
  110. package/school/paper_search_school/assets/capsule.html +156 -116
  111. package/school/paper_search_school/assets/capsule_en.json +69 -46
  112. package/school/paper_search_school/assets/capsule_fr.json +70 -47
  113. package/school/paper_search_school/assets/capsule_ja.json +69 -46
  114. package/school/paper_search_school/assets/capsule_ko.json +69 -46
  115. package/school/paper_search_school/assets/capsule_zh-Hant.json +68 -45
  116. package/school/paper_search_school/browser/batch_session.py +1 -1
  117. package/school/paper_search_school/browser/challenge/__init__.py +12 -9
  118. package/school/paper_search_school/browser/challenge/continuation.py +65 -0
  119. package/school/paper_search_school/browser/challenge/handlers/__init__.py +1 -0
  120. package/school/paper_search_school/browser/challenge/handlers/aws_waf.py +260 -0
  121. package/school/paper_search_school/browser/challenge/handlers/recaptcha_hcaptcha.py +167 -0
  122. package/school/paper_search_school/browser/challenge/handlers/text_captcha.py +100 -0
  123. package/school/paper_search_school/browser/challenge/handlers/turnstile.py +174 -0
  124. package/school/paper_search_school/browser/challenge/kinds.py +203 -0
  125. package/school/paper_search_school/browser/challenge/local/__init__.py +1 -0
  126. package/school/paper_search_school/browser/challenge/{interaction.py → local/interaction.py} +94 -13
  127. package/school/paper_search_school/browser/challenge/{pointer.py → local/pointer.py} +2 -2
  128. package/school/paper_search_school/browser/challenge/local/prompt.py +283 -0
  129. package/school/paper_search_school/browser/challenge/local/submission.py +33 -0
  130. package/school/paper_search_school/browser/challenge/services/__init__.py +1 -0
  131. package/school/paper_search_school/browser/challenge/services/solver.py +272 -0
  132. package/school/paper_search_school/cli_config.py +10 -5
  133. package/school/paper_search_school/config.py +11 -10
  134. package/school/paper_search_school/download_diagnostics.py +7 -2
  135. package/school/paper_search_school/engine/access_rules.py +12 -3
  136. package/school/paper_search_school/engine/batch.py +43 -11
  137. package/school/paper_search_school/engine/batch_access.py +38 -12
  138. package/school/paper_search_school/engine/batch_capture.py +215 -18
  139. package/school/paper_search_school/engine/batch_common.py +3 -0
  140. package/school/paper_search_school/engine/batch_diagnostics.py +25 -5
  141. package/school/paper_search_school/engine/batch_institution.py +38 -3
  142. package/school/paper_search_school/engine/batch_login.py +223 -16
  143. package/school/paper_search_school/engine/batch_pdf_urls.py +38 -7
  144. package/school/paper_search_school/engine/batch_waits.py +179 -12
  145. package/school/paper_search_school/engine/bridge.py +28 -4
  146. package/school/paper_search_school/engine/fulltext_page.py +45 -7
  147. package/school/paper_search_school/engine/router.py +16 -1
  148. package/school/paper_search_school/entitlements.py +1 -1
  149. package/school/paper_search_school/pdf_utils.py +25 -16
  150. package/school/paper_search_school/progress_capsule.py +36 -6
  151. package/school/paper_search_school/progress_reporter.py +54 -5
  152. package/school/paper_search_school/progress_view.py +63 -43
  153. package/school/paper_search_school/publishers/builtin/iop.json +2 -1
  154. package/school/paper_search_school/publishers/builtin/neurology.json +4 -2
  155. package/school/paper_search_school/publishers/site.py +12 -4
  156. package/school/paper_search_school/school_test.py +1 -1
  157. package/school/paper_search_school/server.py +17 -6
  158. package/school/paper_search_school/user_settings.py +13 -0
  159. package/school/pyproject.toml +1 -0
  160. package/skills/paper-search/SKILL.md +107 -107
  161. package/skills/paper-search/references/browser-download.md +102 -99
  162. package/skills/paper-search/references/capability-routing.md +89 -89
  163. package/skills/paper-search/references/cli-contract.md +78 -78
  164. package/skills/paper-search/references/federation-support.md +172 -172
  165. package/skills/paper-search/references/management-layer.md +78 -78
  166. package/skills/paper-search/references/publisher-support.md +38 -38
  167. package/skills/paper-search/references/school-setup.md +56 -55
  168. package/skills/paper-search/references/setup.md +20 -20
  169. package/skills/paper-search/references/troubleshooting.md +12 -12
  170. 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 @@
1
+ """Image recognition service transport and response decoding; no browser actions."""
@@ -0,0 +1,272 @@
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
+ GRID_TASK = "AwsClassification"
24
+ TASKS = {
25
+ "image_code": IMAGE_TASK,
26
+ "awswaf": GRID_TASK,
27
+ "bcaptcha": "bCaptchaClassification",
28
+ "recaptcha": "ReCaptchaV2Classification",
29
+ "hcaptcha": "HCaptchaClassification",
30
+ }
31
+
32
+
33
+ def service(config: dict[str, Any] | None) -> str:
34
+ return str((config or {}).get("captcha_service") or "none").strip().lower()
35
+
36
+
37
+ def endpoint(config: dict[str, Any] | None) -> str:
38
+ return str((config or {}).get("captcha_service_url") or DEFAULT_ENDPOINT).strip().rstrip("/")
39
+
40
+
41
+ def key(config: dict[str, Any] | None) -> str:
42
+ """Read the key from config, environment, then the local key file."""
43
+ value = str((config or {}).get("captcha_key") or "").strip()
44
+ if value:
45
+ return value
46
+ value = os.environ.get("YESCAPTCHA_KEY", "").strip()
47
+ if value:
48
+ return value
49
+ try:
50
+ return KEY_FILE.read_text(encoding="utf-8").strip()
51
+ except OSError:
52
+ return ""
53
+
54
+
55
+ def configured(config: dict[str, Any] | None) -> bool:
56
+ return service(config) == "yescaptcha" and bool(key(config))
57
+
58
+
59
+ def _mask(value: str) -> str:
60
+ return "***" if value else ""
61
+
62
+
63
+ def _post(url: str, payload: dict[str, Any], timeout: int,
64
+ post: Callable[..., Any] | None = None) -> dict[str, Any] | None:
65
+ """Post JSON; return None on transport or response errors."""
66
+ sender = post
67
+ if sender is None:
68
+ import requests
69
+
70
+ sender = requests.post
71
+ try:
72
+ response = sender(url, json=payload, timeout=timeout)
73
+ data = response.json()
74
+ except Exception: # noqa: BLE001 - the caller records transport or response errors
75
+ return None
76
+ return data if isinstance(data, dict) else None
77
+
78
+
79
+ class Budget:
80
+ """Thread-safe request budget shared by a downloader."""
81
+
82
+ def __init__(self, limit: int | None = None, config: dict[str, Any] | None = None) -> None:
83
+ raw = limit if limit is not None else int((config or {}).get("captcha_max_per_run", DEFAULT_MAX_PER_RUN) or 0)
84
+ self.limit = max(0, int(raw))
85
+ self.used = 0
86
+ self._lock = threading.Lock()
87
+
88
+ def take(self) -> bool:
89
+ with self._lock:
90
+ if self.used >= self.limit:
91
+ return False
92
+ self.used += 1
93
+ return True
94
+
95
+
96
+ def get_balance(config: dict[str, Any] | None, *, post: Callable[..., Any] | None = None,
97
+ timeout: int | None = None) -> float | None:
98
+ """Read the balance without creating a task."""
99
+ token = key(config)
100
+ if service(config) != "yescaptcha" or not token:
101
+ return None
102
+ seconds = int(timeout or (config or {}).get("captcha_timeout") or DEFAULT_TIMEOUT)
103
+ data = _post(f"{endpoint(config)}/getBalance", {"clientKey": token, "softID": SOFT_ID}, seconds, post)
104
+ if not data or data.get("errorId"):
105
+ return None
106
+ try:
107
+ return float(data.get("balance"))
108
+ except (TypeError, ValueError):
109
+ return None
110
+
111
+
112
+ def solve_image(image: bytes, config: dict[str, Any] | None, *,
113
+ post: Callable[..., Any] | None = None,
114
+ timeout: float | None = None, checkpoint: Any = None) -> str | None:
115
+ """Return recognized characters, or None on failure."""
116
+ if not image:
117
+ return None
118
+ solution = _solve_task({"type": IMAGE_TASK, "body": base64.b64encode(image).decode("ascii")},
119
+ config, timeout=timeout, post=post, checkpoint=checkpoint)
120
+ if not solution or not isinstance(solution.get("text"), str):
121
+ return None
122
+ return solution["text"].strip() or None
123
+
124
+
125
+ @dataclass(frozen=True, repr=False)
126
+ class TurnstileAnswer:
127
+ token: str
128
+ user_agent: str
129
+
130
+
131
+ def solve_turnstile(origin: str, sitekey: str, config: dict | None, *,
132
+ action: str = "", timeout: float | None = None,
133
+ checkpoint: Any = None, post: Callable[..., Any] | None = None) -> TurnstileAnswer | None:
134
+ """Send only the public origin and widget settings, never a session URL."""
135
+ parsed = urlsplit(origin)
136
+ if (parsed.scheme != "https" or not parsed.hostname or parsed.username or parsed.password
137
+ or parsed.path not in {"", "/"} or parsed.query or parsed.fragment
138
+ or not re.fullmatch(r"0x[A-Za-z0-9_-]{10,100}", sitekey)
139
+ or (action and not re.fullmatch(r"[A-Za-z0-9_-]{1,32}", action))):
140
+ return None
141
+ task = {"type": "TurnstileTaskProxyless", "websiteURL": origin, "websiteKey": sitekey}
142
+ if action:
143
+ task["pageAction"] = action
144
+ solution = _solve_task(task, config, timeout=timeout, checkpoint=checkpoint, post=post)
145
+ if not solution:
146
+ return None
147
+ token, agent = solution.get("token"), solution.get("userAgent")
148
+ if (not isinstance(token, str) or not 1 <= len(token) <= 4096 or re.search(r"\s", token)
149
+ or not isinstance(agent, str) or not 1 <= len(agent) <= 1024
150
+ or any(ord(c) < 32 or ord(c) > 126 for c in agent)):
151
+ return None
152
+ return TurnstileAnswer(token, agent)
153
+
154
+
155
+ def solve_grid(image: bytes, question: str, config: dict[str, Any] | None, *,
156
+ post: Callable[..., Any] | None = None,
157
+ timeout: int | None = None, kind: str = "awswaf") -> list[tuple[float, float]]:
158
+ """Return click coordinates for a supported whole-grid image task."""
159
+ # Each provider has a different wire format. Never default an unknown kind
160
+ # (or a non-grid provider) to an AWS task.
161
+ if not image or kind not in {"awswaf", "bcaptcha"}:
162
+ return []
163
+ task = {"type": TASKS[kind], "queries": base64.b64encode(image).decode("ascii"),
164
+ "question": str(question).strip()}
165
+ return _points(_solve_task(task, config, timeout=timeout, post=post))
166
+
167
+
168
+ def _solve_task(task: dict, config: dict | None, *, timeout: float | None = None,
169
+ post: Callable[..., Any] | None = None, checkpoint: Any = None) -> dict | None:
170
+ """One deadline includes creation and all result polls; late answers are ignored."""
171
+ if not configured(config):
172
+ return None
173
+ seconds = float(timeout if timeout is not None else (config or {}).get("captcha_timeout", DEFAULT_TIMEOUT))
174
+ deadline = time.monotonic() + max(0, seconds)
175
+ def request(path: str, body: dict) -> dict | None:
176
+ if checkpoint:
177
+ checkpoint()
178
+ left = deadline - time.monotonic()
179
+ if left <= 0:
180
+ return None
181
+ data = _post(f"{endpoint(config)}/{path}",
182
+ {"clientKey": key(config), "softID": SOFT_ID, **body}, left, post)
183
+ if checkpoint:
184
+ checkpoint()
185
+ return data if time.monotonic() < deadline else None
186
+ queries = task.get("queries")
187
+ image_count = len(queries) if isinstance(queries, list) else int(any(k in task for k in ('queries', 'body', 'image')))
188
+ log.info("captcha service request: task=%s images=%d examples=%d", task["type"], image_count, len(task.get("anchors", [])))
189
+ data = request("createTask", {"task": task})
190
+ while data and not data.get("errorId"):
191
+ if str(data.get("status", "")).lower() == "ready" or not data.get("taskId"):
192
+ value = data.get("solution")
193
+ log.info("captcha service result: task=%s status=%s", task["type"],
194
+ "ready" if isinstance(value, dict) else "invalid_solution")
195
+ return value if isinstance(value, dict) else None
196
+ task_id = data["taskId"]
197
+ left = deadline - time.monotonic()
198
+ if left <= 5:
199
+ return None
200
+ # Short sleeps allow cancellation while waiting for the next poll.
201
+ for _ in range(10):
202
+ if checkpoint:
203
+ checkpoint()
204
+ time.sleep(0.5)
205
+ data = request("getTaskResult", {"taskId": task_id})
206
+ if data and not data.get("taskId") and data.get("status") == "processing":
207
+ data["taskId"] = task_id
208
+ error = str((data or {}).get("errorCode") or "network_or_format")
209
+ if not re.fullmatch(r"[A-Za-z0-9_]{1,80}", error):
210
+ error = "service_error"
211
+ log.info("captcha service result: task=%s failure=%s", task["type"], error)
212
+ return None
213
+
214
+
215
+ def solve_tiles(images: list[bytes], question: str, config: dict | None, *,
216
+ kind: str, count: int, timeout: float, anchors: list[bytes] = (),
217
+ post: Callable[..., Any] | None = None, checkpoint: Any = None) -> list[int] | None:
218
+ """Provider-specific image tasks; None is failure, [] is a valid empty answer."""
219
+ if not images or not all(images) or not question:
220
+ return None
221
+ encode = lambda image: base64.b64encode(image).decode("ascii")
222
+ if kind == "hcaptcha" and len(images) == count == 9:
223
+ task = {"type": TASKS[kind], "queries": [encode(im) for im in images], "question": question}
224
+ if anchors:
225
+ task["anchors"] = [encode(im) for im in anchors]
226
+ elif kind == "recaptcha" and len(images) == 1 and count in (9, 16) and question.startswith("/m/"):
227
+ task = {"type": TASKS[kind], "image": encode(images[0]), "question": question, "confidence": 0.5}
228
+ else:
229
+ return None
230
+ solution = _solve_task(task, config, timeout=timeout, post=post, checkpoint=checkpoint)
231
+ if not solution or solution.get("type") in {"drag", "single"}:
232
+ return None
233
+ objects = solution.get("objects")
234
+ if not isinstance(objects, list):
235
+ return None
236
+ if kind == "hcaptcha":
237
+ if len(objects) != count or any(type(v) is not bool for v in objects):
238
+ return None
239
+ return [i for i, hit in enumerate(objects) if hit]
240
+ if any(type(i) is not int or not 0 <= i < count for i in objects):
241
+ return None
242
+ return sorted(set(objects))
243
+
244
+
245
+ def _points(solution: Any) -> list[tuple[float, float]]:
246
+ """The answer's points: ``clicks`` (pixels of the picture), ``objects`` (nine
247
+ tile booleans, in reading order) or ``box`` (pixel pairs), whichever it gives."""
248
+ if not isinstance(solution, dict):
249
+ return []
250
+ clicks = solution.get("clicks")
251
+ if isinstance(clicks, list):
252
+ points: list[tuple[float, float]] = []
253
+ for item in clicks:
254
+ try:
255
+ points.append((float(item["x"]), float(item["y"])))
256
+ except (KeyError, TypeError, ValueError):
257
+ continue
258
+ if points:
259
+ return points
260
+ objects = solution.get("objects")
261
+ if isinstance(objects, list) and len(objects) == 9 and all(isinstance(flag, bool) for flag in objects):
262
+ return [(float(index % 3), float(index // 3)) for index, flag in enumerate(objects) if flag]
263
+ box = solution.get("box")
264
+ if isinstance(box, list):
265
+ numbers: list[float] = []
266
+ for value in box:
267
+ try:
268
+ numbers.append(float(value))
269
+ except (TypeError, ValueError):
270
+ continue
271
+ return list(zip(numbers[::2], numbers[1::2]))
272
+ return []
@@ -38,13 +38,18 @@ def update(changes: dict[str, str | None]) -> None:
38
38
  data.pop(key, None)
39
39
  else:
40
40
  data[key] = value
41
- target = config_path()
41
+ write_private_json(config_path(), data)
42
+
43
+
44
+ def write_private_json(target: Path, data: dict) -> None:
45
+ """Atomically replace a local JSON file that can contain credentials."""
42
46
  target.parent.mkdir(parents=True, exist_ok=True)
43
- with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", dir=target.parent, delete=False) as fh:
44
- temporary = Path(fh.name)
45
- json.dump(data, fh, ensure_ascii=False, indent=2)
46
- fh.write("\n")
47
+ fh = tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", dir=target.parent, delete=False)
48
+ temporary = Path(fh.name)
47
49
  try:
50
+ with fh:
51
+ json.dump(data, fh, ensure_ascii=False, indent=2)
52
+ fh.write("\n")
48
53
  os.chmod(temporary, 0o600)
49
54
  temporary.replace(target)
50
55
  finally:
@@ -84,6 +84,9 @@ DEFAULT_CONFIG: dict[str, Any] = {
84
84
  "publisher_hourly_limit": 100,
85
85
  # 改了上面的上限时,正在等上限的篇目是否立即按新上限接着下;false = 这一小时过后再按新上限。
86
86
  "publisher_hourly_limit_now": False,
87
+ # 失败后自动重试:原因不明的批量最后再试一次,被网站拦截的 10 分钟后再试一次;默认关(用户 2026-11-24)。
88
+ "batch_retry_failed": False,
89
+ # 验证码识别服务(用户 2026-11-25 定):见 browser/challenge/services/solver.py。
87
90
  # 没权限时换下一所学校 (school_switch.py; user, 2026-11-21): on unless turned off.
88
91
  "school_switch": True,
89
92
  # 灰色源竞速浏览器的独立无头开关(只影响 sci-hub 竞速,机构登录仍有可见窗口)。
@@ -131,7 +134,7 @@ def _from_before_rename(existing: dict[str, Any]) -> dict[str, Any]:
131
134
  return existing
132
135
 
133
136
 
134
- def load_config() -> dict[str, Any]:
137
+ def load_config(*, strict: bool = False) -> dict[str, Any]:
135
138
  config = DEFAULT_CONFIG.copy()
136
139
  if CONFIG_FILE.exists():
137
140
  try:
@@ -139,8 +142,11 @@ def load_config() -> dict[str, Any]:
139
142
  existing = json.load(fh)
140
143
  if isinstance(existing, dict):
141
144
  config.update(_from_before_rename(existing))
145
+ elif strict:
146
+ raise ValueError("School backend configuration must be a JSON object")
142
147
  except Exception:
143
- pass
148
+ if strict:
149
+ raise
144
150
  for key, value in DEFAULT_CONFIG.items():
145
151
  config.setdefault(key, value)
146
152
  for key in _RETIRED_KEYS:
@@ -149,14 +155,9 @@ def load_config() -> dict[str, Any]:
149
155
 
150
156
 
151
157
  def save_config(config: dict[str, Any]) -> None:
152
- DATA_DIR.mkdir(parents=True, exist_ok=True)
153
- with CONFIG_FILE.open("w", encoding="utf-8") as fh:
154
- json.dump(config, fh, indent=2, ensure_ascii=False)
155
- try:
156
- # Readable by the user only: it may hold a school's account (school_login.py).
157
- CONFIG_FILE.chmod(0o600)
158
- except OSError:
159
- pass
158
+ from .cli_config import write_private_json
159
+
160
+ write_private_json(CONFIG_FILE.resolve(), config)
160
161
 
161
162
 
162
163
  _VALIDATION_RULES: dict[str, tuple[type, Any, Any]] = {