Compare commits
10 Commits
v2.2.9
...
72e64f1316
| Author | SHA1 | Date | |
|---|---|---|---|
|
72e64f1316
|
|||
|
e235d835aa
|
|||
|
03c66f4223
|
|||
|
70488a6a48
|
|||
|
760245d1c7
|
|||
|
d40d924176
|
|||
|
c2e4fccf56
|
|||
|
0c0919f78d
|
|||
|
7299ea0614
|
|||
|
7004cd16ed
|
4
package-lock.json
generated
4
package-lock.json
generated
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "@tsndr/cloudflare-worker-jwt",
|
||||
"version": "2.2.9",
|
||||
"version": "2.3.2",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "@tsndr/cloudflare-worker-jwt",
|
||||
"version": "2.2.9",
|
||||
"version": "2.3.2",
|
||||
"license": "MIT",
|
||||
"devDependencies": {
|
||||
"@cloudflare/workers-types": "^4.20231025.0",
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
{
|
||||
"name": "@tsndr/cloudflare-worker-jwt",
|
||||
"version": "2.2.9",
|
||||
"version": "2.3.2",
|
||||
"description": "A lightweight JWT implementation with ZERO dependencies for Cloudflare Worker",
|
||||
"main": "index.js",
|
||||
"type": "module",
|
||||
"exports": "./index.js",
|
||||
"types": "index.d.ts",
|
||||
"engine": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "tsc",
|
||||
"test": "jest"
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
|
||||
import crypto from 'node:crypto'
|
||||
Object.defineProperty(global, 'crypto', { value: { subtle: crypto.webcrypto.subtle }})
|
||||
|
||||
@@ -15,6 +14,11 @@ type Data = {
|
||||
[key in JwtAlgorithm]: Dataset
|
||||
}
|
||||
|
||||
type Payload = {
|
||||
sub: string
|
||||
name: string
|
||||
}
|
||||
|
||||
const data: Data = {
|
||||
'ES256': {
|
||||
public: '-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEEVs/o5+uQbTjL3chynL4wXgUg2R9\nq9UU8I5mEovUf86QZ7kOBIjJwqnzD1omageEHWwHdBO6B+dFabmdT9POxg==\n-----END PUBLIC KEY-----',
|
||||
@@ -64,7 +68,7 @@ const data: Data = {
|
||||
|
||||
}
|
||||
|
||||
const payload = {
|
||||
const payload: Payload = {
|
||||
sub: "1234567890",
|
||||
name: "John Doe",
|
||||
}
|
||||
@@ -78,18 +82,18 @@ describe.each(Object.entries(data) as [JwtAlgorithm, Dataset][])('%s', (algorith
|
||||
})
|
||||
|
||||
test('decode external', async () => {
|
||||
const decoded = jwt.decode(data.token)
|
||||
const decoded = jwt.decode<Payload>(data.token)
|
||||
expect({
|
||||
sub: payload.sub,
|
||||
name: payload.name
|
||||
}).toMatchObject({
|
||||
sub: decoded.payload.sub,
|
||||
sub: decoded.payload?.sub,
|
||||
name: payload.name
|
||||
})
|
||||
})
|
||||
|
||||
test('sign internal', async () => {
|
||||
token = await jwt.sign(payload, data.private, algorithm)
|
||||
token = await jwt.sign<Payload>(payload, data.private, algorithm)
|
||||
expect(token).toMatch(/^[a-zA-Z0-9\-_]+\.[a-zA-Z0-9\-_]+\.[a-zA-Z0-9\-_]+$/)
|
||||
})
|
||||
|
||||
@@ -99,7 +103,7 @@ describe.each(Object.entries(data) as [JwtAlgorithm, Dataset][])('%s', (algorith
|
||||
sub: payload.sub,
|
||||
name: payload.name
|
||||
}).toMatchObject({
|
||||
sub: decoded.payload.sub,
|
||||
sub: decoded.payload?.sub,
|
||||
name: payload.name
|
||||
})
|
||||
})
|
||||
|
||||
166
src/index.ts
166
src/index.ts
@@ -10,7 +10,7 @@ export type JwtAlgorithm = 'ES256'|'ES384'|'ES512'|'HS256'|'HS384'|'HS512'|'RS25
|
||||
/**
|
||||
* @typedef JwtAlgorithms
|
||||
*/
|
||||
export interface JwtAlgorithms {
|
||||
export type JwtAlgorithms = {
|
||||
[key: string]: SubtleCryptoImportKeyAlgorithm
|
||||
}
|
||||
|
||||
@@ -18,16 +18,14 @@ export interface JwtAlgorithms {
|
||||
* @typedef JwtHeader
|
||||
* @prop {string} [typ] Type
|
||||
*/
|
||||
export interface JwtHeader {
|
||||
export type JwtHeader<T = {}> = {
|
||||
/**
|
||||
* Type (default: `"JWT"`)
|
||||
*
|
||||
* @default "JWT"
|
||||
*/
|
||||
typ?: string
|
||||
|
||||
[key: string]: any
|
||||
}
|
||||
} & T
|
||||
|
||||
/**
|
||||
* @typedef JwtPayload
|
||||
@@ -39,7 +37,7 @@ export interface JwtHeader {
|
||||
* @prop {string} [iat] Issued At
|
||||
* @prop {string} [jti] JWT ID
|
||||
*/
|
||||
export interface JwtPayload {
|
||||
export type JwtPayload<T = {}> = {
|
||||
/** Issuer */
|
||||
iss?: string
|
||||
|
||||
@@ -62,13 +60,13 @@ export interface JwtPayload {
|
||||
jti?: string
|
||||
|
||||
[key: string]: any
|
||||
}
|
||||
} & T
|
||||
|
||||
/**
|
||||
* @typedef JwtOptions
|
||||
* @prop {JwtAlgorithm | string} algorithm
|
||||
*/
|
||||
export interface JwtOptions {
|
||||
export type JwtOptions = {
|
||||
algorithm?: JwtAlgorithm | string
|
||||
}
|
||||
|
||||
@@ -77,37 +75,32 @@ export interface JwtOptions {
|
||||
* @extends JwtOptions
|
||||
* @prop {JwtHeader} [header]
|
||||
*/
|
||||
export interface JwtSignOptions extends JwtOptions {
|
||||
export type JwtSignOptions = {
|
||||
header?: JwtHeader
|
||||
}
|
||||
} & JwtOptions
|
||||
|
||||
/**
|
||||
* @typedef JwtVerifyOptions
|
||||
* @extends JwtOptions
|
||||
* @prop {boolean} [throwError=false] If `true` throw error if checks fail. (default: `false`)
|
||||
*/
|
||||
export interface JwtVerifyOptions extends JwtOptions {
|
||||
/**
|
||||
* If `true` all expiry checks will be skipped
|
||||
*/
|
||||
skipValidation?: boolean
|
||||
|
||||
export type JwtVerifyOptions = {
|
||||
/**
|
||||
* If `true` throw error if checks fail. (default: `false`)
|
||||
*
|
||||
* @default false
|
||||
*/
|
||||
throwError?: boolean
|
||||
}
|
||||
} & JwtOptions
|
||||
|
||||
/**
|
||||
* @typedef JwtData
|
||||
* @prop {JwtHeader} header
|
||||
* @prop {JwtPayload} payload
|
||||
*/
|
||||
export interface JwtData {
|
||||
header: JwtHeader
|
||||
payload: JwtPayload
|
||||
export type JwtData<Payload = {}, Header = {}> = {
|
||||
header?: JwtHeader<Header>
|
||||
payload?: JwtPayload<Payload>
|
||||
}
|
||||
|
||||
const algorithms: JwtAlgorithms = {
|
||||
@@ -203,77 +196,14 @@ async function importKey(key: string | JsonWebKey, algorithm: SubtleCryptoImport
|
||||
return importTextSecret(key, algorithm)
|
||||
}
|
||||
|
||||
function decodePayload(raw: string): JwtHeader | JwtPayload | null {
|
||||
function decodePayload<T = any>(raw: string): T | undefined {
|
||||
try {
|
||||
raw += '='.repeat(4-(raw.length % 4))
|
||||
return JSON.parse(atob(raw))
|
||||
} catch {
|
||||
return null
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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', skipValidation: false, throwError: false }): Promise<boolean> {
|
||||
if (typeof options === 'string')
|
||||
options = { algorithm: options, throwError: false }
|
||||
|
||||
options = { algorithm: 'HS256', skipValidation: false, 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 (!options.skipValidation && !payload) {
|
||||
if (options.throwError)
|
||||
throw 'PARSE_ERROR'
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
if (!options.skipValidation && payload.nbf && payload.nbf > Math.floor(Date.now() / 1000)) {
|
||||
if (options.throwError)
|
||||
throw 'NOT_YET_VALID'
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
if (!options.skipValidation && payload.exp && payload.exp <= Math.floor(Date.now() / 1000)) {
|
||||
if (options.throwError)
|
||||
throw 'EXPIRED'
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
const key = await importKey(secret, algorithm)
|
||||
|
||||
return await crypto.subtle.verify(algorithm, key, base64UrlToArrayBuffer(tokenParts[2]), textToArrayBuffer(`${tokenParts[0]}.${tokenParts[1]}`))
|
||||
}
|
||||
|
||||
/**
|
||||
* Signs a payload and returns the token
|
||||
*
|
||||
@@ -283,9 +213,10 @@ export async function verify(token: string, secret: string | JsonWebKey, options
|
||||
* @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 = 'HS256'): Promise<string> {
|
||||
export async function sign<Payload = {}>(payload: JwtPayload<Payload>, secret: string | JsonWebKey, options: JwtSignOptions | JwtAlgorithm = 'HS256'): Promise<string> {
|
||||
if (typeof options === 'string')
|
||||
options = { algorithm: options }
|
||||
|
||||
options = { algorithm: 'HS256', header: { typ: 'JWT' }, ...options }
|
||||
|
||||
if (!payload || typeof payload !== 'object')
|
||||
@@ -313,16 +244,73 @@ export async function sign(payload: JwtPayload, secret: string | JsonWebKey, opt
|
||||
return `${partialToken}.${arrayBufferToBase64Url(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)
|
||||
|
||||
try {
|
||||
if (!payload)
|
||||
throw new Error('PARSE_ERROR')
|
||||
|
||||
if (payload.nbf && payload.nbf > Math.floor(Date.now() / 1000))
|
||||
throw new Error('NOT_YET_VALID')
|
||||
|
||||
if (payload.exp && payload.exp <= Math.floor(Date.now() / 1000))
|
||||
throw new Error('EXPIRED')
|
||||
|
||||
const key = await importKey(secret, algorithm)
|
||||
|
||||
return await crypto.subtle.verify(algorithm, key, base64UrlToArrayBuffer(tokenParts[2]), textToArrayBuffer(`${tokenParts[0]}.${tokenParts[1]}`))
|
||||
} catch(err) {
|
||||
if (options.throwError)
|
||||
throw err
|
||||
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 {
|
||||
export function decode<Payload = {}, Header = {}>(token: string): JwtData<Payload, Header> {
|
||||
return {
|
||||
header: decodePayload(token.split('.')[0].replace(/-/g, '+').replace(/_/g, '/')) as JwtHeader,
|
||||
payload: decodePayload(token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/')) as JwtPayload
|
||||
header: decodePayload<JwtHeader<Header>>(token.split('.')[0].replace(/-/g, '+').replace(/_/g, '/')),
|
||||
payload: decodePayload<JwtPayload<Payload>>(token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/'))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user