1
0

Compare commits

..

61 Commits

Author SHA1 Message Date
a8f95f1c6d 2.2.2 2023-08-25 16:01:57 +02:00
Tom Lokhorst
b2886c0778 Allow array in Audience 2023-08-25 16:00:30 +02:00
76b7fcef27 2.2.1 2023-02-02 16:13:50 +01:00
3b5d8bcde8 hotfix 2023-02-02 16:13:28 +01:00
e22c509852 2.2.0 2023-02-02 15:48:08 +01:00
7ed375e876 audit fix 2023-02-02 15:46:10 +01:00
de658122b9 clean up 2023-02-02 15:46:10 +01:00
Michael Cereda
10dcf2f01b Support JWK format 2023-02-02 15:46:10 +01:00
1de6acbfff 2.1.4 2022-12-14 14:42:51 +01:00
b002db4547 option to set iat 2022-12-14 14:42:23 +01:00
1bdbd0a5c5 2.1.3 2022-11-25 00:34:50 +01:00
883ec55b73 ocd 2022-11-25 00:32:26 +01:00
Can Rau
c515fb76e6 docs: don't install as dev dependency (I think?)
Think the installation command shouldn't use `-D` as it's used in the production code right, so installing as dev dep would be confusing, right?

Please correct me if I'm wrong 🙏

Also thanks a lot for this package, was just using for a way to sign and verify JWT in Pages ❤️
2022-11-25 00:07:00 +01:00
ec41207832 2.1.2 2022-10-09 20:56:50 +02:00
e64e89f325 fix typo 2022-10-09 20:56:35 +02:00
fb573d928a 2.1.1 2022-10-09 20:48:01 +02:00
382ad66ea9 Revert "support for base64 secrets"
This reverts commit 67f1a8e5ed.
2022-10-09 20:47:29 +02:00
ffc1e87b32 2.1.0 2022-10-03 01:58:51 +02:00
decfa65391 clean up 2022-10-03 01:57:59 +02:00
badoge
67f1a8e5ed support for base64 secrets 2022-10-03 01:54:28 +02:00
fe1baf46b4 2.0.1 2022-07-08 15:07:00 +02:00
81f9eafd86 export types 2022-07-08 15:06:17 +02:00
747931ba69 2.0.0 2022-06-28 22:13:42 +02:00
261069d5cb fix workflow 2022-06-28 22:12:09 +02:00
7466a881a0 2.0.0-pre.0 2022-06-26 17:42:13 +02:00
81dde823d3 optimizations 2022-06-26 17:03:02 +02:00
210b733591 clean up 2022-06-26 15:54:10 +02:00
bf11705d11 exclude test file from npm package 2022-06-26 13:22:53 +02:00
99d172179e update workflow 2022-06-26 13:20:15 +02:00
63de8056a5 adapt old test file 2022-06-26 13:17:41 +02:00
b953f4165a typescript 2022-06-26 12:57:49 +02:00
c9da88c4bb Options fix 2022-06-22 19:11:53 +02:00
21ec1b6f2a Update to v1.4.3 2022-06-22 12:37:08 +02:00
Toby Schneider
97df6e7f81 Merge pull request #17 from IMZihad21/main
Destructure payload from decode function properly
2022-06-22 12:11:09 +02:00
ZèD
7198501a40 Destructure payload from decode function properly
The decode function returns an object containing a header and payload properties. Assigning the whole object to payload fails nbf and exp checks on verify JWT as those properties not found in decode return object directly. Instead, destructure payload property from decode return data that contains those values and check them correctly.

