Skip to content

Commit

Permalink
Merge pull request #152 from arku3/main
Browse files Browse the repository at this point in the history
Fix TOTP custom period
  • Loading branch information
n0cloud authored Jan 3, 2024
2 parents 8d468d4 + dd14509 commit 0d32dab
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/time-based/time-based.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export class TimeBased {
config: ValidTotpConfig
): string[] {
const epoch = Math.floor(Date.now() / 1000);
const counter = Math.floor(epoch / DEFAULT_TOTP_PERIOD);
const counter = Math.floor(epoch / (config.period || DEFAULT_TOTP_PERIOD));

const counters = [counter];
if (options.drift && options.drift > 0) {
Expand Down
63 changes: 63 additions & 0 deletions test/otp.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,69 @@ describe("TOTP passcodes default config", () => {
});
});


describe("TOTP passcodes custom config", () => {
const key = Totp.generateKey({ issuer, user }, { period : 60, digits: 8 , secretSize: 20});
const driftValue = 1; // Should return 3 codes

const otherSecret = generateSecret(20);

const codes = Totp.generatePasscodes(
{ secret: key.secret, drift: driftValue },
key.config
);

test("drift with value 1 respected", () => {
expect(codes.length).toBe(3);
});

test("codes digits", () => {
codes.forEach((c) => {
expect(c.length).toBe(key.config.digits);
});
});

test("validation with key secret", () => {
const idx = Math.floor(Math.random() * codes.length); // Getting a random index
expect(
Totp.validate({
passcode: codes[idx],
secret: key.secret,
drift: driftValue,
}, key.config)
).toBe(true);
});

test("failed validation with other secret", () => {
const idx = Math.floor(Math.random() * codes.length); // Getting a random index
expect(
Totp.validate({
passcode: codes[idx],
secret: otherSecret,
drift: driftValue,
}, key.config)
).toBe(false);
});

test("invalid secret length", () => {
const secret = generateSecret(32);
expect(() => Totp.validate({ passcode: codes[1], secret }, key.config)).toThrow(
"Invalid secret"
);
});

test("valid secret length but wrong secret", () => {
const secret = generateSecret(20);
expect(Totp.validate({ passcode: codes[1], secret }, key.config)).toBe(false);
});

test("invalid passcode length", () => {
expect(() =>
Totp.validate({ passcode: "123", secret: key.secret }, key.config)
).toThrow("Invalid passcode");
});
});

describe("TOTP passcodes hashing algorithms", () => {
const sha256Config = generateConfig({ algo: "sha256" });

Expand Down

0 comments on commit 0d32dab

Please sign in to comment.