Compare commits
18 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 430fa0eb84 | |||
| 4d4cf316d0 | |||
| e244ff0618 | |||
|
|
13943f64d7 | ||
| 8952a12e4f | |||
| af3ea4cf8d | |||
| d99e361d65 | |||
| 79f030a35a | |||
| 5fd472c33d | |||
| 54ad90f6fd | |||
| 8d9f70ca36 | |||
| e34e1aedab | |||
| d31254de78 | |||
| 8fadfab966 | |||
| 187bd60b57 | |||
| f905176573 | |||
| 39c3fb790d | |||
| 5d8345996a |
1
.github/FUNDING.yml
vendored
Normal file
1
.github/FUNDING.yml
vendored
Normal file
@@ -0,0 +1 @@
|
|||||||
|
github: tsndr
|
||||||
19
.github/workflows/lint.yml
vendored
Normal file
19
.github/workflows/lint.yml
vendored
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
name: Lint
|
||||||
|
|
||||||
|
on:
|
||||||
|
pull_request:
|
||||||
|
branches: [ main ]
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v2
|
||||||
|
- name: Use Node.js
|
||||||
|
uses: actions/setup-node@v1
|
||||||
|
with:
|
||||||
|
node-version: 15.x
|
||||||
|
- run: npm ci
|
||||||
|
- run: npm run lint --if-present
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
name: Publish NPM Package
|
name: Publish
|
||||||
|
|
||||||
on:
|
on:
|
||||||
release:
|
release:
|
||||||
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.*
|
||||||
177
README.md
177
README.md
@@ -2,80 +2,121 @@
|
|||||||
|
|
||||||
A lightweight JWT implementation with ZERO dependencies for Cloudflare Workers.
|
A lightweight JWT implementation with ZERO dependencies for Cloudflare Workers.
|
||||||
|
|
||||||
|
|
||||||
## Contents
|
## Contents
|
||||||
|
|
||||||
- [Usage](#usage)
|
|
||||||
- [Install](#install)
|
- [Install](#install)
|
||||||
|
- [Examples](#examples)
|
||||||
## Usage
|
- [Usage](#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.
|
|
||||||
|
|
||||||
|
|
||||||
`payload`
|
|
||||||
|
|
||||||
The payload object.
|
|
||||||
|
|
||||||
|
|
||||||
`secret`
|
|
||||||
|
|
||||||
A string which is used to sign the payload.
|
|
||||||
|
|
||||||
|
|
||||||
`algorithm` (optional, default: `HS256`)
|
|
||||||
|
|
||||||
The algorithm used to sign the payload, possible values: `HS256` 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` or `HS512`
|
|
||||||
|
|
||||||
### `jwt.decode(token)`
|
|
||||||
|
|
||||||
Returns the payload without verifying the integrity of the token.
|
|
||||||
|
|
||||||
|
|
||||||
`token`
|
|
||||||
|
|
||||||
The token string generated by `jwt.sign()`.
|
|
||||||
|
|
||||||
|
|
||||||
## Install
|
## 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
|
||||||
48
index.d.ts
vendored
48
index.d.ts
vendored
@@ -1,7 +1,51 @@
|
|||||||
|
/**
|
||||||
|
* JWT
|
||||||
|
*
|
||||||
|
* @class
|
||||||
|
* @constructor
|
||||||
|
* @public
|
||||||
|
*/
|
||||||
declare class JWT {
|
declare class JWT {
|
||||||
sign(payload: object, secret: string, algorithm?: "HS256" | "HS512"): Promise<string>
|
|
||||||
verify(token: string, secret: string, algorithm?: "HS256" | "HS512"): Promise<boolean>
|
/**
|
||||||
|
* 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
|
decode(token: string): object | null
|
||||||
}
|
}
|
||||||
declare const _exports: JWT
|
declare const _exports: JWT
|
||||||
|
|
||||||
|
type JWTAlgorithm = 'ES256' | 'ES384' | 'ES512' | 'HS256' | 'HS384' | 'HS512'
|
||||||
|
|
||||||
|
type JWTSignOptions = {
|
||||||
|
algorithm?: JWTAlgorithm,
|
||||||
|
keyid?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
type JWTVerifyOptions = {
|
||||||
|
algorithm?: JWTAlgorithm
|
||||||
|
}
|
||||||
|
|
||||||
export = _exports
|
export = _exports
|
||||||
141
index.js
141
index.js
@@ -12,89 +12,104 @@ class JWT {
|
|||||||
if (!crypto || !crypto.subtle)
|
if (!crypto || !crypto.subtle)
|
||||||
throw new Error('Crypto not supported!')
|
throw new Error('Crypto not supported!')
|
||||||
this.algorithms = {
|
this.algorithms = {
|
||||||
HS256: {
|
ES256: { name: 'ECDSA', namedCurve: 'P-256', hash: { name: 'SHA-256' } },
|
||||||
name: 'HMAC',
|
ES384: { name: 'ECDSA', namedCurve: 'P-384', hash: { name: 'SHA-384' } },
|
||||||
hash: {
|
ES512: { name: 'ECDSA', namedCurve: 'P-512', hash: { name: 'SHA-512' } },
|
||||||
name: 'SHA-256'
|
HS256: { name: 'HMAC', hash: { name: 'SHA-256' } },
|
||||||
}
|
HS384: { name: 'HMAC', hash: { name: 'SHA-384' } },
|
||||||
},
|
HS512: { name: 'HMAC', hash: { name: 'SHA-512' } }
|
||||||
HS512: {
|
|
||||||
name: 'HMAC',
|
|
||||||
hash: {
|
|
||||||
name: 'SHA-512'
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
_utf8ToUint8Array(str) {
|
||||||
}
|
|
||||||
utf8ToUint8Array(str) {
|
|
||||||
return Base64URL.parse(btoa(unescape(encodeURIComponent(str))))
|
return Base64URL.parse(btoa(unescape(encodeURIComponent(str))))
|
||||||
}
|
}
|
||||||
async sign(payload, secret, algorithm = 'HS256') {
|
_str2ab(str) {
|
||||||
if (payload === null || typeof payload !== 'object')
|
const buf = new ArrayBuffer(str.length);
|
||||||
throw new Error('payload must be an object')
|
const bufView = new Uint8Array(buf);
|
||||||
if (typeof secret !== 'string')
|
for (let i = 0, strLen = str.length; i < strLen; i++) {
|
||||||
throw new Error('secret must be a string')
|
bufView[i] = str.charCodeAt(i);
|
||||||
if (typeof algorithm !== 'string')
|
|
||||||
throw new Error('algorithm must be a string')
|
|
||||||
const importAlgorithm = this.algorithms[algorithm]
|
|
||||||
if (!importAlgorithm)
|
|
||||||
throw new Error('algorithm not found')
|
|
||||||
const payloadAsJSON = JSON.stringify(payload)
|
|
||||||
const partialToken = `${Base64URL.stringify(this.utf8ToUint8Array(JSON.stringify({ alg: algorithm, 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 buf;
|
||||||
return `${partialToken}.${Base64URL.stringify(new Uint8Array(signature))}`
|
|
||||||
}
|
}
|
||||||
async verify(token, secret, algorithm = 'HS256') {
|
_decodePayload(raw) {
|
||||||
if (typeof token !== 'string')
|
switch (raw.length % 4) {
|
||||||
throw new Error('token must be a string')
|
|
||||||
if (typeof secret !== 'string')
|
|
||||||
throw new Error('secret must be a string')
|
|
||||||
if (typeof algorithm !== 'string')
|
|
||||||
throw new Error('algorithm must be a string')
|
|
||||||
const tokenParts = token.split('.')
|
|
||||||
if (tokenParts.length !== 3)
|
|
||||||
throw new Error('token must have 3 parts')
|
|
||||||
const importAlgorithm = this.algorithms[algorithm]
|
|
||||||
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) {
|
|
||||||
case 0:
|
case 0:
|
||||||
break
|
break
|
||||||
case 2:
|
case 2:
|
||||||
output += '=='
|
raw += '=='
|
||||||
break
|
break
|
||||||
case 3:
|
case 3:
|
||||||
output += '='
|
raw += '='
|
||||||
break
|
break
|
||||||
default:
|
default:
|
||||||
throw new Error('Illegal base64url string!')
|
throw new Error('Illegal base64url string!')
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
return JSON.parse(decodeURIComponent(escape(atob(output))))
|
return JSON.parse(decodeURIComponent(escape(atob(raw))))
|
||||||
} catch {
|
} catch {
|
||||||
return null
|
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
|
module.exports = new JWT
|
||||||
|
|||||||
@@ -1,11 +1,8 @@
|
|||||||
{
|
{
|
||||||
"name": "@tsndr/cloudflare-worker-jwt",
|
"name": "@tsndr/cloudflare-worker-jwt",
|
||||||
"version": "1.0.7",
|
"version": "1.1.5",
|
||||||
"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": {
|
|
||||||
"test": "echo \"Error: no test specified\" && exit 1"
|
|
||||||
},
|
|
||||||
"repository": {
|
"repository": {
|
||||||
"type": "git",
|
"type": "git",
|
||||||
"url": "git+https://github.com/tsndr/cloudflare-worker-jwt.git"
|
"url": "git+https://github.com/tsndr/cloudflare-worker-jwt.git"
|
||||||
|
|||||||
Reference in New Issue
Block a user