Files
sso/source/rust/crates/plugin-sso/src/captcha.rs
T
ssw a988cc3763 refactor: 网关拆分为 ipass-core 内核 + plugin-sso/plugin-domain 插件 + gateway
原 source/rust/src/ 单体 crate 拆为 Cargo workspace:

  crates/ipass-core/    内核:state(共享内存) / store(JSON 原子写) /
                        users(账号唯一写入口) / models(共性字段 + extra 透传) /
                        config(共性常量) / plugin(装配契约) / loc(开关) /
                        session / audit / http / util
  crates/plugin-sso/    身份插件:OAuth2 / OIDC / IAP / TOTP / RSA 等个性代码
  crates/plugin-domain/ 域名插件:企业域名「子域名 → 后端」转发 + 申请/审核
  gateway/              **唯一** cdylib,module 壳 + PLUGINS 装配数组

收窄原则:内核只留共性,个性代码下放插件。收窄后内核不再提供原单体的
bump_window / put_ukey / put_upstream / reload_shm 等,改由插件用 state 泛型
原语自行重建;OAuth 常量与前缀(如 OAUTH_SESSION_COOKIE=sso_sid、
IAP_TOKEN_AUDIENCE=sso-gateway)与历史取值严格一致。

插件一律 crate-type=["rlib"] 由 gateway 静态链入,产出单个
libsso_gateway.dylib —— 不各自出 .so(nginx 动态模块无稳定 ABI,
跨 .so 传 String 即双重 free)。

插件装配点集中在 gateway 5 处:use / PLUGINS 数组 / ModuleConfig 字段 /
Merge / loc_switch 分支,外加指令数组(长度 +1,新增 sso_domain 等开关)。
2026-09-13 10:23:34 +08:00

