From f51260bc2fe1b6d3c7a305d7ccbe5cc162daa9be Mon Sep 17 00:00:00 2001 From: Pinta365 Date: Sun, 28 Apr 2024 22:50:33 +0200 Subject: [PATCH] unsafeParseJWT function --- README.md | 7 +++++++ deno.jsonc | 2 +- mod.ts | 2 +- src/error.ts | 13 +++++++++++++ src/validate.ts | 18 ++++++++++++++++++ 5 files changed, 40 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 74df95d..59429ec 100644 --- a/README.md +++ b/README.md @@ -72,6 +72,13 @@ const data = await validateJWT(jwt, cryptoKey); const data = await validateJWT(jwt, false); ``` +- **`unsafeParseJWT(jwt: string): Promise`** + +```javascript +// "unsafely" parse a JWT without cryptokey, will return the payload. +const unsafeData = unsafeParseJWT(jwt); +``` + **Helper Functions** - **`generateKey(keyStr: string, optionsOrAlgorithm?: SupportedKeyAlgorithms | Options): Promise`** diff --git a/deno.jsonc b/deno.jsonc index f00294d..22cba11 100644 --- a/deno.jsonc +++ b/deno.jsonc @@ -1,6 +1,6 @@ { "name": "@cross/jwt", - "version": "0.4.2", + "version": "0.4.3", "exports": "./mod.ts", "tasks": { diff --git a/mod.ts b/mod.ts index c0796d0..9a7063b 100644 --- a/mod.ts +++ b/mod.ts @@ -1,6 +1,6 @@ // mod.ts export { signJWT } from "./src/sign.ts"; -export { validateJWT } from "./src/validate.ts"; +export { unsafeParseJWT, validateJWT } from "./src/validate.ts"; export { exportPEMKey, generateKey, generateKeyPair, importPEMKey } from "./src/cryptokeys.ts"; export type { GenerateKeyOptions, diff --git a/src/error.ts b/src/error.ts index d664882..3bbd329 100644 --- a/src/error.ts +++ b/src/error.ts @@ -97,3 +97,16 @@ export class JWTRequiredOptionMissingError extends JWTFormatError { this.name = "JWTRequiredOptionMissingError"; } } + +/** + * Represents a parsing error that occurred during JWT parsing. + */ +export class JWTParseError extends Error { + /** + * @param {string} message - A descriptive message about the parsing failure. + */ + constructor(message: string) { + super(message); + this.name = "JWTParseError"; + } +} diff --git a/src/validate.ts b/src/validate.ts index 52e1e25..bb4686d 100644 --- a/src/validate.ts +++ b/src/validate.ts @@ -5,6 +5,7 @@ import { JWTExpiredError, JWTFormatError, JWTNotYetValidError, + JWTParseError, JWTRequiredClaimMissingError, JWTUnsupportedAlgorithmError, JWTValidationError, @@ -237,3 +238,20 @@ export async function verify(key: CryptoKey, data: string, signature: string, op throw new Error("Unsupported algorithm"); } } + +/** + * Validates and parses a JWT, verifying it with the given key. + * + * @param {string} jwt - The encoded JWT string. + * @returns {Promise} A promise resolving to the decoded JWT payload. + * @throws {JWTParseError} If the jwt string is not parsable. + */ +export function unsafeParseJWT(jwt: string): Promise { + try { + const jwtParts = validateParts(jwt); + const payload = JSON.parse(textDecode(decodeBase64Url(jwtParts[1]))); + return payload; + } catch (error) { + throw new JWTParseError(error); + } +}