Compare commits
14 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
c9da88c4bb
|
|||
|
21ec1b6f2a
|
|||
|
|
97df6e7f81 | ||
|
|
7198501a40 | ||
|
cb6209b1b6
|
|||
|
8f4e5e3199
|
|||
|
594cdd6c05
|
|||
|
f85abf30a8
|
|||
|
095b1d43f3
|
|||
|
0bc128fec1
|
|||
|
f846695242
|
|||
|
695e1c0dfe
|
|||
|
64da4c625f
|
|||
|
e4038ae0a7
|
41
README.md
41
README.md
@@ -8,6 +8,9 @@ A lightweight JWT implementation with ZERO dependencies for Cloudflare Workers.
|
|||||||
- [Install](#install)
|
- [Install](#install)
|
||||||
- [Examples](#examples)
|
- [Examples](#examples)
|
||||||
- [Usage](#usage)
|
- [Usage](#usage)
|
||||||
|
- [Sign](#sign)
|
||||||
|
- [Verify](#verify)
|
||||||
|
- [Decode](#decode)
|
||||||
|
|
||||||
|
|
||||||
## Install
|
## Install
|
||||||
@@ -36,7 +39,7 @@ async () => {
|
|||||||
return
|
return
|
||||||
|
|
||||||
// Decoding token
|
// Decoding token
|
||||||
const payload = jwt.decode(token)
|
const { payload } = jwt.decode(token)
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -62,15 +65,20 @@ async () => {
|
|||||||
return
|
return
|
||||||
|
|
||||||
// Decoding token
|
// Decoding token
|
||||||
const payload = jwt.decode(token) // { name: 'John Doe', email: 'john.doe@gmail.com', ... }
|
const { payload } = jwt.decode(token) // { name: 'John Doe', email: 'john.doe@gmail.com', ... }
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
|
|
||||||
|
- [Sign](#sign)
|
||||||
|
- [Verify](#verify)
|
||||||
|
- [Decode](#decode)
|
||||||
|
|
||||||
<hr>
|
<hr>
|
||||||
|
|
||||||
### `jwt.sign(payload, secret, [options])`
|
### Sign
|
||||||
|
#### `jwt.sign(payload, secret, [options])`
|
||||||
|
|
||||||
Signs a payload and returns the token.
|
Signs a payload and returns the token.
|
||||||
|
|
||||||
@@ -80,14 +88,15 @@ Argument | Type | Satus | 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` | required | - | A string which is used to sign the payload.
|
`secret` | `string` | required | - | A string which is used to sign the payload.
|
||||||
`options` | `object`, `string` | optional | `{ algorithm: 'HS256' }` | The options object supporting `algorithm` and `keyid` or just the algorithm string. (See [Available Algorithms](#available-algorithms))
|
`options` | `object` | optional | `{ algorithm: 'HS256' }` | The options object supporting `algorithm` and `keyid`. (See [Available Algorithms](#available-algorithms))
|
||||||
|
|
||||||
#### `return`
|
#### `return`
|
||||||
Returns token as a `string`.
|
Returns token as a `string`.
|
||||||
|
|
||||||
<hr>
|
<hr>
|
||||||
|
|
||||||
### `jwt.verify(token, secret, [options])`
|
### Verify
|
||||||
|
#### `jwt.verify(token, secret, [options])`
|
||||||
|
|
||||||
Verifies the integrity of the token and returns a boolean value.
|
Verifies the integrity of the token and returns a boolean value.
|
||||||
|
|
||||||
@@ -95,14 +104,18 @@ Argument | Type | Satus | Default | Description
|
|||||||
----------- | -------- | -------- | ------- | -----------
|
----------- | -------- | -------- | ------- | -----------
|
||||||
`token` | `string` | required | - | The token string generated by `jwt.sign()`.
|
`token` | `string` | required | - | The token string generated by `jwt.sign()`.
|
||||||
`secret` | `string` | required | - | The string which was used to sign the payload.
|
`secret` | `string` | required | - | The string which was used to sign the payload.
|
||||||
`algorithm` | `object`, `string` | optional | `{ algorithm: 'HS256', throwError: false }` | The options object supporting `algorithm` or just the algorithm string. (See [Available Algorithms](#available-algorithms))
|
`options` | `object` | optional | `{ algorithm: 'HS256', throwError: false }` | The options object supporting `algorithm` and `throwError`. (See [Available Algorithms](#available-algorithms))
|
||||||
|
|
||||||
|
#### `throws`
|
||||||
|
If `options.throwError` is `true` and the token is invalid, an error will be thrown.
|
||||||
|
|
||||||
#### `return`
|
#### `return`
|
||||||
Returns `true` if signature, `nbf` (if set) and `exp` (if set) are valid, otherwise returns `false`.
|
Returns `true` if signature, `nbf` (if set) and `exp` (if set) are valid, otherwise returns `false`.
|
||||||
|
|
||||||
<hr>
|
<hr>
|
||||||
|
|
||||||
### `jwt.decode(token)`
|
### Decode
|
||||||
|
#### `jwt.decode(token)`
|
||||||
|
|
||||||
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 `jwt.verify()` first to keep your application secure!
|
||||||
|
|
||||||
@@ -111,7 +124,19 @@ Argument | Type | Satus | Default | Description
|
|||||||
`token` | `string` | required | - | The token string generated by `jwt.sign()`.
|
`token` | `string` | required | - | The token string generated by `jwt.sign()`.
|
||||||
|
|
||||||
#### `return`
|
#### `return`
|
||||||
Returns payload `object`.
|
Returns an `object` containing `header` and `payload`:
|
||||||
|
```javascript
|
||||||
|
{
|
||||||
|
header: {
|
||||||
|
alg: 'HS256',
|
||||||
|
typ: 'JWT'
|
||||||
|
},
|
||||||
|
payload: {
|
||||||
|
name: 'John Doe',
|
||||||
|
email: 'john.doe@gmail.com'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
### Available Algorithms
|
### Available Algorithms
|
||||||
- ES256
|
- ES256
|
||||||
|
|||||||
9
index.d.ts
vendored
9
index.d.ts
vendored
@@ -33,9 +33,9 @@ declare class JWT {
|
|||||||
* 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 `jwt.verify()` first to keep your application secure!
|
||||||
*
|
*
|
||||||
* @param {string} token The token string generated by `jwt.sign()`.
|
* @param {string} token The token string generated by `jwt.sign()`.
|
||||||
* @returns {object | null} Returns payload `object`.
|
* @returns {JWTDecodeReturn} Returns an `object` containing `header` and `payload`.
|
||||||
*/
|
*/
|
||||||
decode(token: string): object | null
|
decode(token: string): JWTDecodeReturn
|
||||||
}
|
}
|
||||||
declare const _exports: JWT
|
declare const _exports: JWT
|
||||||
|
|
||||||
@@ -52,4 +52,9 @@ type JWTVerifyOptions = {
|
|||||||
throwError?: boolean
|
throwError?: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type JWTDecodeReturn = {
|
||||||
|
header: object,
|
||||||
|
payload: object
|
||||||
|
}
|
||||||
|
|
||||||
export = _exports
|
export = _exports
|
||||||
11
index.js
11
index.js
@@ -56,6 +56,7 @@ class JWT {
|
|||||||
async sign(payload, secret, options = { algorithm: 'HS256', header: { typ: 'JWT' } }) {
|
async sign(payload, secret, options = { algorithm: 'HS256', header: { typ: 'JWT' } }) {
|
||||||
if (typeof options === 'string')
|
if (typeof options === 'string')
|
||||||
options = { algorithm: options, header: { typ: 'JWT' } }
|
options = { algorithm: options, header: { typ: 'JWT' } }
|
||||||
|
options = { algorithm: 'HS256', header: { typ: 'JWT' }, ...options }
|
||||||
if (payload === null || typeof payload !== 'object')
|
if (payload === null || typeof payload !== 'object')
|
||||||
throw new Error('payload must be an object')
|
throw new Error('payload must be an object')
|
||||||
if (typeof secret !== 'string')
|
if (typeof secret !== 'string')
|
||||||
@@ -82,6 +83,7 @@ class JWT {
|
|||||||
async verify(token, secret, options = { algorithm: 'HS256', throwError: false }) {
|
async verify(token, secret, options = { algorithm: 'HS256', throwError: false }) {
|
||||||
if (typeof options === 'string')
|
if (typeof options === 'string')
|
||||||
options = { algorithm: options }
|
options = { algorithm: options }
|
||||||
|
options = { algorithm: 'HS256', throwError: false, ...options }
|
||||||
if (typeof token !== 'string')
|
if (typeof token !== 'string')
|
||||||
throw new Error('token must be a string')
|
throw new Error('token must be a string')
|
||||||
if (typeof secret !== 'string')
|
if (typeof secret !== 'string')
|
||||||
@@ -94,7 +96,7 @@ class JWT {
|
|||||||
const importAlgorithm = this.algorithms[options.algorithm]
|
const importAlgorithm = this.algorithms[options.algorithm]
|
||||||
if (!importAlgorithm)
|
if (!importAlgorithm)
|
||||||
throw new Error('algorithm not found')
|
throw new Error('algorithm not found')
|
||||||
const payload = this.decode(token)
|
const { payload } = this.decode(token)
|
||||||
if (payload.nbf && payload.nbf > Math.floor(Date.now() / 1000)) {
|
if (payload.nbf && payload.nbf > Math.floor(Date.now() / 1000)) {
|
||||||
if (options.throwError)
|
if (options.throwError)
|
||||||
throw 'NOT_YET_VALID'
|
throw 'NOT_YET_VALID'
|
||||||
@@ -113,10 +115,13 @@ class JWT {
|
|||||||
} else
|
} else
|
||||||
keyData = this._utf8ToUint8Array(secret)
|
keyData = this._utf8ToUint8Array(secret)
|
||||||
const key = await crypto.subtle.importKey(keyFormat, keyData, importAlgorithm, false, ['verify'])
|
const key = await crypto.subtle.importKey(keyFormat, keyData, importAlgorithm, false, ['verify'])
|
||||||
return await crypto.subtle.verify(importAlgorithm, key, Base64URL.parse(tokenParts[2]), `${tokenParts[0]}.${tokenParts[1]}`)
|
return await crypto.subtle.verify(importAlgorithm, key, Base64URL.parse(tokenParts[2]), this._utf8ToUint8Array(`${tokenParts[0]}.${tokenParts[1]}`))
|
||||||
}
|
}
|
||||||
decode(token) {
|
decode(token) {
|
||||||
return this._decodePayload(token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/'))
|
return {
|
||||||
|
header: this._decodePayload(token.split('.')[0].replace(/-/g, '+').replace(/_/g, '/')),
|
||||||
|
payload: this._decodePayload(token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/'))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
const { subtle } = require('crypto').webcrypto
|
const { subtle } = require('node:crypto').webcrypto
|
||||||
Object.defineProperty(global, 'crypto', {
|
Object.defineProperty(global, 'crypto', {
|
||||||
value: { subtle }
|
value: { subtle }
|
||||||
})
|
})
|
||||||
@@ -115,12 +115,14 @@ test.each(Object.entries(secrets))(`Self test: %s`, async (algorithm, key) => {
|
|||||||
privateKey = key.private
|
privateKey = key.private
|
||||||
publicKey = key.public
|
publicKey = key.public
|
||||||
}
|
}
|
||||||
|
|
||||||
const token = await JWT.sign(testPayload, privateKey, { algorithm })
|
const token = await JWT.sign(testPayload, privateKey, { algorithm })
|
||||||
expect(token).toMatch(/^[a-zA-Z0-9\-_]+\.[a-zA-Z0-9\-_]+\.[a-zA-Z0-9\-_]+$/)
|
expect(token).toMatch(/^[a-zA-Z0-9\-_]+\.[a-zA-Z0-9\-_]+\.[a-zA-Z0-9\-_]+$/)
|
||||||
|
|
||||||
const verified = await JWT.verify(token, publicKey, { algorithm })
|
const verified = await JWT.verify(token, publicKey, { algorithm })
|
||||||
expect(verified).toBeTruthy()
|
expect(verified).toBeTruthy()
|
||||||
const payload = JWT.decode(token)
|
|
||||||
expect(payload).toBeTruthy()
|
const { payload } = JWT.decode(token)
|
||||||
expect({
|
expect({
|
||||||
sub: payload.sub,
|
sub: payload.sub,
|
||||||
name: payload.name
|
name: payload.name
|
||||||
@@ -151,9 +153,11 @@ test.each(Object.entries(externalTokens))('Verify external tokens: %s', async (a
|
|||||||
privateKey = key.private
|
privateKey = key.private
|
||||||
publicKey = key.public
|
publicKey = key.public
|
||||||
}
|
}
|
||||||
|
|
||||||
const verified = await JWT.verify(token, publicKey, { algorithm })
|
const verified = await JWT.verify(token, publicKey, { algorithm })
|
||||||
expect(verified).toBeTruthy()
|
expect(verified).toBeTruthy()
|
||||||
const payload = JWT.decode(token)
|
|
||||||
|
const { payload } = JWT.decode(token)
|
||||||
expect({
|
expect({
|
||||||
sub: payload.sub,
|
sub: payload.sub,
|
||||||
name: payload.name
|
name: payload.name
|
||||||
|
|||||||
16
package-lock.json
generated
16
package-lock.json
generated
@@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"name": "@tsndr/cloudflare-worker-jwt",
|
"name": "@tsndr/cloudflare-worker-jwt",
|
||||||
"version": "1.2.0",
|
"version": "1.4.4",
|
||||||
"lockfileVersion": 2,
|
"lockfileVersion": 2,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "@tsndr/cloudflare-worker-jwt",
|
"name": "@tsndr/cloudflare-worker-jwt",
|
||||||
"version": "1.2.0",
|
"version": "1.4.4",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"jest": "^28.1.0"
|
"jest": "^28.1.0"
|
||||||
@@ -4262,9 +4262,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/path-parse": {
|
"node_modules/path-parse": {
|
||||||
"version": "1.0.6",
|
"version": "1.0.7",
|
||||||
"resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.6.tgz",
|
"resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz",
|
||||||
"integrity": "sha512-GSmOT2EbHrINBf9SR7CDELwlJ8AENk3Qn7OikK4nFYAu3Ote2+JYNVvkpAEQm3/TLNEJFD/xZJjzyxg3KBWOzw==",
|
"integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==",
|
||||||
"dev": true
|
"dev": true
|
||||||
},
|
},
|
||||||
"node_modules/picocolors": {
|
"node_modules/picocolors": {
|
||||||
@@ -8066,9 +8066,9 @@
|
|||||||
"dev": true
|
"dev": true
|
||||||
},
|
},
|
||||||
"path-parse": {
|
"path-parse": {
|
||||||
"version": "1.0.6",
|
"version": "1.0.7",
|
||||||
"resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.6.tgz",
|
"resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz",
|
||||||
"integrity": "sha512-GSmOT2EbHrINBf9SR7CDELwlJ8AENk3Qn7OikK4nFYAu3Ote2+JYNVvkpAEQm3/TLNEJFD/xZJjzyxg3KBWOzw==",
|
"integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==",
|
||||||
"dev": true
|
"dev": true
|
||||||
},
|
},
|
||||||
"picocolors": {
|
"picocolors": {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@tsndr/cloudflare-worker-jwt",
|
"name": "@tsndr/cloudflare-worker-jwt",
|
||||||
"version": "1.3.0",
|
"version": "1.4.4",
|
||||||
"description": "A lightweight JWT implementation with ZERO dependencies for Cloudflare Worker",
|
"description": "A lightweight JWT implementation with ZERO dependencies for Cloudflare Worker",
|
||||||
"main": "index.js",
|
"main": "index.js",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
|
|||||||
Reference in New Issue
Block a user