leetcode-local-cli 0.7.0__tar.gz → 0.7.2__tar.gz

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: leetcode-local-cli
3
- Version: 0.7.0
3
+ Version: 0.7.2
4
4
  Summary: Local coding workflow CLI for LeetCode CN.
5
5
  Keywords: cli,leetcode,leetcode-cn,uv
6
6
  Author: Aetherialter
@@ -26,7 +26,13 @@ Description-Content-Type: text/markdown
26
26
 
27
27
  一个面向 LeetCode 中文站的轻量本地刷题 CLI。它复用浏览器登录态,在线获取题目,在当前工作目录生成单文件 `solution.py`,并支持本地测试和远程提交。
28
28
 
29
- 当前版本:`v0.7.0`
29
+ 当前版本:`v0.7.2`
30
+
31
+ ## 长期开发手册
32
+
33
+ [v1.0 总体设计大纲](PROJECT_DESIGN.md)记录了从当前版本演进到稳定 CLI 与 Python API 的长期架构、版本阶段和验收标准。该文档目前处于 Draft 状态,具体实施前仍需按阶段审查。
34
+
35
+ [安全审计与修复清单](SECURITY_REVIEW.md)记录了当前源码的风险等级、攻击前提和建议修复顺序;其中列出的问题尚未全部修复。
30
36
 
31
37
  ## 核心能力
32
38
 
@@ -54,16 +60,16 @@ Description-Content-Type: text/markdown
54
60
  Linux / macOS 一键安装:
55
61
 
56
62
  ```bash
57
- curl -LsSf https://raw.githubusercontent.com/Aetherialter/leetcode-local-cli/v0.7.0/scripts/install.sh | sh
63
+ curl -LsSf https://raw.githubusercontent.com/Aetherialter/leetcode-local-cli/v0.7.2/scripts/install.sh | sh
58
64
  ```
59
65
 
60
66
  Windows PowerShell 一键安装:
61
67
 
62
68
  ```powershell
63
- powershell -ExecutionPolicy ByPass -Command "irm https://raw.githubusercontent.com/Aetherialter/leetcode-local-cli/v0.7.0/scripts/install.ps1 | iex"
69
+ powershell -ExecutionPolicy ByPass -Command "irm https://raw.githubusercontent.com/Aetherialter/leetcode-local-cli/v0.7.2/scripts/install.ps1 | iex"
64
70
  ```
65
71
 
