dsh-zju-lecture-note 2.2.3 → 2.2.5

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 (43) hide show
  1. package/CHANGELOG.md +102 -1
  2. package/README.md +98 -150
  3. package/SECURITY.md +136 -44
  4. package/docs/technical.md +175 -45
  5. package/lib/client.js +14 -13
  6. package/lib/index.js +53 -19
  7. package/lib/tools.js +28 -3
  8. package/lib/tools.schema.json +28 -3
  9. package/mcp_server.py +285 -34
  10. package/package.json +6 -2
  11. package/skills/scholia-notes/SKILL.md +8 -1
  12. package/skills/scholia-notes/references/format-spec.md +57 -6
  13. package/skills/scholia-notes/references/prelude.typ +55 -0
  14. package/skills/scholia-notes/references/typography-spec.md +4 -4
  15. package/skills/scholia-notes.manifest.json +9 -9
  16. package/skills/zju-lecture-summarizer/SKILL.md +56 -11
  17. package/skills/zju-lecture-summarizer-help/SKILL.md +95 -0
  18. package/skills/zju-lecture-summarizer-help.manifest.json +14 -0
  19. package/skills/zju-lecture-summarizer-login/SKILL.md +40 -0
  20. package/skills/zju-lecture-summarizer-login.manifest.json +14 -0
  21. package/skills/zju-lecture-summarizer.manifest.json +4 -4
  22. package/zju_lecture/__init__.py +16 -0
  23. package/zju_lecture/browser_login.py +923 -0
  24. package/zju_lecture/cli.py +98 -3
  25. package/zju_lecture/client.py +808 -741
  26. package/zju_lecture/handout.py +390 -60
  27. package/zju_lecture/handout_prelude.typ +47 -2
  28. package/zju_lecture/note_lint.py +12 -0
  29. package/zju_lecture/prelude.typ +55 -0
  30. package/zju_lecture/study_notes.py +415 -4
  31. package/zju_lecture/typst-packages/VENDORED.md +1 -1
  32. package/zju_lecture/typst-packages/preview/noteworthy/0.4.0/LICENSE +20 -20
  33. package/zju_lecture/typst-packages/preview/noteworthy/0.4.0/lib.typ +128 -128
  34. package/zju_lecture/typst-packages/preview/noteworthy/0.4.0/typst.toml +15 -15
  35. package/zju_lecture/typst-packages/preview/scholia/0.1.0/src/lib.typ +2 -2
  36. package/zju_lecture/typst-packages/preview/showybox/2.0.4/LICENSE +21 -21
  37. package/zju_lecture/typst-packages/preview/showybox/2.0.4/lib/func.typ +142 -142
  38. package/zju_lecture/typst-packages/preview/showybox/2.0.4/lib/id.typ +11 -11
  39. package/zju_lecture/typst-packages/preview/showybox/2.0.4/lib/pre-rendering.typ +50 -50
  40. package/zju_lecture/typst-packages/preview/showybox/2.0.4/lib/sections.typ +141 -141
  41. package/zju_lecture/typst-packages/preview/showybox/2.0.4/lib/shadows.typ +118 -118
  42. package/zju_lecture/typst-packages/preview/showybox/2.0.4/showy.typ +267 -267
  43. package/zju_lecture/typst-packages/preview/showybox/2.0.4/typst.toml +11 -11
