Skip to main content

bsv_rs/totp/
core.rs

1//! TOTP (Time-based One-Time Password) implementation.
2//!
3//! Implements RFC 6238 for generating time-based OTPs commonly used in 2FA.
4
5use crate::primitives::hash::{sha1_hmac, sha256_hmac, sha512_hmac};
6use subtle::ConstantTimeEq;
7
8/// HMAC algorithm for TOTP generation.
9///
10/// Per RFC 6238, SHA-1 is the default algorithm for backwards compatibility
11/// with most authenticator apps, though SHA-256 and SHA-512 offer stronger
12/// security margins.
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
14pub enum Algorithm {
15    /// HMAC-SHA1 (default, 20-byte output)
16    #[default]
17    Sha1,
18    /// HMAC-SHA256 (32-byte output)
19    Sha256,
20    /// HMAC-SHA512 (64-byte output)
21    Sha512,
22}
23
24/// Options for TOTP generation.
25///
26/// All fields have sensible defaults following RFC 6238 recommendations.
27#[derive(Debug, Clone)]
28pub struct TotpOptions {
29    /// Number of digits in the generated code (default: 6).
30    ///
31    /// Common values are 6 or 8. The value should be between 1 and 10
32    /// for practical use.
33    pub digits: u32,
34
35    /// HMAC algorithm to use (default: SHA-1).
36    ///
37    /// SHA-1 is the most widely supported by authenticator apps.
38    /// SHA-256 and SHA-512 provide stronger security.
39    pub algorithm: Algorithm,
40
41    /// Time period in seconds (default: 30).
42    ///
43    /// The counter increments every `period` seconds. 30 seconds is
44    /// the standard value used by most services.
45    pub period: u64,
46
47    /// Override timestamp in seconds since Unix epoch.
48    ///
49    /// If `None`, uses the current system time. Set this for testing
50    /// or when generating codes for a specific time.
51    pub timestamp: Option<u64>,
52}
53
54impl Default for TotpOptions {
55    fn default() -> Self {
56        Self {
57            digits: 6,
58            algorithm: Algorithm::Sha1,
59            period: 30,
60            timestamp: None,
61        }
62    }
63}
64
65/// Options for TOTP validation.
66///
67/// Extends `TotpOptions` with a skew parameter to handle clock drift.
68#[derive(Debug, Clone)]
69pub struct TotpValidateOptions {
70    /// Base TOTP options (digits, algorithm, period, timestamp).
71    pub options: TotpOptions,
72
73    /// Number of time periods to check before and after the current period.
74    ///
75    /// Default is 1, which means codes from the previous period, current
76    /// period, and next period are all accepted. This accommodates up to
77    /// 30 seconds of clock drift in either direction (with default 30-second
78    /// periods).
79    ///
80    /// Higher values increase tolerance for clock drift but reduce security.
81    pub skew: u32,
82}
83
84impl Default for TotpValidateOptions {
85    fn default() -> Self {
86        Self {
87            options: TotpOptions::default(),
88            skew: 1,
89        }
90    }
91}
92
93/// TOTP (Time-based One-Time Password) implementation.
94///
95/// Implements RFC 6238 for generating time-based OTPs commonly used in 2FA.
96///
97/// # Security Considerations
98///
99/// - The secret should be at least 16 bytes (128 bits) of high-entropy data
100/// - Codes should be transmitted over secure channels only
101/// - Validation uses constant-time comparison to prevent timing attacks
102/// - Consider rate limiting validation attempts to prevent brute force attacks
103///
104/// # Example
105///
106/// ```rust
107/// use bsv_rs::totp::{Totp, TotpOptions};
108///
109/// let secret = b"12345678901234567890";
110///
111/// // Generate with defaults (6 digits, SHA-1, 30-second period)
112/// let code = Totp::generate(secret, None);
113///
114/// // Validate the code
115/// assert!(Totp::validate(secret, &code, None));
116/// ```
117pub struct Totp;
118
119impl Totp {
120    /// Generate a TOTP code from a shared secret.
121    ///
122    /// # Arguments
123    ///
124    /// * `secret` - The shared secret key (raw bytes, typically 20+ bytes)
125    /// * `options` - Optional TOTP parameters; uses defaults if `None`
126    ///
127    /// # Returns
128    ///
129    /// A string containing the TOTP code, zero-padded to the configured
130    /// number of digits.
131    ///
132    /// # Example
133    ///
134    /// ```rust
135    /// use bsv_rs::totp::{Totp, TotpOptions, Algorithm};
136    ///
137    /// let secret = b"12345678901234567890";
138    ///
139    /// // Generate with defaults
140    /// let code = Totp::generate(secret, None);
141    /// assert_eq!(code.len(), 6);
142    ///
143    /// // Generate with custom options
144    /// let options = TotpOptions {
145    ///     digits: 8,
146    ///     algorithm: Algorithm::Sha256,
147    ///     timestamp: Some(59), // Fixed time for testing
148    ///     ..Default::default()
149    /// };
150    /// let code = Totp::generate(secret, Some(options));
151    /// assert_eq!(code.len(), 8);
152    /// ```
153    pub fn generate(secret: &[u8], options: Option<TotpOptions>) -> String {
154        let options = options.unwrap_or_default();
155        let timestamp = options.timestamp.unwrap_or_else(current_unix_seconds);
156        let counter = timestamp / options.period;
157        generate_hotp(secret, counter, &options)
158    }
159
160    /// Validate a TOTP code against a shared secret.
161    ///
162    /// Checks the provided passcode against codes generated for the current
163    /// time window and adjacent windows (determined by the `skew` parameter).
164    ///
165    /// # Arguments
166    ///
167    /// * `secret` - The shared secret key (raw bytes)
168    /// * `passcode` - The TOTP code to validate (will be trimmed of whitespace)
169    /// * `options` - Optional validation parameters; uses defaults if `None`
170    ///
171    /// # Returns
172    ///
173    /// `true` if the passcode matches any valid code within the skew window,
174    /// `false` otherwise.
175    ///
176    /// # Security
177    ///
178    /// This function uses constant-time comparison to prevent timing attacks.
179    ///
180    /// # Example
181    ///
182    /// ```rust
183    /// use bsv_rs::totp::{Totp, TotpValidateOptions, TotpOptions};
184    ///
185    /// let secret = b"12345678901234567890";
186    /// let code = Totp::generate(secret, None);
187    ///
188    /// // Validate with default skew (1 period before/after)
189    /// assert!(Totp::validate(secret, &code, None));
190    ///
191    /// // Validate with custom options
192    /// let validate_options = TotpValidateOptions {
193    ///     options: TotpOptions::default(),
194    ///     skew: 2, // Accept codes from 2 periods before/after
195    /// };
196    /// assert!(Totp::validate(secret, &code, Some(validate_options)));
197    ///
198    /// // Invalid codes are rejected
199    /// assert!(!Totp::validate(secret, "000000", None));
200    /// ```
201    pub fn validate(secret: &[u8], passcode: &str, options: Option<TotpValidateOptions>) -> bool {
202        let options = options.unwrap_or_default();
203        let passcode = passcode.trim();
204
205        // Quick reject if length doesn't match expected digits
206        if passcode.len() != options.options.digits as usize {
207            return false;
208        }
209
210        let timestamp = options
211            .options
212            .timestamp
213            .unwrap_or_else(current_unix_seconds);
214        let counter = timestamp / options.options.period;
215
216        // Check current counter and adjacent counters within skew window
217        // We check current first, then alternating before/after
218        let mut counters_to_check = Vec::with_capacity(1 + 2 * options.skew as usize);
219        counters_to_check.push(counter);
220
221        for i in 1..=options.skew as u64 {
222            counters_to_check.push(counter.wrapping_add(i));
223            // Use saturating_sub to handle counter near 0
224            if counter >= i {
225                counters_to_check.push(counter - i);
226            }
227        }
228
229        for check_counter in counters_to_check {
230            let expected = generate_hotp(secret, check_counter, &options.options);
231            if constant_time_eq(passcode, &expected) {
232                return true;
233            }
234        }
235
236        false
237    }
238}
239
240/// Generate an HOTP code for a specific counter value.
241///
242/// Implements RFC 4226 (HOTP algorithm):
243/// 1. Compute HMAC of counter (as 8-byte big-endian) using the secret
244/// 2. Dynamic truncation to extract 4-byte code
245/// 3. Reduce modulo 10^digits
246/// 4. Zero-pad to required length
247fn generate_hotp(secret: &[u8], counter: u64, options: &TotpOptions) -> String {
248    // Counter as 8-byte big-endian (RFC 4226 Section 5.1)
249    let counter_bytes = counter.to_be_bytes();
250
251    // Compute HMAC based on algorithm
252    let hmac_result: Vec<u8> = match options.algorithm {
253        Algorithm::Sha1 => sha1_hmac(secret, &counter_bytes).to_vec(),
254        Algorithm::Sha256 => sha256_hmac(secret, &counter_bytes).to_vec(),
255        Algorithm::Sha512 => sha512_hmac(secret, &counter_bytes).to_vec(),
256    };
257
258    // Dynamic truncation (RFC 4226 Section 5.4)
259    let offset = (hmac_result[hmac_result.len() - 1] & 0x0f) as usize;
260
261    // Extract 4 bytes starting at offset
262    let code_bytes = [
263        hmac_result[offset] & 0x7f, // Mask high bit to ensure positive
264        hmac_result[offset + 1],
265        hmac_result[offset + 2],
266        hmac_result[offset + 3],
267    ];
268
269    let code = u32::from_be_bytes(code_bytes);
270
271    // Reduce modulo 10^digits
272    let divisor = 10u32.pow(options.digits);
273    let truncated = code % divisor;
274
275    // Zero-pad to required length
276    format!("{:0>width$}", truncated, width = options.digits as usize)
277}
278
279/// Get current Unix timestamp in seconds.
280fn current_unix_seconds() -> u64 {
281    crate::util::time::current_time_secs()
282}
283
284/// Constant-time string comparison to prevent timing attacks.
285fn constant_time_eq(a: &str, b: &str) -> bool {
286    if a.len() != b.len() {
287        return false;
288    }
289    a.as_bytes().ct_eq(b.as_bytes()).into()
290}
291
292#[cfg(test)]
293mod tests {
294    use super::*;
295
296    // RFC 6238 Appendix B test vectors
297    // Secret keys for different algorithms (from the RFC)
298    const SHA1_SECRET: &[u8] = b"12345678901234567890";
299    const SHA256_SECRET: &[u8] = b"12345678901234567890123456789012";
300    const SHA512_SECRET: &[u8] =
301        b"1234567890123456789012345678901234567890123456789012345678901234";
302
303    // RFC 6238 test vectors (8-digit codes)
304    #[test]
305    fn test_rfc6238_sha1_time_59() {
306        let options = TotpOptions {
307            digits: 8,
308            algorithm: Algorithm::Sha1,
309            timestamp: Some(59),
310            ..Default::default()
311        };
312        let code = Totp::generate(SHA1_SECRET, Some(options));
313        assert_eq!(code, "94287082");
314    }
315
316    #[test]
317    fn test_rfc6238_sha256_time_59() {
318        let options = TotpOptions {
319            digits: 8,
320            algorithm: Algorithm::Sha256,
321            timestamp: Some(59),
322            ..Default::default()
323        };
324        let code = Totp::generate(SHA256_SECRET, Some(options));
325        assert_eq!(code, "46119246");
326    }
327
328    #[test]
329    fn test_rfc6238_sha512_time_59() {
330        let options = TotpOptions {
331            digits: 8,
332            algorithm: Algorithm::Sha512,
333            timestamp: Some(59),
334            ..Default::default()
335        };
336        let code = Totp::generate(SHA512_SECRET, Some(options));
337        assert_eq!(code, "90693936");
338    }
339
340    #[test]
341    fn test_rfc6238_sha1_time_1111111109() {
342        let options = TotpOptions {
343            digits: 8,
344            algorithm: Algorithm::Sha1,
345            timestamp: Some(1111111109),
346            ..Default::default()
347        };
348        let code = Totp::generate(SHA1_SECRET, Some(options));
349        assert_eq!(code, "07081804");
350    }
351
352    #[test]
353    fn test_rfc6238_sha256_time_1111111109() {
354        let options = TotpOptions {
355            digits: 8,
356            algorithm: Algorithm::Sha256,
357            timestamp: Some(1111111109),
358            ..Default::default()
359        };
360        let code = Totp::generate(SHA256_SECRET, Some(options));
361        assert_eq!(code, "68084774");
362    }
363
364    #[test]
365    fn test_rfc6238_sha512_time_1111111109() {
366        let options = TotpOptions {
367            digits: 8,
368            algorithm: Algorithm::Sha512,
369            timestamp: Some(1111111109),
370            ..Default::default()
371        };
372        let code = Totp::generate(SHA512_SECRET, Some(options));
373        assert_eq!(code, "25091201");
374    }
375
376    #[test]
377    fn test_rfc6238_sha1_time_1111111111() {
378        let options = TotpOptions {
379            digits: 8,
380            algorithm: Algorithm::Sha1,
381            timestamp: Some(1111111111),
382            ..Default::default()
383        };
384        let code = Totp::generate(SHA1_SECRET, Some(options));
385        assert_eq!(code, "14050471");
386    }
387
388    #[test]
389    fn test_rfc6238_sha256_time_1111111111() {
390        let options = TotpOptions {
391            digits: 8,
392            algorithm: Algorithm::Sha256,
393            timestamp: Some(1111111111),
394            ..Default::default()
395        };
396        let code = Totp::generate(SHA256_SECRET, Some(options));
397        assert_eq!(code, "67062674");
398    }
399
400    #[test]
401    fn test_rfc6238_sha512_time_1111111111() {
402        let options = TotpOptions {
403            digits: 8,
404            algorithm: Algorithm::Sha512,
405            timestamp: Some(1111111111),
406            ..Default::default()
407        };
408        let code = Totp::generate(SHA512_SECRET, Some(options));
409        assert_eq!(code, "99943326");
410    }
411
412    #[test]
413    fn test_rfc6238_sha1_time_1234567890() {
414        let options = TotpOptions {
415            digits: 8,
416            algorithm: Algorithm::Sha1,
417            timestamp: Some(1234567890),
418            ..Default::default()
419        };
420        let code = Totp::generate(SHA1_SECRET, Some(options));
421        assert_eq!(code, "89005924");
422    }
423
424    #[test]
425    fn test_rfc6238_sha256_time_1234567890() {
426        let options = TotpOptions {
427            digits: 8,
428            algorithm: Algorithm::Sha256,
429            timestamp: Some(1234567890),
430            ..Default::default()
431        };
432        let code = Totp::generate(SHA256_SECRET, Some(options));
433        assert_eq!(code, "91819424");
434    }
435
436    #[test]
437    fn test_rfc6238_sha512_time_1234567890() {
438        let options = TotpOptions {
439            digits: 8,
440            algorithm: Algorithm::Sha512,
441            timestamp: Some(1234567890),
442            ..Default::default()
443        };
444        let code = Totp::generate(SHA512_SECRET, Some(options));
445        assert_eq!(code, "93441116");
446    }
447
448    #[test]
449    fn test_rfc6238_sha1_time_2000000000() {
450        let options = TotpOptions {
451            digits: 8,
452            algorithm: Algorithm::Sha1,
453            timestamp: Some(2000000000),
454            ..Default::default()
455        };
456        let code = Totp::generate(SHA1_SECRET, Some(options));
457        assert_eq!(code, "69279037");
458    }
459
460    #[test]
461    fn test_rfc6238_sha256_time_2000000000() {
462        let options = TotpOptions {
463            digits: 8,
464            algorithm: Algorithm::Sha256,
465            timestamp: Some(2000000000),
466            ..Default::default()
467        };
468        let code = Totp::generate(SHA256_SECRET, Some(options));
469        assert_eq!(code, "90698825");
470    }
471
472    #[test]
473    fn test_rfc6238_sha512_time_2000000000() {
474        let options = TotpOptions {
475            digits: 8,
476            algorithm: Algorithm::Sha512,
477            timestamp: Some(2000000000),
478            ..Default::default()
479        };
480        let code = Totp::generate(SHA512_SECRET, Some(options));
481        assert_eq!(code, "38618901");
482    }
483
484    #[test]
485    fn test_rfc6238_sha1_time_20000000000() {
486        let options = TotpOptions {
487            digits: 8,
488            algorithm: Algorithm::Sha1,
489            timestamp: Some(20000000000),
490            ..Default::default()
491        };
492        let code = Totp::generate(SHA1_SECRET, Some(options));
493        assert_eq!(code, "65353130");
494    }
495
496    #[test]
497    fn test_rfc6238_sha256_time_20000000000() {
498        let options = TotpOptions {
499            digits: 8,
500            algorithm: Algorithm::Sha256,
501            timestamp: Some(20000000000),
502            ..Default::default()
503        };
504        let code = Totp::generate(SHA256_SECRET, Some(options));
505        assert_eq!(code, "77737706");
506    }
507
508    #[test]
509    fn test_rfc6238_sha512_time_20000000000() {
510        let options = TotpOptions {
511            digits: 8,
512            algorithm: Algorithm::Sha512,
513            timestamp: Some(20000000000),
514            ..Default::default()
515        };
516        let code = Totp::generate(SHA512_SECRET, Some(options));
517        assert_eq!(code, "47863826");
518    }
519
520    // 6-digit tests (common use case)
521    #[test]
522    fn test_6_digit_sha1_time_59() {
523        let options = TotpOptions {
524            digits: 6,
525            algorithm: Algorithm::Sha1,
526            timestamp: Some(59),
527            ..Default::default()
528        };
529        let code = Totp::generate(SHA1_SECRET, Some(options));
530        // Last 6 digits of 94287082
531        assert_eq!(code, "287082");
532    }
533
534    #[test]
535    fn test_6_digit_sha256_time_59() {
536        let options = TotpOptions {
537            digits: 6,
538            algorithm: Algorithm::Sha256,
539            timestamp: Some(59),
540            ..Default::default()
541        };
542        let code = Totp::generate(SHA256_SECRET, Some(options));
543        // Last 6 digits of 46119246
544        assert_eq!(code, "119246");
545    }
546
547    #[test]
548    fn test_6_digit_sha512_time_59() {
549        let options = TotpOptions {
550            digits: 6,
551            algorithm: Algorithm::Sha512,
552            timestamp: Some(59),
553            ..Default::default()
554        };
555        let code = Totp::generate(SHA512_SECRET, Some(options));
556        // Last 6 digits of 90693936
557        assert_eq!(code, "693936");
558    }
559
560    // Validation tests
561    #[test]
562    fn test_validate_current_code() {
563        let options = TotpOptions {
564            digits: 6,
565            timestamp: Some(59),
566            ..Default::default()
567        };
568        let code = Totp::generate(SHA1_SECRET, Some(options.clone()));
569
570        let validate_options = TotpValidateOptions { options, skew: 1 };
571        assert!(Totp::validate(SHA1_SECRET, &code, Some(validate_options)));
572    }
573
574    #[test]
575    fn test_validate_rejects_invalid_code() {
576        let options = TotpOptions {
577            digits: 6,
578            timestamp: Some(59),
579            ..Default::default()
580        };
581        let validate_options = TotpValidateOptions { options, skew: 1 };
582        assert!(!Totp::validate(
583            SHA1_SECRET,
584            "000000",
585            Some(validate_options)
586        ));
587    }
588
589    #[test]
590    fn test_validate_with_skew_previous_period() {
591        // Generate code for time 59 (counter 1)
592        let gen_options = TotpOptions {
593            digits: 6,
594            timestamp: Some(59),
595            ..Default::default()
596        };
597        let code = Totp::generate(SHA1_SECRET, Some(gen_options));
598
599        // Validate at time 89 (counter 2, but skew=1 should accept counter 1)
600        let validate_options = TotpValidateOptions {
601            options: TotpOptions {
602                digits: 6,
603                timestamp: Some(89),
604                ..Default::default()
605            },
606            skew: 1,
607        };
608        assert!(Totp::validate(SHA1_SECRET, &code, Some(validate_options)));
609    }
610
611    #[test]
612    fn test_validate_with_skew_next_period() {
613        // Generate code for time 59 (counter 1)
614        let gen_options = TotpOptions {
615            digits: 6,
616            timestamp: Some(59),
617            ..Default::default()
618        };
619        let code = Totp::generate(SHA1_SECRET, Some(gen_options));
620
621        // Validate at time 29 (counter 0, but skew=1 should accept counter 1)
622        let validate_options = TotpValidateOptions {
623            options: TotpOptions {
624                digits: 6,
625                timestamp: Some(29),
626                ..Default::default()
627            },
628            skew: 1,
629        };
630        assert!(Totp::validate(SHA1_SECRET, &code, Some(validate_options)));
631    }
632
633    #[test]
634    fn test_validate_rejects_outside_skew() {
635        // Generate code for time 59 (counter 1)
636        let gen_options = TotpOptions {
637            digits: 6,
638            timestamp: Some(59),
639            ..Default::default()
640        };
641        let code = Totp::generate(SHA1_SECRET, Some(gen_options));
642
643        // Validate at time 119 (counter 3, skew=1 only accepts counters 2,3,4)
644        let validate_options = TotpValidateOptions {
645            options: TotpOptions {
646                digits: 6,
647                timestamp: Some(119),
648                ..Default::default()
649            },
650            skew: 1,
651        };
652        assert!(!Totp::validate(SHA1_SECRET, &code, Some(validate_options)));
653    }
654
655    #[test]
656    fn test_validate_rejects_wrong_length() {
657        let validate_options = TotpValidateOptions {
658            options: TotpOptions {
659                digits: 6,
660                timestamp: Some(59),
661                ..Default::default()
662            },
663            skew: 1,
664        };
665
666        // Too short
667        assert!(!Totp::validate(
668            SHA1_SECRET,
669            "12345",
670            Some(validate_options.clone())
671        ));
672
673        // Too long
674        assert!(!Totp::validate(
675            SHA1_SECRET,
676            "1234567",
677            Some(validate_options)
678        ));
679    }
680
681    #[test]
682    fn test_validate_trims_whitespace() {
683        let options = TotpOptions {
684            digits: 6,
685            timestamp: Some(59),
686            ..Default::default()
687        };
688        let code = Totp::generate(SHA1_SECRET, Some(options.clone()));
689
690        let validate_options = TotpValidateOptions { options, skew: 1 };
691
692        // Should accept code with leading/trailing whitespace
693        let padded_code = format!("  {}  ", code);
694        assert!(Totp::validate(
695            SHA1_SECRET,
696            &padded_code,
697            Some(validate_options)
698        ));
699    }
700
701    #[test]
702    fn test_60_second_period() {
703        let options_30 = TotpOptions {
704            digits: 6,
705            timestamp: Some(59),
706            period: 30,
707            ..Default::default()
708        };
709        let options_60 = TotpOptions {
710            digits: 6,
711            timestamp: Some(59),
712            period: 60,
713            ..Default::default()
714        };
715
716        let code_30 = Totp::generate(SHA1_SECRET, Some(options_30));
717        let code_60 = Totp::generate(SHA1_SECRET, Some(options_60));
718
719        // Different periods should produce different codes (same counter value)
720        // At time 59: 30-second period has counter 1, 60-second period has counter 0
721        assert_ne!(code_30, code_60);
722    }
723
724    // Cross-SDK compatibility tests (TypeScript SDK vectors)
725    #[test]
726    fn test_ts_sdk_compat_unix_epoch() {
727        // TypeScript SDK test vector: time=0, secret=0x48656c6c6f21deadbeef
728        let secret = hex::decode("48656c6c6f21deadbeef").unwrap();
729        let options = TotpOptions {
730            digits: 6,
731            algorithm: Algorithm::Sha1,
732            period: 30,
733            timestamp: Some(0),
734        };
735        let code = Totp::generate(&secret, Some(options));
736        assert_eq!(code, "282760");
737    }
738
739    #[test]
740    fn test_ts_sdk_compat_2016_timestamp() {
741        // TypeScript SDK test vector: time=1465324707000ms = 1465324707s
742        let secret = hex::decode("48656c6c6f21deadbeef").unwrap();
743        let options = TotpOptions {
744            digits: 6,
745            algorithm: Algorithm::Sha1,
746            period: 30,
747            timestamp: Some(1465324707),
748        };
749        let code = Totp::generate(&secret, Some(options));
750        assert_eq!(code, "341128");
751    }
752
753    #[test]
754    fn test_ts_sdk_compat_leading_zero() {
755        // TypeScript SDK test vector with leading zero: time=1365324707000ms = 1365324707s
756        let secret = hex::decode("48656c6c6f21deadbeef").unwrap();
757        let options = TotpOptions {
758            digits: 6,
759            algorithm: Algorithm::Sha1,
760            period: 30,
761            timestamp: Some(1365324707),
762        };
763        let code = Totp::generate(&secret, Some(options));
764        assert_eq!(code, "089029");
765    }
766
767    #[test]
768    fn test_ts_sdk_compat_cycle_boundary_start() {
769        // TypeScript SDK: time=(1665644340000 + 1)ms = 1665644340s (counter 55521478)
770        let secret = hex::decode("48656c6c6f21deadbeef").unwrap();
771        let options = TotpOptions {
772            digits: 6,
773            algorithm: Algorithm::Sha1,
774            period: 30,
775            timestamp: Some(1665644340),
776        };
777        let code = Totp::generate(&secret, Some(options));
778        assert_eq!(code, "886842");
779    }
780
781    #[test]
782    fn test_ts_sdk_compat_cycle_boundary_end() {
783        // TypeScript SDK: time=(1665644340000 - 1)ms = 1665644339s (counter 55521477)
784        let secret = hex::decode("48656c6c6f21deadbeef").unwrap();
785        let options = TotpOptions {
786            digits: 6,
787            algorithm: Algorithm::Sha1,
788            period: 30,
789            timestamp: Some(1665644339),
790        };
791        let code = Totp::generate(&secret, Some(options));
792        assert_eq!(code, "134996");
793    }
794
795    // Edge cases
796    #[test]
797    fn test_default_options() {
798        // Ensure defaults work without panicking
799        let code = Totp::generate(SHA1_SECRET, None);
800        assert_eq!(code.len(), 6);
801    }
802
803    #[test]
804    fn test_validate_with_none_options() {
805        let code = Totp::generate(SHA1_SECRET, None);
806        assert!(Totp::validate(SHA1_SECRET, &code, None));
807    }
808
809    #[test]
810    fn test_constant_time_eq() {
811        assert!(constant_time_eq("123456", "123456"));
812        assert!(!constant_time_eq("123456", "654321"));
813        assert!(!constant_time_eq("123", "123456"));
814        assert!(!constant_time_eq("123456", "123"));
815    }
816
817    #[test]
818    fn test_constant_time_eq_empty() {
819        // Both empty - they are equal
820        assert!(constant_time_eq("", ""));
821    }
822
823    #[test]
824    fn test_counter_near_zero() {
825        // Test validation when counter is 0 (edge case for skew subtraction)
826        let options = TotpOptions {
827            digits: 6,
828            timestamp: Some(0), // counter = 0
829            ..Default::default()
830        };
831        let code = Totp::generate(SHA1_SECRET, Some(options.clone()));
832
833        let validate_options = TotpValidateOptions { options, skew: 1 };
834        assert!(Totp::validate(SHA1_SECRET, &code, Some(validate_options)));
835    }
836
837    #[test]
838    fn test_algorithm_enum_default() {
839        let algo: Algorithm = Default::default();
840        assert_eq!(algo, Algorithm::Sha1);
841    }
842
843    #[test]
844    fn test_algorithm_enum_clone_eq() {
845        let algo1 = Algorithm::Sha256;
846        let algo2 = algo1;
847        assert_eq!(algo1, algo2);
848    }
849
850    #[test]
851    fn test_totp_options_clone() {
852        let options = TotpOptions {
853            digits: 8,
854            algorithm: Algorithm::Sha512,
855            period: 60,
856            timestamp: Some(12345),
857        };
858        let cloned = options.clone();
859        assert_eq!(cloned.digits, 8);
860        assert_eq!(cloned.algorithm, Algorithm::Sha512);
861        assert_eq!(cloned.period, 60);
862        assert_eq!(cloned.timestamp, Some(12345));
863    }
864
865    // Unusual digit count tests
866    #[test]
867    fn test_digits_1() {
868        let options = TotpOptions {
869            digits: 1,
870            timestamp: Some(59),
871            ..Default::default()
872        };
873        let code = Totp::generate(SHA1_SECRET, Some(options.clone()));
874        assert_eq!(code.len(), 1);
875
876        // Should still validate
877        let validate_options = TotpValidateOptions { options, skew: 0 };
878        assert!(Totp::validate(SHA1_SECRET, &code, Some(validate_options)));
879    }
880
881    #[test]
882    fn test_digits_9() {
883        // 9 digits is the max that fits in u32 (10^9 = 1_000_000_000 < u32::MAX)
884        let options = TotpOptions {
885            digits: 9,
886            timestamp: Some(59),
887            ..Default::default()
888        };
889        let code = Totp::generate(SHA1_SECRET, Some(options.clone()));
890        assert_eq!(code.len(), 9);
891
892        // Should still validate
893        let validate_options = TotpValidateOptions { options, skew: 0 };
894        assert!(Totp::validate(SHA1_SECRET, &code, Some(validate_options)));
895    }
896
897    // RFC 4226 Appendix D HOTP test vectors
898    // Secret: "12345678901234567890" (ASCII), 6-digit codes
899    // These verify the underlying HOTP algorithm by using period=1 and timestamp=counter
900    #[test]
901    fn test_rfc4226_hotp_vectors() {
902        let expected = [
903            "755224", // counter 0
904            "287082", // counter 1
905            "359152", // counter 2
906            "969429", // counter 3
907            "338314", // counter 4
908            "254676", // counter 5
909            "287922", // counter 6
910            "162583", // counter 7
911            "399871", // counter 8
912            "520489", // counter 9
913        ];
914
915        for (counter, expected_code) in expected.iter().enumerate() {
916            let options = TotpOptions {
917                digits: 6,
918                algorithm: Algorithm::Sha1,
919                period: 1,                       // 1-second period so timestamp == counter
920                timestamp: Some(counter as u64), // counter value
921            };
922            let code = Totp::generate(SHA1_SECRET, Some(options));
923            assert_eq!(
924                &code, expected_code,
925                "RFC 4226 HOTP vector failed for counter {}",
926                counter
927            );
928        }
929    }
930}