66
- 安装器会在缺少 uv 时通过 uv 官方 HTTPS 安装器完成引导,然后使用 `uv tool install` 安装 `leetcode-local-cli`,并执行 `lc --version` 验证结果。安装过程不使用 `sudo`,也不会保存 PyPI 或 GitHub 凭据。
72
+ 安装器要求系统已安装 uv;如果未检测到 uv,会安全退出并提示访问 [uv 官方文档](https://docs.astral.sh/uv/),不会自动下载或执行第三方远端安装脚本。检测到 uv 后,安装器会使用 `uv tool install` 安装 `leetcode-local-cli`,并执行 `lc --version` 验证结果。安装过程不使用 `sudo`,也不会保存 PyPI 或 GitHub 凭据。
67
73
 
68
74
  已经安装 uv 时,也可以直接安装:
69
75
 
@@ -103,7 +109,8 @@ lc submit
103
109
  | `lc get <题号>` | 在线展示题目详情 |
104
110
  | `lc solve <题号>` | 覆盖生成当前目录的 `solution.py` |
105
111
  | `lc test` | 运行本地 `solution.py` |
106
- | `lc doctor` | 诊断 Session、网络、Cookie 和 `solution.py` |
112
+ | `lc doctor` | 诊断 Session、网络、Cookie 和 `solution.py`,默认不执行代码 |
113
+ | `lc doctor --run-solution` | 额外运行当前工作区的 `solution.py` |
107
114
  | `lc submit` | 提交当前 `solution.py` 的提交区域代码 |
108
115
 
109
116
  ## solution.py 规则
@@ -149,7 +156,9 @@ class Solution:
149
156
  - `lc test` 默认隐藏 Python traceback,只展示本地测试通过或失败。
150
157
  - 如果 `run_cases()` 中没有断言,`lc test` 显示通过是当前轻量化设计允许的行为。
151
158
  - 树、链表等题型中,LeetCode 模板里的 `TreeNode` / `ListNode` 定义默认保持注释状态;如需本地构造用例,请自行取消注释并编写测试数据。
152
- - `lc doctor` 会向 LeetCode 中文站发送一次登录态查询,并在本地运行语法有效的 `solution.py`;本地运行超过 10 秒会判定失败。
159
+ - `lc doctor` 会向 LeetCode 中文站发送一次登录态查询,并静态检查 `solution.py` 的存在性、可读性、Python 语法和提交结构;默认不会执行文件。
160
+ - `lc doctor --run-solution` 会额外运行语法有效的 `solution.py`,本地运行超过 10 秒会判定失败。
161
+ - `lc test` 和 `lc doctor --run-solution` 会以当前用户权限执行本地 Python 代码,请勿在不可信工作区中运行。
153
162
 
154
163
  ## 安全说明
155
164
 
@@ -229,6 +238,7 @@ tests/
229
238
  test_doctor.py
230
239
  test_install_scripts.py
231
240
  test_problem.py
241
+ test_release.py
232
242
  test_service.py
233
243
  test_ui.py
234
244
  test_workspace.py
@@ -243,6 +253,8 @@ tests/
243
253
  - `v0.5.7`: 修复非 Windows 环境导入 `os.startfile` 导致 CLI 无法启动的问题。
244
254
  - `v0.6.0`: 新增 `lc doctor`,完善客户端边界校验、本地文件诊断、错误提示和提交目标展示。
245
255
  - `v0.7.0`: uv 全局工具安装、跨平台引导脚本和 PyPI Trusted Publisher 发布流程。
256
+ - `v0.7.1`: 修正安装版 CLI 的命令建议,并引入版本化 GitHub Release Notes。
257
+ - `v0.7.2`: 收紧安全边界,避免诊断命令默认执行解题文件,并移除安装器的远端脚本执行。
246
258
  - `v0.8`: `lc init` 与正式工作区管理。
247
259
  - `v0.9`: 轻量缓存。
248
260
  - `v0.10`: 样例提取原型。
@@ -2,7 +2,13 @@
2
2
 
3
3
  一个面向 LeetCode 中文站的轻量本地刷题 CLI。它复用浏览器登录态,在线获取题目,在当前工作目录生成单文件 `solution.py`,并支持本地测试和远程提交。
4
4
 
5
- 当前版本:`v0.7.0`
5
+ 当前版本:`v0.7.2`
6
+
7
+ ## 长期开发手册
8
+
9
+ [v1.0 总体设计大纲](PROJECT_DESIGN.md)记录了从当前版本演进到稳定 CLI 与 Python API 的长期架构、版本阶段和验收标准。该文档目前处于 Draft 状态,具体实施前仍需按阶段审查。
10
+
11
+ [安全审计与修复清单](SECURITY_REVIEW.md)记录了当前源码的风险等级、攻击前提和建议修复顺序;其中列出的问题尚未全部修复。
6
12
 
7
13
  ## 核心能力
8
14
 
@@ -30,16 +36,16 @@
30
36
  Linux / macOS 一键安装:
31
37
 
32
38
  ```bash
33
- curl -LsSf https://raw.githubusercontent.com/Aetherialter/leetcode-local-cli/v0.7.0/scripts/install.sh | sh
39
+ curl -LsSf https://raw.githubusercontent.com/Aetherialter/leetcode-local-cli/v0.7.2/scripts/install.sh | sh
34
40
  ```
35
41
 
36
42
  Windows PowerShell 一键安装:
37
43
 
38
44
  ```powershell
39
- powershell -ExecutionPolicy ByPass -Command "irm https://raw.githubusercontent.com/Aetherialter/leetcode-local-cli/v0.7.0/scripts/install.ps1 | iex"
45
+ powershell -ExecutionPolicy ByPass -Command "irm https://raw.githubusercontent.com/Aetherialter/leetcode-local-cli/v0.7.2/scripts/install.ps1 | iex"
40
46
  ```
41
47
 
42
- 安装器会在缺少 uv 时通过 uv 官方 HTTPS 安装器完成引导,然后使用 `uv tool install` 安装 `leetcode-local-cli`,并执行 `lc --version` 验证结果。安装过程不使用 `sudo`,也不会保存 PyPI 或 GitHub 凭据。
48
+ 安装器要求系统已安装 uv;如果未检测到 uv,会安全退出并提示访问 [uv 官方文档](https://docs.astral.sh/uv/),不会自动下载或执行第三方远端安装脚本。检测到 uv 后,安装器会使用 `uv tool install` 安装 `leetcode-local-cli`,并执行 `lc --version` 验证结果。安装过程不使用 `sudo`,也不会保存 PyPI 或 GitHub 凭据。
43
49
 
44
50
  已经安装 uv 时,也可以直接安装:
45
51
 
@@ -79,7 +85,8 @@ lc submit
79
85
  | `lc get <题号>` | 在线展示题目详情 |
80
86
  | `lc solve <题号>` | 覆盖生成当前目录的 `solution.py` |
81
87
  | `lc test` | 运行本地 `solution.py` |
82
- | `lc doctor` | 诊断 Session、网络、Cookie 和 `solution.py` |
88
+ | `lc doctor` | 诊断 Session、网络、Cookie 和 `solution.py`,默认不执行代码 |
89
+ | `lc doctor --run-solution` | 额外运行当前工作区的 `solution.py` |
83
90
  | `lc submit` | 提交当前 `solution.py` 的提交区域代码 |
84
91
 
85
92
  ## solution.py 规则
@@ -125,7 +132,9 @@ class Solution:
125
132
  - `lc test` 默认隐藏 Python traceback,只展示本地测试通过或失败。
126
133
  - 如果 `run_cases()` 中没有断言,`lc test` 显示通过是当前轻量化设计允许的行为。
127
134
  - 树、链表等题型中,LeetCode 模板里的 `TreeNode` / `ListNode` 定义默认保持注释状态;如需本地构造用例,请自行取消注释并编写测试数据。
128
- - `lc doctor` 会向 LeetCode 中文站发送一次登录态查询,并在本地运行语法有效的 `solution.py`;本地运行超过 10 秒会判定失败。
135
+ - `lc doctor` 会向 LeetCode 中文站发送一次登录态查询,并静态检查 `solution.py` 的存在性、可读性、Python 语法和提交结构;默认不会执行文件。
136
+ - `lc doctor --run-solution` 会额外运行语法有效的 `solution.py`,本地运行超过 10 秒会判定失败。
137
+ - `lc test` 和 `lc doctor --run-solution` 会以当前用户权限执行本地 Python 代码,请勿在不可信工作区中运行。
129
138
 
130
139
  ## 安全说明
131
140
 
@@ -205,6 +214,7 @@ tests/
205
214
  test_doctor.py
206
215
  test_install_scripts.py
207
216
  test_problem.py
217
+ test_release.py
208
218
  test_service.py
209
219
  test_ui.py
210
220
  test_workspace.py
@@ -219,6 +229,8 @@ tests/
219
229
  - `v0.5.7`: 修复非 Windows 环境导入 `os.startfile` 导致 CLI 无法启动的问题。
220
230
  - `v0.6.0`: 新增 `lc doctor`,完善客户端边界校验、本地文件诊断、错误提示和提交目标展示。
221
231
  - `v0.7.0`: uv 全局工具安装、跨平台引导脚本和 PyPI Trusted Publisher 发布流程。
232
+ - `v0.7.1`: 修正安装版 CLI 的命令建议,并引入版本化 GitHub Release Notes。
233
+ - `v0.7.2`: 收紧安全边界,避免诊断命令默认执行解题文件,并移除安装器的远端脚本执行。
222
234
  - `v0.8`: `lc init` 与正式工作区管理。
223
235
  - `v0.9`: 轻量缓存。
224
236
  - `v0.10`: 样例提取原型。
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "leetcode-local-cli"
3
- version = "0.7.0"
3
+ version = "0.7.2"
4
4
  description = "Local coding workflow CLI for LeetCode CN."
5
5
  readme = "README.md"
6
6
  license = "MIT"
@@ -1,11 +1,22 @@
1
1
  import json
2
2
  import os
3
+ import warnings
3
4
  from dataclasses import dataclass
4
5
  from enum import Enum
5
6
  from getpass import getpass
6
7
  from pathlib import Path
7
8
 
8
- import browser_cookie3
9
+
10
+ with warnings.catch_warnings():
11
+ # wmi 1.5.1, imported transitively by browser-cookie3 on Windows, contains
12
+ # invalid escape sequences in docstrings. Keep those third-party warnings
13
+ # out of every CLI invocation without disabling SyntaxWarning globally.
14
+ warnings.filterwarnings(
15
+ "ignore",
16
+ message=r".*invalid escape sequence.*",
17
+ category=SyntaxWarning,
18
+ )
19
+ import browser_cookie3
9
20
 
10
21
  LC_DOMAIN = "leetcode.cn"
11
22
  # BROWSER_LOADERS = [("Edge", browser_cookie3.edge), ("Chrome", browser_cookie3.chrome)]
@@ -70,7 +81,7 @@ def get_cookies_from_browser() -> tuple[str, dict[str, str]] | None:
70
81
  try:
71
82
  cookie_jar = loader(domain_name=LC_DOMAIN)
72
83
 
73
- except Exception:
84
+ except (browser_cookie3.BrowserCookieError, OSError, RuntimeError):
74
85
  continue
75
86
 
76
87
  cookies_dict: dict[str, str] = {
@@ -78,7 +89,7 @@ def get_cookies_from_browser() -> tuple[str, dict[str, str]] | None:
78
89
  for cookie in cookie_jar
79
90
  if (
80
91
  cookie.domain
81
- and cookie.domain.lstrip(".").endswith(LC_DOMAIN)
92
+ and _cookie_domain_matches(cookie.domain, LC_DOMAIN)
82
93
  and cookie.value is not None
83
94
  )
84
95
  }
@@ -91,6 +102,15 @@ def get_cookies_from_browser() -> tuple[str, dict[str, str]] | None:
91
102
  return None
92
103
 
93
104
 
105
+ def _cookie_domain_matches(domain: str, expected_domain: str) -> bool:
106
+ normalized_domain = domain.removeprefix(".").lower()
107
+ normalized_expected_domain = expected_domain.lower()
108
+ return (
109
+ normalized_domain == normalized_expected_domain
110
+ or normalized_domain.endswith(f".{normalized_expected_domain}")
111
+ )
112
+
113
+
94
114
  def parse_cookie_header(cookies: str) -> dict[str, str] | None:
95
115
  cookies_dict = {}
96
116
  for item in cookies.split(";"):
@@ -199,9 +199,17 @@ def test() -> None:
199
199
 
200
200
 
201
201
  @app.command()
202
- def doctor() -> None:
202
+ def doctor(
203
+ run_solution: Annotated[
204
+ bool,
205
+ Option(
206
+ "--run-solution",
207
+ help="显式执行当前工作区的 solution.py",
208
+ ),
209
+ ] = False,
210
+ ) -> None:
203
211
  with loading("正在检查本地环境与 LeetCode 连接..."):
204
- report = get_doctor_report()
212
+ report = get_doctor_report(run_solution=run_solution)
205
213
  render_doctor_report(report)
206
214
  if not report.ok:
207
215
  raise Exit(1)
@@ -160,7 +160,8 @@ class LeetCodeClient:
160
160
  if not result.ok:
161
161
  return result
162
162
  payload = result.data
163
- assert isinstance(payload, dict)
163
+ if not isinstance(payload, dict):
164
+ return ClientResult(error=ClientErrorKind.INVALID_RESPONSE)
164
165
  data = payload.get("data")
165
166
  if not isinstance(data, dict):
166
167
  return ClientResult(error=ClientErrorKind.INVALID_RESPONSE)
@@ -180,7 +181,8 @@ class LeetCodeClient:
180
181
  if not result.ok:
181
182
  return result
182
183
  payload = result.data
183
- assert isinstance(payload, dict)
184
+ if not isinstance(payload, dict):
185
+ return ClientResult(error=ClientErrorKind.INVALID_RESPONSE)
184
186
 
185
187
  stats = {
186
188
  "solved": {
@@ -276,7 +278,8 @@ class LeetCodeClient:
276
278
  if not result.ok:
277
279
  return result
278
280
  response_payload = result.data
279
- assert isinstance(response_payload, dict)
281
+ if not isinstance(response_payload, dict):
282
+ return ClientResult(error=ClientErrorKind.INVALID_RESPONSE)
280
283
  data = response_payload.get("data")
281
284
  if not isinstance(data, dict):
282
285
  return ClientResult(error=ClientErrorKind.INVALID_RESPONSE)
@@ -310,7 +313,8 @@ class LeetCodeClient:
310
313
  if not result.ok:
311
314
  return result
312
315
  response_payload = result.data
313
- assert isinstance(response_payload, dict)
316
+ if not isinstance(response_payload, dict):
317
+ return ClientResult(error=ClientErrorKind.INVALID_RESPONSE)
314
318
  data = response_payload.get("data")
315
319
  if not isinstance(data, dict):
316
320
  return ClientResult(error=ClientErrorKind.INVALID_RESPONSE)
@@ -343,7 +347,8 @@ class LeetCodeClient:
343
347
  if not result.ok:
344
348
  return result
345
349
  response_payload = result.data
346
- assert isinstance(response_payload, dict)
350
+ if not isinstance(response_payload, dict):
351
+ return ClientResult(error=ClientErrorKind.INVALID_RESPONSE)
347
352
  submission_id = response_payload.get("submission_id")
348
353
  if not isinstance(submission_id, int) or isinstance(submission_id, bool):
349
354
  return ClientResult(error=ClientErrorKind.INVALID_RESPONSE)
@@ -358,7 +363,8 @@ class LeetCodeClient:
358
363
  if not result.ok:
359
364
  return result
360
365
  payload = result.data
361
- assert isinstance(payload, dict)
366
+ if not isinstance(payload, dict):
367
+ return ClientResult(error=ClientErrorKind.INVALID_RESPONSE)
362
368
  if not isinstance(payload.get("state"), str):
363
369
  return ClientResult(error=ClientErrorKind.INVALID_RESPONSE)
364
370
  return result
@@ -65,7 +65,7 @@ def diagnose_session(path: Path | None = None) -> DoctorCheck:
65
65
  name=SESSION_CHECK_NAME,
66
66
  status=DoctorStatus.FAIL,
67
67
  message="未找到 Session 文件",
68
- suggestion="请执行 uv run lc login 创建登录态",
68
+ suggestion="请执行 lc login 创建登录态",
69
69
  )
70
70
 
71
71
  case SessionFileStatus.READ_ERROR:
@@ -73,7 +73,7 @@ def diagnose_session(path: Path | None = None) -> DoctorCheck:
73
73
  name=SESSION_CHECK_NAME,
74
74
  status=DoctorStatus.FAIL,
75
75
  message="无法读取 Session 文件",
76
- suggestion="请检查文件权限,或重新执行 uv run lc login",
76
+ suggestion="请检查文件权限,或重新执行 lc login",
77
77
  )
78
78
 
79
79
  case SessionFileStatus.INVALID_JSON:
@@ -81,7 +81,7 @@ def diagnose_session(path: Path | None = None) -> DoctorCheck:
81
81
  name=SESSION_CHECK_NAME,
82
82
  status=DoctorStatus.FAIL,
83
83
  message="Session 文件不是有效的 JSON",
84
- suggestion="请执行 uv run lc login 重新生成登录态",
84
+ suggestion="请执行 lc login 重新生成登录态",
85
85
  )
86
86
 
87
87
  case SessionFileStatus.INVALID_STRUCTURE:
@@ -89,7 +89,7 @@ def diagnose_session(path: Path | None = None) -> DoctorCheck:
89
89
  name=SESSION_CHECK_NAME,
90
90
  status=DoctorStatus.FAIL,
91
91
  message="Session 文件结构无效",
92
- suggestion="请执行 uv run lc login 重新生成登录态",
92
+ suggestion="请执行 lc login 重新生成登录态",
93
93
  )
