papersearch 0.5.15 → 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.
- package/README.en.md +28 -9
- package/README.md +28 -9
- package/carsi/paper_search_carsi/adapters/base.py +7 -0
- package/carsi/paper_search_carsi/adapters/elsevier/__init__.py +23 -3
- package/carsi/paper_search_carsi/adapters/ieee/__init__.py +1 -1
- package/carsi/paper_search_carsi/adapters/platforms/atypon/__init__.py +14 -11
- package/carsi/paper_search_carsi/adapters/sage/__init__.py +2 -4
- package/carsi/paper_search_carsi/adapters/thieme/__init__.py +12 -10
- package/carsi/paper_search_carsi/adapters/world_scientific/__init__.py +2 -1
- package/carsi/paper_search_carsi/cli.py +65 -22
- package/carsi/paper_search_carsi/cold_start.py +3 -1
- package/carsi/paper_search_carsi/config.py +10 -3
- package/carsi/paper_search_carsi/download_diagnostics.py +1 -1
- package/carsi/paper_search_carsi/engine/batch_access.py +3 -2
- package/carsi/paper_search_carsi/engine/batch_diagnostics.py +1 -1
- package/carsi/paper_search_carsi/engine/batch_institution.py +199 -79
- package/carsi/paper_search_carsi/engine/batch_login.py +39 -24
- package/carsi/paper_search_carsi/engine/batch_waits.py +2 -1
- package/carsi/paper_search_carsi/engine/bridge.py +16 -18
- package/carsi/paper_search_carsi/engine/login_wait.py +25 -3
- package/carsi/paper_search_carsi/federations/__init__.py +155 -0
- package/carsi/paper_search_carsi/federations/builtin/carsi.json +22 -0
- package/carsi/paper_search_carsi/federations/builtin/gakunin.json +11 -0
- package/carsi/paper_search_carsi/federations/builtin/hkaf.json +12 -0
- package/carsi/paper_search_carsi/federations/builtin/kafe.json +11 -0
- package/carsi/paper_search_carsi/federations/builtin/openathens.json +21 -0
- package/carsi/paper_search_carsi/federations/builtin/sgaf.json +11 -0
- package/carsi/paper_search_carsi/federations/builtin/sifulan.json +11 -0
- package/carsi/paper_search_carsi/federations/schools.py +393 -0
- package/carsi/paper_search_carsi/report_sanitizer.py +15 -0
- package/carsi/pyproject.toml +1 -1
- package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.js +1 -1
- package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.js.map +1 -1
- package/dist/management/carsi/installer.d.ts.map +1 -1
- package/dist/management/carsi/installer.js +23 -16
- package/dist/management/carsi/installer.js.map +1 -1
- package/package.json +1 -1
- package/skills/paper-search/SKILL.md +4 -3
- package/skills/paper-search/references/carsi-setup.md +9 -8
- package/skills/paper-search/references/cli-contract.md +1 -1
- package/skills/paper-search/references/federation-support.md +31 -0
- 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.
|
|
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
|
-
#
|
|
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.
|
|
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
|
|
683
|
-
"""A federation list without
|
|
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
|
|
689
|
-
|
|
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(
|
|
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(
|
|
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.
|
|
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.
|
|
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
|
|
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.
|
|
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.
|
|
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.
|
|
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
|
-
(
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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.
|
|
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(
|
|
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")
|
|
@@ -21,6 +21,8 @@ from pathlib import Path
|
|
|
21
21
|
from typing import Any
|
|
22
22
|
from urllib.parse import urlparse
|
|
23
23
|
|
|
24
|
+
from .. import federations
|
|
25
|
+
from ..federations import schools
|
|
24
26
|
from ..log import get_logger
|
|
25
27
|
|
|
26
28
|
log = get_logger()
|
|
@@ -148,7 +150,7 @@ def try_institutional(
|
|
|
148
150
|
|
|
149
151
|
# Mode 1: External instsci package — full cascade
|
|
150
152
|
# The external adapter does not carry the explicit federation choice.
|
|
151
|
-
if
|
|
153
|
+
if federations.configured(config) is None:
|
|
152
154
|
result = _try_external_instsci(doi, output_path, config)
|
|
153
155
|
if result:
|
|
154
156
|
return result
|
|
@@ -160,10 +162,7 @@ def try_institutional(
|
|
|
160
162
|
|
|
161
163
|
|
|
162
164
|
def _any_institutional_configured(config: dict[str, Any]) -> bool:
|
|
163
|
-
return
|
|
164
|
-
config.get("publisher_institution_federation") == "carsi"
|
|
165
|
-
or (config.get("carsi_enabled") and config.get("carsi_idp_name", "").strip())
|
|
166
|
-
)
|
|
165
|
+
return schools.institutional_configured(config)
|
|
167
166
|
|
|
168
167
|
|
|
169
168
|
# ---------------------------------------------------------------------------
|
|
@@ -201,20 +200,20 @@ def _try_external_instsci(
|
|
|
201
200
|
return _instsci_result_to_dict(result, doi, output_path)
|
|
202
201
|
|
|
203
202
|
|
|
204
|
-
def _map_to_instsci_config(
|
|
203
|
+
def _map_to_instsci_config(backend_config: dict[str, Any], output_path: Path):
|
|
205
204
|
from instsci.config import Config as InstSciConfig
|
|
206
205
|
# This backend has no WebVPN or EZProxy route: the package gets none either.
|
|
207
206
|
return InstSciConfig(
|
|
208
207
|
school="",
|
|
209
208
|
webvpn_base_url="",
|
|
210
209
|
ezproxy_base_url="",
|
|
211
|
-
email=
|
|
212
|
-
elsevier_api_key=
|
|
213
|
-
elsevier_inst_token=
|
|
214
|
-
carsi_enabled=
|
|
215
|
-
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", ""),
|
|
216
215
|
output_dir=str(output_path.parent),
|
|
217
|
-
cache_dir=
|
|
216
|
+
cache_dir=backend_config.get("cache_dir", ""),
|
|
218
217
|
)
|
|
219
218
|
|
|
220
219
|
|
|
@@ -280,7 +279,7 @@ def _try_builtin_institutional(
|
|
|
280
279
|
getattr(profile, "name", ""))
|
|
281
280
|
|
|
282
281
|
failures: list[dict[str, str]] = []
|
|
283
|
-
|
|
282
|
+
manual_school = federations.configured(config) is not None
|
|
284
283
|
|
|
285
284
|
# Remembered entitlement decisions (progress-window buttons): a journal or
|
|
286
285
|
# publisher the user marked as "no access" is skipped before any browser.
|
|
@@ -352,7 +351,7 @@ def _try_builtin_institutional(
|
|
|
352
351
|
# jobs cannot propagate the federation/manual-selection policy.
|
|
353
352
|
if profile:
|
|
354
353
|
log.info(" [Institutional] Publisher driver (%s)", getattr(profile, "name", ""))
|
|
355
|
-
if not
|
|
354
|
+
if not manual_school:
|
|
356
355
|
result = _try_session_broker(doi, output_path, config, profile)
|
|
357
356
|
if accept(result, "institutional:session_broker"):
|
|
358
357
|
return result
|
|
@@ -377,7 +376,7 @@ def _try_builtin_institutional(
|
|
|
377
376
|
"action": primary["action"], "source_failures": failures}
|
|
378
377
|
if primary["error_type"] == "access_blocked":
|
|
379
378
|
_remember_blocked_journal(doi, identity)
|
|
380
|
-
if primary["error_type"] == "institution_federation_unavailable" and
|
|
379
|
+
if primary["error_type"] == "institution_federation_unavailable" and manual_school:
|
|
381
380
|
_remember_missing_route(publisher_name, config, doi)
|
|
382
381
|
if "reason_code" in primary:
|
|
383
382
|
result["reason_code"] = primary["reason_code"]
|
|
@@ -513,9 +512,8 @@ def _try_browser_batch_download(
|
|
|
513
512
|
|
|
514
513
|
# The caller's title checks the PDF when the article page names none (orchestrator).
|
|
515
514
|
record = PaperRecord(doi=doi, title=str(config.get("record_title") or ""))
|
|
516
|
-
# The institution name is the user's own setting (
|
|
517
|
-
institution_query = (config
|
|
518
|
-
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 ""
|
|
519
517
|
login_timeout = config.get("browser_login_timeout", 180)
|
|
520
518
|
|
|
521
519
|
downloader = PublisherBatchDownloader(
|
|
@@ -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
|
|
80
|
-
|
|
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,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)
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
{
|
|
2
|
+
"code": "carsi",
|
|
3
|
+
"name": "CARSI",
|
|
4
|
+
"country": "CN",
|
|
5
|
+
"registration_authorities": [
|
|
6
|
+
"https://www.carsi.edu.cn"
|
|
7
|
+
],
|
|
8
|
+
"chooser_labels": [
|
|
9
|
+
"China CERNET Federation (CARSI)",
|
|
10
|
+
"China (CARSI)"
|
|
11
|
+
],
|
|
12
|
+
"chooser_pattern": "\\bCARSI\\b",
|
|
13
|
+
"discovery_hosts": [
|
|
14
|
+
"ds.carsi.edu.cn"
|
|
15
|
+
],
|
|
16
|
+
"service_domains": [
|
|
17
|
+
"carsi.edu.cn"
|
|
18
|
+
],
|
|
19
|
+
"metadata_url": "",
|
|
20
|
+
"member_list": "carsi",
|
|
21
|
+
"without_school": true
|
|
22
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
{
|
|
2
|
+
"code": "gakunin",
|
|
3
|
+
"name": "GakuNin",
|
|
4
|
+
"country": "JP",
|
|
5
|
+
"registration_authorities": ["https://www.gakunin.jp"],
|
|
6
|
+
"chooser_labels": ["Academic Access Management Federation in Japan (GakuNin)"],
|
|
7
|
+
"chooser_pattern": "\\bGakuNin\\b|\\bAcademic\\s+Access\\s+Management\\s+Federation\\s+in\\s+Japan\\b",
|
|
8
|
+
"discovery_hosts": [],
|
|
9
|
+
"service_domains": ["gakunin.nii.ac.jp"],
|
|
10
|
+
"metadata_url": "https://metadata.gakunin.nii.ac.jp/gakunin-edugain-metadata.xml"
|
|
11
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
{
|
|
2
|
+
"code": "hkaf",
|
|
3
|
+
"name": "HKAF",
|
|
4
|
+
"country": "HK",
|
|
5
|
+
"registration_authorities": ["https://hkaf.edu.hk"],
|
|
6
|
+
"chooser_labels": ["Hong Kong Access Federation"],
|
|
7
|
+
"chooser_pattern": "\\bHKAF\\b|\\bHong\\s+Kong\\s+Access\\s+Federation\\b",
|
|
8
|
+
"discovery_hosts": [],
|
|
9
|
+
"service_domains": ["hkaf.edu.hk"],
|
|
10
|
+
"metadata_url": "https://md.hkaf.edu.hk/hkaf-edugain-metadata.xml",
|
|
11
|
+
"member_list": ""
|
|
12
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
{
|
|
2
|
+
"code": "kafe",
|
|
3
|
+
"name": "KAFE",
|
|
4
|
+
"country": "KR",
|
|
5
|
+
"registration_authorities": ["http://kafe.kreonet.net"],
|
|
6
|
+
"chooser_labels": ["Korean Access Federation"],
|
|
7
|
+
"chooser_pattern": "\\bKAFE\\b|\\bKorean\\s+Access\\s+Federation\\b",
|
|
8
|
+
"discovery_hosts": [],
|
|
9
|
+
"service_domains": ["kreonet.net"],
|
|
10
|
+
"metadata_url": "https://fedinfo.kreonet.net/signedmetadata/federation/Upstream-eduGAIN/metadata.xml"
|
|
11
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
{
|
|
2
|
+
"code": "openathens",
|
|
3
|
+
"name": "OpenAthens",
|
|
4
|
+
"country": "",
|
|
5
|
+
"kind": "service",
|
|
6
|
+
"secondary": true,
|
|
7
|
+
"openathens_entries": true,
|
|
8
|
+
"registration_authorities": [
|
|
9
|
+
"https://openathens.net"
|
|
10
|
+
],
|
|
11
|
+
"chooser_labels": [
|
|
12
|
+
"OpenAthens Federation"
|
|
13
|
+
],
|
|
14
|
+
"chooser_pattern": "\\bOpenAthens\\b",
|
|
15
|
+
"discovery_hosts": [],
|
|
16
|
+
"service_domains": [],
|
|
17
|
+
"metadata_url": "",
|
|
18
|
+
"school_login_pages": [
|
|
19
|
+
"https://login.openathens.net/auth/*/o/"
|
|
20
|
+
]
|
|
21
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
{
|
|
2
|
+
"code": "sgaf",
|
|
3
|
+
"name": "SGAF",
|
|
4
|
+
"country": "SG",
|
|
5
|
+
"registration_authorities": ["https://www.singaren.net.sg"],
|
|
6
|
+
"chooser_labels": ["Singapore Access Federation"],
|
|
7
|
+
"chooser_pattern": "\\bSGAF\\b|\\bSingapore\\s+Access\\s+Federation\\b",
|
|
8
|
+
"discovery_hosts": [],
|
|
9
|
+
"service_domains": ["sgaf.org.sg"],
|
|
10
|
+
"metadata_url": "https://ds.sgaf.org.sg/distribution/metadata/sgaf-edugain-export-metadata.xml"
|
|
11
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
{
|
|
2
|
+
"code": "sifulan",
|
|
3
|
+
"name": "SIFULAN",
|
|
4
|
+
"country": "MY",
|
|
5
|
+
"registration_authorities": ["https://sifulan.my"],
|
|
6
|
+
"chooser_labels": ["Malaysian Access Federation (SIFULAN)"],
|
|
7
|
+
"chooser_pattern": "\\bSIFULAN\\b|\\bMalaysian\\s+Access\\s+Federation\\b",
|
|
8
|
+
"discovery_hosts": [],
|
|
9
|
+
"service_domains": ["sifulan.my"],
|
|
10
|
+
"metadata_url": "https://sifulan.my/metadata/edugain-metadata.xml"
|
|
11
|
+
}
|