Files
martin a6ed67d841 fix: 完成 P3 细节优化项
依据《代码分析结果.md》P3 章节,逐条修复 20 项细节问题:

正确性修复:
- P3-1 锁定剩余分钟改用 math.Ceil,避免「0.9 分钟」显示为「0 分钟」
- P3-12 移除 CheckAndUpgradeLevel 中恒真的 hasUpdate 标志
- P3-14 移除 CheckTrialExpiry 中恒真表达式(count > 0 || true)调试残留,改用 RowsAffected
- P3-2 成员不存在统一返回 NewNotFoundError(404),与其它方法语义一致

安全加固:
- P3-6 X-Request-Id 加格式校验 ^[A-Za-z0-9-]{1,64}$,防日志注入
- P3-7 新增公共 EscapeLikePattern,转义 admin LIKE 搜索的 %/_ 通配符
- P3-8 Encrypt 输出加 v1: 版本前缀,Decrypt 兼容无前缀历史密文
- P3-9 turnstile 响应体读取加 64KB 上限,防内存耗尽
- P3-11 backup codes 熵由 48-bit 提升到 64-bit
- P3-15 recordAudit 对 multipart/二进制体跳过 Unmarshal 与原文落库
- P3-17 错误日志按 Content-Type 跳过 multipart/二进制体读取
- P3-16 HandleRealtime 加 panic recover 与连接生命周期日志

可维护性/一致性:
- P3-3 oauth.go 时间格式统一为 time.RFC3339
- P3-5 MsgSuccess 统一为 ok,response.go 改用常量引用
- P3-4 错误码分段策略加注释,说明空洞与跳跃的成因
- P3-13 ModelMultiplier 占位语义加注释(计费公式设计位 + 快照列)
- P3-19 抽取 registerCronJobs,主启动流程清爽

重构:
- P3-18 删除死代码 BuildBillingSummary/SummaryParams(仅测试引用),保留共用 helper
- P3-20 抽取 relay.InvalidateMemberModelScopeCache 单一失效入口,
  消除三处 member_model 前缀字面量重复(原为有意跨包失效,原建议改名会破坏)

经核实保留 + 文档化:
- P3-10 TOTP 暂保留 SHA-1:totp.Validate 硬编码 SHA-1 且存储不保存算法元信息,
  直接切 SHA-256 会导致校验恒失败,需配合 schema 改动,超出 P3 范围
2026-07-26 12:16:33 +08:00

141 lines
3.9 KiB
Go

package crypto
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"encoding/hex"
"errors"
"fmt"
"io"
"strings"
)
var (
ErrInvalidCiphertext = errors.New("invalid ciphertext")
ErrInvalidKeyLength = errors.New("key must be 32 bytes for AES-256")
)
// versionPrefix 是当前加密格式的版本前缀。写入密文以便后续密钥/算法轮换:
// 旧数据(无前缀)按 v1 解密,新数据带 "v1:" 前缀,未来引入 v2 时可平滑迁移。
const versionPrefix = "v1:"
// Encrypt encrypts plaintext using AES-256-GCM.
// Returns "v1:" + base64-encoded ciphertext (nonce prepended).
func Encrypt(key, plaintext []byte) (string, error) {
if len(key) != 32 {
return "", ErrInvalidKeyLength
}
block, err := aes.NewCipher(key)
if err != nil {
return "", fmt.Errorf("create cipher: %w", err)
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return "", fmt.Errorf("create gcm: %w", err)
}
nonce := make([]byte, gcm.NonceSize())
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
return "", fmt.Errorf("generate nonce: %w", err)
}
ciphertext := gcm.Seal(nonce, nonce, plaintext, nil)
return versionPrefix + base64.StdEncoding.EncodeToString(ciphertext), nil
}
// Decrypt decrypts base64-encoded AES-256-GCM ciphertext.
// 兼容无前缀的历史密文(按 v1 处理)与带 "v1:" 前缀的新密文。
func Decrypt(key []byte, encoded string) ([]byte, error) {
if len(key) != 32 {
return nil, ErrInvalidKeyLength
}
// 剥离版本前缀(若有)。无前缀的历史密文按 v1 处理,保证存量数据可解。
payload := encoded
if strings.HasPrefix(encoded, versionPrefix) {
payload = strings.TrimPrefix(encoded, versionPrefix)
}
ciphertext, err := base64.StdEncoding.DecodeString(payload)
if err != nil {
return nil, fmt.Errorf("decode base64: %w", err)
}
block, err := aes.NewCipher(key)
if err != nil {
return nil, fmt.Errorf("create cipher: %w", err)
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, fmt.Errorf("create gcm: %w", err)
}
nonceSize := gcm.NonceSize()
if len(ciphertext) < nonceSize {
return nil, ErrInvalidCiphertext
}
nonce, ciphertext := ciphertext[:nonceSize], ciphertext[nonceSize:]
plaintext, err := gcm.Open(nil, nonce, ciphertext, nil)
if err != nil {
return nil, fmt.Errorf("decrypt: %w", err)
}
return plaintext, nil
}
// EncryptString is a convenience wrapper for string input/output.
func EncryptString(key []byte, plaintext string) (string, error) {
return Encrypt(key, []byte(plaintext))
}
// DecryptString is a convenience wrapper for string input/output.
func DecryptString(key []byte, encoded string) (string, error) {
plain, err := Decrypt(key, encoded)
if err != nil {
return "", err
}
return string(plain), nil
}
// GetEncryptionKey decodes and validates a hex-encoded AES-256 key.
// Returns an error instead of panicking, so callers can validate at startup.
func GetEncryptionKey(hexKey string) ([]byte, error) {
key, err := hex.DecodeString(hexKey)
if err != nil {
return nil, fmt.Errorf("invalid encryption key hex: %w", err)
}
if len(key) != 32 {
return nil, fmt.Errorf("%w: got %d", ErrInvalidKeyLength, len(key))
}
return key, nil
}
// MustGetEncryptionKey returns the encryption key from a hex-encoded string.
// Panics if the key is invalid. Prefer validating the key at startup (see
// GetEncryptionKey) so this never panics on a live request path.
func MustGetEncryptionKey(hexKey string) []byte {
key, err := GetEncryptionKey(hexKey)
if err != nil {
panic(err.Error())
}
return key
}
// HashPassword hashes a password using bcrypt.
// This is a convenience wrapper to keep crypto utilities together.
func HashPassword(password string) (string, error) {
// Use Go's standard library bcrypt
return hashPasswordBcrypt(password)
}
// VerifyPassword verifies a password against a bcrypt hash.
func VerifyPassword(password, hash string) bool {
return verifyPasswordBcrypt(password, hash)
}