Compare commits
20 Commits
v2.5.4
...
1b4c93adb2
| Author | SHA1 | Date | |
|---|---|---|---|
|
1b4c93adb2
|
|||
|
06c5605bf2
|
|||
|
a4edaba6f0
|
|||
|
b2a3b4c25f
|
|||
|
c691324515
|
|||
|
66385f323c
|
|||
|
1b6ac02f7c
|
|||
|
95e45e67f6
|
|||
|
5e6af9cf25
|
|||
|
d3d7e10b60
|
|||
|
fdaa618f65
|
|||
|
cce5a61777
|
|||
|
e57ccf7e1c
|
|||
|
0d4eb1919b
|
|||
|
ea136cf1a5
|
|||
|
457a989fe3
|
|||
|
9f74c8b56c
|
|||
|
c7ce8686d3
|
|||
|
9a68f6fdad
|
|||
|
11a002052d
|
20
.github/workflows/publish.yml
vendored
20
.github/workflows/publish.yml
vendored
@@ -1,8 +1,9 @@
|
||||
name: Publish
|
||||
run-name: Publish ${{ github.ref_name }}
|
||||
|
||||
on:
|
||||
release:
|
||||
types: [published]
|
||||
types: [ published ]
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
@@ -13,18 +14,27 @@ jobs:
|
||||
with:
|
||||
node-version: latest
|
||||
registry-url: https://registry.npmjs.org/
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
|
||||
- name: Run tests
|
||||
run: npm test
|
||||
|
||||
- name: Build
|
||||
run: npm run build
|
||||
|
||||
- name: Publish to npmjs
|
||||
run: npm publish --tag latest --access public
|
||||
env:
|
||||
NODE_AUTH_TOKEN: ${{secrets.NPM_TOKEN}}
|
||||
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
run: npm publish --tag ${{ contains(github.ref_name, '-') && 'pre' || 'latest' }} --access public
|
||||
|
||||
- uses: actions/setup-node@v3
|
||||
with:
|
||||
node-version: latest
|
||||
registry-url: https://npm.pkg.github.com/
|
||||
|
||||
- name: Publish to GPR
|
||||
run: npm publish --tag latest --access public
|
||||
env:
|
||||
NODE_AUTH_TOKEN: ${{secrets.GITHUB_TOKEN}}
|
||||
NODE_AUTH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: npm publish --tag ${{ contains(github.ref_name, '-') && 'pre' || 'latest' }} --access public
|
||||
31
.github/workflows/release.yml
vendored
Normal file
31
.github/workflows/release.yml
vendored
Normal file
@@ -0,0 +1,31 @@
|
||||
name: Release
|
||||
run-name: Release ${{ github.ref_name }}
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- 'v*'
|
||||
|
||||
jobs:
|
||||
release:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/setup-node@v3
|
||||
with:
|
||||
node-version: latest
|
||||
registry-url: https://registry.npmjs.org/
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
|
||||
- name: Run tests
|
||||
run: npm test
|
||||
|
||||
- name: Build
|
||||
run: npm run build
|
||||
|
||||
- name: Create release
|
||||
run: gh release create ${{ github.ref_name }} --draft ${{ contains(github.ref_name, '-') && '--prerelease --latest=false' || '--latest' }}
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
5
.github/workflows/test.yml
vendored
5
.github/workflows/test.yml
vendored
@@ -15,7 +15,12 @@ jobs:
|
||||
with:
|
||||
node-version: latest
|
||||
registry-url: https://registry.npmjs.org/
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
|
||||
- name: Run tests
|
||||
run: npm test
|
||||
|
||||
- name: Build
|
||||
run: npm run build
|
||||
160
README.md
160
README.md
@@ -15,57 +15,68 @@ A lightweight JWT implementation with ZERO dependencies for Cloudflare Workers.
|
||||
|
||||
## Install
|
||||
|
||||
```
|
||||
```bash
|
||||
npm i @tsndr/cloudflare-worker-jwt
|
||||
```
|
||||
|
||||
|
||||
## Examples
|
||||
|
||||
### Basic Example
|
||||
|
||||
```typescript
|
||||
import jwt from "@tsndr/cloudflare-worker-jwt"
|
||||
|
||||
async () => {
|
||||
import jwt from '@tsndr/cloudflare-worker-jwt'
|
||||
|
||||
// Creating a token
|
||||
const token = await jwt.sign({ name: 'John Doe', email: 'john.doe@gmail.com' }, 'secret')
|
||||
// Create a token
|
||||
const token = await jwt.sign({
|
||||
sub: "1234",
|
||||
name: "John Doe",
|
||||
email: "john.doe@gmail.com"
|
||||
}, "secret")
|
||||
|
||||
// Verifing token
|
||||
const isValid = await jwt.verify(token, 'secret')
|
||||
// Verify token
|
||||
const verifiedToken = await jwt.verify(token, "secret")
|
||||
|
||||
// Check for validity
|
||||
if (!isValid)
|
||||
// Abort if token isn't valid
|
||||
if (!verifiedToken)
|
||||
return
|
||||
|
||||
// Decoding token
|
||||
const { payload } = jwt.decode(token)
|
||||
// Access token payload
|
||||
const { payload } = verifiedToken
|
||||
|
||||
// { sub: "1234", name: "John Doe", email: "john.doe@gmail.com" }
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
### Restrict Timeframe
|
||||
|
||||
```typescript
|
||||
async () => {
|
||||
import jwt from '@tsndr/cloudflare-worker-jwt'
|
||||
import jwt from "@tsndr/cloudflare-worker-jwt"
|
||||
|
||||
// Creating a token
|
||||
async () => {
|
||||
|
||||
// Create a token
|
||||
const token = await jwt.sign({
|
||||
name: 'John Doe',
|
||||
email: 'john.doe@gmail.com',
|
||||
sub: "1234",
|
||||
name: "John Doe",
|
||||
email: "john.doe@gmail.com",
|
||||
nbf: Math.floor(Date.now() / 1000) + (60 * 60), // Not before: Now + 1h
|
||||
exp: Math.floor(Date.now() / 1000) + (2 * (60 * 60)) // Expires: Now + 2h
|
||||
}, 'secret')
|
||||
}, "secret")
|
||||
|
||||
// Verifing token
|
||||
const isValid = await jwt.verify(token, 'secret') // false
|
||||
// Verify token
|
||||
const verifiedToken = await jwt.verify(token, "secret")
|
||||
|
||||
// Check for validity
|
||||
if (!isValid)
|
||||
// Abort if token isn't valid
|
||||
if (!verifiedToken)
|
||||
return
|
||||
|
||||
// Decoding token
|
||||
const { payload } = jwt.decode(token) // { name: 'John Doe', email: 'john.doe@gmail.com', ... }
|
||||
// Access token payload
|
||||
const { payload } = verifiedToken
|
||||
|
||||
// { sub: "1234", name: "John Doe", email: "john.doe@gmail.com", ... }
|
||||
}
|
||||
```
|
||||
|
||||
@@ -78,79 +89,104 @@ async () => {
|
||||
<hr>
|
||||
|
||||
### Sign
|
||||
#### `jwt.sign(payload, secret, [options])`
|
||||
#### `sign(payload, secret, [options])`
|
||||
|
||||
Signs a payload and returns the token.
|
||||
|
||||
|
||||
#### Arguments
|
||||
|
||||
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.
|
||||
`secret` | `string`, `JsonWebKey`, `CryptoKey` | required | - | A string which is used to sign the payload.
|
||||
`secret` | `string`, `JsonWebKey`, `CryptoKey` | optional | - | A secret which is used to sign the payload.
|
||||
`options` | `string`, `object` | optional | `HS256` | Either the `algorithm` string or an object.
|
||||
`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`
|
||||
|
||||
Returns token as a `string`.
|
||||
|
||||
|
||||
<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
|
||||
------------------------ | ------------------ | -------- | ------- | -----------
|
||||
`token` | `string` | required | - | The token string generated by `jwt.sign()`.
|
||||
`secret` | `string`, `JsonWebKey`, `CryptoKey` | required | - | The string which was used to sign the payload.
|
||||
------------------------ | ----------------------------------- | -------- | ------- | -----------
|
||||
`token` | `string` | required | - | The token string generated by `sign()`.
|
||||
`secret` | `string`, `JsonWebKey`, `CryptoKey` | optional | - | The secret which was used to sign the payload.
|
||||
`options` | `string`, `object` | optional | `HS256` | Either the `algorithm` string or an object.
|
||||
`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.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`
|
||||
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`
|
||||
Returns `true` if signature, `nbf` (if set) and `exp` (if set) are valid, otherwise returns `false`.
|
||||
|
||||
<hr>
|
||||
Returns the decoded token or `undefined`.
|
||||
|
||||
### Decode
|
||||
#### `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
|
||||
```typescript
|
||||
{
|
||||
header: {
|
||||
alg: 'HS256',
|
||||
typ: 'JWT'
|
||||
alg: "HS256",
|
||||
typ: "JWT"
|
||||
},
|
||||
payload: {
|
||||
name: 'John Doe',
|
||||
email: 'john.doe@gmail.com'
|
||||
sub: "1234",
|
||||
name: "John Doe",
|
||||
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: {
|
||||
sub: "1234",
|
||||
name: "John Doe",
|
||||
email: "john.doe@gmail.com"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
### Available Algorithms
|
||||
- ES256
|
||||
- ES384
|
||||
- ES512
|
||||
- HS256
|
||||
- HS384
|
||||
- HS512
|
||||
- RS256
|
||||
- RS384
|
||||
- RS512
|
||||
|
||||
- `ES256`, `ES384`, `ES512`
|
||||
- `HS256`, `HS384`, `HS512`
|
||||
- `RS256`, `RS384`, `RS512`
|
||||
- `none`
|
||||
1229
package-lock.json
generated
1229
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
12
package.json
12
package.json
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@tsndr/cloudflare-worker-jwt",
|
||||
"version": "2.5.4",
|
||||
"version": "3.1.7",
|
||||
"description": "A lightweight JWT implementation with ZERO dependencies for Cloudflare Worker",
|
||||
"type": "module",
|
||||
"exports": "./index.js",
|
||||
@@ -30,10 +30,10 @@
|
||||
},
|
||||
"homepage": "https://github.com/tsndr/cloudflare-worker-jwt#readme",
|
||||
"devDependencies": {
|
||||
"@cloudflare/workers-types": "^4.20240925.0",
|
||||
"@edge-runtime/vm": "^4.0.3",
|
||||
"esbuild": "^0.24.0",
|
||||
"typescript": "^5.6.2",
|
||||
"vitest": "^2.1.1"
|
||||
"@cloudflare/workers-types": "^4.20250525.0",
|
||||
"@edge-runtime/vm": "^5.0.0",
|
||||
"esbuild": "^0.25.4",
|
||||
"typescript": "^5.8.3",
|
||||
"vitest": "^3.1.4"
|
||||
}
|
||||
}
|
||||
|
||||
94
src/index.ts
94
src/index.ts
@@ -1,7 +1,7 @@
|
||||
import {
|
||||
textToArrayBuffer,
|
||||
textToUint8Array,
|
||||
arrayBufferToBase64Url,
|
||||
base64UrlToArrayBuffer,
|
||||
base64UrlToUint8Array,
|
||||
textToBase64Url,
|
||||
importKey,
|
||||
decodePayload
|
||||
@@ -12,9 +12,9 @@ if (typeof crypto === "undefined" || !crypto.subtle)
|
||||
|
||||
/**
|
||||
* @typedef JwtAlgorithm
|
||||
* @type {"ES256" | "ES384" | "ES512" | "HS256" | "HS384" | "HS512" | "RS256" | "RS384" | "RS512"}
|
||||
* @type {"none" | "ES256" | "ES384" | "ES512" | "HS256" | "HS384" | "HS512" | "RS256" | "RS384" | "RS512"}
|
||||
*/
|
||||
export type JwtAlgorithm = "ES256" | "ES384" | "ES512" | "HS256" | "HS384" | "HS512" | "RS256" | "RS384" | "RS512"
|
||||
export type JwtAlgorithm = "none" | "ES256" | "ES384" | "ES512" | "HS256" | "HS384" | "HS512" | "RS256" | "RS384" | "RS512"
|
||||
|
||||
/**
|
||||
* @typedef JwtAlgorithms
|
||||
@@ -118,11 +118,12 @@ export type JwtVerifyOptions = {
|
||||
* @prop {JwtPayload} payload
|
||||
*/
|
||||
export type JwtData<Payload = {}, Header = {}> = {
|
||||
header?: JwtHeader<Header>
|
||||
payload?: JwtPayload<Payload>
|
||||
header: JwtHeader<Header>
|
||||
payload: JwtPayload<Payload>
|
||||
}
|
||||
|
||||
const algorithms: JwtAlgorithms = {
|
||||
none: { name: "none" },
|
||||
ES256: { name: "ECDSA", namedCurve: "P-256", hash: { name: "SHA-256" } },
|
||||
ES384: { name: "ECDSA", namedCurve: "P-384", hash: { name: "SHA-384" } },
|
||||
ES512: { name: "ECDSA", namedCurve: "P-521", hash: { name: "SHA-512" } },
|
||||
@@ -137,22 +138,22 @@ const algorithms: JwtAlgorithms = {
|
||||
/**
|
||||
* 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 {string | JsonWebKey | CryptoKey} 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.
|
||||
* @throws {Error} If there"s a validation issue.
|
||||
* @returns {Promise<string>} Returns token as a `string`.
|
||||
* @param payload The payload object. To use `nbf` (Not Before) and/or `exp` (Expiration Time) add `nbf` and/or `exp` to the payload.
|
||||
* @param secret A string which is used to sign the payload.
|
||||
* @param [options={ algorithm: "HS256", header: { typ: "JWT" } }] The options object or the algorithm.
|
||||
* @throws If there"s a validation issue.
|
||||
* @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 | JsonWebKeyWithKid | CryptoKey | undefined, options: JwtSignOptions<Header> | JwtAlgorithm = "HS256"): Promise<string> {
|
||||
if (typeof options === "string")
|
||||
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")
|
||||
throw new Error("payload must be an object")
|
||||
|
||||
if (!secret || (typeof secret !== "string" && typeof secret !== "object"))
|
||||
if (options.algorithm !== "none" && (!secret || (typeof secret !== "string" && typeof secret !== "object")))
|
||||
throw new Error("secret must be a string, a JWK object or a CryptoKey object")
|
||||
|
||||
if (typeof options.algorithm !== "string")
|
||||
@@ -168,8 +169,11 @@ export async function sign<Payload = {}, Header = {}>(payload: JwtPayload<Payloa
|
||||
|
||||
const partialToken = `${textToBase64Url(JSON.stringify({ ...options.header, alg: options.algorithm }))}.${textToBase64Url(JSON.stringify(payload))}`
|
||||
|
||||
const key = secret instanceof CryptoKey ? secret : await importKey(secret, algorithm, ["sign"])
|
||||
const signature = await crypto.subtle.sign(algorithm, key, textToArrayBuffer(partialToken))
|
||||
if (options.algorithm === "none")
|
||||
return partialToken
|
||||
|
||||
const key = secret instanceof CryptoKey ? secret : await importKey(secret!, algorithm, ["sign"])
|
||||
const signature = await crypto.subtle.sign(algorithm, key, textToUint8Array(partialToken))
|
||||
|
||||
return `${partialToken}.${arrayBufferToBase64Url(signature)}`
|
||||
}
|
||||
@@ -177,13 +181,13 @@ export async function sign<Payload = {}, Header = {}>(payload: JwtPayload<Payloa
|
||||
/**
|
||||
* Verifies the integrity of the token and returns a boolean value.
|
||||
*
|
||||
* @param {string} token The token string generated by `jwt.sign()`.
|
||||
* @param {string | JsonWebKey | CryptoKey} secret The string which was used to sign the payload.
|
||||
* @param {JWTVerifyOptions | JWTAlgorithm} 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.
|
||||
* @returns {Promise<boolean>} Returns `true` if signature, `nbf` (if set) and `exp` (if set) are valid, otherwise returns `false`.
|
||||
* @param token The token string generated by `sign()`.
|
||||
* @param secret The string which was used to sign the payload.
|
||||
* @param options The options object or the algorithm.
|
||||
* @throws Throws integration errors and if `options.throwError` is set to `true` also throws `NOT_YET_VALID`, `EXPIRED` or `INVALID_SIGNATURE`.
|
||||
* @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 | JsonWebKeyWithKid | CryptoKey | undefined, options: JwtVerifyOptions | JwtAlgorithm = "HS256"): Promise<JwtData<Payload, Header> | undefined> {
|
||||
if (typeof options === "string")
|
||||
options = { algorithm: options }
|
||||
options = { algorithm: "HS256", clockTolerance: 0, throwError: false, ...options }
|
||||
@@ -191,57 +195,61 @@ export async function verify(token: string, secret: string | JsonWebKey | Crypto
|
||||
if (typeof token !== "string")
|
||||
throw new Error("token must be a string")
|
||||
|
||||
if (typeof secret !== "string" && typeof secret !== "object")
|
||||
if (options.algorithm !== "none" && typeof secret !== "string" && typeof secret !== "object")
|
||||
throw new Error("secret must be a string, a JWK object or a CryptoKey object")
|
||||
|
||||
if (typeof options.algorithm !== "string")
|
||||
throw new Error("options.algorithm must be a string")
|
||||
|
||||
const tokenParts = token.split(".")
|
||||
const tokenParts = token.split(".", 3)
|
||||
|
||||
if (tokenParts.length !== 3)
|
||||
throw new Error("token must consist of 3 parts")
|
||||
if (tokenParts.length < 2)
|
||||
throw new Error("token must consist of 2 or more parts")
|
||||
|
||||
const [ tokenHeader, tokenPayload, tokenSignature ] = tokenParts
|
||||
|
||||
const algorithm: SubtleCryptoImportKeyAlgorithm = algorithms[options.algorithm]
|
||||
|
||||
if (!algorithm)
|
||||
throw new Error("algorithm not found")
|
||||
|
||||
const { header, payload } = decode(token)
|
||||
|
||||
if (header?.alg !== options.algorithm) {
|
||||
if (options.throwError)
|
||||
throw new Error("ALG_MISMATCH")
|
||||
return false
|
||||
}
|
||||
const decodedToken = decode<Payload, Header>(token)
|
||||
|
||||
try {
|
||||
if (!payload)
|
||||
throw new Error("PARSE_ERROR")
|
||||
if (decodedToken.header?.alg !== options.algorithm)
|
||||
throw new Error("INVALID_SIGNATURE")
|
||||
|
||||
if (decodedToken.payload) {
|
||||
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")
|
||||
|
||||
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")
|
||||
}
|
||||
|
||||
const key = secret instanceof CryptoKey ? secret : await importKey(secret, algorithm, ["verify"])
|
||||
if (algorithm.name === "none")
|
||||
return decodedToken
|
||||
|
||||
return await crypto.subtle.verify(algorithm, key, base64UrlToArrayBuffer(tokenParts[2]), textToArrayBuffer(`${tokenParts[0]}.${tokenParts[1]}`))
|
||||
const key = secret instanceof CryptoKey ? secret : await importKey(secret!, algorithm, ["verify"])
|
||||
|
||||
if (!await crypto.subtle.verify(algorithm, key, base64UrlToUint8Array(tokenSignature), textToUint8Array(`${tokenHeader}.${tokenPayload}`)))
|
||||
throw new Error("INVALID_SIGNATURE")
|
||||
|
||||
return decodedToken
|
||||
} catch(err) {
|
||||
if (options.throwError)
|
||||
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()`.
|
||||
* @returns {JwtData} Returns an `object` containing `header` and `payload`.
|
||||
* @param token The token string generated by `sign()`.
|
||||
* @returns Returns an `object` containing `header` and `payload`.
|
||||
*/
|
||||
export function decode<Payload = {}, Header = {}>(token: string): JwtData<Payload, Header> {
|
||||
return {
|
||||
|
||||
36
src/utils.ts
36
src/utils.ts
@@ -1,3 +1,5 @@
|
||||
export type KeyUsages = "sign" | "verify"
|
||||
|
||||
export function bytesToByteString(bytes: Uint8Array): string {
|
||||
let byteStr = ""
|
||||
for (let i = 0; i < bytes.byteLength; i++) {
|
||||
@@ -18,11 +20,11 @@ export function arrayBufferToBase64String(arrayBuffer: ArrayBuffer): string {
|
||||
return btoa(bytesToByteString(new Uint8Array(arrayBuffer)))
|
||||
}
|
||||
|
||||
export function base64StringToArrayBuffer(b64str: string): ArrayBuffer {
|
||||
return byteStringToBytes(atob(b64str)).buffer
|
||||
export function base64StringToUint8Array(b64str: string): Uint8Array {
|
||||
return byteStringToBytes(atob(b64str))
|
||||
}
|
||||
|
||||
export function textToArrayBuffer(str: string): ArrayBuffer {
|
||||
export function textToUint8Array(str: string): Uint8Array {
|
||||
return byteStringToBytes(str)
|
||||
}
|
||||
|
||||
@@ -34,27 +36,27 @@ export function arrayBufferToBase64Url(arrayBuffer: ArrayBuffer): string {
|
||||
return arrayBufferToBase64String(arrayBuffer).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_")
|
||||
}
|
||||
|
||||
export function base64UrlToArrayBuffer(b64url: string): ArrayBuffer {
|
||||
return base64StringToArrayBuffer(b64url.replace(/-/g, "+").replace(/_/g, "/").replace(/\s/g, ""))
|
||||
export function base64UrlToUint8Array(b64url: string): Uint8Array {
|
||||
return base64StringToUint8Array(b64url.replace(/-/g, "+").replace(/_/g, "/").replace(/\s/g, ""))
|
||||
}
|
||||
|
||||
export function textToBase64Url(str: string): string {
|
||||
const encoder = new TextEncoder();
|
||||
const charCodes = encoder.encode(str);
|
||||
const binaryStr = String.fromCharCode(...charCodes);
|
||||
const encoder = new TextEncoder()
|
||||
const charCodes = encoder.encode(str)
|
||||
const binaryStr = String.fromCharCode(...charCodes)
|
||||
|
||||
return btoa(binaryStr).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_")
|
||||
}
|
||||
|
||||
export function pemToBinary(pem: string): ArrayBuffer {
|
||||
return base64StringToArrayBuffer(pem.replace(/-+(BEGIN|END).*/g, "").replace(/\s/g, ""))
|
||||
export function pemToBinary(pem: string): Uint8Array {
|
||||
return base64StringToUint8Array(pem.replace(/-+(BEGIN|END).*/g, "").replace(/\s/g, ""))
|
||||
}
|
||||
|
||||
type KeyUsages = "sign" | "verify";
|
||||
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", textToUint8Array(key), algorithm, true, keyUsages)
|
||||
}
|
||||
|
||||
export async function importJwk(key: JsonWebKey, algorithm: SubtleCryptoImportKeyAlgorithm, keyUsages: KeyUsages[]): Promise<CryptoKey> {
|
||||
export async function importJwk(key: JsonWebKeyWithKid, algorithm: SubtleCryptoImportKeyAlgorithm, keyUsages: KeyUsages[]): Promise<CryptoKey> {
|
||||
return await crypto.subtle.importKey("jwk", key, algorithm, true, keyUsages)
|
||||
}
|
||||
|
||||
@@ -66,7 +68,7 @@ export async function importPrivateKey(key: string, algorithm: SubtleCryptoImpor
|
||||
return await crypto.subtle.importKey("pkcs8", pemToBinary(key), algorithm, true, keyUsages)
|
||||
}
|
||||
|
||||
export async function importKey(key: string | JsonWebKey, algorithm: SubtleCryptoImportKeyAlgorithm, keyUsages: KeyUsages[]): Promise<CryptoKey> {
|
||||
export async function importKey(key: string | JsonWebKeyWithKid, algorithm: SubtleCryptoImportKeyAlgorithm, keyUsages: KeyUsages[]): Promise<CryptoKey> {
|
||||
if (typeof key === "object")
|
||||
return importJwk(key, algorithm, keyUsages)
|
||||
|
||||
@@ -82,13 +84,9 @@ export async function importKey(key: string | JsonWebKey, algorithm: SubtleCrypt
|
||||
return importTextSecret(key, algorithm, keyUsages)
|
||||
}
|
||||
|
||||
export function decodePayload<T = any>(raw: string): T | undefined {
|
||||
try {
|
||||
export function decodePayload<T = any>(raw: string): T {
|
||||
const bytes = Array.from(atob(raw), char => char.charCodeAt(0));
|
||||
const decodedString = new TextDecoder("utf-8").decode(new Uint8Array(bytes));
|
||||
|
||||
return JSON.parse(decodedString);
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -2,8 +2,8 @@ import { describe, expect, test } from 'vitest'
|
||||
import jwt, { JwtAlgorithm } from '../src/index'
|
||||
|
||||
type Dataset = {
|
||||
public: string
|
||||
private: string
|
||||
public?: string
|
||||
private?: string
|
||||
token: string
|
||||
}
|
||||
|
||||
@@ -18,6 +18,9 @@ type Payload = {
|
||||
}
|
||||
|
||||
const data: Data = {
|
||||
'none': {
|
||||
token: 'eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ'
|
||||
},
|
||||
'ES256': {
|
||||
public: '-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEEVs/o5+uQbTjL3chynL4wXgUg2R9\nq9UU8I5mEovUf86QZ7kOBIjJwqnzD1omageEHWwHdBO6B+dFabmdT9POxg==\n-----END PUBLIC KEY-----',
|
||||
private: '-----BEGIN PRIVATE KEY-----\nMIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgevZzL1gdAFr88hb2\nOF/2NxApJCzGCEDdfSp6VQO30hyhRANCAAQRWz+jn65BtOMvdyHKcvjBeBSDZH2r\n1RTwjmYSi9R/zpBnuQ4EiMnCqfMPWiZqB4QdbAd0E7oH50VpuZ1P087G\n-----END PRIVATE KEY-----',
|
||||
@@ -72,7 +75,7 @@ const payload: Payload = {
|
||||
emoji: "😎"
|
||||
}
|
||||
|
||||
const jwtRegex = /^[a-zA-Z0-9\-_]+\.[a-zA-Z0-9\-_]+\.[a-zA-Z0-9\-_]+$/
|
||||
const jwtRegex = /^[a-zA-Z0-9\-_]+\.[a-zA-Z0-9\-_]+(\.[a-zA-Z0-9\-_]+)?$/
|
||||
|
||||
describe("Internal", () => {
|
||||
test.each(Object.entries(data) as [JwtAlgorithm, Dataset][])('%s', async (algorithm, data) => {
|
||||
@@ -83,7 +86,7 @@ describe("Internal", () => {
|
||||
expect(decoded.payload).toMatchObject(payload)
|
||||
|
||||
const verified = await jwt.verify(token, data.public, algorithm)
|
||||
expect(verified).toBe(true)
|
||||
expect(verified).toBeTruthy()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -99,6 +102,6 @@ describe("External", async () => {
|
||||
})
|
||||
|
||||
const verified = await jwt.verify(data.token, data.public, algorithm)
|
||||
expect(verified).toBe(true)
|
||||
expect(verified).toBeTruthy()
|
||||
})
|
||||
})
|
||||
@@ -13,27 +13,27 @@ describe("Verify", async () => {
|
||||
const notYetValidToken = await jwt.sign({ sub: "me", nbf: now + offset }, secret)
|
||||
const expiredToken = await jwt.sign({ sub: "me", exp: now - offset }, secret)
|
||||
|
||||
test("Valid", () => {
|
||||
expect(jwt.verify(validToken, secret, { throwError: true })).resolves.toBe(true)
|
||||
test("Valid", async () => {
|
||||
await expect(jwt.verify(validToken, secret, { throwError: true })).resolves.toBeTruthy()
|
||||
})
|
||||
|
||||
test("Not yet expired", () => {
|
||||
expect(jwt.verify(notYetExpired, secret, { throwError: true })).resolves.toBe(true)
|
||||
test("Not yet expired", async () => {
|
||||
await expect(jwt.verify(notYetExpired, secret, { throwError: true })).resolves.toBeTruthy()
|
||||
})
|
||||
|
||||
test("Not yet valid", () => {
|
||||
expect(jwt.verify(notYetValidToken, secret, { throwError: true })).rejects.toThrowError("NOT_YET_VALID")
|
||||
test("Not yet valid", async () => {
|
||||
await expect(jwt.verify(notYetValidToken, secret, { throwError: true })).rejects.toThrowError("NOT_YET_VALID")
|
||||
})
|
||||
|
||||
test("Expired", () => {
|
||||
expect(jwt.verify(expiredToken, secret, { throwError: true })).rejects.toThrowError("EXPIRED")
|
||||
test("Expired", async () => {
|
||||
await expect(jwt.verify(expiredToken, secret, { throwError: true })).rejects.toThrowError("EXPIRED")
|
||||
})
|
||||
|
||||
test("Clock offset", () => {
|
||||
expect(jwt.verify(notYetValidToken, secret, { clockTolerance: offset, throwError: true })).resolves.toBe(true)
|
||||
expect(jwt.verify(expiredToken, secret, { clockTolerance: offset, throwError: true })).resolves.toBe(true)
|
||||
test("Clock offset", async () => {
|
||||
await expect(jwt.verify(notYetValidToken, secret, { clockTolerance: offset, throwError: true })).resolves.toBeTruthy()
|
||||
await 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(expiredToken, secret, { clockTolerance: offset - 1, throwError: true })).rejects.toThrowError("EXPIRED")
|
||||
await expect(jwt.verify(notYetValidToken, secret, { clockTolerance: offset - 1, throwError: true })).rejects.toThrowError("NOT_YET_VALID")
|
||||
await expect(jwt.verify(expiredToken, secret, { clockTolerance: offset - 1, throwError: true })).rejects.toThrowError("EXPIRED")
|
||||
})
|
||||
})
|
||||
@@ -3,11 +3,11 @@ import {
|
||||
bytesToByteString,
|
||||
byteStringToBytes,
|
||||
arrayBufferToBase64String,
|
||||
base64StringToArrayBuffer,
|
||||
textToArrayBuffer,
|
||||
base64StringToUint8Array,
|
||||
textToUint8Array,
|
||||
arrayBufferToText,
|
||||
arrayBufferToBase64Url,
|
||||
base64UrlToArrayBuffer,
|
||||
base64UrlToUint8Array,
|
||||
textToBase64Url,
|
||||
pemToBinary,
|
||||
importTextSecret
|
||||
@@ -18,7 +18,7 @@ describe("Converters", () => {
|
||||
const testByteArray = [ 99, 108, 111, 117, 100, 102, 108, 97, 114, 101, 45, 119, 111, 114, 107, 101, 114, 45, 106, 119, 116 ]
|
||||
const testUint8Array = new Uint8Array(testByteArray)
|
||||
const testBase64String = "Y2xvdWRmbGFyZS13b3JrZXItand0"
|
||||
const testArrayBuffer = testUint8Array.buffer
|
||||
const testArrayBuffer = testUint8Array
|
||||
|
||||
test("bytesToByteString", () => {
|
||||
expect(bytesToByteString(testUint8Array)).toStrictEqual(testString)
|
||||
@@ -33,11 +33,11 @@ describe("Converters", () => {
|
||||
})
|
||||
|
||||
test("base64StringToArrayBuffer", () => {
|
||||
expect(base64StringToArrayBuffer(testBase64String)).toStrictEqual(testArrayBuffer)
|
||||
expect(base64StringToUint8Array(testBase64String)).toStrictEqual(testArrayBuffer)
|
||||
})
|
||||
|
||||
test("textToArrayBuffer", () => {
|
||||
expect(textToArrayBuffer(testString)).toStrictEqual(testUint8Array)
|
||||
expect(textToUint8Array(testString)).toStrictEqual(testUint8Array)
|
||||
})
|
||||
|
||||
test("arrayBufferToText", () => {
|
||||
@@ -49,7 +49,7 @@ describe("Converters", () => {
|
||||
})
|
||||
|
||||
test("base64UrlToArrayBuffer", () => {
|
||||
expect(base64UrlToArrayBuffer(testBase64String)).toStrictEqual(testArrayBuffer)
|
||||
expect(base64UrlToUint8Array(testBase64String)).toStrictEqual(testArrayBuffer)
|
||||
})
|
||||
|
||||
test("textToBase64Url", () => {
|
||||
@@ -67,7 +67,7 @@ describe("Imports", () => {
|
||||
const testAlgorithm = { name: "HMAC", hash: { name: "SHA-256" } }
|
||||
const testCryptoKey = { type: "secret", extractable: true, algorithm: { ...testAlgorithm, length: 168 }, usages: ["verify", "sign"] }
|
||||
|
||||
expect(await importTextSecret(testKey, testAlgorithm, ["verify", "sign"])).toMatchObject(testCryptoKey)
|
||||
await expect(importTextSecret(testKey, testAlgorithm, ["verify", "sign"])).resolves.toMatchObject(testCryptoKey)
|
||||
})
|
||||
|
||||
test.todo("importJwk")
|
||||
|
||||
Reference in New Issue
Block a user