dsh-zju-lecture-note 2.2.7 → 2.2.8

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.
@@ -15,11 +15,18 @@ and asks the browser process itself for its cookies through the Chrome DevTools
15
15
  Protocol (CDP). ABE never enters the picture, the user's daily Edge profile is
16
16
  never touched, and the login page handles SSO / 2FA normally.
17
17
 
18
- The cookie header is then stored securely:
18
+ The cookie header is then stored securely, always through a platform
19
+ credential facility (:mod:`zju_lecture.credential_store`):
19
20
 
20
21
  * Windows: DPAPI (``CryptProtectData``), decryptable only by the same Windows
21
22
  user on this machine;
22
- * macOS / Linux: a ``0600`` file under the user's state directory.
23
+ * macOS: a generic-password item in the login Keychain;
24
+ * Linux: a Secret Service item written through ``secret-tool``;
25
+ * none of the above available (or ``ZJU_LOGIN_STORAGE=memory``): the session
26
+ stays in this process only — **no plaintext file is ever written**.
27
+
28
+ The dedicated browser profile is deleted after the cookie is extracted, so the
29
+ browser's own copy of the session does not survive either.
23
30
 
24
31
  No password is ever accepted or stored. The only inputs are a classroom URL,
25
32
  a timeout and a ``clear`` flag.
@@ -37,29 +44,35 @@ import socket
37
44
  import struct
38
45
  import subprocess
39
46
  import sys
40
- import tempfile
41
47
  import time
42
48
  import urllib.parse
43
49
  import urllib.request
44
50
  from typing import Any, Dict, List, Optional, Tuple
45
51
 
52
+ from . import credential_store
46
53
  from .client import extract_classroom_token, is_zju_host
47
54
  from .cookies import DEFAULT_DOMAIN, _host_matches, _parent_domain, _secure_remove
55
+ from .credential_store import (
56
+ LOGIN_DIR_ENV,
57
+ StoreUnavailable,
58
+ login_dir,
59
+ session_file,
60
+ )
48
61
  from .security import cookie_names, sanitize_cookie_header
49
62
 
50
63
  IS_WIN = sys.platform == "win32"
51
64
  IS_MAC = sys.platform == "darwin"
52
65
 
53
66
  DEFAULT_LOGIN_URL = "https://classroom.zju.edu.cn/"
54
- LOGIN_DIR_ENV = "ZJU_LOGIN_DIR"
55
67
  BROWSER_ENV = "ZJU_BROWSER_BIN"
56
68
 
57
- SESSION_MAGIC = b"ZJU-LOGIN\x01"
69
+ #: Kept for callers/tests: the legacy blob magic, the payload version and the
70
+ #: same ceiling the 2.2.7 file format used.
71
+ SESSION_MAGIC = credential_store.LEGACY_BLOB_MAGIC
58
72
  SESSION_VERSION = 1
59
- SESSION_MAX_BYTES = 64 * 1024
60
- SESSION_ENTROPY = b"zju-lecture-summarizer-login-v1"
73
+ SESSION_MAX_BYTES = credential_store.SESSION_MAX_BYTES
74
+ SESSION_ENTROPY = credential_store.SESSION_ENTROPY
61
75
  PROFILE_DIR_NAME = "login-profile"
62
- SESSION_FILE_NAME = "session.bin"
63
76
 
64
77
  MAX_LOGIN_TIMEOUT = 540
65
78
  MIN_LOGIN_TIMEOUT = 30
@@ -86,32 +99,14 @@ class LoginError(Exception):
86
99
 
87
100
  # ------------------------------------------------------------------ locations
88
101
 
89
- def login_dir() -> str:
90
- """The per-user directory for the login profile and the saved session."""
91
- override = os.environ.get(LOGIN_DIR_ENV, "").strip()
92
- if override:
93
- return os.path.abspath(os.path.expanduser(override))
94
- if IS_WIN:
95
- base = os.environ.get("LOCALAPPDATA", "").strip() or os.path.join(
96
- os.path.expanduser("~"), "AppData", "Local"
97
- )
98
- return os.path.join(base, "zju-lecture")
99
- if IS_MAC:
100
- return os.path.join(os.path.expanduser("~"), "Library", "Application Support", "zju-lecture")
101
- base = os.environ.get("XDG_STATE_HOME", "").strip() or os.path.join(
102
- os.path.expanduser("~"), ".local", "state"
103
- )
104
- return os.path.join(base, "zju-lecture")
105
-
102
+ # ``login_dir`` / ``session_file`` live in :mod:`zju_lecture.credential_store`
103
+ # and are imported above: the directory is shared by the browser profile and the
104
+ # (Windows) encrypted session blob, so there is exactly one definition.
106
105
 
