wiremux-auth 0.10.0

Wiremux TokenProvider, vendor profile catalog, and pasteable OAuth packs.
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
//! Profile AST (data only). No IR.

use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

use serde::de::Error as _;
use serde::{Deserialize, Deserializer, Serialize, Serializer};

use super::error::ProfileError;

/// Highest `schema_version` this crate understands.
pub const SCHEMA_VERSION_MAX: u32 = 1;

/// Catalog load inputs. Same-id layers merge field-wise
/// (shipped < user dir < explicit file).
#[derive(Debug, Clone)]
pub struct LoadOptions<'a> {
    /// Optional id hint (required unless an explicit file supplies `id`).
    pub id: Option<&'a str>,
    /// Extra file to include, keyed by its document `id`.
    pub explicit_file: Option<&'a Path>,
    /// Extra directories of profile files (`WIREMUX_PROFILE_DIR`).
    pub extra_profile_dirs: Vec<PathBuf>,
    /// When false, skip crate-shipped presets.
    pub include_shipped: bool,
    /// When false, skip XDG/HOME user dirs and `WIREMUX_PROFILE_DIR`.
    pub include_user_config: bool,
}

impl Default for LoadOptions<'_> {
    fn default() -> Self {
        Self {
            id: None,
            explicit_file: None,
            extra_profile_dirs: Vec::new(),
            include_shipped: true,
            include_user_config: true,
        }
    }
}

/// Fully resolved profile document (one `id`).
#[derive(Debug, Clone, PartialEq)]
pub struct ResolvedProfile {
    /// Schema version after parse (`<= SCHEMA_VERSION_MAX`).
    pub schema_version: u32,
    /// Stable catalog key.
    pub id: String,
    /// Optional human label.
    pub display_name: Option<String>,
    /// Dialect table (root-level fields in the file).
    pub dialect: Dialect,
    /// HTTP table (root-level fields in the file).
    pub http: Http,
    /// Optional OAuth pack.
    pub oauth: Option<OauthPack>,
    /// Env names for a static key when `[oauth]` is absent. First non-empty wins.
    pub access_env: Vec<String>,
    /// Optional fingerprint table.
    pub fingerprint: Option<Fingerprint>,
    /// Beta header list and merge policy.
    pub betas: Betas,
}

/// Dialect selection and stream/tool policies.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Dialect {
    /// `chat-completions` | `messages` | `responses` | `gemini` | `converse`.
    pub wire: Option<Wire>,
    /// Recognized SSE event names (built-in list when omitted).
    pub stream_events: Vec<String>,
    /// Merge policy for `stream_events` (and `oauth.scopes` when set there).
    pub list_merge: ListMerge,
    /// How to treat namespaced / hosted tool types.
    pub tool_type_policy: ToolTypePolicy,
    /// How to treat unrecognized stream events.
    pub stream_unknown_policy: StreamUnknownPolicy,
}

/// v1 wire dialects. Not a host registry name.
///
/// New dialects may be added in a minor release. Hosts must include a
/// `_` arm so an additive variant is not a compile break:
///
/// ```
/// use wiremux_auth::Wire;
///
/// fn host_label(wire: Wire) -> &'static str {
///     match wire {
///         Wire::ChatCompletions => "chat-completions",
///         Wire::Messages => "messages",
///         Wire::Responses => "responses",
///         Wire::Gemini => "gemini",
///         Wire::Converse => "converse",
///         _ => "unknown",
///     }
/// }
/// assert_eq!(host_label(Wire::Messages), "messages");
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[non_exhaustive]
#[serde(rename_all = "kebab-case")]
pub enum Wire {
    /// OpenAI Chat Completions.
    ChatCompletions,
    /// Anthropic Messages.
    Messages,
    /// OpenAI Responses.
    Responses,
    /// Google Gemini generateContent.
    Gemini,
    /// Amazon Bedrock Converse.
    Converse,
}

