dsh-zju-lecture-note 2.2.6 → 2.2.7

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/mcp_server.py CHANGED
@@ -64,6 +64,7 @@ from zju_lecture.paths import (
64
64
  is_inside_workspace,
65
65
  note_target,
66
66
  primary_workspace,
67
+ require_workspace_path,
67
68
  resolve_path,
68
69
  )
69
70
  from zju_lecture.formatter import (
@@ -76,6 +77,7 @@ from zju_lecture.formatter import (
76
77
  transcript_quality,
77
78
  )
78
79
  from zju_lecture.security import (
80
+ COURSEWARE_EXTENSIONS,
79
81
  NOTE_EXTENSIONS,
80
82
  REDACTOR,
81
83
  LocalFileError,
@@ -96,7 +98,7 @@ from zju_lecture.study_notes import (
96
98
  )
97
99
 
98
100
  SERVER_NAME = "zju-lecture-mcp"
99
- SERVER_VERSION = "2.2.6"
101
+ SERVER_VERSION = "2.2.7"
100
102
  DEFAULT_TENANT = "112"
101
103
  DEFAULT_DOMAIN = "classroom.zju.edu.cn"
102
104
 
@@ -565,6 +567,14 @@ TOOLS: List[Dict[str, Any]] = [
565
567
  ),
566
568
  "default": True,
567
569
  },
570
+ "confirm": {
571
+ "type": "boolean",
572
+ "description": (
573
+ "确认执行有副作用的操作(默认 false)。confirm=true 才批量下载截图"
574
+ "(最多 2000 张)到工作区并合成 PDF;否则只返回清单,不写盘"
575
+ ),
576
+ "default": False,
577
+ },
568
578
  },
569
579
  "required": ["url_or_sub_id"],
570
580
  },
@@ -590,6 +600,15 @@ TOOLS: List[Dict[str, Any]] = [
590
600
  "description": "最多提取字符数(默认 10000 字符)",
591
601
  "default": 10000,
592
602
  },
603
+ "allow_outside_workspace": {
604
+ "type": "boolean",
605
+ "description": (
606
+ "是否允许读取工作区之外的课件(默认 false)。"
607
+ "显式设为 true 时仍拒绝凭据/浏览器数据/密钥文件,"
608
+ "并在结果首行标注「已读取工作区外文件」"
609
+ ),
610
+ "default": False,
611
+ },
593
612
  },
594
613
  "required": ["file_path"],
595
614
  },
@@ -627,7 +646,7 @@ TOOLS: List[Dict[str, Any]] = [
627
646
  "检查/修正已有讲义 Markdown 的公式与渲染规范(静态、不联网)。"
628
647
  "write_note 已自动检查,通常无需重复调用;只有手工改过文件时才用它修复。"
629
648
  "fix=true 自动修正机械问题并先备份;报告按问题类型聚合。"
630
- "pdf=true 时检查后重新排版一份同名 PDF。"
649
+ "pdf=true 时检查后重新排版一份同名 PDF。只处理工作区内的讲义。"
631
650
  ),
632
651
  "inputSchema": {
633
652
  "type": "object",
@@ -744,6 +763,14 @@ TOOLS: List[Dict[str, Any]] = [
744
763
  "description": "只清除本机保存的登录态与独立登录窗口配置,不打开窗口(默认 false)",
745
764
  "default": False,
746
765
  },
766
+ "confirm": {
767
+ "type": "boolean",
768
+ "description": (
769
+ "确认执行有副作用的操作(默认 false)。clear=true 时必须同时传 "
770
+ "confirm=true 才会删除登录态与浏览器配置"
771
+ ),
772
+ "default": False,
773
+ },
747
774
  },
748
775
  },
749
776
  },
@@ -883,6 +910,14 @@ TOOLS: List[Dict[str, Any]] = [
883
910
  "description": "是否读取本机登录态检查可用性(默认否;不会回显凭据)",
884
911
  "default": False,
885
912
  },
