papersearch 0.5.14 → 0.6.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 (49) hide show
  1. package/README.en.md +28 -9
  2. package/README.md +28 -9
  3. package/carsi/paper_search_carsi/adapters/base.py +10 -0
  4. package/carsi/paper_search_carsi/adapters/elsevier/__init__.py +23 -3
  5. package/carsi/paper_search_carsi/adapters/ieee/__init__.py +1 -1
  6. package/carsi/paper_search_carsi/adapters/platforms/atypon/__init__.py +14 -11
  7. package/carsi/paper_search_carsi/adapters/platforms/figshare/__init__.py +8 -2
  8. package/carsi/paper_search_carsi/adapters/sage/__init__.py +2 -4
  9. package/carsi/paper_search_carsi/adapters/thieme/__init__.py +12 -10
  10. package/carsi/paper_search_carsi/adapters/world_scientific/__init__.py +2 -1
  11. package/carsi/paper_search_carsi/assets/capsule.html +0 -1
  12. package/carsi/paper_search_carsi/cli.py +65 -22
  13. package/carsi/paper_search_carsi/cold_start.py +3 -1
  14. package/carsi/paper_search_carsi/config.py +10 -3
  15. package/carsi/paper_search_carsi/download_diagnostics.py +1 -1
  16. package/carsi/paper_search_carsi/engine/batch.py +13 -3
  17. package/carsi/paper_search_carsi/engine/batch_access.py +3 -2
  18. package/carsi/paper_search_carsi/engine/batch_diagnostics.py +1 -1
  19. package/carsi/paper_search_carsi/engine/batch_institution.py +199 -79
  20. package/carsi/paper_search_carsi/engine/batch_login.py +39 -24
  21. package/carsi/paper_search_carsi/engine/batch_waits.py +2 -1
  22. package/carsi/paper_search_carsi/engine/bridge.py +31 -30
  23. package/carsi/paper_search_carsi/engine/login_wait.py +25 -3
  24. package/carsi/paper_search_carsi/engine/page_supplements.py +67 -0
  25. package/carsi/paper_search_carsi/federations/__init__.py +155 -0
  26. package/carsi/paper_search_carsi/federations/builtin/carsi.json +22 -0
  27. package/carsi/paper_search_carsi/federations/builtin/gakunin.json +11 -0
  28. package/carsi/paper_search_carsi/federations/builtin/hkaf.json +12 -0
  29. package/carsi/paper_search_carsi/federations/builtin/kafe.json +11 -0
  30. package/carsi/paper_search_carsi/federations/builtin/openathens.json +21 -0
  31. package/carsi/paper_search_carsi/federations/builtin/sgaf.json +11 -0
  32. package/carsi/paper_search_carsi/federations/builtin/sifulan.json +11 -0
  33. package/carsi/paper_search_carsi/federations/schools.py +393 -0
  34. package/carsi/paper_search_carsi/progress_view.py +0 -2
  35. package/carsi/paper_search_carsi/report_sanitizer.py +15 -0
  36. package/carsi/pyproject.toml +1 -1
  37. package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.js +1 -1
  38. package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.js.map +1 -1
  39. package/dist/management/carsi/installer.d.ts.map +1 -1
  40. package/dist/management/carsi/installer.js +23 -16
  41. package/dist/management/carsi/installer.js.map +1 -1
  42. package/package.json +1 -1
  43. package/skills/paper-search/SKILL.md +4 -3
  44. package/skills/paper-search/references/browser-download.md +1 -1
  45. package/skills/paper-search/references/carsi-setup.md +9 -8
  46. package/skills/paper-search/references/cli-contract.md +2 -2
  47. package/skills/paper-search/references/federation-support.md +31 -0
  48. package/skills/paper-search/references/publisher-support.md +2 -2
  49. package/skills/paper-search/references/setup.md +1 -1
@@ -14,7 +14,7 @@ from urllib.parse import unquote, urljoin, urlparse
14
14
 
15
15
  from . import access_rules
16
16
  from .login_wait import LoginWait
17
- from .. import progress_reporter
17
+ from .. import federations, progress_reporter
18
18
  from .batch_common import (AWAY_WAIT_SEC, POLL_MS, DownloadResult, PublisherContentError, _is_browser_error,
19
19
  _is_navigation_cut, open_page, pump_until, settle)
20
20
 
@@ -263,7 +263,7 @@ class LoginMixin:
263
263
 
264
264
  @contextmanager
265
265
  def _login_wait_budget(self, result: DownloadResult, attribute: str, deadline: float, clock):
266
- wait = result._login_wait = LoginWait(deadline, clock, attribute=attribute)
266
+ wait = result._login_wait = LoginWait(deadline, clock, attribute=attribute, idle_limit=self.login_timeout_sec)
267
267
  try:
268
268
  yield wait
269
269
  finally:
@@ -277,7 +277,7 @@ class LoginMixin:
277
277
  own = self.adapter.complete_login(page, result)
278
278
  if own is not None:
