UNPKG

js-pkce

Version:

A package that makes using the OAuth2 PKCE flow easier

300 lines (299 loc) 13.5 kB
"use strict"; var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (g && (g = 0, op[0] && (_ = 0)), _) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); var sha256_1 = __importDefault(require("crypto-js/sha256")); var enc_base64_1 = __importDefault(require("crypto-js/enc-base64")); var lib_typedarrays_1 = __importDefault(require("crypto-js/lib-typedarrays")); var PKCE = /** @class */ (function () { /** * Initialize the instance with configuration * @param {IConfig} config */ function PKCE(config) { this.STATE_KEY = 'pkce_state'; this.CODE_VERIFIER_KEY = 'pkce_code_verifier'; this.corsRequestOptions = {}; this.config = config; } /** * Generate the authorize url * @param {object} additionalParams include additional parameters in the query * @return Promise<string> */ PKCE.prototype.authorizeUrl = function (additionalParams) { if (additionalParams === void 0) { additionalParams = {}; } this.setCodeVerifier(); this.setState(additionalParams.state || null); var codeChallenge = this.pkceChallengeFromVerifier(); var queryString = new URLSearchParams(__assign({ response_type: 'code', client_id: this.config.client_id, state: this.getState(), scope: this.config.requested_scopes, redirect_uri: this.config.redirect_uri, code_challenge: codeChallenge, code_challenge_method: 'S256' }, additionalParams)).toString(); return "".concat(this.config.authorization_endpoint, "?").concat(queryString); }; /** * Allow the user to enable cross domain cors requests * @param enable turn the cross domain request options on. * @return ICorsOptions */ PKCE.prototype.enableCorsCredentials = function (enable) { this.corsRequestOptions = enable ? { credentials: 'include', mode: 'cors', } : {}; return this.corsRequestOptions; }; /** * Given the return url, get a token from the oauth server * @param url current urlwith params from server * @param {object} additionalParams include additional parameters in the request body * @return {Promise<ITokenResponse>} */ PKCE.prototype.exchangeForAccessToken = function (url, additionalParams) { if (additionalParams === void 0) { additionalParams = {}; } return __awaiter(this, void 0, void 0, function () { var code, response; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.parseAuthResponseUrl(url)]; case 1: code = (_a.sent()).code; return [4 /*yield*/, fetch(this.config.token_endpoint, __assign({ method: 'POST', body: new URLSearchParams(__assign({ grant_type: 'authorization_code', code: code, client_id: this.config.client_id, redirect_uri: this.config.redirect_uri, code_verifier: this.getCodeVerifier() }, additionalParams)), headers: { Accept: 'application/json', 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8', } }, this.corsRequestOptions))]; case 2: response = _a.sent(); return [4 /*yield*/, response.json()]; case 3: return [2 /*return*/, _a.sent()]; } }); }); }; /** * Get the current codeVerifier * @return {string} */ PKCE.prototype.getCodeVerifier = function () { var codeVerifier = this.getStore().getItem(this.CODE_VERIFIER_KEY); if (null === codeVerifier) { throw new Error('Code Verifier not set.'); } return codeVerifier; }; /** * Get the current state * @return {string} */ PKCE.prototype.getState = function () { var state = this.getStore().getItem(this.STATE_KEY); if (null === state) { throw new Error('State not set.'); } return state; }; /** * Given a refresh token, return a new token from the oauth server * @param refreshTokens current refresh token from server * @return {Promise<ITokenResponse>} */ PKCE.prototype.refreshAccessToken = function (refreshToken) { return __awaiter(this, void 0, void 0, function () { var response; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, fetch(this.config.token_endpoint, { method: 'POST', body: new URLSearchParams({ grant_type: 'refresh_token', client_id: this.config.client_id, refresh_token: refreshToken, }), headers: { Accept: 'application/json', 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8', }, })]; case 1: response = _a.sent(); return [4 /*yield*/, response.json()]; case 2: return [2 /*return*/, _a.sent()]; } }); }); }; /** * Revoke an existing token. * Optionally send a token_type_hint as second parameter * @param {string} tokenToExpire the token to be expired * @param {string} hint when not empty, token_type_hint will be sent with request * @returns */ PKCE.prototype.revokeToken = function (tokenToExpire, hint) { if (hint === void 0) { hint = ''; } return __awaiter(this, void 0, void 0, function () { var params, response; return __generator(this, function (_a) { switch (_a.label) { case 0: this.checkEndpoint('revoke_endpoint'); params = new URLSearchParams({ token: tokenToExpire, client_id: this.config.client_id, }); if (hint.length) { params.append('token_type_hint', hint); } return [4 /*yield*/, fetch(this.config.revoke_endpoint, { method: 'POST', body: params, headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8', }, })]; case 1: response = _a.sent(); return [2 /*return*/, response.ok]; } }); }); }; /** * Check if an endpoint from configuration is set and using https protocol * Allow http on localhost * @param {string} propertyName the key of the item in configuration to check */ PKCE.prototype.checkEndpoint = function (propertyName) { if (!this.config.hasOwnProperty(propertyName)) { throw new Error("".concat(propertyName, " not configured.")); } var url = new URL(this.config[propertyName]); var isLocalHost = ['localhost', '127.0.0.1'].indexOf(url.hostname) !== -1; if (url.protocol !== 'https:' && !isLocalHost) { throw new Error("Protocol ".concat(url.protocol, " not allowed with this action.")); } }; /** * Generate a random string * @return {string} */ PKCE.prototype.generateRandomString = function () { return lib_typedarrays_1.default.random(64); }; /** * Get the query params as json from a auth response url * @param {string} url a url expected to have AuthResponse params * @return {Promise<IAuthResponse>} */ PKCE.prototype.parseAuthResponseUrl = function (url) { var params = new URL(url).searchParams; return this.validateAuthResponse({ error: params.get('error'), query: params.get('query'), state: params.get('state'), code: params.get('code'), }); }; /** * Generate a code challenge * @return {Promise<string>} */ PKCE.prototype.pkceChallengeFromVerifier = function () { var hashed = (0, sha256_1.default)(this.getCodeVerifier()); return enc_base64_1.default.stringify(hashed).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); }; /** * Set the code verifier in storage to a random string * @return {void} */ PKCE.prototype.setCodeVerifier = function () { this.getStore().setItem(this.CODE_VERIFIER_KEY, this.generateRandomString()); }; /** * Set the state in storage to a random string. * Optionally set an explicit state * @param {string | null} explicit when set, we will use this value for the state value * @return {void} */ PKCE.prototype.setState = function (explicit) { if (explicit === void 0) { explicit = null; } var value = explicit !== null ? explicit : this.generateRandomString(); this.getStore().setItem(this.STATE_KEY, value); }; /** * Validates params from auth response * @param {AuthResponse} queryParams * @return {Promise<IAuthResponse>} */ PKCE.prototype.validateAuthResponse = function (queryParams) { var _this = this; return new Promise(function (resolve, reject) { if (queryParams.error) { return reject({ error: queryParams.error }); } if (queryParams.state !== _this.getState()) { return reject({ error: 'Invalid State' }); } return resolve(queryParams); }); }; /** * Get the instance of Storage interface to use. * Defaults to sessionStorage. * @return {Storage} */ PKCE.prototype.getStore = function () { var _a; return ((_a = this.config) === null || _a === void 0 ? void 0 : _a.storage) || sessionStorage; }; return PKCE; }()); exports.default = PKCE;