acosmi-sdk 4.0.0

Acosmi Rust SDK:模型网关、Agent Run Gateway 与 Compliance 统一客户端。双格式(Anthropic + OpenAI)。端口自 acosmi-sdk-ts。
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
//! OAuth 2.1 PKCE 流程。端口自 `auth/auth.ts`(其端口自 `acosmi-sdk-go/auth.go`)。
//!
//! 含:
//!   - Discovery(`discover_with_profile` / `discover` / `discover_web_oauth_metadata`)
//!   - Dynamic Client Registration(`register` / `register_web_oauth_client`,RFC 7591)
//!   - PKCE(`generate_code_verifier` + S256 `code_challenge` / `generate_state`)
//!   - Token Exchange(`exchange_code` / `exchange_code_with_expiry`)
//!   - Refresh(`refresh_token`,轮换:换新撤旧由 Client 协调)
//!   - Revoke(`revoke_token`,服务端不支持时静默跳过)
//!   - 浏览器 Web OAuth 原语(`create_web_authorization_request` /
//!     `complete_web_authorization_request`,平台无关纯逻辑:PKCE / state 校验 / 兑换)
//!   - loopback `authorize()`(桌面 OAuth,`#[cfg(feature = "desktop-loopback")]`)
//!
//! 所有 HTTP 经传入的 `reqwest::Client`(对应 TS `fetchImpl`),auth 专用 30s 超时。

use crate::auth::types::{ClientRegistration, ServerMetadata, TokenResponse, TokenSet};
use crate::core::transport::{HttpClient, HttpPurpose};
use crate::shared::errors::{Error, Result};
use chrono::Utc;
use sha2::{Digest, Sha256};
use std::time::Duration;

/// auth 专用超时(与 Go `authHTTPClient` 30s 一致)。
const AUTH_TIMEOUT: Duration = Duration::from_secs(30);

// =============================================================================
// OAuthTokenEndpointError —— token 端点结构化错误(对应 TS 同名子类)
// =============================================================================

/// token 端点(exchange / refresh)的结构化错误。携带 OAuth `error` 码用于
/// `is_invalid_grant_error` 判定(invalid_grant → 本地 token 失效,需重登)。
#[derive(Clone)]
pub struct OAuthTokenEndpointError {
    pub status: u16,
    pub oauth_error: String,
    pub error_description: String,
}

impl std::fmt::Display for OAuthTokenEndpointError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "token: HTTP {}", self.status)
    }
}

impl std::error::Error for OAuthTokenEndpointError {}

/// 判定错误是否为 OAuth `invalid_grant`(refresh token 失效)。对应 TS `isInvalidGrantError`。
pub fn is_invalid_grant_error(err: &Error) -> bool {
    matches!(err, Error::OAuthTokenEndpoint(e) if e.oauth_error == "invalid_grant")
}

/// 检测 SSL/TLS 相关错误(企业代理 Zscaler 等)。对应 TS `isSSLError`。
pub fn is_ssl_error(msg: &str) -> bool {
    msg.contains("tls:") || msg.contains("x509:") || msg.contains("certificate")
}

// =============================================================================
// Discovery
// =============================================================================

/// OAuth metadata profile —— 决定 well-known 端点的路径后缀。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OAuthMetadataProfile {
    /// 桌面 loopback OAuth。
    Desktop,
    /// 浏览器 Web OAuth。
    Web,
}

impl OAuthMetadataProfile {
    /// well-known 端点路径后缀。
    pub fn as_str(self) -> &'static str {
        match self {
            OAuthMetadataProfile::Desktop => "desktop",
            OAuthMetadataProfile::Web => "web",
        }
    }
}

/// 从 well-known 端点获取指定 profile 的 OAuth 服务元数据(RFC 8414)。
///
/// `server_url` 可能含路径(如 `https://acosmi.ai/api/v4`);well-known 端点按 RFC 8414
/// 必须在 origin 根路径:`https://acosmi.ai/.well-known/oauth-authorization-server/<profile>`。
pub async fn discover_with_profile_with_transport(
    http: &HttpClient,
    server_url: &str,
    profile: OAuthMetadataProfile,
) -> Result<ServerMetadata> {
    // 去尾随 '/' 后解析;取 origin(scheme://host[:port])。
    let trimmed = server_url.trim_end_matches('/');
    let parsed = url::Url::parse(trimmed)
        .map_err(|e| Error::other(format!("discover: invalid server URL: {e}")))?;
    let host = parsed
        .host_str()
        .ok_or_else(|| Error::other("discover: invalid server URL: missing host"))?;
    let mut origin = format!("{}://{}", parsed.scheme(), host);
    if let Some(port) = parsed.port() {
        origin.push_str(&format!(":{port}"));
    }
    let endpoint = format!(
        "{origin}/.well-known/oauth-authorization-server/{}",
        profile.as_str()
    );

    let resp = http
        .get(&endpoint)
        .purpose(HttpPurpose::OAuthDiscovery)
        .timeout(AUTH_TIMEOUT)
        .send()
        .await
        .map_err(|e| Error::other(format!("discover: {e}")))?;

    if !resp.status().is_success() {
        return Err(Error::other(format!("discover: HTTP {}", resp.status())));
    }

    let meta: ServerMetadata = resp
        .json()
        .await
        .map_err(|_| Error::other("discover: decode failed"))?;

    if meta.token_endpoint.is_empty() || meta.authorization_endpoint.is_empty() {
        return Err(Error::other(
            "discover: metadata missing required endpoints",
        ));
    }

    Ok(meta)
}

/// 从 well-known 端点获取 Desktop OAuth 服务元数据。对应 TS `discover`。
pub async fn discover_with_transport(
    http: &HttpClient,
    server_url: &str,
) -> Result<ServerMetadata> {
    discover_with_profile_with_transport(http, server_url, OAuthMetadataProfile::Desktop).await
}

/// 从 well-known 端点获取 Web OAuth 服务元数据。对应 TS `discoverWebOAuthMetadata`。
///
/// 与 `discover` 行为一致,但请求 `web` profile(csign 等第一方 Web 应用必须用此 profile;
/// `desktop` 返回的是桌面 loopback 端点,不可混用)。
pub async fn discover_web_oauth_metadata_with_transport(
    http: &HttpClient,
    server_url: &str,
) -> Result<ServerMetadata> {
    discover_with_profile_with_transport(http, server_url, OAuthMetadataProfile::Web).await
}

// =============================================================================
// Dynamic Client Registration (RFC 7591)
// =============================================================================

