yimo-kit 0.1.0__py3-none-any.whl

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.
Files changed (70) hide show
  1. yimo/__init__.py +26 -0
  2. yimo/kit/__init__.py +98 -0
  3. yimo/kit/ai/__init__.py +110 -0
  4. yimo/kit/ai/_internal/__init__.py +27 -0
  5. yimo/kit/ai/_internal/failover.py +535 -0
  6. yimo/kit/ai/_internal/pool.py +526 -0
  7. yimo/kit/ai/_internal/rerank_transport.py +137 -0
  8. yimo/kit/ai/_internal/retry_after.py +51 -0
  9. yimo/kit/ai/_internal/sdk_client.py +463 -0
  10. yimo/kit/ai/_internal/service_base.py +115 -0
  11. yimo/kit/ai/_internal/types.py +28 -0
  12. yimo/kit/ai/agent/__init__.py +127 -0
  13. yimo/kit/ai/agent/approval.py +66 -0
  14. yimo/kit/ai/agent/errors.py +128 -0
  15. yimo/kit/ai/agent/loop.py +643 -0
  16. yimo/kit/ai/agent/mcp.py +278 -0
  17. yimo/kit/ai/agent/registry.py +203 -0
  18. yimo/kit/ai/agent/session.py +150 -0
  19. yimo/kit/ai/agent/skill.py +370 -0
  20. yimo/kit/ai/agent/types.py +161 -0
  21. yimo/kit/ai/chat_service.py +724 -0
  22. yimo/kit/ai/decision/__init__.py +57 -0
  23. yimo/kit/ai/decision/decima.py +853 -0
  24. yimo/kit/ai/decision/laya.py +552 -0
  25. yimo/kit/ai/embedding_service.py +198 -0
  26. yimo/kit/ai/exceptions.py +109 -0
  27. yimo/kit/ai/image_service.py +84 -0
  28. yimo/kit/ai/messages.py +105 -0
  29. yimo/kit/ai/model_builder.py +121 -0
  30. yimo/kit/ai/model_client.py +62 -0
  31. yimo/kit/ai/profiles.py +577 -0
  32. yimo/kit/ai/rerank_service.py +136 -0
  33. yimo/kit/ai/runner.py +1127 -0
  34. yimo/kit/common_kit.py +221 -0
  35. yimo/kit/config/__init__.py +44 -0
  36. yimo/kit/config/kit_config.py +210 -0
  37. yimo/kit/config/log_config.py +171 -0
  38. yimo/kit/crawl/__init__.py +71 -0
  39. yimo/kit/crawl/article_io.py +325 -0
  40. yimo/kit/crawl/article_models.py +172 -0
  41. yimo/kit/crawl/deepseek_kit.py +673 -0
  42. yimo/kit/crawl/web_article_kit.py +638 -0
  43. yimo/kit/crawl/wx_article_kit.py +692 -0
  44. yimo/kit/db/__init__.py +101 -0
  45. yimo/kit/db/audit.py +625 -0
  46. yimo/kit/db/base_db_kit.py +1265 -0
  47. yimo/kit/db/crud.py +423 -0
  48. yimo/kit/db/engine.py +235 -0
  49. yimo/kit/db/exceptions.py +45 -0
  50. yimo/kit/db/models/__init__.py +33 -0
  51. yimo/kit/db/models/base.py +56 -0
  52. yimo/kit/db/mysql_kit.py +348 -0
  53. yimo/kit/db/pg_kit.py +442 -0
  54. yimo/kit/db/query.py +338 -0
  55. yimo/kit/db/session.py +85 -0
  56. yimo/kit/db/sqlite_kit.py +462 -0
  57. yimo/kit/db/transaction.py +109 -0
  58. yimo/kit/docs/__init__.py +34 -0
  59. yimo/kit/docs/anydoc_kit.py +490 -0
  60. yimo/kit/docs/docx_kit.py +895 -0
  61. yimo/kit/docs/md2doc_kit.py +1801 -0
  62. yimo/kit/docs/mineru_kit.py +1497 -0
  63. yimo/kit/docs/rc_docparser_kit.py +654 -0
  64. yimo/kit/file_kit.py +518 -0
  65. yimo/kit/license_kit.py +533 -0
  66. yimo/kit/redis_kit.py +392 -0
  67. yimo_kit-0.1.0.dist-info/METADATA +1673 -0
  68. yimo_kit-0.1.0.dist-info/RECORD +70 -0
  69. yimo_kit-0.1.0.dist-info/WHEEL +4 -0
  70. yimo_kit-0.1.0.dist-info/licenses/LICENSE +201 -0