94
94
 
95
95
  case SessionFileStatus.MISSING_COOKIES:
@@ -98,14 +98,16 @@ def diagnose_session(path: Path | None = None) -> DoctorCheck:
98
98
  name=SESSION_CHECK_NAME,
99
99
  status=DoctorStatus.FAIL,
100
100
  message=f"缺少或无效的 Cookie:{missing}",
101
- suggestion="请执行 uv run lc login 刷新 Cookie",
101
+ suggestion="请执行 lc login 刷新 Cookie",
102
102
  )
103
103
 
104
104
 
105
- def diagnose_solution(path: Path | None = None) -> DoctorCheck:
106
- """Inspect solution.py and verify its local entry point in a subprocess."""
105
+ def diagnose_solution(
106
+ path: Path | None = None, *, run_solution: bool = False
107
+ ) -> DoctorCheck:
108
+ """Inspect solution.py and optionally verify it in a subprocess."""
107
109
  inspection = inspect_solution_file(path)
108
- if inspection.status in {
110
+ if run_solution and inspection.status in {
109
111
  SolutionFileStatus.READY,
110
112
  SolutionFileStatus.NOT_SUBMITTABLE,
111
113
  }:
@@ -119,10 +121,16 @@ def diagnose_solution(path: Path | None = None) -> DoctorCheck:
119
121
  target = (
120
122
  f"{metadata.problem_id}. {metadata.title}" if metadata else "未知题目"
121
123
  )
124
+ message = (
125
+ "solution.py 语法、提交信息与本地运行正常"
126
+ if run_solution
127
+ else "solution.py 语法和提交信息正常"
128
+ )
129
+
122
130
  return DoctorCheck(
123
131
  name=SOLUTION_CHECK_NAME,
124
132
  status=DoctorStatus.PASS,
125
- message=f"solution.py 语法、提交信息与本地运行正常({target})",
133
+ message=f"{message}({target})",
126
134
  )
127
135
 
128
136
  case SolutionFileStatus.MISSING:
@@ -130,7 +138,7 @@ def diagnose_solution(path: Path | None = None) -> DoctorCheck:
130
138
  name=SOLUTION_CHECK_NAME,
131
139
  status=DoctorStatus.WARNING,
132
140
  message="未找到 solution.py",
133
- suggestion="请执行 uv run lc solve <题号> 创建解题文件",
141
+ suggestion="请执行 lc solve <题号> 创建解题文件",
134
142
  )