impl Wire {
    /// Catalog spellings. CLI `--from` also accepts `chat` for `chat-completions`.
    pub const NAMES: &'static [&'static str] = &[
        "chat-completions",
        "messages",
        "responses",
        "gemini",
        "converse",
    ];

    /// Catalog / file spelling (`messages`, `chat-completions`, `responses`, `gemini`, `converse`).
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::ChatCompletions => "chat-completions",
            Self::Messages => "messages",
            Self::Responses => "responses",
            Self::Gemini => "gemini",
            Self::Converse => "converse",
        }
    }

    pub(crate) fn parse(s: &str) -> Result<Self, String> {
        match s {
            "chat-completions" => Ok(Self::ChatCompletions),
            "messages" => Ok(Self::Messages),
            "responses" => Ok(Self::Responses),
            "gemini" => Ok(Self::Gemini),
            "converse" => Ok(Self::Converse),
            other => Err(unknown_kebab("wire", other, Self::NAMES)),
        }
    }

    /// Close match after folding case and `_`/`-`.
    #[must_use]
    pub fn suggest(s: &str) -> Option<&'static str> {
        suggest_kebab(s, Self::NAMES)
    }

    /// Built-in SSE event names when `stream_events` is omitted.
    #[must_use]
    pub fn default_stream_events(self) -> &'static [&'static str] {
        match self {
            Self::ChatCompletions => &["chunk", "[DONE]"],
            Self::Messages => &[
                "message_start",
                "content_block_start",
                "content_block_delta",
                "content_block_stop",
                "message_delta",
                "message_stop",
                "ping",
                "error",
            ],
            Self::Responses => &[
                "response.created",
                "response.in_progress",
                "response.output_item.added",
                "response.content_part.added",
                "response.output_text.delta",
                "response.reasoning_summary_text.delta",
                "response.reasoning.delta",
                "response.refusal.delta",
                "response.output_text.annotation.added",
                "response.audio.delta",
                "response.audio.transcript.delta",
                "response.function_call_arguments.delta",
                "response.custom_tool_call_input.delta",
                "response.output_item.done",
                "response.completed",
                "response.failed",
                "response.incomplete",
            ],
            Self::Gemini => &["chunk"],
            Self::Converse => &[
                "messageStart",
                "contentBlockStart",
                "contentBlockDelta",
                "contentBlockStop",
                "messageStop",
                "metadata",
            ],
        }
    }

    /// Dialect default chat path.
    #[must_use]
    pub fn default_chat_path(self) -> &'static str {
        match self {
            Self::ChatCompletions => "/v1/chat/completions",
            Self::Messages => "/v1/messages",
            Self::Responses => "/v1/responses",
            Self::Gemini => "/v1beta/models/{model}:generateContent",
            Self::Converse => "/model/{model}/converse",
        }
    }

    /// Dialect default auth scheme.
    #[must_use]
    pub fn default_auth_scheme(self) -> AuthScheme {
        match self {
            Self::Messages => AuthScheme::XApiKey,
            Self::Gemini => AuthScheme::Header("x-goog-api-key".into()),
            Self::ChatCompletions | Self::Responses | Self::Converse => AuthScheme::Bearer,
        }
    }
}

impl<'de> Deserialize<'de> for Wire {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        deserialize_kebab(deserializer, Self::parse)
    }
}

/// List merge policy. `verbatim` is an alias of `replace`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum ListMerge {
    /// Later items overlay; earlier unique values remain.
    #[default]
    Union,
    /// Later list or map is the entire set.
    Replace,
}

impl ListMerge {
    pub(crate) fn parse(s: &str) -> Result<Self, String> {
        match s {
            "union" => Ok(Self::Union),
            "replace" | "verbatim" => Ok(Self::Replace),
            other => Err(unknown_kebab(
                "list_merge",
                other,
                &["union", "replace", "verbatim"],
            )),
        }
    }
}

impl<'de> Deserialize<'de> for ListMerge {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        deserialize_kebab(deserializer, Self::parse)
    }
}