/// 动态注册桌面客户端,获取 client_id。对应 TS `register`。
pub async fn register_with_transport(
    http: &HttpClient,
    meta: &ServerMetadata,
    app_name: &str,
) -> Result<ClientRegistration> {
    let body = serde_json::json!({
        "client_name": app_name,
        "token_endpoint_auth_method": "none",
        "grant_types": ["authorization_code", "refresh_token"],
        "redirect_uris": ["http://127.0.0.1/callback"],
        "response_types": ["code"],
    });
    post_register(http, &meta.registration_endpoint, body).await
}

/// Web OAuth 动态注册参数。对应 TS `RegisterWebOAuthClientOptions`。
#[derive(Debug, Clone)]
pub struct RegisterWebOAuthClientOptions {
    /// 客户端展示名(RFC 7591 client_name)。
    pub client_name: String,
    /// 浏览器 Web OAuth 的 redirect_uri 列表。
    pub redirect_uris: Vec<String>,
    /// 可选 scope 列表 —— 提供时以空格连接写入 RFC 7591 scope 字段。
    pub scopes: Option<Vec<String>>,
}

/// 动态注册 Web OAuth(浏览器)客户端,获取 client_id。对应 TS `registerWebOAuthClient`。
///
/// 与 `register`(桌面 loopback,硬编码 redirect_uri=127.0.0.1)的区别:本函数允许传入
/// 任意 Web redirect_uri,供 csign 等第一方 Web 应用使用。auth method 仍为 `none`(PKCE public)。
pub async fn register_web_oauth_client_with_transport(
    http: &HttpClient,
    meta: &ServerMetadata,
    opts: &RegisterWebOAuthClientOptions,
) -> Result<ClientRegistration> {
    let mut body = serde_json::json!({
        "client_name": opts.client_name,
        "token_endpoint_auth_method": "none",
        "grant_types": ["authorization_code", "refresh_token"],
        "redirect_uris": opts.redirect_uris,
        "response_types": ["code"],
    });
    if let Some(scopes) = &opts.scopes {
        body["scope"] = serde_json::Value::String(scopes.join(" "));
    }
    post_register(http, &meta.registration_endpoint, body).await
}

async fn post_register(
    http: &HttpClient,
    endpoint: &str,
    body: serde_json::Value,
) -> Result<ClientRegistration> {
    let resp = http
        .post(endpoint)
        .purpose(HttpPurpose::OAuthRegistration)
        .timeout(AUTH_TIMEOUT)
        .json(&body)
        .send()
        .await
        .map_err(|e| Error::other(format!("register: {e}")))?;

    let status = resp.status().as_u16();
    if status != 200 && status != 201 {
        return Err(Error::other(format!("register: HTTP {status}")));
    }

    resp.json()
        .await
        .map_err(|_| Error::other("register: decode failed"))
}

// =============================================================================
// PKCE
// =============================================================================

/// 生成 32 字节加密随机数,base64url 无填充编码 —— PKCE verifier / state 共用随机源。
fn random_base64url_32() -> String {
    use rand::RngCore;
    let mut b = [0u8; 32];
    rand::rngs::OsRng.fill_bytes(&mut b);
    base64url_no_pad(&b)
}

/// 生成 PKCE code_verifier(32 字节随机 → base64url 无填充)。
pub fn generate_code_verifier() -> String {
    random_base64url_32()
}

/// 生成 OAuth `state` 参数(32 字节随机 → base64url 无填充)。对应 TS `generateState`。
///
/// 与 `generate_code_verifier` 共用随机源。Web OAuth 流程用它做 CSRF 防护:授权请求带上
/// state,callback 回来必须逐字符比对。
pub fn generate_state() -> String {
    random_base64url_32()
}

/// 桌面 loopback callback 的 state 判定(2026-08-15,与 TS/Go 同契约):
/// 恰好一个 state 且与本次登录严格相等,否则给出**只描述形态、不回显取值**的失败原因。
/// 对 /callback 的一切形态(成功 / OAuth error / 畸形)先行——error 回调绕过 state 直接
/// 结算 denied 会让本机任意进程零知识打断/塑形等待中的登录。
///
/// 门控与唯一消费者(`mod loopback`)一致 + `test`:否则 `--no-default-features` 构建下它是
/// dead_code,CI 的 `RUSTFLAGS: -D warnings` 会据此报错(2026-08-15 实测,此前被 fmt 红挡住)。
#[cfg(any(feature = "desktop-loopback", test))]
fn callback_state_failure(states: &[String], want: &str) -> Option<&'static str> {
    match states {
        [] => Some("callback missing state"),
        [only] if only == want => None,
        [_] => Some("callback state does not match pending state"),
        _ => Some("callback carried multiple state values"),
    }
}

/// S256 code_challenge:SHA-256(verifier) → base64url 无填充。
///
/// # Examples
///
/// ```
/// use acosmi::{generate_code_verifier, code_challenge};
///
/// let verifier = generate_code_verifier();
/// let challenge = code_challenge(&verifier);
/// assert!(!challenge.is_empty());
/// assert_eq!(code_challenge(&verifier), challenge); // 同 verifier 确定性
/// ```
pub fn code_challenge(verifier: &str) -> String {
    let digest = Sha256::digest(verifier.as_bytes());
    base64url_no_pad(&digest)
}

fn base64url_no_pad(b: &[u8]) -> String {
    use base64::engine::general_purpose::URL_SAFE_NO_PAD;
    use base64::Engine as _;
    URL_SAFE_NO_PAD.encode(b)
}

// =============================================================================
// LoginWithHandler 事件模型
// =============================================================================

/// 登录流程事件类型。对应 TS `LoginEventType`。
pub const EVENT_AUTH_URL: &str = "auth_url";
pub const EVENT_COMPLETE: &str = "complete";
pub const EVENT_ERROR: &str = "error";

/// 登录错误分类码。对应 TS `LoginErrCode` 常量。
pub const ERR_DISCOVERY: &str = "discovery_failed";
pub const ERR_REGISTRATION: &str = "registration_failed";
pub const ERR_BROWSER_OPEN: &str = "browser_open_failed";
pub const ERR_AUTH_DENIED: &str = "auth_denied";
pub const ERR_TIMEOUT: &str = "auth_timeout";
pub const ERR_TOKEN_EXCHANGE: &str = "token_exchange_failed";
pub const ERR_SSL_PROXY: &str = "ssl_proxy_detected";
/// Web OAuth callback 的 state 与发起时不一致(CSRF 防护)。
pub const ERR_STATE_MISMATCH: &str = "state_mismatch";

