delopay 0.3.0

Official Rust SDK for the DeloPay payments API
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
//! The user / dashboard-auth models: sessions, tokens, team members, roles and
//! two-factor enrolment.
//!
//! # Secrets
//!
//! Much of this surface *returns* credentials: a sign-in mints a bearer token,
//! TOTP enrolment hands back the shared secret and its `otpauth://`
//! provisioning URI, recovery-code generation returns the codes themselves, and
//! adding a team member can echo a server-generated password once. Every
//! response type below that carries one has a **hand-written `Debug`** that
//! redacts it, so `{:?}` on a response — or on anything containing one — can
//! never spill a credential into a log line. Unit tests at the bottom of this
//! file pin that behaviour for each type, including that an *unset* optional
//! secret still renders as `None`.

use serde::Deserialize;
use serde_json::Value;

/// Purpose of a single-purpose JWT, e.g. `"totp"`, `"reset_password"`,
/// `"sso"`, `"verify_email"`. A string rather than an enum so a new purpose
/// minted by the API does not break deserialization.
pub type TokenPurpose = String;

/// A top-level permission group recognized by the Delopay API, e.g.
/// `"Operations"`, `"Connectors"`, `"Users"`. A string so new groups do not
/// break deserialization.
pub type ParentGroup = String;

/// A permission scope: `"Read"` allows viewing, `"Write"` is required for any
/// mutation.
pub type PermissionScope = String;

// =====================================================================
// Sign-in / token responses
// =====================================================================

/// The result of any call that establishes or re-establishes a session:
/// sign-up, sign-in, OIDC sign-in, email verification, merchant / shop
/// switching, invitation acceptance and recovery-code redemption.
///
/// Unmodeled fields are preserved in [`extra`](AuthResponse::extra) so new API
/// fields never break deserialization.
#[derive(Clone, Deserialize)]
#[non_exhaustive]
pub struct AuthResponse {
    /// Signed session JWT — send it as `Authorization: Bearer <token>`.
    /// Treat it as a credential: anyone holding it *is* the user.
    pub token: String,

    /// Kind of token issued, when the API says so.
    #[serde(default)]
    pub token_type: Option<String>,
    /// Seconds until the token expires, when the API says so.
    #[serde(default)]
    pub expires: Option<i64>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

// Hand-written: `token` is a bearer credential — whoever holds it holds the
// session — so it must never reach a log line through `{:?}`. Pinned by
// `auth_response_debug_redacts_the_token`.
impl std::fmt::Debug for AuthResponse {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AuthResponse")
            .field("token", &"[redacted]")
            .field("token_type", &self.token_type)
            .field("expires", &self.expires)
            .field("extra", &self.extra)
            .finish()
    }
}

/// A freshly minted single-purpose token, returned by the email-token
/// exchange, the two-factor terminate step and employee impersonation.
///
/// [`token_type`](TokenResponse::token_type) tells the client which step of
/// the flow to run next.
#[derive(Clone, Deserialize)]
#[non_exhaustive]
pub struct TokenResponse {
    /// Signed JWT — pass as `Authorization: Bearer <token>` on the next call.
    /// Treat it as a credential.
    pub token: String,
    /// Kind of token — tells the client which step to perform next.
    pub token_type: TokenPurpose,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

// Hand-written: `token` authorises the next step of a password-reset,
// invitation or impersonation flow and must never reach a log line through
// `{:?}`. Pinned by `token_response_debug_redacts_the_token`.
impl std::fmt::Debug for TokenResponse {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TokenResponse")
            .field("token", &"[redacted]")
            .field("token_type", &self.token_type)
            .field("extra", &self.extra)
            .finish()
    }
}

// =====================================================================
// The user record
// =====================================================================