/// How encode treats unknown / namespaced tool types.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum ToolTypePolicy {
    /// Forward the tool type as-is.
    Passthrough,
    /// Flatten `namespace.tool` into the target dialect.
    FlattenNamespace,
    /// Fail the map.
    #[default]
    HardError,
}

impl ToolTypePolicy {
    pub(crate) fn parse(s: &str) -> Result<Self, String> {
        match s {
            "passthrough" => Ok(Self::Passthrough),
            "flatten-namespace" => Ok(Self::FlattenNamespace),
            "hard-error" => Ok(Self::HardError),
            other => Err(unknown_kebab(
                "tool_type_policy",
                other,
                &["passthrough", "flatten-namespace", "hard-error"],
            )),
        }
    }
}

impl<'de> Deserialize<'de> for ToolTypePolicy {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        deserialize_kebab(deserializer, Self::parse)
    }
}

/// How decode treats unrecognized SSE events.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum StreamUnknownPolicy {
    /// Fail the map.
    #[default]
    HardError,
    /// Forward the raw SSE frame.
    Passthrough,
}

impl StreamUnknownPolicy {
    pub(crate) fn parse(s: &str) -> Result<Self, String> {
        match s {
            "hard-error" => Ok(Self::HardError),
            "passthrough" => Ok(Self::Passthrough),
            other => Err(unknown_kebab(
                "stream_unknown_policy",
                other,
                &["hard-error", "passthrough"],
            )),
        }
    }
}

impl<'de> Deserialize<'de> for StreamUnknownPolicy {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        deserialize_kebab(deserializer, Self::parse)
    }
}

/// HTTP request surface (API calls, not the token POST).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Http {
    /// `https` or loopback `http`.
    pub base_url: Option<String>,
    /// Request path, or an absolute URL.
    pub chat_path: Option<String>,
    /// How the access token is sent.
    pub auth_scheme: Option<AuthScheme>,
    /// Extra API headers (after env subst).
    pub headers: BTreeMap<String, String>,
    /// Merge policy for `headers`.
    pub header_merge: ListMerge,
    /// When set (`bedrock`), the HTTP client SigV4-signs the POST.
    pub aws_service: Option<String>,
    /// Region for SigV4 (`us-east-1`). `{env:AWS_REGION}` is allowed.
    pub aws_region: Option<String>,
    /// Env that holds a GCP service-account JSON path (`GOOGLE_APPLICATION_CREDENTIALS`).
    pub gcp_key_env: Option<String>,
    /// Idle-read timeout in seconds for API calls. Default 120 when unset.
    pub read_timeout_secs: Option<u64>,
}

/// API auth scheme. `none` sends no `Authorization` and no `x-api-key`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AuthScheme {
    /// `Authorization: Bearer <token>`.
    Bearer,
    /// `x-api-key: <token>`.
    XApiKey,
    /// Named header (`header:<name>`).
    Header(String),
    /// No auth header.
    None,
}

impl AuthScheme {
    pub(crate) fn parse(s: &str) -> Result<Self, ProfileError> {
        if let Some(name) = s.strip_prefix("header:") {
            if name.is_empty() {
                return Err(ProfileError::Parse(
                    "auth_scheme header: requires a header name".into(),
                ));
            }
            return Ok(Self::Header(name.to_string()));
        }
        match s {
            "bearer" => Ok(Self::Bearer),
            "x-api-key" => Ok(Self::XApiKey),
            "none" => Ok(Self::None),
            other => {
                let listed = "bearer|x-api-key|none|header:<name>";
                let mut msg = format!("unknown auth_scheme `{other}` ({listed})");
                if let Some(suggest) = suggest_auth_scheme(other) {
                    msg.push_str(&format!("; did you mean `{suggest}`"));
                }
                Err(ProfileError::Parse(msg))
            }
        }
    }
}

const AUTH_SCHEME_NAMES: &[&str] = &["bearer", "x-api-key", "none", "header:<name>"];

fn suggest_auth_scheme(s: &str) -> Option<&'static str> {
    suggest_kebab(s, AUTH_SCHEME_NAMES)
}

