1
0

Compare commits

..

19 Commits

Author SHA1 Message Date
1394e4e33d 2.2.3 2023-10-02 23:19:51 +02:00
47028970b4 update readme 2023-10-02 23:18:05 +02:00
6ac43d493d add skipValidation option for verify 2023-10-02 23:10:45 +02:00
cc66bd9c47 add .editorconfig 2023-10-02 23:10:20 +02:00
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
5 changed files with 66 additions and 38 deletions

10
.editorconfig Normal file
View 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

View File

@@ -16,7 +16,7 @@ A lightweight JWT implementation with ZERO dependencies for Cloudflare Workers.
## Install ## 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 #### 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. `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.
@@ -100,11 +100,11 @@ Returns token as a `string`.
Verifies the integrity of the token and returns a boolean value. 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()`. `token` | `string` | required | - | The token string generated by `jwt.sign()`.
`secret` | `string` | required | - | The string which was used to sign the payload. `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` #### `throws`
If `options.throwError` is `true` and the token is invalid, an error will be thrown. 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! 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()`. `token` | `string` | required | - | The token string generated by `jwt.sign()`.
@@ -147,4 +147,4 @@ Returns an `object` containing `header` and `payload`:
- HS512 - HS512
- RS256 - RS256
- RS384 - RS384
- RS512 - RS512

16
package-lock.json generated
View File