913
+ "confirm": {
914
+ "type": "boolean",
915
+ "description": (
916
+ "确认执行有副作用的操作(默认 false)。install=true 时必须同时传 "
917
+ "confirm=true 才会下载安装 Typst(约 20 MB)"
918
+ ),
919
+ "default": False,
920
+ },
886
921
  },
887
922
  },
888
923
  },
@@ -1226,13 +1261,11 @@ def _patch_draft(arguments: Dict[str, Any]) -> str:
1226
1261
  if not isinstance(raw_edits, list) or not raw_edits:
1227
1262
  return "错误: mode=patch 需要非空的 edits(每项 {old, new})"
1228
1263
 
1229
- resolved, tried = resolve_path(draft_path)
1230
- if resolved is None:
1231
- return f"错误: 找不到填空底稿: {draft_path}{describe_attempts(tried)}"
1232
- try:
1233
- resolved = guard_local_file(resolved, NOTE_EXTENSIONS, kind="填空底稿")
1234
- except LocalFileError as exc:
1235
- return f"错误: {exc}"
1264
+ resolved, path_error = require_workspace_path(
1265
+ draft_path, extensions=NOTE_EXTENSIONS, kind="填空底稿", write=True
1266
+ )
1267
+ if path_error:
1268
+ return f"错误: {path_error}"
1236
1269
  try:
1237
1270
  with open(resolved, "r", encoding="utf-8") as handle:
1238
1271
  draft_text = handle.read()
@@ -1472,7 +1505,13 @@ def _dispatch_tool(name: str, arguments: Dict[str, Any]) -> Any:
1472
1505
  _ensure_tool_enabled(name)
1473
1506
 
1474
1507
  if name == "zju_doctor":
1475
- return _doctor_report(bool(arguments.get("install")), bool(arguments.get("login")))
1508
+ install = bool(arguments.get("install"))
1509
+ if install and arguments.get("confirm") is not True:
1510
+ return (
1511
+ "该操作会下载并安装 Typst(约 20 MB,按固定 SHA256 校验);"
1512
+ "确认后以 confirm=true 重试。只想查看依赖状态时不要传 install=true。"
1513
+ )
1514
+ return _doctor_report(install, bool(arguments.get("login")))
1476
1515
 
1477
1516
  if name == "zju_parse_url":
1478
1517
  parsed = parse_lecture_url(str(arguments.get("url", "")))
@@ -1480,6 +1519,11 @@ def _dispatch_tool(name: str, arguments: Dict[str, Any]) -> Any:
1480
1519
 
1481
1520
  if name == "zju_login":
1482
1521
  if arguments.get("clear"):
1522
+ if arguments.get("confirm") is not True:
1523
+ return (
1524
+ "该操作会删除本机保存的登录态与独立登录窗口的浏览器配置;"
1525
+ "确认后以 confirm=true 重试。只想登录时不要传 clear=true。"
1526
+ )
1483
1527
  result = clear_session(delete_profile=True)
1484
1528
  _COOKIE_CACHE.pop(DEFAULT_DOMAIN, None)