/// The authenticated user's own details, as returned by the profile,
/// update and password-change endpoints.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct UserResponse {
    /// Merchant account the session is currently scoped to.
    pub merchant_id: String,
    /// The user's display name.
    pub name: String,
    /// The user's email address.
    pub email: String,
    /// Role the user holds in the current scope.
    pub role_id: String,
    /// Whether the user has completed TOTP enrolment.
    pub is_two_factor_auth_setup: bool,
    /// Shop (business profile) the session is currently scoped to.
    pub profile_id: String,
    /// Lineage level the session is scoped to, e.g. `"merchant"`.
    pub entity_type: String,
    /// Version of the user record's shape.
    pub version: String,

    /// Days left before email verification becomes mandatory.
    #[serde(default)]
    pub verification_days_left: Option<i64>,
    /// Unused recovery codes remaining.
    #[serde(default)]
    pub recovery_codes_left: Option<i64>,
    /// Dashboard theme selected by the user.
    #[serde(default)]
    pub theme_id: Option<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

// =====================================================================
// Login activity and sessions
// =====================================================================

/// One row from the authenticated user's login history.
///
/// `event_type` enumerates the sign-in attempt outcome (`signin_success`,
/// `signin_failure`, `totp_failure`, …) and `failure_reason` is set on failure
/// rows (`invalid_credentials`, `totp_invalid`, …). Both are strings so older
/// rows stay readable as the enums grow.
///
/// The geo fields are populated by a GeoIP lookup at sign-in time. They stay
/// `None` for private / loopback IPs, when the lookup misses, or when GeoIP is
/// not enabled.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct LoginHistoryEntry {
    /// Unique identifier of this history row.
    pub id: String,
    /// Outcome of the sign-in attempt.
    pub event_type: String,
    /// How the attempt authenticated: `"password"`, `"magic_link"`,
    /// `"sso_oidc"`, `"totp"`, `"recovery_code"`.
    pub auth_method: String,
    /// ISO 8601 timestamp the row was inserted (sign-in attempt time).
    pub created_at: String,

    /// Why the attempt failed, on failure rows.
    #[serde(default)]
    pub failure_reason: Option<String>,
    /// Source IP of the attempt.
    #[serde(default)]
    pub ip_address: Option<String>,
    /// `User-Agent` sent by the client.
    #[serde(default)]
    pub user_agent: Option<String>,
    /// Two-letter country code resolved by GeoIP.
    #[serde(default)]
    pub country_code: Option<String>,
    /// City resolved by GeoIP.
    #[serde(default)]
    pub city: Option<String>,
    /// Latitude resolved by GeoIP.
    #[serde(default)]
    pub latitude: Option<f64>,
    /// Longitude resolved by GeoIP.
    #[serde(default)]
    pub longitude: Option<f64>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// A page of the authenticated user's login history.
///
/// When a Delopay admin is impersonating a merchant the API returns an empty
/// page, so the admin's IP / geo data is not exposed inside the merchant
/// dashboard.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct LoginHistoryResponse {
    /// The rows in this page, newest first.
    pub entries: Vec<LoginHistoryEntry>,
    /// Unpaginated row count, for client-side page-count calculation.
    pub total_count: i64,
    /// Offset this page starts at.
    pub offset: i64,
    /// Maximum rows this page could contain.
    pub limit: i64,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// One currently-active dashboard session — a single minted login JWT.
///
/// [`id`](UserSessionEntry::id) is also the JWT's `jti`, and is what you pass
/// to the revoke endpoint.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct UserSessionEntry {
    /// Session identifier, equal to the JWT's `jti`.
    pub id: String,
    /// Sign-in method that produced the session.
    pub auth_method: String,
    /// ISO 8601 timestamp the session was created (sign-in time).
    pub created_at: String,
    /// ISO 8601 timestamp of the most recent observed API call on this
    /// session.
    pub last_seen_at: String,
    /// ISO 8601 timestamp at which the session JWT expires.
    pub expires_at: String,
    /// `true` for the row matching the JWT that made the listing request —
    /// what lets a dashboard render a "This device" tag.
    pub is_current: bool,

    /// Source IP the session signed in from.
    #[serde(default)]
    pub ip_address: Option<String>,
    /// `User-Agent` the session signed in with.
    #[serde(default)]
    pub user_agent: Option<String>,
    /// Two-letter country code resolved by GeoIP.
    #[serde(default)]
    pub country_code: Option<String>,
    /// City resolved by GeoIP.
    #[serde(default)]
    pub city: Option<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// The authenticated user's active sessions.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct UserSessionListResponse {
    /// One entry per live session.
    pub sessions: Vec<UserSessionEntry>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// The result of disconnecting one of the user's sessions.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct UserSessionRevokeResponse {
    /// Whether the session was revoked.
    pub revoked: bool,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

