Metadata-Version: 2.5
Name: totp-sdk
Version: 0.2.1
Summary: TOTP 验证 SDK：本地验码、密钥与 otpauth 链接生成（RFC 6238 + 国密 SM3）
Project-URL: Repository, https://gitea.yunnanpost.cn:9003/xinyouhui/ynyz_totp
Project-URL: Issues, https://gitea.yunnanpost.cn:9003/xinyouhui/ynyz_totp/issues
License-Expression: MIT
License-File: LICENSE
Keywords: 2fa,gmssl,mfa,otp,rfc6238,sm3,totp
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Security
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.11
Requires-Dist: gmssl>=3.2.2
Description-Content-Type: text/markdown

# totp-sdk

TOTP（RFC 6238）验证 SDK：**业务系统本地验码，不发起任何网络请求**。附带密钥生成与 `otpauth://` 链接生成，支持国密 SM3。

[![PyPI](https://img.shields.io/pypi/v/totp-sdk.svg)](https://pypi.org/project/totp-sdk/)
[![Python](https://img.shields.io/pypi/pyversions/totp-sdk.svg)](https://pypi.org/project/totp-sdk/)

## 特性

- **零网络依赖**：secret 由业务系统自行持有，验码在进程内完成，可用性不受认证服务影响。
- **算法齐全**：`SHA1` / `SHA256` / `SHA512` / `SM3`（国密），默认 6 位、30 秒步长。
- **常量时间比较**：使用 `hmac.compare_digest`，不泄漏比对位置。
- **时间漂移容忍**：默认接受 `±1` 个步长（±30s），可配置。
- **进程内防重放**：`TotpLocal` 记录最近一次通过的计数器，同一验证码不可重复使用。
- **输入宽松**：secret 自动处理小写、空格与 base32 填充。

> 注意：本 SDK 只做 **TOTP 算法与验码**，不包含用户体系、二维码渲染、secret 加密存储等你应当自行掌控的部分。

## 安装

```bash
pip install totp-sdk
```

需要 Python 3.11+。`gmssl` 为默认依赖（SM3 实现，纯 Python）。若只用 SHA 系列，可忽略其开销。

## 快速开始

```python
from totp_sdk import TotpLocal, generate_secret_b32, provisioning_uri

# 1. 业务系统生成并加密保存 secret（建议 KMS / 信封加密）
secret = generate_secret_b32()          # 32 字符 base32，160 bit 熵 → 用户绑定

# 2. 生成 otpauth:// 链接，交给前端渲染二维码
uri = provisioning_uri(secret, "zhangsan", "OA")
# otpauth://totp/OA%3Azhangsan?secret=...&issuer=OA&algorithm=SHA1&digits=6&period=30

# 3. 验码
t = TotpLocal(secret)                   # 默认 SHA1 / 6 位 / 30s / drift=1
t.verify("123456")                      # True / False，含防重放
```

国密场景只需切换算法，其余不变：

```python
t = TotpLocal(secret, alg="SM3")
uri = provisioning_uri(secret, "zhangsan", "OA", alg="SM3")
```

## 三种集成方式

| 场景 | 用法 |
| --- | --- |
| 只验用户的码 | `TotpLocal(secret).verify(code)` |
| 只算某时刻的码（对账/调试/服务端校验客户端） | `totp_at(key, timestamp, ...)` |
| 对接国家标准/自研 App | `provisioning_uri(...)` + 自定义算法参数 |

## API

### 类：`TotpLocal`

```python
TotpLocal(secret_b32: str, *, period: int = 30, digits: int = 6,
          alg: str = "SHA1", drift: int = 1)
```

| 成员 | 说明 |
| --- | --- |
| `verify(code, *, now=None) -> bool` | 验码。命中后记录计数器，重复使用返回 `False`（防重放）。`now` 可注入时间戳便于测试。 |
| `now() -> str` | 当前时刻应有的一次性密码（用于测试/对账）。 |
| `key` / `period` / `digits` / `alg` / `drift` | 生效参数，`alg` 已归一化为大写。 |

构造时算法不受支持会抛 `ValueError`。

### 函数

| 函数 | 说明 |
| --- | --- |
| `generate_secret_b32(length: int = 20) -> str` | 用 `secrets.token_bytes(length)` 生成 base32 密钥，默认 160 bit。 |
| `normalize_secret(secret: str) -> bytes` | 归一化 base32 密钥为原始字节，容忍大小写、空格与缺失填充。 |
| `hotp(key: bytes, counter: int, digits: int = 6, alg: str = "SHA1") -> str` | RFC 4226 HOTP。 |
| `totp_at(key: bytes, timestamp: int, period: int = 30, digits: int = 6, alg: str = "SHA1") -> str` | 指定时间戳的 TOTP。 |
| `verify_totp(code, key, *, period=30, digits=6, alg="SHA1", drift=1, now=None) -> int \| None` | 验码，返回命中的偏移步数（`-drift..drift`），失败返回 `None`；不含防重放。 |
| `provisioning_uri(secret_b32, account, issuer, digits=6, period=30, alg="SHA1") -> str` | 生成 `otpauth://totp` 链接（二维码内容），label 形如 `issuer:account`。 |
| `SUPPORTED_ALGS` | `("SHA1", "SHA256", "SHA512", "SM3")`。 |

## 兼容性

RFC 6238 附录 B 测试向量（8 位验证码）已全部通过：

| 时间戳 | SHA1 | SHA256 | SHA512 |
| --- | --- | --- | --- |
| 59 | `94287082` | `46119246` | `90693936` |
| 1111111109 | `07081804` | `68084774` | `25091201` |
| 1234567890 | `89005924` | `91819424` | `93441116` |

算法可用性：

| 算法 | 本 SDK | 主流验证器 App |
| --- | --- | --- |
| `SHA1` | 支持 | 全部支持 |
| `SHA256` / `SHA512` | 支持 | 部分支持（视 App 版本） |
| `SM3` | 支持 | 基本不支持，需自研 App |

`algorithm=SM3` 不在 RFC 中，属于私有扩展：链接里的参数会被不认识的 App 忽略并回落到 SHA1，导致验码必然失败。**使用 SM3 前请确认客户端确实实现了 HMAC-SM3。**

## 安全建议

1. **secret 按密码等级保护**：加密存储（KMS / 信封加密），不要写日志、不要进前端除二维码之外的下发链路。
2. **防重放只在单实例内**：`TotpLocal._last_used` 是进程内状态。多进程 / 多副本部署时，请把最近一次通过的计数器落库（Redis/DB）并做原子比较，否则同一码可在不同副本各用一次。
3. **时间同步**：服务端与客户端时钟需在漂移窗口内。`drift` 不要随意放大，窗口越宽可爆破的码越多。
4. **限流**：手工输入通道必须限次（如每账号 5 次/分钟），6 位码在宽窗口下并非不可穷举。
5. **码只在服务端校验**：前端展示的二维码只含 secret 与参数，不参与校验。

多副本防重放的落库示意：

```python
last = store.get(user_id)                 # 上次通过的计数器
offset = verify_totp(code, key, ...)      # 只验算法
counter = now // period + offset
if offset is not None and (last is None or counter > last):
    store.set_if_greater(user_id, counter)  # 原子 CAS
```

## 不带网络的 SDK 模式 vs 在线校验

| | 本 SDK | 在线校验服务 |
| --- | --- | --- |
| 依赖 | 仅事件循环内一次 HMAC | 网络 + 对端可用性 |
| secret 位置 | 业务系统自有存储 | 对端 |
| 扩展 | 随业务进程线性扩展 | 受对端 QPS / 配额限制 |
| 一致性 | 每次都要自己处理重放与并发 | 集中处理 |

## 开发

```bash
uv sync                                    # 安装依赖（含 dev 组）
uv build                                   # 产出 dist/*.whl 与 dist/*.tar.gz
uv run twine check dist/*                  # 校验 README 与元数据
```

发布前请撤销/轮换历史 token，改用环境变量注入：

```bash
export TWINE_USERNAME=__token__
export TWINE_PASSWORD=pypi-xxxxxxxx        # 不要写进仓库
uv run twine upload dist/*
```

## 许可证

MIT，见 [LICENSE](https://gitea.yunnanpost.cn:9003/xinyouhui/ynyz_totp/src/branch/main/sdk/LICENSE)。