279
279
  return own
280
- manual_selection = self.config.get("publisher_institution_federation") == "carsi"
280
+ manual_selection = self.federation is not None
281
281
  if self._institution_pdf_entitlement_missing(page):
282
282
  return False
283
283
  result.state = "sso_required"
@@ -363,9 +363,9 @@ class LoginMixin:
363
363
  break
364
364
  time.sleep(1) # each pass checks the page again: a step done goes on within a second
365
365
  if manual_selection and self.institution_query and not getattr(result, "_institution_not_listed", False):
366
- # A CARSI school list without the school ends the wait whatever this pass
366
+ # The federation's school list without the school ends the wait whatever this pass
367
367
  # would do next (Science, 2026-11-11: the list stood a whole page wait).
368
- self._check_carsi_school_links(page, result, str(getattr(page, "url", "") or ""))
368
+ self._check_federation_school_links(page, result, str(getattr(page, "url", "") or ""))
369
369
  if getattr(result, "_institution_not_listed", False):
370
370
  # The publisher's institution search has no entry for the school.
371
371
  result.reason = "institution_federation_unavailable"
@@ -679,14 +679,15 @@ class LoginMixin:
679
679
  return str(kind)
680
680
  return "duo" if "authentication with duo is required" in self._body_text(page, 2_000).lower() else ""
681
681
 
682
- def _federation_list_lacks_carsi(self, page: Any) -> str:
683
- """A federation list without CARSI: no route for a CARSI school, so waiting
682
+ def _federation_list_lacks_ours(self, page: Any) -> str:
683
+ """A federation list without the school's federation: no route for the school, so waiting
684
684
  for a login cannot succeed. One rule for every chooser: a <select> named a
685
685
  federation (its id or name, or its placeholder: BMJ's #shib-fed-select,
686
686
  AACR's #FederationDropdown "--Select a Federation--" listing only the UK,
687
687
  US and German federations, 2026-11-02) with two or more entries, none of
688
- them CARSI. The list and its entries, or "" (a list with CARSI, or none)."""
689
- if self.config.get("publisher_institution_federation") != "carsi":
688
+ them the school's federation. The list and its entries, or "" (a list with it, or none)."""
689
+ federation = self.federation
690
+ if federation is None:
690
691
  return ""
691
692
  for select in self._page_selects(page):
692
693
  options = [o for o in select.get("options") or () if isinstance(o, (list, tuple)) and len(o) == 2]
@@ -694,14 +695,14 @@ class LoginMixin:
694
695
  placeholder = str(options[0][1]) if options else ""
695
696
  entries = [str(label) for value, label in options if str(value).strip() and str(label).strip()]
696
697
  if (not (re.search(r"fed", name, re.I) or re.search(r"federation", placeholder, re.I)) or len(entries) < 2
697
- or any(self._CARSI_OPTION.search(label) for label in entries)):
698
+ or any(federation.matches(label) for label in entries)):
698
699
  continue
699
700
  return f"{name}: {', '.join(label[:40] for label in entries[:6])}"
700
701
  if self._on_publisher_host(str(getattr(page, "url", "") or "")):
701
702
  listing = page.locator(self._FEDERATION_LINK_LIST).first
702
703
  if listing.is_visible() is True:
703
704
  entries = [label.strip() for label in listing.get_by_role("link").all_text_contents() if label.strip()]
704
- if len(entries) >= 2 and not any(self._CARSI_OPTION.search(label) for label in entries):
705
+ if len(entries) >= 2 and not any(federation.matches(label) for label in entries):
705
706
  return f"federation links: {', '.join(label[:40] for label in entries[:6])}"
706
707
  return ""
707
708
 
@@ -709,7 +710,7 @@ class LoginMixin:
709
710
  """OpenAthens's "Find your institution" answers "No institutions found" for
710
711
  the configured school: it lists OpenAthens members, not CARSI schools
711
712
  (Sage's OpenAthens route: no CARSI school is listed, 2026-11-01)."""
