1
0

Compare commits

...

7 Commits

Author SHA1 Message Date
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
7 changed files with 114 additions and 45 deletions

View File

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

View File

@@ -2,35 +2,64 @@
A lightweight JWT implementation with ZERO dependencies for Cloudflare Workers. A lightweight JWT implementation with ZERO dependencies for Cloudflare Workers.
## Contents ## Contents
- [Install](#install) - [Install](#install)
- [Examples](#examples)
- [Usage](#usage) - [Usage](#usage)
## Install ## Install
``` ```
npm i @tsndr/cloudflare-worker-jwt npm i @tsndr/cloudflare-worker-jwt
``` ```
## Usage
### Simple Example ## Examples
### Basic Example
```javascript ```javascript
async () => {
const jwt = require('@tsndr/cloudflare-worker-jwt') const jwt = require('@tsndr/cloudflare-worker-jwt')
// Creating a token // Creating a token
const token = jwt.sign({ name: 'John Doe', email: 'john.doe@gmail.com' }, 'secret') const token = await jwt.sign({ name: 'John Doe', email: 'john.doe@gmail.com' }, 'secret')
// Verifing token // Verifing token
const isValid = jwt.verify(token, 'secret') const isValid = await jwt.verify(token, 'secret')
// Decoding token // Decoding token
const payload = jwt.decode(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
// Decoding token
const payload = jwt.decode(token) // { name: 'John Doe', email: 'john.doe@gmail.com', ... }
}
```
## Usage
<hr> <hr>
### `jwt.sign(payload, secret, [algorithm])` ### `jwt.sign(payload, secret, [algorithm])`
@@ -41,12 +70,12 @@ Signs a payload and returns the token.
Argument | Type | Satus | Default | Description Argument | Type | Satus | Default | Description
----------- | -------- | -------- | ------- | ----------- ----------- | -------- | -------- | ------- | -----------
`payload` | `object` | required | - | The payload object `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.
`algorithm` | `string` | optional | `HS256` | The algorithm used to sign the payload, possible values: `HS256` or `HS512` `algorithm` | `string` | optional | `HS256` | The algorithm used to sign the payload, possible values: `HS256` or `HS512`
#### `return` #### `return`
returns token as a `string` Returns token as a `string`.
<hr> <hr>
@@ -61,17 +90,17 @@ Argument | Type | Satus | Default | Description
`algorithm` | `string` | optional | `HS256` | The algorithm used to sign the payload, possible values: `HS256` or `HS512` `algorithm` | `string` | optional | `HS256` | The algorithm used to sign the payload, possible values: `HS256` or `HS512`
#### `return` #### `return`
returns `boolean` Returns `true` if signature, `nbf` (if set) and `exp` (if set) are valid, otherwise returns `false`.
<hr> <hr>
### `jwt.decode(token)` ### `jwt.decode(token)`
Returns the payload without verifying the integrity of the 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 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 payload `object`.

32
index.d.ts vendored
View File

@@ -1,6 +1,38 @@
/**
* JWT
*
* @class
* @constructor
* @public
*/
declare class JWT { 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 {'HS256' | 'HS512'} [algorithm=HS256] The algorithm used to sign the payload, possible values: `HS256` or `HS512`
* @returns {Promise<string>} Returns token as a `string`.
*/
sign(payload: object, secret: string, algorithm?: "HS256" | "HS512"): Promise<string> sign(payload: object, secret: string, algorithm?: "HS256" | "HS512"): 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 {'HS256' | 'HS512'} [algorithm=HS256] The algorithm used to sign the payload, possible values: `HS256` or `HS512`
* @returns {Promise<boolean>} Returns `true` if signature, `nbf` (if set) and `exp` (if set) are valid, otherwise returns `false`.
*/
verify(token: string, secret: string, algorithm?: "HS256" | "HS512"): Promise<boolean> verify(token: string, secret: string, algorithm?: "HS256" | "HS512"): 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

View File

@@ -26,9 +26,28 @@ class JWT {
} }
} }
} }
utf8ToUint8Array(str) { _utf8ToUint8Array(str) {
return Base64URL.parse(btoa(unescape(encodeURIComponent(str)))) return Base64URL.parse(btoa(unescape(encodeURIComponent(str))))
} }
_decodePayload(raw) {
switch (raw.length % 4) {
case 0:
break
case 2:
raw += '=='
break
case 3:
raw += '='
break
default:
throw new Error('Illegal base64url string!')
}
try {
return JSON.parse(decodeURIComponent(escape(atob(raw))))
} catch {
return null
}
}
async sign(payload, secret, algorithm = 'HS256') { async sign(payload, secret, algorithm = 'HS256') {
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')
@@ -39,11 +58,12 @@ class JWT {
const importAlgorithm = this.algorithms[algorithm] const importAlgorithm = this.algorithms[algorithm]
if (!importAlgorithm) if (!importAlgorithm)
throw new Error('algorithm not found') throw new Error('algorithm not found')
payload.iat = Math.floor(Date.now() / 1000)
const payloadAsJSON = JSON.stringify(payload) const payloadAsJSON = JSON.stringify(payload)
const partialToken = `${Base64URL.stringify(this.utf8ToUint8Array(JSON.stringify({ alg: algorithm, typ: 'JWT' })))}.${Base64URL.stringify(this.utf8ToUint8Array(payloadAsJSON))}` 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 key = await crypto.subtle.importKey('raw', this._utf8ToUint8Array(secret), importAlgorithm, false, ['sign'])
const characters = payloadAsJSON.split('') const characters = payloadAsJSON.split('')
const it = this.utf8ToUint8Array(payloadAsJSON).entries() const it = this._utf8ToUint8Array(payloadAsJSON).entries()
let i = 0 let i = 0
const result = [] const result = []
let current let current
@@ -51,7 +71,7 @@ class JWT {
result.push([current.value[1], characters[i]]) result.push([current.value[1], characters[i]])
i++ i++
} }
const signature = await crypto.subtle.sign(importAlgorithm.name, key, this.utf8ToUint8Array(partialToken)) const signature = await crypto.subtle.sign(importAlgorithm.name, key, this._utf8ToUint8Array(partialToken))
return `${partialToken}.${Base64URL.stringify(new Uint8Array(signature))}` return `${partialToken}.${Base64URL.stringify(new Uint8Array(signature))}`
} }
async verify(token, secret, algorithm = 'HS256') { async verify(token, secret, algorithm = 'HS256') {
@@ -67,33 +87,21 @@ class JWT {
const importAlgorithm = this.algorithms[algorithm] const importAlgorithm = this.algorithms[algorithm]
if (!importAlgorithm) if (!importAlgorithm)
throw new Error('algorithm not found') throw new Error('algorithm not found')
const keyData = this.utf8ToUint8Array(secret) const keyData = this._utf8ToUint8Array(secret)
const key = await crypto.subtle.importKey('raw', keyData, importAlgorithm, false, ['sign']) const key = await crypto.subtle.importKey('raw', keyData, importAlgorithm, false, ['sign'])
const partialToken = tokenParts.slice(0, 2).join('.') const partialToken = tokenParts.slice(0, 2).join('.')
const payload = this._decodePayload(tokenParts[1].replace(/-/g, '+').replace(/_/g, '/'))
if (payload.nbf && payload.nbf >= Math.floor(Date.now() / 1000))
return false
if (payload.exp && payload.exp < Math.floor(Date.now() / 1000))
return false
const signaturePart = tokenParts[2] const signaturePart = tokenParts[2]
const messageAsUint8Array = this.utf8ToUint8Array(partialToken) const messageAsUint8Array = this._utf8ToUint8Array(partialToken)
const res = await crypto.subtle.sign(importAlgorithm.name, key, messageAsUint8Array) const res = await crypto.subtle.sign(importAlgorithm.name, key, messageAsUint8Array)
return Base64URL.stringify(new Uint8Array(res)) === signaturePart return Base64URL.stringify(new Uint8Array(res)) === signaturePart
} }
decode(token) { decode(token) {
let output = token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/') return this._decodePayload(token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/'))
switch (output.length % 4) {
case 0:
break
case 2:
output += '=='
break
case 3:
output += '='
break
default:
throw new Error('Illegal base64url string!')
}
try {
return JSON.parse(decodeURIComponent(escape(atob(output))))
} catch {
return null
}
} }
} }

