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
|
@@ -0,0 +1,621 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""Encrypted-at-rest session storage for every supported platform.
|
|
3
|
+
|
|
4
|
+
Design rules
|
|
5
|
+
------------
|
|
6
|
+
|
|
7
|
+
* **No plaintext, ever.** The classroom login cookie is only ever written
|
|
8
|
+
through a platform credential facility: DPAPI on Windows, the login Keychain
|
|
9
|
+
on macOS, Secret Service on Linux. When none of them is available the session
|
|
10
|
+
stays in memory and the caller is told why — re-login is preferred over a
|
|
11
|
+
plaintext file at any location.
|
|
12
|
+
* **Secrets never appear on a command line.** ``ps`` shows argv to every local
|
|
13
|
+
user on the machine, so the macOS write path goes through ``security -i``
|
|
14
|
+
(the command, including the secret, arrives on stdin) and the Linux write path
|
|
15
|
+
through ``secret-tool store`` (secret on stdin). Reads and deletes only pass
|
|
16
|
+
metadata (service / account).
|
|
17
|
+
* **No hand-rolled cryptography.** A key derived from a passphrase, a machine
|
|
18
|
+
id or a fixed constant protects nothing against another process running as
|
|
19
|
+
the same user, and it advertises "encrypted" while adding no real boundary.
|
|
20
|
+
The only implementations used here are the platform ones.
|
|
21
|
+
|
|
22
|
+
Honest boundary (also in ``SECURITY.md``): the OS store protects the secret
|
|
23
|
+
*at rest* — disk images, backups, other system users, a stolen laptop — and it
|
|
24
|
+
keeps it out of the plugin's own files. It does not protect against malware
|
|
25
|
+
already running as the same user, because such a process can ask the same store
|
|
26
|
+
for the same item.
|
|
27
|
+
|
|
28
|
+
Backend selection
|
|
29
|
+
-----------------
|
|
30
|
+
|
|
31
|
+
``ZJU_LOGIN_STORAGE=os`` (default) picks the platform backend; ``memory``
|
|
32
|
+
refuses to persist at all. A missing/unusable backend degrades to ``memory``
|
|
33
|
+
with a reason instead of falling back to a private file: the file *is* the
|
|
34
|
+
plaintext path this module exists to remove.
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
from __future__ import annotations
|
|
38
|
+
|
|
39
|
+
import base64
|
|
40
|
+
import ctypes
|
|
41
|
+
import json
|
|
42
|
+
import os
|
|
43
|
+
import shutil
|
|
44
|
+
import subprocess
|
|
45
|
+
import sys
|
|
46
|
+
import tempfile
|
|
47
|
+
from typing import Any, Callable, Dict, Optional, Sequence, Tuple
|
|
48
|
+
|
|
49
|
+
from .cookies import _secure_remove
|
|
50
|
+
|
|
51
|
+
#: Prefix of the keyring secret. ``[A-Za-z0-9_:-]`` only, so the value can never
|
|
52
|
+
#: be split by ``security -i``'s whitespace tokenizer or need quote escaping.
|
|
53
|
+
SECRET_PREFIX = "zju-lecture-session-v2:"
|
|
54
|
+
|
|
55
|
+
#: Legacy on-disk blob (2.2.7 and earlier). Windows wrote ``"D" + DPAPI``,
|
|
56
|
+
#: POSIX wrote ``"P" + plaintext``; only the reader keeps the plaintext branch.
|
|
57
|
+
LEGACY_BLOB_MAGIC = b"ZJU-LOGIN\x01"
|
|
58
|
+
|
|
59
|
+
#: DPAPI entropy — **must not change**, otherwise existing Windows sessions
|
|
60
|
+
#: become undecryptable.
|
|
61
|
+
SESSION_ENTROPY = b"zju-lecture-summarizer-login-v1"
|
|
62
|
+
|
|
63
|
+
#: The same ceiling the 2.2.7 file format used.
|
|
64
|
+
SESSION_MAX_BYTES = 64 * 1024
|
|
65
|
+
|
|
66
|
+
#: Keychain / Secret Service item identity.
|
|
67
|
+
SERVICE = "zju-lecture-classroom"
|
|
68
|
+
ACCOUNT = "classroom"
|
|
69
|
+
|
|
70
|
+
#: ``security -i`` and ``secret-tool`` can block on a locked keyring or a D-Bus
|
|
71
|
+
#: that never answers; a credential store must never hang a login or a doctor.
|
|
72
|
+
COMMAND_TIMEOUT_SECONDS = 10.0
|
|
73
|
+
|
|
74
|
+
STORAGE_ENV = "ZJU_LOGIN_STORAGE"
|
|
75
|
+
LOGIN_DIR_ENV = "ZJU_LOGIN_DIR"
|
|
76
|
+
SESSION_FILE_NAME = "session.bin"
|
|
77
|
+
|
|
78
|
+
IS_WIN = sys.platform == "win32"
|
|
79
|
+
IS_MAC = sys.platform == "darwin"
|
|
80
|
+
|
|
81
|
+
Runner = Callable[..., Tuple[int, str, str]]
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class StoreUnavailable(Exception):
|
|
85
|
+
"""A credential backend exists on paper but cannot be used right now.
|
|
86
|
+
|
|
87
|
+
``reason`` is a short, value-free sentence suitable for a tool result.
|
|
88
|
+
"""
|
|
89
|
+
|
|
90
|
+
def __init__(self, reason: str, hint: str = "") -> None:
|
|
91
|
+
self.reason = reason
|
|
92
|
+
self.hint = hint
|
|
93
|
+
super().__init__(f"{reason}\n{hint}" if hint else reason)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
# --------------------------------------------------------------------- encoding
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def encode_secret(payload: Dict[str, Any]) -> str:
|
|
100
|
+
"""Serialise one session payload into the keyring string format."""
|
|
101
|
+
raw = json.dumps(payload, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
|
|
102
|
+
if len(raw) > SESSION_MAX_BYTES:
|
|
103
|
+
raise StoreUnavailable("登录态过大,已拒绝保存。")
|
|
104
|
+
body = base64.urlsafe_b64encode(raw).rstrip(b"=").decode("ascii")
|
|
105
|
+
return SECRET_PREFIX + body
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def decode_secret(text: str) -> Optional[Dict[str, Any]]:
|
|
109
|
+
"""Parse a keyring string; ``None`` when it is not one of ours."""
|
|
110
|
+
value = str(text or "").strip()
|
|
111
|
+
if not value.startswith(SECRET_PREFIX):
|
|
112
|
+
return None
|
|
113
|
+
body = value[len(SECRET_PREFIX):].strip()
|
|
114
|
+
if not body or any(char.isspace() for char in body):
|
|
115
|
+
return None
|
|
116
|
+
padding = "=" * (-len(body) % 4)
|
|
117
|
+
try:
|
|
118
|
+
raw = base64.urlsafe_b64decode(body + padding)
|
|
119
|
+
except (ValueError, TypeError):
|
|
120
|
+
return None
|
|
121
|
+
if len(raw) > SESSION_MAX_BYTES:
|
|
122
|
+
return None
|
|
123
|
+
try:
|
|
124
|
+
payload = json.loads(raw.decode("utf-8"))
|
|
125
|
+
except (UnicodeDecodeError, ValueError):
|
|
126
|
+
return None
|
|
127
|
+
return payload if isinstance(payload, dict) else None
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def decode_legacy_blob(blob: bytes) -> Optional[Tuple[str, Dict[str, Any]]]:
|
|
131
|
+
"""Decode the 2.2.7 file format into ``(mode, payload)``.
|
|
132
|
+
|
|
133
|
+
``mode`` is ``"D"`` (DPAPI) or ``"P"`` (plaintext). The plaintext branch is
|
|
134
|
+
read-only and exists solely to migrate and delete old files.
|
|
135
|
+
"""
|
|
136
|
+
if not blob or not blob.startswith(LEGACY_BLOB_MAGIC):
|
|
137
|
+
return None
|
|
138
|
+
marker = blob[len(LEGACY_BLOB_MAGIC):][:1]
|
|
139
|
+
body = blob[len(LEGACY_BLOB_MAGIC) + 1:]
|
|
140
|
+
if marker == b"D":
|
|
141
|
+
if sys.platform != "win32":
|
|
142
|
+
return None
|
|
143
|
+
try:
|
|
144
|
+
body = _dpapi_unprotect(body)
|
|
145
|
+
except OSError:
|
|
146
|
+
return None
|
|
147
|
+
elif marker != b"P":
|
|
148
|
+
return None
|
|
149
|
+
if not body or len(body) > SESSION_MAX_BYTES:
|
|
150
|
+
return None
|
|
151
|
+
try:
|
|
152
|
+
payload = json.loads(body.decode("utf-8"))
|
|
153
|
+
except (UnicodeDecodeError, ValueError):
|
|
154
|
+
return None
|
|
155
|
+
if not isinstance(payload, dict):
|
|
156
|
+
return None
|
|
157
|
+
return marker.decode("ascii"), payload
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
# ------------------------------------------------------------------------- DPAPI
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _dpapi(data: bytes, protect: bool) -> bytes:
|
|
164
|
+
"""Protect/unprotect bytes with Windows DPAPI, bound to the current user."""
|
|
165
|
+
from ctypes import wintypes
|
|
166
|
+
|
|
167
|
+
class DATA_BLOB(ctypes.Structure):
|
|
168
|
+
_fields_ = [
|
|
169
|
+
("cbData", wintypes.DWORD),
|
|
170
|
+
("pbData", ctypes.POINTER(ctypes.c_char)),
|
|
171
|
+
]
|
|
172
|
+
|
|
173
|
+
crypt32 = ctypes.WinDLL("crypt32", use_last_error=True)
|
|
174
|
+
kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
|
|
175
|
+
|
|
176
|
+
buffer = ctypes.create_string_buffer(data, len(data))
|
|
177
|
+
blob_in = DATA_BLOB(len(data), ctypes.cast(buffer, ctypes.POINTER(ctypes.c_char)))
|
|
178
|
+
entropy_buffer = ctypes.create_string_buffer(SESSION_ENTROPY, len(SESSION_ENTROPY))
|
|
179
|
+
entropy_blob = DATA_BLOB(
|
|
180
|
+
len(SESSION_ENTROPY),
|
|
181
|
+
ctypes.cast(entropy_buffer, ctypes.POINTER(ctypes.c_char)),
|
|
182
|
+
)
|
|
183
|
+
blob_out = DATA_BLOB()
|
|
184
|
+
# CRYPTPROTECT_UI_FORBIDDEN: a tool call must never open an OS dialog.
|
|
185
|
+
flags = 0x1
|
|
186
|
+
if protect:
|
|
187
|
+
ok = crypt32.CryptProtectData(
|
|
188
|
+
ctypes.byref(blob_in), "zju-lecture login", ctypes.byref(entropy_blob),
|
|
189
|
+
None, None, flags, ctypes.byref(blob_out),
|
|
190
|
+
)
|
|
191
|
+
else:
|
|
192
|
+
ok = crypt32.CryptUnprotectData(
|
|
193
|
+
ctypes.byref(blob_in), None, ctypes.byref(entropy_blob),
|
|
194
|
+
None, None, flags, ctypes.byref(blob_out),
|
|
195
|
+
)
|
|
196
|
+
if not ok:
|
|
197
|
+
error = ctypes.get_last_error()
|
|
198
|
+
raise OSError(f"DPAPI 调用失败(错误码 {error})")
|
|
199
|
+
try:
|
|
200
|
+
return ctypes.string_at(blob_out.pbData, blob_out.cbData)
|
|
201
|
+
finally:
|
|
202
|
+
kernel32.LocalFree(blob_out.pbData)
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def _dpapi_unprotect(data: bytes) -> bytes:
|
|
206
|
+
if sys.platform != "win32":
|
|
207
|
+
raise OSError("DPAPI 只在 Windows 上可用")
|
|
208
|
+
return _dpapi(data, protect=False)
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
# ----------------------------------------------------------------------- runner
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def run_command(
|
|
215
|
+
argv: Sequence[str],
|
|
216
|
+
stdin_text: Optional[str] = None,
|
|
217
|
+
timeout: float = COMMAND_TIMEOUT_SECONDS,
|
|
218
|
+
) -> Tuple[int, str, str]:
|
|
219
|
+
"""Run one credential-store CLI call with a hard timeout.
|
|
220
|
+
|
|
221
|
+
A locked keyring or a half-initialised D-Bus session can block forever, so
|
|
222
|
+
``TimeoutExpired`` is mapped to :class:`StoreUnavailable` instead of being
|
|
223
|
+
allowed to hang ``zju_doctor`` or the login flow.
|
|
224
|
+
"""
|
|
225
|
+
try:
|
|
226
|
+
completed = subprocess.run(
|
|
227
|
+
list(argv),
|
|
228
|
+
input=stdin_text,
|
|
229
|
+
text=True,
|
|
230
|
+
capture_output=True,
|
|
231
|
+
timeout=timeout,
|
|
232
|
+
check=False,
|
|
233
|
+
)
|
|
234
|
+
except subprocess.TimeoutExpired as exc:
|
|
235
|
+
raise StoreUnavailable(
|
|
236
|
+
"凭据库响应超时(D-Bus/密钥环可能未解锁或无图形会话)",
|
|
237
|
+
"解锁密钥环后重试;无图形会话的服务器请改用 ZJU_COOKIE_FILE。",
|
|
238
|
+
) from exc
|
|
239
|
+
except FileNotFoundError as exc:
|
|
240
|
+
raise StoreUnavailable(f"未找到命令 {argv[0]}") from exc
|
|
241
|
+
except OSError as exc:
|
|
242
|
+
raise StoreUnavailable(f"无法调用 {argv[0]}:{exc}") from exc
|
|
243
|
+
return completed.returncode, completed.stdout or "", completed.stderr or ""
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def _which(name: str) -> Optional[str]:
|
|
247
|
+
return shutil.which(name)
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
# --------------------------------------------------------------------- locations
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def login_dir() -> str:
|
|
254
|
+
"""The per-user directory for the login profile and legacy session file."""
|
|
255
|
+
override = str(os.environ.get(LOGIN_DIR_ENV, "") or "").strip()
|
|
256
|
+
if override:
|
|
257
|
+
return os.path.abspath(os.path.expanduser(override))
|
|
258
|
+
if IS_WIN:
|
|
259
|
+
base = str(os.environ.get("LOCALAPPDATA", "") or "").strip() or os.path.join(
|
|
260
|
+
os.path.expanduser("~"), "AppData", "Local"
|
|
261
|
+
)
|
|
262
|
+
return os.path.join(base, "zju-lecture")
|
|
263
|
+
if IS_MAC:
|
|
264
|
+
return os.path.join(os.path.expanduser("~"), "Library", "Application Support", "zju-lecture")
|
|
265
|
+
base = str(os.environ.get("XDG_STATE_HOME", "") or "").strip() or os.path.join(
|
|
266
|
+
os.path.expanduser("~"), ".local", "state"
|
|
267
|
+
)
|
|
268
|
+
return os.path.join(base, "zju-lecture")
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def session_file() -> str:
|
|
272
|
+
"""Path of the Windows DPAPI blob / of a legacy plaintext session file."""
|
|
273
|
+
return os.path.join(login_dir(), SESSION_FILE_NAME)
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
# ---------------------------------------------------------------------- backends
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
class SessionBackend:
|
|
280
|
+
"""One credential store. ``save`` returns a human-readable descriptor."""
|
|
281
|
+
|
|
282
|
+
name = "memory"
|
|
283
|
+
persistent = False
|
|
284
|
+
|
|
285
|
+
def describe(self) -> str:
|
|
286
|
+
raise NotImplementedError
|
|
287
|
+
|
|
288
|
+
def advice(self) -> str:
|
|
289
|
+
"""One actionable sentence when the backend cannot persist."""
|
|
290
|
+
return ""
|
|
291
|
+
|
|
292
|
+
def save(self, payload: Dict[str, Any]) -> str:
|
|
293
|
+
raise NotImplementedError
|
|
294
|
+
|
|
295
|
+
def load(self) -> Optional[Dict[str, Any]]:
|
|
296
|
+
raise NotImplementedError
|
|
297
|
+
|
|
298
|
+
def clear(self) -> bool:
|
|
299
|
+
return False
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
def _atomic_write(path: str, data: bytes, mode: int = 0o600) -> None:
|
|
303
|
+
"""Write ``data`` to ``path`` through a private temp file + ``os.replace``."""
|
|
304
|
+
directory = os.path.dirname(os.path.abspath(path)) or "."
|
|
305
|
+
os.makedirs(directory, exist_ok=True)
|
|
306
|
+
temporary = ""
|
|
307
|
+
try:
|
|
308
|
+
descriptor, temporary = tempfile.mkstemp(
|
|
309
|
+
dir=directory, prefix=".zju-session-", suffix=".tmp"
|
|
310
|
+
)
|
|
311
|
+
if hasattr(os, "fchmod"):
|
|
312
|
+
try:
|
|
313
|
+
os.fchmod(descriptor, mode)
|
|
314
|
+
except OSError:
|
|
315
|
+
pass
|
|
316
|
+
with os.fdopen(descriptor, "wb") as handle:
|
|
317
|
+
handle.write(data)
|
|
318
|
+
handle.flush()
|
|
319
|
+
os.fsync(handle.fileno())
|
|
320
|
+
os.replace(temporary, path)
|
|
321
|
+
temporary = ""
|
|
322
|
+
finally:
|
|
323
|
+
if temporary:
|
|
324
|
+
try:
|
|
325
|
+
os.unlink(temporary)
|
|
326
|
+
except OSError:
|
|
327
|
+
pass
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
class DpapiFileBackend(SessionBackend):
|
|
331
|
+
"""Windows: DPAPI-encrypted file, the 2.2.7 format kept for compatibility."""
|
|
332
|
+
|
|
333
|
+
name = "dpapi"
|
|
334
|
+
persistent = True
|
|
335
|
+
|
|
336
|
+
def __init__(self, path_provider: Callable[[], str]) -> None:
|
|
337
|
+
self._path_provider = path_provider
|
|
338
|
+
|
|
339
|
+
def describe(self) -> str:
|
|
340
|
+
return "Windows DPAPI 加密文件(%LOCALAPPDATA%\\zju-lecture,仅当前用户可解密)"
|
|
341
|
+
|
|
342
|
+
def save(self, payload: Dict[str, Any]) -> str:
|
|
343
|
+
raw = json.dumps(payload, ensure_ascii=False).encode("utf-8")
|
|
344
|
+
if len(raw) > SESSION_MAX_BYTES:
|
|
345
|
+
raise StoreUnavailable("登录态过大,已拒绝保存。")
|
|
346
|
+
try:
|
|
347
|
+
blob = LEGACY_BLOB_MAGIC + b"D" + _dpapi(raw, protect=True)
|
|
348
|
+
except OSError as exc:
|
|
349
|
+
raise StoreUnavailable(
|
|
350
|
+
f"DPAPI 加密失败:{exc}",
|
|
351
|
+
"在当前 Windows 用户下重试;仍失败可改用 ZJU_COOKIE_FILE。",
|
|
352
|
+
) from exc
|
|
353
|
+
try:
|
|
354
|
+
_atomic_write(self._path_provider(), blob)
|
|
355
|
+
except OSError as exc:
|
|
356
|
+
raise StoreUnavailable(
|
|
357
|
+
f"写入登录态文件失败:{exc}",
|
|
358
|
+
"检查用户目录写权限,或设置 ZJU_LOGIN_DIR。",
|
|
359
|
+
) from exc
|
|
360
|
+
return self.describe()
|
|
361
|
+
|
|
362
|
+
def load(self) -> Optional[Dict[str, Any]]:
|
|
363
|
+
path = self._path_provider()
|
|
364
|
+
try:
|
|
365
|
+
if not os.path.isfile(path) or os.path.getsize(path) > SESSION_MAX_BYTES + 1024:
|
|
366
|
+
return None
|
|
367
|
+
with open(path, "rb") as handle:
|
|
368
|
+
blob = handle.read()
|
|
369
|
+
except OSError:
|
|
370
|
+
return None
|
|
371
|
+
decoded = decode_legacy_blob(blob)
|
|
372
|
+
if not decoded:
|
|
373
|
+
return None
|
|
374
|
+
mode, payload = decoded
|
|
375
|
+
if mode == "P":
|
|
376
|
+
# A plaintext blob on Windows (e.g. copied from a POSIX machine)
|
|
377
|
+
# is rewritten through DPAPI in place.
|
|
378
|
+
try:
|
|
379
|
+
self.save(payload)
|
|
380
|
+
except StoreUnavailable:
|
|
381
|
+
pass
|
|
382
|
+
return payload
|
|
383
|
+
|
|
384
|
+
def clear(self) -> bool:
|
|
385
|
+
path = self._path_provider()
|
|
386
|
+
if not os.path.exists(path):
|
|
387
|
+
return False
|
|
388
|
+
_secure_remove(path)
|
|
389
|
+
return not os.path.exists(path)
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
def _security_failure(code: int, stdout: str, stderr: str) -> str:
|
|
393
|
+
"""Turn a ``security`` result into a failure sentence (``""`` when fine)."""
|
|
394
|
+
lines = [line.strip() for line in (stderr or "").splitlines() if line.strip()]
|
|
395
|
+
lines = [line for line in lines if not line.startswith("security>")]
|
|
396
|
+
if code == 45:
|
|
397
|
+
return "钥匙串中已有同名项且未能更新(exit 45)"
|
|
398
|
+
if code != 0:
|
|
399
|
+
detail = lines[0] if lines else "无错误输出"
|
|
400
|
+
return f"security 命令失败(exit {code}):{detail}"
|
|
401
|
+
if lines:
|
|
402
|
+
# Some macOS builds print the failure to stderr yet still exit 0; the
|
|
403
|
+
# read-back check in ``save`` is the authoritative guard, this is the
|
|
404
|
+
# fast path for an obviously broken call.
|
|
405
|
+
return f"security 报告错误(返回码 0):{lines[0]}"
|
|
406
|
+
return ""
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
class KeychainBackend(SessionBackend):
|
|
410
|
+
"""macOS: a generic-password item in the login Keychain."""
|
|
411
|
+
|
|
412
|
+
name = "keychain"
|
|
413
|
+
persistent = True
|
|
414
|
+
|
|
415
|
+
def __init__(self, runner: Runner = run_command) -> None:
|
|
416
|
+
self._run = runner
|
|
417
|
+
|
|
418
|
+
def describe(self) -> str:
|
|
419
|
+
return "macOS 钥匙串(Keychain,静态加密)"
|
|
420
|
+
|
|
421
|
+
def save(self, payload: Dict[str, Any]) -> str:
|
|
422
|
+
secret = encode_secret(payload)
|
|
423
|
+
# The payload charset is [A-Za-z0-9_:-]; refuse anything else rather than
|
|
424
|
+
# letting ``security -i`` split or mangle it.
|
|
425
|
+
if any(char.isspace() for char in secret):
|
|
426
|
+
raise StoreUnavailable("凭据含空白字符,已拒绝写入钥匙串。")
|
|
427
|
+
command = (
|
|
428
|
+
f"add-generic-password -U -s {SERVICE} -a {ACCOUNT} "
|
|
429
|
+
f"-l {SERVICE} -w {secret}"
|
|
430
|
+
)
|
|
431
|
+
code, out, err = self._run(
|
|
432
|
+
[_which("security") or "security", "-i"],
|
|
433
|
+
stdin_text=command + "\n",
|
|
434
|
+
)
|
|
435
|
+
problem = _security_failure(code, out, err)
|
|
436
|
+
if problem:
|
|
437
|
+
raise StoreUnavailable(problem, "调用 zju_login 重试;仍失败可改用 ZJU_COOKIE_FILE。")
|
|
438
|
+
if self.load() != payload:
|
|
439
|
+
self.clear()
|
|
440
|
+
raise StoreUnavailable(
|
|
441
|
+
"钥匙串写入后回读不一致,已删除该凭据项。",
|
|
442
|
+
"重试一次;仍失败请检查钥匙串是否已解锁。",
|
|
443
|
+
)
|
|
444
|
+
return self.describe()
|
|
445
|
+
|
|
446
|
+
def load(self) -> Optional[Dict[str, Any]]:
|
|
447
|
+
code, out, err = self._run(
|
|
448
|
+
[_which("security") or "security", "find-generic-password", "-w",
|
|
449
|
+
"-s", SERVICE, "-a", ACCOUNT]
|
|
450
|
+
)
|
|
451
|
+
if code == 44: # errSecItemNotFound
|
|
452
|
+
return None
|
|
453
|
+
problem = _security_failure(code, out, err)
|
|
454
|
+
if problem:
|
|
455
|
+
raise StoreUnavailable(problem)
|
|
456
|
+
return decode_secret(out)
|
|
457
|
+
|
|
458
|
+
def clear(self) -> bool:
|
|
459
|
+
try:
|
|
460
|
+
code, out, err = self._run(
|
|
461
|
+
[_which("security") or "security", "delete-generic-password",
|
|
462
|
+
"-s", SERVICE, "-a", ACCOUNT]
|
|
463
|
+
)
|
|
464
|
+
except StoreUnavailable:
|
|
465
|
+
return False
|
|
466
|
+
if code == 44:
|
|
467
|
+
return False
|
|
468
|
+
problem = _security_failure(code, out, err)
|
|
469
|
+
return not problem
|
|
470
|
+
|
|
471
|
+
|
|
472
|
+
class SecretToolBackend(SessionBackend):
|
|
473
|
+
"""Linux: Secret Service item written through ``secret-tool``."""
|
|
474
|
+
|
|
475
|
+
name = "secret-service"
|
|
476
|
+
persistent = True
|
|
477
|
+
|
|
478
|
+
def __init__(self, runner: Runner = run_command) -> None:
|
|
479
|
+
self._run = runner
|
|
480
|
+
|
|
481
|
+
def describe(self) -> str:
|
|
482
|
+
return "Linux 密钥环(Secret Service,静态加密)"
|
|
483
|
+
|
|
484
|
+
def save(self, payload: Dict[str, Any]) -> str:
|
|
485
|
+
secret = encode_secret(payload)
|
|
486
|
+
code, _out, err = self._run(
|
|
487
|
+
["secret-tool", "store", "--label", SERVICE,
|
|
488
|
+
"service", SERVICE, "account", ACCOUNT],
|
|
489
|
+
stdin_text=secret,
|
|
490
|
+
)
|
|
491
|
+
if code != 0:
|
|
492
|
+
detail = (err or "").strip().splitlines()
|
|
493
|
+
raise StoreUnavailable(
|
|
494
|
+
"写入密钥环失败:" + (detail[0] if detail else f"exit {code}"),
|
|
495
|
+
"确认密钥环已解锁;无桌面会话请改用 ZJU_COOKIE_FILE。",
|
|
496
|
+
)
|
|
497
|
+
if self.load() != payload:
|
|
498
|
+
self.clear()
|
|
499
|
+
raise StoreUnavailable(
|
|
500
|
+
"密钥环写入后回读不一致,已删除该凭据项。",
|
|
501
|
+
"重试一次;仍失败可改用 ZJU_COOKIE_FILE。",
|
|
502
|
+
)
|
|
503
|
+
return self.describe()
|
|
504
|
+
|
|
505
|
+
def load(self) -> Optional[Dict[str, Any]]:
|
|
506
|
+
code, out, err = self._run(
|
|
507
|
+
["secret-tool", "lookup", "service", SERVICE, "account", ACCOUNT]
|
|
508
|
+
)
|
|
509
|
+
if code == 0:
|
|
510
|
+
return decode_secret(out)
|
|
511
|
+
if (err or "").strip():
|
|
512
|
+
raise StoreUnavailable(
|
|
513
|
+
"读取密钥环失败:" + err.strip().splitlines()[0],
|
|
514
|
+
"确认 D-Bus 会话与密钥环可用;无桌面会话请改用 ZJU_COOKIE_FILE。",
|
|
515
|
+
)
|
|
516
|
+
return None
|
|
517
|
+
|
|
518
|
+
def clear(self) -> bool:
|
|
519
|
+
try:
|
|
520
|
+
code, _out, _err = self._run(
|
|
521
|
+
["secret-tool", "clear", "service", SERVICE, "account", ACCOUNT]
|
|
522
|
+
)
|
|
523
|
+
except StoreUnavailable:
|
|
524
|
+
return False
|
|
525
|
+
return code == 0
|
|
526
|
+
|
|
527
|
+
|
|
528
|
+
class MemoryBackend(SessionBackend):
|
|
529
|
+
"""No persistence at all: the session lives for this process only."""
|
|
530
|
+
|
|
531
|
+
name = "memory"
|
|
532
|
+
persistent = False
|
|
533
|
+
|
|
534
|
+
def __init__(self, reason: str = "") -> None:
|
|
535
|
+
self._payload: Optional[Dict[str, Any]] = None
|
|
536
|
+
self._reason = reason
|
|
537
|
+
|
|
538
|
+
def describe(self) -> str:
|
|
539
|
+
detail = f"({self._reason})" if self._reason else ""
|
|
540
|
+
return f"仅内存,不落盘{detail}"
|
|
541
|
+
|
|
542
|
+
def advice(self) -> str:
|
|
543
|
+
return (
|
|
544
|
+
"仅当前进程有效(CLI 单次命令退出即失效;"
|
|
545
|
+
"无桌面/无密钥环环境建议用 ZJU_COOKIE_FILE 自行管理登录态)。"
|
|
546
|
+
)
|
|
547
|
+
|
|
548
|
+
def save(self, payload: Dict[str, Any]) -> str:
|
|
549
|
+
self._payload = dict(payload)
|
|
550
|
+
return self.describe()
|
|
551
|
+
|
|
552
|
+
def load(self) -> Optional[Dict[str, Any]]:
|
|
553
|
+
return dict(self._payload) if self._payload else None
|
|
554
|
+
|
|
555
|
+
def clear(self) -> bool:
|
|
556
|
+
had = self._payload is not None
|
|
557
|
+
self._payload = None
|
|
558
|
+
return had
|
|
559
|
+
|
|
560
|
+
|
|
561
|
+
# ------------------------------------------------------------------- selection
|
|
562
|
+
|
|
563
|
+
|
|
564
|
+
def storage_mode() -> str:
|
|
565
|
+
"""``os`` (persist through the platform store) or ``memory`` (never persist)."""
|
|
566
|
+
raw = str(os.environ.get(STORAGE_ENV, "") or "").strip().lower()
|
|
567
|
+
return "memory" if raw in ("memory", "none", "off") else "os"
|
|
568
|
+
|
|
569
|
+
|
|
570
|
+
def default_backend(
|
|
571
|
+
platform: Optional[str] = None,
|
|
572
|
+
session_path: Optional[Callable[[], str]] = None,
|
|
573
|
+
runner: Runner = run_command,
|
|
574
|
+
) -> SessionBackend:
|
|
575
|
+
"""Pick the backend for ``platform`` without ever falling back to a file."""
|
|
576
|
+
system = platform or sys.platform
|
|
577
|
+
if storage_mode() == "memory":
|
|
578
|
+
return MemoryBackend("ZJU_LOGIN_STORAGE=memory")
|
|
579
|
+
if system == "win32":
|
|
580
|
+
return DpapiFileBackend(session_path or session_file)
|
|
581
|
+
if system == "darwin":
|
|
582
|
+
if _which("security"):
|
|
583
|
+
return KeychainBackend(runner)
|
|
584
|
+
return MemoryBackend("未找到 macOS security 命令")
|
|
585
|
+
if system.startswith("linux"):
|
|
586
|
+
if _which("secret-tool"):
|
|
587
|
+
return SecretToolBackend(runner)
|
|
588
|
+
return MemoryBackend(
|
|
589
|
+
"未找到 secret-tool(安装 libsecret-tools 后可持久化)"
|
|
590
|
+
)
|
|
591
|
+
return MemoryBackend(f"当前平台({system})没有可用的加密凭据库")
|
|
592
|
+
|
|
593
|
+
|
|
594
|
+
_BACKEND: Optional[SessionBackend] = None
|
|
595
|
+
_BACKEND_KEY: Optional[Tuple[str, str, str]] = None
|
|
596
|
+
|
|
597
|
+
|
|
598
|
+
def session_path_from(login_dir: Callable[[], str], filename: str = "session.bin") -> Callable[[], str]:
|
|
599
|
+
"""Lazily resolve ``<login dir>/<filename>`` (the env can change per test)."""
|
|
600
|
+
return lambda: os.path.join(login_dir(), filename)
|
|
601
|
+
|
|
602
|
+
|
|
603
|
+
def backend() -> SessionBackend:
|
|
604
|
+
"""The process-wide backend, rebuilt when the environment changes."""
|
|
605
|
+
global _BACKEND, _BACKEND_KEY
|
|
606
|
+
key = (
|
|
607
|
+
storage_mode(),
|
|
608
|
+
os.environ.get("ZJU_LOGIN_DIR", ""),
|
|
609
|
+
sys.platform,
|
|
610
|
+
)
|
|
611
|
+
if _BACKEND is None or key != _BACKEND_KEY:
|
|
612
|
+
_BACKEND = default_backend()
|
|
613
|
+
_BACKEND_KEY = key
|
|
614
|
+
return _BACKEND
|
|
615
|
+
|
|
616
|
+
|
|
617
|
+
def reset_backend() -> None:
|
|
618
|
+
"""Forget the cached backend (tests, or after ``zju_login(clear=true)``)."""
|
|
619
|
+
global _BACKEND, _BACKEND_KEY
|
|
620
|
+
_BACKEND = None
|
|
621
|
+
_BACKEND_KEY = None
|
package/zju_lecture/deps.py
CHANGED
|
@@ -608,6 +608,22 @@ def compile_args(workspace_root: str) -> List[str]:
|
|
|
608
608
|
return args
|
|
609
609
|
|
|
610
610
|
|
|
611
|
+
def typst_env() -> Dict[str, str]:
|
|
612
|
+
"""Child environment for ``typst``: the parent's, minus every credential.
|
|
613
|
+
|
|
614
|
+
Typst needs ``PATH`` / proxy / locale variables, but it has no business
|
|
615
|
+
inheriting the classroom session that this process happens to hold in
|
|
616
|
+
``ZJU_COOKIE`` / ``ZJU_COOKIE_FILE``. The filter is case-insensitive so a
|
|
617
|
+
differently cased variable on a case-insensitive platform cannot slip
|
|
618
|
+
through.
|
|
619
|
+
"""
|
|
620
|
+
return {
|
|
621
|
+
key: value
|
|
622
|
+
for key, value in os.environ.items()
|
|
623
|
+
if not str(key).upper().startswith("ZJU_COOKIE")
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
|
|
611
627
|
def ensure_dir(path: str) -> str:
|
|
612
628
|
os.makedirs(path, exist_ok=True)
|
|
613
629
|
return path
|