@@ -0,0 +1,533 @@
1
+ """
2
+ Copyright (c) 2021-2026 溢墨修心(Yimo). All Rights Reserved.
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+
16
+ Project: yimo
17
+ Author: 溢墨修心(Yimo)
18
+ """
19
+
20
+ # date: 2026-10-16
21
+ """license 授权工具类:机器指纹 + 离线签名授权文件(Ed25519)
22
+
23
+ 面向单机分发场景的轻量授权体系(防君子定位):应用以打包 exe 形式离线分发,
24
+ 无远端授权服务。工作流:
25
+
26
+ 1. 客户机 `LicenseKit.export_fingerprint_file()` 导出 `.fp` 指纹文件;
27
+ 2. 签发方 `LicenseKit.parse_fingerprint_file()` 解析,填入 `LicensePayload`
28
+ 后 `LicenseKit.sign()` 生成 `.lic` 授权文件回签;
29
+ 3. 客户机 `LicenseVerifier.verify()` 验签 + 绑定校验(product / 机器码 / 有效期)。
30
+
31
+ 安全边界(务必知悉):
32
+
33
+ - 非对称体系安全性**仅依赖私钥保密**;本模块代码(含 `sign`)公开可读无碍;
34
+ - 离线体系无法吊销永久授权;订阅场景靠 `expires_at` 到期不续签实现"软吊销";
35
+ - `expires_at` 依赖系统时钟,回拨可延长——防君子定位下接受,不做时钟防护;
36
+ - 指纹 = MachineGuid + 系统盘卷序列号组合短码:VM 克隆镜像会复制指纹,
37
+ 重装系统需重新授权;
38
+ - 私钥丢失 = 全部已发授权作废,务必备份(换钥需重发全部授权)。
39
+
40
+ 时间约定:payload 的时间字段一律 **aware UTC**(naive 直接拒绝),
41
+ 规范化 JSON 序列化后签名,杜绝字段顺序 / 空白差异导致验签漂移。
42
+
43
+ 用法:
44
+ from yimo.kit.license_kit import LicenseKit, LicensePayload, LicenseVerifier
45
+
46
+ private_pem, public_pem = LicenseKit.generate_keypair()
47
+ payload = LicensePayload(product="myapp", machine_code="0123456789abcdef",
48
+ issued_at=datetime.now(timezone.utc),
49
+ expires_at=None)
50
+ lic_text = LicenseKit.sign(payload, private_pem)
51
+
52
+ verifier = LicenseVerifier(public_pem, Path("license.lic"))
53
+ info = verifier.verify(product="myapp", machine_code="0123456789abcdef")
54
+
55
+ 形态说明:0.4.2 为模块级函数,0.4.3 起收进静态工具类 `LicenseKit`
56
+ (与 FileKit / LayaKit 等其它 kit 形态一致);`LicenseVerifier` 因持有
57
+ 公钥缓存与验签上下文实例状态,保持独立类。
58
+ """
59
+
60
+ import base64
61
+ import hashlib
62
+ import json
63
+ import re
64
+ import sys
65
+ from datetime import datetime, timezone
66
+ from pathlib import Path
67
+
68
+ from cryptography.exceptions import InvalidSignature
69
+ from cryptography.hazmat.primitives import serialization
70
+ from cryptography.hazmat.primitives.asymmetric.ed25519 import (
71
+ Ed25519PrivateKey,
72
+ Ed25519PublicKey,
73
+ )
74
+ from pydantic import BaseModel, field_validator
75
+
76
+ from yimo.kit.config.log_config import get_default_logger
77
+
78
+ logger = get_default_logger(__name__)
79
+
80
+ # 指纹文件格式版本(结构变更时递增;parse 只接受 <= 当前版本)
81
+ FINGERPRINT_FORMAT_VERSION = 1
82
+ # license 载荷格式版本(载荷结构变更时递增;verify 只接受当前版本)
83
+ LICENSE_PAYLOAD_VERSION = 1
84
+ # 机器码短码长度(SHA256 截断,16 hex = 64bit,单机场景碰撞可忽略)
85
+ MACHINE_CODE_LENGTH = 16
86
+ # 指纹文件标识(parse 时强校验,防止拿错文件)
87
+ # 说明:该值是**落盘格式标识**,不是品牌文案。历史版本写入的指纹文件为
88
+ # "sdpy-fingerprint",改名会导致旧机器指纹被判为非法,故按兼容性保留。
89
+ _FINGERPRINT_KIND = "sdpy-fingerprint"
90
+
91
+ _MACHINE_GUID_KEY_PATH = r"SOFTWARE\Microsoft\Cryptography"
92
+ _MACHINE_GUID_VALUE_NAME = "MachineGuid"
93
+
94
+ _HEX16_RE = re.compile(r"^[0-9a-f]{16}$")
95
+
96
+
97
+ # ---------------------------------------------------------------------------
98
+ # 异常体系(独立基线,不挂 DBError——license 非 db 域)
99
+ # ---------------------------------------------------------------------------
100
+
101
+
102
+ class LicenseError(Exception):
103
+ """license 域异常基类"""
104
+
105
+
106
+ class LicenseUnsupportedPlatformError(LicenseError):
107
+ """当前平台不支持指纹采集(指纹实现仅覆盖 Windows)"""
108
+
109
+
110
+ class LicenseFormatError(LicenseError):
111
+ """文件损坏 / JSON 结构不合法 / 格式版本不识别 / 密钥类型不符"""
112
+
113
+
114
+ class LicenseSignatureError(LicenseError):
115
+ """Ed25519 签名验证失败(文件被篡改或公钥不匹配)"""
116
+
117
+
118
+ class LicenseProductMismatchError(LicenseError):
119
+ """product 与验签方期望值不符(防跨项目重放)"""
120
+
121
+
122
+ class LicenseMachineMismatchError(LicenseError):
123
+ """machine_code 与本机指纹不符(授权被拷贝到其他机器)"""
124
+
125
+
126
+ class LicenseExpiredError(LicenseError):
127
+ """授权已过期(expires_at 早于当前时间)"""
128
+
129
+
130
+ # ---------------------------------------------------------------------------
131
+ # 机器指纹私有实现(Windows 专属;winreg/ctypes 延迟导入保证模块任意平台可 import)
132
+ # ---------------------------------------------------------------------------
133
+
134
+
135
+ def _read_machine_guid() -> str:
136
+ """读注册表 MachineGuid(重装系统才变化的主机标识)"""
137
+ import winreg
138
+
139
+ with winreg.OpenKey(
140
+ winreg.HKEY_LOCAL_MACHINE, _MACHINE_GUID_KEY_PATH
141
+ ) as key:
142
+ value, _ = winreg.QueryValueEx(key, _MACHINE_GUID_VALUE_NAME)
143
+ guid = str(value).strip()
144
+ if not guid:
145
+ raise LicenseFormatError("注册表 MachineGuid 为空")
146
+ return guid
147
+
148
+
149
+ def _read_volume_serial() -> str:
150
+ """读系统盘卷序列号(GetVolumeInformationW,十进制字符串)"""
151
+ import ctypes.wintypes
152
+ import os
153
+
154
+ drive = os.environ.get("SystemDrive", "C:") + "\\"
155
+ serial = ctypes.wintypes.DWORD(0)
156
+ # GetVolumeInformationW 只需要根路径与序列号出参,其余参数可传占位
157
+ ok = ctypes.windll.kernel32.GetVolumeInformationW(
158
+ ctypes.c_wchar_p(drive),
159
+ None,
160
+ 0,
161
+ ctypes.byref(serial),
162
+ None,
163
+ None,
164
+ None,
165
+ 0,
166
+ )
167
+ if not ok or serial.value == 0:
168
+ raise LicenseFormatError(f"读取系统盘卷序列号失败:{drive}")
169
+ return str(serial.value)
170
+
171
+
172
+ def _collect_components() -> tuple[str, str]:
173
+ """采集原始指纹组件,返回 (machine_guid, volume_serial);非 Windows 抛错"""
174
+ if sys.platform != "win32":
175
+ raise LicenseUnsupportedPlatformError(
176
+ f"机器指纹采集仅支持 Windows,当前平台:{sys.platform}"
177
+ )
178
+ return _read_machine_guid(), _read_volume_serial()
179
+
180
+
181
+ def _machine_code_of(machine_guid: str, volume_serial: str) -> str:
182
+ """由原始组件计算机器码短码(签发与导出共用,避免两处公式漂移)"""
183
+ digest = hashlib.sha256(f"{machine_guid}|{volume_serial}".encode("utf-8"))
184
+ return digest.hexdigest()[:MACHINE_CODE_LENGTH]
185
+
186
+
187
+ # ---------------------------------------------------------------------------
188
+ # 载荷(签发与验签共用)
189
+ # ---------------------------------------------------------------------------
190
+
191
+
192
+ class LicensePayload(BaseModel):
193
+ """授权载荷(license 文件中承载的业务信息)"""
194
+
195
+ version: int = LICENSE_PAYLOAD_VERSION
196
+ product: str # 应用标识,防跨项目重放
197
+ machine_code: str # 授权绑定的机器码(16 hex)
198
+ tier: str = "full" # 档位,语义由应用侧定义
199
+ customer_id: str | None = None # 可选,便于售后检索
200
+ issued_at: datetime # 签发时间(aware UTC)
201
+ expires_at: datetime | None = None # 过期时间;None = 买断永久
202
+
203
+ @field_validator("version")
204
+ @classmethod
205
+ def _check_version(cls, value: int) -> int:
206
+ if value != LICENSE_PAYLOAD_VERSION:
207
+ raise ValueError(f"不支持的载荷版本:{value}")
208
+ return value
209
+
210
+ @field_validator("product")
211
+ @classmethod
212
+ def _check_product(cls, value: str) -> str:
213
+ if not value.strip():
214
+ raise ValueError("product 不能为空")
215
+ return value
216
+
217
+ @field_validator("machine_code")
218
+ @classmethod
219
+ def _check_machine_code(cls, value: str) -> str:
220
+ normalized = value.strip().lower()
221
+ if not _HEX16_RE.fullmatch(normalized):
222
+ raise ValueError("machine_code 必须为 16 位十六进制短码")
223
+ return normalized
224
+
225
+ @field_validator("issued_at", "expires_at")
226
+ @classmethod
227
+ def _require_aware_utc(cls, value: datetime | None) -> datetime | None:
228
+ if value is None:
229
+ return None
230
+ if value.tzinfo is None:
231
+ raise ValueError("时间字段必须为 aware datetime(拒绝 naive)")
232
+ return value.astimezone(timezone.utc)
233
+
234
+
235
+ def _canonical_bytes(payload: dict) -> bytes:
236
+ """规范化 JSON 字节:键排序 + 紧凑分隔符 + UTF-8(签发/验签共用)"""
237
+ return json.dumps(
238
+ payload, sort_keys=True, separators=(",", ":"), ensure_ascii=False
239
+ ).encode("utf-8")
240
+
241
+
242
+ # ---------------------------------------------------------------------------
243
+ # 静态工具类(与其它 kit 形态一致;格式唯一事实源——签发与验签共用本模块实现)
244
+ # ---------------------------------------------------------------------------
245
+
246
+
247
+ class LicenseKit:
248
+ """license 授权静态工具类:指纹、密钥、签发"""
249
+
250
+ @staticmethod
251
+ def get_machine_code() -> str:
252
+ """计算本机机器码:组合指纹 SHA256 短码(16 hex 小写)
253
+
254
+ Returns:
255
+ str: 16 位十六进制机器码
256
+
257
+ Raises:
258
+ LicenseUnsupportedPlatformError: 非 Windows 平台
259
+ LicenseFormatError: 指纹组件读取失败
260
+ """
261
+ machine_guid, volume_serial = _collect_components()
262
+ return _machine_code_of(machine_guid, volume_serial)
263
+
264
+ @staticmethod
265
+ def export_fingerprint_file(path: Path) -> Path:
266
+ """导出指纹文件(.fp):机器码 + 原始组件 + 导出时间
267
+
268
+ 原始组件仅用于报障诊断(作者侧可看出哪个组件不匹配),验签只比短码。
269
+
270
+ Args:
271
+ path: 指纹文件输出路径
272
+
273
+ Returns:
274
+ Path: 实际写入的文件路径
275
+
276
+ Raises:
277
+ LicenseUnsupportedPlatformError: 非 Windows 平台
278
+ LicenseFormatError: 指纹组件读取失败
279
+ """
280
+ machine_guid, volume_serial = _collect_components()
281
+ document = {
282
+ "kind": _FINGERPRINT_KIND,
283
+ "format_version": FINGERPRINT_FORMAT_VERSION,
284
+ "machine_code": _machine_code_of(machine_guid, volume_serial),
285
+ "components": {
286
+ "machine_guid": machine_guid,
287
+ "volume_serial": volume_serial,
288
+ },
289
+ "exported_at": datetime.now(timezone.utc).isoformat(),
290
+ }
291
+ target = Path(path)
292
+ target.parent.mkdir(parents=True, exist_ok=True)
293
+ target.write_text(
294
+ json.dumps(document, ensure_ascii=False, indent=2), encoding="utf-8"
295
+ )
296
+ logger.info("指纹文件已导出:%s(机器码 %s)", target, document["machine_code"])
297
+ return target
298
+
299
+ @staticmethod
300
+ def parse_fingerprint_file(path: Path) -> str:
301
+ """解析指纹文件,返回机器码(签发侧使用;跨机器无法重算原文,只校验结构)
302
+
303
+ Args:
304
+ path: 指纹文件路径
305
+
306
+ Returns:
307
+ str: 16 位十六进制机器码
308
+
309
+ Raises:
310
+ LicenseFormatError: 文件缺失 / JSON 损坏 / 标识或版本不符 / 机器码格式非法
311
+ """
312
+ source = Path(path)
313
+ if not source.is_file():
314
+ raise LicenseFormatError(f"指纹文件不存在:{source}")
315
+ try:
316
+ document = json.loads(source.read_text(encoding="utf-8"))
317
+ except (OSError, json.JSONDecodeError) as exc:
318
+ raise LicenseFormatError(f"指纹文件读取或解析失败:{exc}") from exc
319
+ if not isinstance(document, dict):
320
+ raise LicenseFormatError("指纹文件结构不合法(顶层应为 JSON 对象)")
321
+ if document.get("kind") != _FINGERPRINT_KIND:
322
+ raise LicenseFormatError("指纹文件标识不符(kind)")
323
+ version = document.get("format_version")
324
+ if not isinstance(version, int) or version > FINGERPRINT_FORMAT_VERSION:
325
+ raise LicenseFormatError(f"指纹文件格式版本不识别:{version!r}")
326
+ machine_code = document.get("machine_code")
327
+ if not isinstance(machine_code, str) or not _HEX16_RE.fullmatch(machine_code):
328
+ raise LicenseFormatError("指纹文件缺少合法机器码(16 hex)")
329
+ return machine_code
330
+
331
+ @staticmethod
332
+ def generate_keypair() -> tuple[str, str]:
333
+ """生成 Ed25519 密钥对(一次性初始化用)
334
+
335
+ Returns:
336
+ tuple[str, str]: (private_pem, public_pem),均为 PEM 文本;
337
+ 私钥务必本机妥善保管(丢失 = 已发授权全部作废)
338
+ """
339
+ private_key = Ed25519PrivateKey.generate()
340
+ private_pem = private_key.private_bytes(
341
+ encoding=serialization.Encoding.PEM,
342
+ format=serialization.PrivateFormat.PKCS8,
343
+ encryption_algorithm=serialization.NoEncryption(),
344
+ ).decode("utf-8")
345
+ public_pem = private_key.public_key().public_bytes(
346
+ encoding=serialization.Encoding.PEM,
347
+ format=serialization.PublicFormat.SubjectPublicKeyInfo,
348
+ ).decode("utf-8")
349
+ return private_pem, public_pem
350
+
351
+ @staticmethod
352
+ def sign(payload: LicensePayload, private_key_pem: str) -> str:
353
+ """对载荷签名,返回 license 文件内容(JSON 文本,即 .lic)
354
+
355
+ Args:
356
+ payload: 授权载荷
357
+ private_key_pem: Ed25519 私钥 PEM(PKCS8)
358
+
359
+ Returns:
360
+ str: license 文件内容 `{"payload": {...}, "signature": "<b64>"}`
361
+
362
+ Raises:
363
+ LicenseFormatError: 私钥解析失败或类型不是 Ed25519
364
+ """
365
+ try:
366
+ private_key = serialization.load_pem_private_key(
367
+ private_key_pem.encode("utf-8"), password=None
368
+ )
369
+ except (ValueError, TypeError) as exc:
370
+ raise LicenseFormatError(f"私钥 PEM 解析失败:{exc}") from exc
371
+ if not isinstance(private_key, Ed25519PrivateKey):
372
+ raise LicenseFormatError("私钥类型不是 Ed25519")
373
+ payload_dict = payload.model_dump(mode="json")
374
+ signature = private_key.sign(_canonical_bytes(payload_dict))
375
+ document = {
376
+ "payload": payload_dict,
377
+ "signature": base64.b64encode(signature).decode("ascii"),
378
+ }
379
+ logger.info(
380
+ "license 已签发:product=%s machine_code=%s",
381
+ payload.product,
382
+ payload.machine_code,
383
+ )
384
+ return json.dumps(document, ensure_ascii=False, indent=2)
385
+
386
+
387
+ # ---------------------------------------------------------------------------
388
+ # 验签
389
+ # ---------------------------------------------------------------------------
390
+
391
+
392
+ class LicenseVerifier:
393
+ """license 文件验签器(应用启动/请求时校验授权)
394
+
395
+ 校验链:签名 → product 匹配 → machine_code 匹配 → 未过期;
396
+ 各环节失败抛对应 LicenseError 子类,应用侧可区分提示语。
397
+ """
398
+
399
+ def __init__(self, public_key_pem: str, license_path: Path) -> None:
400
+ """保存公钥与 license 路径(文件读取延迟到 verify 时)
401
+
402
+ Args:
403
+ public_key_pem: Ed25519 公钥 PEM(应用配置注入)
404
+ license_path: license 文件路径(应用侧显式给出,不做路径猜测)
405
+ """
406
+ self._public_key_pem = public_key_pem
407
+ self._license_path = Path(license_path)
408
+ self._public_key: Ed25519PublicKey | None = None
409
+ # 最近一次 verify 成功的上下文,供 reverify() 使用
410
+ self._verified_context: tuple[str, str] | None = None
411
+
412
+ def _load_public_key(self) -> Ed25519PublicKey:
413
+ """解析并缓存公钥;类型不符抛 LicenseFormatError"""
414
+ if self._public_key is None:
415
+ try:
416
+ key = serialization.load_pem_public_key(
417
+ self._public_key_pem.encode("utf-8")
418
+ )
419
+ except (ValueError, TypeError) as exc:
420
+ raise LicenseFormatError(f"公钥 PEM 解析失败:{exc}") from exc
421
+ if not isinstance(key, Ed25519PublicKey):
422
+ raise LicenseFormatError("公钥类型不是 Ed25519")
423
+ self._public_key = key
424
+ return self._public_key
425
+
426
+ def _load_document(self) -> tuple[dict, bytes]:
427
+ """读 license 文件并拆出 (payload dict, 签名字节)"""
428
+ if not self._license_path.is_file():
429
+ raise LicenseFormatError(f"license 文件不存在:{self._license_path}")
430
+ try:
431
+ document = json.loads(self._license_path.read_text(encoding="utf-8"))
432
+ except (OSError, json.JSONDecodeError) as exc:
433
+ raise LicenseFormatError(f"license 文件读取或解析失败:{exc}") from exc
434
+ if not isinstance(document, dict):
435
+ raise LicenseFormatError("license 文件结构不合法(顶层应为 JSON 对象)")
436
+ payload_dict = document.get("payload")
437
+ signature_text = document.get("signature")
438
+ if not isinstance(payload_dict, dict) or not isinstance(signature_text, str):
439
+ raise LicenseFormatError("license 文件缺少 payload 或 signature 字段")
440
+ try:
441
+ signature = base64.b64decode(signature_text, validate=True)
442
+ except (ValueError, TypeError) as exc:
443
+ raise LicenseFormatError(f"signature 不是合法 base64:{exc}") from exc
444
+ return payload_dict, signature
445
+
446
+ def verify(
447
+ self,
448
+ *,
449
+ product: str,
450
+ machine_code: str,
451
+ now: datetime | None = None,
452
+ ) -> LicensePayload:
453
+ """全量校验 license,返回载荷
454
+
455
+ Args:
456
+ product: 期望的应用标识
457
+ machine_code: 期望的机器码(本机 `LicenseKit.get_machine_code()` 结果)
458
+ now: 判定"当前时间";None 取 aware UTC 当前时刻;naive 按 UTC 处理
459
+
460
+ Returns:
461
+ LicensePayload: 校验通过的授权载荷
462
+
463
+ Raises:
464
+ LicenseFormatError: 文件缺失/损坏/版本不识别/字段非法
465
+ LicenseSignatureError: 签名验证失败
466
+ LicenseProductMismatchError: product 不匹配
467
+ LicenseMachineMismatchError: machine_code 不匹配
468
+ LicenseExpiredError: 已过期
469
+ """
470
+ check_time = now or datetime.now(timezone.utc)
471
+ if check_time.tzinfo is None:
472
+ check_time = check_time.replace(tzinfo=timezone.utc)
473
+ payload_dict, signature = self._load_document()
474
+ try:
475
+ self._load_public_key().verify(signature, _canonical_bytes(payload_dict))
476
+ except InvalidSignature as exc:
477
+ raise LicenseSignatureError("license 签名验证失败") from exc
478
+ payload = self._validated_payload(payload_dict)
479
+ if payload.product != product:
480
+ raise LicenseProductMismatchError(
481
+ f"product 不匹配:期望 {product!r},实际 {payload.product!r}"
482
+ )
483
+ expected_code = machine_code.strip().lower()
484
+ if payload.machine_code != expected_code:
485
+ raise LicenseMachineMismatchError(
486
+ f"机器码不匹配:期望 {expected_code!r},实际 {payload.machine_code!r}"
487
+ )
488
+ if payload.expires_at is not None and check_time > payload.expires_at:
489
+ raise LicenseExpiredError(
490
+ f"授权已于 {payload.expires_at.isoformat()} 过期"
491
+ )
492
+ self._verified_context = (product, expected_code)
493
+ logger.info("license 校验通过:product=%s tier=%s", payload.product, payload.tier)
494
+ return payload
495
+
496
+ def _validated_payload(self, payload_dict: dict) -> LicensePayload:
497
+ """载荷 dict → 模型校验(版本/字段/时间格式),失败归一为 LicenseFormatError"""
498
+ try:
499
+ return LicensePayload.model_validate(payload_dict)
500
+ except Exception as exc: # noqa: BLE001 - pydantic 校验错误统一归一
501
+ raise LicenseFormatError(f"license 载荷校验失败:{exc}") from exc
502
+
503
+ def file_signature(self) -> str:
504
+ """license 文件内容指纹:SHA256(文件字节)
505
+
506
+ 供应用侧运行中检测文件被替换(每请求比对,变化即调 `reverify()`)。
507
+ 只哈希内容、不含 mtime——mtime 在解压/拷贝场景随机变化,参与比对只会误触发。
508
+
509
+ Returns:
510
+ str: 十六进制 SHA256
511
+
512
+ Raises:
513
+ LicenseFormatError: 文件缺失或不可读
514
+ """
515
+ try:
516
+ content = self._license_path.read_bytes()
517
+ except OSError as exc:
518
+ raise LicenseFormatError(f"license 文件不可读:{exc}") from exc
519
+ return hashlib.sha256(content).hexdigest()
520
+
521
+ def reverify(self) -> LicensePayload:
522
+ """用最近一次成功 verify 的上下文重新全量校验(文件被换时相应失败)
523
+
524
+ Returns:
525
+ LicensePayload: 重新校验通过的授权载荷
526
+
527
+ Raises:
528
+ LicenseError: 尚未成功执行过 verify()
529
+ """
530
+ if self._verified_context is None:
531
+ raise LicenseError("尚未成功执行 verify(),无法 reverify")
532
+ product, machine_code = self._verified_context
533
+ return self.verify(product=product, machine_code=machine_code)