/// 登录流程事件。对应 TS `LoginEvent`。
#[derive(Debug, Clone, Default)]
pub struct LoginEvent {
    /// 事件类型([`EVENT_AUTH_URL`] / [`EVENT_COMPLETE`] / [`EVENT_ERROR`])。
    pub r#type: String,
    /// 授权 URL(`auth_url` 事件)。
    pub url: Option<String>,
    /// 错误消息(`error` 事件)。
    pub error: Option<String>,
    /// 错误分类码(`error` 事件)。
    pub err_code: Option<String>,
}

impl LoginEvent {
    pub fn auth_url(url: impl Into<String>) -> Self {
        Self {
            r#type: EVENT_AUTH_URL.to_string(),
            url: Some(url.into()),
            ..Default::default()
        }
    }
    pub fn complete() -> Self {
        Self {
            r#type: EVENT_COMPLETE.to_string(),
            ..Default::default()
        }
    }
    pub fn error(code: impl Into<String>, error: impl Into<String>) -> Self {
        Self {
            r#type: EVENT_ERROR.to_string(),
            err_code: Some(code.into()),
            error: Some(error.into()),
            ..Default::default()
        }
    }
}

/// 登录选项(对应 TS `LoginOptions`,函数选项模式)。
#[derive(Debug, Clone, Default)]
pub struct LoginOptions {
    /// 跳过自动打开浏览器(由调用方控制浏览器)。
    pub skip_browser: bool,
    /// SSO 场景下的 email 预填。
    pub login_hint: Option<String>,
    /// 登录方法(如 `"sso"`)。
    pub login_method: Option<String>,
    /// 强制组织登录。
    pub org_uuid: Option<String>,
    /// 自定义 token 有效期(秒)。
    pub expires_in: Option<i64>,
    /// 桌面 loopback 授权成功后 302 重定向的品牌成功页 URL(替代本地 127.0.0.1 HTML)。
    ///
    /// 必须随调用方部署 origin 变化,不可硬编码单一域名;缺失 / 非法时回退本地 HTML(零回归)。
    pub success_redirect_url: Option<String>,
}

// =============================================================================
// Token Exchange
// =============================================================================

/// authorization_code 换 token。对应 TS `exchangeCode`。
pub async fn exchange_code_with_transport(
    http: &HttpClient,
    meta: &ServerMetadata,
    client_id: &str,
    code: &str,
    redirect_uri: &str,
    code_verifier: &str,
) -> Result<TokenResponse> {
    let params = [
        ("grant_type", "authorization_code"),
        ("client_id", client_id),
        ("code", code),
        ("redirect_uri", redirect_uri),
        ("code_verifier", code_verifier),
    ];
    post_token(http, &meta.token_endpoint, &params).await
}

/// 与 [`exchange_code_with_transport`] 相同,但附带 `expires_in` 参数(setup-token 模式)。
/// 对应 TS `exchangeCodeWithExpiry`(TS barrel 漏 re-export,此处补齐导出)。
pub async fn exchange_code_with_expiry_with_transport(
    http: &HttpClient,
    meta: &ServerMetadata,
    client_id: &str,
    code: &str,
    redirect_uri: &str,
    code_verifier: &str,
    expires_in: i64,
) -> Result<TokenResponse> {
    let expires_in_str = expires_in.to_string();
    let params = [
        ("grant_type", "authorization_code"),
        ("client_id", client_id),
        ("code", code),
        ("redirect_uri", redirect_uri),
        ("code_verifier", code_verifier),
        ("expires_in", expires_in_str.as_str()),
    ];
    post_token(http, &meta.token_endpoint, &params).await
}

/// 刷新 access_token。对应 TS `refreshToken`。
///
/// 轮换语义(换新撤旧)由 Client 协调:网关签发新 refresh_token,旧 RT 服务端作废。
pub async fn refresh_token_with_transport(
    http: &HttpClient,
    meta: &ServerMetadata,
    client_id: &str,
    refresh_token_value: &str,
) -> Result<TokenResponse> {
    let params = [
        ("grant_type", "refresh_token"),
        ("client_id", client_id),
        ("refresh_token", refresh_token_value),
    ];
    post_token(http, &meta.token_endpoint, &params).await
}

/// 吊销 token。服务端不支持吊销(`revocation_endpoint` 为空)时静默跳过。对应 TS `revokeToken`。
pub async fn revoke_token_with_transport(
    http: &HttpClient,
    meta: &ServerMetadata,
    token: &str,
) -> Result<()> {
    if meta.revocation_endpoint.is_empty() {
        return Ok(());
    }
    let params = [("token", token)];
    http.post(&meta.revocation_endpoint)
        .purpose(HttpPurpose::OAuthRevocation)
        .timeout(AUTH_TIMEOUT)
        .form(&params)
        .send()
        .await
        .map_err(|e| Error::other(format!("revoke: {e}")))?;
    Ok(())
}

async fn post_token(
    http: &HttpClient,
    endpoint: &str,
    params: &[(&str, &str)],
) -> Result<TokenResponse> {
    let resp = http
        .post(endpoint)
        .purpose(HttpPurpose::OAuthToken)
        .timeout(AUTH_TIMEOUT)
        .form(params)
        .send()
        .await
        .map_err(|e| Error::other(format!("token request: {e}")))?;

    if !resp.status().is_success() {
        let status = resp.status().as_u16();
        // 尽力解析 OAuth error body;失败则空串(bug-for-bug 与 TS 一致)。
        let (oauth_error, error_description) = match resp.json::<serde_json::Value>().await {
            Ok(body) => (
                body.get("error")
                    .and_then(|v| v.as_str())
                    .unwrap_or_default()
                    .to_string(),
                body.get("error_description")
                    .and_then(|v| v.as_str())
                    .unwrap_or_default()
                    .to_string(),
            ),
            Err(_) => (String::new(), String::new()),
        };
        return Err(Error::OAuthTokenEndpoint(OAuthTokenEndpointError {
            status,
            oauth_error,
            error_description,
        }));
    }

    resp.json()
        .await
        .map_err(|_| Error::other("token: decode failed"))
}

/// 从 `TokenResponse` 构造可持久化的 `TokenSet`。对应 TS `newTokenSet`。
///
/// 根因修复 #14:`expires_in=0` 会导致 token 立即过期 → 无限刷新循环。最少保证 60 秒有效期。
pub fn new_token_set(resp: &TokenResponse, client_id: &str, server_url: &str) -> TokenSet {
    let mut expires_in = resp.expires_in;
    if expires_in < 60 {
        expires_in = 60;
    }
    let expires_at = (Utc::now() + chrono::Duration::seconds(expires_in)).to_rfc3339_opts(
        chrono::SecondsFormat::Millis,
        true, // use_z:UTC 后缀 'Z',对齐 TS toISOString()。
    );
    TokenSet {
        access_token: resp.access_token.clone(),
        refresh_token: resp.refresh_token.clone().unwrap_or_default(),
        expires_at,
        scope: resp.scope.clone().unwrap_or_default(),
        client_id: client_id.to_string(),
        server_url: server_url.to_string(),
    }
}

