Skip to main content

futu_backend/auth/
types.rs

1//! v1.4.110+ Tier 1 split (from `auth/mod.rs`): 顶层类型 + 2 const.
2//!
3//! - `UserAttribution` enum + impl (region / auth_domain / conn_identity 映射)
4//! - `AuthConfig` (输入: account / pwd / device_id / client_type)
5//! - `AuthResult` (输出: client_sig / client_key / auth_code_list / svr_time_offset / web_sig / ...)
6//! - `BrokerAuthCode` (auth_code_list 单元)
7//! - `AUTH_SERVER_PROD` / `TGTGT_VALIDITY_SECS` 顶层 const
8//!
9//! 不含业务逻辑 — 业务 fn 仍在 mod.rs.
10
11/// 默认认证服务器——CN / HK 归属地账号用这个。
12/// 海外账号(US/SG/AU/JP)实际请求时会按 `UserAttribution::auth_domain()` 切换。
13pub const AUTH_SERVER_PROD: &str = "https://auth.futunn.com";
14
15/// v1.4.71: TGTGT 票据有效期(30 天),对齐 C++ `auth_cryptor.cpp:135`
16/// `CreateNewTgtgt` 里 `InvalidTime = RefreshTime + 30 * 24 * 3600`。
17///
18/// **绝对不 hardcode**:之前 `30 * 24 * 3600` 魔法数散落在 2 处(`handle_device_verify`
19/// + `tgtgt_payload_structure_ftnn_aligns_cpp_spec` test),改动需同步。提为 const 保一致。
20pub const TGTGT_VALIDITY_SECS: u32 = 30 * 24 * 3600;
21
22/// Cached credentials ticket age summary for daemon diagnostics.
23///
24/// This exposes only timestamps / derived age, never `tgtgt`, rand key,
25/// device sig, web sig, account, or uid. `None` values mean legacy credentials
26/// did not carry `tgtgt_saved_at` yet.
27#[derive(Debug, Clone, serde::Serialize)]
28pub struct CredentialTicketStatus {
29    pub saved_at: Option<u64>,
30    pub age_days: Option<u64>,
31    pub expires_in_days: Option<i64>,
32    pub expiry_warning: Option<String>,
33}
34
35/// 用户归属地(对齐 C++ `FTLogin/Src/ftlogin/ftlogin_def.h:261-270`
36/// 和 `config/impl/user_attr_config.cpp:8-15`)
37///
38/// salt 响应里 `user_attribution` 字段决定认证域名:
39/// - CN / HK → `auth.futunn.com`
40/// - US / SG / AU / JP → `auth.moomoo.com`
41///
42/// 海外账号(moomoo)如果发到 futunn 域名会返回 `error_code=11`(误导为"验证码",
43/// 实际是服务端校验失败),必须按 attribution 切域名。
44#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
45#[repr(u8)]
46#[non_exhaustive]
47pub enum UserAttribution {
48    /// 中国大陆
49    Cn = 1,
50    /// 美国(moomoo)
51    Us = 2,
52    /// 新加坡(moomoo)
53    Sg = 3,
54    /// 澳大利亚(moomoo)
55    Au = 4,
56    /// 日本(moomoo)
57    Jp = 5,
58    /// 香港
59    Hk = 6,
60}
61
62impl UserAttribution {
63    /// 从 salt 响应的 `user_attribution` 整数字段解析。
64    /// 未知值(0 或 7+)返回 `None`,让调用方走 fallback(默认 futunn)。
65    pub fn from_u32(v: u32) -> Option<Self> {
66        match v {
67            1 => Some(Self::Cn),
68            2 => Some(Self::Us),
69            3 => Some(Self::Sg),
70            4 => Some(Self::Au),
71            5 => Some(Self::Jp),
72            6 => Some(Self::Hk),
73            _ => None,
74        }
75    }
76
77    /// 从 JSON 数字解析 `user_attribution`。服务端字段语义是 u32 范围内的
78    /// enum;超出 u32 的异常值不能截断后再进入 `from_u32`。
79    pub fn from_u64(v: u64) -> Option<Self> {
80        u32::try_from(v).ok().and_then(Self::from_u32)
81    }
82
83    /// 对齐 C++ `user_attr_config.cpp:8-15` 的映射表。
84    pub fn auth_domain(self) -> &'static str {
85        match self {
86            Self::Cn | Self::Hk => "https://auth.futunn.com",
87            Self::Us | Self::Sg | Self::Au | Self::Jp => "https://auth.moomoo.com",
88        }
89    }
90
91    /// 人读地区代码(日志 / 凭据文件用)。
92    pub fn region(self) -> &'static str {
93        match self {
94            Self::Cn => "CN",
95            Self::Us => "US",
96            Self::Sg => "SG",
97            Self::Au => "AU",
98            Self::Jp => "JP",
99            Self::Hk => "HK",
100        }
101    }
102
103    /// TCP 登录 `ReqEncryptData.conn_identity` 字段:
104    /// 对齐 C++ `FTConnCmn.proto` ConnIdentity enum,UserAttribution 数值直接对应
105    /// (CN=1, US=2, SG=3, AU=4, JP=5, HK=6,见 `user_attr_config.cpp:8-15`)
106    pub fn to_conn_identity(self) -> u32 {
107        self as u32
108    }
109}
110
111/// v1.4.19:`ZeroizeOnDrop` 让 `AuthConfig` drop 时自动把 `password` 字段的
112/// 堆内存清零,减少进程 core dump / `/proc/<pid>/mem` 读到明文的窗口。
113/// 其他字段(auth_server / account / device_id)不是秘密,`#[zeroize(skip)]`
114/// 跳过。注意 `Clone` 每次复制都会产生新堆分配,drop 时各自 zeroize。
115#[derive(Clone, zeroize::ZeroizeOnDrop)]
116pub struct AuthConfig {
117    #[zeroize(skip)]
118    pub auth_server: String,
119    #[zeroize(skip)]
120    pub account: String,
121    /// 密码:`password_is_md5 = false` 时是明文(内部做 MD5);
122    /// `password_is_md5 = true` 时是 32 位小写 hex 的 MD5(直接使用)。
123    /// drop 时自动 zeroize。
124    pub password: String,
125    /// 是否为预哈希 MD5;`false` 时按明文处理
126    #[zeroize(skip)]
127    pub password_is_md5: bool,
128    #[zeroize(skip)]
129    pub device_id: String,
130    /// C++ `AppConfig::GetClientTypeValue()` 语义的 40/60 client_type。
131    ///
132    /// 对齐 C++ `NNBase_Define_Enum.h:1113-1114`:
133    /// - `40` = `NN_ClientType_FutuOpenD`(牛牛 FTNN)
134    /// - `60` = `NN_ClientType_FutuOpenDMooMoo`(moomoo FTMM)
135    ///
136    /// v1.4.15:moomoo 的 `auth.moomoo.com` 对 client-type=40 直接拒绝
137    /// (返回 `error_code=2`),必须用 60。由 `--platform` flag 决定。
138    #[zeroize(skip)]
139    pub client_type: u8,
140}
141
142impl std::fmt::Debug for AuthConfig {
143    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
144        let account_fp = crate::auth::redact::account_log_fingerprint(&self.account);
145        let device_id_fp = crate::auth::redact::device_id_log_fingerprint(&self.device_id);
146        let redacted_password = format!("<REDACTED len={}>", self.password.len());
147
148        f.debug_struct("AuthConfig")
149            .field("auth_server", &self.auth_server)
150            .field("account_fp", &account_fp)
151            .field("password", &redacted_password)
152            .field("password_is_md5", &self.password_is_md5)
153            .field("device_id_fp", &device_id_fp)
154            .field("client_type", &self.client_type)
155            .finish()
156    }
157}
158
159/// `auth_code_list` 响应条目——每个 broker 一项。
160/// 对齐 C++ `FTLogin/Src/ftlogin/auth/impl/auth_impl.cpp:3504`(`ParseAuthCodeList`)
161#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
162pub struct BrokerAuthCode {
163    pub broker_id: u32,
164    pub auth_code: String,
165    pub invalid_time: u64,
166}
167
168#[derive(Debug, Clone)]
169pub struct AuthResult {
170    pub user_id: u64,
171    pub client_sig: Vec<u8>,
172    pub client_key: Vec<u8>,
173    /// 从 salt 响应拿到的归属地,TCP 登录时会用来派生 conn_identity
174    pub user_attribution: UserAttribution,
175    /// HTTP auth 响应的 `auth_code_list`——每个已授权 broker 的票据,
176    /// 用来后续向 `/broker_auth/client_auth` 换取 broker_client_sig / broker_client_key
177    pub auth_code_list: Vec<BrokerAuthCode>,
178    /// 原始 rand_key(解密用)——broker_auth 响应里的 `broker_client_key` 也是
179    /// 用这个 rand_key 加密过的,需要它做 `aes_cbc_md5_decrypt_var` 解开
180    pub rand_key: Vec<u8>,
181    /// v1.4.22:**服务端时间 - 本机时间**(秒)—— salt 响应时捕获。
182    ///
183    /// 用于让后续 TOTP / time-based token 用"服务端时间"而不是本机时间。
184    /// 机器时钟飘了 > 30s 的场景下 TOTP 会被服务端拒,offset 校正后可免。
185    /// 对齐 C++ `INNBiz_SvrTime::GetSvrTimeStamp()` 机制。
186    ///
187    /// 使用方式:`let server_now = local_now + svr_time_offset;`
188    /// 首次 salt 时 offset < 0 说明本机时钟比服务端快,反之则慢。0 = 没取到。
189    pub svr_time_offset: i64,
190    /// v1.4.93 G3 (CLAUDE.md C4 audit): `web_sig` from `/authority/` 响应里的
191    /// `web_sig_new` 字段(对齐 C++ `auth_impl.cpp:3193,3260`
192    /// `account.web_sig_`)。
193    ///
194    /// **用途**:G2 [`crate::auth::repull::repull_auth_code`] 把它作 POST
195    /// `/authority/repull_auth_code` body 字段(C++ `auth_impl.cpp:738-748`),
196    /// broker auth_code 过期时拉新 auth_code,让 broker channel self-heal
197    /// 不必重启 daemon。
198    ///
199    /// 缺失 → 空字符串(旧 v1.4.92 及之前的凭据 / device-verify shell 路径
200    /// 没此字段)。空时调用方应跳过 repull, fallback 走 platform refresh。
201    pub web_sig: String,
202    /// v1.4.93 G1 (CLAUDE.md C4 audit P1): client_sig 失效的本地时戳 (秒, UTC epoch).
203    /// 对齐 C++ `auth_impl.cpp:3245-3247` 解 `cltsig_invalidtime`
204    /// (服务端绝对过期 epoch),再按
205    /// `(cltsig_invalidtime - svr_time) + local_now` 得本地时间, 写到
206    /// `account.client_sig_invalid_local_time_s_`.
207    ///
208    /// **用途**: 记录服务端下发的 client_sig 失效时间。当前 auth 模块只负责
209    /// 解析/持久化该字段,不启动 proactive timer;长跑 daemon 的 client_sig
210    /// 更新走 reconnect 失败后的 reactive remember-login refresh 路径。
211    ///
212    /// **缺失 (老 backend / 旧 credentials shell)**: 0 (不触发 proactive refresh).
213    pub client_sig_invalid_local_time_s: u64,
214    /// v1.4.94 G6 (P2 protocol gap): `moomoo_client_sig` from `/authority/`
215    /// 响应里的 `moomoo_client_sig` 字段, **base64 已解码**.
216    ///
217    /// 对齐 C++ `auth_impl.cpp:3195` `ParseJsonString(jval_result, "moomoo_client_sig", mm_sig);`
218    /// 映射到 `account.us_client_sig_`. 用于 moomoo / US 路径独立于
219    /// `client_sig` 的 broker channel 鉴权 — 当账号 attribution = US/SG/AU/JP/CA
220    /// 时, broker_auth_code 换 client_sig 走的是 `moomoo_client_sig` 而不是
221    /// 主 `client_sig`.
222    ///
223    /// 缺失 (futunn HK 账号 / 老 backend) → 空 Vec (handler 检查 `is_empty()`
224    /// 决定 fallback 主 `client_sig`).
225    ///
226    /// ## ⚠️ v1.4.96 BUG #010 doctrine fix (external reviewer double-tester 2026-04-26):
227    ///
228    /// 真机 verify 发现 backend 对 **futunn 账号也下发 moomoo_client_sig**
229    /// (mm_sig_len=128). 字段名 `moomoo_*` **不**意味着账号是 moomoo 系.
230    ///
231    /// **不要**基于 `moomoo_client_sig.is_empty()` 判账号 broker path. 真正
232    /// 的 broker path 判断用 `broker_id` (1001/1007=Futu HK/US, 6xxx=moomoo).
233    pub moomoo_client_sig: Vec<u8>,
234    /// v1.4.94 G6 (P2 protocol gap): `moomoo_client_key` 解密后的 client key
235    /// (对应 moomoo path), 与 `client_key` 平级. 缺失 → 空 Vec.
236    ///
237    /// 对齐 C++ `auth_impl.cpp:3196,3260` `account.us_client_key_` (经
238    /// `UpdateRandKey` 解密).
239    pub moomoo_client_key: Vec<u8>,
240    /// v1.4.94 G6 (P2 protocol gap): `moomoo_web_sig_new` from `/authority/`
241    /// 响应. 对齐 C++ `auth_impl.cpp:3197,3260` `account.us_web_sig_`. 用于
242    /// moomoo path repull_auth_code (类似 `web_sig` 之于主 path). 缺失 →
243    /// 空字符串.
244    pub moomoo_web_sig: String,
245}
246
247#[cfg(test)]
248mod tests;