Signed-off-by: ZèD <imzihad@gmail.com>
2022-06-22 12:06:50 +06:00
cb6209b1b6 Docs fix 2022-06-04 22:29:46 +02:00
8f4e5e3199 Docs fix 2022-06-04 22:29:30 +02:00
594cdd6c05 Docs fix 2022-06-04 17:43:48 +02:00
f85abf30a8 Update docs 2022-06-04 17:43:11 +02:00
095b1d43f3 Update docs 2022-06-04 17:42:33 +02:00
0bc128fec1 Update docs 2022-06-04 17:40:47 +02:00
f846695242 Update docs 2022-06-04 17:29:50 +02:00
695e1c0dfe .decode() syntax change to support headers 2022-06-04 17:23:53 +02:00
64da4c625f .verify() bugfix 2022-06-04 14:53:59 +02:00
e4038ae0a7 Just to make sure 2022-06-04 14:40:06 +02:00
44329617de Fix .verify() and add testing 2022-06-04 14:18:06 +02:00
Toby Schneider
e7964b63c2 Merge pull request #9 from alaister/main
Add support for JWT header
2022-06-01 20:10:51 +02:00
b733a0650d Update readme 2022-06-01 15:11:57 +02:00
43879de15e Implement throwError option for .verify(). 2022-06-01 15:09:25 +02:00
0c8f476751 Update to v1.1.7 2022-04-11 02:20:54 +02:00
3c5d178fec Fix timestamp check 2022-04-11 02:20:14 +02:00
Alaister Young
f12cafd9d0 Add support for JWT header 2022-03-01 10:21:32 +11:00
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
15 changed files with 6147 additions and 549 deletions

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

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

View File

@@ -1,19 +0,0 @@
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

View File

@@ -2,29 +2,29 @@ name: Publish
on:
release:
types: [created]
types: [published]
jobs:
publish-npm:
publish:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v1
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: 12
node-version: 16
registry-url: https://registry.npmjs.org/
- run: npm publish --access public
- name: Install dependencies
run: npm ci
- name: Build
run: npm run build
- name: Publish to npmjs
run: npm publish --tag latest --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
- uses: actions/setup-node@v3
with:
node-version: 12
registry-url: https://npm.pkg.github.com/
- run: npm publish --access public
- name: Publish to GPR
run: npm publish --tag latest --access public
env:
NODE_AUTH_TOKEN: ${{secrets.GITHUB_TOKEN}}

6
.gitignore vendored
View File

@@ -141,4 +141,8 @@ dist
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*
.pnp.*
# Custom
/index.js
/index.d.ts

6
.npmignore Normal file
View File

@@ -0,0 +1,6 @@
.github/
src/
test/
.nvmrc
index.test.js
tsconfig.json

1
.nvmrc Normal file
View File

@@ -0,0 +1 @@
v16

View File