// =============================================================================
// Web OAuth(浏览器整页重定向流程,平台无关纯逻辑)
// =============================================================================

/// Web OAuth 授权请求 —— `create_web_authorization_request` 的返回结构。对应 TS `WebAuthorizationRequest`。
///
/// 发起方应把整个对象持久化为 pending 状态(HttpOnly cookie 等),callback 回来时取出供
/// `complete_web_authorization_request` 校验。
#[derive(Debug, Clone)]
pub struct WebAuthorizationRequest {
    /// 完整授权 URL —— 浏览器整页跳转到此地址。
    pub auth_url: String,
    /// CSRF state —— callback 必须回传同值。
    pub state: String,
    /// PKCE code_verifier —— 换 token 时使用,切勿泄露给浏览器 URL。
    pub verifier: String,
    /// 动态注册得到的 client_id。
    pub client_id: String,
    /// 本次授权使用的 redirect_uri。
    pub redirect_uri: String,
    /// OAuth issuer / SDK 业务域名(用于 callback 阶段重新发现 metadata)。
    pub server_url: String,
    /// 创建时间戳(Unix 毫秒),发起方可据此实现 TTL 过期判定。
    pub created_at: i64,
}

/// `create_web_authorization_request` 参数。对应 TS `CreateWebAuthorizationRequestOptions`。
#[derive(Debug, Clone)]
pub struct CreateWebAuthorizationRequestOptions {
    /// 动态注册得到的 client_id。
    pub client_id: String,
    /// redirect_uri(须与动态注册登记的一致)。
    pub redirect_uri: String,
    /// 请求的 scope 列表 —— 以空格连接写入 auth_url。
    pub scopes: Vec<String>,
    /// OAuth issuer / SDK 业务域名。
    pub server_url: String,
    /// 可选 —— SSO 场景下预填邮箱。
    pub login_hint: Option<String>,
}

/// 构造 Web OAuth 授权请求。对应 TS `createWebAuthorizationRequest`。
///
/// 生成 PKCE verifier + S256 challenge + CSRF state,按 OAuth 2.1 拼装授权 URL
/// (含 `state` 参数 —— 桌面 `authorize` 不带 state,Web 流程必须带)。
///
/// 返回的 [`WebAuthorizationRequest`] 应整体持久化为 pending 状态,callback 阶段交给
/// `complete_web_authorization_request`。
pub fn create_web_authorization_request(
    meta: &ServerMetadata,
    opts: &CreateWebAuthorizationRequestOptions,
) -> Result<WebAuthorizationRequest> {
    let verifier = generate_code_verifier();
    let challenge = code_challenge(&verifier);
    let state = generate_state();

    let mut auth_url = url::Url::parse(&meta.authorization_endpoint).map_err(|e| {
        Error::other(format!(
            "createWebAuthorizationRequest: invalid auth endpoint: {e}"
        ))
    })?;
    {
        let mut q = auth_url.query_pairs_mut();
        q.append_pair("response_type", "code");
        q.append_pair("client_id", &opts.client_id);
        q.append_pair("redirect_uri", &opts.redirect_uri);
        q.append_pair("code_challenge", &challenge);
        q.append_pair("code_challenge_method", "S256");
        q.append_pair("state", &state);
        q.append_pair("scope", &opts.scopes.join(" "));
        if let Some(hint) = &opts.login_hint {
            q.append_pair("login_hint", hint);
        }
    }

    Ok(WebAuthorizationRequest {
        auth_url: auth_url.to_string(),
        state,
        verifier,
        client_id: opts.client_id.clone(),
        redirect_uri: opts.redirect_uri.clone(),
        server_url: opts.server_url.clone(),
        created_at: Utc::now().timestamp_millis(),
    })
}

/// `complete_web_authorization_request` 的 pending 状态([`WebAuthorizationRequest`] 的子集)。
/// 对应 TS `WebAuthorizationPending`。
#[derive(Debug, Clone)]
pub struct WebAuthorizationPending {
    pub state: String,
    pub verifier: String,
    pub client_id: String,
    pub redirect_uri: String,
    pub server_url: String,
}

/// `complete_web_authorization_request` 的 callback 参数。对应 TS `WebAuthorizationCallbackParams`。
#[derive(Debug, Clone)]
pub struct WebAuthorizationCallbackParams {
    /// 授权服务器回传的 authorization code。
    pub code: String,
    /// 授权服务器回传的 state —— 必须与 `pending.state` 一致。
    pub state: String,
}

/// 完成 Web OAuth 授权 —— 校验 state → 换 token → 返回可持久化的 `TokenSet`。
/// 对应 TS `completeWebAuthorizationRequest`。
///
/// state 不匹配时返 `Err`(CSRF 防护)。内部依次:
/// `discover_web_oauth_metadata_with_transport(pending.server_url)` → `exchange_code_with_transport(...)` → `new_token_set(...)`。
pub async fn complete_web_authorization_request_with_transport(
    http: &HttpClient,
    pending: &WebAuthorizationPending,
    params: &WebAuthorizationCallbackParams,
) -> Result<TokenSet> {
    if params.code.is_empty() {
        return Err(Error::other(
            "completeWebAuthorizationRequest: missing authorization code",
        ));
    }
    if params.state != pending.state {
        return Err(Error::other(format!(
            "completeWebAuthorizationRequest: {ERR_STATE_MISMATCH}: callback state does not match pending state (possible CSRF)"
        )));
    }

    let meta = discover_web_oauth_metadata_with_transport(http, &pending.server_url).await?;
    let resp = exchange_code_with_transport(
        http,
        &meta,
        &pending.client_id,
        &params.code,
        &pending.redirect_uri,
        &pending.verifier,
    )
    .await?;
    Ok(new_token_set(
        &resp,
        &pending.client_id,
        &pending.server_url,
    ))
}

// =============================================================================
// authorize (loopback HTTP server) —— 桌面 OAuth
// =============================================================================

/// `authorize` 的返回(授权码 + 实际 redirect_uri)。对应 TS `AuthorizeResult`。
#[derive(Debug, Clone)]
pub struct AuthorizeResult {
    pub code: String,
    pub redirect_uri: String,
}

