Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Issue Description
The function totpPadSecret in the library contains a logic issue when padding secrets shorter than the required minLength. Specifically, the following line:
javascript
Copy code
const newSecret = new Array(minLength - currentLength + 1).join(hexSecret); Concatenates the secret (hexSecret) multiple times unnecessarily, leading to an incorrect padded result. Instead of properly extending the secret to meet the required length, it produces a duplicated string, which affects the generated HMAC and, consequently, the TOTP codes.
For example:
Secret: a3eee3d94bd287fa5a39 (10 bytes)
Expected padded output (to 20 bytes): a3eee3d94bd287fa5a39a3eee3d94bd287fa5a39 Actual output: a3eee3d94bd287fa5a39a3eee3d94bd287fa5a39a3eee3d94bd287fa5a39... (duplicated more than required) This issue results in a mismatch between the generated TOTP codes and those from standard implementations (e.g., Google Authenticator, other TOTP tools).
Proposed Solution
Replace the logic with a safer and more predictable padding approach:
javascript
Copy code
const newSecret = hexSecret.repeat(Math.ceil(minLength / hexSecret.length)); return newSecret.slice(0, minLength * 2); // Ensure it meets the required minLength This ensures the secret is repeated and truncated exactly to the required length, avoiding duplication errors. The corrected function now behaves as expected, producing compatible TOTP codes.
Testing
This fix has been tested with the following conditions:
Various secret lengths and encodings (shorter, equal, longer than minLength). TOTP codes validated against widely-used tools such as Google Authenticator and https://totp.danhersam.com/.