|
|
|
|
@@ -87,11 +87,6 @@ export interface JwtSignOptions 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
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* If `true` throw error if checks fail. (default: `false`)
|
|
|
|
|
*
|
|
|
|
|
@@ -106,20 +101,8 @@ export interface JwtVerifyOptions extends JwtOptions {
|
|
|
|
|
* @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, '_')
|
|
|
|
|
header?: JwtHeader
|
|
|
|
|
payload?: JwtPayload
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const algorithms: JwtAlgorithms = {
|
|
|
|
|
@@ -134,41 +117,92 @@ const algorithms: JwtAlgorithms = {
|
|
|
|
|
RS512: { name: 'RSASSA-PKCS1-v1_5', hash: { name: 'SHA-512' } }
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function _utf8ToUint8Array(str: string): Uint8Array {
|
|
|
|
|
return base64UrlParse(btoa(unescape(encodeURIComponent(str))))
|
|
|
|
|
function bytesToByteString(bytes: Uint8Array): string {
|
|
|
|
|
let byteStr = ''
|
|
|
|
|
for (let i = 0; i < bytes.byteLength; i++) {
|
|
|
|
|
byteStr += String.fromCharCode(bytes[i])
|
|
|
|
|
}
|
|
|
|
|
return byteStr
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
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);
|
|
|
|
|
function byteStringToBytes(byteStr: string): Uint8Array {
|
|
|
|
|
let bytes = new Uint8Array(byteStr.length)
|
|
|
|
|
for (let i = 0; i < byteStr.length; i++) {
|
|
|
|
|
bytes[i] = byteStr.charCodeAt(i)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return buf;
|
|
|
|
|
return bytes
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
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!')
|
|
|
|
|
}
|
|
|
|
|
function arrayBufferToBase64String(arrayBuffer: ArrayBuffer): string {
|
|
|
|
|
return btoa(bytesToByteString(new Uint8Array(arrayBuffer)))
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function base64StringToArrayBuffer(b64str: string): ArrayBuffer {
|
|
|
|
|
return byteStringToBytes(atob(b64str)).buffer
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function textToArrayBuffer(str: string): ArrayBuffer {
|
|
|
|
|
return byteStringToBytes(decodeURI(encodeURIComponent(str)))
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// @ts-ignore
|
|
|
|
|
function arrayBufferToText(arrayBuffer: ArrayBuffer): string {
|
|
|
|
|
return bytesToByteString(new Uint8Array(arrayBuffer))
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function arrayBufferToBase64Url(arrayBuffer: ArrayBuffer): string {
|
|
|
|
|
return arrayBufferToBase64String(arrayBuffer).replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_')
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function base64UrlToArrayBuffer(b64url: string): ArrayBuffer {
|
|
|
|
|
return base64StringToArrayBuffer(b64url.replace(/-/g, '+').replace(/_/g, '/').replace(/\s/g, ''))
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function textToBase64Url(str: string): string {
|
|
|
|
|
return btoa(str).replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_')
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function pemToBinary(pem: string): ArrayBuffer {
|
|
|
|
|
return base64StringToArrayBuffer(pem.replace(/-+(BEGIN|END).*/g, '').replace(/\s/g, ''))
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async function importTextSecret(key: string, algorithm: SubtleCryptoImportKeyAlgorithm): Promise<CryptoKey> {
|
|
|
|
|
return await crypto.subtle.importKey("raw", textToArrayBuffer(key), algorithm, true, ["verify", "sign"])
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async function importJwk(key: JsonWebKey, algorithm: SubtleCryptoImportKeyAlgorithm): Promise<CryptoKey> {
|
|
|
|
|
return await crypto.subtle.importKey("jwk", key, algorithm, true, ["verify", "sign"])
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async function importPublicKey(key: string, algorithm: SubtleCryptoImportKeyAlgorithm): Promise<CryptoKey> {
|
|
|
|
|
return await crypto.subtle.importKey("spki", pemToBinary(key), algorithm, true, ["verify"])
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async function importPrivateKey(key: string, algorithm: SubtleCryptoImportKeyAlgorithm): Promise<CryptoKey> {
|
|
|
|
|
return await crypto.subtle.importKey("pkcs8", pemToBinary(key), algorithm, true, ["sign"])
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async function importKey(key: string | JsonWebKey, algorithm: SubtleCryptoImportKeyAlgorithm): Promise<CryptoKey> {
|
|
|
|
|
if (typeof key === 'object')
|
|
|
|
|
return importJwk(key, algorithm)
|
|
|
|
|
|
|
|
|
|
if (typeof key !== 'string')
|
|
|
|
|
throw new Error('Unsupported key type!')
|
|
|
|
|
|
|
|
|
|
if (key.includes('PUBLIC'))
|
|
|
|
|
return importPublicKey(key, algorithm)
|
|
|
|
|
|
|
|
|
|
if (key.includes('PRIVATE'))
|
|
|
|
|
return importPrivateKey(key, algorithm)
|
|
|
|
|
|
|
|
|
|
return importTextSecret(key, algorithm)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function decodePayload<T = any>(raw: string): T | undefined {
|
|
|
|
|
try {
|
|
|
|
|
return JSON.parse(decodeURIComponent(escape(atob(raw))))
|
|
|
|
|
return JSON.parse(atob(raw))
|
|
|
|
|
} catch {
|
|
|
|
|
return null
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
@@ -181,16 +215,16 @@ function _decodePayload(raw: string): JwtHeader | JwtPayload | null {
|
|
|
|
|
* @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> {
|
|
|
|
|
export async function sign(payload: JwtPayload, secret: string | JsonWebKey, options: JwtSignOptions | JwtAlgorithm = 'HS256'): Promise<string> {
|
|
|
|
|
if (typeof options === 'string')
|
|
|
|
|
options = { algorithm: options, header: { typ: 'JWT' } }
|
|
|
|
|
options = { algorithm: options }
|
|
|
|
|
|
|
|
|
|
options = { algorithm: 'HS256', header: { typ: 'JWT' }, ...options }
|
|
|
|
|
|
|
|
|
|
if (payload === null || typeof payload !== 'object')
|
|
|
|
|
if (!payload || typeof payload !== 'object')
|
|
|
|
|
throw new Error('payload must be an object')
|
|
|
|
|
|
|
|
|
|
if (typeof secret !== 'string' && typeof secret !== 'object')
|
|
|
|
|
if (!secret || (typeof secret !== 'string' && typeof secret !== 'object'))
|
|
|
|
|
throw new Error('secret must be a string or a JWK object')
|
|
|
|
|
|
|
|
|
|
if (typeof options.algorithm !== 'string')
|
|
|
|
|
@@ -204,25 +238,12 @@ export async function sign(payload: JwtPayload, secret: string | JsonWebKey, opt
|
|
|
|
|
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))}`
|
|
|
|
|
const partialToken = `${textToBase64Url(JSON.stringify({ ...options.header, alg: options.algorithm }))}.${textToBase64Url(JSON.stringify(payload))}`
|
|
|
|
|
|
|
|
|
|
let keyFormat = 'raw'
|
|
|
|
|
let keyData
|
|
|
|
|
const key = await importKey(secret, algorithm)
|
|
|
|
|
const signature = await crypto.subtle.sign(algorithm, key, textToArrayBuffer(partialToken))
|
|
|
|
|
|
|
|
|
|
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))}`
|
|
|
|
|
return `${partialToken}.${arrayBufferToBase64Url(signature)}`
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
@@ -234,11 +255,11 @@ export async function sign(payload: JwtPayload, secret: string | JsonWebKey, opt
|
|
|
|
|
* @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> {
|
|
|
|
|
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', skipValidation: false, throwError: false, ...options }
|
|
|
|
|
options = { algorithm: 'HS256', throwError: false, ...options }
|
|
|
|
|
|
|
|
|
|
if (typeof token !== 'string')
|
|
|
|
|
throw new Error('token must be a string')
|
|
|
|
|
@@ -261,41 +282,25 @@ export async function verify(token: string, secret: string | JsonWebKey, options
|
|
|
|
|
|
|
|
|
|
const { payload } = decode(token)
|
|
|
|
|
|
|
|
|
|
if (!options.skipValidation && !payload) {
|
|
|
|
|
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 'PARSE_ERROR'
|
|
|
|
|
throw err
|
|
|
|
|
|
|
|
|
|
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
|
|
|
|
|
}
|
|
|
|
|
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]}`))
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
@@ -306,8 +311,8 @@ export async function verify(token: string, secret: string | JsonWebKey, options
|
|
|
|
|
*/
|
|
|
|
|
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
|
|
|
|
|
header: decodePayload<JwtHeader>(token.split('.')[0].replace(/-/g, '+').replace(/_/g, '/')),
|
|
|
|
|
payload: decodePayload<JwtPayload>(token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/'))
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|