/// 按 OAuth 2.1 PKCE 拼装授权 URL(loopback 桌面流程),**带 `state`**。
///
/// 2026-08-14 起桌面流程同样发送并校验 `state`。此前不带的理由是"本地回环天然防 CSRF",
/// 但回环监听在整个流程期间对**本机任意进程**开放:一个本地恶意进程只要往
/// `http://127.0.0.1:<port>/callback?code=<攻击者的授权码>` 打一枪,SDK 就会拿别人的授权码
/// 去换 token,把用户会话接到攻击者账号上(login-CSRF)。端口随机但可枚举。
/// 带上 32 字节随机 `state` 后,这一枪必须先猜中它。
///
/// 其余桌面专属参数(`org_uuid` / `login_method` 等)不变。
/// `#[cfg(feature = "desktop-loopback")]` 下的 `authorize` 用此 helper 构造 URL。
pub fn build_desktop_authorization_url(
    meta: &ServerMetadata,
    client_id: &str,
    redirect_uri: &str,
    challenge: &str,
    state: &str,
    scopes: &[String],
    opts: &LoginOptions,
) -> Result<String> {
    let mut auth_url = url::Url::parse(&meta.authorization_endpoint)
        .map_err(|e| Error::other(format!("authorize: invalid auth endpoint: {e}")))?;
    {
        let mut q = auth_url.query_pairs_mut();
        q.append_pair("client_id", client_id);
        q.append_pair("redirect_uri", redirect_uri);
        q.append_pair("response_type", "code");
        q.append_pair("code_challenge", challenge);
        q.append_pair("code_challenge_method", "S256");
        q.append_pair("state", state);
        if !scopes.is_empty() {
            q.append_pair("scope", &scopes.join(" "));
        }
        if let Some(hint) = &opts.login_hint {
            q.append_pair("login_hint", hint);
        }
        if let Some(method) = &opts.login_method {
            q.append_pair("login_method", method);
        }
        if let Some(org) = &opts.org_uuid {
            q.append_pair("orgUUID", org);
        }
    }
    Ok(auth_url.to_string())
}

/// 校验调用方提供的桌面授权成功页重定向 URL。对应 TS `resolveSuccessRedirect`。
///
/// 仅接受 `http(s)` 绝对 URL —— 拒绝 `javascript:` / `data:` 等其他协议(纵深防御,防开放重定向)。
/// 缺失或非法时返回 `None`,调用方据此回退本地成功 HTML。
pub fn resolve_success_redirect(raw: Option<&str>) -> Option<String> {
    let raw = raw?;
    let u = url::Url::parse(raw).ok()?;
    match u.scheme() {
        "http" | "https" => Some(u.to_string()),
        _ => None,
    }
}

#[cfg(feature = "desktop-loopback")]
pub use loopback::authorize;

#[cfg(feature = "desktop-loopback")]
mod loopback {
    use super::*;
    use tokio::io::{AsyncReadExt, AsyncWriteExt};
    use tokio::net::{TcpListener, TcpStream};
    use tokio::sync::mpsc;

    /// 每连接请求头上限(8 KB,沿用旧实现读缓冲大小);超限即静默丢弃该连接(不结算)。
    const MAX_REQUEST_HEAD: usize = 8192;
    /// 每连接读预算:慢/哑连接(端口探针、浏览器预测性预连接)最多占用一个后台任务这么久,
    /// 不影响主 accept 循环(Node headersTimeout 的近似物,取更紧的 10s)。
    const PER_CONN_READ_BUDGET: Duration = Duration::from_secs(10);

    /// HTML 转义(对应 TS `htmlEscape`)。
    fn html_escape(s: &str) -> String {
        s.replace('&', "&amp;")
            .replace('<', "&lt;")
            .replace('>', "&gt;")
            .replace('"', "&quot;")
            .replace('\'', "&#39;")
    }

