Skip to content

Commit

Permalink
Merge pull request #6 from oslo-project/totp-grace-period
Browse files Browse the repository at this point in the history
Add verifyTOTPWithGracePeriod()
  • Loading branch information
pilcrowonpaper authored Dec 11, 2024
2 parents e44c8fa + ba21c8f commit 220637f
Show file tree
Hide file tree
Showing 4 changed files with 52 additions and 1 deletion.
1 change: 1 addition & 0 deletions docs/pages/reference/main/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,4 @@ title: "@oslojs/otp"
- [`generateTOTP()`](/reference/main/generateTOTP)
- [`verifyHOTP()`](/reference/main/verifyHOTP)
- [`verifyTOTP()`](/reference/main/verifyTOTP)
- [`verifyTOTPWithGracePeriod()`](/reference/main/verifyTOTPWithGracePeriod)
23 changes: 23 additions & 0 deletions docs/pages/reference/main/verifyTOTPWithGracePeriod.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
---
title: "verifyTOTPWithGracePeriod()"
---

Verifies a TOTP using [`verifyTOTP()`](/reference/main/verifyTOTP) with a grace period. If the grace period is 30 seconds for example, the OTP is valid if it was generated within the 30-second time span before or after the current machine time (60 seconds in total).

```ts
function verifyTOTPWithGracePeriod(
key: Uint8Array,
intervalInSeconds: number,
digits: number,
otp: string,
gracePeriodInSeconds: number
): boolean;
```

### Parameters

- `key`: HMAC key
- `intervalInSeconds`
- `digits`
- `otp`
- `gracePeriodInSeconds`
2 changes: 1 addition & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
export { generateHOTP, verifyHOTP, createHOTPKeyURI } from "./hotp.js";
export { generateTOTP, verifyTOTP, createTOTPKeyURI } from "./totp.js";
export { generateTOTP, verifyTOTP, verifyTOTPWithGracePeriod, createTOTPKeyURI } from "./totp.js";
27 changes: 27 additions & 0 deletions src/totp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,33 @@ export function verifyTOTP(
return valid;
}

export function verifyTOTPWithGracePeriod(
key: Uint8Array,
intervalInSeconds: number,
digits: number,
otp: string,
gracePeriodInSeconds: number
): boolean {
if (gracePeriodInSeconds < 0) {
throw new TypeError("Grace period must be a positive number");
}
const nowUnixMilliseconds = Date.now();
let counter = BigInt(
Math.floor((nowUnixMilliseconds - gracePeriodInSeconds * 1000) / (intervalInSeconds * 1000))
);
const maxCounterInclusive = BigInt(
Math.floor((nowUnixMilliseconds + gracePeriodInSeconds * 1000) / (intervalInSeconds * 1000))
);
while (counter <= maxCounterInclusive) {
const valid = verifyHOTP(key, counter, digits, otp);
if (valid) {
return true;
}
counter++;
}
return false;
}

export function createTOTPKeyURI(
issuer: string,
accountName: string,
Expand Down

0 comments on commit 220637f

Please sign in to comment.