UNPKG

@gaonengwww/jose

Version:

JWA, JWS, JWE, JWT, JWK, JWKS for Node.js, Browser, Cloudflare Workers, Deno, Bun, and other Web-interoperable runtimes

107 lines (101 loc) 2.98 kB
// src/lib/buffer_utils.ts var encoder = new TextEncoder(); var decoder = new TextDecoder(); var MAX_INT32 = 2 ** 32; // src/lib/base64.ts function decodeBase64(encoded) { if (Uint8Array.fromBase64) { return Uint8Array.fromBase64(encoded); } const binary = atob(encoded); const bytes = new Uint8Array(binary.length); for (let i = 0; i < binary.length; i++) { bytes[i] = binary.charCodeAt(i); } return bytes; } // src/util/base64url.ts function decode(input) { if (Uint8Array.fromBase64) { return Uint8Array.fromBase64(typeof input === "string" ? input : decoder.decode(input), { alphabet: "base64url" }); } let encoded = input; if (encoded instanceof Uint8Array) { encoded = decoder.decode(encoded); } encoded = encoded.replace(/-/g, "+").replace(/_/g, "/").replace(/\s/g, ""); try { return decodeBase64(encoded); } catch { throw new TypeError("The input to be decoded is not correctly encoded."); } } // src/lib/is_object.ts function isObjectLike(value) { return typeof value === "object" && value !== null; } var is_object_default = (input) => { if (!isObjectLike(input) || Object.prototype.toString.call(input) !== "[object Object]") { return false; } if (Object.getPrototypeOf(input) === null) { return true; } let proto = input; while (Object.getPrototypeOf(proto) !== null) { proto = Object.getPrototypeOf(proto); } return Object.getPrototypeOf(input) === proto; }; // src/util/errors.ts var JOSEError = class extends Error { /** * A unique error code for the particular error subclass. * * @ignore */ static code = "ERR_JOSE_GENERIC"; /** A unique error code for {@link JOSEError}. */ code = "ERR_JOSE_GENERIC"; /** @ignore */ constructor(message, options) { super(message, options); this.name = this.constructor.name; Error.captureStackTrace?.(this, this.constructor); } }; var JWTInvalid = class extends JOSEError { /** @ignore */ static code = "ERR_JWT_INVALID"; /** A unique error code for {@link JWTInvalid}. */ code = "ERR_JWT_INVALID"; }; // src/util/decode_jwt.ts function decodeJwt(jwt) { if (typeof jwt !== "string") throw new JWTInvalid("JWTs must use Compact JWS serialization, JWT must be a string"); const { 1: payload, length } = jwt.split("."); if (length === 5) throw new JWTInvalid("Only JWTs using Compact JWS serialization can be decoded"); if (length !== 3) throw new JWTInvalid("Invalid JWT"); if (!payload) throw new JWTInvalid("JWTs must contain a payload"); let decoded; try { decoded = decode(payload); } catch { throw new JWTInvalid("Failed to base64url decode the payload"); } let result; try { result = JSON.parse(decoder.decode(decoded)); } catch { throw new JWTInvalid("Failed to parse the decoded payload as JSON"); } if (!is_object_default(result)) throw new JWTInvalid("Invalid JWT Claims Set"); return result; } export { decodeJwt };