135
143
 
136
144
  case SolutionFileStatus.EMPTY:
@@ -138,7 +146,7 @@ def diagnose_solution(path: Path | None = None) -> DoctorCheck:
138
146
  name=SOLUTION_CHECK_NAME,
139
147
  status=DoctorStatus.WARNING,
140
148
  message="solution.py 当前为空",
141
- suggestion="请执行 uv run lc solve <题号> 生成解题模板",
149
+ suggestion="请执行 lc solve <题号> 生成解题模板",
142
150
  )
143
151
 
144
152
  case SolutionFileStatus.READ_ERROR:
@@ -159,7 +167,7 @@ def diagnose_solution(path: Path | None = None) -> DoctorCheck:
159
167
  name=SOLUTION_CHECK_NAME,
160
168
  status=DoctorStatus.FAIL,
161
169
  message=f"solution.py 存在 Python 语法错误({line})",
162
- suggestion="请修复语法错误后重新执行 uv run lc doctor",
170
+ suggestion="请修复语法错误后重新执行 lc doctor",
163
171
  )
164
172
 
165
173
  case SolutionFileStatus.NOT_SUBMITTABLE:
@@ -167,7 +175,7 @@ def diagnose_solution(path: Path | None = None) -> DoctorCheck:
167
175
  name=SOLUTION_CHECK_NAME,
