Skip to main content

futu_opend/
hints.rs

1//! v1.4.110 P1-2: auth error hint messages (抽自 main.rs lines 1416-1604).
2//!
3//! v1.4.97 P1-D: error message classification + user-facing recovery hints.
4//! ret_type=2/15/21/45 等错误码 → 不同恢复建议 (device_id 重置 / 反刷 sleep /
5//! 防火墙开放 9595 / 平台 + 客户端版本切换).
6
7use crate::config::RuntimeConfig;
8
9fn cached_sms_pending_hint_text(error: &futu_core::error::FutuError) -> Option<&'static str> {
10    matches!(
11        error,
12        futu_core::error::FutuError::SmsVerificationCodeRequired
13    )
14    .then_some(
15        r#"
16⚠️  已缓存的 SMS challenge 正在等待验证码,尚未发送新的认证请求。
17
18请保持同一 HOME,在前台交互式终端重新运行;也可以在短缓存窗口内使用:
19  futu-opend --verify-code <CODE> ...
20
21不要反复重启、清理缓存或执行 --reset-device;这些动作可能替换现有 challenge
22并触发新的 SMS。
23"#,
24    )
25}
26
27/// 解析 auth error string + 给出对应 recovery hint (打到 stderr + tracing).
28///
29/// 调用方在 `Err(e) => { ... }` match arm 内调用此 fn (替代 inline if-chain).
30/// 调用方随后 fail closed;无凭据启动才是受支持的 offline mode。
31pub fn print_auth_error_hint(e: &futu_core::error::FutuError, config: &RuntimeConfig) {
32    if let Some(hint) = cached_sms_pending_hint_text(e) {
33        eprint!("{hint}");
34        tracing::error!(
35            error = %e,
36            "cached SMS verification is awaiting operator input; no replacement request was sent"
37        );
38        return;
39    }
40
41    let err_str = format!("{e}");
42    let hint_21 = err_str.contains("ret_type=21") || err_str.contains("验证码错");
43    let hint_15 = err_str.contains("ret_type=15") || err_str.contains("长时间没有登录");
44    // v1.4.19:识别"所有 Platform IP 都连不上"—— 几乎一定是本机
45    // 出站防火墙挡了 9595 端口(腾讯云 Lighthouse 默认不放 9595;
46    // 企业内网 / 云厂商安全组也常见)
47    let hint_firewall =
48        err_str.contains("Platform IP pool exhausted") || err_str.contains("timed out");
49    // v1.4.92 D1: 更多细分 hint —— error_code=2 / 45 / 网络 DNS / SMS 非交互
50    let hint_2 = err_str.contains("ret_type=2,")
51        || err_str.contains("ret_type=2 ")
52        || err_str.contains("账号密码不匹配");
53    let hint_45 = err_str.contains("ret_type=45") || err_str.contains("当前应用版本过低");
54    let hint_dns = err_str.contains("dns error")
55        || err_str.contains("failed to lookup")
56        || err_str.contains("Name or service not known")
57        || err_str.contains("nodename nor servname");
58    // SMS 非交互:error 是 SMS 流程相关 + stdin 不是 TTY
59    let hint_sms_noninteractive = (err_str.contains("ret_type=20")
60        || err_str.contains("require_device_verify")
61        || err_str.contains("device_verify_sig"))
62        && !std::io::IsTerminal::is_terminal(&std::io::stdin())
63        && config.verify_code.is_none();
64    if hint_21 {
65        tracing::error!(
66            error = %e,
67            "gateway init failed: SMS code mismatch (ret_type=21). \
68             Device_id may be locked after multiple wrong codes — try \
69             `futu-opend --reset-device --setup-only ...` to regenerate \
70             and re-verify via SMS."
71        );
72        // v1.4.72 BUG-009 Fix 9b (external reviewer v1.4.69 P1): setup-only + TTY
73        // 场景保持前台 wait,让用户读完错误 + 手动决定下一步(不要
74        // 立即退出让 supervisor 重启 → 重 POST /authority → 新 SMS
75        // 失效旧码 → 累计失败触发账户锁)。
76        //
77        // 判断条件:setup_only + stdin 是 tty(可交互)+ --verify-code
78        // 用过(说明这次 SMS 输错)。非交互 daemon (systemd / Docker)
79        // 保持旧行为 return Err → supervisor 决定重启策略。
80        if config.setup_only
81            && std::io::IsTerminal::is_terminal(&std::io::stdin())
82            && config.verify_code.is_some()
83        {
84            eprintln!();
85            eprintln!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
86            eprintln!("⚠️  v1.4.72 BUG-009 Fix 9b: SMS 验证码错 (ret_type=21)");
87            eprintln!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
88            eprintln!();
89            eprintln!("   daemon 不立即退出,让你有时间读完错误 + 决定下一步。");
90            eprintln!();
91            eprintln!("   下一步建议(不要盲目重跑 daemon,避免新 SMS + 账户锁):");
92            eprintln!("   1. 等 30 秒,等服务端限流过");
93            eprintln!("   2. 检查手机上最新收到的 SMS(可能有多条,用最新那条)");
94            eprintln!("   3. 重跑 daemon 带新码:");
95            eprintln!("      futu-opend --setup-only --verify-code <新 SMS 码> ...");
96            eprintln!();
97            eprintln!("   按 Enter 退出(Ctrl+C 也可)...");
98            let mut pause = String::new();
99            if let Err(err) = std::io::stdin().read_line(&mut pause) {
100                tracing::debug!(
101                    error = %err,
102                    "failed to wait for interactive SMS error acknowledgment"
103                );
104            }
105        }
106    } else if hint_15 {
107        // v1.4.74 A3 BUG-003 fix(external reviewer v1.4.71 AI tester §4.2 Layer 2):
108        // error_code=15 原本用一大段 inline text 列 5 因,用户 skim 读
109        // 很难 discharge 每一条 cause。改为结构化 stderr 输出 + tracing
110        // log 保留引用;让用户能**按优先级逐条排查**。
111        eprint!("{}", ret_type_15_hint_text());
112        tracing::error!(
113            error = %e,
114            "ret_type=15 — see stderr for 5-cause diagnostic checklist"
115        );
116    } else if hint_firewall {
117        tracing::error!(
118            error = %e,
119            "gateway init failed: all Platform connection endpoints are unreachable on port 9595. \
120             This is almost always an outbound firewall issue on your host, NOT \
121             a Futu server problem. Quick check: \
122             `nc -vz hkconn.futunn.com 9595` and `nc -vz usconn.moomoo.com 9595` — \
123             if these also fail, your host is blocking outbound TCP 9595. \
124             Fix: open 9595 in your cloud security group \
125             (Tencent Cloud Lighthouse / CVM / AWS / Aliyun all default to \
126             blocking non-standard ports)."
127        );
128    } else if hint_2 {
129        // v1.4.92 D1: error_code=2 "账号密码不匹配"
130        // 真因 4 类(按出现概率排序):
131        //   1. 密码真错(最常见)
132        //   2. --platform 选错(auth.futunn.com 收 client_type=60 / 反之 → 直接拒)
133        //   3. account 拆区号错(+86-xxx 整串发 → 服务端按号码本体查 hash 不匹配)
134        //   4. 同号在 futunn / moomoo 各注册了一个,登错了那个
135        eprintln!();
136        eprintln!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
137        eprintln!("⚠️  ret_type=2 — 账号密码不匹配");
138        eprintln!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
139        eprintln!();
140        eprintln!("💡 Hint: 这个错误可能 4 种根因(按概率):");
141        eprintln!("  1. 密码真错 → 检查 --login-pwd 或 --login-pwd-md5");
142        eprintln!("  2. --platform 选错 → futunn 系账号必须 --platform futunn,");
143        eprintln!("     moomoo (US/SG/AU/JP/CA/MY) 系账号必须 --platform moomoo");
144        eprintln!("  3. 同号双注册 → futunn / moomoo 同手机号 / 邮箱可各注册一个,");
145        eprintln!("     检查 `futu-opend --login-account ... --platform <对侧>` 是否能登");
146        eprintln!("  4. 区号写错 → 手机号格式 +86-13900000000 (区号 + dash + 号码本体)");
147        eprintln!();
148        tracing::error!(error = %e, "ret_type=2 — see stderr 4-cause hint");
149    } else if hint_45 {
150        // v1.4.92 D1: error_code=45 "当前应用版本过低"
151        eprintln!();
152        eprintln!("⚠️  ret_type=45 — 当前应用版本过低");
153        eprintln!();
154        eprintln!("💡 Hint: 服务端对海外账号 (user_attribution != 1) 严格校验,");
155        eprintln!("        客户端版本号需 ≥ 800(X-Futu-Client-Version 字段)。");
156        eprintln!("        本 Rust daemon 使用 backend 可识别的 Rust 版本号 1031。");
157        eprintln!("        若仍报 45,可能是 backend 升级了最低版本要求,");
158        eprintln!("        升级 daemon: brew upgrade futuleaf/tap/futu-opend-rs");
159        eprintln!();
160        tracing::error!(error = %e, "ret_type=45 — version too low, see stderr hint");
161    } else if hint_dns {
162        // v1.4.92 D1: DNS 解析失败 (auth.futunn.com / auth.moomoo.com)
163        eprintln!();
164        eprintln!("⚠️  网络错: DNS 解析 auth server 失败");
165        eprintln!();
166        eprintln!("💡 Hint: 检查域名解析 + 网络连通性:");
167        eprintln!("  1. ping auth.futunn.com / ping auth.moomoo.com");
168        eprintln!("  2. 若公司 / 校园 VPN 限制了海外域名 → 切换 VPN 或开放 auth.* 解析");
169        eprintln!("  3. 中国大陆 ISP 偶尔抽风 auth.moomoo.com → 试 8.8.8.8 DNS");
170        eprintln!("  4. 检查 /etc/hosts 是否有错误的 auth server override");
171        eprintln!();
172        tracing::error!(error = %e, "DNS lookup failed for auth server");
173    } else if hint_sms_noninteractive {
174        // v1.4.92 D1: SMS 验证需要交互终端 + stdin 不是 TTY (nohup / docker -d / systemd)
175        eprintln!();
176        eprintln!("⚠️  SMS 验证码需要交互式终端 (stdin 不是 TTY)");
177        eprintln!();
178        eprintln!("💡 Hint: 后台 / 守护进程模式下 SMS 输入会立即返回空字符串,");
179        eprintln!("        毒化 device_id 触发 ret_type=15 / 21。");
180        eprintln!();
181        eprintln!("  正确部署姿势 (systemd / Docker):");
182        eprintln!("  1. 前台一次完成 SMS:");
183        eprintln!("     futu-opend --setup-only --login-account X --login-pwd Y \\");
184        eprintln!("                --platform <futunn|moomoo>");
185        eprintln!("     (或用 --verify-code <已收到的码> 跳过 stdin)");
186        eprintln!("  2. 完成后凭据写入 ~/.futu-opend-rs/,daemon 后续自动跳 SMS");
187        eprintln!("  3. 启动后台 daemon:");
188        eprintln!("     futu-opend --login-account X --login-pwd Y --platform ...");
189        eprintln!();
190        tracing::error!(error = %e, "SMS required but stdin is not a TTY");
191    } else {
192        tracing::error!(error = %e, "gateway initialization failed; startup will abort");
193    }
194}
195
196fn ret_type_15_hint_text() -> &'static str {
197    r#"
198━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
199⚠️  Gateway init failed: server returned ret_type=15
200    ("请重新输入密码" — 协议层是 kAuthTgtgtExpired:服务端判定 tgtgt 大票过期/无效)
201━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
202
203不要反复输入同一密码。15 不等于密码一定错误,也不是 WebTCP/HTTP transport
204失败;请求已经到达 auth backend,服务端在 authority 业务层拒绝。
205
206authority raw response 的 `error` 对象可以一行定性:
207
208  - `require_device_verify=true` → 应进入 SMS/设备验证流程
209  - `delete_password=true` → C++ 会塌缩成 15,按删除密码凭据/重认证处理
210  - 裸 `error_code=15` → tgtgt 被服务端票据校验拒绝
211
212这个错误仍有若干常见触发因素,按优先级逐条排查:
213
214  [0] **有另一个 Futu OpenD 正在用这个账号**(v1.4.52 新增)
215      → 检查所有机器:`lsof -i :11111` + `ps aux | grep -i opend`
216      → 停掉另一个 OpenD(C++ 或 Rust),然后重试
217
218  [1] **短时间重复 authority / 服务端拒绝继续发票据**
219      → 等 60 秒后再重试
220
221  [2] **SMS 超限 / device_id 验证状态异常**(v1.4.57 新增)
222      → 等 3-5 分钟让限流过
223      → 手机上登录富途/moomoo App 一次清账号状态
224      → 重启 daemon 带 `--verify-code <CODE>` 避免 stdin 延迟
225
226  [3] **device_id 验证状态需要重置**(空 SMS 提交 / 长时间不用)
227      → 先试 `--reset-device --setup-only`
228      → 注意:破坏性操作,会触发二次 SMS 验证
229
230  [4] **账号级状态异常 / 不适合密码登录**
231      → 手机上登录富途/moomoo App 一次清账号状态
232      → 若账号从未在 App 登录激活,必须先激活
233
234  建议试序:[0] → [1] → [2] → [3] → [4]
235
236"#
237}
238
239#[cfg(test)]
240mod tests;