- readme §16 补 1.0.10-1.0.13 四条变更记录;§12.6 tag 表补 1.0.9-1.0.13 - readme §5 架构图更新为插件化结构(PLUGINS 注册表/四开关/四表) - readme §11 补 api-proxies.json 数据模型小节;§8 管理台表格补 API 代理行 - readme/CLAUDE.md 测试断言数对齐 262(102+160);三个 JSON 改四个 - CLAUDE.md LLM 落点表改 crates/plugin-llm 路径;发版补 git push 前置教训 - 清理全部前身实现引用(readme 三处、CLAUDE.md 性能章节、util.rs 注释) - PLUGIN_ARCHITECTURE.md 增补 1.0.13 sso 合流记录
356 lines
12 KiB
Rust
356 lines
12 KiB
Rust
//! 通用工具:时间 / 随机 / 摘要 / 口令哈希 / 常量时间比较 / 格式化 / 参数解码。
|
||
//!
|
||
//! 其中 `hash_password` 的算法**必须逐位一致**(口径沿用自重构前实现,
|
||
//! 存量 `users.json` 才能正常登录),
|
||
//! 否则旧的 `data/users.json` 里的口令哈希将全部失效。
|
||
|
||
use sha2::{Digest, Sha256};
|
||
|
||
use crate::config::HASH_ROUNDS;
|
||
|
||
// ===========================================================================
|
||
// 日志
|
||
// ===========================================================================
|
||
|
||
/// 写 nginx error log。
|
||
///
|
||
/// 形参顺序容易记错:`ngx_log_error_core(level, log, err, fmt, ...)`,
|
||
/// 其中 `err` 只在需要附带系统错误号时非 0。
|
||
pub fn log_at(level: usize, msg: &str) {
|
||
// SAFETY: 传入的 CString 在本调用期间存活;日志接口不持有其引用
|
||
unsafe {
|
||
let c = std::ffi::CString::new(msg).unwrap_or_default();
|
||
let lg = if nginx_sys::ngx_cycle.is_null() {
|
||
core::ptr::null_mut()
|
||
} else {
|
||
(*nginx_sys::ngx_cycle).log
|
||
};
|
||
nginx_sys::ngx_log_error_core(level, lg, 0, c"%s".as_ptr(), c.as_ptr());
|
||
}
|
||
}
|
||
|
||
pub fn log_err(msg: &str) {
|
||
log_at(nginx_sys::NGX_LOG_ERR as usize, msg);
|
||
}
|
||
|
||
pub fn log_warn(msg: &str) {
|
||
log_at(nginx_sys::NGX_LOG_WARN as usize, msg);
|
||
}
|
||
|
||
pub fn log_notice(msg: &str) {
|
||
log_at(nginx_sys::NGX_LOG_NOTICE as usize, msg);
|
||
}
|
||
|
||
// ===========================================================================
|
||
// 时间
|
||
// ===========================================================================
|
||
|
||
/// 当前 Unix 时间戳(秒)。
|
||
///
|
||
/// nginx 的 `ngx_time()` 是宏,bindgen 拿不到;直接走 libc 的 `time()`,
|
||
/// 在 Linux/macOS 上都由 vDSO 提供,代价与读一个全局变量相当。
|
||
#[inline]
|
||
pub fn now() -> i64 {
|
||
// SAFETY: time(NULL) 只读系统时钟,无副作用
|
||
unsafe { libc::time(core::ptr::null_mut()) as i64 }
|
||
}
|
||
|
||
/// `%Y-%m-%d %H:%M:%S`(本地时区,等价旧版 `os.date`);ts <= 0 返回 `-`
|
||
pub fn fmt_time(ts: i64) -> String {
|
||
if ts <= 0 {
|
||
return "-".to_owned();
|
||
}
|
||
// SAFETY: 传入有效指针;localtime_r 不返回静态数据,线程安全
|
||
unsafe {
|
||
let t = ts as libc::time_t;
|
||
let mut tm: libc::tm = core::mem::zeroed();
|
||
if libc::localtime_r(&t, &mut tm).is_null() {
|
||
return "-".to_owned();
|
||
}
|
||
let mut buf = [0 as libc::c_char; 40];
|
||
let fmt = c"%Y-%m-%d %H:%M:%S";
|
||
let n = libc::strftime(buf.as_mut_ptr(), buf.len(), fmt.as_ptr(), &tm);
|
||
if n == 0 {
|
||
return "-".to_owned();
|
||
}
|
||
core::ffi::CStr::from_ptr(buf.as_ptr()).to_string_lossy().into_owned()
|
||
}
|
||
}
|
||
|
||
/// `%m-%d`(本地时区)。趋势图 x 轴用——带上年份会让 14 天的轴标签又长又重复
|
||
pub fn fmt_day(ts: i64) -> String {
|
||
if ts <= 0 {
|
||
return "-".to_owned();
|
||
}
|
||
// SAFETY: 同 fmt_time
|
||
unsafe {
|
||
let t = ts as libc::time_t;
|
||
let mut tm: libc::tm = core::mem::zeroed();
|
||
if libc::localtime_r(&t, &mut tm).is_null() {
|
||
return "-".to_owned();
|
||
}
|
||
let mut buf = [0 as libc::c_char; 16];
|
||
let fmt = c"%m-%d";
|
||
let n = libc::strftime(buf.as_mut_ptr(), buf.len(), fmt.as_ptr(), &tm);
|
||
if n == 0 {
|
||
return "-".to_owned();
|
||
}
|
||
core::ffi::CStr::from_ptr(buf.as_ptr()).to_string_lossy().into_owned()
|
||
}
|
||
}
|
||
|
||
/// 本地时区的「日窗 id」(年份×1000 + 年内第几天),跨天自动翻窗。
|
||
///
|
||
/// 限流配额按**本地日**切(面向中国用户,即东八区自然日),不用 UTC——
|
||
/// UTC 的日界线在北京时间早上 8 点,「每日额度」会在半夜重置,反直觉。
|
||
pub fn day_id(ts: i64) -> i64 {
|
||
// SAFETY: localtime_r 只读时间戳并填充调用方的结构体
|
||
unsafe {
|
||
let t = ts as libc::time_t;
|
||
let mut tm: libc::tm = core::mem::zeroed();
|
||
if libc::localtime_r(&t, &mut tm).is_null() {
|
||
return ts.div_euclid(86400); // 兜底:退化成 UTC 日
|
||
}
|
||
tm.tm_year as i64 * 1000 + tm.tm_yday as i64
|
||
}
|
||
}
|
||
|
||
/// 剩余时长的中文描述(与旧版 `fmt_left` 输出一致)
|
||
pub fn fmt_left(seconds: i64) -> String {
|
||
if seconds <= 0 {
|
||
return "已过期".to_owned();
|
||
}
|
||
let h = seconds / 3600;
|
||
let m = (seconds % 3600) / 60;
|
||
let s = seconds % 60;
|
||
if h > 0 {
|
||
format!("{h} 小时 {m} 分")
|
||
} else if m > 0 {
|
||
format!("{m} 分 {s} 秒")
|
||
} else {
|
||
format!("{s} 秒")
|
||
}
|
||
}
|
||
|
||
// ===========================================================================
|
||
// 随机与十六进制
|
||
// ===========================================================================
|
||
|
||
pub fn to_hex(bytes: &[u8]) -> String {
|
||
const HEX: &[u8; 16] = b"0123456789abcdef";
|
||
let mut out = String::with_capacity(bytes.len() * 2);
|
||
for &b in bytes {
|
||
out.push(HEX[(b >> 4) as usize] as char);
|
||
out.push(HEX[(b & 0x0f) as usize] as char);
|
||
}
|
||
out
|
||
}
|
||
|
||
/// 密码学安全随机字节。取不到随机源时返回 None(调用方必须显式处理,
|
||
/// **不允许**退化成可预测的伪随机——那等于把 API Key 直接送给攻击者)。
|
||
fn rand_bytes(buf: &mut [u8]) -> Option<()> {
|
||
getrandom::getrandom(buf).ok()
|
||
}
|
||
|
||
/// `n` 字节随机数的 hex 表示(会话 token 等场景)
|
||
pub fn rand_hex(n: usize) -> String {
|
||
let mut b = vec![0u8; n];
|
||
if rand_bytes(&mut b).is_none() {
|
||
let mut seed = now() as u64 ^ 0x2545_f491_4f6c_dd1d;
|
||
for byte in b.iter_mut() {
|
||
// xorshift:随机源失效时的最后手段,至少不产出常量
|
||
seed ^= seed << 13;
|
||
seed ^= seed >> 7;
|
||
seed ^= seed << 17;
|
||
*byte = (seed & 0xff) as u8;
|
||
}
|
||
}
|
||
to_hex(&b)
|
||
}
|
||
|
||
/// 口令盐:16 字节 → 32 位 hex
|
||
pub fn gen_salt() -> String {
|
||
let mut b = [0u8; 16];
|
||
if rand_bytes(&mut b).is_none() {
|
||
// 极罕见:随机源不可用。此处不能 panic(会崩掉整个 worker),
|
||
// 退化为基于时间的混淆值并让上层记录失败。
|
||
let n = now() as u64 ^ 0x9e37_79b9_7f4a_7c15;
|
||
b[..8].copy_from_slice(&n.to_le_bytes());
|
||
b[8..].copy_from_slice(&n.rotate_left(17).to_le_bytes());
|
||
}
|
||
to_hex(&b)
|
||
}
|
||
|
||
/// 账号 API Key:`sk_` + 24 字节 → 48 位 hex
|
||
pub fn gen_key() -> String {
|
||
let mut b = [0u8; 24];
|
||
if rand_bytes(&mut b).is_none() {
|
||
let n = now() as u64;
|
||
for (i, chunk) in b.chunks_mut(8).enumerate() {
|
||
chunk.copy_from_slice(&n.rotate_left((i as u32) * 13).to_le_bytes());
|
||
}
|
||
}
|
||
format!("sk_{}", to_hex(&b))
|
||
}
|
||
|
||
/// 域名记录 id:`d_` + 6 字节 → 12 位 hex
|
||
pub fn gen_id() -> String {
|
||
let mut b = [0u8; 6];
|
||
if rand_bytes(&mut b).is_none() {
|
||
let n = now() as u32;
|
||
b[..4].copy_from_slice(&n.to_le_bytes());
|
||
b[4..].copy_from_slice(&(n ^ 0xa5a5).to_le_bytes()[..2]);
|
||
}
|
||
format!("d_{}", to_hex(&b))
|
||
}
|
||
|
||
/// `n` 位纯数字随机串(每位 0-9 等概率)。
|
||
///
|
||
/// 用**拒绝采样**而不是 `byte % 10`:256 不是 10 的倍数,直接取模会让 0-5
|
||
/// 比 6-9 各多出现约 0.4%(对子域名无害,但没理由留这个瑕疵)。
|
||
/// 只接受 `< 250` 的字节(250 = 25×10),落桶严格均匀。
|
||
///
|
||
/// 非安全场景(子域名后缀),但仍复用 `getrandom`——顺带拿到「随机源不可用」
|
||
/// 的统一退化路径,且随机源失效时绝不 panic。
|
||
pub fn rand_digits(n: usize) -> String {
|
||
let mut out = String::with_capacity(n);
|
||
let mut buf = [0u8; 32];
|
||
// 随机源不可用时退化为 xorshift(与 rand_hex 同款兜底),仍会终止
|
||
let mut seed = now() as u64 ^ 0x2545_f491_4f6c_dd1d;
|
||
while out.len() < n {
|
||
let take = (n - out.len()).min(buf.len());
|
||
let slice = &mut buf[..take];
|
||
let ok = rand_bytes(slice).is_some();
|
||
if !ok {
|
||
for byte in slice.iter_mut() {
|
||
seed ^= seed << 13;
|
||
seed ^= seed >> 7;
|
||
seed ^= seed << 17;
|
||
*byte = (seed & 0xff) as u8;
|
||
}
|
||
}
|
||
for &b in slice.iter() {
|
||
if b < 250 && out.len() < n {
|
||
out.push((b'0' + (b % 10)) as char);
|
||
}
|
||
}
|
||
}
|
||
out
|
||
}
|
||
|
||
// ===========================================================================
|
||
// 摘要与口令
|
||
// ===========================================================================
|
||
|
||
pub fn sha256_hex(data: &[u8]) -> String {
|
||
let mut h = Sha256::new();
|
||
h.update(data);
|
||
to_hex(&h.finalize())
|
||
}
|
||
|
||
/// 迭代加盐哈希,降低撞库速度。
|
||
///
|
||
/// 算法(与旧版 `util.hash_password` 完全一致):
|
||
/// x = sha256(salt + ":" + password)
|
||
/// 重复 HASH_ROUNDS 次:x = sha256(x + salt)
|
||
pub fn hash_password(password: &str, salt: &str) -> String {
|
||
let mut x = sha256_hex(format!("{salt}:{password}").as_bytes());
|
||
for _ in 0..HASH_ROUNDS {
|
||
x = sha256_hex(format!("{x}{salt}").as_bytes());
|
||
}
|
||
x
|
||
}
|
||
|
||
pub fn verify_password(password: &str, salt: &str, expected: &str) -> bool {
|
||
ct_eq(&hash_password(password, salt), expected)
|
||
}
|
||
|
||
/// 常量时间比较:无论差异出现在第几位,都在同一轮数内完成。
|
||
pub fn ct_eq(a: &str, b: &str) -> bool {
|
||
let (a, b) = (a.as_bytes(), b.as_bytes());
|
||
if a.len() != b.len() {
|
||
return false;
|
||
}
|
||
let mut diff = 0u8;
|
||
for i in 0..a.len() {
|
||
diff |= a[i] ^ b[i];
|
||
}
|
||
diff == 0
|
||
}
|
||
|
||
// ===========================================================================
|
||
// 文本
|
||
// ===========================================================================
|
||
|
||
pub fn trim(v: &str) -> &str {
|
||
v.trim()
|
||
}
|
||
|
||
pub fn to_bool(v: Option<&String>) -> bool {
|
||
match v {
|
||
Some(s) => matches!(s.to_ascii_lowercase().as_str(), "1" | "true" | "on" | "yes"),
|
||
None => false,
|
||
}
|
||
}
|
||
|
||
/// `sk_12345678...abcd` → `sk_12345...abcd`
|
||
pub fn mask_key(key: &str) -> String {
|
||
if key.len() < 12 {
|
||
return key.to_owned();
|
||
}
|
||
format!("{}...{}", &key[..8], &key[key.len() - 4..])
|
||
}
|
||
|
||
/// percent-decode(`%XX`)并把 `+` 还原为空格。
|
||
///
|
||
/// 旧版由 `ngx.req.get_uri_args` / `get_post_args` 自动完成,
|
||
/// Rust 侧必须自己实现,否则带中文或特殊字符的参数会解析错误。
|
||
pub fn url_decode(input: &str) -> String {
|
||
let bytes = input.as_bytes();
|
||
let mut out: Vec<u8> = Vec::with_capacity(bytes.len());
|
||
let mut i = 0;
|
||
while i < bytes.len() {
|
||
match bytes[i] {
|
||
b'+' => {
|
||
out.push(b' ');
|
||
i += 1;
|
||
}
|
||
b'%' if i + 2 < bytes.len() => {
|
||
let hi = (bytes[i + 1] as char).to_digit(16);
|
||
let lo = (bytes[i + 2] as char).to_digit(16);
|
||
match (hi, lo) {
|
||
(Some(h), Some(l)) => {
|
||
out.push((h * 16 + l) as u8);
|
||
i += 3;
|
||
}
|
||
_ => {
|
||
out.push(b'%');
|
||
i += 1;
|
||
}
|
||
}
|
||
}
|
||
b => {
|
||
out.push(b);
|
||
i += 1;
|
||
}
|
||
}
|
||
}
|
||
String::from_utf8_lossy(&out).into_owned()
|
||
}
|
||
|
||
/// 解析 `a=1&b=2` 形式的键值对(自动 percent-decode)。
|
||
pub fn parse_kv(raw: &[u8]) -> Vec<(String, String)> {
|
||
let mut out = Vec::new();
|
||
let text = String::from_utf8_lossy(raw);
|
||
for pair in text.split('&') {
|
||
if pair.is_empty() {
|
||
continue;
|
||
}
|
||
let mut it = pair.splitn(2, '=');
|
||
let k = it.next().unwrap_or("");
|
||
let v = it.next().unwrap_or("");
|
||
out.push((url_decode(k), url_decode(v)));
|
||
}
|
||
out
|
||
}
|