107
106
  def profile_dir() -> str:
108
107
  return os.path.join(login_dir(), PROFILE_DIR_NAME)
109
108
 
110
109
 
111
- def session_file() -> str:
112
- return os.path.join(login_dir(), SESSION_FILE_NAME)
113
-
114
-
115
110
  def _ensure_private_dir(path: str) -> None:
116
111
  os.makedirs(path, exist_ok=True)
117
112
  try:
@@ -203,99 +198,10 @@ def login_available() -> Tuple[bool, str]:
203
198
  return True, f"{browser_label(path)}({path})"
204
199
 
205
200
 
206
- # ------------------------------------------------------------------ DPAPI (Windows)
201
+ # ------------------------------------------------------------------ session store
207
202
 
208
- def _win_dpapi(data: bytes, protect: bool, entropy: bytes) -> bytes:
209
- """Protect/unprotect bytes with Windows DPAPI, bound to the current user."""
210
- import ctypes
211
- from ctypes import wintypes
212
-
213
- class DATA_BLOB(ctypes.Structure):
214
- _fields_ = [
215
- ("cbData", wintypes.DWORD),
216
- ("pbData", ctypes.POINTER(ctypes.c_char)),
217
- ]
218
-
219
- crypt32 = ctypes.WinDLL("crypt32", use_last_error=True)
220
- kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
221
-
222
- buf = ctypes.create_string_buffer(data, len(data))
223
- blob_in = DATA_BLOB(len(data), ctypes.cast(buf, ctypes.POINTER(ctypes.c_char)))
224
- blob_out = DATA_BLOB()
225
- entropy_buf = None
226
- entropy_blob = None
227
- if entropy:
228
- entropy_buf = ctypes.create_string_buffer(entropy, len(entropy))
229
- entropy_blob = DATA_BLOB(
230
- len(entropy), ctypes.cast(entropy_buf, ctypes.POINTER(ctypes.c_char))
231
- )
232
- p_entropy = ctypes.byref(entropy_blob) if entropy_blob is not None else None
233
- # CRYPTPROTECT_UI_FORBIDDEN: never show an OS prompt from a tool call.
234
- flags = 0x1
235
- try:
236
- if protect:
237
- ok = crypt32.CryptProtectData(
238
- ctypes.byref(blob_in), "zju-lecture login", p_entropy,
239
- None, None, flags, ctypes.byref(blob_out),
240
- )
241
- else:
242
- ok = crypt32.CryptUnprotectData(
243
- ctypes.byref(blob_in), None, p_entropy,
244
- None, None, flags, ctypes.byref(blob_out),
245
- )
246
- except OSError as exc:
247
- raise LoginError(
248
- f"Windows DPAPI 调用失败:{exc}",
249
- "请在当前 Windows 用户下重试;若仍失败,可改用 ZJU_COOKIE_FILE。",
250
- reason="save_failed",
251
- ) from exc
252
- if not ok:
253
- error = ctypes.get_last_error()
254
- raise LoginError(
255
- f"Windows DPAPI 调用失败(错误码 {error})。",
256
- "请确认当前 Windows 用户有可用的用户配置;也可改用 ZJU_COOKIE_FILE。",
257
- reason="save_failed",
258
- )
259
- try:
260
- return ctypes.string_at(blob_out.pbData, blob_out.cbData)
261
- finally:
262
- kernel32.LocalFree(blob_out.pbData)
263
-
264
-
265
- def _encode_session(payload: Dict[str, Any]) -> bytes:
266
- raw = json.dumps(payload, ensure_ascii=False).encode("utf-8")
267
- if len(raw) > SESSION_MAX_BYTES:
268
- raise LoginError("登录态过大,已拒绝保存。", reason="save_failed")
269
- if IS_WIN:
270
- return SESSION_MAGIC + b"D" + _win_dpapi(raw, True, SESSION_ENTROPY)
271
- return SESSION_MAGIC + b"P" + raw
272
-
273
-
274
- def _decode_session(blob: bytes) -> Optional[Dict[str, Any]]:
275
- if not blob.startswith(SESSION_MAGIC):
276
- return None
277
- mode = blob[len(SESSION_MAGIC): len(SESSION_MAGIC) + 1]
278
- body = blob[len(SESSION_MAGIC) + 1:]
279
- if mode == b"D":
280
- if not IS_WIN:
281
- return None
282
- try:
283
- body = _win_dpapi(body, False, SESSION_ENTROPY)
284
- except LoginError:
285
- return None
286
- elif mode != b"P":
287
- return None
288
- if len(body) > SESSION_MAX_BYTES:
289
- return None
290
- try:
291
- payload = json.loads(body.decode("utf-8"))
292
- except (UnicodeDecodeError, ValueError):
293
- return None
294
- return payload if isinstance(payload, dict) else None
295
-
296
-
297
- def save_session(cookie: str, browser: str = "") -> str:
298
- """Validate + persist the cookie header; return the file path."""
203
+ def _validated_payload(cookie: str, browser: str = "") -> Dict[str, Any]:
204
+ """Validate the cookie header and build the payload every backend stores."""
299
205
  try:
