dsh-zju-lecture-note 2.2.6 → 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.
- package/CHANGELOG.md +154 -2
- package/README.md +77 -46
- package/SECURITY.md +169 -66
- package/docs/technical.md +101 -50
- package/lib/bridge.js +288 -79
- package/lib/client.js +1013 -758
- package/lib/index.js +349 -75
- package/lib/tools.js +28 -3
- package/lib/tools.schema.json +23 -3
- package/mcp.json +21 -0
- package/mcp_server.py +186 -44
- package/package.json +5 -2
- package/plugin.json +19 -0
- package/server.mjs +118 -0
- package/skills/scholia-notes/references/prelude.typ +9 -1
- package/skills/scholia-notes.manifest.json +3 -3
- package/skills/zju-lecture-summarizer/SKILL.md +14 -4
- package/skills/zju-lecture-summarizer/SLIDES.md +42 -5
- package/skills/zju-lecture-summarizer-help/SKILL.md +3 -3
- package/skills/zju-lecture-summarizer-help.manifest.json +4 -4
- package/skills/zju-lecture-summarizer-login/SKILL.md +1 -1
- package/skills/zju-lecture-summarizer-login.manifest.json +4 -4
- package/skills/zju-lecture-summarizer.manifest.json +6 -6
- package/zju_lecture/browser_login.py +174 -210
- package/zju_lecture/cli.py +50 -2
- package/zju_lecture/client.py +95 -18
- package/zju_lecture/cookies.py +43 -4
- package/zju_lecture/courseware.py +37 -2
- package/zju_lecture/credential_store.py +621 -0
- package/zju_lecture/deps.py +114 -17
- package/zju_lecture/handout.py +29 -3
- package/zju_lecture/note_lint.py +34 -10
- package/zju_lecture/paths.py +57 -2
- package/zju_lecture/prelude.typ +9 -1
- package/zju_lecture/slides.py +73 -35
- package/zju_lecture/study_notes.py +40 -4
|
@@ -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.
|
|
@@ -42,23 +49,30 @@ import urllib.parse
|
|
|
42
49
|
import urllib.request
|
|
43
50
|
from typing import Any, Dict, List, Optional, Tuple
|
|
44
51
|
|
|
52
|
+
from . import credential_store
|
|
45
53
|
from .client import extract_classroom_token, is_zju_host
|
|
46
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
|
+
)
|
|
47
61
|
from .security import cookie_names, sanitize_cookie_header
|
|
48
62
|
|
|
49
63
|
IS_WIN = sys.platform == "win32"
|
|
50
64
|
IS_MAC = sys.platform == "darwin"
|
|
51
65
|
|
|
52
66
|
DEFAULT_LOGIN_URL = "https://classroom.zju.edu.cn/"
|
|
53
|
-
LOGIN_DIR_ENV = "ZJU_LOGIN_DIR"
|
|
54
67
|
BROWSER_ENV = "ZJU_BROWSER_BIN"
|
|
55
68
|
|
|
56
|
-
|
|
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
|
|
57
72
|
SESSION_VERSION = 1
|
|
58
|
-
SESSION_MAX_BYTES =
|
|
59
|
-
SESSION_ENTROPY =
|
|
73
|
+
SESSION_MAX_BYTES = credential_store.SESSION_MAX_BYTES
|
|
74
|
+
SESSION_ENTROPY = credential_store.SESSION_ENTROPY
|
|
60
75
|
PROFILE_DIR_NAME = "login-profile"
|
|
61
|
-
SESSION_FILE_NAME = "session.bin"
|
|
62
76
|
|
|
63
77
|
MAX_LOGIN_TIMEOUT = 540
|
|
64
78
|
MIN_LOGIN_TIMEOUT = 30
|
|
@@ -85,32 +99,14 @@ class LoginError(Exception):
|
|
|
85
99
|
|
|
86
100
|
# ------------------------------------------------------------------ locations
|
|
87
101
|
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
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
|
-
|
|
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.
|
|
105
105
|
|
|
106
106
|
def profile_dir() -> str:
|
|
107
107
|
return os.path.join(login_dir(), PROFILE_DIR_NAME)
|
|
108
108
|
|
|
109
109
|
|
|
110
|
-
def session_file() -> str:
|
|
111
|
-
return os.path.join(login_dir(), SESSION_FILE_NAME)
|
|
112
|
-
|
|
113
|
-
|
|
114
110
|
def _ensure_private_dir(path: str) -> None:
|
|
115
111
|
os.makedirs(path, exist_ok=True)
|
|
116
112
|
try:
|
|
@@ -202,99 +198,10 @@ def login_available() -> Tuple[bool, str]:
|
|
|
202
198
|
return True, f"{browser_label(path)}({path})"
|
|
203
199
|
|
|
204
200
|
|
|
205
|
-
# ------------------------------------------------------------------
|
|
201
|
+
# ------------------------------------------------------------------ session store
|
|
206
202
|
|
|
207
|
-
def
|
|
208
|
-
"""
|
|
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."""
|
|
203
|
+
def _validated_payload(cookie: str, browser: str = "") -> Dict[str, Any]:
|
|
204
|
+
"""Validate the cookie header and build the payload every backend stores."""
|
|
298
205
|
try:
|
|
299
206
|
header = sanitize_cookie_header(cookie)
|
|
300
207
|
except ValueError as exc:
|
|
@@ -309,132 +216,170 @@ def save_session(cookie: str, browser: str = "") -> str:
|
|
|
309
216
|
"请确认登录的是 classroom.zju.edu.cn(不是其他浙大站点),然后重试。",
|
|
310
217
|
reason="save_failed",
|
|
311
218
|
)
|
|
312
|
-
|
|
219
|
+
return {
|
|
313
220
|
"version": SESSION_VERSION,
|
|
314
221
|
"saved_at": int(time.time()),
|
|
315
222
|
"browser": browser,
|
|
316
223
|
"cookie": header,
|
|
317
224
|
}
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
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
|
|
322
234
|
try:
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
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
|
|
235
|
+
header = sanitize_cookie_header(raw)
|
|
236
|
+
except ValueError:
|
|
237
|
+
return None
|
|
238
|
+
return header if extract_classroom_token(header) else None
|
|
239
|
+
|
|
343
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.
|
|
344
243
|
|
|
345
|
-
|
|
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
|
+
"""
|
|
346
248
|
path = session_file()
|
|
347
249
|
try:
|
|
348
250
|
if not os.path.isfile(path) or os.path.getsize(path) > SESSION_MAX_BYTES + 1024:
|
|
349
251
|
return None
|
|
350
252
|
with open(path, "rb") as handle:
|
|
351
|
-
|
|
253
|
+
blob = handle.read()
|
|
352
254
|
except OSError:
|
|
353
255
|
return None
|
|
354
|
-
|
|
256
|
+
decoded = credential_store.decode_legacy_blob(blob)
|
|
257
|
+
if not decoded or decoded[0] != "P":
|
|
355
258
|
return None
|
|
356
|
-
|
|
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
|
|
357
286
|
|
|
358
287
|
|
|
359
288
|
def load_session_cookie() -> Optional[str]:
|
|
360
289
|
"""Return the saved cookie header, or ``None`` when absent/invalid."""
|
|
361
|
-
|
|
362
|
-
if not payload:
|
|
363
|
-
return None
|
|
364
|
-
raw = payload.get("cookie")
|
|
365
|
-
if not isinstance(raw, str):
|
|
366
|
-
return None
|
|
290
|
+
backend = credential_store.backend()
|
|
367
291
|
try:
|
|
368
|
-
|
|
369
|
-
except
|
|
370
|
-
|
|
371
|
-
|
|
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)
|
|
372
300
|
|
|
373
301
|
|
|
374
302
|
def session_summary() -> Dict[str, Any]:
|
|
375
303
|
"""Credential-free description of the saved session (safe for diagnostics)."""
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
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
|
+
}
|
|
382
312
|
try:
|
|
383
|
-
|
|
384
|
-
except
|
|
385
|
-
|
|
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
|
|
386
320
|
names = cookie_names(header)
|
|
387
|
-
|
|
388
|
-
"available":
|
|
389
|
-
"
|
|
390
|
-
"
|
|
391
|
-
"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 "",
|
|
392
325
|
"cookie_count": len(names),
|
|
393
326
|
"names": names,
|
|
394
|
-
"has_token":
|
|
395
|
-
}
|
|
327
|
+
"has_token": True,
|
|
328
|
+
})
|
|
329
|
+
return summary
|
|
396
330
|
|
|
397
331
|
|
|
398
|
-
def
|
|
399
|
-
"""Delete the
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
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))
|
|
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:
|
|
412
343
|
if is_link:
|
|
413
344
|
# Never follow a symlink/junction outside our state directory.
|
|
414
345
|
try:
|
|
415
346
|
os.rmdir(profile)
|
|
416
347
|
except OSError:
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
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, "")
|
|
432
375
|
try:
|
|
433
376
|
os.rmdir(login_dir())
|
|
434
377
|
except OSError:
|
|
435
378
|
pass
|
|
436
379
|
return {
|
|
437
|
-
"session_removed":
|
|
380
|
+
"session_removed": bool(cleared or removed_file),
|
|
381
|
+
"backend": backend.name,
|
|
382
|
+
"backend_error": backend_error,
|
|
438
383
|
"profile_removed": removed_profile,
|
|
439
384
|
"profile_error": profile_error,
|
|
440
385
|
"profile_path": profile_dir(),
|
|
@@ -849,6 +794,7 @@ def open_login_window(url: str = "", timeout_s: int = 300) -> Dict[str, Any]:
|
|
|
849
794
|
|
|
850
795
|
profile = profile_dir()
|
|
851
796
|
try:
|
|
797
|
+
_ensure_private_dir(login_dir())
|
|
852
798
|
_ensure_private_dir(profile)
|
|
853
799
|
except OSError as exc:
|
|
854
800
|
raise LoginError(
|
|
@@ -860,6 +806,7 @@ def open_login_window(url: str = "", timeout_s: int = 300) -> Dict[str, Any]:
|
|
|
860
806
|
started = time.monotonic()
|
|
861
807
|
process: Optional[subprocess.Popen] = None
|
|
862
808
|
cdp: Optional[_Cdp] = None
|
|
809
|
+
result: Optional[Dict[str, Any]] = None
|
|
863
810
|
try:
|
|
864
811
|
# Always start a fresh instance. Reusing a stale DevToolsActivePort
|
|
865
812
|
# could connect to an unrelated browser that reused the same port;
|
|
@@ -891,21 +838,27 @@ def open_login_window(url: str = "", timeout_s: int = 300) -> Dict[str, Any]:
|
|
|
891
838
|
)
|
|
892
839
|
header = _cookie_header_from_cdp(cookies)
|
|
893
840
|
if header and extract_classroom_token(header):
|
|
894
|
-
|
|
841
|
+
backend = credential_store.backend()
|
|
842
|
+
storage = backend.describe()
|
|
895
843
|
save_error = ""
|
|
844
|
+
saved = False
|
|
896
845
|
try:
|
|
897
|
-
|
|
846
|
+
storage = save_session(header, browser=browser_label(binary))
|
|
847
|
+
saved = backend.persistent
|
|
898
848
|
except LoginError as exc:
|
|
899
849
|
save_error = exc.message
|
|
900
|
-
|
|
850
|
+
storage = f"{backend.describe()}(写入失败)"
|
|
851
|
+
result = {
|
|
901
852
|
"cookie": header,
|
|
902
853
|
"names": cookie_names(header),
|
|
903
854
|
"browser": browser_label(binary),
|
|
904
855
|
"elapsed": round(time.monotonic() - started, 1),
|
|
905
|
-
"saved":
|
|
906
|
-
"
|
|
856
|
+
"saved": saved,
|
|
857
|
+
"storage": storage,
|
|
858
|
+
"storage_advice": backend.advice(),
|
|
907
859
|
"save_error": save_error,
|
|
908
860
|
}
|
|
861
|
+
break
|
|
909
862
|
if process is not None and process.poll() is not None:
|
|
910
863
|
raise LoginError(
|
|
911
864
|
"登录窗口已退出,没有检测到完整登录态。",
|
|
@@ -921,3 +874,14 @@ def open_login_window(url: str = "", timeout_s: int = 300) -> Dict[str, Any]:
|
|
|
921
874
|
time.sleep(1.0)
|
|
922
875
|
finally:
|
|
923
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
|
package/zju_lecture/cli.py
CHANGED
|
@@ -38,6 +38,30 @@ from .paths import artifact_dir
|
|
|
38
38
|
from .security import describe_cookie, sanitize_cookie_header
|
|
39
39
|
|
|
40
40
|
|
|
41
|
+
def _confirm_cookie_reveal() -> bool:
|
|
42
|
+
"""Ask for a second confirmation before printing a Cookie in clear text.
|
|
43
|
+
|
|
44
|
+
``--reveal`` puts a live session credential into the terminal scrollback
|
|
45
|
+
and shell history. A non-interactive invocation (CI, a pipe) is refused
|
|
46
|
+
outright; an interactive one must type ``yes``.
|
|
47
|
+
"""
|
|
48
|
+
if not sys.stdin.isatty():
|
|
49
|
+
print(
|
|
50
|
+
"已拒绝 --reveal:非交互式终端不显示 Cookie 明文。"
|
|
51
|
+
"如需本机排查,请在终端里交互执行,或改用 `zju-lecture login`。",
|
|
52
|
+
file=sys.stderr,
|
|
53
|
+
)
|
|
54
|
+
return False
|
|
55
|
+
try:
|
|
56
|
+
answer = input("将回显 Cookie 明文(会进入终端历史),输入 yes 继续:")
|
|
57
|
+
except EOFError:
|
|
58
|
+
return False
|
|
59
|
+
if answer.strip().lower() != "yes":
|
|
60
|
+
print("已取消。")
|
|
61
|
+
return False
|
|
62
|
+
return True
|
|
63
|
+
|
|
64
|
+
|
|
41
65
|
def _read_cookie_file(path: str) -> str:
|
|
42
66
|
"""Read a cookie header from a local file (never printed)."""
|
|
43
67
|
with open(os.path.expanduser(path), "r", encoding="utf-8") as handle:
|
|
@@ -339,6 +363,12 @@ def main():
|
|
|
339
363
|
f"{result['profile_error']}。请先关闭该窗口后重试。",
|
|
340
364
|
file=sys.stderr,
|
|
341
365
|
)
|
|
366
|
+
if result.get("backend_error"):
|
|
367
|
+
print(
|
|
368
|
+
"凭据库中的登录态未能清除:"
|
|
369
|
+
f"{result['backend_error']}。可在系统钥匙串/密钥环里手动删除。",
|
|
370
|
+
file=sys.stderr,
|
|
371
|
+
)
|
|
342
372
|
return
|
|
343
373
|
try:
|
|
344
374
|
result = open_login_window(args.url, args.timeout)
|
|
@@ -351,12 +381,30 @@ def main():
|
|
|
351
381
|
print(f"- 浏览器: {result['browser']}")
|
|
352
382
|
print(f"- Cookie: {len(result['names'])} 条(含 _token,值不回显)")
|
|
353
383
|
if result.get("saved"):
|
|
354
|
-
print(
|
|
384
|
+
print(
|
|
385
|
+
"- 保存: 已加密保存到 "
|
|
386
|
+
f"{result.get('storage') or '系统凭据库'}(不含账号密码)"
|
|
387
|
+
)
|
|
355
388
|
else:
|
|
356
|
-
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
|
+
)
|
|
357
403
|
print("现在可以运行 `zju-lecture fetch <url>`。")
|
|
358
404
|
|
|
359
405
|
elif args.command == "cookie":
|
|
406
|
+
if args.reveal and not _confirm_cookie_reveal():
|
|
407
|
+
return
|
|
360
408
|
c = get_edge_cookie()
|
|
361
409
|
if not c:
|
|
362
410
|
print("未能在本机 Edge 找到 classroom.zju.edu.cn 的 Cookie。")
|