@dvsa/appdev-api-common
Version:
Utils library for common API functionality
52 lines (51 loc) • 1.9 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.JwtAuthoriser = void 0;
const jose_1 = require("jose");
const http_status_codes_1 = require("../api/http-status-codes");
const auth_errors_1 = require("./auth-errors");
class JwtAuthoriser {
clientId;
static ENV = process.env.environment?.toUpperCase() ?? "";
static tokenExpiryEnvExclusionList = [
"DEVELOPMENT",
"NON-PROD",
];
static JWKS_URI = new URL("https://login.microsoftonline.com/common/discovery/keys");
static JWKS = (0, jose_1.createRemoteJWKSet)(JwtAuthoriser.JWKS_URI);
/**
* Create a new instance of the JwtAuthoriser class
* @param clientId - the client id to validate the token against
*/
constructor(clientId = null) {
this.clientId = clientId;
}
/**
* Validate a JWT and return the decoded payload
* @param {string} token - the JWT token to validate
* @returns {Promise<JWTPayload>}
*/
async verify(token) {
try {
const opts = {
clockTolerance: 10,
algorithms: ["RS256"],
};
// issuer validation is handled automatically if present in token
if (this.clientId) {
opts.audience = this.clientId;
}
if (JwtAuthoriser.tokenExpiryEnvExclusionList.includes(JwtAuthoriser.ENV)) {
opts.maxTokenAge = Number.POSITIVE_INFINITY;
}
const { payload } = await (0, jose_1.jwtVerify)(token, JwtAuthoriser.JWKS, opts);
return payload;
}
catch (err) {
const error = err;
const code = "code" in error ? error.code : "";
throw new auth_errors_1.AuthError(http_status_codes_1.HttpStatus.UNAUTHORIZED, err.message, code);
}
}
}
exports.JwtAuthoriser = JwtAuthoriser;