300
206
  header = sanitize_cookie_header(cookie)
301
207
  except ValueError as exc:
@@ -310,142 +216,170 @@ def save_session(cookie: str, browser: str = "") -> str:
310
216
  "请确认登录的是 classroom.zju.edu.cn(不是其他浙大站点),然后重试。",
311
217
  reason="save_failed",
312
218
  )
313
- payload = {
219
+ return {
314
220
  "version": SESSION_VERSION,
315
221
  "saved_at": int(time.time()),
316
222
  "browser": browser,
317
223
  "cookie": header,
318
224
  }
319
- blob = _encode_session(payload)
320
- directory = login_dir()
321
- target = session_file()
322
- tmp = ""
225
+
226
+
227
+ def _cookie_from_payload(payload: Optional[Dict[str, Any]]) -> Optional[str]:
228
+ """The usable cookie header inside a stored payload, or ``None``."""
229
+ if not payload or payload.get("version") != SESSION_VERSION:
230
+ return None
231
+ raw = payload.get("cookie")
232
+ if not isinstance(raw, str):
233
+ return None
323
234
  try:
324
- _ensure_private_dir(directory)
325
- # mkstemp 用 O_EXCL 建文件,固定 ".tmp" 路径可被预置的链接劫持。
326
- descriptor, tmp = tempfile.mkstemp(
327
- dir=directory, prefix=".zju-session-", suffix=".tmp"
328
- )
329
- # Create with 0600 from the first byte on POSIX; Windows ignores the
330
- # mode and relies on DPAPI plus the per-user profile directory.
331
- if hasattr(os, "fchmod"):
332
- try:
333
- os.fchmod(descriptor, 0o600)
334
- except OSError:
335
- pass
336
- with os.fdopen(descriptor, "wb") as handle:
337
- handle.write(blob)
338
- handle.flush()
339
- os.fsync(handle.fileno())
340
- os.replace(tmp, target)
341
- tmp = ""
342
- except OSError as exc:
343
- if tmp:
344
- try:
345
- os.unlink(tmp)
346
- except OSError:
347
- pass
348
- raise LoginError(
349
- f"登录成功,但保存登录态失败:{exc}",
350
- "本次会话仍可使用;请检查用户目录写权限,或改用 ZJU_COOKIE_FILE。",
351
- reason="save_failed",
352
- ) from exc
353
- return target
235
+ header = sanitize_cookie_header(raw)
236
+ except ValueError:
237
+ return None
238
+ return header if extract_classroom_token(header) else None
239
+
354
240
 
241
+ def _migrate_legacy_plaintext(backend: Any) -> Optional[str]:
242
+ """Read a 2.2.7 plaintext session file once, migrate it, then delete it.
355
243
 
356
- def _read_session_payload() -> Optional[Dict[str, Any]]:
244
+ The plaintext file must not survive on disk even when migration fails: the
245
+ whole point of this module is that no plaintext credential path remains.
246
+ The cookie is still returned so the current process can keep working.
247
+ """
357
248
  path = session_file()
358
249
  try:
359
250
  if not os.path.isfile(path) or os.path.getsize(path) > SESSION_MAX_BYTES + 1024:
360
251
  return None
361
252
  with open(path, "rb") as handle:
362
- payload = _decode_session(handle.read())
253
+ blob = handle.read()
363
254
  except OSError:
364
255
  return None
365
- if not payload or payload.get("version") != SESSION_VERSION:
256
+ decoded = credential_store.decode_legacy_blob(blob)
257
+ if not decoded or decoded[0] != "P":
366
258
  return None
367
- return payload
259
+ payload = decoded[1]
260
+ try:
261
+ backend.save(payload)
262
+ except StoreUnavailable:
263
+ pass
264
+ _secure_remove(path)
265
+ return _cookie_from_payload(payload)
266
+
267
+
268
+ def save_session(cookie: str, browser: str = "") -> str:
269
+ """Validate + persist the cookie header through the platform store.
270
+
271
+ Returns a human-readable descriptor (``"macOS 钥匙串(Keychain…)"``,
272
+ ``"Windows DPAPI 加密文件…"`` …). A missing/unusable store is **not** a
273
+ reason to write a plaintext file: the session stays in memory
274
+ (``backend().persistent`` is ``False``) and the caller tells the user.
275
+ """
276
+ payload = _validated_payload(cookie, browser)
277
+ _ensure_private_dir(login_dir())
278
+ try:
279
+ return credential_store.backend().save(payload)
280
+ except StoreUnavailable as exc:
281
+ raise LoginError(
282
+ f"登录成功,但未能写入加密凭据库:{exc.reason}",
283
+ exc.hint or "本次会话仍可使用;解锁系统凭据库后重试,或改用 ZJU_COOKIE_FILE。",
284
+ reason="save_failed",
285
+ ) from exc
368
286
 
369
287
 
370
288
  def load_session_cookie() -> Optional[str]:
371
289
  """Return the saved cookie header, or ``None`` when absent/invalid."""
372
- payload = _read_session_payload()
373
- if not payload:
374
- return None
375
- raw = payload.get("cookie")
376
- if not isinstance(raw, str):
377
- return None
290
+ backend = credential_store.backend()
378
291
  try:
379
- header = sanitize_cookie_header(raw)
380
- except ValueError:
381
- return None
382
- return header if extract_classroom_token(header) else None
292
+ payload = backend.load()
293
+ except StoreUnavailable:
294
+ payload = None
295
+ cookie = _cookie_from_payload(payload)
296
+ if cookie:
297
+ return cookie
298
+ # Upgrade path: 2.2.7 wrote plaintext on POSIX; read it once, migrate, delete.
299
+ return _migrate_legacy_plaintext(backend)
383
300
 
384
301
 
385
302
  def session_summary() -> Dict[str, Any]:
386
303
  """Credential-free description of the saved session (safe for diagnostics)."""
387
- payload = _read_session_payload()
388
- if not payload:
389
- return {"available": False, "path": session_file()}
390
- raw = payload.get("cookie")
391
- if not isinstance(raw, str):
392
- return {"available": False, "path": session_file()}
304
+ backend = credential_store.backend()
305
+ summary: Dict[str, Any] = {
306
+ "available": False,
307
+ "backend": backend.name,
308
+ "storage": backend.describe(),
309
+ "persistent": backend.persistent,
310
+ "advice": backend.advice(),
311
+ }
393
312
  try:
394
- header = sanitize_cookie_header(raw)
395
- except ValueError:
396
- return {"available": False, "path": session_file()}
313
+ payload = backend.load()
314
+ except StoreUnavailable as exc:
315
+ summary["reason"] = exc.reason
316
+ return summary
317
+ header = _cookie_from_payload(payload)
318
+ if not header:
319
+ return summary
397
320
  names = cookie_names(header)
398
- return {
399
- "available": bool(extract_classroom_token(header)),
400
- "path": session_file(),
401
- "saved_at": payload.get("saved_at"),
402
- "browser": payload.get("browser") or "",
321
+ summary.update({
322
+ "available": True,
323
+ "saved_at": (payload or {}).get("saved_at"),
324
+ "browser": (payload or {}).get("browser") or "",
403
325
  "cookie_count": len(names),
404
326
  "names": names,
405
- "has_token": bool(extract_classroom_token(header)),
406
- }
327
+ "has_token": True,
328
+ })
329
+ return summary
407
330
 
408
331
 
409
- def clear_session(delete_profile: bool = True) -> Dict[str, Any]:
410
- """Delete the saved session and (optionally) the dedicated browser profile."""
411
- removed_session = os.path.exists(session_file())
412
- if removed_session:
413
- _secure_remove(session_file())
414
- removed_profile = False
415
- profile_error = ""
416
- if delete_profile:
417
- profile = profile_dir()
418
- # Only ever delete our own directory; never follow a symlink out of it.
419
- expected = os.path.join(login_dir(), PROFILE_DIR_NAME)
420
- if os.path.normcase(os.path.abspath(profile)) == os.path.normcase(os.path.abspath(expected)):
421
- real = os.path.realpath(profile)
422
- is_link = os.path.normcase(real) != os.path.normcase(os.path.abspath(profile))
332
+ def _wipe_profile() -> Tuple[bool, str]:
333
+ """Delete the dedicated browser profile (a second copy of the cookies)."""
334
+ profile = profile_dir()
335
+ expected = os.path.join(login_dir(), PROFILE_DIR_NAME)
336
+ if os.path.normcase(os.path.abspath(profile)) != os.path.normcase(os.path.abspath(expected)):
337
+ return False, "登录窗口目录校验失败"
338
+ last_error = ""
339
+ for attempt in range(3):
340
+ real = os.path.realpath(profile)
341
+ is_link = os.path.normcase(real) != os.path.normcase(os.path.abspath(profile))
342
+ try:
423
343
  if is_link:
424
344
  # Never follow a symlink/junction outside our state directory.
425
345
  try:
426
346
  os.rmdir(profile)
427
347
  except OSError:
428
- try:
429
- os.unlink(profile)
430
- except OSError as exc:
431
- profile_error = str(exc)
432
- removed_profile = False
433
- else:
434
- removed_profile = True
435
- else:
436
- removed_profile = True
437
- elif os.path.isdir(profile):
438
- try:
439
- shutil.rmtree(profile)
440
- removed_profile = True
441
- except OSError as exc:
442
- profile_error = str(exc)
348
+ os.unlink(profile)
349
+ return True, ""
350
+ if not os.path.isdir(profile):
351
+ return False, ""
352
+ shutil.rmtree(profile)
353
+ return True, ""
354
+ except OSError as exc:
355
+ last_error = str(exc)
356
+ time.sleep(0.4 * (attempt + 1))
357
+ return False, last_error
358
+
359
+
360
+ def clear_session(delete_profile: bool = True) -> Dict[str, Any]:
361
+ """Delete the saved session (all backends) and the browser profile."""
362
+ backend = credential_store.backend()
363
+ removed_file = os.path.exists(session_file())
364
+ if removed_file:
365
+ _secure_remove(session_file())
366
+ backend_error = ""
367
+ cleared = False
368
+ try:
369
+ cleared = bool(backend.clear())
370
+ except StoreUnavailable as exc:
371
+ backend_error = exc.reason
372
+ if removed_file:
373
+ cleared = True
374
+ removed_profile, profile_error = _wipe_profile() if delete_profile else (False, "")
443
375
  try:
444
376
  os.rmdir(login_dir())
445
377
  except OSError:
446
378
  pass
447
379
  return {
448
- "session_removed": removed_session,
380
+ "session_removed": bool(cleared or removed_file),
381
+ "backend": backend.name,
382
+ "backend_error": backend_error,
449
383
  "profile_removed": removed_profile,
450
384
  "profile_error": profile_error,
451
385
  "profile_path": profile_dir(),
@@ -860,6 +794,7 @@ def open_login_window(url: str = "", timeout_s: int = 300) -> Dict[str, Any]:
860
794
 
861
795
  profile = profile_dir()
862
796
  try:
797
+ _ensure_private_dir(login_dir())
863
798
  _ensure_private_dir(profile)
864
799
  except OSError as exc:
865
800
  raise LoginError(
@@ -871,6 +806,7 @@ def open_login_window(url: str = "", timeout_s: int = 300) -> Dict[str, Any]:
871
806
  started = time.monotonic()
872
807
  process: Optional[subprocess.Popen] = None
873
808
  cdp: Optional[_Cdp] = None
809
+ result: Optional[Dict[str, Any]] = None
874
810
  try:
875
811
  # Always start a fresh instance. Reusing a stale DevToolsActivePort
876
812
  # could connect to an unrelated browser that reused the same port;
@@ -902,21 +838,27 @@ def open_login_window(url: str = "", timeout_s: int = 300) -> Dict[str, Any]:
902
838
  )
903
839
  header = _cookie_header_from_cdp(cookies)
904
840
  if header and extract_classroom_token(header):
905
- saved_path = ""
841
+ backend = credential_store.backend()
842
+ storage = backend.describe()
906
843
  save_error = ""
844
+ saved = False
907
845
  try:
908
- saved_path = save_session(header, browser=browser_label(binary))
846
+ storage = save_session(header, browser=browser_label(binary))
847
+ saved = backend.persistent
909
848
  except LoginError as exc:
910
849
  save_error = exc.message
911
- return {
850
+ storage = f"{backend.describe()}(写入失败)"
851
+ result = {
912
852
  "cookie": header,
913
853
  "names": cookie_names(header),
914
854
  "browser": browser_label(binary),
915
855
  "elapsed": round(time.monotonic() - started, 1),
916
- "saved": bool(saved_path),
917
- "saved_path": saved_path,
856
+ "saved": saved,
857
+ "storage": storage,
858
+ "storage_advice": backend.advice(),
918
859
  "save_error": save_error,
919
860
  }
861
+ break
920
862
  if process is not None and process.poll() is not None:
921
863
  raise LoginError(
922
864
  "登录窗口已退出,没有检测到完整登录态。",
@@ -932,3 +874,14 @@ def open_login_window(url: str = "", timeout_s: int = 300) -> Dict[str, Any]:
932
874
  time.sleep(1.0)
933
875
  finally:
934
876
  _close_browser(cdp, process)
877
+
878
+ if result is None: # pragma: no cover - the loop only breaks on success
879
+ raise LoginError("登录窗口结束但没有取得登录态。", reason="closed")
880
+
881
+ # The dedicated profile holds the browser's own copy of the cookies. It is
882
+ # always wiped after a successful extraction: exactly one credential copy
883
+ # remains (the DPAPI blob / Keychain item / Secret Service item).
884
+ profile_removed, profile_error = _wipe_profile()
885
+ result["profile_removed"] = profile_removed
886
+ result["profile_error"] = profile_error
887
+ return result
@@ -363,6 +363,12 @@ def main():
363
363
  f"{result['profile_error']}。请先关闭该窗口后重试。",
364
364
  file=sys.stderr,
365
365
  )
366
+ if result.get("backend_error"):
367
+ print(
368
+ "凭据库中的登录态未能清除:"
369
+ f"{result['backend_error']}。可在系统钥匙串/密钥环里手动删除。",
370
+ file=sys.stderr,
371
+ )
366
372
  return
367
373
  try:
368
374
  result = open_login_window(args.url, args.timeout)
@@ -375,9 +381,25 @@ def main():
375
381
  print(f"- 浏览器: {result['browser']}")
376
382
  print(f"- Cookie: {len(result['names'])} 条(含 _token,值不回显)")
377
383
  if result.get("saved"):
378
- print(f"- 保存: {result['saved_path']}(仅当前系统用户可解密)")
384
+ print(
385
+ "- 保存: 已加密保存到 "
386
+ f"{result.get('storage') or '系统凭据库'}(不含账号密码)"
387
+ )
379
388
  else:
380
- print(f"- 保存失败: {result.get('save_error') or '未知原因'}(本次会话可用)")
389
+ print(
390
+ "- 保存: 未落盘("
391
+ f"{result.get('storage') or '本机没有可用的加密凭据库'})"
392
+ )
393
+ advice = str(result.get("storage_advice") or "").strip()
394
+ if advice:
395
+ print(f"- 说明: {advice}")
396
+ if result.get("save_error"):
397
+ print(f"- 保存失败原因: {result['save_error']}")
398
+ if result.get("profile_error"):
399
+ print(
400
+ "- 独立登录窗口配置未能清理:"
401
+ f"{result['profile_error']}(可运行 `zju-lecture login --clear` 重试)"
402
+ )
381
403
  print("现在可以运行 `zju-lecture fetch <url>`。")
382
404
 
383
405
  elif args.command == "cookie":
@@ -15,9 +15,10 @@ import sqlite3
15
15
  import subprocess
16
16
  import sys
17
17
  import tempfile
18
+ import time
18
19
  from typing import List, Optional, Tuple
19
20
 
20
- from .security import sanitize_cookie_header
21
+ from .security import REDACTOR, sanitize_cookie_header
21
22
 
22
23
  IS_WIN = sys.platform == "win32"
23
24
  IS_MAC = sys.platform == "darwin"
@@ -378,6 +379,37 @@ def _secure_remove_tree(tmp_dir: str) -> None:
378
379
  pass
379
380
 
380
381
 
382
+ def _sweep_stale_cookie_copies(max_age_seconds: int = 3600) -> int:
383
+ """Shred private cookie-DB copies left behind by a killed process.
384
+
385
+ The normal path overwrites and deletes the copy immediately. A power loss
386
+ or a ``kill -9`` between the copy and the cleanup can leave a plaintext
387
+ cookie database in the temp directory, which is exactly the "明文落盘" this
388
+ plugin promises not to create. Anything older than an hour cannot belong to
389
+ a live call (a read takes milliseconds), so it is removed on the next run.
390
+ """
391
+ root = tempfile.gettempdir()
392
+ try:
393
+ names = os.listdir(root)
394
+ except OSError:
395
+ return 0
396
+ removed = 0
397
+ now = time.time()
398
+ for name in names:
399
+ if not name.startswith("zju-lecture-cookie-"):
400
+ continue
401
+ path = os.path.join(root, name)
402
+ try:
403
+ age = now - os.path.getmtime(path)
404
+ except OSError:
405
+ continue
406
+ if age < max_age_seconds:
407
+ continue
408
+ _secure_remove_tree(path)
409
+ removed += 1
410
+ return removed
411
+
412
+
381
413
  def _copy_cookie_db(db_path: str) -> str:
382
414
  """Copy the live Edge cookie DB and its WAL sidecars into a private dir.
383
415
 
@@ -388,6 +420,7 @@ def _copy_cookie_db(db_path: str) -> str:
388
420
  which lets SQLite replay and checkpoint the WAL in *our* private copy; the
389
421
  browser's own files are never touched.
390
422
  """
423
+ _sweep_stale_cookie_copies()
391
424
  tmp_dir = tempfile.mkdtemp(prefix="zju-lecture-cookie-")
392
425
  try:
393
426
  os.chmod(tmp_dir, 0o700)
@@ -595,10 +628,16 @@ def read_edge_cookies(
595
628
  )
596
629
 
597
630
  if decrypt_failures:
598
- print(
599
- f"[zju-lecture] {decrypt_failures} 条 Edge Cookie 解密失败,已跳过。",
600
- file=sys.stderr,
631
+ # Route every diagnostic through the redactor, even a bare count: one
632
+ # code path writing to stderr directly is how a future message that
633
+ # *does* contain a value slips past the guarantee in SECURITY.md.
634
+ sys.stderr.write(
635
+ REDACTOR.redact(
636
+ f"[zju-lecture] {decrypt_failures} 条 Edge Cookie 解密失败,已跳过。"
637
+ )
638
+ + "\n"
601
639
  )
640
+ sys.stderr.flush()
602
641
 
603
642
  try:
604
643
  return sanitize_cookie_header("; ".join(pairs)), None