@@ -1,12 +1,12 @@
{ {
"name": "@tsndr/cloudflare-worker-jwt", "name": "@tsndr/cloudflare-worker-jwt",
"version": "2.1.1", "version": "2.2.3",
"lockfileVersion": 2, "lockfileVersion": 2,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "@tsndr/cloudflare-worker-jwt", "name": "@tsndr/cloudflare-worker-jwt",
"version": "2.1.1", "version": "2.2.3",
"license": "MIT", "license": "MIT",
"devDependencies": { "devDependencies": {
"@cloudflare/workers-types": "^3.13.0", "@cloudflare/workers-types": "^3.13.0",
@@ -2542,9 +2542,9 @@
"dev": true "dev": true
}, },
"node_modules/json5": { "node_modules/json5": {
"version": "2.2.1", "version": "2.2.3",
"resolved": "https://registry.npmjs.org/json5/-/json5-2.2.1.tgz", "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz",
"integrity": "sha512-1hqLFMSrGHRHxav9q9gNjJ5EXznIxGVO09xQRrwplcS8qs28pZ8s8hupZAmqDwZUmVZ2Qb2jnyPOWcDH8m8dlA==", "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==",
"dev": true, "dev": true,
"bin": { "bin": {
"json5": "lib/cli.js" "json5": "lib/cli.js"
@@ -5364,9 +5364,9 @@
"dev": true "dev": true
}, },
"json5": { "json5": {
"version": "2.2.1", "version": "2.2.3",
"resolved": "https://registry.npmjs.org/json5/-/json5-2.2.1.tgz", "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz",
"integrity": "sha512-1hqLFMSrGHRHxav9q9gNjJ5EXznIxGVO09xQRrwplcS8qs28pZ8s8hupZAmqDwZUmVZ2Qb2jnyPOWcDH8m8dlA==", "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==",
"dev": true "dev": true
}, },
"kleur": { "kleur": {

View File

@@ -1,6 +1,6 @@
{ {
"name": "@tsndr/cloudflare-worker-jwt", "name": "@tsndr/cloudflare-worker-jwt",
"version": "2.1.1", "version": "2.2.3",
"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",
"types": "index.d.ts", "types": "index.d.ts",

View File

@@ -21,7 +21,7 @@ export interface JwtAlgorithms {
export interface JwtHeader { export interface JwtHeader {
/** /**
* Type (default: `"JWT"`) * Type (default: `"JWT"`)
* *
* @default "JWT" * @default "JWT"
*/ */
typ?: string typ?: string
@@ -33,7 +33,7 @@ export interface JwtHeader {
* @typedef JwtPayload * @typedef JwtPayload
* @prop {string} [iss] Issuer * @prop {string} [iss] Issuer
* @prop {string} [sub] Subject * @prop {string} [sub] Subject
* @prop {string} [aud] Audience * @prop {string | string[]} [aud] Audience
* @prop {string} [exp] Expiration Time * @prop {string} [exp] Expiration Time
* @prop {string} [nbf] Not Before * @prop {string} [nbf] Not Before
* @prop {string} [iat] Issued At * @prop {string} [iat] Issued At
@@ -47,7 +47,7 @@ export interface JwtPayload {
sub?: string sub?: string
/** Audience */ /** Audience */
aud?: string aud?: string | string[]
/** Expiration Time */ /** Expiration Time */
exp?: number exp?: number
@@ -87,9 +87,14 @@ export interface JwtSignOptions extends JwtOptions {
* @prop {boolean} [throwError=false] If `true` throw error if checks fail. (default: `false`) * @prop {boolean} [throwError=false] If `true` throw error if checks fail. (default: `false`)
*/ */
export 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`) * If `true` throw error if checks fail. (default: `false`)
* *
* @default false * @default false
*/ */
throwError?: boolean throwError?: boolean
@@ -169,14 +174,14 @@ function _decodePayload(raw: string): JwtHeader | JwtPayload | null {
/** /**
* Signs a payload and returns the token * 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 {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. * @param {JwtSignOptions | JwtAlgorithm | string} [options={ algorithm: 'HS256', header: { typ: 'JWT' } }] The options object or the algorithm.
* @throws {Error} If there's a validation issue. * @throws {Error} If there's a validation issue.
* @returns {Promise<string>} Returns token as a `string`. * @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') if (typeof options === 'string')
options = { algorithm: options, header: { typ: 'JWT' } } options = { algorithm: options, header: { typ: 'JWT' } }
@@ -185,8 +190,8 @@ export async function sign(payload: JwtPayload, secret: string, options: JwtSign
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')
if (typeof secret !== 'string') if (typeof secret !== 'string' && typeof secret !== 'object')
throw new Error('secret must be a string') throw new Error('secret must be a string or a JWK object')
if (typeof options.algorithm !== 'string') if (typeof options.algorithm !== 'string')
throw new Error('options.algorithm must be a string') throw new Error('options.algorithm must be a string')
@@ -196,17 +201,24 @@ export async function sign(payload: JwtPayload, secret: string, options: JwtSign
if (!algorithm) if (!algorithm)
throw new Error('algorithm not found') throw new Error('algorithm not found')
payload.iat = Math.floor(Date.now() / 1000) if (!payload.iat)
payload.iat = Math.floor(Date.now() / 1000)
const payloadAsJSON = JSON.stringify(payload) const payloadAsJSON = JSON.stringify(payload)
const partialToken = `${base64UrlStringify(_utf8ToUint8Array(JSON.stringify({ ...options.header, alg: options.algorithm })))}.${base64UrlStringify(_utf8ToUint8Array(payloadAsJSON))}` const partialToken = `${base64UrlStringify(_utf8ToUint8Array(JSON.stringify({ ...options.header, alg: options.algorithm })))}.${base64UrlStringify(_utf8ToUint8Array(payloadAsJSON))}`
let keyFormat = 'raw' let keyFormat = 'raw'
let keyData let keyData
if (secret.startsWith('-----BEGIN')) {
if (typeof secret === 'object') {
keyFormat = 'jwk'
keyData = secret
} else if (typeof secret === 'string' && secret.startsWith('-----BEGIN')) {
keyFormat = 'pkcs8' keyFormat = 'pkcs8'
keyData = _str2ab(secret.replace(/-----BEGIN.*?-----/g, '').replace(/-----END.*?-----/g, '').replace(/\s/g, '')) keyData = _str2ab(secret.replace(/-----BEGIN.*?-----/g, '').replace(/-----END.*?-----/g, '').replace(/\s/g, ''))
} else } else
keyData = _utf8ToUint8Array(secret) keyData = _utf8ToUint8Array(secret)
const key = await crypto.subtle.importKey(keyFormat, keyData, algorithm, false, ['sign']) const key = await crypto.subtle.importKey(keyFormat, keyData, algorithm, false, ['sign'])
const signature = await crypto.subtle.sign(algorithm, key, _utf8ToUint8Array(partialToken)) const signature = await crypto.subtle.sign(algorithm, key, _utf8ToUint8Array(partialToken))
@@ -215,24 +227,24 @@ export async function sign(payload: JwtPayload, secret: string, options: JwtSign
/** /**
* Verifies the integrity of the token and returns a boolean value. * Verifies the integrity of the token and returns a boolean value.
* *
* @param {string} token The token string generated by `jwt.sign()`. * @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. * @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. * @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`. * @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') if (typeof options === 'string')
options = { algorithm: options, throwError: false } options = { algorithm: options, throwError: false }
options = { algorithm: 'HS256', throwError: false, ...options } options = { algorithm: 'HS256', skipValidation: false, throwError: false, ...options }
if (typeof token !== 'string') if (typeof token !== 'string')
throw new Error('token must be a string') throw new Error('token must be a string')
if (typeof secret !== 'string') if (typeof secret !== 'string' && typeof secret !== 'object')
throw new Error('secret must be a string') throw new Error('secret must be a string or a JWK object')
if (typeof options.algorithm !== 'string') if (typeof options.algorithm !== 'string')
throw new Error('options.algorithm must be a string') throw new Error('options.algorithm must be a string')
@@ -249,21 +261,21 @@ export async function verify(token: string, secret: string, options: JwtVerifyOp
const { payload } = decode(token) const { payload } = decode(token)
if (!payload) { if (!options.skipValidation && !payload) {
if (options.throwError) if (options.throwError)
throw 'PARSE_ERROR' throw 'PARSE_ERROR'
return false 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) if (options.throwError)
throw 'NOT_YET_VALID' throw 'NOT_YET_VALID'
return false 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) if (options.throwError)
throw 'EXPIRED' throw 'EXPIRED'
@@ -271,18 +283,24 @@ export async function verify(token: string, secret: string, options: JwtVerifyOp
} }
let keyFormat = 'raw' let keyFormat = 'raw'
let keyData let keyData
if (secret.startsWith('-----BEGIN')) {
if (typeof secret === 'object') {
keyFormat = 'jwk';
keyData = secret;
} else if (typeof secret === 'string' && secret.startsWith('-----BEGIN')) {
keyFormat = 'spki' keyFormat = 'spki'
keyData = _str2ab(secret.replace(/-----BEGIN.*?-----/g, '').replace(/-----END.*?-----/g, '').replace(/\s/g, '')) keyData = _str2ab(secret.replace(/-----BEGIN.*?-----/g, '').replace(/-----END.*?-----/g, '').replace(/\s/g, ''))
} else } else
keyData = _utf8ToUint8Array(secret) keyData = _utf8ToUint8Array(secret)
const key = await crypto.subtle.importKey(keyFormat, keyData, algorithm, false, ['verify']) 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]}`)) 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! * 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()`. * @param {string} token The token string generated by `jwt.sign()`.
* @returns {JwtData} Returns an `object` containing `header` and `payload`. * @returns {JwtData} Returns an `object` containing `header` and `payload`.
*/ */