1
0

Compare commits

...

27 Commits

Author SHA1 Message Date
e0219ff21f Update to v1.1.6 2022-02-27 16:15:58 +01:00
Toby Schneider
bc7fa845ed Merge pull request #7 from plesiv/add-rsa-algorithm
Add support for RSA algorithm
2022-02-27 15:56:13 +01:00
Toby Schneider
5ee043e597 Merge pull request #8 from workeffortwaste/fix-constructor-error
Fix constructor error
2022-02-27 15:55:38 +01:00
Chris Johnson
9c52217ca2 Fix constructor error 2022-02-24 09:17:40 +00:00
Zoran Plesivcak
5160cfa416 Add support for RSA algorithm 2022-02-13 23:58:16 +00:00
430fa0eb84 Update to 1.1.5 2021-11-02 13:58:16 +01:00
4d4cf316d0 Change error message 2021-11-02 13:56:12 +01:00
e244ff0618 Added more algorithms, keyid and did some cleanup 2021-10-27 01:22:01 +02:00
Toby Schneider
13943f64d7 Create FUNDING.yml 2021-10-26 23:54:37 +02:00
8952a12e4f Updated example code 2021-09-23 22:51:14 +02:00
af3ea4cf8d Rearranged readme 2021-05-26 19:16:25 +02:00
d99e361d65 Bump version 2021-05-26 02:19:23 +02:00
79f030a35a Added JSDoc 2021-05-26 02:19:04 +02:00
5fd472c33d Renamed workflow 2021-05-25 22:44:42 +02:00
54ad90f6fd Updated tslint 2021-05-25 22:44:10 +02:00
8d9f70ca36 Added nbf and exp support 2021-05-23 22:41:35 +02:00
e34e1aedab Cleaned up 2021-05-23 18:33:04 +02:00
d31254de78 Bumped version to 1.0.8 2021-05-23 18:18:04 +02:00
8fadfab966 Rearranged readme 2021-05-23 18:17:12 +02:00
187bd60b57 Updated readme 2021-05-23 18:16:04 +02:00
f905176573 Updated readme 2021-05-23 18:03:28 +02:00
39c3fb790d Updated workflow 2021-05-23 17:48:49 +02:00
5d8345996a Added linting 2021-05-23 17:47:22 +02:00
eebc0e988a Bumped version 2021-05-01 16:24:26 +02:00
bf90a7c855 Added typescript support 2021-05-01 16:21:47 +02:00
6e0ce1cf82 Renamed alg to algorithm 2021-05-01 16:21:27 +02:00
4ed24b18c5 Removed unused variable 2021-05-01 15:54:49 +02:00
7 changed files with 393 additions and 140 deletions

1
.github/FUNDING.yml vendored Normal file
View File

@@ -0,0 +1 @@
github: tsndr

View File

@@ -1,4 +1,4 @@
name: Publish NPM Package
name: Publish
on:
release:

144
.gitignore vendored Normal file
View 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.*

180
README.md
View File

@@ -2,80 +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.
`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()`.
- [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
View 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
View File

@@ -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

View File

@@ -1,11 +1,8 @@
{
"name": "@tsndr/cloudflare-worker-jwt",
"version": "1.0.6",
"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"