dsh-zju-lecture-note 2.2.7 → 2.2.9

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:
@@ -307,145 +213,174 @@ def save_session(cookie: str, browser: str = "") -> str:
307
213
  if not extract_classroom_token(header):
308
214
  raise LoginError(
309
215
  "登录态里没有 _token,无法用于字幕鉴权。",
310
- "请确认登录的是 classroom.zju.edu.cn(不是其他浙大站点),然后重试。",
216
+ "请确认登录的是智云课堂 / 互动式课堂(classroom.zju.edu.cn 或 "
217
+ "interactivemeta.cmc.zju.edu.cn),而不是其他浙大站点,然后重试。",
311
218
  reason="save_failed",
312
219
  )
313
- payload = {
220
+ return {
314
221
  "version": SESSION_VERSION,
315
222
  "saved_at": int(time.time()),
316
223
  "browser": browser,
317
224
  "cookie": header,
318
225
  }
319
- blob = _encode_session(payload)
320
- directory = login_dir()
321
- target = session_file()
322
- tmp = ""
226
+
227
+
228
+ def _cookie_from_payload(payload: Optional[Dict[str, Any]]) -> Optional[str]:
229
+ """The usable cookie header inside a stored payload, or ``None``."""
230
+ if not payload or payload.get("version") != SESSION_VERSION:
231
+ return None
232
+ raw = payload.get("cookie")
233
+ if not isinstance(raw, str):
234
+ return None
323
235
  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
236
+ header = sanitize_cookie_header(raw)
237
+ except ValueError:
238
+ return None
239
+ return header if extract_classroom_token(header) else None
240
+
354
241
 
242
+ def _migrate_legacy_plaintext(backend: Any) -> Optional[str]:
243
+ """Read a 2.2.7 plaintext session file once, migrate it, then delete it.
355
244
 
356
- def _read_session_payload() -> Optional[Dict[str, Any]]:
245
+ The plaintext file must not survive on disk even when migration fails: the
246
+ whole point of this module is that no plaintext credential path remains.
247
+ The cookie is still returned so the current process can keep working.
248
+ """
357
249
  path = session_file()
358
250
  try:
359
251
  if not os.path.isfile(path) or os.path.getsize(path) > SESSION_MAX_BYTES + 1024:
360
252
  return None
361
253
  with open(path, "rb") as handle:
362
- payload = _decode_session(handle.read())
254
+ blob = handle.read()
363
255
  except OSError:
364
256
  return None
365
- if not payload or payload.get("version") != SESSION_VERSION:
257
+ decoded = credential_store.decode_legacy_blob(blob)
258
+ if not decoded or decoded[0] != "P":
366
259
  return None
367
- return payload
260
+ payload = decoded[1]
261
+ try:
262
+ backend.save(payload)
263
+ except StoreUnavailable:
264
+ pass
265
+ _secure_remove(path)
266
+ return _cookie_from_payload(payload)
267
+
268
+
269
+ def save_session(cookie: str, browser: str = "") -> str:
270
+ """Validate + persist the cookie header through the platform store.
271
+
272
+ Returns a human-readable descriptor (``"macOS 钥匙串(Keychain…)"``,
273
+ ``"Windows DPAPI 加密文件…"`` …). A missing/unusable store is **not** a
274
+ reason to write a plaintext file: the session stays in memory
275
+ (``backend().persistent`` is ``False``) and the caller tells the user.
276
+ """
277
+ payload = _validated_payload(cookie, browser)
278
+ _ensure_private_dir(login_dir())
279
+ try:
280
+ return credential_store.backend().save(payload)
281
+ except StoreUnavailable as exc:
282
+ raise LoginError(
283
+ f"登录成功,但未能写入加密凭据库:{exc.reason}",
284
+ exc.hint or "本次会话仍可使用;解锁系统凭据库后重试,或改用 ZJU_COOKIE_FILE。",
285
+ reason="save_failed",
286
+ ) from exc
368
287
 
369
288
 
370
289
  def load_session_cookie() -> Optional[str]:
371
290
  """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
291
+ backend = credential_store.backend()
378
292
  try:
379
- header = sanitize_cookie_header(raw)
380
- except ValueError:
381
- return None
382
- return header if extract_classroom_token(header) else None
293
+ payload = backend.load()
294
+ except StoreUnavailable:
295
+ payload = None
296
+ cookie = _cookie_from_payload(payload)
297
+ if cookie:
298
+ return cookie
299
+ # Upgrade path: 2.2.7 wrote plaintext on POSIX; read it once, migrate, delete.
300
+ return _migrate_legacy_plaintext(backend)
383
301
 
384
302
 
385
303
  def session_summary() -> Dict[str, Any]:
386
304
  """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()}
305
+ backend = credential_store.backend()
306
+ summary: Dict[str, Any] = {
307
+ "available": False,
308
+ "backend": backend.name,
309
+ "storage": backend.describe(),
310
+ "persistent": backend.persistent,
311
+ "advice": backend.advice(),
312
+ }
393
313
  try:
394
- header = sanitize_cookie_header(raw)
395
- except ValueError:
396
- return {"available": False, "path": session_file()}
314
+ payload = backend.load()
315
+ except StoreUnavailable as exc:
316
+ summary["reason"] = exc.reason
317
+ return summary
318
+ header = _cookie_from_payload(payload)
319
+ if not header:
320
+ return summary
397
321
  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 "",