1485
1529
  lines = [
@@ -1632,6 +1676,12 @@ def _dispatch_tool(name: str, arguments: Dict[str, Any]) -> Any:
1632
1676
  dedup = True if dedup_arg is None else bool(dedup_arg)
1633
1677
  output_dir = str(arguments.get("output_dir") or "").strip()
1634
1678
 
1679
+ if download and arguments.get("confirm") is not True:
1680
+ return (
1681
+ "该操作会把投影截图(最多 2000 张)下载到工作区并合成 PDF;"
1682
+ "确认后以 confirm=true 重试。只想查看截图清单时传 download=false。"
1683
+ )
1684
+
1635
1685
  cookie, cookie_error, source, reason = _resolve_cookie()
1636
1686
  if not cookie:
1637
1687
  return _cookie_failure_text(
@@ -1743,15 +1793,32 @@ def _dispatch_tool(name: str, arguments: Dict[str, Any]) -> Any:
1743
1793
  if name == "zju_extract_courseware":
1744
1794
  file_path = str(arguments.get("file_path", ""))
1745
1795
  max_chars = arguments.get("max_chars") or 10000
1746
- resolved, tried = resolve_path(file_path)
1747
- if resolved is None:
1748
- return f"错误: 找不到课件文件: {file_path}{describe_attempts(tried)}"
1796
+ allow_outside = arguments.get("allow_outside_workspace") is True
1797
+ outside_note = ""
1798
+ if allow_outside:
1799
+ # 显式开关:仍然走同一套扩展名/凭据防护,只是不要求在工作区内。
1800
+ resolved, tried = resolve_path(file_path)
1801
+ if resolved is None:
1802
+ return f"错误: 找不到课件文件: {file_path}{describe_attempts(tried)}"
1803
+ try:
1804
+ resolved = guard_local_file(resolved, COURSEWARE_EXTENSIONS, kind="课件文件")
1805
+ except LocalFileError as exc:
1806
+ return f"错误: {exc}"
1807
+ if not is_inside_workspace(resolved):
1808
+ outside_note = f"已读取工作区外文件: {resolved}\n"
1809
+ else:
1810
+ resolved, path_error = require_workspace_path(
1811
+ file_path, extensions=COURSEWARE_EXTENSIONS, kind="课件文件"
1812
+ )
1813
+ if path_error:
1814
+ return f"错误: {path_error}"
1749
1815
  try:
1750
1816
  text = extract_courseware_text(resolved, max_chars)
1751
1817
  except CoursewareError as exc:
1752
1818
  return f"错误: {exc}"
1753
1819
  return (
1754
- f"=== 课件文件提取成功 ({os.path.basename(resolved)}) ===\n"
1820
+ outside_note
1821
+ + f"=== 课件文件提取成功 ({os.path.basename(resolved)}) ===\n"
1755
1822
  f"提取字数: {len(text)} 字符\n\n"
1756
1823
  f"{text}"
1757
1824
  )
@@ -1787,14 +1854,12 @@ def _dispatch_tool(name: str, arguments: Dict[str, Any]) -> Any:
1787
1854
  file_path = str(arguments.get("file_path", "")).strip()
1788
1855
  if not file_path:
1789
1856
  raise ValueError("zju_check_note 需要 file_path 参数")
1790
- resolved, tried = resolve_path(file_path)
1791
- if resolved is None:
1792
- return f"错误: 找不到讲义文件: {file_path}{describe_attempts(tried)}"
1793
- file_path = resolved
1794
- try:
1795
- file_path = guard_local_file(file_path, NOTE_EXTENSIONS, kind="讲义文件")
1796
- except LocalFileError as exc:
1797
- return f"错误: {exc}"
1857
+ wants_fix = arguments.get("fix") is True
1858
+ file_path, path_error = require_workspace_path(
1859
+ file_path, extensions=NOTE_EXTENSIONS, kind="讲义文件", write=wants_fix
1860
+ )
1861
+ if path_error:
1862
+ return f"错误: {path_error}"
1798
1863
  try:
1799
1864
  with open(file_path, "r", encoding="utf-8") as handle:
1800
1865
  note_text = handle.read()
@@ -1806,7 +1871,7 @@ def _dispatch_tool(name: str, arguments: Dict[str, Any]) -> Any:
1806
1871
  max_samples = _clamped_max_samples(arguments.get("max_samples"), 3)
1807
1872
  applied = []
1808
1873
  backup_path = ""
1809
- if arguments.get("fix"):
1874
+ if wants_fix:
1810
1875
  fixed_text, applied = fix_markdown(note_text)
1811
1876
  if fixed_text != note_text:
1812
1877
  try:
@@ -1937,7 +2002,19 @@ def _dispatch_tool(name: str, arguments: Dict[str, Any]) -> Any:
1937
2002
 
1938
2003
 
1939
2004
  def handle_tool_call(name: str, arguments: Dict[str, Any]) -> Any:
1940
- """Execute a tool and redact secrets from whatever it returns."""
2005
+ """Execute a tool and redact secrets from whatever it returns.
2006
+
2007
+ Before dispatch, every key must be declared in the tool's inputSchema.
2008
+ dsh 0.2.x does not close the root object, so an undeclared ``cookie`` /
2009
+ ``token`` field reaches the Python side and would already have been written
2010
+ to the host's call log. Refusing the call keeps the failure local.
2011
+ """
2012
+ tool = next((item for item in TOOLS if item["name"] == name), None)
2013
+ if tool is not None and isinstance(arguments, dict):
2014
+ allowed = set((tool["inputSchema"].get("properties") or {}).keys())
2015
+ unknown = sorted(key for key in arguments if key not in allowed)
2016
+ if unknown:
2017
+ raise ValueError("未知参数: " + ", ".join(unknown))
1941
2018
  return REDACTOR.redact(_dispatch_tool(name, arguments))
1942
2019
 
1943
2020
 
@@ -2010,6 +2087,7 @@ def handle_request(message: Dict[str, Any]) -> Optional[Dict[str, Any]]:
2010
2087
  SlidesDisabledError,
2011
2088
  StudyNotesDisabledError,
2012
2089
  LoginToolsDisabledError,
2090
+ ValueError,
2013
2091
  ) as exc:
2014
2092
  message_text = REDACTOR.redact(str(exc))
2015
2093
  _log(f"{tool_name}: {message_text}")
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-zju-lecture-note",
3
- "version": "2.2.6",
3
+ "version": "2.2.7",
4
4
  "description": "浙大智云课堂回放讲义插件(DeepSeek Harness 原生插件):以「语音字幕 + 本地课件」为主链路,写完讲义自动排版同名 PDF;可选启用投影 PPT 截图抓取、基于 Typst scholia 模板排版的填空式学习笔记与登录辅助工具;一键登录窗口让用户正常登录后自动安全保存登录态(Windows DPAPI),不回显、不进入对话、不保存密码",
5
5
  "license": "MIT",
6
6
  "author": "chenqianyu486",
@@ -146,7 +146,15 @@
146
146
  )
