raytoolsbox 2.1.0__tar.gz → 3.0.0__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.
- {raytoolsbox-2.1.0 → raytoolsbox-3.0.0}/.gitignore +1 -1
- raytoolsbox-3.0.0/CHANGELOG.md +107 -0
- raytoolsbox-3.0.0/LICENSE +21 -0
- {raytoolsbox-2.1.0 → raytoolsbox-3.0.0}/PKG-INFO +38 -73
- {raytoolsbox-2.1.0 → raytoolsbox-3.0.0}/README.md +31 -71
- {raytoolsbox-2.1.0 → raytoolsbox-3.0.0}/pyproject.toml +10 -2
- {raytoolsbox-2.1.0 → raytoolsbox-3.0.0}/src/raytoolsbox/security/__init__.py +1 -1
- {raytoolsbox-2.1.0 → raytoolsbox-3.0.0}/src/raytoolsbox/security/authenticator.py +110 -51
- {raytoolsbox-2.1.0 → raytoolsbox-3.0.0}/src/raytoolsbox/utils/mailToPhone.py +5 -8
- {raytoolsbox-2.1.0 → raytoolsbox-3.0.0}/tests/security/test_authenticator.py +90 -25
- {raytoolsbox-2.1.0 → raytoolsbox-3.0.0}/tests/test_lazy_imports.py +2 -2
- raytoolsbox-3.0.0/tests/utils/test_mail_to_phone.py +107 -0
- raytoolsbox-2.1.0/CHANGELOG.md +0 -113
- raytoolsbox-2.1.0/tests/utils/test_mail_to_phone.py +0 -54
- {raytoolsbox-2.1.0 → raytoolsbox-3.0.0}/src/raytoolsbox/__init__.py +0 -0
- {raytoolsbox-2.1.0 → raytoolsbox-3.0.0}/src/raytoolsbox/_lazy.py +0 -0
- {raytoolsbox-2.1.0 → raytoolsbox-3.0.0}/src/raytoolsbox/security/crypto_manager.py +0 -0
- {raytoolsbox-2.1.0 → raytoolsbox-3.0.0}/src/raytoolsbox/security/pin_manager.py +0 -0
- {raytoolsbox-2.1.0 → raytoolsbox-3.0.0}/src/raytoolsbox/utils/__init__.py +0 -0
- {raytoolsbox-2.1.0 → raytoolsbox-3.0.0}/src/raytoolsbox/utils/monitor_func.py +0 -0
- {raytoolsbox-2.1.0 → raytoolsbox-3.0.0}/src/raytoolsbox/utils/useful_func.py +0 -0
- {raytoolsbox-2.1.0 → raytoolsbox-3.0.0}/tests/readme.md +0 -0
- {raytoolsbox-2.1.0 → raytoolsbox-3.0.0}/tests/security/test_crypto_manager.py +0 -0
- {raytoolsbox-2.1.0 → raytoolsbox-3.0.0}/tests/security/test_pin_manager.py +0 -0
- {raytoolsbox-2.1.0 → raytoolsbox-3.0.0}/tests/utils/test_monitor_func.py +0 -0
- {raytoolsbox-2.1.0 → raytoolsbox-3.0.0}/tests/utils/test_useful_func.py +0 -0
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
所有对本项目的显著变更都将记录在此文件中。
|
|
4
|
+
|
|
5
|
+
格式基于 [Keep a Changelog](https://keepachangelog.com/zh-CN/1.1.0/),
|
|
6
|
+
版本管理遵循 [Semantic Versioning](https://semver.org/lang/zh-CN/)。
|
|
7
|
+
|
|
8
|
+
## [Unreleased]
|
|
9
|
+
|
|
10
|
+
## [3.0.0] - 2026-12-07
|
|
11
|
+
|
|
12
|
+
### Changed
|
|
13
|
+
|
|
14
|
+
- `Authenticator.get_secret()` 不再打印终端二维码,只返回 `{uri, secret, expires_in}`,二维码由调用方自行生成
|
|
15
|
+
- `Authenticator.delete()` 改为 `delete(code)`:已绑定时必须提供当前验证码,验证失败抛 `PermissionError`,避免本机任意脚本静默摘除 2FA
|
|
16
|
+
- `Authenticator.get_secret()` 增加防误用限制:已有未完成的待绑定 secret 时拒绝重复生成;待绑定 secret 有 5 分钟有效期与 5 次失败上限,超时或超次后作废
|
|
17
|
+
|
|
18
|
+
### Removed
|
|
19
|
+
|
|
20
|
+
- 移除库内二维码生成能力与 `qrcode[pil]` 运行时依赖(连带去掉 pillow),展示层交还调用方
|
|
21
|
+
- `Authenticator.get_secret(force=True)`:重新绑定必须先 `delete(code)` 解除,不再支持直接覆盖已绑定账户
|
|
22
|
+
|
|
23
|
+
### ⚠ Breaking
|
|
24
|
+
|
|
25
|
+
- `get_secret()` 返回值新增 `expires_in`,不再输出二维码;依赖终端 ASCII 二维码的调用方需自行渲染
|
|
26
|
+
- `get_secret()` 移除 `force` 参数,已绑定时一律抛 `RuntimeError`,需先 `delete(code)`
|
|
27
|
+
- `delete()` 已绑定时必须传当前验证码 `code`,否则抛 `ValueError`
|
|
28
|
+
|
|
29
|
+
## [2.1.0] - 2026-12-06
|
|
30
|
+
|
|
31
|
+
### Added
|
|
32
|
+
|
|
33
|
+
- 新增子进程/子线程执行器(`run_in_subprocess` / `run_in_subthread`,支持超时与异常透传),并提供顶层公共 API 与 `raytoolsbox.__version__`
|
|
34
|
+
- 安全模块增强:`get_secret(force=True)` 支持重新绑定,keyring 不可用时回退 600 权限文件存储,新增输入校验
|
|
35
|
+
- `send_email()` 支持 `timeout` 与 SSL/TLS;新增 `scripts/release.py` 一键发布脚本
|
|
36
|
+
|
|
37
|
+
### Changed
|
|
38
|
+
|
|
39
|
+
- 改用 `src/` layout,子包改为 PEP 562 惰性导入,不再连带加载无关依赖
|
|
40
|
+
- 库内 `print` 改为 `logging`,移除 `__main__` 演示块与死循环;切换 Hatchling 构建,重构测试与 `example/` 目录结构
|
|
41
|
+
- 版本管理改为手动,`uv version --bump` 升版本(同步 `uv.lock`),tag 在发布成功后创建
|
|
42
|
+
|
|
43
|
+
### Fixed
|
|
44
|
+
|
|
45
|
+
- `CryptoManager` 修复空 PIN 无法加载,非法参数改为先校验并抛 `TypeError`,不再静默返回 `None`
|
|
46
|
+
- `run_in_subprocess()` 无法 pickle 时抛出带原始原因的异常;PIN 哈希比较改用 `hmac.compare_digest`;`make_timer()` 改用单调时钟
|
|
47
|
+
|
|
48
|
+
### Removed
|
|
49
|
+
|
|
50
|
+
- 移除 `python-semantic-release` 及配置、早期重复实现、构建残留与示例多余开发依赖
|
|
51
|
+
|
|
52
|
+
### ⚠ Breaking
|
|
53
|
+
|
|
54
|
+
- `get_secret()` 已绑定时改抛 `RuntimeError`;`decrypt()` / `verify()` 参数类型错误改抛 `TypeError`
|
|
55
|
+
|
|
56
|
+
## [2.0.1] - 2026-07-03
|
|
57
|
+
|
|
58
|
+
### Added
|
|
59
|
+
|
|
60
|
+
- 集成 `python-semantic-release` 自动版本管理
|
|
61
|
+
|
|
62
|
+
### Changed
|
|
63
|
+
|
|
64
|
+
- `uv` 全面替代 `pip`/`poetry` 管理依赖和构建
|
|
65
|
+
|
|
66
|
+
## [1.1.2] - 2026-02-05
|
|
67
|
+
|
|
68
|
+
### Fixed
|
|
69
|
+
|
|
70
|
+
- 修复资源路径获取逻辑,增强 PyInstaller 打包兼容性
|
|
71
|
+
|
|
72
|
+
### Changed
|
|
73
|
+
|
|
74
|
+
- 重构函数注释体系,统一文档风格
|
|
75
|
+
|
|
76
|
+
## [1.1.1] - 2026-02-02
|
|
77
|
+
|
|
78
|
+
### Fixed
|
|
79
|
+
|
|
80
|
+
- 调整 Python 支持范围为 `>=3.11`
|
|
81
|
+
|
|
82
|
+
### Changed
|
|
83
|
+
|
|
84
|
+
- Python 版本从 3.13 降级至 3.11,提升兼容性
|
|
85
|
+
|
|
86
|
+
## [1.1.0] - 2026-02-02
|
|
87
|
+
|
|
88
|
+
### Added
|
|
89
|
+
|
|
90
|
+
- **PinManager** — PBKDF2-HMAC-SHA256 PIN 码哈希存储模块
|
|
91
|
+
- **Authenticator** — TOTP 双因素认证模块
|
|
92
|
+
|
|
93
|
+
### Changed
|
|
94
|
+
|
|
95
|
+
- 重构项目结构,将所有密码学相关操作归入 `security` 子包
|
|
96
|
+
|
|
97
|
+
## [1.0.0] - 2026-02-01
|
|
98
|
+
|
|
99
|
+
### Added
|
|
100
|
+
|
|
101
|
+
- 项目初始发布
|
|
102
|
+
- **CryptoManager** — ECC 加密套件(X25519 + ChaCha20-Poly1305 + Ed25519 签名)
|
|
103
|
+
- 邮件发送、性能监控、资源路径解析等工具模块
|
|
104
|
+
|
|
105
|
+
---
|
|
106
|
+
|
|
107
|
+
各版本标签:`v1.0.0` `v1.1.0` `v1.1.1` `v1.1.2` `2.0.1`
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 TIMLES
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -1,16 +1,21 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: raytoolsbox
|
|
3
|
-
Version:
|
|
3
|
+
Version: 3.0.0
|
|
4
4
|
Summary: 个人 Python 工具箱:常用开发工具、性能监控与安全模块(加密签名 / TOTP / PIN)
|
|
5
|
+
Project-URL: Homepage, https://github.com/TIMLES/RayToolsbox
|
|
6
|
+
Project-URL: Repository, https://github.com/TIMLES/RayToolsbox
|
|
7
|
+
Project-URL: Documentation, https://github.com/TIMLES/RayToolsbox/tree/main/example
|
|
8
|
+
Project-URL: Changelog, https://github.com/TIMLES/RayToolsbox/blob/main/CHANGELOG.md
|
|
9
|
+
Project-URL: Issues, https://github.com/TIMLES/RayToolsbox/issues
|
|
5
10
|
Author: TIMLES@https://github.com/TIMLES
|
|
6
11
|
License: MIT
|
|
12
|
+
License-File: LICENSE
|
|
7
13
|
Requires-Python: >=3.11
|
|
8
14
|
Requires-Dist: cryptography>=46.0.4
|
|
9
15
|
Requires-Dist: keyring>=25.7.0
|
|
10
16
|
Requires-Dist: psutil>=7.2.2
|
|
11
17
|
Requires-Dist: pyotp>=2.9.0
|
|
12
18
|
Requires-Dist: pyyaml>=6.0.3
|
|
13
|
-
Requires-Dist: qrcode[pil]>=8.2
|
|
14
19
|
Description-Content-Type: text/markdown
|
|
15
20
|
|
|
16
21
|
|
|
@@ -31,6 +36,9 @@ Description-Content-Type: text/markdown
|
|
|
31
36
|
- 🔐 **现代化加密工具**
|
|
32
37
|
使用 X25519 密钥交换 + ChaCha20-Poly1305 对称加密 + Ed25519 数字签名,支持文本、字节和文件的加密解密与签名验签。
|
|
33
38
|
|
|
39
|
+
- 🛡️ **TOTP 双因素认证与 PIN 管理**
|
|
40
|
+
基于 RFC 6238 的 TOTP 绑定/验证/解绑,密钥存入系统 keyring(不可用时回退 600 权限文件);PIN 使用 PBKDF2-SHA256 加盐哈希,常数时间比较。库只返回数据,二维码由调用方渲染。
|
|
41
|
+
|
|
34
42
|
- ⏱️ **性能监控工具**
|
|
35
43
|
简易性能计时函数 `make_timer()` 与内存监控函数 `make_memory_monitor()`,
|
|
36
44
|
以及完整 benchmark 测试工具 `to_test_func()`,适合代码性能分析和调试。
|
|
@@ -103,89 +111,46 @@ decrypted = cm.decrypt(encrypted)
|
|
|
103
111
|
signed = cm.sign("重要数据", sign_key)
|
|
104
112
|
verified = cm.verify(signed, verify_key)
|
|
105
113
|
```
|
|
114
|
+
|
|
106
115
|
---
|
|
107
116
|
|
|
108
|
-
##
|
|
117
|
+
## 🔐 安全模块(TOTP / PIN)
|
|
109
118
|
|
|
110
|
-
|
|
111
|
-
raytoolsbox/
|
|
112
|
-
│
|
|
113
|
-
├── pyproject.toml # 项目信息 + 依赖管理(uv)
|
|
114
|
-
├── README.md # 项目文档
|
|
115
|
-
├── AGENTS.md # AI 编码助手指令(含发布流程)
|
|
116
|
-
├── CHANGELOG.md # 变更日志
|
|
117
|
-
├── src/
|
|
118
|
-
│ └── raytoolsbox/
|
|
119
|
-
│ ├── __init__.py
|
|
120
|
-
│ ├── utils/
|
|
121
|
-
│ │ ├── __init__.py
|
|
122
|
-
│ │ ├── useful_func.py # 资源路径、窗口居中、子进程/子线程执行器
|
|
123
|
-
│ │ ├── mailToPhone.py # 邮件发送工具
|
|
124
|
-
│ │ └── monitor_func.py # 性能计时器、内存监控、benchmark 测试
|
|
125
|
-
│ └── security/
|
|
126
|
-
│ ├── __init__.py
|
|
127
|
-
│ ├── crypto_manager.py # ECC 加密/签名工具
|
|
128
|
-
│ ├── authenticator.py
|
|
129
|
-
│ └── pin_manager.py
|
|
130
|
-
│
|
|
131
|
-
└── tests/
|
|
132
|
-
├── security/
|
|
133
|
-
│ ├── test_authenticator.py # TOTP 认证测试
|
|
134
|
-
│ ├── test_crypto_manager.py # 加密/签名 + fuzz 测试
|
|
135
|
-
│ └── test_pin_manager.py # PIN 管理测试
|
|
136
|
-
└── utils/
|
|
137
|
-
├── test_mail_to_phone.py # 邮件发送测试
|
|
138
|
-
├── test_monitor_func.py # 性能监控测试
|
|
139
|
-
└── test_useful_func.py # 路径/窗口/子进程工具测试
|
|
140
|
-
|
|
141
|
-
example/ # 与 src 对应的示例(不随包发布)
|
|
142
|
-
├── security/ # 加密与签名.py / 验证器.py / PIN码.py
|
|
143
|
-
└── utils/ # 邮件发送.py / 监控与计时.py / 通用工具.py
|
|
144
|
-
|
|
145
|
-
scripts/
|
|
146
|
-
└── release.py # 一键发布脚本
|
|
147
|
-
```
|
|
119
|
+
### TOTP 双因素认证
|
|
148
120
|
|
|
149
|
-
|
|
121
|
+
库只负责生成/校验并保存密钥,**不生成二维码**——`get_secret()` 返回 `uri` 供任意 QR 库渲染(`qrcode`、`segno`、前端的 `qrcodejs` 都行)。
|
|
150
122
|
|
|
151
|
-
|
|
123
|
+
```python
|
|
124
|
+
from raytoolsbox.security import Authenticator
|
|
152
125
|
|
|
153
|
-
|
|
126
|
+
auth = Authenticator("MyApp", "alice")
|
|
154
127
|
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
128
|
+
if not auth.exist():
|
|
129
|
+
info = auth.get_secret() # {"uri", "secret", "expires_in"}
|
|
130
|
+
# info["uri"] → otpauth://totp/... 交给 QR 库画图
|
|
131
|
+
# info["secret"] → 手机端手动录入用
|
|
132
|
+
# info["expires_in"] → 待绑定密钥有效期(秒),过期需重新获取
|
|
133
|
+
auth.verify(input("6 位验证码:")) # 首次验证通过即完成绑定
|
|
134
|
+
|
|
135
|
+
auth.verify(code) # 之后每次校验,window=1 容忍 ±30 秒时钟误差
|
|
136
|
+
auth.delete(code) # 解绑需提供当前验证码
|
|
159
137
|
```
|
|
160
138
|
|
|
161
|
-
|
|
139
|
+
已绑定时 `get_secret()` 抛出 `RuntimeError`,必须先 `delete(code)`;待绑定密钥有 5 分钟有效期与 5 次失败上限。
|
|
162
140
|
|
|
163
|
-
|
|
164
|
-
58 passed
|
|
165
|
-
```
|
|
141
|
+
### PIN 管理
|
|
166
142
|
|
|
167
|
-
|
|
143
|
+
```python
|
|
144
|
+
from raytoolsbox.security import PinManager
|
|
145
|
+
|
|
146
|
+
pm = PinManager("MyApp")
|
|
147
|
+
pm.set_pin("1234")
|
|
148
|
+
pm.verify_pin("1234") # "OK" / "FAIL" / "not_set"
|
|
149
|
+
pm.change_pin("1234", "5678") # 需提供旧 PIN
|
|
150
|
+
```
|
|
168
151
|
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
### 已完成
|
|
172
|
-
- [x] 邮件发送工具封装(支持多 SMTP 服务)
|
|
173
|
-
- [x] 可本地覆盖的配置系统
|
|
174
|
-
- [x] pytest 自动化测试(mock 网络发送)
|
|
175
|
-
- [x] 现代化加密模块(X25519 + ChaCha20-Poly1305 + Ed25519)
|
|
176
|
-
- [x] 数字签名与验签功能
|
|
177
|
-
- [x] 计时工具
|
|
178
|
-
- [x] 窗口居中工具
|
|
179
|
-
- [x] 资源路径获取(PyInstaller 兼容)
|
|
180
|
-
|
|
181
|
-
### 开发中 / 计划中
|
|
182
|
-
- [ ] 屏幕工具(DPI、尺寸测量)
|
|
183
|
-
- [ ] Tkinter / PySide6 GUI 工具类
|
|
184
|
-
- [ ] 文件操作工具(临时文件、下载器)
|
|
185
|
-
- [ ] 日期工具、定时工具、任务提醒系统
|
|
186
|
-
- [ ] 扩展 CLI(命令行使用工具箱)
|
|
187
|
-
|
|
188
|
-
如果你有想加入的功能欢迎告诉我!
|
|
152
|
+
> 完整可运行示例(FastAPI + 浏览器交互,含二维码渲染与解绑):
|
|
153
|
+
> <https://github.com/TIMLES/RayToolsbox/tree/main/example>
|
|
189
154
|
|
|
190
155
|
---
|
|
191
156
|
|
|
@@ -16,6 +16,9 @@
|
|
|
16
16
|
- 🔐 **现代化加密工具**
|
|
17
17
|
使用 X25519 密钥交换 + ChaCha20-Poly1305 对称加密 + Ed25519 数字签名,支持文本、字节和文件的加密解密与签名验签。
|
|
18
18
|
|
|
19
|
+
- 🛡️ **TOTP 双因素认证与 PIN 管理**
|
|
20
|
+
基于 RFC 6238 的 TOTP 绑定/验证/解绑,密钥存入系统 keyring(不可用时回退 600 权限文件);PIN 使用 PBKDF2-SHA256 加盐哈希,常数时间比较。库只返回数据,二维码由调用方渲染。
|
|
21
|
+
|
|
19
22
|
- ⏱️ **性能监控工具**
|
|
20
23
|
简易性能计时函数 `make_timer()` 与内存监控函数 `make_memory_monitor()`,
|
|
21
24
|
以及完整 benchmark 测试工具 `to_test_func()`,适合代码性能分析和调试。
|
|
@@ -88,89 +91,46 @@ decrypted = cm.decrypt(encrypted)
|
|
|
88
91
|
signed = cm.sign("重要数据", sign_key)
|
|
89
92
|
verified = cm.verify(signed, verify_key)
|
|
90
93
|
```
|
|
94
|
+
|
|
91
95
|
---
|
|
92
96
|
|
|
93
|
-
##
|
|
97
|
+
## 🔐 安全模块(TOTP / PIN)
|
|
94
98
|
|
|
95
|
-
|
|
96
|
-
raytoolsbox/
|
|
97
|
-
│
|
|
98
|
-
├── pyproject.toml # 项目信息 + 依赖管理(uv)
|
|
99
|
-
├── README.md # 项目文档
|
|
100
|
-
├── AGENTS.md # AI 编码助手指令(含发布流程)
|
|
101
|
-
├── CHANGELOG.md # 变更日志
|
|
102
|
-
├── src/
|
|
103
|
-
│ └── raytoolsbox/
|
|
104
|
-
│ ├── __init__.py
|
|
105
|
-
│ ├── utils/
|
|
106
|
-
│ │ ├── __init__.py
|
|
107
|
-
│ │ ├── useful_func.py # 资源路径、窗口居中、子进程/子线程执行器
|
|
108
|
-
│ │ ├── mailToPhone.py # 邮件发送工具
|
|
109
|
-
│ │ └── monitor_func.py # 性能计时器、内存监控、benchmark 测试
|
|
110
|
-
│ └── security/
|
|
111
|
-
│ ├── __init__.py
|
|
112
|
-
│ ├── crypto_manager.py # ECC 加密/签名工具
|
|
113
|
-
│ ├── authenticator.py
|
|
114
|
-
│ └── pin_manager.py
|
|
115
|
-
│
|
|
116
|
-
└── tests/
|
|
117
|
-
├── security/
|
|
118
|
-
│ ├── test_authenticator.py # TOTP 认证测试
|
|
119
|
-
│ ├── test_crypto_manager.py # 加密/签名 + fuzz 测试
|
|
120
|
-
│ └── test_pin_manager.py # PIN 管理测试
|
|
121
|
-
└── utils/
|
|
122
|
-
├── test_mail_to_phone.py # 邮件发送测试
|
|
123
|
-
├── test_monitor_func.py # 性能监控测试
|
|
124
|
-
└── test_useful_func.py # 路径/窗口/子进程工具测试
|
|
125
|
-
|
|
126
|
-
example/ # 与 src 对应的示例(不随包发布)
|
|
127
|
-
├── security/ # 加密与签名.py / 验证器.py / PIN码.py
|
|
128
|
-
└── utils/ # 邮件发送.py / 监控与计时.py / 通用工具.py
|
|
129
|
-
|
|
130
|
-
scripts/
|
|
131
|
-
└── release.py # 一键发布脚本
|
|
132
|
-
```
|
|
99
|
+
### TOTP 双因素认证
|
|
133
100
|
|
|
134
|
-
|
|
101
|
+
库只负责生成/校验并保存密钥,**不生成二维码**——`get_secret()` 返回 `uri` 供任意 QR 库渲染(`qrcode`、`segno`、前端的 `qrcodejs` 都行)。
|
|
135
102
|
|
|
136
|
-
|
|
103
|
+
```python
|
|
104
|
+
from raytoolsbox.security import Authenticator
|
|
137
105
|
|
|
138
|
-
|
|
106
|
+
auth = Authenticator("MyApp", "alice")
|
|
139
107
|
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
108
|
+
if not auth.exist():
|
|
109
|
+
info = auth.get_secret() # {"uri", "secret", "expires_in"}
|
|
110
|
+
# info["uri"] → otpauth://totp/... 交给 QR 库画图
|
|
111
|
+
# info["secret"] → 手机端手动录入用
|
|
112
|
+
# info["expires_in"] → 待绑定密钥有效期(秒),过期需重新获取
|
|
113
|
+
auth.verify(input("6 位验证码:")) # 首次验证通过即完成绑定
|
|
114
|
+
|
|
115
|
+
auth.verify(code) # 之后每次校验,window=1 容忍 ±30 秒时钟误差
|
|
116
|
+
auth.delete(code) # 解绑需提供当前验证码
|
|
144
117
|
```
|
|
145
118
|
|
|
146
|
-
|
|
119
|
+
已绑定时 `get_secret()` 抛出 `RuntimeError`,必须先 `delete(code)`;待绑定密钥有 5 分钟有效期与 5 次失败上限。
|
|
147
120
|
|
|
148
|
-
|
|
149
|
-
58 passed
|
|
150
|
-
```
|
|
121
|
+
### PIN 管理
|
|
151
122
|
|
|
152
|
-
|
|
123
|
+
```python
|
|
124
|
+
from raytoolsbox.security import PinManager
|
|
125
|
+
|
|
126
|
+
pm = PinManager("MyApp")
|
|
127
|
+
pm.set_pin("1234")
|
|
128
|
+
pm.verify_pin("1234") # "OK" / "FAIL" / "not_set"
|
|
129
|
+
pm.change_pin("1234", "5678") # 需提供旧 PIN
|
|
130
|
+
```
|
|
153
131
|
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
### 已完成
|
|
157
|
-
- [x] 邮件发送工具封装(支持多 SMTP 服务)
|
|
158
|
-
- [x] 可本地覆盖的配置系统
|
|
159
|
-
- [x] pytest 自动化测试(mock 网络发送)
|
|
160
|
-
- [x] 现代化加密模块(X25519 + ChaCha20-Poly1305 + Ed25519)
|
|
161
|
-
- [x] 数字签名与验签功能
|
|
162
|
-
- [x] 计时工具
|
|
163
|
-
- [x] 窗口居中工具
|
|
164
|
-
- [x] 资源路径获取(PyInstaller 兼容)
|
|
165
|
-
|
|
166
|
-
### 开发中 / 计划中
|
|
167
|
-
- [ ] 屏幕工具(DPI、尺寸测量)
|
|
168
|
-
- [ ] Tkinter / PySide6 GUI 工具类
|
|
169
|
-
- [ ] 文件操作工具(临时文件、下载器)
|
|
170
|
-
- [ ] 日期工具、定时工具、任务提醒系统
|
|
171
|
-
- [ ] 扩展 CLI(命令行使用工具箱)
|
|
172
|
-
|
|
173
|
-
如果你有想加入的功能欢迎告诉我!
|
|
132
|
+
> 完整可运行示例(FastAPI + 浏览器交互,含二维码渲染与解绑):
|
|
133
|
+
> <https://github.com/TIMLES/RayToolsbox/tree/main/example>
|
|
174
134
|
|
|
175
135
|
---
|
|
176
136
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "raytoolsbox"
|
|
3
|
-
version = "
|
|
3
|
+
version = "3.0.0"
|
|
4
4
|
description = "个人 Python 工具箱:常用开发工具、性能监控与安全模块(加密签名 / TOTP / PIN)"
|
|
5
5
|
authors = [{ name = "TIMLES@https://github.com/TIMLES" }]
|
|
6
6
|
license = {text = "MIT"}
|
|
@@ -12,14 +12,22 @@ dependencies = [
|
|
|
12
12
|
"psutil>=7.2.2",
|
|
13
13
|
"pyotp>=2.9.0",
|
|
14
14
|
"pyyaml>=6.0.3",
|
|
15
|
-
"qrcode[pil]>=8.2",
|
|
16
15
|
]
|
|
17
16
|
|
|
17
|
+
[project.urls]
|
|
18
|
+
Homepage = "https://github.com/TIMLES/RayToolsbox"
|
|
19
|
+
Repository = "https://github.com/TIMLES/RayToolsbox"
|
|
20
|
+
Documentation = "https://github.com/TIMLES/RayToolsbox/tree/main/example"
|
|
21
|
+
Changelog = "https://github.com/TIMLES/RayToolsbox/blob/main/CHANGELOG.md"
|
|
22
|
+
Issues = "https://github.com/TIMLES/RayToolsbox/issues"
|
|
23
|
+
|
|
18
24
|
# 开发依赖(不会随包发布)
|
|
19
25
|
[dependency-groups]
|
|
20
26
|
dev = [
|
|
27
|
+
"fastapi>=0.115",
|
|
21
28
|
"hypothesis>=6.151.4",
|
|
22
29
|
"pytest>=9.0.2",
|
|
30
|
+
"uvicorn>=0.32",
|
|
23
31
|
]
|
|
24
32
|
|
|
25
33
|
# 指定构建系统
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import importlib.util
|
|
2
1
|
import json
|
|
3
2
|
import logging
|
|
4
3
|
import os
|
|
@@ -7,10 +6,14 @@ import time
|
|
|
7
6
|
|
|
8
7
|
import keyring
|
|
9
8
|
import pyotp
|
|
10
|
-
import qrcode
|
|
11
9
|
|
|
12
10
|
logger = logging.getLogger(__name__)
|
|
13
11
|
|
|
12
|
+
#: 待绑定 secret 的有效期(秒),超时后需重新调用 get_secret()
|
|
13
|
+
PENDING_TTL = 300
|
|
14
|
+
#: 待绑定 secret 允许的验证失败次数,达到后作废
|
|
15
|
+
PENDING_MAX_ATTEMPTS = 5
|
|
16
|
+
|
|
14
17
|
|
|
15
18
|
class Authenticator:
|
|
16
19
|
"""
|
|
@@ -20,7 +23,10 @@ class Authenticator:
|
|
|
20
23
|
- 生成及验证 TOTP(基于时间的一次性验证码)
|
|
21
24
|
- 使用系统安全存储(keyring)保存密钥,文件存储作为兜底
|
|
22
25
|
- 支持首次绑定流程(先生成 secret,验证成功后再保存)
|
|
23
|
-
-
|
|
26
|
+
- 只返回绑定数据(otpauth URI / secret / 有效期),不生成也不打印二维码,
|
|
27
|
+
展示交给调用方
|
|
28
|
+
- 重新绑定必须先 delete() 解绑
|
|
29
|
+
- 待绑定 secret 有有效期与失败次数上限,超时或超次需重新 get_secret()
|
|
24
30
|
|
|
25
31
|
说明:
|
|
26
32
|
TOTP 本质上需要一个"secret 秘钥"来生成验证码。
|
|
@@ -55,7 +61,9 @@ class Authenticator:
|
|
|
55
61
|
self._file_path = os.path.expanduser(f"~/.{service_name.lower()}_{account}_totp")
|
|
56
62
|
|
|
57
63
|
# 临时 secret(仅在 get_secret → verify 期间使用)
|
|
58
|
-
self._pending_secret = None
|
|
64
|
+
self._pending_secret: str | None = None
|
|
65
|
+
self._pending_expires: float = 0.0
|
|
66
|
+
self._pending_attempts: int = 0
|
|
59
67
|
|
|
60
68
|
try:
|
|
61
69
|
self._load_secret()
|
|
@@ -77,80 +85,86 @@ class Authenticator:
|
|
|
77
85
|
# ============================================================
|
|
78
86
|
# 绑定 / 初始化
|
|
79
87
|
# ============================================================
|
|
80
|
-
def get_secret(self
|
|
88
|
+
def get_secret(self) -> dict:
|
|
81
89
|
"""
|
|
82
|
-
生成新的 TOTP secret
|
|
90
|
+
生成新的 TOTP secret,返回绑定所需的数据(不生成二维码)
|
|
83
91
|
|
|
84
92
|
功能:
|
|
85
|
-
-
|
|
86
|
-
|
|
87
|
-
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
参数:
|
|
92
|
-
force: 已绑定时是否强制重新生成 secret 以重新绑定(默认 False)
|
|
93
|
+
- 生成新的临时密钥(secret),需配合 :meth:`verify` 输入首次验证码,
|
|
94
|
+
验证成功后永久保存
|
|
95
|
+
- 已绑定时不允许直接重新生成,必须先调用 :meth:`delete` 解绑,避免
|
|
96
|
+
旧绑定在无提示的情况下被覆盖
|
|
97
|
+
- 同一实例已有未过期的待绑定 secret 时拒绝重复生成,防止前一张
|
|
98
|
+
二维码被静默作废
|
|
93
99
|
|
|
94
100
|
返回:
|
|
95
101
|
dict: 包含以下键值:
|
|
96
|
-
- "uri": TOTP 绑定用的 otpauth URI
|
|
97
|
-
- "secret":
|
|
102
|
+
- "uri": TOTP 绑定用的 otpauth URI,交给调用方生成二维码
|
|
103
|
+
- "secret": 此次生成的临时密钥,用于手动输入
|
|
104
|
+
- "expires_in": 该 secret 的剩余有效期(秒),过期后需重新获取
|
|
98
105
|
|
|
99
106
|
异常:
|
|
100
|
-
RuntimeError:
|
|
107
|
+
RuntimeError: 账户已绑定(需先 delete()),或已有未过期的待绑定 secret
|
|
101
108
|
"""
|
|
102
|
-
if self._if_bind
|
|
109
|
+
if self._if_bind:
|
|
103
110
|
raise RuntimeError(
|
|
104
111
|
f"已存在对应账户和应用的 Authenticator({self.service_name} / {self.account});"
|
|
105
|
-
"
|
|
112
|
+
"如需重新绑定,请先调用 delete(code) 解绑"
|
|
113
|
+
)
|
|
114
|
+
|
|
115
|
+
if self._pending_alive():
|
|
116
|
+
remaining = max(int(self._pending_expires - time.monotonic()), 0)
|
|
117
|
+
raise RuntimeError(
|
|
118
|
+
"已有待验证的 secret,请先完成 verify(),"
|
|
119
|
+
f"或等待其过期(剩余约 {remaining} 秒)后重试"
|
|
106
120
|
)
|
|
107
121
|
|
|
108
122
|
# 随机生成 TOTP 的 Base32 秘钥
|
|
109
123
|
self._pending_secret = pyotp.random_base32()
|
|
124
|
+
self._pending_expires = time.monotonic() + PENDING_TTL
|
|
125
|
+
self._pending_attempts = 0
|
|
110
126
|
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
logger.info("正在生成 Authenticator 绑定信息...")
|
|
127
|
+
logger.info(
|
|
128
|
+
"正在生成 Authenticator 绑定信息(请在 %d 分钟内完成绑定)...", PENDING_TTL // 60
|
|
129
|
+
)
|
|
115
130
|
|
|
116
|
-
# 根据 secret 生成 provisioning URI
|
|
131
|
+
# 根据 secret 生成 provisioning URI(调用方据此生成二维码)
|
|
117
132
|
totp = pyotp.TOTP(self._pending_secret)
|
|
118
133
|
uri = totp.provisioning_uri(
|
|
119
134
|
name=self.account, # 在 Authenticator 中显示的账户名
|
|
120
135
|
issuer_name=self.service_name, # 在 Authenticator 中显示的服务名
|
|
121
136
|
)
|
|
122
137
|
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
box_size=1,
|
|
129
|
-
border=0,
|
|
130
|
-
)
|
|
131
|
-
qr.add_data(uri)
|
|
132
|
-
qr.make(fit=True)
|
|
133
|
-
|
|
134
|
-
logger.info("请使用 Authenticator 扫描下面二维码:")
|
|
135
|
-
qr.print_ascii(invert=True) # 终端 ASCII QR 显示
|
|
136
|
-
logger.info("请扫描二维码后,输入首次验证码完成绑定。")
|
|
137
|
-
else:
|
|
138
|
-
# qrcode 的 ASCII 输出依赖 pillow,未安装时退化为文本提示
|
|
139
|
-
logger.warning("未安装 pillow,无法输出终端二维码;请改用返回的 uri 或 secret 手工添加")
|
|
140
|
-
logger.info("绑定 URI: %s", uri)
|
|
138
|
+
return {
|
|
139
|
+
"uri": uri,
|
|
140
|
+
"secret": self._pending_secret,
|
|
141
|
+
"expires_in": PENDING_TTL,
|
|
142
|
+
}
|
|
141
143
|
|
|
142
144
|
return {"uri": uri, "secret": self._pending_secret}
|
|
143
145
|
|
|
144
146
|
# ============================================================
|
|
145
147
|
# 删除现有绑定(解绑)
|
|
146
148
|
# ============================================================
|
|
147
|
-
def delete(self) -> bool:
|
|
149
|
+
def delete(self, code: str | None = None) -> bool:
|
|
148
150
|
"""
|
|
149
|
-
删除当前账户的 TOTP
|
|
151
|
+
删除当前账户的 TOTP 绑定(已绑定时需验证当前验证码)
|
|
152
|
+
|
|
153
|
+
参数:
|
|
154
|
+
code: 当前绑定设备显示的 6 位验证码;已绑定时必填,未绑定时可省略
|
|
150
155
|
|
|
151
156
|
返回:
|
|
152
157
|
bool: True 表示至少有一个存储被删除,False 表示两个地方都没有数据(或删除失败)
|
|
158
|
+
|
|
159
|
+
异常:
|
|
160
|
+
ValueError: 已绑定但未提供 code,或 code 格式不合法
|
|
161
|
+
PermissionError: 验证码校验失败,绑定未被解除
|
|
153
162
|
"""
|
|
163
|
+
if self._if_bind:
|
|
164
|
+
if code is None:
|
|
165
|
+
raise ValueError("解除绑定需要提供当前验证码,请传入 delete(code)")
|
|
166
|
+
self._check_stored_code(code)
|
|
167
|
+
|
|
154
168
|
removed = False
|
|
155
169
|
try:
|
|
156
170
|
stored = keyring.get_password(self.service_name, self._key)
|
|
@@ -174,9 +188,46 @@ class Authenticator:
|
|
|
174
188
|
logger.info("没有找到可删除的 TOTP 绑定: %s / %s", self.service_name, self.account)
|
|
175
189
|
|
|
176
190
|
self._if_bind = False
|
|
177
|
-
self.
|
|
191
|
+
self._clear_pending()
|
|
178
192
|
return removed
|
|
179
193
|
|
|
194
|
+
# ============================================================
|
|
195
|
+
# 待绑定 secret 状态
|
|
196
|
+
# ============================================================
|
|
197
|
+
def _clear_pending(self) -> None:
|
|
198
|
+
"""清空待绑定 secret 及其有效期与失败计数。"""
|
|
199
|
+
self._pending_secret = None
|
|
200
|
+
self._pending_expires = 0.0
|
|
201
|
+
self._pending_attempts = 0
|
|
202
|
+
|
|
203
|
+
def _pending_alive(self) -> bool:
|
|
204
|
+
"""待绑定 secret 是否仍可用;超时或失败次数超限时自动作废。"""
|
|
205
|
+
if self._pending_secret is None:
|
|
206
|
+
return False
|
|
207
|
+
if time.monotonic() >= self._pending_expires:
|
|
208
|
+
logger.warning("待绑定的 secret 已超时(超过 %d 秒),已作废", PENDING_TTL)
|
|
209
|
+
self._clear_pending()
|
|
210
|
+
return False
|
|
211
|
+
if self._pending_attempts >= PENDING_MAX_ATTEMPTS:
|
|
212
|
+
logger.warning("待绑定的 secret 验证失败次数过多,已作废")
|
|
213
|
+
self._clear_pending()
|
|
214
|
+
return False
|
|
215
|
+
return True
|
|
216
|
+
|
|
217
|
+
def _check_stored_code(self, code: str) -> None:
|
|
218
|
+
"""用已存储的 secret 校验验证码,失败抛 PermissionError。
|
|
219
|
+
|
|
220
|
+
存储密钥已丢失时直接放行(此时没有可保护的绑定,允许清理残留)。
|
|
221
|
+
"""
|
|
222
|
+
code = self._normalize_code(code)
|
|
223
|
+
try:
|
|
224
|
+
secret = self._load_secret()
|
|
225
|
+
except RuntimeError:
|
|
226
|
+
logger.warning("绑定密钥已丢失,直接清理残留数据")
|
|
227
|
+
return
|
|
228
|
+
if not pyotp.TOTP(secret).verify(code, valid_window=1):
|
|
229
|
+
raise PermissionError("验证码校验失败,绑定未被解除")
|
|
230
|
+
|
|
180
231
|
# ============================================================
|
|
181
232
|
# 验证验证码
|
|
182
233
|
# ============================================================
|
|
@@ -211,30 +262,38 @@ class Authenticator:
|
|
|
211
262
|
异常:
|
|
212
263
|
TypeError: code 不是字符串
|
|
213
264
|
ValueError: code 不是 6 位数字
|
|
214
|
-
RuntimeError:
|
|
265
|
+
RuntimeError: 没有待验证的 secret,或待绑定 secret 已过期/失败次数超限
|
|
215
266
|
"""
|
|
216
267
|
code = self._normalize_code(code)
|
|
217
268
|
|
|
218
|
-
if self._if_bind
|
|
269
|
+
if self._if_bind:
|
|
219
270
|
try:
|
|
220
271
|
totp = pyotp.TOTP(self._load_secret()) # 根据存储密钥,创建 TOTP 验证器
|
|
221
272
|
except RuntimeError:
|
|
222
273
|
# 已绑定状态下的密钥丢失(外部清理 keyring / 文件)
|
|
223
274
|
# 同步修正内部状态,避免后续调用持续抛出异常
|
|
224
275
|
self._if_bind = False
|
|
225
|
-
self.
|
|
276
|
+
self._clear_pending()
|
|
226
277
|
logger.warning("已绑定的 TOTP 密钥丢失,状态已重置为未绑定")
|
|
227
278
|
return False
|
|
228
279
|
return totp.verify(code, valid_window=window)
|
|
229
280
|
|
|
230
|
-
if
|
|
281
|
+
if self._pending_secret is None:
|
|
231
282
|
raise RuntimeError("当前没有待绑定的 secret,请先执行 get_secret()")
|
|
283
|
+
if not self._pending_alive():
|
|
284
|
+
raise RuntimeError("待绑定的 secret 已超时或失败次数过多,请重新调用 get_secret()")
|
|
232
285
|
|
|
233
286
|
totp = pyotp.TOTP(self._pending_secret)
|
|
234
287
|
|
|
235
288
|
# 验证用户输入的验证码
|
|
236
289
|
if not totp.verify(code, valid_window=window):
|
|
237
|
-
|
|
290
|
+
self._pending_attempts += 1
|
|
291
|
+
remaining = PENDING_MAX_ATTEMPTS - self._pending_attempts
|
|
292
|
+
if remaining <= 0:
|
|
293
|
+
logger.warning("待绑定的 secret 失败次数过多,已作废,请重新调用 get_secret()")
|
|
294
|
+
self._clear_pending()
|
|
295
|
+
else:
|
|
296
|
+
logger.warning("验证码验证失败,剩余尝试次数 %d", remaining)
|
|
238
297
|
return False
|
|
239
298
|
|
|
240
299
|
# 构建保存的数据
|
|
@@ -252,7 +311,7 @@ class Authenticator:
|
|
|
252
311
|
return False
|
|
253
312
|
|
|
254
313
|
self._if_bind = True
|
|
255
|
-
self.
|
|
314
|
+
self._clear_pending()
|
|
256
315
|
logger.info("首次验证成功,Authenticator 绑定完成")
|
|
257
316
|
return True
|
|
258
317
|
|
|
@@ -36,14 +36,11 @@ def _open_smtp(server: str, port: int, use_ssl, timeout: float):
|
|
|
36
36
|
|
|
37
37
|
|
|
38
38
|
def _load_email_config(provider: str) -> dict:
|
|
39
|
-
#
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
#
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
# 挑选存在的一个
|
|
46
|
-
config_path = local_config if local_config.exists() else home_config
|
|
39
|
+
# 只从用户主目录读,三平台语义一致:
|
|
40
|
+
# Windows -> %USERPROFILE%\.email_config.yaml
|
|
41
|
+
# Linux/macOS -> $HOME/.email_config.yaml
|
|
42
|
+
# 不读模块目录(那是 site-packages,打包后还是临时目录),也不读 cwd
|
|
43
|
+
config_path = Path.home() / ".email_config.yaml"
|
|
47
44
|
|
|
48
45
|
if not config_path.exists():
|
|
49
46
|
raise FileNotFoundError(
|
|
@@ -37,45 +37,78 @@ def test_exist_false_by_default(auth):
|
|
|
37
37
|
# get_secret
|
|
38
38
|
# ======================================================
|
|
39
39
|
def test_get_secret_returns_uri_and_secret(auth):
|
|
40
|
-
"""get_secret() 应返回包含 uri
|
|
40
|
+
"""get_secret() 应返回包含 uri、secret 与 expires_in 的字典。"""
|
|
41
41
|
result = auth.get_secret()
|
|
42
42
|
assert isinstance(result, dict)
|
|
43
|
-
assert "uri"
|
|
44
|
-
assert "secret" in result
|
|
43
|
+
assert set(result) == {"uri", "secret", "expires_in"}
|
|
45
44
|
assert result["uri"].startswith("otpauth://")
|
|
45
|
+
assert result["expires_in"] > 0
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def test_get_secret_does_not_load_qrcode(auth):
|
|
49
|
+
"""库内不再生成二维码,调用 get_secret 不应连带导入 qrcode/PIL。"""
|
|
50
|
+
import sys
|
|
51
|
+
|
|
52
|
+
auth.get_secret()
|
|
53
|
+
assert "qrcode" not in sys.modules
|
|
54
|
+
assert "PIL" not in sys.modules
|
|
46
55
|
|
|
47
56
|
|
|
48
57
|
def test_get_secret_after_bound_raises(auth):
|
|
49
|
-
"""已绑定状态下调用 get_secret 应抛出 RuntimeError
|
|
58
|
+
"""已绑定状态下调用 get_secret 应抛出 RuntimeError,需先 delete()。"""
|
|
50
59
|
# 模拟绑定
|
|
51
60
|
auth._if_bind = True
|
|
52
61
|
with pytest.raises(RuntimeError, match="已存在"):
|
|
53
62
|
auth.get_secret()
|
|
54
63
|
|
|
55
64
|
|
|
56
|
-
def
|
|
57
|
-
"""
|
|
65
|
+
def test_get_secret_repeats_raise_while_pending(auth):
|
|
66
|
+
"""存在未过期的待绑定 secret 时,重复 get_secret 应拒绝而不是静默覆盖。"""
|
|
67
|
+
first = auth.get_secret()
|
|
68
|
+
with pytest.raises(RuntimeError, match="已有待验证的 secret"):
|
|
69
|
+
auth.get_secret()
|
|
70
|
+
# 第一次生成的 secret 仍然有效
|
|
71
|
+
assert auth._pending_secret == first["secret"]
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def test_get_secret_allowed_after_pending_expires(auth):
|
|
75
|
+
"""待绑定 secret 过期后应允许重新生成。"""
|
|
76
|
+
import time
|
|
77
|
+
|
|
78
|
+
auth.get_secret()
|
|
79
|
+
auth._pending_expires = time.monotonic() - 1
|
|
80
|
+
second = auth.get_secret()
|
|
81
|
+
assert second["secret"]
|
|
82
|
+
assert auth._pending_attempts == 0
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def test_verify_rejects_expired_pending(auth):
|
|
86
|
+
"""待绑定 secret 过期后 verify 应抛 RuntimeError,且不完成绑定。"""
|
|
87
|
+
import time
|
|
88
|
+
|
|
58
89
|
import pyotp
|
|
59
90
|
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
# 强制重新生成:拿到的是新 secret,但此时仍未覆盖旧绑定
|
|
66
|
-
second = auth.get_secret(force=True)
|
|
67
|
-
assert isinstance(second, dict)
|
|
68
|
-
assert second["secret"] != old_secret
|
|
69
|
-
assert second["uri"].startswith("otpauth://")
|
|
70
|
-
assert auth.exist() is True
|
|
91
|
+
secret = auth.get_secret()["secret"]
|
|
92
|
+
auth._pending_expires = time.monotonic() - 1
|
|
93
|
+
with pytest.raises(RuntimeError, match="已超时"):
|
|
94
|
+
auth.verify(pyotp.TOTP(secret).now())
|
|
95
|
+
assert auth.exist() is False
|
|
71
96
|
|
|
72
|
-
# 新 secret 校验失败不应破坏原有绑定
|
|
73
|
-
assert auth.verify(pyotp.TOTP(old_secret).now(), window=0) is False
|
|
74
|
-
assert auth.exist() is True
|
|
75
97
|
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
98
|
+
def test_verify_pending_attempts_exhausted(auth):
|
|
99
|
+
"""首次绑定连续输错达上限后,待绑定 secret 作废。"""
|
|
100
|
+
import pyotp
|
|
101
|
+
|
|
102
|
+
from raytoolsbox.security.authenticator import PENDING_MAX_ATTEMPTS
|
|
103
|
+
|
|
104
|
+
secret = auth.get_secret()["secret"]
|
|
105
|
+
for _ in range(PENDING_MAX_ATTEMPTS):
|
|
106
|
+
assert auth.verify("000000", window=0) is False
|
|
107
|
+
|
|
108
|
+
assert auth._pending_secret is None
|
|
109
|
+
with pytest.raises(RuntimeError, match="没有待绑定的 secret"):
|
|
110
|
+
auth.verify(pyotp.TOTP(secret).now())
|
|
111
|
+
assert auth.exist() is False
|
|
79
112
|
|
|
80
113
|
|
|
81
114
|
def test_verify_normalizes_whitespace(auth):
|
|
@@ -176,13 +209,45 @@ def test_verify_bound_wrong_code(auth):
|
|
|
176
209
|
# delete
|
|
177
210
|
# ======================================================
|
|
178
211
|
def test_delete_removes_binding(auth):
|
|
179
|
-
"""delete()
|
|
212
|
+
"""delete(code) 验证通过后应解除绑定。"""
|
|
213
|
+
import pyotp
|
|
214
|
+
|
|
215
|
+
info = auth.get_secret()
|
|
216
|
+
totp = pyotp.TOTP(info["secret"])
|
|
217
|
+
auth.verify(totp.now())
|
|
218
|
+
|
|
219
|
+
assert auth.exist() is True
|
|
220
|
+
assert auth.delete(totp.now()) is True
|
|
221
|
+
assert auth.exist() is False
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def test_delete_requires_code_when_bound(auth):
|
|
225
|
+
"""已绑定时不传 code 应拒绝解绑。"""
|
|
180
226
|
import pyotp
|
|
181
227
|
|
|
182
228
|
info = auth.get_secret()
|
|
183
229
|
totp = pyotp.TOTP(info["secret"])
|
|
184
230
|
auth.verify(totp.now())
|
|
185
231
|
|
|
232
|
+
with pytest.raises(ValueError, match="需要提供当前验证码"):
|
|
233
|
+
auth.delete()
|
|
186
234
|
assert auth.exist() is True
|
|
187
|
-
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def test_delete_rejects_wrong_code(auth):
|
|
238
|
+
"""验证码错误时不得解绑。"""
|
|
239
|
+
import pyotp
|
|
240
|
+
|
|
241
|
+
info = auth.get_secret()
|
|
242
|
+
totp = pyotp.TOTP(info["secret"])
|
|
243
|
+
auth.verify(totp.now())
|
|
244
|
+
|
|
245
|
+
with pytest.raises(PermissionError, match="验证码校验失败"):
|
|
246
|
+
auth.delete("000000")
|
|
247
|
+
assert auth.exist() is True
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def test_delete_without_binding_needs_no_code(auth):
|
|
251
|
+
"""未绑定时 delete() 可不传 code,直接返回 False。"""
|
|
252
|
+
assert auth.delete() is False
|
|
188
253
|
assert auth.exist() is False
|
|
@@ -36,8 +36,8 @@ def _modules_after(statement: str) -> set[str]:
|
|
|
36
36
|
(_STATEMENTS["utils_monitor"], {"smtplib", "yaml", "multiprocessing"}),
|
|
37
37
|
# 只想用路径工具,同样不该拉进邮件
|
|
38
38
|
(_STATEMENTS["utils_useful"], {"smtplib", "yaml"}),
|
|
39
|
-
# 只想用加密,不该拉进 keyring /
|
|
40
|
-
(_STATEMENTS["security_crypto"], {"keyring", "
|
|
39
|
+
# 只想用加密,不该拉进 keyring / pyotp
|
|
40
|
+
(_STATEMENTS["security_crypto"], {"keyring", "pyotp"}),
|
|
41
41
|
# 只 import 顶层包,版本号也不该触发 importlib.metadata
|
|
42
42
|
(_STATEMENTS["top"], {"importlib.metadata", "psutil", "cryptography"}),
|
|
43
43
|
],
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
"""测试 send_email(基于 smtplib.SMTP_SSL)"""
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from unittest.mock import patch
|
|
5
|
+
|
|
6
|
+
import pytest
|
|
7
|
+
|
|
8
|
+
from raytoolsbox.utils.mailToPhone import _load_email_config, send_email
|
|
9
|
+
|
|
10
|
+
YAML_TEXT = """
|
|
11
|
+
qq:
|
|
12
|
+
smtp_server: smtp.qq.com
|
|
13
|
+
smtp_port: 465
|
|
14
|
+
from_addr: test@qq.com
|
|
15
|
+
password: auth_code
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@pytest.fixture
|
|
20
|
+
def fake_home(tmp_path, monkeypatch):
|
|
21
|
+
"""把 Path.home() 指向临时目录,避免读写真实 ~/.email_config.yaml。"""
|
|
22
|
+
monkeypatch.setattr(Path, "home", classmethod(lambda cls: tmp_path))
|
|
23
|
+
return tmp_path
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def test_config_read_from_home(fake_home):
|
|
27
|
+
"""配置只从用户主目录读取。"""
|
|
28
|
+
(fake_home / ".email_config.yaml").write_text(YAML_TEXT, encoding="utf-8")
|
|
29
|
+
config = _load_email_config("qq")
|
|
30
|
+
assert config["smtp_server"] == "smtp.qq.com"
|
|
31
|
+
assert config["smtp_port"] == 465
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def test_config_not_found_message_contains_path(fake_home):
|
|
35
|
+
"""找不到配置时,报错信息应给出完整路径方便用户排查。"""
|
|
36
|
+
with pytest.raises(FileNotFoundError) as exc:
|
|
37
|
+
_load_email_config("qq")
|
|
38
|
+
assert str(fake_home / ".email_config.yaml") in str(exc.value)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def test_config_ignores_module_dir(tmp_path, monkeypatch):
|
|
42
|
+
"""放在包模块同目录(site-packages)的配置不会被读取。"""
|
|
43
|
+
monkeypatch.setattr(Path, "home", classmethod(lambda cls: tmp_path / "home"))
|
|
44
|
+
(tmp_path / "home").mkdir()
|
|
45
|
+
package_dir = Path(__file__).parent.parent.parent / "src" / "raytoolsbox" / "utils"
|
|
46
|
+
monkeypatch.setattr(
|
|
47
|
+
"raytoolsbox.utils.mailToPhone.__file__",
|
|
48
|
+
str(package_dir / "mailToPhone.py"),
|
|
49
|
+
)
|
|
50
|
+
with pytest.raises(FileNotFoundError):
|
|
51
|
+
_load_email_config("qq")
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def test_config_unknown_provider(fake_home):
|
|
55
|
+
"""provider 不存在时抛 KeyError 并列出已配置的项。"""
|
|
56
|
+
(fake_home / ".email_config.yaml").write_text(YAML_TEXT, encoding="utf-8")
|
|
57
|
+
with pytest.raises(KeyError):
|
|
58
|
+
_load_email_config("gmail")
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def test_load_email_config_not_found():
|
|
62
|
+
"""找不到配置文件时 send_email 应当返回 False。"""
|
|
63
|
+
with patch("raytoolsbox.utils.mailToPhone.Path.exists", return_value=False):
|
|
64
|
+
result = send_email()
|
|
65
|
+
assert result is False
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def test_smtp_connection_failure():
|
|
69
|
+
"""SMTP 连接失败时应当返回 False。"""
|
|
70
|
+
with (
|
|
71
|
+
patch(
|
|
72
|
+
"raytoolsbox.utils.mailToPhone._load_email_config",
|
|
73
|
+
return_value={
|
|
74
|
+
"smtp_server": "smtp.qq.com",
|
|
75
|
+
"smtp_port": 465,
|
|
76
|
+
"from_addr": "test@qq.com",
|
|
77
|
+
"password": "wrong",
|
|
78
|
+
},
|
|
79
|
+
),
|
|
80
|
+
patch(
|
|
81
|
+
"raytoolsbox.utils.mailToPhone.smtplib.SMTP_SSL",
|
|
82
|
+
side_effect=OSError("模拟连接失败"),
|
|
83
|
+
),
|
|
84
|
+
):
|
|
85
|
+
result = send_email()
|
|
86
|
+
assert result is False
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def test_smtp_login_failure():
|
|
90
|
+
"""SMTP 登录失败时应当返回 False。"""
|
|
91
|
+
mock_smtp = patch("raytoolsbox.utils.mailToPhone.smtplib.SMTP_SSL").start()
|
|
92
|
+
instance = mock_smtp.return_value
|
|
93
|
+
instance.login.side_effect = OSError("模拟登录失败")
|
|
94
|
+
|
|
95
|
+
with patch(
|
|
96
|
+
"raytoolsbox.utils.mailToPhone._load_email_config",
|
|
97
|
+
return_value={
|
|
98
|
+
"smtp_server": "smtp.qq.com",
|
|
99
|
+
"smtp_port": 465,
|
|
100
|
+
"from_addr": "test@qq.com",
|
|
101
|
+
"password": "wrong",
|
|
102
|
+
},
|
|
103
|
+
):
|
|
104
|
+
result = send_email()
|
|
105
|
+
assert result is False
|
|
106
|
+
|
|
107
|
+
patch.stopall()
|
raytoolsbox-2.1.0/CHANGELOG.md
DELETED
|
@@ -1,113 +0,0 @@
|
|
|
1
|
-
# Changelog
|
|
2
|
-
|
|
3
|
-
所有对本项目的显著变更都将记录在此文件中。
|
|
4
|
-
|
|
5
|
-
格式基于 [Keep a Changelog](https://keepachangelog.com/zh-CN/1.1.0/),
|
|
6
|
-
版本管理遵循 [Semantic Versioning](https://semver.org/lang/zh-CN/)。
|
|
7
|
-
|
|
8
|
-
## [Unreleased]
|
|
9
|
-
|
|
10
|
-
## [2.1.0] - 2026-12-06
|
|
11
|
-
|
|
12
|
-
### Added
|
|
13
|
-
|
|
14
|
-
- 子进程/子线程执行器(`run_in_subprocess` / `run_in_subthread`),支持超时与异常透传
|
|
15
|
-
- 顶层与子包公共 API:可直接 `from raytoolsbox.security import CryptoManager`、`from raytoolsbox.utils import make_timer`,并提供 `raytoolsbox.__version__`
|
|
16
|
-
- `Authenticator.get_secret(force=True)`:已绑定时可重新生成 secret 并重新打印二维码,新 secret 验证通过前原绑定保持有效
|
|
17
|
-
- `PinManager` 在 keyring 不可用时回退到文件存储(权限 600),与 `Authenticator` 行为一致
|
|
18
|
-
- `send_email()` 新增 `timeout` 与 `use_ssl` 参数:465 端口走隐式 SSL,587/25 自动升级 STARTTLS
|
|
19
|
-
- `scripts/release.py` 一键发布脚本:发布前校验 → 测试 → 构建 → 上传 PyPI → 打 tag 推送
|
|
20
|
-
|
|
21
|
-
### Fixed
|
|
22
|
-
|
|
23
|
-
- `CryptoManager` 空 PIN 生成密钥后无法加载("能存不能读"):现在保存与加载对 PIN 的处理严格对称
|
|
24
|
-
- `CryptoManager` 未指定密钥目录时加载密钥抛 `AttributeError`,改为抛明确的 `ValueError`
|
|
25
|
-
- `CryptoManager` 解密/验签会把调用方错误(如 `packet` 传 `str`)当成解密失败静默返回 `None`,现在一律抛 `TypeError`
|
|
26
|
-
- `CryptoManager.sign()` 先对非法数据签名再报类型错误,现改为先校验参数
|
|
27
|
-
- `run_in_subprocess()` 返回值或异常无法 pickle 时父进程只收到 `EOFError: ""`,现改为抛带原始原因的 `TypeError`,并把子进程 traceback 附加到异常上
|
|
28
|
-
- `PinManager` 的 PIN 哈希比较改用 `hmac.compare_digest`,避免时序侧信道
|
|
29
|
-
- `make_timer()` 改用单调时钟 `time.perf_counter()`,不再受系统对时/夏令时影响
|
|
30
|
-
- 移除 `monitor_func.py` 中永不退出的 `while 1` 演示死循环
|
|
31
|
-
|
|
32
|
-
### Changed
|
|
33
|
-
|
|
34
|
-
- 子包 `__init__` 改为惰性导入(PEP 562):`import raytoolsbox.utils.monitor_func` 不再连带加载 `smtplib` / `yaml` / `multiprocessing`,`import raytoolsbox.security.crypto_manager` 不再连带加载 `keyring` / `qrcode` / `pyotp`;`raytoolsbox.__version__` 也改为用到时才查 `importlib.metadata`
|
|
35
|
-
- 库内所有 `print` 改为 `logging`(`getLogger(__name__)`),不再污染调用方的 stdout
|
|
36
|
-
- `Authenticator` / `PinManager` 增加输入校验:`service_name`/`account` 拒绝路径分隔符,验证码与 PIN 自动清洗并校验
|
|
37
|
-
- `Authenticator` 写文件改为以 600 权限原子创建,消除先写后改权限的窗口期
|
|
38
|
-
- 移除 `src/` 下三处 `__main__` 演示块,演示统一放到 `example/`
|
|
39
|
-
- `pyproject.toml` 补全中文 description,`qrcode` 改为 `qrcode[pil]`(终端二维码依赖 pillow)
|
|
40
|
-
- 测试体系重构,切换至 Hatchling 构建系统
|
|
41
|
-
- 引入 `src/` layout 项目布局
|
|
42
|
-
- 移除 `python-semantic-release`,改为手动管理版本和 CHANGELOG
|
|
43
|
-
- 显式指定 wheel 打包目录 `src/raytoolsbox`
|
|
44
|
-
- 版本号改用 `uv version --bump` 升级(同步 `uv.lock`),tag 改为发布成功后创建
|
|
45
|
-
- 仓库结构整理:根目录草稿文件夹(`实用工具/`、`邮件发送/`、`C++调用/`、`web及数据工具/`)合并到 `example/` 下的中文分类目录
|
|
46
|
-
- 项目指令文件 `CLAUDE.md` 改名为通用的 `AGENTS.md`,`CLAUDE.md` 仅保留指向
|
|
47
|
-
- `example/` 与 `tests/` 按 `security/`、`utils/` 两个子目录组织,与 `src/raytoolsbox` 一一对应
|
|
48
|
-
- 发布流程文档并入 `AGENTS.md`(主流程 + release 命令内部流程图、失败处理),不再单独维护 `包发布流程.md`
|
|
49
|
-
|
|
50
|
-
### Removed
|
|
51
|
-
|
|
52
|
-
- `python-semantic-release` 自动版本管理工具及其 `[tool.semantic_release]` 配置
|
|
53
|
-
- 早期重复实现(`邮件发送/mailToPhone.py`、`web及数据工具/安全性/验证器.py`)与编译产物 `mylib.dll`
|
|
54
|
-
- hatch 脚手架残留 `main.py`
|
|
55
|
-
- 示例不再需要的开发依赖:`flask`、`fastapi`、`uvicorn`、`matplotlib`、`pynput`、`pyside6`、`tkinterdnd2`、`ttkbootstrap`、`zhdate`,以及重复声明的 `pyyaml`
|
|
56
|
-
|
|
57
|
-
### ⚠ Breaking
|
|
58
|
-
|
|
59
|
-
- `Authenticator.get_secret()` 在账户已绑定时由"返回错误说明字符串"改为抛出 `RuntimeError`,返回类型恒为 `dict`;依赖旧字符串返回值的调用方需改为捕获异常,或传 `force=True` 重新绑定
|
|
60
|
-
- `CryptoManager.decrypt()` / `verify()` 对参数类型错误(如 `packet` 传 `str`)由"静默返回 `None`"改为抛出 `TypeError`,只有数据损坏或密钥不匹配才返回 `None`
|
|
61
|
-
|
|
62
|
-
## [2.0.1] - 2026-07-03
|
|
63
|
-
|
|
64
|
-
### Added
|
|
65
|
-
|
|
66
|
-
- 集成 `python-semantic-release` 自动版本管理
|
|
67
|
-
|
|
68
|
-
### Changed
|
|
69
|
-
|
|
70
|
-
- `uv` 全面替代 `pip`/`poetry` 管理依赖和构建
|
|
71
|
-
|
|
72
|
-
## [1.1.2] - 2026-02-05
|
|
73
|
-
|
|
74
|
-
### Fixed
|
|
75
|
-
|
|
76
|
-
- 修复资源路径获取逻辑,增强 PyInstaller 打包兼容性
|
|
77
|
-
|
|
78
|
-
### Changed
|
|
79
|
-
|
|
80
|
-
- 重构函数注释体系,统一文档风格
|
|
81
|
-
|
|
82
|
-
## [1.1.1] - 2026-02-02
|
|
83
|
-
|
|
84
|
-
### Fixed
|
|
85
|
-
|
|
86
|
-
- 调整 Python 支持范围为 `>=3.11`
|
|
87
|
-
|
|
88
|
-
### Changed
|
|
89
|
-
|
|
90
|
-
- Python 版本从 3.13 降级至 3.11,提升兼容性
|
|
91
|
-
|
|
92
|
-
## [1.1.0] - 2026-02-02
|
|
93
|
-
|
|
94
|
-
### Added
|
|
95
|
-
|
|
96
|
-
- **PinManager** — PBKDF2-HMAC-SHA256 PIN 码哈希存储模块
|
|
97
|
-
- **Authenticator** — TOTP 双因素认证模块
|
|
98
|
-
|
|
99
|
-
### Changed
|
|
100
|
-
|
|
101
|
-
- 重构项目结构,将所有密码学相关操作归入 `security` 子包
|
|
102
|
-
|
|
103
|
-
## [1.0.0] - 2026-02-01
|
|
104
|
-
|
|
105
|
-
### Added
|
|
106
|
-
|
|
107
|
-
- 项目初始发布
|
|
108
|
-
- **CryptoManager** — ECC 加密套件(X25519 + ChaCha20-Poly1305 + Ed25519 签名)
|
|
109
|
-
- 邮件发送、性能监控、资源路径解析等工具模块
|
|
110
|
-
|
|
111
|
-
---
|
|
112
|
-
|
|
113
|
-
各版本标签:`v1.0.0` `v1.1.0` `v1.1.1` `v1.1.2` `2.0.1`
|
|
@@ -1,54 +0,0 @@
|
|
|
1
|
-
"""测试 send_email(基于 smtplib.SMTP_SSL)"""
|
|
2
|
-
|
|
3
|
-
from unittest.mock import patch
|
|
4
|
-
|
|
5
|
-
from raytoolsbox.utils.mailToPhone import send_email
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
def test_load_email_config_not_found():
|
|
9
|
-
"""找不到配置文件时应当返回 False。"""
|
|
10
|
-
with patch("raytoolsbox.utils.mailToPhone.Path.exists", return_value=False):
|
|
11
|
-
result = send_email()
|
|
12
|
-
assert result is False
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
def test_smtp_connection_failure():
|
|
16
|
-
"""SMTP 连接失败时应当返回 False。"""
|
|
17
|
-
with (
|
|
18
|
-
patch(
|
|
19
|
-
"raytoolsbox.utils.mailToPhone._load_email_config",
|
|
20
|
-
return_value={
|
|
21
|
-
"smtp_server": "smtp.qq.com",
|
|
22
|
-
"smtp_port": 465,
|
|
23
|
-
"from_addr": "test@qq.com",
|
|
24
|
-
"password": "wrong",
|
|
25
|
-
},
|
|
26
|
-
),
|
|
27
|
-
patch(
|
|
28
|
-
"raytoolsbox.utils.mailToPhone.smtplib.SMTP_SSL",
|
|
29
|
-
side_effect=OSError("模拟连接失败"),
|
|
30
|
-
),
|
|
31
|
-
):
|
|
32
|
-
result = send_email()
|
|
33
|
-
assert result is False
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
def test_smtp_login_failure():
|
|
37
|
-
"""SMTP 登录失败时应当返回 False。"""
|
|
38
|
-
mock_smtp = patch("raytoolsbox.utils.mailToPhone.smtplib.SMTP_SSL").start()
|
|
39
|
-
instance = mock_smtp.return_value
|
|
40
|
-
instance.login.side_effect = OSError("模拟登录失败")
|
|
41
|
-
|
|
42
|
-
with patch(
|
|
43
|
-
"raytoolsbox.utils.mailToPhone._load_email_config",
|
|
44
|
-
return_value={
|
|
45
|
-
"smtp_server": "smtp.qq.com",
|
|
46
|
-
"smtp_port": 465,
|
|
47
|
-
"from_addr": "test@qq.com",
|
|
48
|
-
"password": "wrong",
|
|
49
|
-
},
|
|
50
|
-
):
|
|
51
|
-
result = send_email()
|
|
52
|
-
assert result is False
|
|
53
|
-
|
|
54
|
-
patch.stopall()
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|