168
176
  status=DoctorStatus.WARNING,
169
177
  message=f"solution.py 可编译,但暂不可提交:{inspection.detail}",
170
- suggestion="请执行 uv run lc solve <题号> 重新生成标准模板",
178
+ suggestion="请执行 lc solve <题号> 重新生成标准模板",
171
179
  )
172
180
 
173
181
 
@@ -196,7 +204,7 @@ def _diagnose_solution_runtime(path: Path | None) -> DoctorCheck | None:
196
204
  name=SOLUTION_CHECK_NAME,
197
205
  status=DoctorStatus.FAIL,
198
206
  message=f"solution.py 本地运行失败(退出码:{result.returncode})",
199
- suggestion="请执行 uv run lc test 定位本地测试错误",
207
+ suggestion="请执行 lc test 定位本地测试错误",
200
208
  )
201
209
  return None
202
210
 
@@ -228,7 +236,7 @@ def diagnose_remote(result: ClientResult) -> tuple[DoctorCheck, DoctorCheck]:
228
236
  name=AUTHENTICATION_CHECK_NAME,
229
237
  status=DoctorStatus.FAIL,
230
238
  message="登录凭证无效或不完整",
231
- suggestion="请执行 uv run lc login 刷新登录态",
239
+ suggestion="请执行 lc login 刷新登录态",
232
240
  ),
