|
|
|
@@ -5,12 +5,12 @@ if (typeof crypto === 'undefined' || !crypto.subtle)
|
|
|
|
* @typedef JwtAlgorithm
|
|
|
|
* @typedef JwtAlgorithm
|
|
|
|
* @type {'ES256'|'ES384'|'ES512'|'HS256'|'HS384'|'HS512'|'RS256'|'RS384'|'RS512'}
|
|
|
|
* @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
|
|
|
|
* @typedef JwtAlgorithms
|
|
|
|
*/
|
|
|
|
*/
|
|
|
|
interface JwtAlgorithms {
|
|
|
|
export interface JwtAlgorithms {
|
|
|
|
[key: string]: SubtleCryptoImportKeyAlgorithm
|
|
|
|
[key: string]: SubtleCryptoImportKeyAlgorithm
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
@@ -18,7 +18,7 @@ interface JwtAlgorithms {
|
|
|
|
* @typedef JwtHeader
|
|
|
|
* @typedef JwtHeader
|
|
|
|
* @prop {string} [typ] Type
|
|
|
|
* @prop {string} [typ] Type
|
|
|
|
*/
|
|
|
|
*/
|
|
|
|
interface JwtHeader {
|
|
|
|
export interface JwtHeader {
|
|
|
|
/**
|
|
|
|
/**
|
|
|
|
* Type (default: `"JWT"`)
|
|
|
|
* Type (default: `"JWT"`)
|
|
|
|
*
|
|
|
|
*
|
|
|
|
@@ -39,7 +39,7 @@ interface JwtHeader {
|
|
|
|
* @prop {string} [iat] Issued At
|
|
|
|
* @prop {string} [iat] Issued At
|
|
|
|
* @prop {string} [jti] JWT ID
|
|
|
|
* @prop {string} [jti] JWT ID
|
|
|
|
*/
|
|
|
|
*/
|
|
|
|
interface JwtPayload {
|
|
|
|
export interface JwtPayload {
|
|
|
|
/** Issuer */
|
|
|
|
/** Issuer */
|
|
|
|
iss?: string
|
|
|
|
iss?: string
|
|
|
|
|
|
|
|
|
|
|
|
@@ -68,7 +68,7 @@ interface JwtPayload {
|
|
|
|
* @typedef JwtOptions
|
|
|
|
* @typedef JwtOptions
|
|
|
|
* @prop {JwtAlgorithm | string} algorithm
|
|
|
|
* @prop {JwtAlgorithm | string} algorithm
|
|
|
|
*/
|
|
|
|
*/
|
|
|
|
interface JwtOptions {
|
|
|
|
export interface JwtOptions {
|
|
|
|
algorithm?: JwtAlgorithm | string
|
|
|
|
algorithm?: JwtAlgorithm | string
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
@@ -77,7 +77,7 @@ interface JwtOptions {
|
|
|
|
* @extends JwtOptions
|
|
|
|
* @extends JwtOptions
|
|
|
|
* @prop {JwtHeader} [header]
|
|
|
|
* @prop {JwtHeader} [header]
|
|
|
|
*/
|
|
|
|
*/
|
|
|
|
interface JwtSignOptions extends JwtOptions {
|
|
|
|
export interface JwtSignOptions extends JwtOptions {
|
|
|
|
header?: JwtHeader
|
|
|
|
header?: JwtHeader
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
@@ -86,7 +86,7 @@ interface JwtSignOptions extends JwtOptions {
|
|
|
|
* @extends JwtOptions
|
|
|
|
* @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`)
|
|
|
|
*/
|
|
|
|
*/
|
|
|
|
interface JwtVerifyOptions extends JwtOptions {
|
|
|
|
export interface JwtVerifyOptions extends JwtOptions {
|
|
|
|
/**
|
|
|
|
/**
|
|
|
|
* If `true` throw error if checks fail. (default: `false`)
|
|
|
|
* If `true` throw error if checks fail. (default: `false`)
|
|
|
|
*
|
|
|
|
*
|
|
|
|
@@ -100,7 +100,7 @@ interface JwtVerifyOptions extends JwtOptions {
|
|
|
|
* @prop {JwtHeader} header
|
|
|
|
* @prop {JwtHeader} header
|
|
|
|
* @prop {JwtPayload} payload
|
|
|
|
* @prop {JwtPayload} payload
|
|
|
|
*/
|
|
|
|
*/
|
|
|
|
interface JwtData {
|
|
|
|
export interface JwtData {
|
|
|
|
header: JwtHeader
|
|
|
|
header: JwtHeader
|
|
|
|
payload: JwtPayload
|
|
|
|
payload: JwtPayload
|
|
|
|
}
|
|
|
|
}
|
|
|
|
@@ -129,17 +129,31 @@ const algorithms: JwtAlgorithms = {
|
|
|
|
RS512: { name: 'RSASSA-PKCS1-v1_5', hash: { name: 'SHA-512' } }
|
|
|
|
RS512: { name: 'RSASSA-PKCS1-v1_5', hash: { name: 'SHA-512' } }
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
function _parseSecret(secret: string): { raw: boolean, key: ArrayBuffer } {
|
|
|
|
|
|
|
|
if (secret.startsWith('-----BEGIN'))
|
|
|
|
|
|
|
|
return { raw: false, key: _str2ab(secret.replace(/-----BEGIN.*?-----/g, '').replace(/-----END.*?-----/g, '').replace(/\s/g, '')) }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
// Check for Base64
|
|
|
|
|
|
|
|
if (/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/.test(secret))
|
|
|
|
|
|
|
|
return { raw: true, key: base64UrlParse(secret) }
|
|
|
|
|
|
|
|
else
|
|
|
|
|
|
|
|
return { raw: true, key: _utf8ToUint8Array(secret) }
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
function _utf8ToUint8Array(str: string): Uint8Array {
|
|
|
|
function _utf8ToUint8Array(str: string): Uint8Array {
|
|
|
|
return base64UrlParse(btoa(unescape(encodeURIComponent(str))))
|
|
|
|
return base64UrlParse(btoa(unescape(encodeURIComponent(str))))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
function _str2ab(str: string): ArrayBuffer {
|
|
|
|
function _str2ab(str: string): ArrayBuffer {
|
|
|
|
str = atob(str)
|
|
|
|
str = atob(str)
|
|
|
|
|
|
|
|
|
|
|
|
const buf = new ArrayBuffer(str.length);
|
|
|
|
const buf = new ArrayBuffer(str.length);
|
|
|
|
const bufView = new Uint8Array(buf);
|
|
|
|
const bufView = new Uint8Array(buf);
|
|
|
|
|
|
|
|
|
|
|
|
for (let i = 0, strLen = str.length; i < strLen; i++) {
|
|
|
|
for (let i = 0, strLen = str.length; i < strLen; i++) {
|
|
|
|
bufView[i] = str.charCodeAt(i);
|
|
|
|
bufView[i] = str.charCodeAt(i);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
return buf;
|
|
|
|
return buf;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
@@ -156,6 +170,7 @@ function _decodePayload(raw: string): JwtHeader | JwtPayload | null {
|
|
|
|
default:
|
|
|
|
default:
|
|
|
|
throw new Error('Illegal base64url string!')
|
|
|
|
throw new Error('Illegal base64url string!')
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
try {
|
|
|
|
try {
|
|
|
|
return JSON.parse(decodeURIComponent(escape(atob(raw))))
|
|
|
|
return JSON.parse(decodeURIComponent(escape(atob(raw))))
|
|
|
|
} catch {
|
|
|
|
} catch {
|
|
|
|
@@ -175,28 +190,32 @@ function _decodePayload(raw: string): JwtHeader | JwtPayload | null {
|
|
|
|
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, 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' } }
|
|
|
|
|
|
|
|
|
|
|
|
options = { algorithm: 'HS256', header: { typ: 'JWT' }, ...options }
|
|
|
|
options = { algorithm: 'HS256', header: { typ: 'JWT' }, ...options }
|
|
|
|
|
|
|
|
|
|
|
|
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')
|
|
|
|
throw new Error('secret must be a string')
|
|
|
|
throw new Error('secret must be a string')
|
|
|
|
|
|
|
|
|
|
|
|
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')
|
|
|
|
|
|
|
|
|
|
|
|
const algorithm: SubtleCryptoImportKeyAlgorithm = algorithms[options.algorithm]
|
|
|
|
const algorithm: SubtleCryptoImportKeyAlgorithm = algorithms[options.algorithm]
|
|
|
|
|
|
|
|
|
|
|
|
if (!algorithm)
|
|
|
|
if (!algorithm)
|
|
|
|
throw new Error('algorithm not found')
|
|
|
|
throw new Error('algorithm not found')
|
|
|
|
|
|
|
|
|
|
|
|
payload.iat = Math.floor(Date.now() / 1000)
|
|
|
|
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'
|
|
|
|
const parsedSecret = _parseSecret(secret)
|
|
|
|
let keyData
|
|
|
|
|
|
|
|
if (secret.startsWith('-----BEGIN')) {
|
|
|
|
const key = await crypto.subtle.importKey(parsedSecret.raw ? 'raw' : 'pkcs8', parsedSecret.key, algorithm, false, ['sign'])
|
|
|
|
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))
|
|
|
|
const signature = await crypto.subtle.sign(algorithm, key, _utf8ToUint8Array(partialToken))
|
|
|
|
|
|
|
|
|
|
|
|
return `${partialToken}.${base64UrlStringify(new Uint8Array(signature))}`
|
|
|
|
return `${partialToken}.${base64UrlStringify(new Uint8Array(signature))}`
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
@@ -212,44 +231,55 @@ export async function sign(payload: JwtPayload, secret: string, options: JwtSign
|
|
|
|
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, options: JwtVerifyOptions | JwtAlgorithm = { algorithm: 'HS256', 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', 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')
|
|
|
|
throw new Error('secret must be a string')
|
|
|
|
throw new Error('secret must be a string')
|
|
|
|
|
|
|
|
|
|
|
|
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')
|
|
|
|
|
|
|
|
|
|
|
|
const tokenParts = token.split('.')
|
|
|
|
const tokenParts = token.split('.')
|
|
|
|
|
|
|
|
|
|
|
|
if (tokenParts.length !== 3)
|
|
|
|
if (tokenParts.length !== 3)
|
|
|
|
throw new Error('token must consist of 3 parts')
|
|
|
|
throw new Error('token must consist of 3 parts')
|
|
|
|
|
|
|
|
|
|
|
|
const algorithm: SubtleCryptoImportKeyAlgorithm = algorithms[options.algorithm]
|
|
|
|
const algorithm: SubtleCryptoImportKeyAlgorithm = algorithms[options.algorithm]
|
|
|
|
|
|
|
|
|
|
|
|
if (!algorithm)
|
|
|
|
if (!algorithm)
|
|
|
|
throw new Error('algorithm not found')
|
|
|
|
throw new Error('algorithm not found')
|
|
|
|
|
|
|
|
|
|
|
|
const { payload } = decode(token)
|
|
|
|
const { payload } = decode(token)
|
|
|
|
|
|
|
|
|
|
|
|
if (!payload) {
|
|
|
|
if (!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 (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 (payload.exp && payload.exp <= Math.floor(Date.now() / 1000)) {
|
|
|
|
if (options.throwError)
|
|
|
|
if (options.throwError)
|
|
|
|
throw 'EXPIRED'
|
|
|
|
throw 'EXPIRED'
|
|
|
|
|
|
|
|
|
|
|
|
return false
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
let keyFormat = 'raw'
|
|
|
|
|
|
|
|
let keyData
|
|
|
|
const parsedSecret = _parseSecret(secret)
|
|
|
|
if (secret.startsWith('-----BEGIN')) {
|
|
|
|
const key = await crypto.subtle.importKey(parsedSecret.raw ? 'raw' : 'spki', parsedSecret.key, algorithm, false, ['verify'])
|
|
|
|
keyFormat = 'spki'
|
|
|
|
|
|
|
|
keyData = _str2ab(secret.replace(/-----BEGIN.*?-----/g, '').replace(/-----END.*?-----/g, '').replace(/\s/g, ''))
|
|
|
|
return crypto.subtle.verify(algorithm, key, base64UrlParse(tokenParts[2]), _utf8ToUint8Array(`${tokenParts[0]}.${tokenParts[1]}`))
|
|
|
|
} 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]}`))
|
|
|
|
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
/**
|
|
|
|
|