    /// 执行 OAuth 2.1 PKCE 授权流程(loopback HTTP server,桌面 only)。对应 TS `authorize`。
    ///
    /// 1) 启动本地 127.0.0.1 HTTP server(随机端口)
    /// 2) 由调用方打开浏览器(`handler` 收到 `auth_url` 事件)—— 不引入 `open` dep,
    ///    SDK 只构造 URL 并发 `EVENT_AUTH_URL`;是否自动打开浏览器由调用方决定
    /// 3) 常驻多连接 accept 循环接收回调(2026-08-15,对齐 TS 常驻 server / Go net/http):
    ///    非 /callback 路径(favicon、端口探针)→ 404 后继续等待;畸形请求 → 400 后继续等待;
    ///    空/哑连接(浏览器预测性预连接)静默丢弃;只有 `/callback` 的三种终局形态
    ///    (state 失败 / 用户拒绝 / 授权码)结算,且只取首发
    /// 4) 返回 code + verifier 供后续 token 交换;成功 / 失败 / 取消一切终止路径都以
    ///    监听端口关闭收尾(TS `server.close()+closeIdleConnections()` 的对应物)
    ///
    /// 取消:传入的 `CancellationToken` 触发时返回超时错误,端口同步释放(旧实现把 listener
    /// 交给 blocking 线程,取消后该线程永久卡在 `accept()` 上:端口活到进程退出或下一个连接
    /// 被它吃掉,且 tokio runtime 关不掉——`Runtime::drop` 会一直等这个线程)。
    ///
    /// 注:TS 版在 `skip_browser=false` 时自动 spawn `open`/`xdg-open`/`rundll32`;Rust 原生
    /// 版**不内置浏览器拉起**(避免引新 dep),统一由调用方监听 `EVENT_AUTH_URL` 事件后自行打开。
    #[allow(clippy::too_many_arguments)]
    pub async fn authorize(
        meta: &ServerMetadata,
        client_id: &str,
        scopes: &[String],
        opts: &LoginOptions,
        handler: Option<&(dyn Fn(LoginEvent) + Send + Sync)>,
        signal: Option<tokio_util::sync::CancellationToken>,
    ) -> Result<(AuthorizeResult, String)> {
        let emit = |e: LoginEvent| {
            if let Some(h) = handler {
                h(e);
            }
        };

        let verifier = generate_code_verifier();
        let challenge = code_challenge(&verifier);
        // 桌面 loopback 的 CSRF 闸(见 build_desktop_authorization_url 文档)。
        let state = generate_state();

        // 1) 启动本地 callback server(异步 listener;结算/取消即 drop 释放端口)。
        let listener = TcpListener::bind("127.0.0.1:0")
            .await
            .map_err(|e| Error::other(format!("authorize: bind loopback: {e}")))?;
        let port = listener
            .local_addr()
            .map_err(|e| Error::other(format!("authorize: local_addr: {e}")))?
            .port();
        let redirect_uri = format!("http://127.0.0.1:{port}/callback");

        // 2) 构造授权 URL + 发事件。
        let auth_url = build_desktop_authorization_url(
            meta,
            client_id,
            &redirect_uri,
            &challenge,
            &state,
            scopes,
            opts,
        )?;
        emit(LoginEvent::auth_url(auth_url.clone()));

        let success_redirect = resolve_success_redirect(opts.success_redirect_url.as_deref());
        // 未传 signal = 一个永不触发的 token,收敛为单一 select 路径。
        let cancel = signal.unwrap_or_default();

        // 结算通道:容量 1 + try_send = 只取首发,后续回调(含洪泛)一律非阻塞丢弃
        // (对齐 Go settleErr;TS 靠 promise 的 settle-once)。
        let (tx, mut rx) = mpsc::channel::<Result<String>>(1);

        // 3) 多连接 accept 循环。每个连接一个后台任务,慢连接不阻塞后续 accept。
        let outcome: Result<String> = loop {
            tokio::select! {
                settled = rx.recv() => {
                    // tx 在本作用域始终存活,recv 不会返回 None;防御性兜底按超时处理。
                    break settled.unwrap_or_else(|| Err(Error::other("authorization timed out")));
                }
                accepted = listener.accept() => match accepted {
                    Ok((stream, _)) => {
                        tokio::spawn(handle_connection(
                            stream,
                            state.clone(),
                            success_redirect.clone(),
                            tx.clone(),
                        ));
                    }
                    // accept 失败视为终局(与旧实现一致;loopback 上仅资源耗尽等罕见情形)。
                    Err(e) => break Err(Error::other(format!("authorize: accept: {e}"))),
                },
                _ = cancel.cancelled() => break Err(Error::other("authorization timed out")),
            }
        };
        // 结算即停止接受新连接并释放端口。决定性响应在结算前已写完(见 handle_connection),
        // 每个响应均 Connection: close + 写后 FIN,无 idle keep-alive 滞留。
        drop(listener);

        match outcome {
            Ok(c) => Ok((
                AuthorizeResult {
                    code: c,
                    redirect_uri,
                },
                verifier,
            )),
            Err(e) => {
                let msg = e.to_string();
                // 分类顺序对齐 TS:state_mismatch → denied → timed out → 兜底 token_exchange
                // (旧实现漏 state_mismatch 分支,误报成 token_exchange)。
                let code = if msg.contains(ERR_STATE_MISMATCH) {
                    ERR_STATE_MISMATCH
                } else if msg.contains("denied") {
                    ERR_AUTH_DENIED
                } else if msg.contains("timed out") {
                    ERR_TIMEOUT
                } else {
                    ERR_TOKEN_EXCHANGE
                };
                emit(LoginEvent::error(code, msg));
                Err(e)
            }
        }
    }

    /// 单连接处理:读请求头 → 按路径分诊 → 写响应 → (仅 /callback 终局)结算。
    /// 先写后结算:结算会让 `authorize` 返回并关闭 listener,先写完保证成功/失败页必达浏览器。
    /// 非终局连接(探针/畸形/空连接)应答或丢弃后返回,登录继续等待。
    async fn handle_connection(
        mut stream: TcpStream,
        state: String,
        success_redirect: Option<String>,
        tx: mpsc::Sender<Result<String>>,
    ) {
        // 读不出请求头(空连接、慢连接超预算、超 8KB、IO 错)→ 静默丢弃。
        // Chrome 的预测性预连接就是"连上不发字节再断开",绝不能当成回调处理。
        let Some(head) = read_request_head(&mut stream).await else {
            return;
        };
        let path = head.split_whitespace().nth(1).unwrap_or("/").to_string();

        // 解析 query。基址仅用于相对路径解析。
        let full = format!("http://127.0.0.1{path}");
        let Ok(parsed) = url::Url::parse(&full) else {
            write_http(&mut stream, 400, "text/plain", "").await;
            return;
        };
        if parsed.path() != "/callback" {
            write_http(&mut stream, 404, "text/plain", "").await;
            return;
        }
        let mut code: Option<String> = None;
        let mut states: Vec<String> = Vec::new();
        let mut err_desc = String::new();
        let mut err_code = String::new();
        for (k, v) in parsed.query_pairs() {
            match k.as_ref() {
                "code" => code = Some(v.to_string()),
                "state" => states.push(v.to_string()),
                "error_description" => err_desc = v.to_string(),
                "error" => err_code = v.to_string(),
                _ => {}
            }
        }

        // state 校验对 /callback 的**每一种**形态先行 —— 成功回调、OAuth error 回调、
        // 畸形回调一视同仁, 且必须在消费 code / 结算 denied **之前**。否则本机任意进程
        // 不猜 state 也能伪造一发 ?error=access_denied 把等待中的登录打成"用户已拒绝"。
        // "恰好一个": 重复 state 参数不允许蒙混 (此前循环取末值), 缺失与错值同罪。
        // 错误信息只描述形态, 不回显任何回调取值。
        if let Some(reason) = callback_state_failure(&states, &state) {
            write_http(
                &mut stream,
                200,
                "text/html; charset=utf-8",
                "<!DOCTYPE html><html><head><meta charset=\"utf-8\"><title>授权失败</title></head>\
                 <body style=\"font-family:system-ui,sans-serif;text-align:center;padding:60px 20px\">\
                 <h2>授权失败</h2><p>回调校验未通过, 已中止登录。</p>\
                 <p style=\"color:#888;font-size:14px\">可以关闭此窗口。</p></body></html>",
            )
            .await;
            let _ = tx.try_send(Err(Error::other(format!(
                "authorize: {ERR_STATE_MISMATCH}: {reason} (possible CSRF)"
            ))));
            return;
        }

        match code {
            Some(c) => {
                // 成功页:品牌 302 或本地 HTML。
                if let Some(redir) = &success_redirect {
                    let resp = format!(
                        "HTTP/1.1 302 Found\r\nLocation: {redir}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
                    );
                    let _ = stream.write_all(resp.as_bytes()).await;
                    let _ = stream.shutdown().await;
                } else {
                    let html = "<!DOCTYPE html><html><head><meta charset=\"utf-8\"><title>授权成功</title></head>\
                        <body style=\"font-family:system-ui,sans-serif;text-align:center;padding:60px 20px\">\
                        <h2>授权成功</h2><p>已完成身份认证, 请返回应用继续使用。</p>\
                        <p style=\"color:#888;font-size:14px\">此窗口将在 3 秒后自动关闭…</p>\
                        <script>setTimeout(function(){window.close()},3000)</script></body></html>";
                    write_http(&mut stream, 200, "text/html; charset=utf-8", html).await;
                }
                let _ = tx.try_send(Ok(c));
            }
            None => {
                let msg = if !err_desc.is_empty() {
                    err_desc
                } else {
                    err_code
                };
                let html = format!(
                    "<!DOCTYPE html><html><head><meta charset=\"utf-8\"><title>授权失败</title></head>\
                    <body style=\"font-family:system-ui,sans-serif;text-align:center;padding:60px 20px\">\
                    <h2>授权失败</h2><p>{}</p>\
                    <p style=\"color:#888;font-size:14px\">可以关闭此窗口。</p></body></html>",
                    html_escape(&msg)
                );
                write_http(&mut stream, 200, "text/html; charset=utf-8", &html).await;
                let _ = tx.try_send(Err(Error::other(format!("authorization denied: {msg}"))));
            }
        }
    }

