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.
- package/ATTRIBUTION.md +1 -1
- package/CHANGELOG.md +108 -2
- package/README.md +57 -25
- package/SECURITY.md +96 -51
- package/docs/technical.md +98 -40
- package/lib/bridge.js +12 -2
- package/lib/client.js +142 -36
- package/lib/index.js +130 -22
- package/lib/tools.js +14 -11
- package/lib/tools.schema.json +14 -11
- package/mcp.json +21 -0
- package/mcp_server.py +258 -43
- package/package.json +5 -2
- package/plugin.json +19 -0
- package/server.mjs +118 -0
- package/skills/scholia-notes.manifest.json +1 -1
- package/skills/zju-lecture-summarizer/SKILL.md +46 -9
- package/skills/zju-lecture-summarizer/SLIDES.md +58 -14
- package/skills/zju-lecture-summarizer-help/SKILL.md +2 -2
- package/skills/zju-lecture-summarizer-help.manifest.json +4 -4
- package/skills/zju-lecture-summarizer-login.manifest.json +1 -1
- package/skills/zju-lecture-summarizer.manifest.json +6 -6
- package/zju_lecture/__init__.py +6 -0
- package/zju_lecture/browser_login.py +176 -222
- package/zju_lecture/cli.py +24 -2
- package/zju_lecture/client.py +325 -116
- package/zju_lecture/cookies.py +43 -4
- package/zju_lecture/credential_store.py +621 -0
- package/zju_lecture/deps.py +16 -0
- package/zju_lecture/formatter.py +201 -3
- package/zju_lecture/handout.py +29 -3
- package/zju_lecture/slides.py +9 -7
- package/zju_lecture/study_notes.py +4 -0
|
@@ -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
|
|
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
|
-
|
|
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 =
|
|
60
|
-
SESSION_ENTROPY =
|
|
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
|
-
|
|
90
|
-
|
|
91
|
-
|
|
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
|
-
# ------------------------------------------------------------------
|
|
201
|
+
# ------------------------------------------------------------------ session store
|
|
207
202
|
|
|
208
|
-
def
|
|
209
|
-
"""
|
|
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
|
-
"
|
|
216
|
+
"请确认登录的是智云课堂 / 互动式课堂(classroom.zju.edu.cn 或 "
|
|
217
|
+
"interactivemeta.cmc.zju.edu.cn),而不是其他浙大站点,然后重试。",
|
|
311
218
|
reason="save_failed",
|
|
312
219
|
)
|
|
313
|
-
|
|
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
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
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
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
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
|
-
|
|
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
|
-
|
|
254
|
+
blob = handle.read()
|
|
363
255
|
except OSError:
|
|
364
256
|
return None
|
|
365
|
-
|
|
257
|
+
decoded = credential_store.decode_legacy_blob(blob)
|
|
258
|
+
if not decoded or decoded[0] != "P":
|
|
366
259
|
return None
|
|
367
|
-
|
|
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
|
-
|
|
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
|
-
|
|
380
|
-
except
|
|
381
|
-
|
|
382
|
-
|
|
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
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
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
|
-
|
|
395
|
-
except
|
|
396
|
-
|
|
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
|
-
|
|
399
|
-
"available":
|
|
400
|
-
"
|
|
401
|
-
"
|
|
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":
|
|
406
|
-
}
|
|
328
|
+
"has_token": True,
|
|
329
|
+
})
|
|
330
|
+
return summary
|
|
407
331
|
|
|
408
332
|
|
|
409
|
-
def
|
|
410
|
-
"""Delete the
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
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
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
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":
|
|
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
|
-
|
|
842
|
+
backend = credential_store.backend()
|
|
843
|
+
storage = backend.describe()
|
|
906
844
|
save_error = ""
|
|
845
|
+
saved = False
|
|
907
846
|
try:
|
|
908
|
-
|
|
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
|
-
|
|
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":
|
|
917
|
-
"
|
|
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
|
package/zju_lecture/cli.py
CHANGED
|
@@ -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(
|
|
384
|
+
print(
|
|
385
|
+
"- 保存: 已加密保存到 "
|
|
386
|
+
f"{result.get('storage') or '系统凭据库'}(不含账号密码)"
|
|
387
|
+
)
|
|
379
388
|
else:
|
|
380
|
-
print(
|
|
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":
|