147
147
  }
148
148
 
149
- // ── 6. 类型速查(写正文时照着选色相) ──
149
+ // ── 6. 封面包装 ──
150
+ // 调用处只传命名参数(`#scholia-cover(title: "...")`),值由渲染器按
151
+ // Typst 字符串字面量转义;位置参数一旦被注入的引号截断,后面就能接
152
+ // `#read(...)` 之类的可执行代码。
153
+ #let scholia-cover(title: "", subtitle: none, author: none, date: none, kicker: none) = {
154
+ cover(title, subtitle: subtitle, author: author, date: date, kicker: kicker)
155
+ }
156
+
157
+ // ── 7. 类型速查(写正文时照着选色相) ──
150
158
  // 结论/定理/证明/回指 → thm 蓝
151
159
  // 定义/公理/术语/标签 → def 青绿
152
160
  // 例子/练习/填空缺口 → eg 琥珀
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "scholia-notes",
3
- "version": "2.2.6",
3
+ "version": "2.2.7",
4
4
  "contentHash": "sha256:a2996a352ec54b35350e9830e3a9063d4ae147324a48ab89efd10fe429e64f3b",
5
5
  "fileCount": 12,
6
6
  "files": [
@@ -48,8 +48,8 @@
48
48
  },
49
49
  {
50
50
  "path": "references/prelude.typ",
51
- "sha256": "4d5cce9323fa32bd49bdb8d460fcf32af78fedb958807a3b573367073e3d531c",
52
- "size": 6551,
51
+ "sha256": "63ead02c837c11db28cfb4d2ada22554d4cf1b0af4fcfb0c5c42f2847330c8f9",
52
+ "size": 6985,
53
53
  "mode": "0644"
54
54
  },
