Compare commits
5 Commits
9b5be8b554
...
v3.1.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
9f74c8b56c
|
|||
|
c7ce8686d3
|
|||
|
9a68f6fdad
|
|||
|
11a002052d
|
|||
|
674ff1ddb5
|
151
README.md
151
README.md
@@ -15,57 +15,66 @@ A lightweight JWT implementation with ZERO dependencies for Cloudflare Workers.
|
|||||||
|
|
||||||
## Install
|
## Install
|
||||||
|
|
||||||
```
|
```bash
|
||||||
npm i @tsndr/cloudflare-worker-jwt
|
npm i @tsndr/cloudflare-worker-jwt
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
## Examples
|
## Examples
|
||||||
|
|
||||||
### Basic Example
|
### Basic Example
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
async () => {
|
async () => {
|
||||||
import jwt from '@tsndr/cloudflare-worker-jwt'
|
import jwt from "@tsndr/cloudflare-worker-jwt"
|
||||||
|
|
||||||
// Creating a token
|
// Create a token
|
||||||
const token = await jwt.sign({ name: 'John Doe', email: 'john.doe@gmail.com' }, 'secret')
|
const token = await sign({
|
||||||
|
sub: "1234",
|
||||||
|
name: "John Doe",
|
||||||
|
email: "john.doe@gmail.com"
|
||||||
|
}, "secret")
|
||||||
|
|
||||||
// Verifing token
|
// Verify token
|
||||||
const isValid = await jwt.verify(token, 'secret')
|
const verifiedToken = await verify(token, "secret")
|
||||||
|
|
||||||
// Check for validity
|
// Abort if token isn't valid
|
||||||
if (!isValid)
|
if (!verifiedToken)
|
||||||
return
|
return
|
||||||
|
|
||||||
// Decoding token
|
// Access token payload
|
||||||
const { payload } = jwt.decode(token)
|
const { payload } = verifiedToken
|
||||||
|
|
||||||
|
// { sub: "1234", name: "John Doe", email: "john.doe@gmail.com" }
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
### Restrict Timeframe
|
### Restrict Timeframe
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
async () => {
|
async () => {
|
||||||
import jwt from '@tsndr/cloudflare-worker-jwt'
|
import jwt from "@tsndr/cloudflare-worker-jwt"
|
||||||
|
|
||||||
// Creating a token
|
// Create a token
|
||||||
const token = await jwt.sign({
|
const token = await sign({
|
||||||
name: 'John Doe',
|
sub: "1234",
|
||||||
email: 'john.doe@gmail.com',
|
name: "John Doe",
|
||||||
|
email: "john.doe@gmail.com",
|
||||||
nbf: Math.floor(Date.now() / 1000) + (60 * 60), // Not before: Now + 1h
|
nbf: Math.floor(Date.now() / 1000) + (60 * 60), // Not before: Now + 1h
|
||||||
exp: Math.floor(Date.now() / 1000) + (2 * (60 * 60)) // Expires: Now + 2h
|
exp: Math.floor(Date.now() / 1000) + (2 * (60 * 60)) // Expires: Now + 2h
|
||||||
}, 'secret')
|
}, "secret")
|
||||||
|
|
||||||
// Verifing token
|
// Verify token
|
||||||
const isValid = await jwt.verify(token, 'secret') // false
|
const verifiedToken = await verify(token, "secret") // false
|
||||||
|
|
||||||
// Check for validity
|
// Abort if token isn't valid
|
||||||
if (!isValid)
|
if (!verifiedToken)
|
||||||
return
|
return
|
||||||
|
|
||||||
// Decoding token
|
// Access token payload
|
||||||
const { payload } = jwt.decode(token) // { name: 'John Doe', email: 'john.doe@gmail.com', ... }
|
const { payload } = verifiedToken
|
||||||
|
|
||||||
|
// { sub: "1234", name: "John Doe", email: "john.doe@gmail.com", ... }
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -78,79 +87,101 @@ async () => {
|
|||||||
<hr>
|
<hr>
|
||||||
|
|
||||||
### Sign
|
### Sign
|
||||||
#### `jwt.sign(payload, secret, [options])`
|
#### `sign(payload, secret, [options])`
|
||||||
|
|
||||||
Signs a payload and returns the token.
|
Signs a payload and returns the token.
|
||||||
|
|
||||||
|
|
||||||
#### Arguments
|
#### Arguments
|
||||||
|
|
||||||
Argument | Type | Status | Default | Description
|
Argument | Type | Status | Default | Description
|
||||||
------------------------ | ------------------ | -------- | ----------- | -----------
|
------------------------ | ----------------------------------- | -------- | ----------- | -----------
|
||||||
`payload` | `object` | required | - | The payload object. To use `nbf` (Not Before) and/or `exp` (Expiration Time) add `nbf` and/or `exp` to the payload.
|
`payload` | `object` | required | - | The payload object. To use `nbf` (Not Before) and/or `exp` (Expiration Time) add `nbf` and/or `exp` to the payload.
|
||||||
`secret` | `string`, `JsonWebKey`, `CryptoKey` | required | - | A string which is used to sign the payload.
|
`secret` | `string`, `JsonWebKey`, `CryptoKey` | required | - | A string which is used to sign the payload.
|
||||||
`options` | `string`, `object` | optional | `HS256` | Either the `algorithm` string or an object.
|
`options` | `string`, `object` | optional | `HS256` | Either the `algorithm` string or an object.
|
||||||
`options.algorithm` | `string` | optional | `HS256` | See [Available Algorithms](#available-algorithms)
|
`options.algorithm` | `string` | optional | `HS256` | See [Available Algorithms](#available-algorithms)
|
||||||
`options.keyid` | `string` | optional | `undefined` | The `keyid` or `kid` to be set in the header of the resulting JWT.
|
`options.header` | `object` | optional | `undefined` | Extend the header of the resulting JWT.
|
||||||
|
|
||||||
|
|
||||||
#### `return`
|
#### `return`
|
||||||
|
|
||||||
Returns token as a `string`.
|
Returns token as a `string`.
|
||||||
|
|
||||||
|
|
||||||
<hr>
|
<hr>
|
||||||
|
|
||||||
### Verify
|
|
||||||
#### `jwt.verify(token, secret, [options])`
|
|
||||||
|
|
||||||
Verifies the integrity of the token and returns a boolean value.
|
### Verify
|
||||||
|
#### `verify(token, secret, [options])`
|
||||||
|
|
||||||
|
Verifies the integrity of the token.
|
||||||
|
|
||||||
Argument | Type | Status | Default | Description
|
Argument | Type | Status | Default | Description
|
||||||
------------------------ | ------------------ | -------- | ------- | -----------
|
------------------------ | ----------------------------------- | -------- | ------- | -----------
|
||||||
`token` | `string` | required | - | The token string generated by `jwt.sign()`.
|
`token` | `string` | required | - | The token string generated by `sign()`.
|
||||||
`secret` | `string`, `JsonWebKey`, `CryptoKey` | required | - | The string which was used to sign the payload.
|
`secret` | `string`, `JsonWebKey`, `CryptoKey` | required | - | The string which was used to sign the payload.
|
||||||
`options` | `string`, `object` | optional | `HS256` | Either the `algorithm` string or an object.
|
`options` | `string`, `object` | optional | `HS256` | Either the `algorithm` string or an object.
|
||||||
`options.algorithm` | `string` | optional | `HS256` | See [Available Algorithms](#available-algorithms)
|
`options.algorithm` | `string` | optional | `HS256` | See [Available Algorithms](#available-algorithms)
|
||||||
`options.clockTolerance` | `number` | optional | `0` | Clock tolerance in seconds, to help with slighly out of sync systems.
|
`options.clockTolerance` | `number` | optional | `0` | Clock tolerance in seconds, to help with slighly out of sync systems.
|
||||||
`options.throwError` | `boolean` | optional | `false` | By default this we will only throw implementation errors, only set this to `true` if you want verification errors to be thrown as well.
|
`options.throwError` | `boolean` | optional | `false` | By default this we will only throw integration errors, only set this to `true` if you want verification errors to be thrown as well.
|
||||||
|
|
||||||
|
|
||||||
#### `throws`
|
#### `throws`
|
||||||
If `options.throwError` is `true` and the token is invalid, an error will be thrown.
|
|
||||||
|
Throws integration errors and if `options.throwError` is set to `true` also throws `ALG_MISMATCH`, `NOT_YET_VALID`, `EXPIRED` or `INVALID_SIGNATURE`.
|
||||||
|
|
||||||
|
|
||||||
#### `return`
|
#### `return`
|
||||||
Returns `true` if signature, `nbf` (if set) and `exp` (if set) are valid, otherwise returns `false`.
|
|
||||||
|
|
||||||
<hr>
|
Returns the decoded token or `undefined`.
|
||||||
|
|
||||||
### Decode
|
```typescript
|
||||||
#### `jwt.decode(token)`
|
|
||||||
|
|
||||||
Returns the payload **without** verifying the integrity of the token. Please use `jwt.verify()` first to keep your application secure!
|
|
||||||
|
|
||||||
Argument | Type | Status | Default | Description
|
|
||||||
----------- | -------- | -------- | ------- | -----------
|
|
||||||
`token` | `string` | required | - | The token string generated by `jwt.sign()`.
|
|
||||||
|
|
||||||
#### `return`
|
|
||||||
Returns an `object` containing `header` and `payload`:
|
|
||||||
```javascript
|
|
||||||
{
|
{
|
||||||
header: {
|
header: {
|
||||||
alg: 'HS256',
|
alg: "HS256",
|
||||||
typ: 'JWT'
|
typ: "JWT"
|
||||||
},
|
},
|
||||||
payload: {
|
payload: {
|
||||||
name: 'John Doe',
|
name: "John Doe",
|
||||||
email: 'john.doe@gmail.com'
|
email: "john.doe@gmail.com"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
|
<hr>
|
||||||
|
|
||||||
|
|
||||||
|
### Decode
|
||||||
|
#### `decode(token)`
|
||||||
|
|
||||||
|
Just returns the decoded token **without** verifying verifying it. Please use `verify()` if you intend to verify it as well.
|
||||||
|
|
||||||
|
Argument | Type | Status | Default | Description
|
||||||
|
----------- | -------- | -------- | ------- | -----------
|
||||||
|
`token` | `string` | required | - | The token string generated by `sign()`.
|
||||||
|
|
||||||
|
|
||||||
|
#### `return`
|
||||||
|
|
||||||
|
Returns an `object` containing `header` and `payload`:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
{
|
||||||
|
header: {
|
||||||
|
alg: "HS256",
|
||||||
|
typ: "JWT"
|
||||||
|
},
|
||||||
|
payload: {
|
||||||
|
name: "John Doe",
|
||||||
|
email: "john.doe@gmail.com"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
### Available Algorithms
|
### Available Algorithms
|
||||||
- ES256
|
|
||||||
- ES384
|
- `ES256`, `ES384`, `ES512`
|
||||||
- ES512
|
- `HS256`, `HS384`, `HS512`
|
||||||
- HS256
|
- `RS256`, `RS384`, `RS512`
|
||||||
- HS384
|
|
||||||
- HS512
|
|
||||||
- RS256
|
|
||||||
- RS384
|
|
||||||
- RS512
|
|
||||||
4
package-lock.json
generated
4
package-lock.json
generated
@@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"name": "@tsndr/cloudflare-worker-jwt",
|
"name": "@tsndr/cloudflare-worker-jwt",
|
||||||
"version": "2.5.3",
|
"version": "3.1.0",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "@tsndr/cloudflare-worker-jwt",
|
"name": "@tsndr/cloudflare-worker-jwt",
|
||||||
"version": "2.5.3",
|
"version": "3.1.0",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@cloudflare/workers-types": "^4.20240925.0",
|
"@cloudflare/workers-types": "^4.20240925.0",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@tsndr/cloudflare-worker-jwt",
|
"name": "@tsndr/cloudflare-worker-jwt",
|
||||||
"version": "2.5.3",
|
"version": "3.1.0",
|
||||||
"description": "A lightweight JWT implementation with ZERO dependencies for Cloudflare Worker",
|
"description": "A lightweight JWT implementation with ZERO dependencies for Cloudflare Worker",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"exports": "./index.js",
|
"exports": "./index.js",
|
||||||
|
|||||||
55
src/index.ts
55
src/index.ts
@@ -137,17 +137,17 @@ const algorithms: JwtAlgorithms = {
|
|||||||
/**
|
/**
|
||||||
* Signs a payload and returns the token
|
* Signs a payload and returns the token
|
||||||
*
|
*
|
||||||
* @param {JwtPayload} payload The payload object. To use `nbf` (Not Before) and/or `exp` (Expiration Time) add `nbf` and/or `exp` to the payload.
|
* @param payload The payload object. To use `nbf` (Not Before) and/or `exp` (Expiration Time) add `nbf` and/or `exp` to the payload.
|
||||||
* @param {string | JsonWebKey | CryptoKey} secret A string which is used to sign the payload.
|
* @param secret A string which is used to sign the payload.
|
||||||
* @param {JwtSignOptions | JwtAlgorithm | string} [options={ algorithm: "HS256", header: { typ: "JWT" } }] The options object or the algorithm.
|
* @param [options={ algorithm: "HS256", header: { typ: "JWT" } }] The options object or the algorithm.
|
||||||
* @throws {Error} If there"s a validation issue.
|
* @throws If there"s a validation issue.
|
||||||
* @returns {Promise<string>} Returns token as a `string`.
|
* @returns Returns token as a `string`.
|
||||||
*/
|
*/
|
||||||
export async function sign<Payload = {}, Header = {}>(payload: JwtPayload<Payload>, secret: string | JsonWebKey | CryptoKey, options: JwtSignOptions<Header> | JwtAlgorithm = "HS256"): Promise<string> {
|
export async function sign<Payload = {}, Header = {}>(payload: JwtPayload<Payload>, secret: string | JsonWebKey | CryptoKey, options: JwtSignOptions<Header> | JwtAlgorithm = "HS256"): Promise<string> {
|
||||||
if (typeof options === "string")
|
if (typeof options === "string")
|
||||||
options = { algorithm: options }
|
options = { algorithm: options }
|
||||||
|
|
||||||
options = { algorithm: "HS256", header: { typ: "JWT" } as JwtHeader<Header>, ...options }
|
options = { algorithm: "HS256", header: { typ: "JWT", ...(options.header ?? {}) } as JwtHeader<Header>, ...options }
|
||||||
|
|
||||||
if (!payload || typeof payload !== "object")
|
if (!payload || typeof payload !== "object")
|
||||||
throw new Error("payload must be an object")
|
throw new Error("payload must be an object")
|
||||||
@@ -177,13 +177,13 @@ export async function sign<Payload = {}, Header = {}>(payload: JwtPayload<Payloa
|
|||||||
/**
|
/**
|
||||||
* Verifies the integrity of the token and returns a boolean value.
|
* Verifies the integrity of the token and returns a boolean value.
|
||||||
*
|
*
|
||||||
* @param {string} token The token string generated by `jwt.sign()`.
|
* @param token The token string generated by `sign()`.
|
||||||
* @param {string | JsonWebKey | CryptoKey} secret The string which was used to sign the payload.
|
* @param secret The string which was used to sign the payload.
|
||||||
* @param {JWTVerifyOptions | JWTAlgorithm} options The options object or the algorithm.
|
* @param options The options object or the algorithm.
|
||||||
* @throws {Error | string} Throws an error `string` if the token is invalid or an `Error-Object` if there"s a validation issue.
|
* @throws Throws integration errors and if `options.throwError` is set to `true` also throws `NOT_YET_VALID`, `EXPIRED` or `INVALID_SIGNATURE`.
|
||||||
* @returns {Promise<boolean>} Returns `true` if signature, `nbf` (if set) and `exp` (if set) are valid, otherwise returns `false`.
|
* @returns Returns the decoded token or `undefined`.
|
||||||
*/
|
*/
|
||||||
export async function verify(token: string, secret: string | JsonWebKey | CryptoKey, options: JwtVerifyOptions | JwtAlgorithm = "HS256"): Promise<boolean> {
|
export async function verify<Payload = {}, Header = {}>(token: string, secret: string | JsonWebKey | CryptoKey, options: JwtVerifyOptions | JwtAlgorithm = "HS256"): Promise<JwtData<Payload, Header> | undefined> {
|
||||||
if (typeof options === "string")
|
if (typeof options === "string")
|
||||||
options = { algorithm: options }
|
options = { algorithm: options }
|
||||||
options = { algorithm: "HS256", clockTolerance: 0, throwError: false, ...options }
|
options = { algorithm: "HS256", clockTolerance: 0, throwError: false, ...options }
|
||||||
@@ -207,41 +207,40 @@ export async function verify(token: string, secret: string | JsonWebKey | Crypto
|
|||||||
if (!algorithm)
|
if (!algorithm)
|
||||||
throw new Error("algorithm not found")
|
throw new Error("algorithm not found")
|
||||||
|
|
||||||
const { header, payload } = decode(token)
|
const decodedToken = decode<Payload, Header>(token)
|
||||||
|
|
||||||
if (header?.alg !== options.algorithm) {
|
|
||||||
if (options.throwError)
|
|
||||||
throw new Error("ALG_MISMATCH")
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if (!payload)
|
if (decodedToken.header?.alg !== options.algorithm)
|
||||||
throw new Error("PARSE_ERROR")
|
throw new Error("INVALID_SIGNATURE")
|
||||||
|
|
||||||
|
if (decodedToken.payload) {
|
||||||
const now = Math.floor(Date.now() / 1000)
|
const now = Math.floor(Date.now() / 1000)
|
||||||
|
|
||||||
if (payload.nbf && payload.nbf > now && (payload.nbf - now) > (options.clockTolerance ?? 0))
|
if (decodedToken.payload.nbf && decodedToken.payload.nbf > now && (decodedToken.payload.nbf - now) > (options.clockTolerance ?? 0))
|
||||||
throw new Error("NOT_YET_VALID")
|
throw new Error("NOT_YET_VALID")
|
||||||
|
|
||||||
if (payload.exp && payload.exp <= now && (now - payload.exp) > (options.clockTolerance ?? 0))
|
if (decodedToken.payload.exp && decodedToken.payload.exp <= now && (now - decodedToken.payload.exp) > (options.clockTolerance ?? 0))
|
||||||
throw new Error("EXPIRED")
|
throw new Error("EXPIRED")
|
||||||
|
}
|
||||||
|
|
||||||
const key = secret instanceof CryptoKey ? secret : await importKey(secret, algorithm, ["verify"])
|
const key = secret instanceof CryptoKey ? secret : await importKey(secret, algorithm, ["verify"])
|
||||||
|
|
||||||
return await crypto.subtle.verify(algorithm, key, base64UrlToArrayBuffer(tokenParts[2]), textToArrayBuffer(`${tokenParts[0]}.${tokenParts[1]}`))
|
if (!await crypto.subtle.verify(algorithm, key, base64UrlToArrayBuffer(tokenParts[2]), textToArrayBuffer(`${tokenParts[0]}.${tokenParts[1]}`)))
|
||||||
|
throw new Error("INVALID_SIGNATURE")
|
||||||
|
|
||||||
|
return decodedToken
|
||||||
} catch(err) {
|
} catch(err) {
|
||||||
if (options.throwError)
|
if (options.throwError)
|
||||||
throw err
|
throw err
|
||||||
return false
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns the payload **without** verifying the integrity of the token. Please use `jwt.verify()` first to keep your application secure!
|
* Returns the payload **without** verifying the integrity of the token. Please use `verify()` first to keep your application secure!
|
||||||
*
|
*
|
||||||
* @param {string} token The token string generated by `jwt.sign()`.
|
* @param token The token string generated by `sign()`.
|
||||||
* @returns {JwtData} Returns an `object` containing `header` and `payload`.
|
* @returns Returns an `object` containing `header` and `payload`.
|
||||||
*/
|
*/
|
||||||
export function decode<Payload = {}, Header = {}>(token: string): JwtData<Payload, Header> {
|
export function decode<Payload = {}, Header = {}>(token: string): JwtData<Payload, Header> {
|
||||||
return {
|
return {
|
||||||
|
|||||||
10
src/utils.ts
10
src/utils.ts
@@ -1,3 +1,5 @@
|
|||||||
|
export type KeyUsages = "sign" | "verify"
|
||||||
|
|
||||||
export function bytesToByteString(bytes: Uint8Array): string {
|
export function bytesToByteString(bytes: Uint8Array): string {
|
||||||
let byteStr = ""
|
let byteStr = ""
|
||||||
for (let i = 0; i < bytes.byteLength; i++) {
|
for (let i = 0; i < bytes.byteLength; i++) {
|
||||||
@@ -39,9 +41,10 @@ export function base64UrlToArrayBuffer(b64url: string): ArrayBuffer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function textToBase64Url(str: string): string {
|
export function textToBase64Url(str: string): string {
|
||||||
const encoder = new TextEncoder();
|
const encoder = new TextEncoder()
|
||||||
const charCodes = encoder.encode(str);
|
const charCodes = encoder.encode(str)
|
||||||
const binaryStr = String.fromCharCode(...charCodes);
|
const binaryStr = String.fromCharCode(...charCodes)
|
||||||
|
|
||||||
return btoa(binaryStr).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_")
|
return btoa(binaryStr).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -49,7 +52,6 @@ export function pemToBinary(pem: string): ArrayBuffer {
|
|||||||
return base64StringToArrayBuffer(pem.replace(/-+(BEGIN|END).*/g, "").replace(/\s/g, ""))
|
return base64StringToArrayBuffer(pem.replace(/-+(BEGIN|END).*/g, "").replace(/\s/g, ""))
|
||||||
}
|
}
|
||||||
|
|
||||||
type KeyUsages = "sign" | "verify";
|
|
||||||
export async function importTextSecret(key: string, algorithm: SubtleCryptoImportKeyAlgorithm, keyUsages: KeyUsages[]): Promise<CryptoKey> {
|
export async function importTextSecret(key: string, algorithm: SubtleCryptoImportKeyAlgorithm, keyUsages: KeyUsages[]): Promise<CryptoKey> {
|
||||||
return await crypto.subtle.importKey("raw", textToArrayBuffer(key), algorithm, true, keyUsages)
|
return await crypto.subtle.importKey("raw", textToArrayBuffer(key), algorithm, true, keyUsages)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -83,7 +83,7 @@ describe("Internal", () => {
|
|||||||
expect(decoded.payload).toMatchObject(payload)
|
expect(decoded.payload).toMatchObject(payload)
|
||||||
|
|
||||||
const verified = await jwt.verify(token, data.public, algorithm)
|
const verified = await jwt.verify(token, data.public, algorithm)
|
||||||
expect(verified).toBe(true)
|
expect(verified).toBeTruthy()
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -99,6 +99,6 @@ describe("External", async () => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
const verified = await jwt.verify(data.token, data.public, algorithm)
|
const verified = await jwt.verify(data.token, data.public, algorithm)
|
||||||
expect(verified).toBe(true)
|
expect(verified).toBeTruthy()
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
@@ -14,11 +14,11 @@ describe("Verify", async () => {
|
|||||||
const expiredToken = await jwt.sign({ sub: "me", exp: now - offset }, secret)
|
const expiredToken = await jwt.sign({ sub: "me", exp: now - offset }, secret)
|
||||||
|
|
||||||
test("Valid", () => {
|
test("Valid", () => {
|
||||||
expect(jwt.verify(validToken, secret, { throwError: true })).resolves.toBe(true)
|
expect(jwt.verify(validToken, secret, { throwError: true })).resolves.toBeTruthy()
|
||||||
})
|
})
|
||||||
|
|
||||||
test("Not yet expired", () => {
|
test("Not yet expired", () => {
|
||||||
expect(jwt.verify(notYetExpired, secret, { throwError: true })).resolves.toBe(true)
|
expect(jwt.verify(notYetExpired, secret, { throwError: true })).resolves.toBeTruthy()
|
||||||
})
|
})
|
||||||
|
|
||||||
test("Not yet valid", () => {
|
test("Not yet valid", () => {
|
||||||
@@ -30,8 +30,8 @@ describe("Verify", async () => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
test("Clock offset", () => {
|
test("Clock offset", () => {
|
||||||
expect(jwt.verify(notYetValidToken, secret, { clockTolerance: offset, throwError: true })).resolves.toBe(true)
|
expect(jwt.verify(notYetValidToken, secret, { clockTolerance: offset, throwError: true })).resolves.toBeTruthy()
|
||||||
expect(jwt.verify(expiredToken, secret, { clockTolerance: offset, throwError: true })).resolves.toBe(true)
|
expect(jwt.verify(expiredToken, secret, { clockTolerance: offset, throwError: true })).resolves.toBeTruthy()
|
||||||
|
|
||||||
expect(jwt.verify(notYetValidToken, secret, { clockTolerance: offset - 1, throwError: true })).rejects.toThrowError("NOT_YET_VALID")
|
expect(jwt.verify(notYetValidToken, secret, { clockTolerance: offset - 1, throwError: true })).rejects.toThrowError("NOT_YET_VALID")
|
||||||
expect(jwt.verify(expiredToken, secret, { clockTolerance: offset - 1, throwError: true })).rejects.toThrowError("EXPIRED")
|
expect(jwt.verify(expiredToken, secret, { clockTolerance: offset - 1, throwError: true })).rejects.toThrowError("EXPIRED")
|
||||||
|
|||||||
Reference in New Issue
Block a user