// =====================================================================
// Team members
// =====================================================================

/// The outcome of inviting one team member — one entry per invitee, in the
/// order the invitations were sent.
#[derive(Clone, Deserialize)]
#[non_exhaustive]
pub struct InviteUsersResponse {
    /// The invited email address.
    pub email: String,
    /// Whether the invitation email was delivered.
    pub is_email_sent: bool,

    /// Temporary password, present only when the invite email could *not* be
    /// delivered. Shown once — share it with the invitee out of band. They are
    /// forced to change it on first sign-in.
    #[serde(default)]
    pub password: Option<String>,
    /// Why the invitation failed, when it did.
    #[serde(default)]
    pub error: Option<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

// Hand-written: `password` is a live credential for the invitee's account and
// must never reach a log line through `{:?}`. The `Option` shape survives
// redaction so callers can still see whether a password was issued. Pinned by
// `invite_users_response_debug_redacts_the_password` and its `None` companion.
impl std::fmt::Debug for InviteUsersResponse {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("InviteUsersResponse")
            .field("email", &self.email)
            .field("is_email_sent", &self.is_email_sent)
            .field("password", &self.password.as_ref().map(|_| "[redacted]"))
            .field("error", &self.error)
            .field("extra", &self.extra)
            .finish()
    }
}

/// The team member created by adding a user directly.
#[derive(Clone, Deserialize)]
#[non_exhaustive]
pub struct AddUserResponse {
    /// Stable identifier of the new member.
    pub user_id: String,
    /// The member's email address.
    pub email: String,
    /// The member's display name.
    pub name: String,
    /// Whether the member's email is already verified.
    pub is_verified: bool,
    /// Whether the member's account is active.
    pub is_active: bool,

    /// Present only when the server generated the password (the request
    /// omitted one). Shown once — it is stored hashed and cannot be read back.
    /// The member is forced to change it on first sign-in.
    #[serde(default)]
    pub password: Option<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

// Hand-written: `password` is a live credential shown exactly once and must
// never reach a log line through `{:?}`. The `Option` shape survives redaction
// so callers can still see whether the server generated one. Pinned by
// `add_user_response_debug_redacts_the_password` and its `None` companion.
impl std::fmt::Debug for AddUserResponse {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AddUserResponse")
            .field("user_id", &self.user_id)
            .field("email", &self.email)
            .field("name", &self.name)
            .field("is_verified", &self.is_verified)
            .field("is_active", &self.is_active)
            .field("password", &self.password.as_ref().map(|_| "[redacted]"))
            .field("extra", &self.extra)
            .finish()
    }
}

/// A role a member holds, as returned when listing the caller's lineage.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct MinimalRoleInfo {
    /// Identifier of the role.
    pub role_id: String,
    /// Human-readable role name.
    pub role_name: String,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// One member of the caller's lineage.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct UserInLineage {
    /// Stable identifier of the member. Use it to target them specifically —
    /// for a per-user operation-limit override, or to resolve a user id
    /// stamped on another resource (such as a refund's `initiated_by`) back to
    /// a person.
    pub user_id: String,
    /// The member's email address.
    pub email: String,
    /// Every role the member holds in this lineage.
    pub roles: Vec<MinimalRoleInfo>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