@@ -8,6 +8,9 @@ A lightweight JWT implementation with ZERO dependencies for Cloudflare Workers.
- [Install](#install)
- [Examples](#examples)
- [Usage](#usage)
- [Sign](#sign)
- [Verify](#verify)
- [Decode](#decode)
## Install
@@ -21,9 +24,9 @@ npm i @tsndr/cloudflare-worker-jwt
### Basic Example
```javascript
```typescript
async () => {
const jwt = require('@tsndr/cloudflare-worker-jwt')
import jwt from '@tsndr/cloudflare-worker-jwt'
// Creating a token
const token = await jwt.sign({ name: 'John Doe', email: 'john.doe@gmail.com' }, 'secret')
@@ -36,15 +39,15 @@ async () => {
return
// Decoding token
const payload = jwt.decode(token)
const { payload } = jwt.decode(token)
}
```
### Restrict Timeframe
```javascript
```typescript
async () => {
const jwt = require('@tsndr/cloudflare-worker-jwt')
import jwt from '@tsndr/cloudflare-worker-jwt'
// Creating a token
const token = await jwt.sign({
@@ -62,53 +65,86 @@ async () => {
return
// 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
- [Sign](#sign)
- [Verify](#verify)
- [Decode](#decode)
<hr>
### `jwt.sign(payload, secret, [algorithm])`
### Sign
#### `jwt.sign(payload, secret, [options])`
Signs a payload and returns the token.
#### Arguments
Argument | Type | Satus | Default | Description
Argument | Type | Status | 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.
`algorithm` | `string` | optional | `HS256` | The algorithm used to sign the payload, possible values: `HS256` or `HS512`
`options` | `object` | optional | `{ algorithm: 'HS256' }` | The options object supporting `algorithm` and `keyid`. (See [Available Algorithms](#available-algorithms))
#### `return`
Returns token as a `string`.
<hr>
### `jwt.verify(token, secret, [algorithm])`
### Verify
#### `jwt.verify(token, secret, [options])`
Verifies the integrity of the token and returns a boolean value.
Argument | Type | Satus | Default | Description
Argument | Type | Status | 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` | `string` | optional | `HS256` | The algorithm used to sign the payload, possible values: `HS256` or `HS512`
`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`
Returns `true` if signature, `nbf` (if set) and `exp` (if set) are valid, otherwise returns `false`.
<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!
Argument | Type | Satus | Default | Description
Argument | Type | Status | Default | Description
----------- | -------- | -------- | ------- | -----------
`token` | `string` | required | - | The token string generated by `jwt.sign()`.
#### `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
- ES256
- ES384
- ES512
- HS256
- HS384
- HS512
- RS256
- RS384
- RS512

39
index.d.ts vendored
View File

@@ -1,39 +0,0 @@
/**
* 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 {'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>
/**
* 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>
/**
* 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
export = _exports

108
index.js
View File

@@ -1,108 +0,0 @@
class Base64URL {
static parse(s) {
return new Uint8Array(Array.prototype.map.call(atob(s.replace(/-/g, '+').replace(/_/g, '/').replace(/\s/g, '')), c => c.charCodeAt(0)))
}
static stringify(a) {
return btoa(String.fromCharCode.apply(0, a)).replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_')
}
}
class JWT {
constructor() {
if (!crypto || !crypto.subtle)
throw new Error('Crypto not supported!')
this.algorithms = {
HS256: {
name: 'HMAC',
hash: {
name: 'SHA-256'
}
},
HS512: {
name: 'HMAC',
hash: {
name: 'SHA-512'
}
}
}
}
_utf8ToUint8Array(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') {
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 algorithm !== 'string')
throw new Error('algorithm must be a string')
const importAlgorithm = this.algorithms[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: 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 `${partialToken}.${Base64URL.stringify(new Uint8Array(signature))}`
}
async verify(token, secret, algorithm = '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 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 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 messageAsUint8Array = this._utf8ToUint8Array(partialToken)
const res = await crypto.subtle.sign(importAlgorithm.name, key, messageAsUint8Array)
return Base64URL.stringify(new Uint8Array(res)) === signaturePart
}
decode(token) {
return this._decodePayload(token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/'))
}
}
module.exports = new JWT

180
index.test.js Normal file
View File

@@ -0,0 +1,180 @@
const { subtle } = require('node:crypto').webcrypto
Object.defineProperty(global, 'crypto', {
value: { subtle }
})
const jwt = require('./index.js')
const oneDay = (60 * 60 * 24)
const now = Date.now() / 1000
const algorithms = [
'ES256',
'ES384',
'ES512',
'HS256',
'HS384',
'HS512',
'RS256',
'RS384',
'RS512'
]
const secrets = {}
// Keypairs
for (const algorithm of algorithms) {
if (algorithm.startsWith('HS')) {
//secrets[algorithm] = 'c2VjcmV0'
secrets[algorithm] = 'secret'
} else if (algorithm.startsWith('RS')) {
secrets[algorithm] = {
public: `-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAu1SU1LfVLPHCozMxH2Mo
4lgOEePzNm0tRgeLezV6ffAt0gunVTLw7onLRnrq0/IzW7yWR7QkrmBL7jTKEn5u
+qKhbwKfBstIs+bMY2Zkp18gnTxKLxoS2tFczGkPLPgizskuemMghRniWaoLcyeh
kd3qqGElvW/VDL5AaWTg0nLVkjRo9z+40RQzuVaE8AkAFmxZzow3x+VJYKdjykkJ
0iT9wCS0DRTXu269V264Vf/3jvredZiKRkgwlL9xNAwxXFg0x/XFw005UWVRIkdg
cKWTjpBP2dPwVZ4WWC+9aGVd+Gyn1o0CLelf4rEjGoXbAAEgAqeGUxrcIlbjXfbc
mwIDAQAB
-----END PUBLIC KEY-----`,
private: `-----BEGIN PRIVATE KEY-----
MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQC7VJTUt9Us8cKj
MzEfYyjiWA4R4/M2bS1GB4t7NXp98C3SC6dVMvDuictGeurT8jNbvJZHtCSuYEvu
NMoSfm76oqFvAp8Gy0iz5sxjZmSnXyCdPEovGhLa0VzMaQ8s+CLOyS56YyCFGeJZ
qgtzJ6GR3eqoYSW9b9UMvkBpZODSctWSNGj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8Fkss8Js1RieK2LniBxMgmYml3pfVLKGnzmng7H2+cwPLhPIzIuwytXywh
2bzbsYEfYx3EoEVgMEpPhoarQnYPukrJO4gwE2o5Te6T5mJSZGlQJQj9q4ZB2Dfz
et6INsK0oG8XVGXSpQvQh3RUYekCZQkBBFcpqWpbIEsCgYAnM3DQf3FJoSnXaMhr
VBIovic5l0xFkEHskAjFTevO86Fsz1C2aSeRKSqGFoOQ0tmJzBEs1R6KqnHInicD
TQrKhArgLXX4v3CddjfTRJkFWDbE/CkvKZNOrcf1nhaGCPspRJj2KUkj1Fhl9Cnc
dn/RsYEONbwQSjIfMPkvxF+8HQ==
-----END PRIVATE KEY-----`
}
} else if (algorithm.startsWith('ES')) {
if (algorithm === 'ES256') {
secrets[algorithm] = {
public: `-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEEVs/o5+uQbTjL3chynL4wXgUg2R9
q9UU8I5mEovUf86QZ7kOBIjJwqnzD1omageEHWwHdBO6B+dFabmdT9POxg==
-----END PUBLIC KEY-----`,
private: `-----BEGIN PRIVATE KEY-----
MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgevZzL1gdAFr88hb2
OF/2NxApJCzGCEDdfSp6VQO30hyhRANCAAQRWz+jn65BtOMvdyHKcvjBeBSDZH2r
1RTwjmYSi9R/zpBnuQ4EiMnCqfMPWiZqB4QdbAd0E7oH50VpuZ1P087G
-----END PRIVATE KEY-----`
}
} else if (algorithm === 'ES384') {
secrets[algorithm] = {
public: `-----BEGIN PUBLIC KEY-----
MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEC1uWSXj2czCDwMTLWV5BFmwxdM6PX9p+
Pk9Yf9rIf374m5XP1U8q79dBhLSIuaojsvOT39UUcPJROSD1FqYLued0rXiooIii
1D3jaW6pmGVJFhodzC31cy5sfOYotrzF
-----END PUBLIC KEY-----`,
private: `-----BEGIN PRIVATE KEY-----
MIG2AgEAMBAGByqGSM49AgEGBSuBBAAiBIGeMIGbAgEBBDCAHpFQ62QnGCEvYh/p
E9QmR1C9aLcDItRbslbmhen/h1tt8AyMhskeenT+rAyyPhGhZANiAAQLW5ZJePZz
MIPAxMtZXkEWbDF0zo9f2n4+T1h/2sh/fviblc/VTyrv10GEtIi5qiOy85Pf1RRw
8lE5IPUWpgu553SteKigiKLUPeNpbqmYZUkWGh3MLfVzLmx85ii2vMU=
-----END PRIVATE KEY-----`
}
} else if (algorithm === 'ES512') {
secrets[algorithm] = {
public: `-----BEGIN PUBLIC KEY-----
MIGbMBAGByqGSM49AgEGBSuBBAAjA4GGAAQBgc4HZz+/fBbC7lmEww0AO3NK9wVZ
PDZ0VEnsaUFLEYpTzb90nITtJUcPUbvOsdZIZ1Q8fnbquAYgxXL5UgHMoywAib47
6MkyyYgPk0BXZq3mq4zImTRNuaU9slj9TVJ3ScT3L1bXwVuPJDzpr5GOFpaj+WwM
Al8G7CqwoJOsW7Kddns=
-----END PUBLIC KEY-----`,
private: `-----BEGIN PRIVATE KEY-----
MIHuAgEAMBAGByqGSM49AgEGBSuBBAAjBIHWMIHTAgEBBEIBiyAa7aRHFDCh2qga
9sTUGINE5jHAFnmM8xWeT/uni5I4tNqhV5Xx0pDrmCV9mbroFtfEa0XVfKuMAxxf
Z6LM/yKhgYkDgYYABAGBzgdnP798FsLuWYTDDQA7c0r3BVk8NnRUSexpQUsRilPN
v3SchO0lRw9Ru86x1khnVDx+duq4BiDFcvlSAcyjLACJvjvoyTLJiA+TQFdmrear
jMiZNE25pT2yWP1NUndJxPcvVtfBW48kPOmvkY4WlqP5bAwCXwbsKrCgk6xbsp12
ew==
-----END PRIVATE KEY-----`
}
}
}
}
// Payload
const testPayload = {
sub: "1234567890",
name: "John Doe"
}
// Self test
test.each(Object.entries(secrets))(`Self test: %s`, async (algorithm, key) => {
let privateKey = key
let publicKey = key
if (typeof key === 'object') {
privateKey = key.private
publicKey = key.public
}
const token = await jwt.sign(testPayload, privateKey, { algorithm })
expect(token).toMatch(/^[a-zA-Z0-9\-_]+\.[a-zA-Z0-9\-_]+\.[a-zA-Z0-9\-_]+$/)
const verified = await jwt.verify(token, publicKey, { algorithm })
expect(verified).toBeTruthy()
const { payload } = jwt.decode(token)
expect({
sub: payload.sub,
name: payload.name
}).toMatchObject({
sub: testPayload.sub,
name: testPayload.name
})
})
// External token test
const externalTokens = {
ES256: 'eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.Ri9u3ZJpyoHf1_i3KpVE5gMggyU3VMYPeEVktAsG1kGLOxFNJBXydQls3WFBaXXH2-sN74IMe-nDcM7NoJ6GMQ',
ES384: 'eyJhbGciOiJFUzM4NCIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.6nmlvcCpsfENb6ssgX3rJ2XSjpFSXD1RPS1CK0iDZFdi6I6Gnmpi456RSW6-0XSSgq2E2XBcWCSYE6TeI63jOGZJTQ6-65g4sndbzBPqYPWbLny00NQ4MQgQXVu6tRzg',
ES512: 'eyJhbGciOiJFUzUxMiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.AbRwaCPJM2X3XjE2kInClHVGJNIcpL5C4a1ZrgwEM05RTryyNbazWRFbXAEDtHm8crvXpqw3a8JQwYDwvMyoOr4jAJ4RbhJitLgCGEzhKjvNy4xGrg3dV8gGEShFowgDfVz0KqHOX_Bc_DbyL-gtZPdfGTwT2upLkJE-lj47RStPDh0b',
HS256: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF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5mHhPSn0qLsZfCFj0NVmb4mz4dFQPCCMj-F5zVn9e3zZoj0lIXWM8rxB69QHC3Er47mtDt3BKgysTL3BvvV89kD6UjLoUcAI3lwj0mi7acLoE27i1_TnIBqWNRPAsdvTDawNE0_4lvI5bxEWQCqisJwxCoMDIeJsmDzfyApgU_SAFSVULxXwU2VewaxdQB-41OZdWwUEAxh81iB6DFWrqd2CaJkUYoWjgYpeWsyeC2m_-ECGrHGEz1nKTm9c7BaPxurz7fHD7RJd9Wpx-mKDVsfspO9quWb_OLeGGbxTtAomMvjQjut56kx2fqTleDnNDh_0GE88w',
RS512: 'eyJhbGciOiJSUzUxMiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.kEZmDAnHHU_0bcGXMd5LA7vF87yQgXNaioPHP4lU4O3JJYuZ54fJdv3HT58xk-MFEDuWro_5fvNIp2VM-PlkZvYWrhQkJ-c-seoSa3ANq_PciC3bGfzYHEdjAE71GrAMI4FlcAGsq3ChkOnCTFqjWDmVwaRYCgMsFQ-U5cjvFhndFMizrkRljTF4v5oFdWytV_J-UafPtNdQXcGND1M74DqObnTHhZHg8aDfNzZcvnIeKcDVGUlUEL5ia1kPMrVhCtOAOJmEU8ivCdWWzt-jMQBf7cZeoCzDKHG72ysTTCfRoBVc1_SrQTHcHDiiBeW9nCazMLkltyP5NeawR_RNlg'
}
test.each(Object.entries(externalTokens))('Verify external tokens: %s', async (algorithm, token) => {
const key = secrets[algorithm]
let publicKey = key
if (typeof key === 'object')
publicKey = key.public
const verified = await jwt.verify(token, publicKey, { algorithm })
expect(verified).toBeTruthy()
const { payload } = jwt.decode(token)
expect({
sub: payload.sub,
name: payload.name
}).toMatchObject({
sub: testPayload.sub,
name: testPayload.name
})
})

5839
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,10 +1,12 @@
{
"name": "@tsndr/cloudflare-worker-jwt",
"version": "1.1.3",
"version": "2.2.2",
"description": "A lightweight JWT implementation with ZERO dependencies for Cloudflare Worker",
"main": "index.js",
"types": "index.d.ts",
"scripts": {
"lint": "tslint index.js"
"build": "tsc",
"test": "jest"
},
"repository": {
"type": "git",
@@ -24,6 +26,8 @@
},
"homepage": "https://github.com/tsndr/cloudflare-worker-jwt#readme",
"devDependencies": {
"tslint": "^6.1.3"
"@cloudflare/workers-types": "^3.13.0",
"jest": "^28.1.1",
"typescript": "^4.7.4"
}
}

313
src/index.ts Normal file
View File

@@ -0,0 +1,313 @@
if (typeof crypto === 'undefined' || !crypto.subtle)
throw new Error('SubtleCrypto not supported!')
/**
* @typedef JwtAlgorithm
* @type {'ES256'|'ES384'|'ES512'|'HS256'|'HS384'|'HS512'|'RS256'|'RS384'|'RS512'}
*/
export type JwtAlgorithm = 'ES256'|'ES384'|'ES512'|'HS256'|'HS384'|'HS512'|'RS256'|'RS384'|'RS512'
/**
* @typedef JwtAlgorithms
*/
export interface JwtAlgorithms {
[key: string]: SubtleCryptoImportKeyAlgorithm
}
/**
* @typedef JwtHeader
* @prop {string} [typ] Type
*/
export interface JwtHeader {
/**
* Type (default: `"JWT"`)
*
* @default "JWT"
*/
typ?: string
[key: string]: any
}
/**
* @typedef JwtPayload
* @prop {string} [iss] Issuer
* @prop {string} [sub] Subject
* @prop {string | string[]} [aud] Audience
* @prop {string} [exp] Expiration Time
* @prop {string} [nbf] Not Before
* @prop {string} [iat] Issued At
* @prop {string} [jti] JWT ID
*/
export interface JwtPayload {
/** Issuer */
iss?: string
/** Subject */
sub?: string
/** Audience */
aud?: string | string[]
/** Expiration Time */
exp?: number
/** Not Before */
nbf?: number
/** Issued At */
iat?: number
/** JWT ID */
jti?: string
[key: string]: any
}
/**
* @typedef JwtOptions
* @prop {JwtAlgorithm | string} algorithm
*/
export interface JwtOptions {
algorithm?: JwtAlgorithm | string
}
/**
* @typedef JwtSignOptions
* @extends JwtOptions
* @prop {JwtHeader} [header]
*/
export interface JwtSignOptions extends JwtOptions {
header?: JwtHeader
}
/**
* @typedef JwtVerifyOptions
* @extends JwtOptions
* @prop {boolean} [throwError=false] If `true` throw error if checks fail. (default: `false`)
*/
export interface JwtVerifyOptions extends JwtOptions {
/**
* If `true` throw error if checks fail. (default: `false`)
*
* @default false
*/
throwError?: boolean
}
/**
* @typedef JwtData
* @prop {JwtHeader} header
* @prop {JwtPayload} payload
*/
export interface JwtData {
header: JwtHeader
payload: JwtPayload
}
function base64UrlParse(s: string): Uint8Array {
// @ts-ignore
return new Uint8Array(Array.prototype.map.call(atob(s.replace(/-/g, '+').replace(/_/g, '/').replace(/\s/g, '')), c => c.charCodeAt(0)))
// return new Uint8Array(Array.from(atob(s.replace(/-/g, '+').replace(/_/g, '/').replace(/\s/g, ''))).map(c => c.charCodeAt(0)))
}
function base64UrlStringify(a: Uint8Array): string {
// @ts-ignore
return btoa(String.fromCharCode.apply(0, a)).replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_')
// return btoa(String.fromCharCode.apply(0, Array.from(a))).replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_')
}
const algorithms: JwtAlgorithms = {
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-521', 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' } }
}
function _utf8ToUint8Array(str: string): Uint8Array {
return base64UrlParse(btoa(unescape(encodeURIComponent(str))))
}
function _str2ab(str: string): ArrayBuffer {
str = atob(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);
}
return buf;
}
function _decodePayload(raw: string): JwtHeader | JwtPayload | null {
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
}
}
/**
* Signs a payload and returns the token
*
* @param {JwtPayload} payload The payload object. To use `nbf` (Not Before) and/or `exp` (Expiration Time) add `nbf` and/or `exp` to the payload.
* @param {string | JsonWebKey} secret A string which is used to sign the payload.
* @param {JwtSignOptions | JwtAlgorithm | string} [options={ algorithm: 'HS256', header: { typ: 'JWT' } }] The options object or the algorithm.
* @throws {Error} If there's a validation issue.
* @returns {Promise<string>} Returns token as a `string`.
*/
export async function sign(payload: JwtPayload, secret: string | JsonWebKey, options: JwtSignOptions | JwtAlgorithm = { algorithm: 'HS256', header: { typ: 'JWT' } }): Promise<string> {
if (typeof options === 'string')
options = { algorithm: options, header: { typ: 'JWT' } }
options = { algorithm: 'HS256', header: { typ: 'JWT' }, ...options }
if (payload === null || typeof payload !== 'object')
throw new Error('payload must be an object')
if (typeof secret !== 'string' && typeof secret !== 'object')
throw new Error('secret must be a string or a JWK object')
if (typeof options.algorithm !== 'string')
throw new Error('options.algorithm must be a string')
const algorithm: SubtleCryptoImportKeyAlgorithm = algorithms[options.algorithm]
if (!algorithm)
throw new Error('algorithm not found')
if (!payload.iat)
payload.iat = Math.floor(Date.now() / 1000)
const payloadAsJSON = JSON.stringify(payload)
const partialToken = `${base64UrlStringify(_utf8ToUint8Array(JSON.stringify({ ...options.header, alg: options.algorithm })))}.${base64UrlStringify(_utf8ToUint8Array(payloadAsJSON))}`
let keyFormat = 'raw'
let keyData
if (typeof secret === 'object') {
keyFormat = 'jwk'
keyData = secret
} else if (typeof secret === 'string' && secret.startsWith('-----BEGIN')) {
keyFormat = 'pkcs8'
keyData = _str2ab(secret.replace(/-----BEGIN.*?-----/g, '').replace(/-----END.*?-----/g, '').replace(/\s/g, ''))
} else
keyData = _utf8ToUint8Array(secret)
const key = await crypto.subtle.importKey(keyFormat, keyData, algorithm, false, ['sign'])
const signature = await crypto.subtle.sign(algorithm, key, _utf8ToUint8Array(partialToken))
return `${partialToken}.${base64UrlStringify(new Uint8Array(signature))}`
}
/**
* Verifies the integrity of the token and returns a boolean value.
*
* @param {string} token The token string generated by `jwt.sign()`.
* @param {string | JsonWebKey} secret The string which was used to sign the payload.
* @param {JWTVerifyOptions | JWTAlgorithm} options The options object or the algorithm.
* @throws {Error | string} Throws an error `string` if the token is invalid or an `Error-Object` if there's a validation issue.
* @returns {Promise<boolean>} Returns `true` if signature, `nbf` (if set) and `exp` (if set) are valid, otherwise returns `false`.
*/
export async function verify(token: string, secret: string | JsonWebKey, options: JwtVerifyOptions | JwtAlgorithm = { algorithm: 'HS256', throwError: false }): Promise<boolean> {
if (typeof options === 'string')
options = { algorithm: options, throwError: false }
options = { algorithm: 'HS256', throwError: false, ...options }
if (typeof token !== 'string')
throw new Error('token must be a string')
if (typeof secret !== 'string' && typeof secret !== 'object')
throw new Error('secret must be a string or a JWK object')
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 algorithm: SubtleCryptoImportKeyAlgorithm = algorithms[options.algorithm]
if (!algorithm)
throw new Error('algorithm not found')
const { payload } = decode(token)
if (!payload) {
if (options.throwError)
throw 'PARSE_ERROR'
return false
}
if (payload.nbf && payload.nbf > Math.floor(Date.now() / 1000)) {
if (options.throwError)
throw 'NOT_YET_VALID'
return false
}
if (payload.exp && payload.exp <= Math.floor(Date.now() / 1000)) {
if (options.throwError)
throw 'EXPIRED'
return false
}
let keyFormat = 'raw'
let keyData
if (typeof secret === 'object') {
keyFormat = 'jwk';
keyData = secret;
} else if (typeof secret === 'string' && secret.startsWith('-----BEGIN')) {
keyFormat = 'spki'
keyData = _str2ab(secret.replace(/-----BEGIN.*?-----/g, '').replace(/-----END.*?-----/g, '').replace(/\s/g, ''))
} else
keyData = _utf8ToUint8Array(secret)
const key = await crypto.subtle.importKey(keyFormat, keyData, algorithm, false, ['verify'])
return await crypto.subtle.verify(algorithm, key, base64UrlParse(tokenParts[2]), _utf8ToUint8Array(`${tokenParts[0]}.${tokenParts[1]}`))
}
/**
* 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 {JwtData} Returns an `object` containing `header` and `payload`.
*/
export function decode(token: string): JwtData {
return {
header: _decodePayload(token.split('.')[0].replace(/-/g, '+').replace(/_/g, '/')) as JwtHeader,
payload: _decodePayload(token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/')) as JwtPayload
}
}
export default {
sign,
verify,
decode
}

27
tsconfig.json Normal file
View File

@@ -0,0 +1,27 @@
{
"compilerOptions": {
"outDir": ".",
"module": "commonjs",
"target": "esnext",
"lib": ["esnext"],
"declaration": true,
"strict": true,
"noImplicitAny": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"strictBindCallApply": true,
"strictPropertyInitialization": true,
"noImplicitThis": true,
"alwaysStrict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"esModuleInterop": true,
"preserveConstEnums": true,
"moduleResolution": "node",
"types": ["@cloudflare/workers-types"]
},
"include": ["src"],
"exclude": ["node_modules"]
}

View File

@@ -1,53 +0,0 @@
{
"jsRules": {
"arrow-return-shorthand": [true, "multiline"],
"binary-expression-operand-order": true,
"class-name": true,
"comment-format": [true, "check-space"],
"curly": [true, "as-needed"],
"encoding": true,
"increment-decrement": [true, "allow-post"],
"indent": [true, "spaces", 2],
"linebreak-style": [true, "LF"],
"no-async-without-await": true,
"no-consecutive-blank-lines": [true, 2],
"no-duplicate-switch-case": true,
"no-duplicate-variable": [true, "check-parameters"],
"no-empty": true,
"no-eval": true,
"no-invalid-template-strings": true,
"no-invalid-this": true,
"no-irregular-whitespace": true,
"no-return-await": true,
"no-shadowed-variable": true,
"no-sparse-arrays": true,
"no-string-throw": true,
"no-tautology-expression": true,
"no-this-assignment": [true, {"allowed-names": ["^self$"], "allow-destructuring": true}],
"no-trailing-whitespace": [true, "ignore-comments", "ignore-jsdoc"],
"no-unnecessary-callback-wrapper": true,
"no-unnecessary-initializer": true,
"no-unsafe-finally": true,
"no-var-keyword": true,
"object-literal-key-quotes": [true, "consistent-as-needed"],
"one-line": [true, "check-catch", "check-finally", "check-else", "check-open-brace", "check-whitespace"],
"one-variable-per-declaration": [true, "ignore-for-loop"],
"ordered-imports": true,
"prefer-conditional-expression": [true, "check-else-if"],
"prefer-const": true,
"prefer-object-spread": true,
"prefer-switch": [true, {"min-cases": 3}],
"prefer-template": [true, "allow-single-concat"],
"prefer-while": true,
"quotemark": [true, "single"],
"semicolon": [true, "never"],
"space-before-function-paren": [true, "never"],
"static-this": true,
"trailing-comma": [true, {"multiline": "never", "singleline": "never"}],
"triple-equals": true,
"unnecessary-constructor": [true, {"check-super-calls": true}],
"unnecessary-else": [true, {"allow-else-if": true}],
"use-isnan": true,
"whitespace": [true, "check-branch", "check-decl", "check-operator", "check-module", "check-separator", "check-rest-spread", "check-type", "check-typecast", "check-type-operator", "check-preblock", "check-postbrace"]
}
}