    /// 读满请求头(到 `\r\n\r\n` 或 EOF),8KB 上限 + 10s 预算。
    /// 超限 / 超时 / IO 错 / 空连接 → `None`(调用方静默丢弃,不结算)。
    /// 只消费请求头即可:OAuth 回调是 GET;POST body 不消费与 Node 行为一致。
    async fn read_request_head(stream: &mut TcpStream) -> Option<String> {
        let fut = async {
            let mut buf: Vec<u8> = Vec::with_capacity(1024);
            let mut chunk = [0u8; 1024];
            loop {
                let n = stream.read(&mut chunk).await.ok()?;
                if n == 0 {
                    break;
                }
                buf.extend_from_slice(&chunk[..n]);
                if buf.windows(4).any(|w| w == b"\r\n\r\n") {
                    break;
                }
                if buf.len() >= MAX_REQUEST_HEAD {
                    return None;
                }
            }
            if buf.is_empty() {
                None
            } else {
                Some(String::from_utf8_lossy(&buf).into_owned())
            }
        };
        tokio::time::timeout(PER_CONN_READ_BUDGET, fut)
            .await
            .ok()
            .flatten()
    }

    async fn write_http(stream: &mut TcpStream, status: u16, content_type: &str, body: &str) {
        let reason = match status {
            200 => "OK",
            400 => "Bad Request",
            404 => "Not Found",
            _ => "OK",
        };
        let resp = format!(
            "HTTP/1.1 {status} {reason}\r\nContent-Type: {content_type}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
            body.len()
        );
        let _ = stream.write_all(resp.as_bytes()).await;
        // FIN:请求头已消费完毕,无 RST 截断响应之虞。
        let _ = stream.shutdown().await;
    }
}

/// Compatibility entry point using the supplied reqwest client.
#[cfg(feature = "native-http")]
pub async fn discover_with_profile(
    http: &reqwest::Client,
    server_url: &str,
    profile: OAuthMetadataProfile,
) -> Result<ServerMetadata> {
    discover_with_profile_with_transport(&HttpClient::legacy(http.clone()), server_url, profile)
        .await
}

/// Compatibility entry point using the supplied reqwest client.
#[cfg(feature = "native-http")]
pub async fn discover_web_oauth_metadata(
    http: &reqwest::Client,
    server_url: &str,
) -> Result<ServerMetadata> {
    discover_web_oauth_metadata_with_transport(&HttpClient::legacy(http.clone()), server_url).await
}

/// Compatibility entry point using the supplied reqwest client.
#[cfg(feature = "native-http")]
pub async fn register(
    http: &reqwest::Client,
    meta: &ServerMetadata,
    app_name: &str,
) -> Result<ClientRegistration> {
    register_with_transport(&HttpClient::legacy(http.clone()), meta, app_name).await
}

/// Compatibility entry point using the supplied reqwest client.
#[cfg(feature = "native-http")]
pub async fn register_web_oauth_client(
    http: &reqwest::Client,
    meta: &ServerMetadata,
    opts: &RegisterWebOAuthClientOptions,
) -> Result<ClientRegistration> {
    register_web_oauth_client_with_transport(&HttpClient::legacy(http.clone()), meta, opts).await
}

/// Compatibility entry point using the supplied reqwest client.
#[cfg(feature = "native-http")]
pub async fn exchange_code(
    http: &reqwest::Client,
    meta: &ServerMetadata,
    client_id: &str,
    code: &str,
    redirect_uri: &str,
    code_verifier: &str,
) -> Result<TokenResponse> {
    exchange_code_with_transport(
        &HttpClient::legacy(http.clone()),
        meta,
        client_id,
        code,
        redirect_uri,
        code_verifier,
    )
    .await
}

/// Compatibility entry point using the supplied reqwest client.
#[cfg(feature = "native-http")]
pub async fn exchange_code_with_expiry(
    http: &reqwest::Client,
    meta: &ServerMetadata,
    client_id: &str,
    code: &str,
    redirect_uri: &str,
    code_verifier: &str,
    expires_in: i64,
) -> Result<TokenResponse> {
    exchange_code_with_expiry_with_transport(
        &HttpClient::legacy(http.clone()),
        meta,
        client_id,
        code,
        redirect_uri,
        code_verifier,
        expires_in,
    )
    .await
}

/// Compatibility entry point using the supplied reqwest client.
#[cfg(feature = "native-http")]
pub async fn refresh_token(
    http: &reqwest::Client,
    meta: &ServerMetadata,
    client_id: &str,
    refresh_token_value: &str,
) -> Result<TokenResponse> {
    refresh_token_with_transport(
        &HttpClient::legacy(http.clone()),
        meta,
        client_id,
        refresh_token_value,
    )
    .await
}

/// Compatibility entry point using the supplied reqwest client.
#[cfg(feature = "native-http")]
pub async fn revoke_token(
    http: &reqwest::Client,
    meta: &ServerMetadata,
    token: &str,
) -> Result<()> {
    revoke_token_with_transport(&HttpClient::legacy(http.clone()), meta, token).await
}

/// Compatibility entry point using the supplied reqwest client.
#[cfg(feature = "native-http")]
pub async fn complete_web_authorization_request(
    http: &reqwest::Client,
    pending: &WebAuthorizationPending,
    params: &WebAuthorizationCallbackParams,
) -> Result<TokenSet> {
    complete_web_authorization_request_with_transport(
        &HttpClient::legacy(http.clone()),
        pending,
        params,
    )
    .await
}

