55 * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
66 */
77
8+ /**
9+ * Valid OTP token lengths supported by the authentication system.
10+ * These values are enforced to ensure compatibility with the OTP verification flow.
11+ */
12+ const VALID_OTP_TOKEN_LENGTHS = [ 6 , 8 ]
13+ const DEFAULT_OTP_TOKEN_LENGTH = 8
14+
15+ /**
16+ * Validates and normalizes the OTP token length configuration.
17+ * Throws an error if the token length is invalid.
18+ *
19+ * @param {string|number|undefined } tokenLength - The token length from config or env var
20+ * @returns {number } Validated token length (6 or 8)
21+ * @throws {Error } If tokenLength is invalid (not 6 or 8)
22+ */
23+ function validateOtpTokenLength ( tokenLength ) {
24+ // If undefined, return default
25+ if ( tokenLength === undefined ) {
26+ return DEFAULT_OTP_TOKEN_LENGTH
27+ }
28+
29+ // Parse to number (handles string numbers like "6" or "8")
30+ const parsedLength = Number ( tokenLength )
31+
32+ // Check if it's one of the allowed values (includes() will return false for NaN or invalid numbers)
33+ if ( ! VALID_OTP_TOKEN_LENGTHS . includes ( parsedLength ) ) {
34+ throw new Error (
35+ `Invalid OTP token length: ${ tokenLength } . Valid values are ${ VALID_OTP_TOKEN_LENGTHS . join (
36+ ' or '
37+ ) } . `
38+ )
39+ }
40+
41+ return parsedLength
42+ }
43+
844/**
945 * Safely parses settings from either a JSON string or object
1046 * @param {string|object } settings - The settings
@@ -30,5 +66,8 @@ function parseSettings(settings) {
3066}
3167
3268module . exports = {
33- parseSettings
69+ parseSettings,
70+ validateOtpTokenLength,
71+ DEFAULT_OTP_TOKEN_LENGTH ,
72+ VALID_OTP_TOKEN_LENGTHS
3473}
0 commit comments