-
Notifications
You must be signed in to change notification settings - Fork 212
Expand file tree
/
Copy pathutils.js
More file actions
73 lines (64 loc) · 2.14 KB
/
utils.js
File metadata and controls
73 lines (64 loc) · 2.14 KB
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
/*
* Copyright (c) 2021, salesforce.com, inc.
* All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
* For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
/**
* Valid OTP token lengths supported by the authentication system.
* These values are enforced to ensure compatibility with the OTP verification flow.
*/
const VALID_OTP_TOKEN_LENGTHS = [6, 8]
const DEFAULT_OTP_TOKEN_LENGTH = 8
/**
* Validates and normalizes the OTP token length configuration.
* Throws an error if the token length is invalid.
*
* @param {string|number|undefined} tokenLength - The token length from config or env var
* @returns {number} Validated token length (6 or 8)
* @throws {Error} If tokenLength is invalid (not 6 or 8)
*/
function validateOtpTokenLength(tokenLength) {
// If undefined, return default
if (tokenLength === undefined) {
return DEFAULT_OTP_TOKEN_LENGTH
}
// Parse to number (handles string numbers like "6" or "8")
const parsedLength = Number(tokenLength)
// Check if it's one of the allowed values (includes() will return false for NaN or invalid numbers)
if (!VALID_OTP_TOKEN_LENGTHS.includes(parsedLength)) {
throw new Error(
`Invalid OTP token length: ${tokenLength}. Valid values are ${VALID_OTP_TOKEN_LENGTHS.join(
' or '
)}. `
)
}
return parsedLength
}
/**
* Safely parses settings from either a JSON string or object
* @param {string|object} settings - The settings
* @returns {object} Parsed settings object
*/
function parseSettings(settings) {
// If settings is already an object, return it
if (typeof settings === 'object' && settings !== null) {
return settings
}
// If settings is a string, try to parse it
if (typeof settings === 'string') {
try {
return JSON.parse(settings)
} catch (error) {
console.warn('Invalid json format:', error.message)
return
}
}
return
}
module.exports = {
parseSettings,
validateOtpTokenLength,
DEFAULT_OTP_TOKEN_LENGTH,
VALID_OTP_TOKEN_LENGTHS
}