fn fold_enum_key(s: &str) -> String {
    s.to_ascii_lowercase().replace(['_', '-'], "")
}

/// Folded exact match, else edit distance <= 2, else a unique prefix/suffix.
pub(crate) fn suggest_kebab<'a>(input: &str, legal: &[&'a str]) -> Option<&'a str> {
    let folded = fold_enum_key(input);
    if folded.is_empty() {
        return None;
    }
    let mut best: Option<(&'a str, usize)> = None;
    let mut prefix = Vec::new();
    for &opt in legal {
        let candidate = fold_enum_key(opt);
        if candidate == folded {
            return Some(opt);
        }
        let dist = edit_distance(&folded, &candidate);
        if dist > 0 && dist <= 2 {
            match best {
                None => best = Some((opt, dist)),
                Some((_, best_dist)) if dist < best_dist => best = Some((opt, dist)),
                Some((best_opt, best_dist)) if dist == best_dist && opt.len() > best_opt.len() => {
                    best = Some((opt, dist));
                }
                _ => {}
            }
        }
        if candidate.starts_with(&folded)
            || folded.starts_with(&candidate)
            || candidate.ends_with(&folded)
            || folded.ends_with(&candidate)
        {
            prefix.push(opt);
        }
    }
    if let Some((opt, _)) = best {
        return Some(opt);
    }
    match prefix.as_slice() {
        [only] => Some(*only),
        _ => None,
    }
}

fn edit_distance(a: &str, b: &str) -> usize {
    let a: Vec<char> = a.chars().collect();
    let b: Vec<char> = b.chars().collect();
    let mut prev: Vec<usize> = (0..=b.len()).collect();
    let mut cur = vec![0; b.len() + 1];
    for (i, ca) in a.iter().enumerate() {
        cur[0] = i + 1;
        for (j, cb) in b.iter().enumerate() {
            let cost = usize::from(ca != cb);
            cur[j + 1] = (prev[j + 1] + 1).min(cur[j] + 1).min(prev[j] + cost);
        }
        std::mem::swap(&mut prev, &mut cur);
    }
    prev[b.len()]
}

fn unknown_kebab(field: &str, got: &str, legal: &[&str]) -> String {
    let listed = legal.join("|");
    let mut msg = format!("unknown {field} `{got}` ({listed})");
    if let Some(suggest) = suggest_kebab(got, legal) {
        msg.push_str(&format!("; did you mean `{suggest}`"));
    }
    msg
}

fn deserialize_kebab<'de, T, D>(
    deserializer: D,
    parse: fn(&str) -> Result<T, String>,
) -> Result<T, D::Error>
where
    D: Deserializer<'de>,
{
    let s = String::deserialize(deserializer)?;
    parse(&s).map_err(D::Error::custom)
}

impl<'de> Deserialize<'de> for AuthScheme {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let s = String::deserialize(deserializer)?;
        Self::parse(&s).map_err(D::Error::custom)
    }
}

impl Serialize for AuthScheme {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let owned: String;
        let s = match self {
            Self::Bearer => "bearer",
            Self::XApiKey => "x-api-key",
            Self::Header(name) => {
                owned = format!("header:{name}");
                owned.as_str()
            }
            Self::None => "none",
        };
        serializer.serialize_str(s)
    }
}