4
package-lock.json generated
View File

@@ -1,12 +1,12 @@
{ {
"name": "@tsndr/cloudflare-worker-jwt", "name": "@tsndr/cloudflare-worker-jwt",
"version": "1.0.7", "version": "1.1.2",
"lockfileVersion": 2, "lockfileVersion": 2,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "@tsndr/cloudflare-worker-jwt", "name": "@tsndr/cloudflare-worker-jwt",
"version": "1.0.7", "version": "1.1.2",
"license": "MIT", "license": "MIT",
"devDependencies": { "devDependencies": {
"tslint": "^6.1.3" "tslint": "^6.1.3"

View File

@@ -1,6 +1,6 @@
{ {
"name": "@tsndr/cloudflare-worker-jwt", "name": "@tsndr/cloudflare-worker-jwt",
"version": "1.0.8", "version": "1.1.2",
"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": {

View File

@@ -24,7 +24,7 @@
"no-string-throw": true, "no-string-throw": true,
"no-tautology-expression": true, "no-tautology-expression": true,
"no-this-assignment": [true, {"allowed-names": ["^self$"], "allow-destructuring": true}], "no-this-assignment": [true, {"allowed-names": ["^self$"], "allow-destructuring": true}],
"no-trailing-whitespace": true, "no-trailing-whitespace": [true, "ignore-comments", "ignore-jsdoc"],
"no-unnecessary-callback-wrapper": true, "no-unnecessary-callback-wrapper": true,
"no-unnecessary-initializer": true, "no-unnecessary-initializer": true,
"no-unsafe-finally": true, "no-unsafe-finally": true,