impl std::fmt::Debug for OAuthTokenEndpointError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("OAuthTokenEndpointError")
            .field("status", &self.status)
            .finish_non_exhaustive()
    }
}

/// Discover using the supplied reqwest client (legacy compatible entry point).
#[cfg(feature = "native-http")]
pub async fn discover(http: &reqwest::Client, server_url: &str) -> Result<ServerMetadata> {
    discover_with_transport(&HttpClient::legacy(http.clone()), server_url).await
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn pkce_challenge_matches_rfc7636_vector() {
        // RFC 7636 Appendix B 测试向量。
        let verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
        let challenge = code_challenge(verifier);
        assert_eq!(challenge, "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM");
    }

    #[test]
    fn verifier_and_state_are_base64url_43_chars() {
        // 32 字节 base64url 无填充 = 43 字符。
        let v = generate_code_verifier();
        let s = generate_state();
        assert_eq!(v.len(), 43);
        assert_eq!(s.len(), 43);
        assert!(!v.contains('+') && !v.contains('/') && !v.contains('='));
        assert_ne!(v, s); // 两次调用应不同(极高概率)。
    }

    #[test]
    fn new_token_set_floors_short_expiry_to_60s() {
        let resp = TokenResponse {
            access_token: "at".into(),
            token_type: "Bearer".into(),
            expires_in: 0, // 应被 floor 到 60s(防无限刷新)。
            refresh_token: Some("rt".into()),
            scope: Some("ai".into()),
        };
        let ts = new_token_set(&resp, "cid", "https://acosmi.com");
        assert_eq!(ts.client_id, "cid");
        assert_eq!(ts.refresh_token, "rt");
        // expires_at 应是有效 RFC3339 且在未来。
        let parsed = chrono::DateTime::parse_from_rfc3339(&ts.expires_at).unwrap();
        assert!(parsed > Utc::now());
        // 'Z' 后缀(对齐 toISOString)。
        assert!(ts.expires_at.ends_with('Z'));
    }

    #[test]
    fn new_token_set_missing_refresh_and_scope_default_empty() {
        let resp = TokenResponse {
            access_token: "at".into(),
            token_type: "Bearer".into(),
            expires_in: 3600,
            refresh_token: None,
            scope: None,
        };
        let ts = new_token_set(&resp, "cid", "https://acosmi.com");
        assert_eq!(ts.refresh_token, "");
        assert_eq!(ts.scope, "");
    }

    #[test]
    fn resolve_success_redirect_rejects_non_http() {
        assert!(resolve_success_redirect(None).is_none());
        assert!(resolve_success_redirect(Some("javascript:alert(1)")).is_none());
        assert!(resolve_success_redirect(Some("data:text/html,x")).is_none());
        assert!(resolve_success_redirect(Some("not a url")).is_none());
        assert!(resolve_success_redirect(Some("https://acosmi.com/ok")).is_some());
        assert!(resolve_success_redirect(Some("http://127.0.0.1/cb")).is_some());
    }

    #[test]
    fn is_invalid_grant_detects_oauth_error() {
        let e = Error::OAuthTokenEndpoint(OAuthTokenEndpointError {
            status: 400,
            oauth_error: "invalid_grant".into(),
            error_description: "refresh token not found".into(),
        });
        assert!(is_invalid_grant_error(&e));
        let other = Error::other("nope");
        assert!(!is_invalid_grant_error(&other));
    }

    #[test]
    fn build_desktop_authorization_url_has_pkce_params() {
        let meta = ServerMetadata {
            issuer: "https://acosmi.com".into(),
            authorization_endpoint: "https://acosmi.com/oauth/authorize".into(),
            token_endpoint: "https://acosmi.com/oauth/token".into(),
            revocation_endpoint: String::new(),
            registration_endpoint: "https://acosmi.com/oauth/register".into(),
            scopes_supported: vec![],
        };
        let opts = LoginOptions {
            login_hint: Some("a@b.com".into()),
            org_uuid: Some("org1".into()),
            ..Default::default()
        };
        let url = build_desktop_authorization_url(
            &meta,
            "cid",
            "http://127.0.0.1:1234/callback",
            "CHAL",
            "STATE123",
            &["ai".to_string(), "skills".to_string()],
            &opts,
        )
        .unwrap();
        assert!(url.contains("code_challenge=CHAL"));
        assert!(url.contains("code_challenge_method=S256"));
        assert!(url.contains("client_id=cid"));
        assert!(url.contains("scope=ai+skills"));
        assert!(url.contains("login_hint=a%40b.com"));
        assert!(url.contains("orgUUID=org1"));
        // 2026-08-14: 桌面流程**必须**带 state(此前钉死的是相反断言,见
        // build_desktop_authorization_url 文档中的 login-CSRF 说明)。
        assert!(url.contains("state=STATE123"));
    }

    #[test]
    fn generate_state_is_random_and_url_safe() {
        let a = generate_state();
        let b = generate_state();
        assert_ne!(a, b, "state 必须每次不同, 否则起不到 CSRF 防护作用");
        // base64url 无填充: 32 字节 → 43 字符, 且只含 URL 安全字符。
        assert_eq!(a.len(), 43);
        assert!(a
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_'));
    }

    /// [2026-08-15] loopback callback state 判定矩阵 (与 TS/Go 同契约): 恰好一个且严格相等;
    /// 缺失 / 重复 (含重复的正确值) / 错值一律拒绝, 且失败原因不回显取值。
    #[test]
    fn callback_state_failure_matrix() {
        let want = "S-correct";
        let s = |v: &str| v.to_string();

        assert_eq!(
            callback_state_failure(&[s(want)], want),
            None,
            "唯一且相等 → 放行"
        );
        assert_eq!(
            callback_state_failure(&[], want),
            Some("callback missing state"),
            "缺失 → 拒绝 (OAuth error 回调不带 state 同样走此路, 不得结算成 auth_denied)"
        );
        assert_eq!(
            callback_state_failure(&[s("S-wrong")], want),
            Some("callback state does not match pending state")
        );
        assert_eq!(
            callback_state_failure(&[s(want), s("S-wrong")], want),
            Some("callback carried multiple state values"),
            "首值正确也不放行 —— 修复前循环取末值, 攻击者可用 ?state=<猜>&state=<junk> 蒙混"
        );
        assert_eq!(
            callback_state_failure(&[s(want), s(want)], want),
            Some("callback carried multiple state values"),
            "重复的正确值也不是'恰好一个'"
        );
    }
}