/// The `[oauth]` table: token POST and login surface.
#[derive(Debug, Clone, PartialEq)]
pub struct OauthPack {
    /// Token endpoint. Required when `[oauth]` is present.
    pub token_url: String,
    /// Used only on HTTP 404 from `token_url`.
    pub token_url_fallback: Option<String>,
    /// Authorize URL. Absent means no login in this profile.
    pub authorize_url: Option<String>,
    /// Extra authorize query parameters.
    pub authorize_params: BTreeMap<String, String>,
    /// Device-flow endpoint.
    pub device_auth_url: Option<String>,
    /// Public client id. May be empty; login then exits 2.
    pub client_id: Option<String>,
    /// PKCE loopback redirect.
    pub redirect_uri: Option<String>,
    /// OAuth scopes.
    pub scopes: Vec<String>,
    /// Merge policy for `scopes`.
    pub list_merge: ListMerge,
    /// PKCE flag. Default true when `authorize_url` is set.
    pub pkce: Option<bool>,
    /// `grant_type` when `refresh_body` omits it.
    pub refresh_grant: Option<String>,
    /// Extra token-POST body fields (data only).
    pub refresh_body: BTreeMap<String, String>,
    /// Token POST encoding.
    pub token_request_format: Option<TokenRequestFormat>,
    /// Headers on the token POST only.
    pub token_headers: BTreeMap<String, String>,
    /// Credential store path (`~` and `{env:}` allowed).
    pub creds_path: Option<String>,
    /// How to read/write the credential store.
    pub creds_format: Option<CredsFormat>,
    /// JSON Pointer into the store for the access token.
    pub access_token_ptr: Option<String>,
    /// JSON Pointer into the store for the refresh token.
    pub refresh_token_ptr: Option<String>,
    /// JSON Pointer into the store for expiry.
    pub expires_ptr: Option<String>,
    /// Unit of the store expiry field.
    pub expires_unit: Option<ExpiresUnit>,
    /// Env fallback for the access token.
    pub access_env: Option<String>,
    /// Login mode.
    pub login: Option<Login>,
    /// Free text printed for `login = "setup-token"`. Backticks allowed.
    pub setup_token_hint: Option<String>,
    /// Optional macOS keychain service.
    pub keychain_service: Option<String>,
    /// Optional keychain account names.
    pub keychain_accounts: Vec<String>,
    /// Pointers into the HTTP refresh response (not the store).
    pub token_response: Option<TokenResponse>,
}

/// `[oauth.token_response]` pointers into the refresh HTTP body.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TokenResponse {
    /// Access token pointer. RFC 6749 default `/access_token`.
    pub access_token_ptr: Option<String>,
    /// Refresh token pointer. RFC 6749 default `/refresh_token`.
    pub refresh_token_ptr: Option<String>,
    /// Expiry pointer. RFC 6749 default `/expires_in`.
    pub expires_ptr: Option<String>,
    /// Expiry unit. RFC 6749 default `s`.
    pub expires_unit: Option<ExpiresUnit>,
}

/// Token POST body encoding.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum TokenRequestFormat {
    /// JSON body (Anthropic).
    Json,
    /// Form body (typical OIDC).
    Form,
}

impl TokenRequestFormat {
    pub(crate) fn parse(s: &str) -> Result<Self, String> {
        match s {
            "json" => Ok(Self::Json),
            "form" => Ok(Self::Form),
            other => Err(unknown_kebab(
                "token_request_format",
                other,
                &["json", "form"],
            )),
        }
    }
}

impl<'de> Deserialize<'de> for TokenRequestFormat {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        deserialize_kebab(deserializer, Self::parse)
    }
}

/// Named credential-store layouts.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum CredsFormat {
    /// Explicit JSON Pointers on the pack.
    JsonPointer,
    /// Claude credentials.json alias map.
    ClaudeCredentials,
    /// Named `{issuer}::{client_id}` object inside an auth.json.
    ///
    /// Pointers: `/{issuer}::{client_id}/key` (access), `/refresh_token`,
    /// `/expires_at` (RFC 3339). `issuer` is the origin of `authorize_url`,
    /// else `token_url`. A `{issuer}::{client_id}@{name}` suffix matches
    /// when the exact key is absent. Empty `client_id` matches the single
    /// `{issuer}::` entry; two or more issuer entries fail closed.
    OidcAuthJson,
    /// GitHub Copilot `hosts.json` / `apps.json` layout.
    ///
    /// Pointer: `/{host}/oauth_token` (first object that has a non-empty
    /// token; default host `github.com`). GitHub Copilot product terms
    /// apply to the token. This crate does not ship a Copilot preset.
    CopilotHosts,
}

