Compare commits
26 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
1394e4e33d
|
|||
|
47028970b4
|
|||
|
6ac43d493d
|
|||
|
cc66bd9c47
|
|||
|
a8f95f1c6d
|
|||
|
|
b2886c0778 | ||
|
76b7fcef27
|
|||
|
3b5d8bcde8
|
|||
|
e22c509852
|
|||
| 7ed375e876 | |||
| de658122b9 | |||
|
|
10dcf2f01b | ||
|
1de6acbfff
|
|||
|
b002db4547
|
|||
|
1bdbd0a5c5
|
|||
|
883ec55b73
|
|||
|
|
c515fb76e6 | ||
|
ec41207832
|
|||
|
e64e89f325
|
|||
|
fb573d928a
|
|||
|
382ad66ea9
|
|||
|
ffc1e87b32
|
|||
|
decfa65391
|
|||
|
|
67f1a8e5ed | ||
|
fe1baf46b4
|
|||
|
81f9eafd86
|
10
.editorconfig
Normal file
10
.editorconfig
Normal file
@@ -0,0 +1,10 @@
|
||||
root = true
|
||||
|
||||
[*]
|
||||
end_of_line = lf
|
||||
insert_final_newline = false
|
||||
|
||||
[src/**/*.ts]
|
||||
charset = utf-8
|
||||
indent_style = space
|
||||
indent_size = 4
|
||||
10
README.md
10
README.md
@@ -16,7 +16,7 @@ A lightweight JWT implementation with ZERO dependencies for Cloudflare Workers.
|
||||
## Install
|
||||
|
||||
```
|
||||
npm i -D @tsndr/cloudflare-worker-jwt
|
||||
npm i @tsndr/cloudflare-worker-jwt
|
||||
```
|
||||
|
||||
|
||||
@@ -84,7 +84,7 @@ 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.
|
||||
@@ -100,11 +100,11 @@ Returns token as a `string`.
|
||||
|
||||
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.
|
||||
`options` | `object` | optional | `{ algorithm: 'HS256', throwError: false }` | The options object supporting `algorithm` and `throwError`. (See [Available Algorithms](#available-algorithms))
|
||||
`options` | `object` | optional | `{ algorithm: 'HS256', skipValidation: false, throwError: false }` | The options object supporting `algorithm`, `skipValidation` and `throwError`. (See [Available Algorithms](#available-algorithms))
|
||||
|
||||
#### `throws`
|
||||
If `options.throwError` is `true` and the token is invalid, an error will be thrown.
|
||||
@@ -119,7 +119,7 @@ Returns `true` if signature, `nbf` (if set) and `exp` (if set) are valid, otherw
|
||||
|
||||
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()`.
|
||||
|
||||
|
||||
@@ -22,9 +22,10 @@ const secrets = {}
|
||||
|
||||
// Keypairs
|
||||
for (const algorithm of algorithms) {
|
||||
if (algorithm.startsWith('HS'))
|
||||
if (algorithm.startsWith('HS')) {
|
||||
//secrets[algorithm] = 'c2VjcmV0'
|
||||
secrets[algorithm] = 'secret'
|
||||
else if (algorithm.startsWith('RS')) {
|
||||
} else if (algorithm.startsWith('RS')) {
|
||||
secrets[algorithm] = {
|
||||
public: `-----BEGIN PUBLIC KEY-----
|
||||
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAu1SU1LfVLPHCozMxH2Mo
|
||||
@@ -122,6 +123,7 @@ const testPayload = {
|
||||
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
|
||||
@@ -158,12 +160,11 @@ const externalTokens = {
|
||||
|
||||
test.each(Object.entries(externalTokens))('Verify external tokens: %s', async (algorithm, token) => {
|
||||
const key = secrets[algorithm]
|
||||
let privateKey = key
|
||||
|
||||
let publicKey = key
|
||||
if (typeof key === 'object') {
|
||||
privateKey = key.private
|
||||
|
||||
if (typeof key === 'object')
|
||||
publicKey = key.public
|
||||
}
|
||||
|
||||
const verified = await jwt.verify(token, publicKey, { algorithm })
|
||||
expect(verified).toBeTruthy()
|
||||
|
||||
16
package-lock.json
generated
16
package-lock.json
generated
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "@tsndr/cloudflare-worker-jwt",
|
||||
"version": "2.0.0",
|
||||
"version": "2.2.3",
|
||||
"lockfileVersion": 2,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "@tsndr/cloudflare-worker-jwt",
|
||||
"version": "2.0.0",
|
||||
"version": "2.2.3",
|
||||
"license": "MIT",
|
||||
"devDependencies": {
|
||||
"@cloudflare/workers-types": "^3.13.0",
|
||||
@@ -2542,9 +2542,9 @@
|
||||
"dev": true
|
||||
},
|
||||
"node_modules/json5": {
|
||||
"version": "2.2.1",
|
||||
"resolved": "https://registry.npmjs.org/json5/-/json5-2.2.1.tgz",
|
||||
"integrity": "sha512-1hqLFMSrGHRHxav9q9gNjJ5EXznIxGVO09xQRrwplcS8qs28pZ8s8hupZAmqDwZUmVZ2Qb2jnyPOWcDH8m8dlA==",
|
||||
"version": "2.2.3",
|
||||
"resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz",
|
||||
"integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==",
|
||||
"dev": true,
|
||||
"bin": {
|
||||
"json5": "lib/cli.js"
|
||||
@@ -5364,9 +5364,9 @@
|
||||
"dev": true
|
||||
},
|
||||
"json5": {
|
||||
"version": "2.2.1",
|
||||
"resolved": "https://registry.npmjs.org/json5/-/json5-2.2.1.tgz",
|
||||
"integrity": "sha512-1hqLFMSrGHRHxav9q9gNjJ5EXznIxGVO09xQRrwplcS8qs28pZ8s8hupZAmqDwZUmVZ2Qb2jnyPOWcDH8m8dlA==",
|
||||
"version": "2.2.3",
|
||||
"resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz",
|
||||
"integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==",
|
||||
"dev": true
|
||||
},
|
||||
"kleur": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@tsndr/cloudflare-worker-jwt",
|
||||
"version": "2.0.0",
|
||||
"version": "2.2.3",
|
||||
"description": "A lightweight JWT implementation with ZERO dependencies for Cloudflare Worker",
|
||||
"main": "index.js",
|
||||
"types": "index.d.ts",
|
||||
|
||||
94
src/index.ts
94
src/index.ts
@@ -5,12 +5,12 @@ if (typeof crypto === 'undefined' || !crypto.subtle)
|
||||
* @typedef JwtAlgorithm
|
||||
* @type {'ES256'|'ES384'|'ES512'|'HS256'|'HS384'|'HS512'|'RS256'|'RS384'|'RS512'}
|
||||
*/
|
||||
type JwtAlgorithm = 'ES256'|'ES384'|'ES512'|'HS256'|'HS384'|'HS512'|'RS256'|'RS384'|'RS512'
|
||||
export type JwtAlgorithm = 'ES256'|'ES384'|'ES512'|'HS256'|'HS384'|'HS512'|'RS256'|'RS384'|'RS512'
|
||||
|
||||
/**
|
||||
* @typedef JwtAlgorithms
|
||||
*/
|
||||
interface JwtAlgorithms {
|
||||
export interface JwtAlgorithms {
|
||||
[key: string]: SubtleCryptoImportKeyAlgorithm
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@ interface JwtAlgorithms {
|
||||
* @typedef JwtHeader
|
||||
* @prop {string} [typ] Type
|
||||
*/
|
||||
interface JwtHeader {
|
||||
export interface JwtHeader {
|
||||
/**
|
||||
* Type (default: `"JWT"`)
|
||||
*
|
||||
@@ -33,13 +33,13 @@ interface JwtHeader {
|
||||
* @typedef JwtPayload
|
||||
* @prop {string} [iss] Issuer
|
||||
* @prop {string} [sub] Subject
|
||||
* @prop {string} [aud] Audience
|
||||
* @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
|
||||
*/
|
||||
interface JwtPayload {
|
||||
export interface JwtPayload {
|
||||
/** Issuer */
|
||||
iss?: string
|
||||
|
||||
@@ -47,7 +47,7 @@ interface JwtPayload {
|
||||
sub?: string
|
||||
|
||||
/** Audience */
|
||||
aud?: string
|
||||
aud?: string | string[]
|
||||
|
||||
/** Expiration Time */
|
||||
exp?: number
|
||||
@@ -68,7 +68,7 @@ interface JwtPayload {
|
||||
* @typedef JwtOptions
|
||||
* @prop {JwtAlgorithm | string} algorithm
|
||||
*/
|
||||
interface JwtOptions {
|
||||
export interface JwtOptions {
|
||||
algorithm?: JwtAlgorithm | string
|
||||
}
|
||||
|
||||
@@ -77,7 +77,7 @@ interface JwtOptions {
|
||||
* @extends JwtOptions
|
||||
* @prop {JwtHeader} [header]
|
||||
*/
|
||||
interface JwtSignOptions extends JwtOptions {
|
||||
export interface JwtSignOptions extends JwtOptions {
|
||||
header?: JwtHeader
|
||||
}
|
||||
|
||||
@@ -86,7 +86,12 @@ interface JwtSignOptions extends JwtOptions {
|
||||
* @extends JwtOptions
|
||||
* @prop {boolean} [throwError=false] If `true` throw error if checks fail. (default: `false`)
|
||||
*/
|
||||
interface JwtVerifyOptions extends JwtOptions {
|
||||
export interface JwtVerifyOptions extends JwtOptions {
|
||||
/**
|
||||
* If `true` all expiry checks will be skipped
|
||||
*/
|
||||
skipValidation?: boolean
|
||||
|
||||
/**
|
||||
* If `true` throw error if checks fail. (default: `false`)
|
||||
*
|
||||
@@ -100,7 +105,7 @@ interface JwtVerifyOptions extends JwtOptions {
|
||||
* @prop {JwtHeader} header
|
||||
* @prop {JwtPayload} payload
|
||||
*/
|
||||
interface JwtData {
|
||||
export interface JwtData {
|
||||
header: JwtHeader
|
||||
payload: JwtPayload
|
||||
}
|
||||
@@ -135,11 +140,14 @@ function _utf8ToUint8Array(str: string): Uint8Array {
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -156,6 +164,7 @@ function _decodePayload(raw: string): JwtHeader | JwtPayload | null {
|
||||
default:
|
||||
throw new Error('Illegal base64url string!')
|
||||
}
|
||||
|
||||
try {
|
||||
return JSON.parse(decodeURIComponent(escape(atob(raw))))
|
||||
} catch {
|
||||
@@ -167,36 +176,52 @@ function _decodePayload(raw: string): JwtHeader | JwtPayload | 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} secret A string which is used to sign 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, options: JwtSignOptions | JwtAlgorithm = { algorithm: 'HS256', header: { typ: 'JWT' } }): Promise<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')
|
||||
throw new Error('secret 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 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 (secret.startsWith('-----BEGIN')) {
|
||||
|
||||
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))}`
|
||||
}
|
||||
|
||||
@@ -204,51 +229,72 @@ export async function sign(payload: JwtPayload, secret: string, options: JwtSign
|
||||
* 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 {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, options: JwtVerifyOptions | JwtAlgorithm = { algorithm: 'HS256', throwError: false }): Promise<boolean> {
|
||||
export async function verify(token: string, secret: string | JsonWebKey, options: JwtVerifyOptions | JwtAlgorithm = { algorithm: 'HS256', skipValidation: false, throwError: false }): Promise<boolean> {
|
||||
if (typeof options === 'string')
|
||||
options = { algorithm: options, throwError: false }
|
||||
options = { algorithm: 'HS256', throwError: false, ...options }
|
||||
|
||||
options = { algorithm: 'HS256', skipValidation: false, throwError: false, ...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 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.skipValidation && !payload) {
|
||||
if (options.throwError)
|
||||
throw 'PARSE_ERROR'
|
||||
|
||||
return false
|
||||
}
|
||||
if (payload.nbf && payload.nbf > Math.floor(Date.now() / 1000)) {
|
||||
|
||||
if (!options.skipValidation && 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.skipValidation && payload.exp && payload.exp <= Math.floor(Date.now() / 1000)) {
|
||||
if (options.throwError)
|
||||
throw 'EXPIRED'
|
||||
|
||||
return false
|
||||
}
|
||||
let keyFormat = 'raw'
|
||||
let keyData
|
||||
if (secret.startsWith('-----BEGIN')) {
|
||||
|
||||
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]}`))
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user