233
241
  )
234
242
  case _:
@@ -246,7 +254,7 @@ def diagnose_remote(result: ClientResult) -> tuple[DoctorCheck, DoctorCheck]:
246
254
  name=AUTHENTICATION_CHECK_NAME,
247
255
  status=DoctorStatus.WARNING,
248
256
  message="网络或接口异常,暂时无法验证 Cookie",
249
- suggestion="请先解决连接问题后重新执行 uv run lc doctor",
257
+ suggestion="请先解决连接问题后重新执行 lc doctor",
250
258
  ),
251
259
  )
252
260
 
@@ -264,7 +272,7 @@ def diagnose_remote(result: ClientResult) -> tuple[DoctorCheck, DoctorCheck]:
264
272
  name=AUTHENTICATION_CHECK_NAME,
265
273
  status=DoctorStatus.FAIL,
266
274
  message="Cookie 无效、已过期或当前未登录",
267
- suggestion="请执行 uv run lc login 刷新登录态",
275
+ suggestion="请执行 lc login 刷新登录态",
268
276
  )
269
277
  else:
270
278
  username = status.get("username")
@@ -45,10 +45,10 @@ def client_error_message(kind: ClientErrorKind | None) -> str:
45
45
  return "LeetCode 接口数据结构异常,可能是接口变更"
46
46
 
47
47
  case ClientErrorKind.UNAUTHORIZED:
48
- return "登录态无效或已过期,请重新执行 uv run lc login"
48
+ return "登录态无效或已过期,请重新执行 lc login"
49
49
 
50
50
  case ClientErrorKind.MISSING_CSRF:
51
- return "缺少提交凭证 csrftoken,请重新执行 uv run lc login"
51
+ return "缺少提交凭证 csrftoken,请重新执行 lc login"
52
52
 
53
53
  case _:
54
54
  return "未知客户端错误"
@@ -67,18 +67,18 @@ def _load_cookies_from_session() -> dict[str, str]:
67
67
  error(str(exc))
68
68
  raise Exit(1)
69
69
  if not isinstance(session, dict):
70
- warning("未找到有效登录态,请先执行 uv run lc login")
70
+ warning("未找到有效登录态,请先执行 lc login")
71
71
  raise Exit(1)
72
72
  cookies = session.get("cookies")
73
73
  if not isinstance(cookies, dict):
74
- error("Session 文件结构无效,请重新执行 uv run lc login")
74
+ error("Session 文件结构无效,请重新执行 lc login")
75
75
  raise Exit(1)
76
76
  valid_cookies: dict[str, str] = {}
77
77
  for name in REQUIRED_COOKIE_NAMES:
78
78
  value = cookies.get(name)
79
79
  if not isinstance(value, str) or not value:
80
80
  error(f"缺少或无效的 Cookie:{name}")
81
- warning("请重新执行 uv run lc login")
81
+ warning("请重新执行 lc login")
82
82
  raise Exit(1)
83
83
  valid_cookies[name] = value
84
84
  return valid_cookies
@@ -86,11 +86,11 @@ def _load_cookies_from_session() -> dict[str, str]:
86
86
 
87
87
  def _parse_question_id_or_exit(question_id: str) -> str:
88
88
  parse_result = parse_question_id(question_id)
89
- if not parse_result.ok:
89
+ parsed_question_id = parse_result.question_id
90
+ if not parse_result.ok or parsed_question_id is None:
90
91
  error(parse_result.error_message or "题号解析失败")