// =====================================================================
// Roles and permissions
// =====================================================================

/// One entry in the caller's permission listing: the role holds the listed
/// [`scopes`](ParentGroupInfo::scopes) over the resources implied by
/// [`name`](ParentGroupInfo::name).
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ParentGroupInfo {
    /// The permission group.
    pub name: ParentGroup,
    /// Resources the group covers.
    pub resources: Vec<String>,
    /// Scopes the caller's role holds over them.
    pub scopes: Vec<PermissionScope>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

// =====================================================================
// Two-factor authentication
// =====================================================================

/// The TOTP enrolment material: the shared secret and the `otpauth://` URI a
/// dashboard renders as a QR code.
///
/// Both fields are enrolment credentials — anyone who reads either can
/// generate valid codes for the account.
#[derive(Clone, Deserialize)]
#[non_exhaustive]
pub struct TotpSecret {
    /// Base32 shared secret to load into an authenticator app.
    pub secret: String,
    /// `otpauth://` provisioning URI — **embeds the secret**, so it is exactly
    /// as sensitive as [`secret`](TotpSecret::secret).
    pub totp_url: String,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

// Hand-written: both the shared secret and the provisioning URI (which embeds
// it) are enrolment credentials and must never reach a log line through
// `{:?}`. Pinned by `totp_secret_debug_redacts_the_secret_and_url`.
impl std::fmt::Debug for TotpSecret {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TotpSecret")
            .field("secret", &"[redacted]")
            .field("totp_url", &"[redacted]")
            .field("extra", &self.extra)
            .finish()
    }
}

/// The result of starting TOTP setup.
///
/// [`secret`](TotpResponse::secret) is `Some` when the user has no TOTP
/// configured yet, and `None` when they are already set up — in which case the
/// caller should prompt for a 6-digit code and verify it instead.
#[derive(Clone, Deserialize)]
#[non_exhaustive]
pub struct TotpResponse {
    /// Enrolment material, when the user is not yet enrolled.
    #[serde(default)]
    pub secret: Option<TotpSecret>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

// Hand-written: the nested enrolment material is a credential and must never
// reach a log line through `{:?}`. Redacted here as well as on `TotpSecret`
// itself, so neither type can leak on its own. The `Option` shape survives
// redaction so callers can still see whether enrolment is pending. Pinned by
// `totp_response_debug_redacts_the_secret` and its `None` companion.
impl std::fmt::Debug for TotpResponse {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TotpResponse")
            .field("secret", &self.secret.as_ref().map(|_| "[redacted]"))
            .field("extra", &self.extra)
            .finish()
    }
}

/// A freshly generated set of recovery codes. Generating a new set invalidates
/// the previous one.
///
/// The codes are single-use second factors: each one substitutes for a TOTP
/// code. Show them to the user once and never persist them in a log.
#[derive(Clone, Deserialize)]
#[non_exhaustive]
pub struct RecoveryCodesResponse {
    /// The codes, in the order the API generated them.
    pub recovery_codes: Vec<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

// Hand-written: every recovery code is a live second factor and must never
// reach a log line through `{:?}`. The count is kept — it is useful and not
// sensitive. Pinned by `recovery_codes_response_debug_redacts_the_codes`.
impl std::fmt::Debug for RecoveryCodesResponse {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("RecoveryCodesResponse")
            .field("recovery_codes", &"[redacted]")
            .field("recovery_codes_len", &self.recovery_codes.len())
            .field("extra", &self.extra)
            .finish()
    }
}

// =====================================================================
// Phone OTP
// =====================================================================

/// The result of sending a one-time code to a phone number.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct PhoneOtpResponse {
    /// Human-readable confirmation from the API.
    pub message: String,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// The result of verifying a one-time code sent to a phone number.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct PhoneOtpVerifyResponse {
    /// Whether the code matched.
    pub verified: bool,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

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

    // Each redaction test below fails if the hand-written `Debug` is deleted
    // (the derive would print the secret) or if the field is rendered with
    // `&self.x` instead of `&"[redacted]"`. The `None` companions fail if an
    // impl hard-codes `Some("[redacted]")` instead of mapping the `Option`.

    fn de<T: serde::de::DeserializeOwned>(json: &str) -> T {
        serde_json::from_str(json).expect("fixture deserializes")
    }

    #[test]
    fn auth_response_debug_redacts_the_token() {
        let res: AuthResponse =
            de(r#"{"token":"jwt-super-secret","token_type":"bearer","expires":3600}"#);
        let rendered = format!("{res:?}");
        assert!(!rendered.contains("jwt-super-secret"), "{rendered}");
        assert!(rendered.contains("bearer"), "{rendered}");
        assert!(rendered.contains("3600"), "{rendered}");
    }

    #[test]
    fn auth_response_keeps_unknown_fields_in_extra() {
        let res: AuthResponse = de(r#"{"token":"t","brand_new_field":"kept"}"#);
        assert_eq!(res.extra["brand_new_field"], "kept");
        assert_eq!(res.token_type, None);
    }

    #[test]
    fn token_response_debug_redacts_the_token() {
        let res: TokenResponse = de(r#"{"token":"spt-super-secret","token_type":"totp"}"#);
        let rendered = format!("{res:?}");
        assert!(!rendered.contains("spt-super-secret"), "{rendered}");
        assert!(rendered.contains("totp"), "{rendered}");
    }

    #[test]
    fn invite_users_response_debug_redacts_the_password() {
        let res: InviteUsersResponse = de(
            r#"{"email":"bob@example.com","is_email_sent":false,"password":"temp-pw-1234","error":"smtp down"}"#,
        );
        let rendered = format!("{res:?}");
        assert!(!rendered.contains("temp-pw-1234"), "{rendered}");
        assert!(rendered.contains("bob@example.com"), "{rendered}");
        assert!(rendered.contains("smtp down"), "{rendered}");
        assert!(rendered.contains("Some("), "{rendered}");
    }

    #[test]
    fn invite_users_response_debug_shows_none_when_no_password() {
        let res: InviteUsersResponse = de(r#"{"email":"bob@example.com","is_email_sent":true}"#);
        assert!(format!("{res:?}").contains("password: None"));
    }

    #[test]
    fn add_user_response_debug_redacts_the_password() {
        let res: AddUserResponse = de(
            r#"{"user_id":"usr_1","email":"bob@example.com","name":"Bob","is_verified":false,"is_active":true,"password":"generated-pw-9000"}"#,
        );
        let rendered = format!("{res:?}");
        assert!(!rendered.contains("generated-pw-9000"), "{rendered}");
        assert!(rendered.contains("usr_1"), "{rendered}");
    }

    #[test]
    fn add_user_response_debug_shows_none_when_password_omitted() {
        let res: AddUserResponse = de(
            r#"{"user_id":"usr_1","email":"bob@example.com","name":"Bob","is_verified":false,"is_active":true}"#,
        );
        assert!(format!("{res:?}").contains("password: None"));
    }

    #[test]
    fn totp_secret_debug_redacts_the_secret_and_url() {
        let res: TotpSecret = de(
            r#"{"secret":"JBSWY3DPEHPK3PXP","totp_url":"otpauth://totp/x?secret=JBSWY3DPEHPK3PXP"}"#,
        );
        let rendered = format!("{res:?}");
        assert!(!rendered.contains("JBSWY3DPEHPK3PXP"), "{rendered}");
        assert!(!rendered.contains("otpauth"), "{rendered}");
    }

    #[test]
    fn totp_response_debug_redacts_the_secret() {
        let res: TotpResponse = de(
            r#"{"secret":{"secret":"JBSWY3DPEHPK3PXP","totp_url":"otpauth://totp/x?secret=JBSWY3DPEHPK3PXP"}}"#,
        );
        let rendered = format!("{res:?}");
        assert!(!rendered.contains("JBSWY3DPEHPK3PXP"), "{rendered}");
        assert!(!rendered.contains("otpauth"), "{rendered}");
        assert!(rendered.contains("Some("), "{rendered}");
    }

    #[test]
    fn totp_response_debug_shows_none_when_already_enrolled() {
        let res: TotpResponse = de(r#"{"secret":null}"#);
        assert!(format!("{res:?}").contains("secret: None"));
    }

    #[test]
    fn recovery_codes_response_debug_redacts_the_codes() {
        let res: RecoveryCodesResponse =
            de(r#"{"recovery_codes":["aaaa-bbbb","cccc-dddd","eeee-ffff"]}"#);
        let rendered = format!("{res:?}");
        assert!(!rendered.contains("aaaa-bbbb"), "{rendered}");
        assert!(!rendered.contains("eeee-ffff"), "{rendered}");
        // The count is not sensitive and is kept, so an impl that dropped the
        // field entirely is distinguishable from one that redacts it.
        assert!(rendered.contains("recovery_codes_len: 3"), "{rendered}");
    }

    #[test]
    fn user_response_parses_optional_fields_and_keeps_extras() {
        let res: UserResponse = de(
            r#"{"merchant_id":"mer_1","name":"Ada","email":"ada@example.com","role_id":"role_1",
                "is_two_factor_auth_setup":true,"profile_id":"pro_1","entity_type":"merchant",
                "version":"v2","theme_id":"dark","new_api_field":7}"#,
        );
        assert_eq!(res.theme_id.as_deref(), Some("dark"));
        assert_eq!(res.verification_days_left, None);
        assert_eq!(res.extra["new_api_field"], 7);
    }

    #[test]
    fn login_history_parses_null_geo_fields() {
        let res: LoginHistoryResponse = de(
            r#"{"entries":[{"id":"lh_1","event_type":"signin_failure","failure_reason":"totp_invalid",
                "auth_method":"totp","ip_address":"127.0.0.1","user_agent":null,"country_code":null,
                "city":null,"latitude":null,"longitude":null,"created_at":"2026-01-01T00:00:00Z"}],
                "total_count":1,"offset":0,"limit":25}"#,
        );
        assert_eq!(res.total_count, 1);
        assert_eq!(
            res.entries[0].failure_reason.as_deref(),
            Some("totp_invalid")
        );
        assert_eq!(res.entries[0].latitude, None);
        assert_eq!(res.entries[0].ip_address.as_deref(), Some("127.0.0.1"));
    }

    #[test]
    fn session_list_parses_the_current_flag() {
        let res: UserSessionListResponse = de(
            r#"{"sessions":[{"id":"ses_1","auth_method":"password","ip_address":null,
                "user_agent":null,"country_code":null,"city":null,
                "created_at":"2026-01-01T00:00:00Z","last_seen_at":"2026-01-02T00:00:00Z",
                "expires_at":"2026-01-08T00:00:00Z","is_current":true}]}"#,
        );
        assert_eq!(res.sessions.len(), 1);
        assert!(res.sessions[0].is_current);
        assert_eq!(res.sessions[0].last_seen_at, "2026-01-02T00:00:00Z");
    }

    #[test]
    fn user_in_lineage_parses_nested_roles() {
        let res: UserInLineage = de(r#"{"user_id":"usr_1","email":"bob@example.com",
                "roles":[{"role_id":"role_1","role_name":"Admin"}]}"#);
        assert_eq!(res.roles[0].role_name, "Admin");
    }

    #[test]
    fn parent_group_info_parses_scopes() {
        let res: ParentGroupInfo = de(
            r#"{"name":"Operations","resources":["payment","refund"],"scopes":["Read","Write"]}"#,
        );
        assert_eq!(res.name, "Operations");
        assert_eq!(res.resources, vec!["payment", "refund"]);
        assert_eq!(res.scopes, vec!["Read", "Write"]);
    }
}