Skip to content

Commit

Permalink
Changed logic for validate exp and nbf claims
Browse files Browse the repository at this point in the history
  • Loading branch information
Pinta365 committed Apr 6, 2024
1 parent f88ec0b commit 87eec18
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 7 deletions.
2 changes: 1 addition & 1 deletion deno.jsonc
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@cross/jwt",
"version": "0.2.0",
"version": "0.2.1",
"exports": "./mod.ts",

"tasks": {
Expand Down
14 changes: 8 additions & 6 deletions mod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,8 @@ export async function generateKeyPair(
*/
const defaultOptions: JWTOptions = {
clockSkewLeewaySeconds: 60,
validateExp: false,
validateNbf: false,
};

/**
Expand Down Expand Up @@ -205,7 +207,7 @@ export async function signJWT(
if (options?.validateExp) {
if (payload.exp) {
const currentTimestamp = Math.floor(Date.now() / 1000);
if (payload.exp <= currentTimestamp) {
if (currentTimestamp >= payload.exp) {
throw new JWTValidationError("JWT 'exp' claim cannot be in the past");
}
} else {
Expand All @@ -216,7 +218,7 @@ export async function signJWT(
if (options?.validateNbf) {
if (payload.nbf) {
const currentTimestamp = Math.floor(Date.now() / 1000);
if (currentTimestamp <= payload.nbf) {
if (currentTimestamp > payload.nbf) {
throw new JWTValidationError("JWT 'nbf' claim cannot be in the past");
}
} else {
Expand Down Expand Up @@ -305,9 +307,9 @@ export async function validateJWT(
if (options?.validateExp) {
if (payload.exp) {
const currentTimestamp = Math.floor(Date.now() / 1000);
const effectiveExpiry = currentTimestamp - (options?.clockSkewLeewaySeconds || 0);
const effectiveExpiry = payload.exp + (options?.clockSkewLeewaySeconds || 0);

if (payload.exp < effectiveExpiry) {
if (currentTimestamp > effectiveExpiry) {
throw new JWTExpiredError();
}
} else {
Expand All @@ -318,9 +320,9 @@ export async function validateJWT(
if (options?.validateNbf) {
if (payload.nbf) {
const currentTimestamp = Math.floor(Date.now() / 1000);
const effectiveNotBefore = currentTimestamp + (options?.clockSkewLeewaySeconds || 0);
const effectiveNotBefore = payload.nbf - (options?.clockSkewLeewaySeconds || 0);

if (payload.nbf > effectiveNotBefore) {
if (currentTimestamp < effectiveNotBefore) {
throw new JWTNotYetValidError();
}
} else {
Expand Down

0 comments on commit 87eec18

Please sign in to comment.