712
- if (self.config.get("publisher_institution_federation") != "carsi"
713
+ if (self.federation is None
713
714
  or urlparse(str(getattr(page, "url", "") or "")).hostname != "login.openathens.net"):
714
715
  return False
715
716
  try:
@@ -746,9 +747,9 @@ class LoginMixin:
746
747
  line = self._denial_line(page)
747
748
  if line:
748
749
  return line
749
- lists = self._federation_list_lacks_carsi(page) if code == "institution_federation_unavailable" else ""
750
+ lists = self._federation_list_lacks_ours(page) if code == "institution_federation_unavailable" else ""
750
751
  if lists:
751
- return f"the federation list has no CARSI entry ({lists})"[:240]
752
+ return f"the federation list has no {self.federation.name} entry ({lists})"[:240]
752
753
  url = urlparse(str(getattr(page, "url", "") or ""))
753
754
  text = f"{self._title(page)}\n{self._body_text(page, 2_000)}"
754
755
  found = self._BLOCK_WORDS.search(text)
@@ -778,7 +779,7 @@ class LoginMixin:
778
779
  pass
779
780
  if self._publisher_access_blocked(page):
780
781
  return "publisher_access_blocked"
781
- if self._federation_list_lacks_carsi(page) or self._openathens_lacks_school(page):
782
+ if self._federation_list_lacks_ours(page) or self._openathens_lacks_school(page):
782
783
  return "institution_federation_unavailable"
783
784
  current_url = str(getattr(page, "url", "") or "").lower()
784
785
  haystack = f"{self._title(page)} {self._body_text(page, 2_000)}".lower()
@@ -1101,7 +1102,7 @@ class LoginMixin:
1101
1102
  # The federation page is already an SSO step. Generic OpenAthens
1102
1103
  # text/ancestor matching can click its logo or account sign-in.
1103
1104
  return False
1104
- if self.config.get("publisher_institution_federation") == "carsi":
1105
+ if self.federation is not None:
1105
1106
  return self._click_manual_institution_entry(page, result)
1106
1107
  sso_selectors = (
1107
1108
  "button:has-text('Access Through Your Institution')",
@@ -1255,7 +1256,7 @@ class LoginMixin:
1255
1256
  if not _is_browser_error(exc):
1256
1257
  raise
1257
1258
  controls = []
1258
- labels = (sorted(self._INSTITUTION_ENTRY_LABELS) if self.config.get("publisher_institution_federation") == "carsi"
1259
+ labels = (sorted(self._INSTITUTION_ENTRY_LABELS) if self.federation is not None
1259
1260
  else list(self.profile.sso_text_markers))
1260
1261
  found = "; ".join(str(c) for c in controls[:8]) if isinstance(controls, list) and controls else "none"
1261
1262
  return (f"looked for: entries ({', '.join(labels)}); access menus (get access, access options, "
@@ -1345,18 +1346,20 @@ class LoginMixin:
1345
1346
  # "Find your institution" (Sage's OpenAthens route, 2026-11-01); the
1346
1347
  # OpenAthens account form there has a password field and stays the user's.
1347
1348
  ("login.openathens.net", "/auth"),
1348
- ("ds.carsi.edu.cn", "/"),
1349
+ # The federations' own discovery pages (CARSI's) come from the federation layer.
1349
1350
  # SeamlessAccess's discovery page behind its button (AIP, 2026-11-03): it was
1350
1351
  # taken for the user's own login and the school was typed by hand.
1351
1352
  ("service.seamlessaccess.org", "/ds"),
1352
1353
  )
1353
1354
 
1354
1355
  def _is_federation_chooser(self, url: str) -> bool:
1356
+ if self._on_school_login_page(url):
1357
+ return False # the school's own sign-in page on a shared service is the user's
1355
1358
  if self.adapter.is_institution_chooser(url):
1356
1359
  return True
1357
1360
  parsed = urlparse(url)
1358
- return parsed.scheme == "https" and any(
1359
- parsed.hostname == host and parsed.path.startswith(path) for host, path in self._FEDERATION_CHOOSERS)
1361
+ return parsed.scheme == "https" and (federations.on_discovery_page(url) or any(
1362
+ parsed.hostname == host and parsed.path.startswith(path) for host, path in self._FEDERATION_CHOOSERS))
1360
1363
 
1361
1364
  def _on_publisher_host(self, url: str) -> bool:
1362
1365
  """The publisher's own site: a profile domain, or an article page its
@@ -1383,7 +1386,13 @@ class LoginMixin:
1383
1386
  and (not self.institution_query or bool(getattr(self, "_manual_school", False))))
1384
1387
 
1385
1388
  def _idp_user_action(self, page: Any) -> bool:
1386
- if not self._is_idp_host(urlparse(str(getattr(page, "url", "") or "")).netloc):
1389
+ url = str(getattr(page, "url", "") or "")
1390
+ if self._on_school_login_page(url):
1391
+ # The school's own page on a shared service: choosing how to sign in
1392
+ # there is the user's step too (a school's OpenAthens page offering
1393
+ # staff and guest sign-in, no field, 2026-11-11).
1394
+ return True
1395
+ if not self._is_idp_host(urlparse(url).netloc):
1387
1396
  return False
1388
1397
  if self._idp_confirmation(page):
1389
1398
  return True
@@ -1412,7 +1421,11 @@ class LoginMixin:
1412
1421
  && !el.disabled && !el.readOnly && ['text','email','tel'].includes(el.type));
1413
1422
  const qr = [...document.querySelectorAll('img,canvas,[role="img"]')].some(el => visible(el)
1414
1423
  && /qr|二维码|扫码/i.test([el.id,el.className,el.getAttribute('alt'),el.getAttribute('aria-label')].join(' ')));
1415
- return input || qr;
1424
+ // A button the identity provider waits on (set up a passkey, choose an
1425
+ // account: a school's Okta page, 2026-11-11).
1426
+ const button = [...document.querySelectorAll('button,input[type=submit],input[type=button],[role=button]')]
1427
+ .some(el => visible(el) && !el.disabled && (el.innerText || el.value || el.getAttribute('aria-label') || '').trim());
1428
+ return input || qr || button;
1416
1429
  }""") is True
1417
1430
 
1418
1431
  def _login_wait_page(self, page: Any) -> str:
@@ -1737,7 +1750,9 @@ class LoginMixin:
1737
1750
  return False
1738
1751
 
1739
1752
  def _click_openathens_entry(self, page: Any, result: DownloadResult) -> bool:
1740
- if self.config.get("publisher_institution_federation") == "carsi":
1753
+ # A federation's school does not sign in through OpenAthens, unless that
1754
+ # is its route (the federation layer's ``openathens_entries``).
1755
+ if self.federation is not None and not self.federation.openathens_entries:
1741
1756
  return False
1742
1757
  current_url = str(getattr(page, "url", "") or "")
1743
1758
  lower_url = current_url.lower()
@@ -1795,7 +1810,7 @@ class LoginMixin:
1795
1810
  matching the user's configured institution; otherwise a chooser page is
1796
1811
  left entirely to the user (no default option is ever submitted).
1797
1812
  """
1798
- if self.config.get("publisher_institution_federation") == "carsi" and not after_selection:
1813
+ if self.federation is not None and not after_selection:
1799
1814
  return
1800
1815
  if not after_selection and self._page_has_institution_chooser(page):
1801
1816
  if not any(e["state"] == "institution_continue_withheld" for e in result.events):
@@ -525,7 +525,8 @@ class UserWaitMixin:
525
525
  manual = True
526
526
  from .login_wait import LoginWait
527
527
  verification_deadline = deadline
528
- verification_wait = result._verification_wait = LoginWait(deadline, time.time)
528
+ verification_wait = result._verification_wait = LoginWait(
529
+ deadline, time.time, idle_limit=self.login_timeout_sec)
529
530
  verification_wait.observe(page, True)
530
531
  self._verification_attention(result, deadline)
531
532
  self._event(result, "challenge_manual_wait", "complete verification in visible browser")
@@ -15,11 +15,14 @@ from __future__ import annotations
15
15
  import html
16
16
  import json
17
17
  import re
18
+ import shutil
18
19
  import time
19
20
  from pathlib import Path
20
21
  from typing import Any
21
22
  from urllib.parse import urlparse
22
23
 
24
+ from .. import federations
25
+ from ..federations import schools
23
26
  from ..log import get_logger
24
27
 
25
28
  log = get_logger()
@@ -60,6 +63,17 @@ _FAILURE_KINDS = {
60
63
  }
61
64
 
62
65
 
66
+ def _move_into_place(src: Path, output_path: Path) -> None:
67
+ """Put a captured PDF at ``output_path``. The backend saves it in its run folder
68
+ first, which is in PaperSearch's own data (since 0.5.13) and can sit on another
69
+ drive than the download folder: a rename cannot cross drives (WinError 17, Windows
70
+ with D:\\Downloads, 2026-11-11), so the file is moved, copied when it must."""
71
+ output_path.parent.mkdir(parents=True, exist_ok=True)
72
+ if output_path.exists():
73
+ output_path.unlink()
74
+ shutil.move(str(src), str(output_path))
75
+
76
+
63
77
  def _remember_blocked_journal(doi: str, identity: dict[str, Any]) -> None:
64
78
  """The journal whose site blocked the current network (``blocked_journals``)."""
65
79
  from .. import blocked_journals
@@ -136,7 +150,7 @@ def try_institutional(
136
150
 
137
151
  # Mode 1: External instsci package — full cascade
138
152
  # The external adapter does not carry the explicit federation choice.
139
- if config.get("publisher_institution_federation") != "carsi":
153
+ if federations.configured(config) is None:
140
154
  result = _try_external_instsci(doi, output_path, config)
141
155
  if result:
142
156
  return result
@@ -148,10 +162,7 @@ def try_institutional(
148
162
 
149
163
 
150
164
  def _any_institutional_configured(config: dict[str, Any]) -> bool:
151
- return bool(
152
- config.get("publisher_institution_federation") == "carsi"
153
- or (config.get("carsi_enabled") and config.get("carsi_idp_name", "").strip())
154
- )
165
+ return schools.institutional_configured(config)
155
166
 
156
167
 
157
168
  # ---------------------------------------------------------------------------
@@ -189,20 +200,20 @@ def _try_external_instsci(
189
200
  return _instsci_result_to_dict(result, doi, output_path)
190
201
 
191
202
 
192
- def _map_to_instsci_config(carsi_config: dict[str, Any], output_path: Path):
203
+ def _map_to_instsci_config(backend_config: dict[str, Any], output_path: Path):
193
204
  from instsci.config import Config as InstSciConfig
194
205
  # This backend has no WebVPN or EZProxy route: the package gets none either.
195
206
  return InstSciConfig(
196
207
  school="",
197
208
  webvpn_base_url="",
198
209
  ezproxy_base_url="",
199
- email=carsi_config.get("email", ""),
200
- elsevier_api_key=carsi_config.get("elsevier_api_key", ""),
201
- elsevier_inst_token=carsi_config.get("elsevier_insttoken", ""),
202
- carsi_enabled=carsi_config.get("carsi_enabled", False),
203
- carsi_idp_name=carsi_config.get("carsi_idp_name", ""),
210
+ email=backend_config.get("email", ""),
211
+ elsevier_api_key=backend_config.get("elsevier_api_key", ""),
212
+ elsevier_inst_token=backend_config.get("elsevier_insttoken", ""),
213
+ carsi_enabled=backend_config.get("carsi_enabled", False),
214
+ carsi_idp_name=backend_config.get("carsi_idp_name", ""),
204
215
  output_dir=str(output_path.parent),
205
- cache_dir=carsi_config.get("cache_dir", ""),
216
+ cache_dir=backend_config.get("cache_dir", ""),
206
217
  )
207
218
 
208
219
 
@@ -216,10 +227,7 @@ def _instsci_result_to_dict(result, doi: str, output_path: Path) -> dict[str, An
216
227
  src = Path(paper.pdf_path)
217
228
  if src.exists():
218
229
  if src != output_path:
219
- output_path.parent.mkdir(parents=True, exist_ok=True)
220
- if output_path.exists():
221
- output_path.unlink()
222
- src.rename(output_path)
230
+ _move_into_place(src, output_path)
223
231
  return {
224
232
  "success": True, "identifier": doi, "doi": doi,
225
233
  "file": str(output_path),
@@ -271,7 +279,7 @@ def _try_builtin_institutional(
271
279
  getattr(profile, "name", ""))
272
280
 
273
281
  failures: list[dict[str, str]] = []
274
- manual_carsi = config.get("publisher_institution_federation") == "carsi"
282
+ manual_school = federations.configured(config) is not None
275
283
 
276
284
  # Remembered entitlement decisions (progress-window buttons): a journal or
277
285
  # publisher the user marked as "no access" is skipped before any browser.
@@ -343,7 +351,7 @@ def _try_builtin_institutional(
343
351
  # jobs cannot propagate the federation/manual-selection policy.
344
352
  if profile:
345
353
  log.info(" [Institutional] Publisher driver (%s)", getattr(profile, "name", ""))
346
- if not manual_carsi:
354
+ if not manual_school:
347
355
  result = _try_session_broker(doi, output_path, config, profile)
348
356
  if accept(result, "institutional:session_broker"):
349
357
  return result
@@ -368,7 +376,7 @@ def _try_builtin_institutional(
368
376
  "action": primary["action"], "source_failures": failures}
369
377
  if primary["error_type"] == "access_blocked":
370
378
  _remember_blocked_journal(doi, identity)
371
- if primary["error_type"] == "institution_federation_unavailable" and manual_carsi:
379
+ if primary["error_type"] == "institution_federation_unavailable" and manual_school:
372
380
  _remember_missing_route(publisher_name, config, doi)
373
381
  if "reason_code" in primary:
374
382
  result["reason_code"] = primary["reason_code"]
@@ -457,10 +465,7 @@ def _try_session_broker(
457
465
  if pdf_path and Path(pdf_path).exists():
458
466
  src = Path(pdf_path)
459
467
  if src != output_path:
460
- output_path.parent.mkdir(parents=True, exist_ok=True)
461
- if output_path.exists():
462
- output_path.unlink()
463
- src.rename(output_path)
468
+ _move_into_place(src, output_path)
464
469
  log.info(f" [Institutional] Session broker download succeeded")
465
470
  return {
466
471
  "success": True, "identifier": doi, "doi": doi,
@@ -507,9 +512,8 @@ def _try_browser_batch_download(
507
512
 
508
513
  # The caller's title checks the PDF when the article page names none (orchestrator).
509
514
  record = PaperRecord(doi=doi, title=str(config.get("record_title") or ""))
510
- # The institution name is the user's own setting (explicit CARSI); empty means "choose by hand".
511
- institution_query = (config.get("carsi_idp_name", "") if config.get("publisher_institution_federation") == "carsi"
512
- else "")
515
+ # The institution name is the user's own setting (with its federation); empty means "choose by hand".
516
+ institution_query = schools.name(config) if federations.configured(config) else ""
513
517
  login_timeout = config.get("browser_login_timeout", 180)
514
518
 
515
519
  downloader = PublisherBatchDownloader(
@@ -630,10 +634,7 @@ def _try_browser_batch_download(
630
634
  src = Path(result.pdf_path)
631
635
  if src.exists():
632
636
  if src != output_path:
633
- output_path.parent.mkdir(parents=True, exist_ok=True)
634
- if output_path.exists():
635
- output_path.unlink()
636
- src.rename(output_path)
637
+ _move_into_place(src, output_path)
637
638
  result.pdf_path = str(output_path)
638
639
  _note_supplements(result, len(getattr(result, "events", [])))
639
640
  log.info(f" [Institutional] Browser download succeeded: {result.size_bytes:,} bytes")
@@ -2,6 +2,10 @@
2
2
 
3
3
  Only events inside the dedicated login document are counted. No field values,
4
4
  key contents, system input hooks or foreground-window observations are used.
5
+
6
+ The stop has a limit (``idle_limit``, the login wait): once that long has passed
7
+ since the user's last input, the time since that input counts again, so a stray
8
+ click on the login page cannot hold a batch forever (the user, 2026-11-11).
5
9
  """
6
10
  from __future__ import annotations
7
11
 
@@ -50,10 +54,13 @@ _REMOVE_ACTIVITY = """token => {
50
54
 
51
55
 
52
56
  class LoginWait:
53
- def __init__(self, deadline: float, clock: Callable[[], float], *, attribute: str = ""):
57
+ def __init__(self, deadline: float, clock: Callable[[], float], *, attribute: str = "",
58
+ idle_limit: float | None = None):
54
59
  self._deadline = deadline
55
60
  self._clock = clock
56
61
  self._paused_at: float | None = None
62
+ self._last_input: float | None = None
63
+ self._idle_limit = idle_limit
57
64
  self._token = uuid4().hex
58
65
  self._frames: dict[Any, int] = {}
59
66
  self.user_step = False
@@ -76,8 +83,22 @@ class LoginWait:
76
83
 
77
84
  def take_over(self) -> None:
78
85
  """An explicit capsule request counts only during a human login step."""
79
- if self.user_step and not self.paused:
80
- self._paused_at = self._clock()
86
+ if self.user_step:
87
+ now = self._clock()
88
+ self._last_input = now
89
+ if not self.paused:
90
+ self._paused_at = now
91
+
92
+ def _resume_when_idle(self) -> None:
93
+ """No input for ``idle_limit``: the stop ends at the last input, and the
94
+ time since then counts as waiting."""
95
+ if self._paused_at is None or self._idle_limit is None or self._last_input is None:
96
+ return
97
+ now = self._clock()
98
+ if now - self._last_input >= self._idle_limit:
99
+ self._account()
100
+ self._deadline -= now - self._last_input
101
+ self._paused_at = None
81
102
 
82
103
  def exclude_elapsed(self, seconds: float) -> None:
83
104
  """A nested manual verification already accounted for this time."""
@@ -103,6 +124,7 @@ class LoginWait:
103
124
  self._frames[frame] = count
104
125
  if count > 0 and count != previous:
105
126
  self.take_over()
127
+ self._resume_when_idle()
106
128
 
107
129
  def _remove_listeners(self) -> None:
108
130
  frames, self._frames = self._frames, {}
@@ -0,0 +1,67 @@
1
+ """The shared rule for a site without a supplementary-file rule of its own: the
2
+ files the article page itself lists as its supplementary material.
3
+
4
+ A link counts only inside the page's supplementary part (an element whose class
5
+ or id says so, or the part under a "Supplementary data", "Supplemental
6
+ material" or "Supporting information" heading), only when its address names this
7
+ article's DOI ("/" kept, or as "_") between two "/", and only when it ends in a
8
+ file name. The DOI in the address binds the file to this article; a page's links
9
+ to other articles, datasets or web pages are no files of it (the Journal of
10
+ Experimental Medicine's tables on its own CDN, 2026-11-11).
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import re
15
+ from typing import Any
16
+ from urllib.parse import unquote, urlparse
17
+
18
+ from ..adapters.base import SupplementLink
19
+
20
+ _SECTION_LINKS_JS = r"""() => {
21
+ const part = '[class*="suppl" i], [id*="suppl" i], [class*="datasupp" i], [class*="supporting" i], [id*="supporting" i]';
22
+ const heading = /^(?:online )?(?:supplementa(?:ry|l) (?:data|materials?|information|files?)|supporting information)$/i;
23
+ const headed = [...document.querySelectorAll('h1, h2, h3, h4, h5, h6, [role="heading"]')]
24
+ .filter(h => heading.test((h.textContent || '').replace(/\s+/g, ' ').trim()) && h.parentElement)
25
+ .map(h => h.parentElement);
26
+ return {
27
+ doi: document.querySelector('meta[name="citation_doi"]')?.content || '',
28
+ rows: [...document.querySelectorAll('a[href]')]
29
+ .filter(a => a.closest(part) || headed.some(p => p.contains(a)))
30
+ .map(a => ({href: a.href, label: (a.innerText || a.getAttribute('title') || '').replace(/\s+/g, ' ').trim().slice(0, 200)}))
31
+ };
32
+ }"""
33
+ # Addresses that end in a web page, not a file (figure slides are .aspx).
34
+ _WEB_PAGES = frozenset({"html", "htm", "xhtml", "shtml", "asp", "aspx", "php", "jsp", "cfm"})
35
+
36
+
37
+ def listed_files(page: Any, doi: str) -> list[SupplementLink]:
38
+ """This article's files in its page's supplementary part (see the module); a
39
+ page that names another article in ``citation_doi`` lists none. A file linked
40
+ several times (signed addresses differ in their query) is taken once."""
41
+ doi = (doi or "").strip().lower()
42
+ data = page.evaluate(_SECTION_LINKS_JS)
43
+ if not doi or not isinstance(data, dict):
44
+ return []
45
+ page_doi = str(data.get("doi") or "").strip().lower()
46
+ if page_doi and page_doi != doi:
47
+ return []
48
+ forms = (f"/{doi}/", f"/{doi.replace('/', '_')}/")
49
+ links: list[SupplementLink] = []
50
+ seen: set[tuple[str, str]] = set()
51
+ rows = data.get("rows")
52
+ for row in rows if isinstance(rows, list) else ():
53
+ if not isinstance(row, dict):
54
+ continue
55
+ target = urlparse(str(row.get("href") or ""))
56
+ path = unquote(target.path)
57
+ name = path.rsplit("/", 1)[-1]
58
+ extension = name.rpartition(".")[2].lower() if "." in name else ""
59
+ if (target.scheme != "https" or not target.hostname or target.username or target.password
60
+ or not any(form in path.lower() for form in forms)
61
+ or not re.fullmatch(r"[a-z0-9]{1,5}", extension) or extension in _WEB_PAGES):
62
+ continue
63
+ key = (target.hostname.lower(), path)
64
+ if key not in seen:
65
+ seen.add(key)
66
+ links.append(SupplementLink(target._replace(fragment="").geturl(), str(row.get("label") or "")))
67
+ return links
@@ -0,0 +1,155 @@
1
+ """Identity federations: which one the user's school belongs to, how publishers'
2
+ choosers name it, and its own school-choosing pages.
3
+
4
+ The federation layer stands beside the publisher layers (engine, platforms,
5
+ publishers, journals; ADR 0014). Publisher rules never name a federation: they
6
+ ask the configured one whether a chooser's entry is it (``Federation.matches``).
7
+ Each federation is one data file in ``builtin/`` (``schema`` below); one whose
8
+ own pages need code gets a module of its own. No school is named here (ADR
9
+ 0009): the school is the user's setting (``schools``).
10
+
11
+ ``builtin/<code>.json``:
12
+
13
+ - ``code``: the value of ``publisher_institution_federation`` ("carsi").
14
+ - ``name``: its short name, as users and the records call it.
15
+ - ``country``: ISO 3166 code of the country it serves.
16
+ - ``registration_authorities``: its registrationAuthority in SAML metadata,
17
+ which tells a school's federation in SeamlessAccess and eduGAIN.
18
+ - ``chooser_labels``: its entry on publishers' federation choosers, as seen;
19
+ ``chooser_pattern`` (a regular expression) matches any of them.
20
+ - ``discovery_hosts``: its own school-choosing pages (none for most).
21
+ - ``service_domains``: the domains of its own services, which remember a
22
+ chosen school (forgotten by a cold start).
23
+ - ``metadata_url``: its published member list (SAML metadata), for the
24
+ schools' login hosts; empty when its own list is read instead
25
+ (``member_list``: "carsi").
26
+ - ``kind``: "federation" (a national identity federation, the default) or
27
+ "service" (OpenAthens: an identity service across countries, which the
28
+ publisher layers know on their own and may name).
29
+ - ``secondary``: a school's entry here is used only when it has none in a
30
+ federation (a school in both GakuNin and OpenAthens signs in through GakuNin).
31
+ - ``openathens_entries``: the publishers' "OpenAthens" sign-in entries and the
32
+ OpenAthens wayfinder lead to the schools of this route.
33
+ - ``school_login_pages``: where its schools' own login pages begin on a service
34
+ shared by all of them: ``{scope}`` stands for the school's domain, ``*`` for any
35
+ one path segment (OpenAthens: ``https://login.openathens.net/auth/*/o/``, an
36
+ organization's own sign-in page; its search page has no ``/o/``, and the
37
+ segment is the organization's OpenAthens name, not always the school's domain).
38
+ - ``without_school``: it may be switched on with no school saved, the user
39
+ choosing in the window (``setup --carsi``); any other route counts only once
40
+ setup saved the school for it.
41
+ """
42
+ from __future__ import annotations
43
+
44
+ import json
45
+ import re
46
+ from dataclasses import dataclass
47
+ from functools import lru_cache
48
+ from pathlib import Path
49
+ from typing import Any, Iterable
50
+ from urllib.parse import urlparse
51
+
52
+ _BUILTIN = Path(__file__).with_name("builtin")
53
+
54
+
55
+ @dataclass(frozen=True)
56
+ class Federation:
57
+ code: str
58
+ name: str
59
+ country: str
60
+ registration_authorities: tuple[str, ...]
61
+ chooser_labels: tuple[str, ...]
62
+ chooser_pattern: re.Pattern[str]
63
+ discovery_hosts: tuple[str, ...] = ()
64
+ service_domains: tuple[str, ...] = ()
65
+ metadata_url: str = ""
66
+ member_list: str = ""
67
+ kind: str = "federation"
68
+ secondary: bool = False
69
+ openathens_entries: bool = False
70
+ without_school: bool = False
71
+ school_login_pages: tuple[str, ...] = ()
72
+
73
+ def matches(self, label: str) -> bool:
74
+ """This federation's entry on a publisher's federation chooser."""
75
+ return bool(self.chooser_pattern.search(" ".join(str(label or "").split())))
76
+
77
+ def option_among(self, labels: Iterable[str]) -> str | None:
78
+ """The one entry among ``labels`` that is this federation, else None."""
79
+ hits = [label for label in labels if self.matches(label)]
80
+ return hits[0] if len(hits) == 1 else None
81
+
82
+ def on_discovery_page(self, url: str) -> bool:
83
+ """``url`` is one of this federation's own school-choosing pages."""
84
+ host = (urlparse(url or "").hostname or "").lower()
85
+ return any(host == h or host.endswith("." + h) for h in self.discovery_hosts)
86
+
87
+
88
+ def _load(path: Path) -> Federation:
89
+ data = json.loads(path.read_text(encoding="utf-8"))
90
+ code = str(data["code"]).strip().lower()
91
+ if code != path.stem:
92
+ raise ValueError(f"{path.name}: code {code!r} differs from the file name")
93
+ labels = tuple(str(label) for label in data.get("chooser_labels") or ())
94
+ pattern = re.compile(str(data["chooser_pattern"]), re.I)
95
+ for label in labels:
96
+ if not pattern.search(label):
97
+ raise ValueError(f"{path.name}: chooser_pattern does not match {label!r}")
98
+ for template in data.get("school_login_pages") or ():
99
+ if not ("{scope}" in str(template) or "*" in str(template)) or not str(template).startswith("https://"):
100
+ raise ValueError(f"{path.name}: school_login_pages needs https:// and {{scope}} or *: {template!r}")
101
+ return Federation(
102
+ code=code,
103
+ name=str(data["name"]),
104
+ country=str(data["country"]).upper(),
105
+ registration_authorities=tuple(str(ra).rstrip("/").lower() for ra in data["registration_authorities"]),
106
+ chooser_labels=labels,
107
+ chooser_pattern=pattern,
108
+ discovery_hosts=tuple(str(h).lower() for h in data.get("discovery_hosts") or ()),
109
+ service_domains=tuple(str(h).lower() for h in data.get("service_domains") or ()),
110
+ metadata_url=str(data.get("metadata_url") or ""),
111
+ member_list=str(data.get("member_list") or ""),
112
+ kind=str(data.get("kind") or "federation"),
113
+ secondary=bool(data.get("secondary")),
114
+ openathens_entries=bool(data.get("openathens_entries")),
115
+ without_school=bool(data.get("without_school")),
116
+ school_login_pages=tuple(str(t) for t in data.get("school_login_pages") or ()),
117
+ )
118
+
119
+
120
+ @lru_cache(maxsize=1)
121
+ def all_federations() -> tuple[Federation, ...]:
122
+ """Every built-in federation, CARSI first (the default)."""
123
+ found = [_load(path) for path in sorted(_BUILTIN.glob("*.json"))]
124
+ return tuple(sorted(found, key=lambda f: (f.code != "carsi", f.code)))
125
+
126
+
127
+ def by_code(code: str | None) -> Federation | None:
128
+ code = str(code or "").strip().lower()
129
+ return next((f for f in all_federations() if f.code == code), None)
130
+
131
+
132
+ def by_registration_authority(authority: str) -> Federation | None:
133
+ """The built-in federation that registered a school ("https://hkaf.edu.hk")."""
134
+ key = str(authority or "").strip().rstrip("/").lower()
135
+ return next((f for f in all_federations() if key in f.registration_authorities), None)
136
+
137
+
138
+ def configured(config: dict[str, Any]) -> Federation | None:
139
+ """The federation the user's school belongs to (``publisher_institution_federation``);
140
+ None when none is set, or a route other than one switched on ``without_school``
141
+ has no school saved (a value an old config file may hold)."""
142
+ federation = by_code(config.get("publisher_institution_federation"))
143
+ if federation is None or federation.without_school or str(config.get("carsi_idp_name") or "").strip():
144
+ return federation
145
+ return None
146
+
147
+
148
+ def on_discovery_page(url: str) -> bool:
149
+ """``url`` is a built-in federation's own school-choosing page."""
150
+ return any(federation.on_discovery_page(url) for federation in all_federations())
151
+
152
+
153
+ def service_domains() -> tuple[str, ...]:
154
+ """Every built-in federation's own service domains."""
155
+ return tuple(domain for federation in all_federations() for domain in federation.service_domains)