136 lines
5.4 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! SVG 图形验证码(对齐 MaxKey kaptcha 的登录防自动化能力,实现为纯 SVG,
//! 零依赖:不引入图像库,浏览器直接内联渲染)。
//!
//! ## 生命周期
//!
//! 1. `GET /api/captcha` → 生成 `id + 5 位码`,码存共享内存 `cap:<id>`(TTL 5 分钟);
//! 2. 登录请求附带 `captcha_id` + `captcha_code`;
//! 3. 校验**一次性**:无论对错,取出即删(对齐 MaxKey 的一次性票据语义),
//! 失败需重新取新码。
//!
//! ## 开关
//!
//! 缺省**关闭**(`OAUTH_CAPTCHA=1` 开启)。验证码图形无法被 curl e2e 读取,
//! 缺省开启会让所有存量端到端失效;生产开启后浏览器路径正常出码。
//!
//! ## 防 OCR 的边界
//!
//! 纯字符 + 干扰线能挡住低成本的自动重放/批量尝试,挡不住定向 OCR——
//! 真正的爆破防线是账号锁定(users::record_login_failure),验证码只是减速带。
use serde_json::{Value, json};
use ipass_core::state;
use ipass_core::util;
/// 验证码共享内存 TTL(秒)——与模块文档一致:5 分钟(300s)。
///
/// 原属 `ipass_core::config`,收窄内核后归本插件自管。
pub const CAPTCHA_TTL: i64 = 5 * 60;
/// 验证码开关环境变量名:取值 `1/true/on/yes` 开启(`api.rs` 登录校验读取)。
///
/// 原属 `ipass_core::config`,收窄内核后归本插件自管。
pub const OAUTH_CAPTCHA_ENV: &str = "OAUTH_CAPTCHA";
/// 键前缀:验证码 id → 码(一次性)
const KEY_CAPTCHA_PREFIX: &[u8] = b"cap:";
/// 无歧义字符集:去掉 0/O/1/I/l,降低人眼误识率
const CHARS: &[u8] = b"abcdefghjkmnpqrstuvwxyz23456789";
/// 码长
const CODE_LEN: usize = 5;
/// 是否启用(环境变量在启动时读取,进程内固定)
pub fn enabled() -> bool {
match std::env::var(OAUTH_CAPTCHA_ENV) {
Ok(v) => matches!(v.to_ascii_lowercase().as_str(), "1" | "true" | "on" | "yes"),
Err(_) => false,
}
}
/// 生成新验证码:返回 `(id, svg)`。码只进共享内存,不进响应体。
pub fn create() -> Option<(String, String)> {
let now = util::now();
let mut code = String::with_capacity(CODE_LEN);
for _ in 0..CODE_LEN {
let b = [util::rand_hex(1).as_bytes()[0]];
code.push(CHARS[(b[0] as usize) % CHARS.len()] as char);
}
let id = util::rand_hex(16);
if !state::put(KEY_CAPTCHA_PREFIX, id.as_bytes(), code.as_bytes(), now + CAPTCHA_TTL) {
return None;
}
Some((id, render(&code)))
}
/// 校验并消费:码对返回 true,码错/过期/id 未知一律 false。
/// **无论结果如何,码都会被删除**(一次性语义,防同码重试)。
pub fn verify(id: &str, answer: &str) -> bool {
if id.is_empty() || answer.is_empty() {
return false;
}
let expected = state::get(KEY_CAPTCHA_PREFIX, id.as_bytes()).map(|(p, _)| p);
state::remove(KEY_CAPTCHA_PREFIX, id.as_bytes());
let Some(expected) = expected else {
return false;
};
// 大小写不敏感:用户输入习惯优先于严格匹配
util::ct_eq(&expected.to_ascii_lowercase(), &answer.trim().to_ascii_lowercase())
}
/// 渲染 SVG:每个字符独立旋转/抖动 + 两条干扰弧线 + 噪点。
/// 宽 160 高 48,颜色固定深蓝系,与管理台视觉一致。
fn render(code: &str) -> String {
let (w, h) = (160.0f32, 48.0f32);
let mut body = String::new();
// 干扰弧线两条
for (i, (x1, y1, x2, y2, cx, cy)) in [
(0.0, 36.0, 160.0, 12.0, 60.0, 60.0),
(0.0, 10.0, 160.0, 40.0, 100.0, -10.0),
]
.into_iter()
.enumerate()
{
body.push_str(&format!(
"<path d='M{x1} {y1} Q{cx} {cy} {x2} {y2}' fill='none' stroke='#93c5fd' stroke-width='{}' opacity='.7'/>",
1 + (i % 2)
));
}
// 噪点
for i in 0..24 {
let x = (util::sha256_hex(format!("n{i}{code}").as_bytes())[..4]
.chars()
.fold(0usize, |a, c| a * 16 + c.to_digit(16).unwrap_or(0) as usize)
% (w as usize)) as f32;
let y = (util::sha256_hex(format!("m{i}{code}").as_bytes())[..4]
.chars()
.fold(0usize, |a, c| a * 16 + c.to_digit(16).unwrap_or(0) as usize)
% (h as usize)) as f32;
body.push_str(&format!("<circle cx='{x}' cy='{y}' r='1.2' fill='#64748b' opacity='.5'/>"));
}
// 字符:等距 + 伪随机旋转/垂直偏移
let step = (w - 24.0) / CODE_LEN as f32;
for (i, c) in code.chars().enumerate() {
let rot_seed = util::sha256_hex(format!("r{i}{c}").as_bytes());
let rot = ((rot_seed.as_bytes()[0] % 50) as f32 - 25.0) as i32; // ±25°
let dy = ((rot_seed.as_bytes()[1] % 10) as f32 - 5.0) as i32; // ±5px
let x = 12.0 + step * i as f32 + step / 2.0;
body.push_str(&format!(
"<text x='{x}' y='{}' text-anchor='middle' font-size='26' font-weight='700' \
font-family='Georgia,serif' fill='#1e3a8a' \
transform='rotate({rot} {x} 28)'>{c}</text>",
34 + dy
));
}
format!(
"<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 {w} {h}' width='{w}' height='{h}' role='img' aria-label='captcha'><rect width='{w}' height='{h}' fill='#f1f5f9' rx='6'/>{body}</svg>"
)
}
/// 管理台 / 登录页取码接口的响应体。
pub fn response() -> Option<Value> {
create().map(|(id, svg)| json!({ "id": id, "svg": svg, "ttl": CAPTCHA_TTL }))
}