55
55
  {
@@ -135,7 +135,7 @@ zju_write_note(
135
135
  **先写文件,再校验,不要只在回复里贴公式。**
136
136
  - 交付时把两条路径都给用户:Markdown 是源文件,同名 `.pdf` 是阅读版。
137
137
  返回里出现 `PDF 跳过: …` 时照常交付 Markdown,**不要重试或假装 PDF 已生成**;
138
- 若原因是 `找不到 typst`,调用一次 `zju_doctor(install=true)` 后重试 `zju_check_note(pdf=true)`,
138
+ 若原因是 `找不到 typst`,调用一次 `zju_doctor(install=true, confirm=true)` 后重试 `zju_check_note(pdf=true)`,
139
139
  仍失败就把 `zju_doctor` 的结论原样转告用户。
140
140
  - **`---` 不用手动清理**:渲染器会把独占一行的 `---` 排成细分隔线。
141
141
  不要为它写脚本,更不要用 `知识总结*.md` 这类通配批量改文件——
@@ -9,7 +9,7 @@
9
9
  `zju_fetch_slides` 抓取智云课堂该节课的投影 PPT **截图清单**。`search-ppt` 接口返回的是
10
10
  投影画面截图(`pptimgurl`),**不是文字层,也不提供 OCR**。需要阅读幻灯片内容时:
11
11
 
12
- - 设置 `download=true` 下载截图并合成 PDF,交给支持视觉的模型查看;
12
+ - 设置 `download=true, confirm=true` 下载截图并合成 PDF,交给支持视觉的模型查看;
13
13
  - 宿主/模型不能看图时,只把截图当作索引,**不要臆造幻灯片文字**;
14
14
  - 需要幻灯片原文时,优先请用户提供原始 `.pptx`,改用 `zju_extract_courseware`。
15
15
 
@@ -24,16 +24,18 @@
24
24
  url_or_sub_id="<完整回放 URL>",
25
25
  course_id="<course_id>",
26
26
  download=true,
27
+ confirm=true,
27
28
  )
28
29
  ```
29
30
 
30
31
  - 只传纯 `sub_id` 时**必须同时传 `course_id`**(完整回放 URL 会自动解析);
32
+ - `confirm=true` 是写盘确认:缺少时工具只返回清单、不下载;确需下载时一次带上;
31
33
  - `output_dir` 默认 `ppt-assets/<sub_id>/`,必须位于当前工作区内;
32
34
  - `dedup=true`(默认)只折叠**连续字节完全相同**的截图,只影响 PDF 页数,下载的原图都保留。
33
35
 
34
36
  ## 3. 下载与输出
35
37
 
36
- `download=true` 时:
38
+ `download=true, confirm=true` 时:
37
39
 
38
40
  - 截图存到工作区 `ppt-assets/<sub_id>/images/slide-XXXX.jpg`(JPEG 原样写入);
39
41
  - 合成 `PPT-<sub_id>.pdf`;
@@ -62,7 +64,7 @@
62
64
  - 相对路径只在工作区内有效;要离线分享或换机器,直接发 `PPT-<sub_id>.pdf`。
63
65
 
64
66
  讲义插图模式关闭时:不要主动下载或插入截图;用户明确要求画面时,
65
- 可以按需调用 `download=true`,并在文末放截图索引。
67
+ 可以按需调用 `download=true, confirm=true`,并在文末放截图索引。
66
68
 
67
69
  ## 5. 登录态与隐私
68
70
 
@@ -66,11 +66,11 @@ description: 浙大智云课堂插件的登录辅助与故障排查(401/403、
66
66
  填空笔记(`enableStudyNotes`)、登录辅助工具(`enableLoginTools`)是独立可选开关。
67
67
  - 修改设置后必须**完全重启 DeepSeek Harness**,当前会话不会热加载新工具集。
68
68
  - 字幕鉴权与 `zju_login` 都不受 `enableLoginTools` 影响,不要把“登录辅助关闭”误判成字幕不可用。
69
- - 用户想清除本机登录态时,调用 `zju_login(clear=true)`,不要手工删文件。
69
+ - 用户想清除本机登录态时,调用 `zju_login(clear=true, confirm=true)`,不要手工删文件。
70
70
 
71
71
  ### C. PDF / Typst
72
72
 
73
- - 先跑 `zju_doctor`;缺少 Typst 时用 `zju_doctor(install=true)`。
73
+ - 先跑 `zju_doctor`;缺少 Typst 时用 `zju_doctor(install=true, confirm=true)`。
74
74
  - 检查 `renderPdf` 是否开启;Markdown 写入成功而 PDF 失败时,先交付 Markdown。
75
75
  - 不要让用户关闭证书校验或从非官方来源安装 Typst。
76
76
 
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "name": "zju-lecture-summarizer-help",
3
- "version": "2.2.6",
4
- "contentHash": "sha256:4b240b3eb2e4d5d23947eebc6867cbb0d1f3d64ffcba6c6ce2dc346e7929b86f",
3
+ "version": "2.2.7",
4
+ "contentHash": "sha256:a9fd34a4bcec2e603dd803ada58cbef50f5a27b395f25d3384665dc47a5ac427",
5
5
  "fileCount": 1,
6
6
  "files": [
7
7
  {
8
8
  "path": "SKILL.md",
9
- "sha256": "4b240b3eb2e4d5d23947eebc6867cbb0d1f3d64ffcba6c6ce2dc346e7929b86f",
10
- "size": 6455,
9
+ "sha256": "a9fd34a4bcec2e603dd803ada58cbef50f5a27b395f25d3384665dc47a5ac427",
10
+ "size": 6483,
11
11
  "mode": "0644"
12
12
  }
13
13
  ]
@@ -17,7 +17,7 @@ description: 打开浙大智云课堂的独立登录窗口并保存本机登录
17
17
  工具会阻塞到登录完成、超时或窗口被关闭;不要在此期间重复调用。
18
18
  4. 成功后只报告:浏览器、Cookie 条数、是否已保存。**不要输出、索要或复述任何 Cookie / token / 密码**。
19
19
  如果用户还有原本的抓字幕任务,接着回到原任务即可;否则到此结束。
20
- 5. 用户明确要退出登录 / 清除本机登录态时,调用 `zju_login(clear=true)`;
20
+ 5. 用户明确要退出登录 / 清除本机登录态时,调用 `zju_login(clear=true, confirm=true)`;
21
21
  它会删除本机登录态与独立登录窗口配置。不要手工删文件或改环境变量。
22
22
 
23
23
  ## 失败时
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "name": "zju-lecture-summarizer-login",
3
- "version": "2.2.6",
4
- "contentHash": "sha256:8e077abdc6e0186b1ca253824adad30080a040a5dc2d8eb817fc6269e4f12010",
3
+ "version": "2.2.7",
4
+ "contentHash": "sha256:be91313617dbd1cfdc8bba3aff93c7291d616b0f395311d706fd5fba56103e08",
5
5
  "fileCount": 1,
6
6
  "files": [
7
7
  {
8
8
  "path": "SKILL.md",
9
- "sha256": "8e077abdc6e0186b1ca253824adad30080a040a5dc2d8eb817fc6269e4f12010",
10
- "size": 2459,
9
+ "sha256": "be91313617dbd1cfdc8bba3aff93c7291d616b0f395311d706fd5fba56103e08",
10
+ "size": 2473,
11
11
  "mode": "0644"
12
12
  }
13
13
  ]
@@ -1,19 +1,19 @@
1
1
  {
2
2
  "name": "zju-lecture-summarizer",
3
- "version": "2.2.6",
4
- "contentHash": "sha256:7e8b14eee6f9fb3a6e7d73ec14f7a6ac10af865b630911ca1a2264afbadc59d9",
3
+ "version": "2.2.7",
4
+ "contentHash": "sha256:24d3c4b1bef945ea10f8cb8cad20c1489863132cf00b341fd40dafd7a7732711",
5
5
  "fileCount": 2,
6
6
  "files": [
7
7
  {
8
8
  "path": "SKILL.md",
9
- "sha256": "7e8b14eee6f9fb3a6e7d73ec14f7a6ac10af865b630911ca1a2264afbadc59d9",
10
- "size": 25423,
9
+ "sha256": "24d3c4b1bef945ea10f8cb8cad20c1489863132cf00b341fd40dafd7a7732711",
10
+ "size": 25437,
11
11
  "mode": "0644"
12
12
  },
13
13
  {
14
14
  "path": "SLIDES.md",
15
- "sha256": "7b44bfb2cb49a34b5c7dffc058fd04bc1c7ff60fa98cab27067645354870d5f8",
16
- "size": 4528,
15
+ "sha256": "fb0057937e46271b16cbf1a3fc35c408d88d3ba979e0b794f23600da56742b3e",
16
+ "size": 4705,
17
17
  "mode": "0644"
18
18
  }
19
19
  ]
@@ -37,6 +37,7 @@ import socket
37
37
  import struct
38
38
  import subprocess
39
39
  import sys
40
+ import tempfile
40
41
  import time
41
42
  import urllib.parse
42
43
  import urllib.request
@@ -318,22 +319,32 @@ def save_session(cookie: str, browser: str = "") -> str:
318
319
  blob = _encode_session(payload)
319
320
  directory = login_dir()
320
321
  target = session_file()
321
- tmp = target + ".tmp"
322
+ tmp = ""
322
323
  try:
323
324
  _ensure_private_dir(directory)
325
+ # mkstemp 用 O_EXCL 建文件,固定 ".tmp" 路径可被预置的链接劫持。
326
+ descriptor, tmp = tempfile.mkstemp(
327
+ dir=directory, prefix=".zju-session-", suffix=".tmp"
328
+ )
324
329
  # Create with 0600 from the first byte on POSIX; Windows ignores the
325
330
  # mode and relies on DPAPI plus the per-user profile directory.
326
- descriptor = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
331
+ if hasattr(os, "fchmod"):
332
+ try:
333
+ os.fchmod(descriptor, 0o600)
334
+ except OSError:
335
+ pass
327
336
  with os.fdopen(descriptor, "wb") as handle:
328
337
  handle.write(blob)
329
338
  handle.flush()
330
339
  os.fsync(handle.fileno())
331
340
  os.replace(tmp, target)
341
+ tmp = ""
332
342
  except OSError as exc:
333
- try:
334
- os.unlink(tmp)
335
- except OSError:
336
- pass
343
+ if tmp:
344
+ try:
345
+ os.unlink(tmp)
346
+ except OSError:
347
+ pass
337
348
  raise LoginError(
338
349
  f"登录成功,但保存登录态失败:{exc}",
339
350
  "本次会话仍可使用;请检查用户目录写权限,或改用 ZJU_COOKIE_FILE。",
@@ -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:
@@ -357,6 +381,8 @@ def main():
357
381
  print("现在可以运行 `zju-lecture fetch <url>`。")
358
382
 
359
383
  elif args.command == "cookie":
384
+ if args.reveal and not _confirm_cookie_reveal():
385
+ return
360
386
  c = get_edge_cookie()
361
387
  if not c:
362
388
  print("未能在本机 Edge 找到 classroom.zju.edu.cn 的 Cookie。")