unitoolkit 0.7.0__py3-none-any.whl

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.
unitoolkit/koha.py ADDED
@@ -0,0 +1,729 @@
1
+ """Koha (biblioteket.shh.se) through the proxied agent browser.
2
+
3
+ Why a browser and not HTTP: the library sits behind Cloudflare, which answers plain
4
+ HTTP clients (including Cloudflare Workers and Apify's HTTP proxy) with 429. A real
5
+ Chrome through a residential proxy gets through, and the catalogue is rendered by
6
+ JavaScript anyway, so the browser is the only reliable reader.
7
+
8
+ Transport: Chrome with --proxy-server=http://127.0.0.1:8118 (a local chaining proxy
9
+ that adds Apify residential credentials; see scripts/apify_chain_proxy.py in the
10
+ school-helper profile). Read-only: search, item availability, your own loans.
11
+ """
12
+ import asyncio
13
+ import json
14
+ import os
15
+ import re
16
+ import socket
17
+ import subprocess
18
+ import sys
19
+ import time
20
+ import urllib.parse
21
+ import urllib.request
22
+ from pathlib import Path
23
+
24
+ CDP = os.environ.get('KOHA_CDP', 'http://127.0.0.1:9334')
25
+ CHAIN_PORT = int(os.environ.get('KOHA_CHAIN_PORT', '8118'))
26
+ PROFILE = os.environ.get('KOHA_CHROME_PROFILE',
27
+ str(Path.home() / '.cache/unitoolkit/koha-chrome'))
28
+ PROXY_PASSWORD_FILE = os.path.expanduser(os.environ.get('CHAIN_UPSTREAM_PASSWORD_FILE',
29
+ '~/.secrets/APIFY_PROXY_PASSWORD'))
30
+ # Chrome flags for the library profile. SameSite enforcement is off because the SSO hand-back
31
+ # is a cross-site POST and Koha's CGISESSID is SameSite=Lax (dropped after a 2-minute grace
32
+ # that two-factor outlasts). This profile holds no other sessions.
33
+ CHROME_FLAGS = ['--no-first-run', '--no-default-browser-check',
34
+ '--disable-features=SameSiteByDefaultCookies,CookiesWithoutSameSiteMustBeSecure']
35
+
36
+
37
+ def _chrome_cmd():
38
+ """How to start Chrome here: KOHA_CHROME_SCRIPT, else a Chrome on PATH, else flatpak."""
39
+ import shutil
40
+ script = os.environ.get('KOHA_CHROME_SCRIPT', '')
41
+ if script and Path(script).exists():
42
+ return [script]
43
+ for name in ('google-chrome', 'google-chrome-stable', 'chromium', 'chromium-browser'):
44
+ exe = shutil.which(name)
45
+ if exe:
46
+ return [exe]
47
+ if shutil.which('flatpak'):
48
+ return ['flatpak', 'run', 'com.google.Chrome']
49
+ raise KohaError('no Chrome found: install Chrome or set KOHA_CHROME_SCRIPT')
50
+ BASE = 'https://biblioteket.shh.se'
51
+ SEARCH = BASE + '/cgi-bin/koha/opac-search.pl?idx=&q=%s&weight_search=1'
52
+ DETAIL = BASE + '/cgi-bin/koha/opac-detail.pl?biblionumber=%s'
53
+ USER = BASE + '/cgi-bin/koha/opac-user.pl'
54
+
55
+
56
+ class KohaError(RuntimeError):
57
+ pass
58
+
59
+
60
+ def _port_open(port, host='127.0.0.1', timeout=1.0):
61
+ s = socket.socket()
62
+ s.settimeout(timeout)
63
+ try:
64
+ s.connect((host, port))
65
+ return True
66
+ except Exception:
67
+ return False
68
+ finally:
69
+ s.close()
70
+
71
+
72
+ def _cdp_up():
73
+ try:
74
+ urllib.request.urlopen(CDP + '/json/version', timeout=3)
75
+ return True
76
+ except Exception:
77
+ return False
78
+
79
+
80
+ def ensure_browser(timeout=40):
81
+ """Start the chain proxy and the proxied Chrome if they are not up. Idempotent."""
82
+ use_proxy = os.environ.get('KOHA_PROXY', '1').lower() not in ('0', 'false', 'no', '')
83
+ if use_proxy and not _port_open(CHAIN_PORT):
84
+ if not Path(PROXY_PASSWORD_FILE).exists():
85
+ raise KohaError('the library proxy is not running and %s is missing. If your network '
86
+ 'reaches biblioteket.shh.se directly, set KOHA_PROXY=0.' % PROXY_PASSWORD_FILE)
87
+ subprocess.Popen([sys.executable, '-m', 'unitoolkit.chainproxy'],
88
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)
89
+ for _ in range(20):
90
+ time.sleep(0.5)
91
+ if _port_open(CHAIN_PORT):
92
+ break
93
+ if not _cdp_up():
94
+ cmd = _chrome_cmd()
95
+ if len(cmd) == 1 and os.environ.get('KOHA_CHROME_SCRIPT') == cmd[0]:
96
+ args = cmd # the script carries its own flags
97
+ else:
98
+ Path(PROFILE).mkdir(parents=True, exist_ok=True)
99
+ args = cmd + ['--user-data-dir=' + PROFILE,
100
+ '--remote-debugging-port=' + CDP.rsplit(':', 1)[1]] + CHROME_FLAGS
101
+ if use_proxy:
102
+ args.append('--proxy-server=http://127.0.0.1:%d' % CHAIN_PORT)
103
+ subprocess.Popen(args, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
104
+ start_new_session=True)
105
+ for _ in range(int(timeout / 1.5)):
106
+ time.sleep(1.5)
107
+ if _cdp_up():
108
+ return True
109
+ raise KohaError('proxied Chrome did not come up on %s' % CDP)
110
+ return True
111
+
112
+
113
+ class _Page:
114
+ """One CDP session against a page tab, synchronous on top of asyncio."""
115
+
116
+ def __init__(self):
117
+ import websockets # noqa: F401 (checked here so the error names the dependency)
118
+ self.loop = asyncio.new_event_loop()
119
+
120
+ def __enter__(self):
121
+ self.loop.run_until_complete(self._open())
122
+ return self
123
+
124
+ def __exit__(self, *exc):
125
+ try:
126
+ self.loop.run_until_complete(self._close())
127
+ finally:
128
+ self.loop.close()
129
+
130
+ async def _open(self):
131
+ import websockets
132
+ ver = json.load(urllib.request.urlopen(CDP + '/json/version', timeout=5))
133
+ self.ws = await websockets.connect(ver['webSocketDebuggerUrl'], max_size=None)
134
+ tabs = json.load(urllib.request.urlopen(CDP + '/json/list', timeout=5))
135
+ pages = [t for t in tabs if t.get('type') == 'page']
136
+ target = pages[0]['id'] if pages else None
137
+ if target is None:
138
+ target = json.load(urllib.request.urlopen(urllib.request.Request(
139
+ CDP + '/json/new?about:blank', method='PUT'), timeout=10))['id']
140
+ res = await self.call('Target.attachToTarget', {'targetId': target, 'flatten': True})
141
+ self.sid = res['sessionId']
142
+ await self.call('Page.enable')
143
+ await self.call('Runtime.enable')
144
+
145
+ async def _close(self):
146
+ try:
147
+ await self.ws.close()
148
+ except Exception:
149
+ pass
150
+
151
+ async def call(self, method, params=None):
152
+ self.n = getattr(self, 'n', 0) + 1
153
+ mine = self.n
154
+ msg = {'id': mine, 'method': method, 'params': params or {}}
155
+ if getattr(self, 'sid', None):
156
+ msg['sessionId'] = self.sid
157
+ await self.ws.send(json.dumps(msg))
158
+ while True:
159
+ raw = json.loads(await self.ws.recv())
160
+ if raw.get('id') == mine:
161
+ return raw.get('result', raw)
162
+ # Events arrive between replies. Keep the recent ones: a login that fails with no
163
+ # on-page message is diagnosed from the POST's status and the page it landed on.
164
+ if raw.get('method') and hasattr(self, 'events'):
165
+ self.events.append(raw)
166
+ del self.events[:-40]
167
+
168
+ def eval(self, expr):
169
+ res = self.loop.run_until_complete(self.call(
170
+ 'Runtime.evaluate', {'expression': expr, 'returnByValue': True, 'awaitPromise': True}))
171
+ self.last_error = ((res.get('exceptionDetails') or {}).get('exception') or {}).get(
172
+ 'description') or ''
173
+ return (res.get('result') or {}).get('value')
174
+
175
+ def goto(self, url, marker=None, timeout=25):
176
+ """Navigate and wait until marker (a JS expression returning truthy) or readyState."""
177
+ self.loop.run_until_complete(self.call('Page.navigate', {'url': url}))
178
+ deadline = time.time() + timeout
179
+ while time.time() < deadline:
180
+ time.sleep(0.6)
181
+ try:
182
+ ok = self.eval('document.readyState === "complete"')
183
+ except Exception:
184
+ continue
185
+ if not ok:
186
+ continue
187
+ if marker is None:
188
+ return True
189
+ try:
190
+ if self.eval(marker):
191
+ return True
192
+ except Exception:
193
+ continue
194
+ return False
195
+
196
+
197
+ SEARCH_JS = r"""(function(){
198
+ var out = [];
199
+ document.querySelectorAll('a[href*="opac-detail"]').forEach(function(a){
200
+ var row = a.closest('tr') || a.closest('div.search-result') || a.parentElement.parentElement;
201
+ var m = /biblionumber=(\d+)/.exec(a.getAttribute('href') || '');
202
+ var txt = row ? row.innerText.replace(/\s+/g, ' ').trim() : '';
203
+ var av = /Availability:\s*(.*?)(?: Save to lists| Add to cart|$)/.exec(txt);
204
+ out.push({biblio: m ? m[1] : null,
205
+ title: a.innerText.trim(),
206
+ availability: av ? av[1].trim() : '',
207
+ row: txt});
208
+ });
209
+ return JSON.stringify(out);
210
+ })()"""
211
+
212
+ ITEMS_JS = r"""(function(){
213
+ var t = document.querySelector('#holdingst') || document.querySelector('table.table');
214
+ var rows = [];
215
+ if (t) { t.querySelectorAll('tr').forEach(function(r){
216
+ var cells = [...r.querySelectorAll('td,th')].map(function(c){return c.innerText.replace(/\s+/g,' ').trim();});
217
+ if (cells.join('').trim()) rows.push(cells); }); }
218
+ var summ = document.querySelectorAll('.results_summary');
219
+ return JSON.stringify({rows: rows,
220
+ summary: [...summ].map(function(e){return e.innerText.replace(/\s+/g,' ').trim();}).slice(0, 8),
221
+ title: document.title});
222
+ })()"""
223
+
224
+ CHECKOUTS_JS = r"""(function(){
225
+ function grab(sel) {
226
+ var t = document.querySelector(sel);
227
+ if (!t) return null;
228
+ return [...t.querySelectorAll('tr')].map(function(r){
229
+ return [...r.querySelectorAll('td,th')].map(function(c){
230
+ return c.innerText.replace(/\s+/g,' ').trim();}).join(' | ');
231
+ }).filter(function(x){return x.replace(/\|/g,'').trim();});
232
+ }
233
+ return JSON.stringify({checkouts: grab('#checkouts_table'),
234
+ holds: grab('#holdst') || grab('#reservest'),
235
+ user: (document.querySelector('#logged-in-info, .loggedinusername') || {}).innerText || ''});
236
+ })()"""
237
+
238
+
239
+ SUBMIT_SEARCH_JS = r'''(function(q){
240
+ var form = document.querySelector('form[action*="opac-search"]') || document.querySelector('#searchform');
241
+ var input = document.querySelector('#transl1') || document.querySelector('input[name="q"]');
242
+ if (!form || !input) return 'no form';
243
+ input.value = q;
244
+ form.submit();
245
+ return 'submitted';
246
+ })(%s)'''
247
+
248
+
249
+ _tries = [0]
250
+
251
+
252
+ def search(q, limit=10):
253
+ """Search through the catalogue form, like a person would.
254
+
255
+ Loading opac-search.pl directly gets the home page back (Koha hands out a session
256
+ on the front page first), so: open the front page, fill the search box, submit.
257
+ """
258
+ if not q or not str(q).strip():
259
+ raise KohaError('empty query')
260
+ ensure_browser()
261
+ with _Page() as p:
262
+ if not p.goto(BASE, marker="!!document.querySelector('#transl1, input[name=\"q\"]')"):
263
+ raise KohaError('the catalogue front page did not load (proxy or Cloudflare problem?)')
264
+ state = p.eval(SUBMIT_SEARCH_JS % json.dumps(str(q)))
265
+ if state != 'submitted':
266
+ raise KohaError('could not find the search form on the front page')
267
+ ok = False
268
+ for _ in range(25):
269
+ time.sleep(1)
270
+ try:
271
+ if p.eval("document.querySelectorAll('a[href*=\"opac-detail\"]').length > 0"):
272
+ ok = True
273
+ break
274
+ except Exception:
275
+ pass
276
+ rows = json.loads(p.eval(SEARCH_JS) or '[]')
277
+ if not ok and not rows:
278
+ raise KohaError('search returned no result page (proxy, Cloudflare or zero hits)')
279
+ # Sometimes the catalogue answers a search with the account page's login message instead
280
+ # of results. That row is not a hit: dropping it, and retrying once, turns a bogus
281
+ # "Log in using your SHH account" into either results or an honest error.
282
+ rows = [r for r in rows if not (r.get('biblio') is None and
283
+ (r.get('title') or '').lower().startswith('log in'))]
284
+ if not rows:
285
+ if _tries[0] >= 1:
286
+ raise KohaError('the catalogue served its login page instead of results for %r '
287
+ '(session or Cloudflare, not an empty result)' % str(q)[:60])
288
+ _tries[0] += 1
289
+ try:
290
+ return search(q, limit)
291
+ finally:
292
+ _tries[0] = 0
293
+ return rows[:limit]
294
+
295
+
296
+ def availability(biblionumber):
297
+ if not str(biblionumber).isdigit():
298
+ raise KohaError('biblionumber must be digits')
299
+ ensure_browser()
300
+ with _Page() as p:
301
+ p.goto(DETAIL % biblionumber, marker="document.querySelectorAll('.results_summary').length > 0")
302
+ data = json.loads(p.eval(ITEMS_JS) or '{}')
303
+ return data
304
+
305
+
306
+ def _secret(name):
307
+ path = Path.home() / '.secrets' / name
308
+ if not path.exists():
309
+ return None
310
+ value = path.read_text().strip()
311
+ return value or None
312
+
313
+
314
+ def credentials():
315
+ """(userid, pin) from ~/.secrets/KOHA_CREDENTIALS (two lines: personnummer, pin).
316
+
317
+ Falls back to the separate KOHA_USER / KOHA_PIN files. Never printed, never logged,
318
+ and only ever posted to the library's own login form.
319
+ """
320
+ path = Path(os.environ.get('KOHA_CREDENTIALS_FILE',
321
+ str(Path.home() / '.secrets' / 'KOHA_CREDENTIALS')))
322
+ if path.exists():
323
+ lines = [ln.strip() for ln in path.read_text().splitlines() if ln.strip()]
324
+ if len(lines) >= 2:
325
+ return lines[0], lines[1]
326
+ user, pin = _secret('KOHA_USER'), _secret('KOHA_PIN')
327
+ return (user, pin) if user and pin else (None, None)
328
+
329
+
330
+ LOGIN_JS = r"""(function(user, pin){
331
+ var f = document.querySelector('#modalAuth') || document.querySelector('form[action*="opac-user"]');
332
+ if (!f) return 'no form';
333
+ var u = f.querySelector('input[name=login_userid], #userid, input[name=userid]');
334
+ var s = f.querySelector('input[name=login_password], #password, input[name=password]');
335
+ if (!u || !s) return 'no fields';
336
+ u.value = user; s.value = pin;
337
+ var ctx = f.querySelector('input[name=koha_login_context]');
338
+ if (ctx) ctx.value = 'opac';
339
+ var op = f.querySelector('input[name=login_op]');
340
+ if (op && !op.value) op.value = 'cud-login'; // Koha ignores the POST without it
341
+ if (f.requestSubmit) f.requestSubmit(); else f.submit();
342
+ return 'submitted';
343
+ })(%s, %s)"""
344
+
345
+ # Tolerant scrape: keep the raw cells, then derive the fields people ask about.
346
+ ACCOUNT_JS = r"""(function(){
347
+ function table(sel){
348
+ var t = document.querySelector(sel);
349
+ if (!t) return null;
350
+ var rows = [];
351
+ t.querySelectorAll('tr').forEach(function(r){
352
+ var cells = [...r.querySelectorAll('td,th')].map(function(c){
353
+ return c.innerText.replace(/\s+/g,' ').trim(); });
354
+ if (cells.join('').trim()) rows.push(cells);
355
+ });
356
+ return rows;
357
+ }
358
+ function firstLink(sel){
359
+ var t = document.querySelector(sel);
360
+ if (!t) return null;
361
+ var a = t.querySelector('a[href*="opac-detail"]');
362
+ return a ? a.innerText.replace(/\s+/g,' ').trim() : null;
363
+ }
364
+ var body = document.body.innerText;
365
+ return JSON.stringify({
366
+ logged_in: !!document.querySelector('#checkoutst, #checkouts_table, #user_summary, #opac-user-views, .loggedinusername'),
367
+ user: ((document.querySelector('.loggedinusername, #user_summary, .user-info') || {}).innerText || '')
368
+ .replace(/\s+/g, ' ').trim().slice(0, 120),
369
+ checkouts: table('#checkoutst') || table('#checkouts_table'),
370
+ holds: table('#holdst') || table('#reservest') || table('#holdst_table'),
371
+ fines: table('#finest') || table('#fines_table') || table('#chargest'),
372
+ overdues: table('#overdues_table'),
373
+ message: ((document.querySelector('.alert, .dialog.alert, #login_error') || {}).innerText || '').trim().slice(0, 300),
374
+ login_form: !!document.querySelector('#modalAuth input[name=login_userid]'),
375
+ titles: {checkout_first: firstLink('#checkouts_table'), hold_first: firstLink('#holdst')}
376
+ });
377
+ })()"""
378
+
379
+ _DATE = re.compile(r'(\d{4}-\d{2}-\d{2}|\d{1,2}/\d{1,2}/\d{4})')
380
+
381
+
382
+ def _secret(name):
383
+ path = Path.home() / '.secrets' / name
384
+ if not path.exists():
385
+ return None
386
+ value = path.read_text().strip()
387
+ return value or None
388
+
389
+
390
+ def _days_left(date_str):
391
+ m = _DATE.search(date_str or '')
392
+ if not m:
393
+ return None
394
+ raw = m.group(1)
395
+ for fmt in ('%Y-%m-%d', '%d/%m/%Y', '%m/%d/%Y'):
396
+ try:
397
+ d = __import__('datetime').datetime.strptime(raw, fmt).date()
398
+ return (d - __import__('datetime').date.today()).days
399
+ except ValueError:
400
+ continue
401
+ return None
402
+
403
+
404
+ def _normalise_account(raw):
405
+ """Rows come back as table cells; name the columns people actually ask for."""
406
+ def rows_of(key):
407
+ return raw.get(key) or []
408
+
409
+ checkouts = []
410
+ for cells in rows_of('checkouts'):
411
+ joined = ' | '.join(cells)
412
+ if re.fullmatch(r'(?i)(titel|title|author|due|förfaller|checked out|\W)+', joined):
413
+ continue # header row
414
+ if cells and cells[0].strip().lower() in ('title', 'titel'):
415
+ continue
416
+ dates = _DATE.findall(joined)
417
+ due = cells[3] if len(cells) > 3 and _DATE.search(cells[3] or '') else (dates[-1] if dates else '')
418
+ checkouts.append({
419
+ 'cells': cells,
420
+ 'title': cells[0] if cells else '',
421
+ 'author': cells[1] if len(cells) > 1 else '',
422
+ 'due': due,
423
+ 'days_left': _days_left(due),
424
+ })
425
+ holds = []
426
+ for cells in rows_of('holds'):
427
+ joined = ' | '.join(cells)
428
+ if re.fullmatch(r'(?i)(titel|title|\W)+', joined):
429
+ continue
430
+ nums = [c for c in cells if c.strip().isdigit()]
431
+ holds.append({
432
+ 'cells': cells,
433
+ 'title': cells[0] if cells else '',
434
+ 'queue_position': int(nums[-1]) if nums else None,
435
+ })
436
+ return {
437
+ 'logged_in': raw.get('logged_in'),
438
+ 'checkouts': checkouts,
439
+ 'checkouts_count': len(checkouts),
440
+ 'holds': holds,
441
+ 'holds_count': len(holds),
442
+ 'fines': rows_of('fines'),
443
+ 'overdues': rows_of('overdues'),
444
+ 'message': raw.get('message', ''),
445
+ }
446
+
447
+
448
+ SHIB_LOGIN = BASE + ('/Shibboleth.sso/Login?target=https%3A%2F%2Fbiblioteket.shh.se'
449
+ '%2Fcgi-bin%2Fkoha%2Fopac-main.pl')
450
+
451
+ SSO_STATE_JS = r"""JSON.stringify({
452
+ host: location.host, path: location.pathname,
453
+ form: !!document.querySelector('#username') && !!document.querySelector('#password'),
454
+ filled: ['#username','#password'].every(function(s){ var e = document.querySelector(s);
455
+ return !!e && e.matches(':-webkit-autofill'); }),
456
+ submit: !!document.querySelector('button[name=_eventId_proceed], input[name=_eventId_proceed]'),
457
+ logged_in: !!document.querySelector('#checkouts_table, #user_summary'),
458
+ error: ((document.querySelector('.form-error, .output--failure, .alert-danger') || {}).innerText || '').slice(0,200)
459
+ })"""
460
+
461
+ CLICK_JS = r"""(function(sel){
462
+ var b = document.querySelector(sel);
463
+ if (!b) return null;
464
+ b.scrollIntoView({block:'center'});
465
+ var r = b.getBoundingClientRect();
466
+ return JSON.stringify({x: r.left + r.width/2, y: r.top + r.height/2});
467
+ })(%s)"""
468
+
469
+
470
+ def _click(p, selector):
471
+ """Real mouse click: Chrome only releases autofilled values after a user gesture."""
472
+ xy = p.eval(CLICK_JS % json.dumps(selector))
473
+ if not xy:
474
+ return False
475
+ xy = json.loads(xy)
476
+ p.loop.run_until_complete(p.call('Input.dispatchMouseEvent',
477
+ {'type': 'mousePressed', 'x': xy['x'], 'y': xy['y'], 'button': 'left', 'clickCount': 1}))
478
+ p.loop.run_until_complete(p.call('Input.dispatchMouseEvent',
479
+ {'type': 'mouseReleased', 'x': xy['x'], 'y': xy['y'], 'button': 'left', 'clickCount': 1}))
480
+ return True
481
+
482
+
483
+ def login_sso(timeout=60):
484
+ """Sign in to Koha through the SHH account (SWAMID), using Chrome's saved password.
485
+
486
+ The library has no separate password: "Log in using your SHH account" sends you to
487
+ Shibboleth, which forwards to the SHH IdP where Chrome already has the login saved.
488
+ Nothing is read, typed or stored here: the script waits for the autofill and clicks.
489
+ """
490
+ ensure_browser()
491
+ with _Page() as p:
492
+ p.goto(USER, marker="!!document.querySelector('#checkouts_table, a[href*=Shibboleth]')")
493
+ if p.eval("!!document.querySelector('#checkoutst, #checkouts_table, #user_summary')"):
494
+ return 'already in'
495
+ p.loop.run_until_complete(p.call('Page.navigate', {'url': SHIB_LOGIN}))
496
+ clicked = False
497
+ deadline = time.time() + timeout
498
+ while time.time() < deadline:
499
+ time.sleep(1.5)
500
+ try:
501
+ st = json.loads(p.eval(SSO_STATE_JS) or '{}')
502
+ except Exception:
503
+ continue
504
+ if st.get('logged_in'):
505
+ return 'ok'
506
+ if st.get('error'):
507
+ raise KohaError('the SHH IdP refused the login: %s' % st['error'])
508
+ if st.get('form') and st.get('filled') and not clicked:
509
+ clicked = _click(p, 'button[name=_eventId_proceed], input[name=_eventId_proceed]')
510
+ if clicked and st.get('host') == 'biblioteket.shh.se':
511
+ time.sleep(1.5)
512
+ if p.eval("!!document.querySelector('#checkoutst, #checkouts_table, #user_summary')"):
513
+ return 'ok'
514
+ raise KohaError('SSO login did not finish in %ds (autofill empty, 2FA, or slow IdP)' % timeout)
515
+
516
+
517
+ # The library's "Log in using your SHH account" goes to Shibboleth, which hands off to
518
+ # Microsoft Entra (login.microsoftonline.com), not to a Shibboleth IdP form. Its login is
519
+ # a two-step wizard: e-mail/username, then password, then "stay signed in".
520
+ ENTRA_JS = r"""JSON.stringify({
521
+ host: location.host, path: location.pathname,
522
+ step: (function(){
523
+ if (document.querySelector('#i0118')) return 'password';
524
+ if (document.querySelector('#i0116, input[name=loginfmt]')) return 'user';
525
+ if (document.querySelector('#idBtn_Back, #idSIButton9')) return 'staysignedin';
526
+ return 'other';
527
+ })(),
528
+ filled: ['#i0116','input[name=loginfmt]','#i0118'].some(function(s){
529
+ var e = document.querySelector(s); return !!e && e.matches(':-webkit-autofill'); }),
530
+ error: ((document.querySelector('#usernameError, #passwordError, .alert-error') || {}).innerText || '').slice(0,200),
531
+ logged_in: !!document.querySelector('#checkouts_table, #user_summary')
532
+ })"""
533
+
534
+
535
+ def _no_credentials():
536
+ raise KohaError('no credentials: put your library username and 4-digit pinkod on two lines '
537
+ 'in ~/.secrets/KOHA_CREDENTIALS (chmod 600). Read from disk, never printed.')
538
+
539
+
540
+ def _advance_entra(p, timeout=90):
541
+ """Walk the Entra wizard, clicking only when Chrome has autofilled the field."""
542
+ clicked = set()
543
+ deadline = time.time() + timeout
544
+ while time.time() < deadline:
545
+ time.sleep(1.5)
546
+ try:
547
+ st = json.loads(p.eval(ENTRA_JS) or '{}')
548
+ except Exception:
549
+ continue
550
+ if st.get('host') == 'biblioteket.shh.se':
551
+ if p.eval("!!document.querySelector('#checkoutst, #checkouts_table, #user_summary')"):
552
+ return 'ok'
553
+ return 'back'
554
+ if st.get('error'):
555
+ raise KohaError('Microsoft login error: %s' % st['error'])
556
+ step = st.get('step')
557
+ if step in ('user', 'password') and st.get('filled') and step not in clicked:
558
+ sel = '#i0116' if step == 'user' else '#i0118'
559
+ if _click(p, sel) and _click(p, '#idSIButton9'):
560
+ clicked.add(step)
561
+ elif step == 'staysignedin' and 'stay' not in clicked:
562
+ if _click(p, '#idBtn_Back') or _click(p, '#idSIButton9'):
563
+ clicked.add('stay')
564
+ return 'timeout'
565
+
566
+
567
+ def _post_trace(p):
568
+ """What the last login POST got back, for a failure with nothing on the page."""
569
+ bits = []
570
+ for ev in getattr(p, 'events', []):
571
+ if ev.get('method') != 'Network.responseReceived':
572
+ continue
573
+ r = ev['params']['response']
574
+ if 'biblioteket.shh.se' in r.get('url', ''):
575
+ bits.append('%s %s' % (r.get('status'), (r.get('url') or '')[:70]))
576
+ page = p.eval("location.pathname + ' | ' + (document.title||'') + ' | ' + "
577
+ "((document.querySelector('#modalAuth, #loginform, form[action*=login]') || "
578
+ "{innerText: ''}).innerText || '').replace(/\\s+/g, ' ').slice(0, 120)")
579
+ return '; '.join((['page: %s' % page] if page else []) + (bits[-3:] or ['no response seen']))
580
+
581
+
582
+ def _form_login(p, user, password):
583
+ """Library form login, from a clean session.
584
+
585
+ Koha binds a session to the client IP and rejects the POST at the second request if the
586
+ address changed ("You are logging from a different IP address"), which is what a rotating
587
+ proxy does. Start from a fresh session on the sticky exit, and load the page with cache
588
+ bypassed so the CSRF token belongs to that session.
589
+ """
590
+ p.events = []
591
+ p.loop.run_until_complete(p.call('Network.enable'))
592
+ p.loop.run_until_complete(p.call('Storage.clearCookies', {}))
593
+ p.goto(USER + '?n=%d' % int(time.time()),
594
+ marker="!!document.querySelector('#modalAuth, a[href*=opac-user]')")
595
+ p.loop.run_until_complete(p.call('Page.reload', {'ignoreCache': True}))
596
+ time.sleep(4)
597
+ if not p.eval("!!document.querySelector('#modalAuth input[name=login_userid]')"):
598
+ _click(p, 'a[href*="opac-user"]')
599
+ time.sleep(2)
600
+ state = p.eval(LOGIN_JS % (json.dumps(user), json.dumps(password)))
601
+ if getattr(p, 'last_error', ''):
602
+ # A script error is not a submit. It was read as one until 2026-11-18, which turned
603
+ # every broken login script into a silent "no answer" with no request sent.
604
+ return 'js error: %s' % p.last_error.splitlines()[0][:140]
605
+ # A successful submit navigates immediately, which destroys the JS context and makes the
606
+ # evaluate return None. That is success, not a missing form.
607
+ if state not in ('submitted', None):
608
+ return 'no form (%s)' % state
609
+ for _ in range(14):
610
+ time.sleep(1.5)
611
+ if p.eval("!!document.querySelector('#checkoutst, #checkouts_table, #user_summary')"):
612
+ return 'ok'
613
+ msg = p.eval("((document.querySelector('.alert, .dialog, #login_error, .form-error')||{}).innerText||'').replace(/\\s+/g,' ').slice(0,160)")
614
+ if msg:
615
+ return msg
616
+ return 'no answer: %s' % _post_trace(p)
617
+
618
+
619
+ def _relax_samesite(p):
620
+ """Rewrite the library's Lax cookies to SameSite=None before a SAML login.
621
+
622
+ The Shibboleth hand-back from login.microsoftonline.com is a cross-site POST, and a
623
+ SameSite=Lax cookie is not sent on those (Chrome only allows it in a 2-minute grace
624
+ window, which two-factor authentication usually outlasts). The result is a login that
625
+ succeeds at Microsoft and lands in Koha signed out. The SP's own state cookies are
626
+ already None; CGISESSID is the one that needs relaxing.
627
+ """
628
+ ck = p.loop.run_until_complete(p.call('Storage.getCookies', {})) or {}
629
+ changed = 0
630
+ for c in ck.get('cookies', []):
631
+ if 'biblioteket.shh.se' not in c.get('domain', ''):
632
+ continue
633
+ if (c.get('sameSite') or 'Lax') == 'None':
634
+ continue
635
+ p.loop.run_until_complete(p.call('Storage.setCookies', {'cookies': [{
636
+ 'name': c['name'], 'value': c['value'], 'domain': c['domain'], 'path': c['path'],
637
+ 'secure': True, 'httpOnly': c.get('httpOnly', False), 'sameSite': 'None',
638
+ 'expires': c.get('expires', -1)}]}))
639
+ changed += 1
640
+ return changed
641
+
642
+
643
+ def open_login():
644
+ """Bring the proxied Chrome to the library account page and leave it there.
645
+
646
+ The one-time case: a human signs in ("Log in using your SHH account" or the library
647
+ form), Chrome keeps the session cookie, and afterwards loans() needs no credentials.
648
+ """
649
+ ensure_browser()
650
+ with _Page() as p:
651
+ p.loop.run_until_complete(p.call('Network.enable'))
652
+ p.goto(USER, marker="!!document.querySelector('#modalAuth, a[href*=Shibboleth], #checkouts_table')")
653
+ relaxed = _relax_samesite(p)
654
+ state = p.eval("!!document.querySelector('#checkouts_table, #user_summary')")
655
+ return {'url': USER, 'signed_in': bool(state), 'cookies_relaxed': relaxed,
656
+ 'next': None if state else 'sign in in the open window, then run koha_wait_login'}
657
+
658
+
659
+ def wait_for_login(timeout=300):
660
+ """Wait until the library account page shows a signed-in session.
661
+
662
+ For the one-time case: the human signs in by hand in the proxied Chrome window
663
+ ("Log in using your SHH account"), and the profile keeps the session cookie. After
664
+ that, `loans()` reads the account with no credentials at all.
665
+ """
666
+ ensure_browser()
667
+ deadline = time.time() + timeout
668
+ with _Page() as p:
669
+ while time.time() < deadline:
670
+ p.goto(USER, marker="!!document.querySelector('#checkouts_table, a[href*=Shibboleth], #modalAuth')")
671
+ if p.eval("!!document.querySelector('#checkoutst, #checkouts_table, #user_summary')"):
672
+ return 'signed in'
673
+ time.sleep(5)
674
+ raise KohaError('no signed-in library session after %ds' % timeout)
675
+
676
+
677
+ def loans(user=None, pin=None, timeout=60):
678
+ """Your own Koha account: loans, holds, fines. Read-only.
679
+
680
+ Signs in through the SHH account (SWAMID) with Chrome's saved password. If that is not
681
+ available and ~/.secrets/KOHA_USER + KOHA_PIN exist, the library form is used instead.
682
+ """
683
+ ensure_browser()
684
+ with _Page() as p:
685
+ p.goto(USER, marker="!!document.querySelector('#modalAuth, #checkouts_table, a[href*=Shibboleth]')")
686
+ raw = json.loads(p.eval(ACCOUNT_JS) or '{}')
687
+ if not raw.get('logged_in'):
688
+ _relax_samesite(p)
689
+ p.loop.run_until_complete(p.call('Page.navigate', {'url': SHIB_LOGIN}))
690
+ clicked = False
691
+ deadline = time.time() + timeout
692
+ while time.time() < deadline:
693
+ time.sleep(1.5)
694
+ try:
695
+ st = json.loads(p.eval(SSO_STATE_JS) or '{}')
696
+ except Exception:
697
+ continue
698
+ if st.get('form') and st.get('filled') and not clicked:
699
+ clicked = _click(p, 'button[name=_eventId_proceed], input[name=_eventId_proceed]')
700
+ if st.get('error'):
701
+ raise KohaError('the SHH IdP refused the login: %s' % st['error'])
702
+ if st.get('host') == 'biblioteket.shh.se' or st.get('logged_in'):
703
+ raw = json.loads(p.eval(ACCOUNT_JS) or '{}')
704
+ if raw.get('logged_in'):
705
+ break
706
+ else:
707
+ raw = json.loads(p.eval(ACCOUNT_JS) or '{}')
708
+ if not raw.get('logged_in'):
709
+ if not (user and pin):
710
+ user, pin = credentials()
711
+ # The SSO attempt may have left us on another host: come back to the
712
+ # account page before using the library's own form.
713
+ p.goto(USER, marker="!!document.querySelector('#modalAuth, #checkouts_table')")
714
+ if not user or not pin:
715
+ _no_credentials()
716
+ result = _form_login(p, user, pin)
717
+ raw = json.loads(p.eval(ACCOUNT_JS) or '{}')
718
+ if not raw.get('logged_in'):
719
+ raise KohaError('library form login failed: %s' % result)
720
+ out = _normalise_account(raw)
721
+ out['user'] = (raw.get('user') or '').strip()[:200]
722
+ return out
723
+
724
+
725
+ def status():
726
+ return {'cdp': CDP, 'cdp_up': _cdp_up(), 'chain_proxy': '127.0.0.1:%d' % CHAIN_PORT,
727
+ 'proxy_enabled': os.environ.get('KOHA_PROXY', '1').lower() not in ('0', 'false', 'no', ''),
728
+ 'chain_up': _port_open(CHAIN_PORT), 'profile': PROFILE,
729
+ 'credentials': all(credentials())}