UNPKG

@sap/xssec

Version:

XS Advanced Container Security API for node.js

222 lines (178 loc) 5.5 kB
const { jwtDecode } = require("jwt-decode"); const InvalidJwtError = require("../error/validation/InvalidJwtError"); const { TOKEN_DATE_LEEWAY } = require("../util/constants"); /** * @typedef {import('../util/Types').JwtHeader} JwtHeader * @typedef {import('../util/Types').JwtPayload} JwtPayload */ class Token { #jwt; /** @type {JwtHeader} */ #header; // parsed header /** @type {JwtPayload} */ #payload; // parsed payload /** * @param {string} jwt * @param {object} [content] - optional parsed header and payload * @param {string} [content.header] - parsed header * @param {string} [content.payload] - parsed payload */ constructor(jwt, { header, payload } = {}) { this.#jwt = jwt; if (header && payload) { this.#header = header; this.#payload = payload; } else { this.#parseJwt(jwt); } } #parseJwt(jwt) { try { this.#header = jwtDecode(jwt, { header: true }); this.#payload = jwtDecode(jwt); } catch (e) { // do not expose jwt-decode specific error => throw xssec-specific error with suggested status code 401 instead throw new InvalidJwtError(jwt, e); } } get audiences() { if (this.payload.aud) { return Array.isArray(this.payload.aud) ? this.payload.aud : [this.payload.aud]; } else { return null; } } get azp() { return this.payload.azp; } get clientId() { if (this.azp) { return this.azp; } if (this.audiences == null || this.audiences.length != 1) { // the fallback to cid only occured if audiences contained exactly 1 element, so we stick to this to be backward-compatible return null; } return this.audiences[0] || this.payload.cid; } get email() { return this.payload.email; } /** * Returns whether the token is expired based on claim exp (expiration time). * There is a 1min leeway after the exp in which the token still counts as valid to account for clock skew. * @return {Boolean} false if token has a positive {@link remainingTime}, true otherwise */ get expired() { return this.remainingTime <= 0; } get expirationDate() { return this.payload.exp ? new Date(this.payload.exp * 1000) : null; } get familyName() { return this.payload.ext_attr?.family_name || this.payload.family_name; } get givenName() { return this.payload.ext_attr?.given_name || this.payload.given_name; } get grantType() { return this.payload.grant_type; } /** @return {JwtHeader} Token header as parsed object */ get header() { return this.#header; } get issuer() { return this.payload.iss; } get issueDate() { return this.payload.iat ? new Date(this.payload.iat * 1000) : null; } /** @return {String} JWT used to construct this Token instance as raw String */ get jwt() { return this.#jwt; } /** * Returns whether the token is not yet valid based on the optional nbf (no use before) claim. * There is a 1min leeway before the nbf in which the token already counts as valid to account for clock skew. * @return {Boolean} true if token has nbf and nbf date lies in future, false otherwise */ get notYetValid() { return this.payload.nbf != null && Math.floor(Date.now() / 1000) + TOKEN_DATE_LEEWAY < this.payload.nbf; } get origin() { return this.payload.origin; } /** @return {JwtPayload} Token payload as parsed object */ get payload() { return this.#payload; } /** * Returns the remaining time until expiration in seconds based on claim exp (expiration time). * There is a 1min leeway after the exp in which the token still counts as valid to account for clock skew. * @returns seconds until expiration or 0 if expired */ get remainingTime() { return Math.max(0, this.payload.exp + TOKEN_DATE_LEEWAY - Math.floor(Date.now() / 1000)); } get subject() { return this.payload.sub; } get userName() { return this.payload.user_name; } get userId() { return this.payload.user_uuid; } // Methods for backward-compatibility getAudiencesArray() { return this.audiences; } getAzp() { return this.azp; } getClientId = function () { return this.clientId; } getEmail() { return this.email; } getExpirationDate() { return this.expirationDate; } getFamilyName() { return this.familyName; } getGivenName() { return this.givenName; } getGrantType() { return this.grantType; } getHeader() { return this.header; } getIssuedAt() { return this.issueDate; } getIssuer() { if(this.issuer && !this.issuer.startsWith('http')) { return `https://${this.issuer}`; } else { return this.issuer; } } getPayload() { return this.payload; } getSubject() { return this.subject; } getTokenValue() { return this.jwt; } getUserId() { return this.userId; } } module.exports = Token;