91
92
  raise Exit(1)
92
- assert parse_result.question_id is not None
93
- return parse_result.question_id
93
+ return parsed_question_id
94
94
 
95
95
 
96
96
  def _find_problem_summary_by_question_id_online(
@@ -201,9 +201,11 @@ def get_problem_detail_by_question_id(question_id: str) -> ProblemDetail:
201
201
  return problem_detail
202
202
 
203
203
 
204
- def get_doctor_report() -> DoctorReport:
204
+ def get_doctor_report(*, run_solution: bool = False) -> DoctorReport:
205
205
  session_check = diagnose_session()
206
- solution_check = diagnose_solution()
206
+ solution_check = diagnose_solution(
207
+ run_solution=run_solution,
208
+ )
207
209
 
208
210
  cookies: dict[str, str] | None = None
209
211
  try:
@@ -9,10 +9,27 @@ from typing import Any
9
9
  from rich.console import Console
10
10
  from rich.panel import Panel
11
11
  from rich.table import Table
12
+ from rich.text import Text
12
13
 
13
14
  from leetcode_local_cli.doctor import DoctorReport, DoctorStatus
14
15
 
15
- console = Console(width=shutil.get_terminal_size(fallback=(120, 24)).columns)
16
+ console = Console(
17
+ width=shutil.get_terminal_size(fallback=(120, 24)).columns,
18
+ markup=False,
19
+ highlight=False,
20
+ )
21
+
22
+ _UNSAFE_TERMINAL_CHARACTERS = re.compile(r"[\x00-\x08\x0b-\x1f\x7f-\x9f]")
23
+
24
+
25
+ def _sanitize_terminal_text(value: object) -> str:
26
+ """Remove terminal control characters while preserving tabs and newlines."""
27
+ return _UNSAFE_TERMINAL_CHARACTERS.sub("\N{REPLACEMENT CHARACTER}", str(value))
28
+
29
+
30
+ def _external_text(value: object, *, style: str = "") -> Text:
31
+ """Render external data as plain text with an optional trusted local style."""
32
+ return Text(_sanitize_terminal_text(value), style=style)
16
33
 
17
34
 
18
35
  def _terminal_width() -> int:
@@ -56,20 +73,20 @@ def _html_to_text(content_html: str) -> str:
56
73
 
57
74
  @contextmanager
58
75
  def loading(message: str) -> Iterator[None]:
59
- with console.status(message, spinner="dots"):
76
+ with console.status(_external_text(message), spinner="dots"):
60
77
  yield
61
78
 
62
79
 
63
80
  def success(message: str) -> None:
64
- console.print(f"[bold green]{message}[/bold green]")
81
+ console.print(_external_text(message, style="bold green"))
65
82
 
66
83
 
67
84
  def warning(message: str) -> None:
68
- console.print(f"[bold yellow]{message}[/bold yellow]")
85
+ console.print(_external_text(message, style="bold yellow"))
69
86
 
70
87
 
71
88
  def error(message: str) -> None:
72
- console.print(f"[bold red]{message}[/bold red]")
89
+ console.print(_external_text(message, style="bold red"))
73
90
 
74
91
 
75
92
  def render_profile(profile: dict[str, Any]) -> None:
@@ -80,16 +97,24 @@ def render_profile(profile: dict[str, Any]) -> None:
80
97
  table.add_column("Item", style="cyan", no_wrap=True)
81
98
  table.add_column("Value", style="white")
82
99
 
83
- table.add_row("Username", str(profile.get("username") or "-"))
84
- table.add_row("Real Name", str(profile.get("real_name") or "-"))
85
- table.add_row("Premium", "Yes" if profile.get("is_premium") else "No")
100
+ table.add_row("Username", _external_text(profile.get("username") or "-"))
101
+ table.add_row("Real Name", _external_text(profile.get("real_name") or "-"))
102
+ table.add_row(
103
+ "Premium", _external_text("Yes" if profile.get("is_premium") else "No")
104
+ )
86
105
  table.add_row(
87
106
  "Solved",
88
- f"All {solved['All']} | Easy {solved['Easy']} | Medium {solved['Medium']} | Hard {solved['Hard']}",
107
+ _external_text(
108
+ f"All {solved['All']} | Easy {solved['Easy']} | "
109
+ f"Medium {solved['Medium']} | Hard {solved['Hard']}"
110
+ ),
89
111
  )
90
112
  table.add_row(
91
113
  "Total",
92
- f"All {total['All']} | Easy {total['Easy']} | Medium {total['Medium']} | Hard {total['Hard']}",
114
+ _external_text(
115
+ f"All {total['All']} | Easy {total['Easy']} | "
116
+ f"Medium {total['Medium']} | Hard {total['Hard']}"
117
+ ),
93
118
  )
94
119
 
95
120
  console.print(Panel(table, border_style="green", width=_terminal_width()))
@@ -121,19 +146,20 @@ def render_problem_list(problems: list[Any]) -> None:
121
146
  for problem in problems:
122
147
  difficulty = problem.difficulty or "-"
123
148
  difficulty_style = difficulty_styles.get(difficulty, "white")
124
- paid_text = (
125
- "[yellow]Paid[/yellow]" if problem.paid_only else "[green]Free[/green]"
149
+ paid_text = _external_text(
150
+ "Paid" if problem.paid_only else "Free",
151
+ style="yellow" if problem.paid_only else "green",
126
152
  )
127
153
  tags = ", ".join(problem.tags[:4])
128
154
  if len(problem.tags) > 4:
129
155
  tags = f"{tags}, ..."
130
156
 
131
157
  table.add_row(
132
- problem.question_id,
133
- problem.title or "-",
134
- f"[{difficulty_style}]{difficulty}[/{difficulty_style}]",
158
+ _external_text(problem.question_id),
159
+ _external_text(problem.title or "-"),
160
+ _external_text(difficulty, style=difficulty_style),
135
161
  paid_text,
136
- tags or "-",
162
+ _external_text(tags or "-", style="dim"),
137
163
  )
138
164
 
139
165
  console.print(table)
@@ -145,12 +171,12 @@ def render_problem_detail(problem: Any) -> None:
145
171
  meta = Table.grid(padding=(0, 2))
146
172
  meta.add_column(style="cyan", no_wrap=True)
147
173
  meta.add_column(style="white")
148
- meta.add_row("ID", problem.question_id)
149
- meta.add_row("Slug", problem.title_slug)
150
- meta.add_row("Difficulty", problem.difficulty)
151
- meta.add_row("Tags", tags)
174
+ meta.add_row("ID", _external_text(problem.question_id))
175
+ meta.add_row("Slug", _external_text(problem.title_slug))
176
+ meta.add_row("Difficulty", _external_text(problem.difficulty))
177
+ meta.add_row("Tags", _external_text(tags))
152
178
 
153
- title = f"{problem.question_id}. {problem.title}"
179
+ title = _external_text(f"{problem.question_id}. {problem.title}")
154
180
  console.print(
155
181
  Panel(meta, title=title, border_style="cyan", width=_terminal_width())
156
182
  )
@@ -158,7 +184,7 @@ def render_problem_detail(problem: Any) -> None:
158
184
  content_text = _html_to_text(problem.content_html)
159
185
  console.print(
160
186
  Panel(
161
- content_text or "-",
187
+ _external_text(content_text or "-"),
162
188
  title="题面",
163
189
  border_style="white",
164
190
  width=_terminal_width(),
@@ -171,9 +197,11 @@ def render_problem_detail(problem: Any) -> None:
171
197
 
172
198
  def render_submission_target(metadata: Any) -> None:
173
199
  console.print(
174
- "[bold cyan]当前提交目标:"
175
- f"{metadata.problem_id}. {metadata.title} ({metadata.title_slug})"
176
- "[/bold cyan]"
200
+ _external_text(
201
+ f"当前提交目标:{metadata.problem_id}. "
202
+ f"{metadata.title} ({metadata.title_slug})",
203
+ style="bold cyan",
204
+ )
177
205
  )
178
206
 
179
207
 
@@ -198,10 +226,10 @@ def render_doctor_report(report: DoctorReport) -> None:
198
226
  for check in report.checks:
199
227
  status_text, status_style = status_labels[check.status]
200
228
  table.add_row(
201
- labels.get(check.name, check.name),
202
- f"[{status_style}]{status_text}[/{status_style}]",
203
- check.message,
204
- check.suggestion or "-",
229
+ _external_text(labels.get(check.name, check.name)),
230
+ _external_text(status_text, style=status_style),
231
+ _external_text(check.message),
232
+ _external_text(check.suggestion or "-"),
205
233
  )
206
234
 
207
235
  border_style = "green" if report.ok else "red"
@@ -235,11 +263,11 @@ def render_submission_result(result: dict[str, Any] | None) -> None:
235
263
  )
236
264
  table.add_column("Item", style="cyan", no_wrap=True)
237
265
  table.add_column("Value", style="white")
238
- table.add_row("Status", status_msg)
239
- table.add_row("Runtime", runtime)
240
- table.add_row("Memory", memory)
266
+ table.add_row("Status", _external_text(status_msg))
267
+ table.add_row("Runtime", _external_text(runtime))
268
+ table.add_row("Memory", _external_text(memory))
241
269
  if total_correct is not None and total_testcases is not None:
242
- table.add_row("Cases", f"{total_correct} / {total_testcases}")
270
+ table.add_row("Cases", _external_text(f"{total_correct} / {total_testcases}"))
243
271
 
244
272
  console.print(
245
273
  Panel(