@@ -0,0 +1,923 @@
1
+ # -*- coding: utf-8 -*-
2
+ """One-click ZJU Classroom login through a dedicated browser profile.
3
+
4
+ Why this exists
5
+ ---------------
6
+
7
+ Recent Edge builds enable App-Bound Encryption (ABE) for cookies. Once ABE is
8
+ on, an external process cannot decrypt the cookie database even after Edge is
9
+ closed, so the old "read Edge cookies" path dead-ends and the user is asked to
10
+ open DevTools and copy a cookie by hand. That is unacceptable for non-technical
11
+ users.
12
+
13
+ This module opens a **separate** browser profile, navigates to the classroom,
14
+ and asks the browser process itself for its cookies through the Chrome DevTools
15
+ Protocol (CDP). ABE never enters the picture, the user's daily Edge profile is
16
+ never touched, and the login page handles SSO / 2FA normally.
17
+
18
+ The cookie header is then stored securely:
19
+
20
+ * Windows: DPAPI (``CryptProtectData``), decryptable only by the same Windows
21
+ user on this machine;
22
+ * macOS / Linux: a ``0600`` file under the user's state directory.
23
+
24
+ No password is ever accepted or stored. The only inputs are a classroom URL,
25
+ a timeout and a ``clear`` flag.
26
+
27
+ Everything is standard library only. The browser is expected to be Edge
28
+ (preferred) or Chrome / Chromium on Windows, macOS and Linux.
29
+ """
30
+
31
+ import base64
32
+ import hashlib
33
+ import json
34
+ import os
35
+ import shutil
36
+ import socket
37
+ import struct
38
+ import subprocess
39
+ import sys
40
+ import time
41
+ import urllib.parse
42
+ import urllib.request
43
+ from typing import Any, Dict, List, Optional, Tuple
44
+
45
+ from .client import extract_classroom_token, is_zju_host
46
+ from .cookies import DEFAULT_DOMAIN, _host_matches, _parent_domain, _secure_remove
47
+ from .security import cookie_names, sanitize_cookie_header
48
+
49
+ IS_WIN = sys.platform == "win32"
50
+ IS_MAC = sys.platform == "darwin"
51
+
52
+ DEFAULT_LOGIN_URL = "https://classroom.zju.edu.cn/"
53
+ LOGIN_DIR_ENV = "ZJU_LOGIN_DIR"
54
+ BROWSER_ENV = "ZJU_BROWSER_BIN"
55
+
56
+ SESSION_MAGIC = b"ZJU-LOGIN\x01"
57
+ SESSION_VERSION = 1
58
+ SESSION_MAX_BYTES = 64 * 1024
59
+ SESSION_ENTROPY = b"zju-lecture-summarizer-login-v1"
60
+ PROFILE_DIR_NAME = "login-profile"
61
+ SESSION_FILE_NAME = "session.bin"
62
+
63
+ MAX_LOGIN_TIMEOUT = 540
64
+ MIN_LOGIN_TIMEOUT = 30
65
+ DEVTOOLS_START_TIMEOUT = 30.0
66
+
67
+
68
+ class LoginError(Exception):
69
+ """A login-window failure with one actionable next step.
70
+
71
+ ``reason`` is machine-readable so the MCP layer can print one conclusion
72
+ instead of a list of maybes: ``no_browser`` / ``bad_url`` / ``launch_failed``
73
+ / ``devtools_blocked`` / ``closed`` / ``timeout`` / ``save_failed``.
74
+ """
75
+
76
+ def __init__(self, message: str, hint: str = "", reason: str = "unknown"):
77
+ super().__init__(message)
78
+ self.message = message
79
+ self.hint = hint
80
+ self.reason = reason
81
+
82
+ def __str__(self) -> str:
83
+ return f"{self.message}\n{self.hint}" if self.hint else self.message
84
+
85
+
86
+ # ------------------------------------------------------------------ locations
87
+
88
+ def login_dir() -> str:
89
+ """The per-user directory for the login profile and the saved session."""
90
+ override = os.environ.get(LOGIN_DIR_ENV, "").strip()
91
+ if override:
92
+ return os.path.abspath(os.path.expanduser(override))
93
+ if IS_WIN:
94
+ base = os.environ.get("LOCALAPPDATA", "").strip() or os.path.join(
95
+ os.path.expanduser("~"), "AppData", "Local"
96
+ )
97
+ return os.path.join(base, "zju-lecture")
98
+ if IS_MAC:
99
+ return os.path.join(os.path.expanduser("~"), "Library", "Application Support", "zju-lecture")
100
+ base = os.environ.get("XDG_STATE_HOME", "").strip() or os.path.join(
101
+ os.path.expanduser("~"), ".local", "state"
102
+ )
103
+ return os.path.join(base, "zju-lecture")
104
+
105
+
106
+ def profile_dir() -> str:
107
+ return os.path.join(login_dir(), PROFILE_DIR_NAME)
108
+
109
+
110
+ def session_file() -> str:
111
+ return os.path.join(login_dir(), SESSION_FILE_NAME)
112
+
113
+
114
+ def _ensure_private_dir(path: str) -> None:
115
+ os.makedirs(path, exist_ok=True)
116
+ try:
117
+ os.chmod(path, 0o700)
118
+ except OSError:
119
+ pass
120
+
121
+
122
+ # ------------------------------------------------------------------ browsers
123
+
124
+ def browser_candidates() -> List[str]:
125
+ """Existing browser executables, Edge first, then Chrome / Chromium."""
126
+ explicit = os.environ.get(BROWSER_ENV, "").strip()
127
+ if explicit:
128
+ expanded = os.path.abspath(os.path.expanduser(explicit))
129
+ return [expanded] if os.path.isfile(expanded) else []
130
+
131
+ candidates: List[str] = []
132
+ if IS_WIN:
133
+ bases = [
134
+ os.environ.get(name, "").strip()
135
+ for name in ("PROGRAMFILES", "PROGRAMFILES(X86)", "LOCALAPPDATA")
136
+ ]
137
+ bases = [base for base in bases if base]
138
+ # Edge first across every install root, then Chrome. Mixing the two
139
+ # inside each root made Chrome win whenever Edge lived in Program
140
+ # Files (x86) and Chrome in Program Files.
141
+ candidates.extend(
142
+ os.path.join(base, "Microsoft", "Edge", "Application", "msedge.exe")
143
+ for base in bases
144
+ )
145
+ candidates.extend(
146
+ os.path.join(base, "Google", "Chrome", "Application", "chrome.exe")
147
+ for base in bases
148
+ )
149
+ elif IS_MAC:
150
+ candidates.extend([
151
+ "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
152
+ os.path.join(os.path.expanduser("~"), "Applications", "Microsoft Edge.app",
153
+ "Contents", "MacOS", "Microsoft Edge"),
154
+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
155
+ os.path.join(os.path.expanduser("~"), "Applications", "Google Chrome.app",
156
+ "Contents", "MacOS", "Google Chrome"),
157
+ "/Applications/Chromium.app/Contents/MacOS/Chromium",
158
+ ])
159
+ else:
160
+ for name in (
161
+ "microsoft-edge-stable", "microsoft-edge", "google-chrome-stable",
162
+ "google-chrome", "chromium", "chromium-browser",
163
+ ):
164
+ found = shutil.which(name)
165
+ if found:
166
+ candidates.append(found)
167
+
168
+ seen = set()
169
+ result = []
170
+ for path in candidates:
171
+ key = os.path.normcase(os.path.abspath(path))
172
+ if key in seen:
173
+ continue
174
+ seen.add(key)
175
+ if os.path.isfile(path):
176
+ result.append(os.path.abspath(path))
177
+ return result
178
+
179
+
180
+ def find_browser() -> Optional[str]:
181
+ candidates = browser_candidates()
182
+ return candidates[0] if candidates else None
183
+
184
+
185
+ def browser_label(path: Optional[str]) -> str:
186
+ name = os.path.basename(path or "")
187
+ lowered = name.lower()
188
+ if "msedge" in lowered or "edge" in lowered:
189
+ return "Microsoft Edge"
190
+ if "chrome" in lowered:
191
+ return "Google Chrome"
192
+ if "chromium" in lowered:
193
+ return "Chromium"
194
+ return name or "浏览器"
195
+
196
+
197
+ def login_available() -> Tuple[bool, str]:
198
+ """``(available, detail)`` for diagnostics; never touches a credential."""
199
+ path = find_browser()
200
+ if not path:
201
+ return False, "未找到 Edge / Chrome / Chromium"
202
+ return True, f"{browser_label(path)}({path})"
203
+
204
+
205
+ # ------------------------------------------------------------------ DPAPI (Windows)
206
+
207
+ def _win_dpapi(data: bytes, protect: bool, entropy: bytes) -> bytes:
208
+ """Protect/unprotect bytes with Windows DPAPI, bound to the current user."""
209
+ import ctypes
210
+ from ctypes import wintypes
211
+
212
+ class DATA_BLOB(ctypes.Structure):
213
+ _fields_ = [
214
+ ("cbData", wintypes.DWORD),
215
+ ("pbData", ctypes.POINTER(ctypes.c_char)),
216
+ ]
217
+
218
+ crypt32 = ctypes.WinDLL("crypt32", use_last_error=True)
219
+ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
220
+
221
+ buf = ctypes.create_string_buffer(data, len(data))
222
+ blob_in = DATA_BLOB(len(data), ctypes.cast(buf, ctypes.POINTER(ctypes.c_char)))
223
+ blob_out = DATA_BLOB()
224
+ entropy_buf = None
225
+ entropy_blob = None
226
+ if entropy:
227
+ entropy_buf = ctypes.create_string_buffer(entropy, len(entropy))
228
+ entropy_blob = DATA_BLOB(
229
+ len(entropy), ctypes.cast(entropy_buf, ctypes.POINTER(ctypes.c_char))
230
+ )
231
+ p_entropy = ctypes.byref(entropy_blob) if entropy_blob is not None else None
232
+ # CRYPTPROTECT_UI_FORBIDDEN: never show an OS prompt from a tool call.
233
+ flags = 0x1
234
+ try:
235
+ if protect:
236
+ ok = crypt32.CryptProtectData(
237
+ ctypes.byref(blob_in), "zju-lecture login", p_entropy,
238
+ None, None, flags, ctypes.byref(blob_out),
239
+ )
240
+ else:
241
+ ok = crypt32.CryptUnprotectData(
242
+ ctypes.byref(blob_in), None, p_entropy,
243
+ None, None, flags, ctypes.byref(blob_out),
244
+ )
245
+ except OSError as exc:
246
+ raise LoginError(
247
+ f"Windows DPAPI 调用失败:{exc}",
248
+ "请在当前 Windows 用户下重试;若仍失败,可改用 ZJU_COOKIE_FILE。",
249
+ reason="save_failed",
250
+ ) from exc
251
+ if not ok:
252
+ error = ctypes.get_last_error()
253
+ raise LoginError(
254
+ f"Windows DPAPI 调用失败(错误码 {error})。",
255
+ "请确认当前 Windows 用户有可用的用户配置;也可改用 ZJU_COOKIE_FILE。",
256
+ reason="save_failed",
257
+ )
258
+ try:
259
+ return ctypes.string_at(blob_out.pbData, blob_out.cbData)
260
+ finally:
261
+ kernel32.LocalFree(blob_out.pbData)
262
+
263
+
264
+ def _encode_session(payload: Dict[str, Any]) -> bytes:
265
+ raw = json.dumps(payload, ensure_ascii=False).encode("utf-8")
266
+ if len(raw) > SESSION_MAX_BYTES:
267
+ raise LoginError("登录态过大,已拒绝保存。", reason="save_failed")
268
+ if IS_WIN:
269
+ return SESSION_MAGIC + b"D" + _win_dpapi(raw, True, SESSION_ENTROPY)
270
+ return SESSION_MAGIC + b"P" + raw
271
+
272
+
273
+ def _decode_session(blob: bytes) -> Optional[Dict[str, Any]]:
274
+ if not blob.startswith(SESSION_MAGIC):
275
+ return None
276
+ mode = blob[len(SESSION_MAGIC): len(SESSION_MAGIC) + 1]
277
+ body = blob[len(SESSION_MAGIC) + 1:]
278
+ if mode == b"D":
279
+ if not IS_WIN:
280
+ return None
281
+ try:
282
+ body = _win_dpapi(body, False, SESSION_ENTROPY)
283
+ except LoginError:
284
+ return None
285
+ elif mode != b"P":
286
+ return None
287
+ if len(body) > SESSION_MAX_BYTES:
288
+ return None
289
+ try:
290
+ payload = json.loads(body.decode("utf-8"))
291
+ except (UnicodeDecodeError, ValueError):
292
+ return None
293
+ return payload if isinstance(payload, dict) else None
294
+
295
+
296
+ def save_session(cookie: str, browser: str = "") -> str:
297
+ """Validate + persist the cookie header; return the file path."""
298
+ try:
299
+ header = sanitize_cookie_header(cookie)
300
+ except ValueError as exc:
301
+ raise LoginError(
302
+ f"浏览器返回的登录态格式不合法:{exc}",
303
+ "请重试登录;若仍失败,改用 ZJU_COOKIE_FILE。",
304
+ reason="save_failed",
305
+ ) from exc
306
+ if not extract_classroom_token(header):
307
+ raise LoginError(
308
+ "登录态里没有 _token,无法用于字幕鉴权。",
309
+ "请确认登录的是 classroom.zju.edu.cn(不是其他浙大站点),然后重试。",
310
+ reason="save_failed",
311
+ )
312
+ payload = {
313
+ "version": SESSION_VERSION,
314
+ "saved_at": int(time.time()),
315
+ "browser": browser,
316
+ "cookie": header,
317
+ }
318
+ blob = _encode_session(payload)
319
+ directory = login_dir()
320
+ target = session_file()
321
+ tmp = target + ".tmp"
322
+ try:
323
+ _ensure_private_dir(directory)
324
+ # Create with 0600 from the first byte on POSIX; Windows ignores the
325
+ # mode and relies on DPAPI plus the per-user profile directory.
326
+ descriptor = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
327
+ with os.fdopen(descriptor, "wb") as handle:
328
+ handle.write(blob)
329
+ handle.flush()
330
+ os.fsync(handle.fileno())
331
+ os.replace(tmp, target)
332
+ except OSError as exc:
333
+ try:
334
+ os.unlink(tmp)
335
+ except OSError:
336
+ pass
337
+ raise LoginError(
338
+ f"登录成功,但保存登录态失败:{exc}",
339
+ "本次会话仍可使用;请检查用户目录写权限,或改用 ZJU_COOKIE_FILE。",
340
+ reason="save_failed",
341
+ ) from exc
342
+ return target
343
+
344
+
345
+ def _read_session_payload() -> Optional[Dict[str, Any]]:
346
+ path = session_file()
347
+ try:
348
+ if not os.path.isfile(path) or os.path.getsize(path) > SESSION_MAX_BYTES + 1024:
349
+ return None
350
+ with open(path, "rb") as handle:
351
+ payload = _decode_session(handle.read())
352
+ except OSError:
353
+ return None
354
+ if not payload or payload.get("version") != SESSION_VERSION:
355
+ return None
356
+ return payload
357
+
358
+
359
+ def load_session_cookie() -> Optional[str]:
360
+ """Return the saved cookie header, or ``None`` when absent/invalid."""
361
+ payload = _read_session_payload()
362
+ if not payload:
363
+ return None
364
+ raw = payload.get("cookie")
365
+ if not isinstance(raw, str):
366
+ return None
367
+ try:
368
+ header = sanitize_cookie_header(raw)
369
+ except ValueError:
370
+ return None
371
+ return header if extract_classroom_token(header) else None
372
+
373
+
374
+ def session_summary() -> Dict[str, Any]:
375
+ """Credential-free description of the saved session (safe for diagnostics)."""
376
+ payload = _read_session_payload()
377
+ if not payload:
378
+ return {"available": False, "path": session_file()}
379
+ raw = payload.get("cookie")
380
+ if not isinstance(raw, str):
381
+ return {"available": False, "path": session_file()}
382
+ try:
383
+ header = sanitize_cookie_header(raw)
384
+ except ValueError:
385
+ return {"available": False, "path": session_file()}
386
+ names = cookie_names(header)
387
+ return {
388
+ "available": bool(extract_classroom_token(header)),
389
+ "path": session_file(),
390
+ "saved_at": payload.get("saved_at"),
391
+ "browser": payload.get("browser") or "",
392
+ "cookie_count": len(names),
393
+ "names": names,
394
+ "has_token": bool(extract_classroom_token(header)),
395
+ }
396
+
397
+
398
+ def clear_session(delete_profile: bool = True) -> Dict[str, Any]:
399
+ """Delete the saved session and (optionally) the dedicated browser profile."""
400
+ removed_session = os.path.exists(session_file())
401
+ if removed_session:
402
+ _secure_remove(session_file())
403
+ removed_profile = False
404
+ profile_error = ""
405
+ if delete_profile:
406
+ profile = profile_dir()
407
+ # Only ever delete our own directory; never follow a symlink out of it.
408
+ expected = os.path.join(login_dir(), PROFILE_DIR_NAME)
409
+ if os.path.normcase(os.path.abspath(profile)) == os.path.normcase(os.path.abspath(expected)):
410
+ real = os.path.realpath(profile)
411
+ is_link = os.path.normcase(real) != os.path.normcase(os.path.abspath(profile))
412
+ if is_link:
413
+ # Never follow a symlink/junction outside our state directory.
414
+ try:
415
+ os.rmdir(profile)
416
+ except OSError:
417
+ try:
418
+ os.unlink(profile)
419
+ except OSError as exc:
420
+ profile_error = str(exc)
421
+ removed_profile = False
422
+ else:
423
+ removed_profile = True
424
+ else:
425
+ removed_profile = True
426
+ elif os.path.isdir(profile):
427
+ try:
428
+ shutil.rmtree(profile)
429
+ removed_profile = True
430
+ except OSError as exc:
431
+ profile_error = str(exc)
432
+ try:
433
+ os.rmdir(login_dir())
434
+ except OSError:
435
+ pass
436
+ return {
437
+ "session_removed": removed_session,
438
+ "profile_removed": removed_profile,
439
+ "profile_error": profile_error,
440
+ "profile_path": profile_dir(),
441
+ }
442
+
443
+
444
+ # ------------------------------------------------------------------ CDP transport
445
+
446
+ _WS_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
447
+
448
+
449
+ class _WSClosed(Exception):
450
+ pass
451
+
452
+
453
+ class _WebSocket:
454
+ """A minimal RFC 6455 client, enough for local CDP text frames."""
455
+
456
+ def __init__(self, url: str, timeout: float = 10.0):
457
+ parsed = urllib.parse.urlparse(url)
458
+ if parsed.scheme != "ws" or not parsed.hostname:
459
+ raise LoginError("浏览器调试端口地址不合法。", reason="devtools_blocked")
460
+ host = parsed.hostname
461
+ port = parsed.port or 80
462
+ self._sock = socket.create_connection((host, port), timeout=timeout)
463
+ self._buffer = bytearray()
464
+ key = base64.b64encode(os.urandom(16)).decode("ascii")
465
+ path = parsed.path or "/"
466
+ if parsed.query:
467
+ path += "?" + parsed.query
468
+ request = (
469
+ f"GET {path} HTTP/1.1\r\n"
470
+ f"Host: {host}:{port}\r\n"
471
+ "Upgrade: websocket\r\n"
472
+ "Connection: Upgrade\r\n"
473
+ f"Sec-WebSocket-Key: {key}\r\n"
474
+ "Sec-WebSocket-Version: 13\r\n\r\n"
475
+ )
476
+ self._sock.sendall(request.encode("ascii"))
477
+ self._read_handshake(key)
478
+
479
+ def _read_handshake(self, key: str) -> None:
480
+ header = bytearray()
481
+ while b"\r\n\r\n" not in header:
482
+ chunk = self._sock.recv(4096)
483
+ if not chunk:
484
+ raise LoginError("浏览器在调试握手时关闭了连接。", reason="devtools_blocked")
485
+ header.extend(chunk)
486
+ if len(header) > 65536:
487
+ raise LoginError("浏览器调试握手响应异常。", reason="devtools_blocked")
488
+ head, _, rest = bytes(header).partition(b"\r\n\r\n")
489
+ self._buffer.extend(rest)
490
+ lines = head.split(b"\r\n")
491
+ if not lines or b" 101 " not in lines[0]:
492
+ raise LoginError("浏览器拒绝本机调试连接。", reason="devtools_blocked")
493
+ headers = {}
494
+ for line in lines[1:]:
495
+ name, separator, value = line.partition(b":")
496
+ if separator:
497
+ headers[name.strip().lower()] = value.strip()
498
+ expected = base64.b64encode(
499
+ hashlib.sha1((key + _WS_GUID).encode("ascii")).digest()
500
+ )
501
+ if headers.get(b"sec-websocket-accept") != expected:
502
+ raise LoginError("浏览器调试握手校验失败。", reason="devtools_blocked")
503
+
504
+ def _read_exact(self, size: int, deadline: float) -> bytes:
505
+ while len(self._buffer) < size:
506
+ remaining = deadline - time.monotonic()
507
+ if remaining <= 0:
508
+ raise socket.timeout("websocket read timed out")
509
+ self._sock.settimeout(remaining)
510
+ chunk = self._sock.recv(65536)
511
+ if not chunk:
512
+ raise _WSClosed()
513
+ self._buffer.extend(chunk)
514
+ data = bytes(self._buffer[:size])
515
+ del self._buffer[:size]
516
+ return data
517
+
518
+ def _send_frame(self, opcode: int, payload: bytes = b"") -> None:
519
+ header = bytearray([0x80 | opcode])
520
+ length = len(payload)
521
+ if length < 126:
522
+ header.append(0x80 | length)
523
+ elif length < 65536:
524
+ header.append(0x80 | 126)
525
+ header.extend(struct.pack("!H", length))
526
+ else:
527
+ header.append(0x80 | 127)
528
+ header.extend(struct.pack("!Q", length))
529
+ mask = os.urandom(4)
530
+ header.extend(mask)
531
+ masked = bytes(byte ^ mask[index % 4] for index, byte in enumerate(payload))
532
+ self._sock.sendall(bytes(header) + masked)
533
+
534
+ def send_text(self, text: str) -> None:
535
+ self._send_frame(0x1, text.encode("utf-8"))
536
+
537
+ def recv_text(self, deadline: float) -> str:
538
+ fragments: List[bytes] = []
539
+ while True:
540
+ first, second = self._read_exact(2, deadline)
541
+ finished = bool(first & 0x80)
542
+ opcode = first & 0x0F
543
+ masked = bool(second & 0x80)
544
+ length = second & 0x7F
545
+ if length == 126:
546
+ length = struct.unpack("!H", self._read_exact(2, deadline))[0]
547
+ elif length == 127:
548
+ length = struct.unpack("!Q", self._read_exact(8, deadline))[0]
549
+ if length > 8 * 1024 * 1024:
550
+ raise LoginError("浏览器调试消息过大。", reason="devtools_blocked")
551
+ mask = self._read_exact(4, deadline) if masked else b""
552
+ payload = self._read_exact(length, deadline)
553
+ if masked:
554
+ payload = bytes(byte ^ mask[index % 4] for index, byte in enumerate(payload))
555
+ if opcode == 0x9:
556
+ self._send_frame(0xA, payload)
557
+ continue
558
+ if opcode == 0xA:
559
+ continue
560
+ if opcode == 0x8:
561
+ raise _WSClosed()
562
+ if opcode == 0x1:
563
+ fragments = [payload]
564
+ elif opcode == 0x0:
565
+ fragments.append(payload)
566
+ else:
567
+ continue
568
+ if finished:
569
+ return b"".join(fragments).decode("utf-8", "replace")
570
+
571
+ def close(self) -> None:
572
+ try:
573
+ self._send_frame(0x8)
574
+ except Exception:
575
+ pass
576
+ try:
577
+ self._sock.close()
578
+ except OSError:
579
+ pass
580
+
581
+
582
+ class _Cdp:
583
+ def __init__(self, ws_url: str, timeout: float = 10.0):
584
+ self._ws = _WebSocket(ws_url, timeout)
585
+ self._next_id = 0
586
+
587
+ def call(self, method: str, params: Optional[Dict[str, Any]] = None,
588
+ timeout: float = 10.0) -> Dict[str, Any]:
589
+ self._next_id += 1
590
+ request_id = self._next_id
591
+ self._ws.send_text(json.dumps({
592
+ "id": request_id,
593
+ "method": method,
594
+ "params": params or {},
595
+ }))
596
+ deadline = time.monotonic() + timeout
597
+ while True:
598
+ try:
599
+ message = json.loads(self._ws.recv_text(deadline))
600
+ except socket.timeout as exc:
601
+ raise LoginError(
602
+ f"等待浏览器响应超时({method})。",
603
+ "请重试;若反复超时,检查安全软件是否拦截了本机调试端口。",
604
+ reason="devtools_blocked",
605
+ ) from exc
606
+ if not isinstance(message, dict) or message.get("id") != request_id:
607
+ continue
608
+ if message.get("error"):
609
+ error = message["error"]
610
+ detail = error.get("message") if isinstance(error, dict) else str(error)
611
+ raise LoginError(
612
+ f"浏览器调试命令失败({method}):{detail}",
613
+ "请重试登录;若仍失败,改用 ZJU_COOKIE_FILE。",
614
+ reason="devtools_blocked",
615
+ )
616
+ return message.get("result") or {}
617
+
618
+ def close(self) -> None:
619
+ self._ws.close()
620
+
621
+
622
+ def _local_json(url: str, timeout: float = 2.0) -> Dict[str, Any]:
623
+ opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
624
+ with opener.open(url, timeout=timeout) as response:
625
+ return json.loads(response.read().decode("utf-8", "replace"))
626
+
627
+
628
+ def _read_active_port(profile: str) -> Optional[Tuple[int, str]]:
629
+ path = os.path.join(profile, "DevToolsActivePort")
630
+ try:
631
+ with open(path, "r", encoding="utf-8") as handle:
632
+ lines = handle.read().splitlines()
633
+ except OSError:
634
+ return None
635
+ if not lines:
636
+ return None
637
+ try:
638
+ port = int(lines[0].strip())
639
+ except (TypeError, ValueError):
640
+ return None
641
+ if not port:
642
+ return None
643
+ return port, (lines[1].strip() if len(lines) > 1 else "")
644
+
645
+
646
+ def _probe_endpoint(profile: str) -> Optional[str]:
647
+ """Return a browser websocket URL from a live DevToolsActivePort."""
648
+ active = _read_active_port(profile)
649
+ if not active:
650
+ return None
651
+ port, path = active
652
+ if path:
653
+ ws_url = f"ws://127.0.0.1:{port}{path}"
654
+ try:
655
+ version = _local_json(f"http://127.0.0.1:{port}/json/version", timeout=1.0)
656
+ except Exception:
657
+ return None
658
+ product = str(version.get("Browser") or "")
659
+ if "Edg" not in product and "Chrome" not in product and "Chromium" not in product:
660
+ return None
661
+ return ws_url
662
+ try:
663
+ version = _local_json(f"http://127.0.0.1:{port}/json/version", timeout=1.0)
664
+ except Exception:
665
+ return None
666
+ value = str(version.get("webSocketDebuggerUrl") or "")
667
+ return value if value.startswith("ws://127.0.0.1:") else None
668
+
669
+
670
+ def _wait_endpoint(profile: str, process: Optional[subprocess.Popen],
671
+ timeout: float = DEVTOOLS_START_TIMEOUT) -> str:
672
+ deadline = time.monotonic() + timeout
673
+ while time.monotonic() < deadline:
674
+ endpoint = _probe_endpoint(profile)
675
+ if endpoint:
676
+ return endpoint
677
+ if process is not None and process.poll() is not None:
678
+ # Give the port file a last chance: a forwarded instance can exit
679
+ # before the new one has finished writing.
680
+ time.sleep(0.3)
681
+ endpoint = _probe_endpoint(profile)
682
+ if endpoint:
683
+ return endpoint
684
+ raise LoginError(
685
+ "浏览器启动后立即退出。可能是独立登录窗口已在运行,或浏览器被策略禁止使用调试端口。",
686
+ "请关闭本插件打开的独立登录窗口后重试;仍不行就改用 ZJU_COOKIE_FILE 高级兜底。",
687
+ reason="launch_failed",
688
+ )
689
+ time.sleep(0.3)
690
+ raise LoginError(
691
+ "浏览器没有开放本机调试端口。",
692
+ "可能是企业策略禁用了远程调试,或被安全软件拦截。"
693
+ "请稍后重试;仍不行就改用 ZJU_COOKIE_FILE 高级兜底。",
694
+ reason="devtools_blocked",
695
+ )
696
+
697
+
698
+ # ------------------------------------------------------------------ cookies
699
+
700
+ def _cookie_header_from_cdp(cookies: List[Dict[str, Any]]) -> str:
701
+ """Keep exactly the cookies a browser would send to the classroom host.
702
+
703
+ Classroom-host cookies come first; domain-scoped ``.zju.edu.cn`` cookies
704
+ (where the PHP-serialized ``_token`` lives) come second. Host-only cookies
705
+ of other ZJU subdomains are excluded. Duplicate names keep the first row,
706
+ matching ``read_edge_cookies``.
707
+ """
708
+ parent = _parent_domain(DEFAULT_DOMAIN) or "zju.edu.cn"
709
+ rows: List[Tuple[int, str, str]] = []
710
+ for cookie in cookies:
711
+ if not isinstance(cookie, dict):
712
+ continue
713
+ name = str(cookie.get("name") or "").strip()
714
+ value = str(cookie.get("value") or "")
715
+ domain = str(cookie.get("domain") or "").strip()
716
+ if not name or not value:
717
+ continue
718
+ expires = cookie.get("expires")
719
+ if isinstance(expires, (int, float)) and 0 < expires < time.time():
720
+ continue
721
+ if _host_matches(domain, DEFAULT_DOMAIN):
722
+ tier = 0
723
+ elif domain.lower().lstrip(".") == parent.lower() and domain.startswith("."):
724
+ tier = 1
725
+ else:
726
+ continue
727
+ rows.append((tier, name, value))
728
+ rows.sort(key=lambda item: item[0])
729
+ seen = set()
730
+ pairs: List[str] = []
731
+ for _tier, name, value in rows:
732
+ if name in seen:
733
+ continue
734
+ seen.add(name)
735
+ pairs.append(f"{name}={value}")
736
+ if not pairs:
737
+ return ""
738
+ try:
739
+ return sanitize_cookie_header("; ".join(pairs))
740
+ except ValueError:
741
+ return ""
742
+
743
+
744
+ def _get_cookies(cdp: _Cdp) -> List[Dict[str, Any]]:
745
+ try:
746
+ result = cdp.call("Storage.getCookies", timeout=8.0)
747
+ except LoginError:
748
+ result = cdp.call("Network.getAllCookies", timeout=8.0)
749
+ value = result.get("cookies")
750
+ return value if isinstance(value, list) else []
751
+
752
+
753
+ # ------------------------------------------------------------------ login window
754
+
755
+ def sanitize_login_url(value: str) -> str:
756
+ """Only allow an https URL on ``*.zju.edu.cn`` (never a lookalike)."""
757
+ url = (value or "").strip()
758
+ if not url:
759
+ return DEFAULT_LOGIN_URL
760
+ if len(url) > 2048:
761
+ raise LoginError("登录链接过长。", reason="bad_url")
762
+ if url.startswith("//"):
763
+ url = "https:" + url
764
+ parsed = urllib.parse.urlparse(url)
765
+ if parsed.username or parsed.password:
766
+ raise LoginError("登录链接不能包含用户名或密码。", reason="bad_url")
767
+ if parsed.scheme == "http" and is_zju_host(parsed.hostname):
768
+ url = "https" + url[4:]
769
+ parsed = urllib.parse.urlparse(url)
770
+ if parsed.scheme != "https" or not is_zju_host(parsed.hostname):
771
+ raise LoginError(
772
+ "登录窗口只允许打开 https 的浙大域名(*.zju.edu.cn)。",
773
+ "请传这节课的智云课堂链接,例如 https://classroom.zju.edu.cn/livingroom?...",
774
+ reason="bad_url",
775
+ )
776
+ return url
777
+
778
+
779
+ def _launch_browser(binary: str, profile: str, url: str) -> subprocess.Popen:
780
+ args = [
781
+ binary,
782
+ f"--user-data-dir={profile}",
783
+ "--no-first-run",
784
+ "--no-default-browser-check",
785
+ "--disable-sync",
786
+ "--remote-debugging-port=0",
787
+ "--remote-debugging-address=127.0.0.1",
788
+ "--start-maximized",
789
+ url,
790
+ ]
791
+ kwargs: Dict[str, Any] = {
792
+ "stdout": subprocess.DEVNULL,
793
+ "stderr": subprocess.DEVNULL,
794
+ "stdin": subprocess.DEVNULL,
795
+ }
796
+ if IS_WIN:
797
+ kwargs["creationflags"] = getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0)
798
+ try:
799
+ return subprocess.Popen(args, **kwargs)
800
+ except OSError as exc:
801
+ raise LoginError(
802
+ f"无法启动浏览器:{exc}",
803
+ "请确认 Edge / Chrome 可正常打开;也可设置 ZJU_BROWSER_BIN 指向浏览器可执行文件。",
804
+ reason="launch_failed",
805
+ ) from exc
806
+
807
+
808
+ def _close_browser(cdp: Optional[_Cdp], process: Optional[subprocess.Popen]) -> None:
809
+ if cdp is not None:
810
+ try:
811
+ cdp.call("Browser.close", timeout=3.0)
812
+ except Exception:
813
+ pass
814
+ cdp.close()
815
+ if process is not None:
816
+ try:
817
+ process.wait(timeout=8)
818
+ except subprocess.TimeoutExpired:
819
+ try:
820
+ process.terminate()
821
+ process.wait(timeout=3)
822
+ except (OSError, subprocess.TimeoutExpired):
823
+ try:
824
+ process.kill()
825
+ except OSError:
826
+ pass
827
+
828
+
829
+ def open_login_window(url: str = "", timeout_s: int = 300) -> Dict[str, Any]:
830
+ """Open the dedicated login window and wait for a classroom ``_token``.
831
+
832
+ Returns a credential-free summary plus the cookie header for the caller's
833
+ in-process cache. The cookie is *never* printed by this module.
834
+ """
835
+ target = sanitize_login_url(url)
836
+ try:
837
+ timeout = int(timeout_s)
838
+ except (TypeError, ValueError):
839
+ timeout = 300
840
+ timeout = max(MIN_LOGIN_TIMEOUT, min(timeout, MAX_LOGIN_TIMEOUT))
841
+
842
+ binary = find_browser()
843
+ if not binary:
844
+ raise LoginError(
845
+ "未找到可用的浏览器(Edge / Chrome / Chromium)。",
846
+ "请先安装 Microsoft Edge 或 Google Chrome;无图形界面的服务器请改用 ZJU_COOKIE_FILE。",
847
+ reason="no_browser",
848
+ )
849
+
850
+ profile = profile_dir()
851
+ try:
852
+ _ensure_private_dir(profile)
853
+ except OSError as exc:
854
+ raise LoginError(
855
+ f"无法创建独立登录配置目录:{exc}",
856
+ "请检查用户状态目录的写权限,或设置 ZJU_LOGIN_DIR 指向可写目录;"
857
+ "无图形界面的服务器改用 ZJU_COOKIE_FILE。",
858
+ reason="launch_failed",
859
+ ) from exc
860
+ started = time.monotonic()
861
+ process: Optional[subprocess.Popen] = None
862
+ cdp: Optional[_Cdp] = None
863
+ try:
864
+ # Always start a fresh instance. Reusing a stale DevToolsActivePort
865
+ # could connect to an unrelated browser that reused the same port;
866
+ # if an old login window is still open, the new launch forwards to it
867
+ # and exits, and the error tells the user to close it.
868
+ try:
869
+ os.unlink(os.path.join(profile, "DevToolsActivePort"))
870
+ except OSError:
871
+ pass
872
+ process = _launch_browser(binary, profile, target)
873
+ endpoint = _wait_endpoint(profile, process)
874
+ try:
875
+ cdp = _Cdp(endpoint, timeout=10.0)
876
+ except (OSError, _WSClosed) as exc:
877
+ raise LoginError(
878
+ f"无法连接浏览器的本机调试端口:{exc}",
879
+ "请重试;若仍失败,可能是安全软件或企业策略拦截了本机调试。",
880
+ reason="devtools_blocked",
881
+ ) from exc
882
+ deadline = time.monotonic() + timeout
883
+ while True:
884
+ try:
885
+ cookies = _get_cookies(cdp)
886
+ except (OSError, _WSClosed):
887
+ raise LoginError(
888
+ "登录窗口已被关闭,没有检测到完整登录态。",
889
+ "请重新调用 zju_login,并在新窗口里完成登录后再关闭窗口。",
890
+ reason="closed",
891
+ )
892
+ header = _cookie_header_from_cdp(cookies)
893
+ if header and extract_classroom_token(header):
894
+ saved_path = ""
895
+ save_error = ""
896
+ try:
897
+ saved_path = save_session(header, browser=browser_label(binary))
898
+ except LoginError as exc:
899
+ save_error = exc.message
900
+ return {
901
+ "cookie": header,
902
+ "names": cookie_names(header),
903
+ "browser": browser_label(binary),
904
+ "elapsed": round(time.monotonic() - started, 1),
905
+ "saved": bool(saved_path),
906
+ "saved_path": saved_path,
907
+ "save_error": save_error,
908
+ }
909
+ if process is not None and process.poll() is not None:
910
+ raise LoginError(
911
+ "登录窗口已退出,没有检测到完整登录态。",
912
+ "请重新调用 zju_login,并完成登录。",
913
+ reason="closed",
914
+ )
915
+ if time.monotonic() >= deadline:
916
+ raise LoginError(
917
+ f"等待 {timeout} 秒仍未检测到登录完成。",
918
+ "请重新调用 zju_login;登录时不要关闭窗口,成功后窗口会自动关闭。",
919
+ reason="timeout",
920
+ )
921
+ time.sleep(1.0)
922
+ finally:
923
+ _close_browser(cdp, process)