impl CredsFormat {
    pub(crate) fn parse(s: &str) -> Result<Self, String> {
        match s {
            "json-pointer" => Ok(Self::JsonPointer),
            "claude-credentials" => Ok(Self::ClaudeCredentials),
            "oidc-auth-json" => Ok(Self::OidcAuthJson),
            "copilot-hosts" => Ok(Self::CopilotHosts),
            other => Err(unknown_kebab(
                "creds_format",
                other,
                &[
                    "json-pointer",
                    "claude-credentials",
                    "oidc-auth-json",
                    "copilot-hosts",
                ],
            )),
        }
    }
}

impl<'de> Deserialize<'de> for CredsFormat {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        deserialize_kebab(deserializer, Self::parse)
    }
}

/// Expiry field unit.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum ExpiresUnit {
    /// Milliseconds since epoch (Claude credentials).
    Ms,
    /// Seconds (`expires_in` / unix time).
    S,
}

impl ExpiresUnit {
    pub(crate) fn parse(s: &str) -> Result<Self, String> {
        match s {
            "ms" => Ok(Self::Ms),
            "s" => Ok(Self::S),
            other => Err(unknown_kebab("expires_unit", other, &["ms", "s"])),
        }
    }
}

impl<'de> Deserialize<'de> for ExpiresUnit {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        deserialize_kebab(deserializer, Self::parse)
    }
}

/// Login engine selection.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum Login {
    /// Print `setup_token_hint` and exit 2.
    SetupToken,
    /// PKCE loopback.
    Pkce,
    /// Device authorization grant.
    Device,
    /// Not ready / disabled.
    None,
}

impl Login {
    pub(crate) fn parse(s: &str) -> Result<Self, String> {
        match s {
            "setup-token" => Ok(Self::SetupToken),
            "pkce" => Ok(Self::Pkce),
            "device" => Ok(Self::Device),
            "none" => Ok(Self::None),
            other => Err(unknown_kebab(
                "login",
                other,
                &["setup-token", "pkce", "device", "none"],
            )),
        }
    }
}

impl<'de> Deserialize<'de> for Login {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        deserialize_kebab(deserializer, Self::parse)
    }
}

/// Encode-time fingerprint (API request only).
#[derive(Debug, Clone, PartialEq)]
pub struct Fingerprint {
    /// `User-Agent` header.
    pub user_agent: Option<String>,
    /// `x-app` header.
    pub x_app: Option<String>,
    /// Prepended to the first system item.
    pub system_prompt_prefix: Option<String>,
    /// Tool name case conversion.
    pub tool_name_case: Option<ToolNameCase>,
    /// Keys the encode path must not send.
    pub forbidden_body_fields: Vec<String>,
    /// What to do when a forbidden field is present.
    pub forbidden_field_policy: ForbiddenFieldPolicy,
    /// Data-only JSON keys merged into the API body.
    pub extra_body: BTreeMap<String, serde_json::Value>,
}

/// Tool-name case conversion.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum ToolNameCase {
    /// Leave names unchanged.
    AsIs,
    /// `snake_case`.
    Snake,
    /// `kebab-case`.
    Kebab,
}

impl ToolNameCase {
    pub(crate) fn parse(s: &str) -> Result<Self, String> {
        match s {
            "as-is" => Ok(Self::AsIs),
            "snake" => Ok(Self::Snake),
            "kebab" => Ok(Self::Kebab),
            other => Err(unknown_kebab(
                "tool_name_case",
                other,
                &["as-is", "snake", "kebab"],
            )),
        }
    }
}

impl<'de> Deserialize<'de> for ToolNameCase {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        deserialize_kebab(deserializer, Self::parse)
    }
}

/// Encode-time policy for `forbidden_body_fields`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum ForbiddenFieldPolicy {
    /// Drop the field.
    Strip,
    /// Fail encode.
    #[default]
    HardError,
}

impl ForbiddenFieldPolicy {
    pub(crate) fn parse(s: &str) -> Result<Self, String> {
        match s {
            "strip" => Ok(Self::Strip),
            "hard-error" => Ok(Self::HardError),
            other => Err(unknown_kebab(
                "forbidden_field_policy",
                other,
                &["strip", "hard-error"],
            )),
        }
    }
}

