Compare commits
37 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| e0219ff21f | |||
|
|
bc7fa845ed | ||
|
|
5ee043e597 | ||
|
|
9c52217ca2 | ||
|
|
5160cfa416 | ||
| 430fa0eb84 | |||
| 4d4cf316d0 | |||
| e244ff0618 | |||
|
|
13943f64d7 | ||
| 8952a12e4f | |||
| af3ea4cf8d | |||
| d99e361d65 | |||
| 79f030a35a | |||
| 5fd472c33d | |||
| 54ad90f6fd | |||
| 8d9f70ca36 | |||
| e34e1aedab | |||
| d31254de78 | |||
| 8fadfab966 | |||
| 187bd60b57 | |||
| f905176573 | |||
| 39c3fb790d | |||
| 5d8345996a | |||
| eebc0e988a | |||
| bf90a7c855 | |||
| 6e0ce1cf82 | |||
| 4ed24b18c5 | |||
| d12809e15d | |||
| 7a093c2c85 | |||
| 14a9631b8b | |||
| c247675832 | |||
| 0d3c7d621a | |||
| 62479197f5 | |||
| 0a3a9b58d1 | |||
| 959a7c9490 | |||
| e7be1ed840 | |||
| f2adb27218 |
1
.github/FUNDING.yml
vendored
Normal file
1
.github/FUNDING.yml
vendored
Normal file
@@ -0,0 +1 @@
|
||||
github: tsndr
|
||||
30
.github/workflows/publish.yml
vendored
Normal file
30
.github/workflows/publish.yml
vendored
Normal file
@@ -0,0 +1,30 @@
|
||||
name: Publish
|
||||
|
||||
on:
|
||||
release:
|
||||
types: [created]
|
||||
|
||||
jobs:
|
||||
publish-npm:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/setup-node@v1
|
||||
with:
|
||||
node-version: 12
|
||||
registry-url: https://registry.npmjs.org/
|
||||
- run: npm publish --access public
|
||||
env:
|
||||
NODE_AUTH_TOKEN: ${{secrets.NPM_TOKEN}}
|
||||
|
||||
publish-gpr:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/setup-node@v1
|
||||
with:
|
||||
node-version: 12
|
||||
registry-url: https://npm.pkg.github.com/
|
||||
- run: npm publish --access public
|
||||
env:
|
||||
NODE_AUTH_TOKEN: ${{secrets.GITHUB_TOKEN}}
|
||||
144
.gitignore
vendored
Normal file
144
.gitignore
vendored
Normal file
@@ -0,0 +1,144 @@
|
||||
# General
|
||||
.DS_Store
|
||||
.AppleDouble
|
||||
.LSOverride
|
||||
|
||||
# Icon must end with two \r
|
||||
Icon
|
||||
|
||||
# Thumbnails
|
||||
._*
|
||||
|
||||
# Files that might appear in the root of a volume
|
||||
.DocumentRevisions-V100
|
||||
.fseventsd
|
||||
.Spotlight-V100
|
||||
.TemporaryItems
|
||||
.Trashes
|
||||
.VolumeIcon.icns
|
||||
.com.apple.timemachine.donotpresent
|
||||
|
||||
# Directories potentially created on remote AFP share
|
||||
.AppleDB
|
||||
.AppleDesktop
|
||||
Network Trash Folder
|
||||
Temporary Items
|
||||
.apdisk
|
||||
|
||||
# node.js
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
lerna-debug.log*
|
||||
|
||||
# Diagnostic reports (https://nodejs.org/api/report.html)
|
||||
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
|
||||
|
||||
# Runtime data
|
||||
pids
|
||||
*.pid
|
||||
*.seed
|
||||
*.pid.lock
|
||||
|
||||
# Directory for instrumented libs generated by jscoverage/JSCover
|
||||
lib-cov
|
||||
|
||||
# Coverage directory used by tools like istanbul
|
||||
coverage
|
||||
*.lcov
|
||||
|
||||
# nyc test coverage
|
||||
.nyc_output
|
||||
|
||||
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
|
||||
.grunt
|
||||
|
||||
# Bower dependency directory (https://bower.io/)
|
||||
bower_components
|
||||
|
||||
# node-waf configuration
|
||||
.lock-wscript
|
||||
|
||||
# Compiled binary addons (https://nodejs.org/api/addons.html)
|
||||
build/Release
|
||||
|
||||
# Dependency directories
|
||||
node_modules/
|
||||
jspm_packages/
|
||||
|
||||
# Snowpack dependency directory (https://snowpack.dev/)
|
||||
web_modules/
|
||||
|
||||
# TypeScript cache
|
||||
*.tsbuildinfo
|
||||
|
||||
# Optional npm cache directory
|
||||
.npm
|
||||
|
||||
# Optional eslint cache
|
||||
.eslintcache
|
||||
|
||||
# Microbundle cache
|
||||
.rpt2_cache/
|
||||
.rts2_cache_cjs/
|
||||
.rts2_cache_es/
|
||||
.rts2_cache_umd/
|
||||
|
||||
# Optional REPL history
|
||||
.node_repl_history
|
||||
|
||||
# Output of 'npm pack'
|
||||
*.tgz
|
||||
|
||||
# Yarn Integrity file
|
||||
.yarn-integrity
|
||||
|
||||
# dotenv environment variables file
|
||||
.env
|
||||
.env.test
|
||||
|
||||
# parcel-bundler cache (https://parceljs.org/)
|
||||
.cache
|
||||
.parcel-cache
|
||||
|
||||
# Next.js build output
|
||||
.next
|
||||
out
|
||||
|
||||
# Nuxt.js build / generate output
|
||||
.nuxt
|
||||
dist
|
||||
|
||||
# Gatsby files
|
||||
.cache/
|
||||
# Comment in the public line in if your project uses Gatsby and not Next.js
|
||||
# https://nextjs.org/blog/next-9-1#public-directory-support
|
||||
# public
|
||||
|
||||
# vuepress build output
|
||||
.vuepress/dist
|
||||
|
||||
# Serverless directories
|
||||
.serverless/
|
||||
|
||||
# FuseBox cache
|
||||
.fusebox/
|
||||
|
||||
# DynamoDB Local files
|
||||
.dynamodb/
|
||||
|
||||
# TernJS port file
|
||||
.tern-port
|
||||
|
||||
# Stores VSCode versions used for testing VSCode extensions
|
||||
.vscode-test
|
||||
|
||||
# yarn v2
|
||||
.yarn/cache
|
||||
.yarn/unplugged
|
||||
.yarn/build-state.yml
|
||||
.yarn/install-state.gz
|
||||
.pnp.*
|
||||
21
LICENSE
Normal file
21
LICENSE
Normal file
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2021 Tobias Schneider
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
166
README.md
166
README.md
@@ -2,66 +2,124 @@
|
||||
|
||||
A lightweight JWT implementation with ZERO dependencies for Cloudflare Workers.
|
||||
|
||||
|
||||
## Contents
|
||||
|
||||
- [Usage](#usage)
|
||||
- [Install](#install)
|
||||
|
||||
## Usage
|
||||
|
||||
### Simple Example
|
||||
|
||||
```javascript
|
||||
const jwt = require('@tsndr/cloudflare-worker-jwt')
|
||||
|
||||
// Creating a token
|
||||
const token = jwt.sign({ name: 'John Doe', email: 'john.doe@gmail.com' }, 'secret')
|
||||
|
||||
// Verifing token
|
||||
const isValid = jwt.verify(token, secret)
|
||||
|
||||
// Decoding token
|
||||
const payload = jwt.decode(token)
|
||||
|
||||
```
|
||||
|
||||
### `jwt.sign(payload, secret, [algorithm])`
|
||||
|
||||
Signs a payload and returns the token.
|
||||
|
||||
#### Parameters
|
||||
`payload`
|
||||
Can be an object, buffer or a string.
|
||||
|
||||
`secret`
|
||||
A string which is used to sign the payload.
|
||||
|
||||
`algorithm` (optional, default: `HS256`)
|
||||
The algorithm used to sign the payload, possible values: `HS256`(default) or `HS512`
|
||||
|
||||
|
||||
### `jwt.verify(token, secret, [algorithm])`
|
||||
|
||||
Verifies the integrity of the token and returns a boolean value.
|
||||
|
||||
`token`
|
||||
The token string generated by `jwt.sign()`.
|
||||
|
||||
`secret`
|
||||
A string which is used to sign the payload.
|
||||
|
||||
`algorithm` (optional, default: `HS256`)
|
||||
The algorithm used to sign the payload, possible values: `HS256`(default) or `HS512`
|
||||
|
||||
### `jwt.decode(token)`
|
||||
Returns the payload without verifying the integrity of the token.
|
||||
|
||||
`token`
|
||||
The token string generated by `jwt.sign()`.
|
||||
- [Examples](#examples)
|
||||
- [Usage](#usage)
|
||||
|
||||
|
||||
## Install
|
||||
|
||||
```
|
||||
npm i @tsndr/cloudflare-worker-jwt
|
||||
npm i -D @tsndr/cloudflare-worker-jwt
|
||||
```
|
||||
|
||||
|
||||
## Examples
|
||||
|
||||
### Basic Example
|
||||
|
||||
```javascript
|
||||
async () => {
|
||||
const jwt = require('@tsndr/cloudflare-worker-jwt')
|
||||
|
||||
// Creating a token
|
||||
const token = await jwt.sign({ name: 'John Doe', email: 'john.doe@gmail.com' }, 'secret')
|
||||
|
||||
// Verifing token
|
||||
const isValid = await jwt.verify(token, 'secret')
|
||||
|
||||
// Check for validity
|
||||
if (!isValid)
|
||||
return
|
||||
|
||||
// Decoding token
|
||||
const payload = jwt.decode(token)
|
||||
}
|
||||
```
|
||||
|
||||
### Restrict Timeframe
|
||||
|
||||
```javascript
|
||||
async () => {
|
||||
const jwt = require('@tsndr/cloudflare-worker-jwt')
|
||||
|
||||
// Creating a token
|
||||
const token = await jwt.sign({
|
||||
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')
|
||||
|
||||
// Verifing token
|
||||
const isValid = await jwt.verify(token, 'secret') // false
|
||||
|
||||
// Check for validity
|
||||
if (!isValid)
|
||||
return
|
||||
|
||||
// Decoding token
|
||||
const payload = jwt.decode(token) // { name: 'John Doe', email: 'john.doe@gmail.com', ... }
|
||||
}
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
<hr>
|
||||
|
||||
### `jwt.sign(payload, secret, [options])`
|
||||
|
||||
Signs a payload and returns the token.
|
||||
|
||||
#### Arguments
|
||||
|
||||
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.
|
||||
`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))
|
||||
|
||||
#### `return`
|
||||
Returns token as a `string`.
|
||||
|
||||
<hr>
|
||||
|
||||
### `jwt.verify(token, secret, [options])`
|
||||
|
||||
Verifies the integrity of the token and returns a boolean value.
|
||||
|
||||
Argument | Type | Satus | Default | Description
|
||||
----------- | -------- | -------- | ------- | -----------
|
||||
`token` | `string` | required | - | The token string generated by `jwt.sign()`.
|
||||
`secret` | `string` | required | - | The string which was used to sign the payload.
|
||||
`algorithm` | `object`, `string` | optional | `{ algorithm: 'HS256' }` | The options object supporting `algorithm` or just the algorithm string. (See [Available Algorithms](#available-algorithms))
|
||||
|
||||
#### `return`
|
||||
Returns `true` if signature, `nbf` (if set) and `exp` (if set) are valid, otherwise returns `false`.
|
||||
|
||||
<hr>
|
||||
|
||||
### `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 | Satus | Default | Description
|
||||
----------- | -------- | -------- | ------- | -----------
|
||||
`token` | `string` | required | - | The token string generated by `jwt.sign()`.
|
||||
|
||||
#### `return`
|
||||
Returns payload `object`.
|
||||
|
||||
### Available Algorithms
|
||||
- ES256
|
||||
- ES384
|
||||
- ES512
|
||||
- HS256
|
||||
- HS384
|
||||
- HS512
|
||||
- RS256
|
||||
- RS384
|
||||
- RS512
|
||||
51
index.d.ts
vendored
Normal file
51
index.d.ts
vendored
Normal file
@@ -0,0 +1,51 @@
|
||||
/**
|
||||
* JWT
|
||||
*
|
||||
* @class
|
||||
* @constructor
|
||||
* @public
|
||||
*/
|
||||
declare class JWT {
|
||||
|
||||
/**
|
||||
* Signs a payload and returns the token
|
||||
*
|
||||
* @param {object} payload The payload object. To use `nbf` (Not Before) and/or `exp` (Expiration Time) add `nbf` and/or `exp` to the payload.
|
||||
* @param {string} secret A string which is used to sign the payload.
|
||||
* @param {JWTSignOptions | JWTAlgorithm} options The options object or the algorithm.
|
||||
* @returns {Promise<string>} Returns token as a `string`.
|
||||
*/
|
||||
sign(payload: object, secret: string, options?: JWTSignOptions | JWTAlgorithm): Promise<string>
|
||||
|
||||
/**
|
||||
* Verifies the integrity of the token and returns a boolean value.
|
||||
*
|
||||
* @param {string} token The token string generated by `jwt.sign()`.
|
||||
* @param {string} secret The string which was used to sign the payload.
|
||||
* @param {JWTVerifyOptions | JWTAlgorithm} options The options object or the algorithm.
|
||||
* @returns {Promise<boolean>} Returns `true` if signature, `nbf` (if set) and `exp` (if set) are valid, otherwise returns `false`.
|
||||
*/
|
||||
verify(token: string, secret: string, options?: JWTVerifyOptions | JWTAlgorithm): Promise<boolean>
|
||||
|
||||
/**
|
||||
* 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()`.
|
||||
* @returns {object | null} Returns payload `object`.
|
||||
*/
|
||||
decode(token: string): object | null
|
||||
}
|
||||
declare const _exports: JWT
|
||||
|
||||
type JWTAlgorithm = 'ES256' | 'ES384' | 'ES512' | 'HS256' | 'HS384' | 'HS512' | 'RS256' | 'RS384' | 'RS512'
|
||||
|
||||
type JWTSignOptions = {
|
||||
algorithm?: JWTAlgorithm,
|
||||
keyid?: string
|
||||
}
|
||||
|
||||
type JWTVerifyOptions = {
|
||||
algorithm?: JWTAlgorithm
|
||||
}
|
||||
|
||||
export = _exports
|
||||
150
index.js
150
index.js
@@ -9,94 +9,110 @@ class Base64URL {
|
||||
|
||||
class JWT {
|
||||
constructor() {
|
||||
if (!crypto || !crypto.subtle)
|
||||
if (typeof crypto === 'undefined' || !crypto.subtle)
|
||||
throw new Error('Crypto not supported!')
|
||||
this.algorithms = {
|
||||
HS256: {
|
||||
name: 'HMAC',
|
||||
hash: {
|
||||
name: 'SHA-256'
|
||||
}
|
||||
},
|
||||
HS512: {
|
||||
name: 'HMAC',
|
||||
hash: {
|
||||
name: 'SHA-512'
|
||||
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-512', hash: { name: 'SHA-512' } },
|
||||
HS256: { name: 'HMAC', hash: { name: 'SHA-256' } },
|
||||
HS384: { name: 'HMAC', hash: { name: 'SHA-384' } },
|
||||
HS512: { name: 'HMAC', hash: { name: 'SHA-512' } },
|
||||
RS256: { name: 'RSASSA-PKCS1-v1_5', hash: { name: 'SHA-256' } },
|
||||
RS384: { name: 'RSASSA-PKCS1-v1_5', hash: { name: 'SHA-384' } },
|
||||
RS512: { name: 'RSASSA-PKCS1-v1_5', hash: { name: 'SHA-512' } },
|
||||
}
|
||||
}
|
||||
_utf8ToUint8Array(str) {
|
||||
return Base64URL.parse(btoa(unescape(encodeURIComponent(str))))
|
||||
}
|
||||
_str2ab(str) {
|
||||
const buf = new ArrayBuffer(str.length);
|
||||
const bufView = new Uint8Array(buf);
|
||||
for (let i = 0, strLen = str.length; i < strLen; i++) {
|
||||
bufView[i] = str.charCodeAt(i);
|
||||
}
|
||||
utf8ToUint8Array(str) {
|
||||
const chars = []
|
||||
str = btoa(unescape(encodeURIComponent(str)))
|
||||
return Base64URL.parse(str)
|
||||
return buf;
|
||||
}
|
||||
async sign(payload, secret, alg = 'HS256') {
|
||||
if (payload === null || typeof payload !== 'object')
|
||||
throw new Error('payload must be an object')
|
||||
if (typeof secret !== 'string')
|
||||
throw new Error('secret must be a string')
|
||||
if (typeof alg !== 'string')
|
||||
throw new Error('alg must be a string')
|
||||
const importAlgorithm = this.algorithms[alg]
|
||||
if (!importAlgorithm)
|
||||
throw new Error('algorithm not found')
|
||||
const payloadAsJSON = JSON.stringify(payload)
|
||||
const partialToken = `${Base64URL.stringify(this.utf8ToUint8Array(JSON.stringify({ alg, typ: 'JWT' })))}.${Base64URL.stringify(this.utf8ToUint8Array(payloadAsJSON))}`
|
||||
const key = await crypto.subtle.importKey('raw', this.utf8ToUint8Array(secret), importAlgorithm, false, ['sign'])
|
||||
const characters = payloadAsJSON.split('')
|
||||
const it = this.utf8ToUint8Array(payloadAsJSON).entries()
|
||||
let i = 0
|
||||
const result = []
|
||||
let current
|
||||
while (!(current = it.next()).done) {
|
||||
result.push([current.value[1], characters[i]])
|
||||
i++
|
||||
}
|
||||
const signature = await crypto.subtle.sign(importAlgorithm.name, key, this.utf8ToUint8Array(partialToken))
|
||||
return `${partialToken}.${Base64URL.stringify(new Uint8Array(signature))}`
|
||||
}
|
||||
async verify(token, secret, alg = 'HS256') {
|
||||
if (typeof token !== 'string')
|
||||
throw new Error('token must be a string')
|
||||
if (typeof secret !== 'string')
|
||||
throw new Error('secret must be a string')
|
||||
if (typeof alg !== 'string')
|
||||
throw new Error('alg must be a string')
|
||||
const tokenParts = token.split('.')
|
||||
if (tokenParts.length !== 3)
|
||||
throw new Error('token must have 3 parts')
|
||||
const importAlgorithm = this.algorithms[alg]
|
||||
if (!importAlgorithm)
|
||||
throw new Error('algorithm not found')
|
||||
const keyData = this.utf8ToUint8Array(secret)
|
||||
const key = await crypto.subtle.importKey('raw', keyData, importAlgorithm, false, ['sign'])
|
||||
const partialToken = tokenParts.slice(0, 2).join('.')
|
||||
const signaturePart = tokenParts[2]
|
||||
const messageAsUint8Array = this.utf8ToUint8Array(partialToken)
|
||||
const res = await crypto.subtle.sign(importAlgorithm.name, key, messageAsUint8Array)
|
||||
return Base64URL.stringify(new Uint8Array(res)) === signaturePart
|
||||
}
|
||||
decode(token) {
|
||||
let output = token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/')
|
||||
switch (output.length % 4) {
|
||||
_decodePayload(raw) {
|
||||
switch (raw.length % 4) {
|
||||
case 0:
|
||||
break
|
||||
case 2:
|
||||
output += '=='
|
||||
raw += '=='
|
||||
break
|
||||
case 3:
|
||||
output += '='
|
||||
raw += '='
|
||||
break
|
||||
default:
|
||||
throw new Error('Illegal base64url string!')
|
||||
}
|
||||
try {
|
||||
return JSON.parse(decodeURIComponent(escape(atob(output))))
|
||||
return JSON.parse(decodeURIComponent(escape(atob(raw))))
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
async sign(payload, secret, options = { algorithm: 'HS256' }) {
|
||||
if (typeof options === 'string')
|
||||
options = { algorithm: options }
|
||||
if (payload === null || typeof payload !== 'object')
|
||||
throw new Error('payload must be an object')
|
||||
if (typeof secret !== 'string')
|
||||
throw new Error('secret must be a string')
|
||||
if (typeof options.algorithm !== 'string')
|
||||
throw new Error('options.algorithm must be a string')
|
||||
const importAlgorithm = this.algorithms[options.algorithm]
|
||||
if (!importAlgorithm)
|
||||
throw new Error('algorithm not found')
|
||||
payload.iat = Math.floor(Date.now() / 1000)
|
||||
const payloadAsJSON = JSON.stringify(payload)
|
||||
const partialToken = `${Base64URL.stringify(this._utf8ToUint8Array(JSON.stringify({ alg: options.algorithm, kid: options.keyid })))}.${Base64URL.stringify(this._utf8ToUint8Array(payloadAsJSON))}`
|
||||
let keyFormat = 'raw'
|
||||
let keyData
|
||||
if (secret.startsWith('-----BEGIN')) {
|
||||
keyFormat = 'pkcs8'
|
||||
keyData = this._str2ab(atob(secret.replace(/-----BEGIN.*?-----/g, '').replace(/-----END.*?-----/g, '').replace(/\s/g, '')))
|
||||
} else
|
||||
keyData = this._utf8ToUint8Array(secret)
|
||||
const key = await crypto.subtle.importKey(keyFormat, keyData, importAlgorithm, false, ['sign'])
|
||||
const signature = await crypto.subtle.sign(importAlgorithm, key, this._utf8ToUint8Array(partialToken))
|
||||
return `${partialToken}.${Base64URL.stringify(new Uint8Array(signature))}`
|
||||
}
|
||||
async verify(token, secret, options = { algorithm: 'HS256' }) {
|
||||
if (typeof options === 'string')
|
||||
options = { algorithm: options }
|
||||
if (typeof token !== 'string')
|
||||
throw new Error('token must be a string')
|
||||
if (typeof secret !== 'string')
|
||||
throw new Error('secret must be a string')
|
||||
if (typeof options.algorithm !== 'string')
|
||||
throw new Error('options.algorithm must be a string')
|
||||
const tokenParts = token.split('.')
|
||||
if (tokenParts.length !== 3)
|
||||
throw new Error('token must consist of 3 parts')
|
||||
const importAlgorithm = this.algorithms[options.algorithm]
|
||||
if (!importAlgorithm)
|
||||
throw new Error('algorithm not found')
|
||||
const payload = this.decode(token)
|
||||
if (payload.nbf && payload.nbf >= Math.floor(Date.now() / 1000))
|
||||
return false
|
||||
if (payload.exp && payload.exp < Math.floor(Date.now() / 1000))
|
||||
return false
|
||||
let keyFormat = 'raw'
|
||||
let keyData
|
||||
if (secret.startsWith('-----BEGIN')) {
|
||||
keyFormat = 'pkcs8'
|
||||
keyData = this._str2ab(atob(secret.replace(/-----BEGIN.*?-----/g, '').replace(/-----END.*?-----/g, '').replace(/\s/g, '')))
|
||||
} else
|
||||
keyData = this._utf8ToUint8Array(secret)
|
||||
const key = await crypto.subtle.importKey(keyFormat, keyData, importAlgorithm, false, ['sign'])
|
||||
const res = await crypto.subtle.sign(importAlgorithm, key, this._utf8ToUint8Array(tokenParts.slice(0, 2).join('.')))
|
||||
return Base64URL.stringify(new Uint8Array(res)) === tokenParts[2]
|
||||
}
|
||||
decode(token) {
|
||||
return this._decodePayload(token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/'))
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new JWT
|
||||
|
||||
@@ -1,11 +1,8 @@
|
||||
{
|
||||
"name": "@tsndr/cloudflare-worker-jwt",
|
||||
"version": "1.0.0",
|
||||
"version": "1.1.6",
|
||||
"description": "A lightweight JWT implementation with ZERO dependencies for Cloudflare Worker",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"test": "echo \"Error: no test specified\" && exit 1"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/tsndr/cloudflare-worker-jwt.git"
|
||||
@@ -18,7 +15,7 @@
|
||||
"cloudflare-worker"
|
||||
],
|
||||
"author": "Tobias Schneider",
|
||||
"license": "ISC",
|
||||
"license": "MIT",
|
||||
"bugs": {
|
||||
"url": "https://github.com/tsndr/cloudflare-worker-jwt/issues"
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user