322
+ summary.update({
323
+ "available": True,
324
+ "saved_at": (payload or {}).get("saved_at"),
325
+ "browser": (payload or {}).get("browser") or "",
403
326
  "cookie_count": len(names),
404
327
  "names": names,
405
- "has_token": bool(extract_classroom_token(header)),
406
- }
328
+ "has_token": True,
329
+ })
330
+ return summary
407
331
 
408
332
 
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))
333
+ def _wipe_profile() -> Tuple[bool, str]:
334
+ """Delete the dedicated browser profile (a second copy of the cookies)."""
335
+ profile = profile_dir()
336
+ expected = os.path.join(login_dir(), PROFILE_DIR_NAME)
337
+ if os.path.normcase(os.path.abspath(profile)) != os.path.normcase(os.path.abspath(expected)):
338
+ return False, "登录窗口目录校验失败"
339
+ last_error = ""
340
+ for attempt in range(3):
341
+ real = os.path.realpath(profile)
342
+ is_link = os.path.normcase(real) != os.path.normcase(os.path.abspath(profile))
343
+ try:
423
344
  if is_link:
424
345
  # Never follow a symlink/junction outside our state directory.
425
346
  try:
426
347
  os.rmdir(profile)
427
348
  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)
349
+ os.unlink(profile)
350
+ return True, ""
351
+ if not os.path.isdir(profile):
352
+ return False, ""
353
+ shutil.rmtree(profile)
354
+ return True, ""
355
+ except OSError as exc:
356
+ last_error = str(exc)
357
+ time.sleep(0.4 * (attempt + 1))
358
+ return False, last_error
359
+
360
+
361
+ def clear_session(delete_profile: bool = True) -> Dict[str, Any]:
362
+ """Delete the saved session (all backends) and the browser profile."""
363
+ backend = credential_store.backend()
364
+ removed_file = os.path.exists(session_file())
365
+ if removed_file:
366
+ _secure_remove(session_file())
367
+ backend_error = ""
368
+ cleared = False
369
+ try:
370
+ cleared = bool(backend.clear())
371
+ except StoreUnavailable as exc:
372
+ backend_error = exc.reason
373
+ if removed_file:
374
+ cleared = True
375
+ removed_profile, profile_error = _wipe_profile() if delete_profile else (False, "")
443
376
  try:
444
377
  os.rmdir(login_dir())
445
378
  except OSError:
446
379
  pass
447
380
  return {
448
- "session_removed": removed_session,
381
+ "session_removed": bool(cleared or removed_file),
382
+ "backend": backend.name,
383
+ "backend_error": backend_error,
449
384
  "profile_removed": removed_profile,
450
385
  "profile_error": profile_error,
451
386
  "profile_path": profile_dir(),
@@ -860,6 +795,7 @@ def open_login_window(url: str = "", timeout_s: int = 300) -> Dict[str, Any]:
860
795
 
861
796
  profile = profile_dir()
862
797
  try:
798
+ _ensure_private_dir(login_dir())
863
799
  _ensure_private_dir(profile)
864
800
  except OSError as exc:
865
801
  raise LoginError(
@@ -871,6 +807,7 @@ def open_login_window(url: str = "", timeout_s: int = 300) -> Dict[str, Any]:
871
807
  started = time.monotonic()
872
808
  process: Optional[subprocess.Popen] = None
873
809
  cdp: Optional[_Cdp] = None
810
+ result: Optional[Dict[str, Any]] = None
874
811
  try:
875
812
  # Always start a fresh instance. Reusing a stale DevToolsActivePort
876
813
  # could connect to an unrelated browser that reused the same port;
@@ -902,21 +839,27 @@ def open_login_window(url: str = "", timeout_s: int = 300) -> Dict[str, Any]:
902
839
  )
903
840
  header = _cookie_header_from_cdp(cookies)
904
841
  if header and extract_classroom_token(header):
905
- saved_path = ""
842
+ backend = credential_store.backend()
843
+ storage = backend.describe()
906
844
  save_error = ""
845
+ saved = False
907
846
  try:
908
- saved_path = save_session(header, browser=browser_label(binary))
847
+ storage = save_session(header, browser=browser_label(binary))
848
+ saved = backend.persistent
909
849
  except LoginError as exc:
910
850
  save_error = exc.message
911
- return {
851
+ storage = f"{backend.describe()}(写入失败)"
852
+ result = {
912
853
  "cookie": header,
913
854
  "names": cookie_names(header),
914
855
  "browser": browser_label(binary),
915
856
  "elapsed": round(time.monotonic() - started, 1),
916
- "saved": bool(saved_path),
917
- "saved_path": saved_path,
857
+ "saved": saved,
858
+ "storage": storage,
859
+ "storage_advice": backend.advice(),
918
860
  "save_error": save_error,
919
861
  }
862
+ break
920
863
  if process is not None and process.poll() is not None:
921
864
  raise LoginError(
922
865
  "登录窗口已退出,没有检测到完整登录态。",
@@ -932,3 +875,14 @@ def open_login_window(url: str = "", timeout_s: int = 300) -> Dict[str, Any]:
932
875
  time.sleep(1.0)
933
876
  finally:
934
877
  _close_browser(cdp, process)
878
+
879
+ if result is None: # pragma: no cover - the loop only breaks on success
880
+ raise LoginError("登录窗口结束但没有取得登录态。", reason="closed")
881
+
882
+ # The dedicated profile holds the browser's own copy of the cookies. It is
883
+ # always wiped after a successful extraction: exactly one credential copy
884
+ # remains (the DPAPI blob / Keychain item / Secret Service item).
885
+ profile_removed, profile_error = _wipe_profile()
886
+ result["profile_removed"] = profile_removed
887
+ result["profile_error"] = profile_error
888
+ 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":