impl<'de> Deserialize<'de> for ForbiddenFieldPolicy {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        deserialize_kebab(deserializer, Self::parse)
    }
}

/// Beta header values and merge policy.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Betas {
    /// Header values, e.g. `oauth-2025-04-20`.
    pub values: Vec<String>,
    /// Header name. Default `anthropic-beta`.
    pub header: String,
    /// `union` or `replace` (`verbatim` alias).
    pub merge: ListMerge,
}

impl Betas {
    pub(crate) fn default_for(wire: Option<Wire>, has_oauth: bool) -> Self {
        let merge = if matches!(wire, Some(Wire::Messages)) && has_oauth {
            ListMerge::Replace
        } else {
            ListMerge::Union
        };
        Self {
            values: Vec::new(),
            header: "anthropic-beta".into(),
            merge,
        }
    }
}

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

    fn unknown_text(input: &str) -> String {
        AuthScheme::parse(input)
            .expect_err("must reject")
            .to_string()
    }

    #[test]
    #[allow(unreachable_patterns)] // non_exhaustive still lets this crate match all known variants
    fn hosts_should_wildcard_unknown_wire_dialects() {
        fn host_spelling(wire: Wire) -> &'static str {
            match wire {
                Wire::ChatCompletions => "chat-completions",
                Wire::Messages => "messages",
                Wire::Responses => "responses",
                Wire::Gemini => "gemini",
                Wire::Converse => "converse",
                _ => "unknown",
            }
        }
        assert_eq!(host_spelling(Wire::ChatCompletions), "chat-completions");
        assert_eq!(host_spelling(Wire::Messages), "messages");
        assert_eq!(host_spelling(Wire::Responses), "responses");
        assert_eq!(host_spelling(Wire::Gemini), "gemini");
        assert_eq!(host_spelling(Wire::Converse), "converse");
        assert!(
            Wire::NAMES.contains(&"converse"),
            "NAMES must include converse"
        );
    }

    #[test]
    fn as_str_rustdoc_lists_converse() {
        let src = include_str!("types.rs");
        let as_str_doc = src
            .lines()
            .find(|line| line.contains("Catalog / file spelling"))
            .expect("as_str rustdoc lists catalog spellings");
        assert!(
            as_str_doc.contains("converse"),
            "as_str rustdoc must list converse with the other spellings, got: {as_str_doc}"
        );
    }

    #[test]
    fn unknown_auth_scheme_lists_legal_values() {
        let text = unknown_text("oauth");
        assert!(text.contains("unknown auth_scheme `oauth`"), "{text}");
        assert!(
            text.contains("bearer")
                && text.contains("x-api-key")
                && text.contains("none")
                && text.contains("header:<name>"),
            "must list legal auth_scheme values, got {text}"
        );
    }

    #[test]
    fn unknown_auth_scheme_suggests_close_matches() {
        let bearer = unknown_text("Bearer");
        assert!(
            bearer.contains("bearer")
                && bearer.contains("x-api-key")
                && bearer.contains("none")
                && bearer.contains("header:<name>"),
            "must list legal values, got {bearer}"
        );
        assert!(
            bearer.contains("bearer"),
            "Bearer must point at bearer, got {bearer}"
        );
        assert!(
            bearer.to_ascii_lowercase().contains("did you mean") && bearer.contains("`bearer`"),
            "Bearer should suggest bearer, got {bearer}"
        );

        for input in ["api-key", "x_api_key", "X-Api-Key"] {
            let text = unknown_text(input);
            assert!(
                text.contains("x-api-key")
                    && text.contains("bearer")
                    && text.contains("none")
                    && text.contains("header:<name>"),
                "{input} must list legal values, got {text}"
            );
            assert!(
                text.to_ascii_lowercase().contains("did you mean") && text.contains("`x-api-key`"),
                "{input} should suggest x-api-key, got {text}"
            );
        }
    }
}