From b05345279dc0c2a70fc37e3cc98f561ea3fcf83c Mon Sep 17 00:00:00 2001 From: Leo Developer Date: Tue, 19 Dec 2023 12:58:21 +0100 Subject: [PATCH] allow using cryptokey directly --- src/index.ts | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/index.ts b/src/index.ts index 7551316..8785a73 100644 --- a/src/index.ts +++ b/src/index.ts @@ -211,7 +211,7 @@ function decodePayload(raw: string): T | undefined { * 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 | JsonWebKey} secret A string which is used to sign the payload. + * @param {string | JsonWebKey | CryptoKey} 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} Returns token as a `string`. @@ -226,7 +226,7 @@ export async function sign(payload: JwtPayload(payload: JwtPayload(payload: JwtPayload} 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 { +export async function verify(token: string, secret: string | JsonWebKey | CryptoKey, options: JwtVerifyOptions | JwtAlgorithm = { algorithm: 'HS256', throwError: false }): Promise { if (typeof options === 'string') options = { algorithm: options, throwError: false } @@ -266,7 +266,7 @@ export async function verify(token: string, secret: string | JsonWebKey, options 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') + throw new Error('secret must be a string, a JWK object or a CryptoKey object') if (typeof options.algorithm !== 'string') throw new Error('options.algorithm must be a string') @@ -293,7 +293,7 @@ export async function verify(token: string, secret: string | JsonWebKey, options if (payload.exp && payload.exp <= Math.floor(Date.now() / 1000)) throw new Error('EXPIRED') - const key = await importKey(secret, algorithm) + const key = secret instanceof CryptoKey ? secret : await importKey(secret, algorithm) return await crypto.subtle.verify(algorithm, key, base64UrlToArrayBuffer(tokenParts[2]), textToArrayBuffer(`${tokenParts[0]}.${tokenParts[1]}`)) } catch(err) { @@ -321,4 +321,4 @@ export default { sign, verify, decode -} +} \ No newline at end of file