UNPKG

pkce-x

Version:

PKCE is a security extension to OAuth 2.0 for public clients on mobile devices, designed to prevent interception of the authorisation code by a malicious application that has sneaked into the same device.

213 lines (212 loc) 10.7 kB
"use strict"; /*! * pkce-x * Copyright(c) 2022 Nadeen Gamage * MIT Licensed */ 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 (_) 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 AuthService = /** @class */ (function () { function AuthService(config) { this.state = ''; this.codeVerifier = ''; this.config = config; } AuthService.prototype.authorize = function (additionalParams) { if (additionalParams === void 0) { additionalParams = {}; } return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { if (this.getCodeFromUrl() === null) { window.location.replace("".concat(this.config.authorization_endpoint, "?").concat(this.getQueryString(additionalParams))); } return [2 /*return*/]; }); }); }; AuthService.prototype.exchange = function (additionalParams) { if (additionalParams === void 0) { additionalParams = {}; } return __awaiter(this, void 0, void 0, function () { var _this = this; return __generator(this, function (_a) { return [2 /*return*/, this.parseAuthResponseUrl(window.location.href).then(function (q) { return __awaiter(_this, void 0, void 0, function () { var response; var _this = this; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, fetch(this.config.token_endpoint, { method: 'POST', body: new URLSearchParams(Object.assign({ grant_type: 'authorization_code', code: q.code, client_id: this.config.client_id, redirect_uri: this.config.redirect_uri, code_verifier: this.getCodeVerifier(), }, additionalParams)), headers: this.getHeaders(), })]; case 1: response = _a.sent(); if (response.status === 200) { response.clone().json().then(function (data) { _this.getStore().setItem('access_token', data.access_token); _this.getStore().setItem('refresh_token', (data.refresh_token !== undefined ? data.refresh_token : null)); _this.getStore().setItem('expires_in', data.expires_in); _this.getStore().setItem('scope', data.scope); _this.getStore().setItem('token_type', data.token_type); }); } if (response.status !== 200) { window.location.replace("".concat(this.config.authorization_endpoint, "?").concat(this.getQueryString(additionalParams))); } return [2 /*return*/, response.json()]; } }); }); })]; }); }); }; AuthService.prototype.getAccessToken = function () { return this.getStore().getItem('access_token') || null; }; AuthService.prototype.getRefreshToken = function () { return this.getStore().getItem('refresh_token') || null; }; AuthService.prototype.getExpiresIn = function () { return parseInt(this.getStore().getItem('expires_in') || '0', 10); }; AuthService.prototype.getScope = function () { return this.getStore().getItem('scope') || null; }; AuthService.prototype.getQueryString = function (additionalParams) { if (additionalParams === void 0) { additionalParams = {}; } var codeChallenge = this.pkceChallengeFromVerifier(); var queryString = new URLSearchParams(Object.assign({ response_type: 'code', client_id: this.config.client_id, state: this.getState(additionalParams.state || null), scope: this.config.requested_scopes, redirect_uri: this.config.redirect_uri, code_challenge: codeChallenge, code_challenge_method: 'S256', }, additionalParams)).toString(); return queryString; }; AuthService.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'), }); }; AuthService.prototype.getHeaders = function () { if (this.config.client_secret) { return { Accept: 'application/json', 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8', 'Authorization': "Basic ".concat(this.getEncodedCredentials()), }; } else { return { Accept: 'application/json', 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8', }; } }; AuthService.prototype.getCodeFromUrl = function () { var params = new URL(window.location.href).searchParams; return params.get('code') || null; }; AuthService.prototype.getEncodedCredentials = function () { return btoa("".concat(this.config.client_id, ":").concat(this.config.client_secret)); }; AuthService.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); }); }; AuthService.prototype.pkceChallengeFromVerifier = function () { var hashed = (0, sha256_1.default)(this.getCodeVerifier()); return enc_base64_1.default.stringify(hashed).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); }; AuthService.prototype.getCodeVerifier = function () { if (this.codeVerifier === '') { this.codeVerifier = this.randomStringFromStorage('pkce_code_verifier'); } return this.codeVerifier; }; AuthService.prototype.getState = function (state) { if (state === void 0) { state = null; } var stateKey = 'pkce_state'; if (state !== null) { this.getStore().setItem(stateKey, state); } if (this.state === '') { this.state = this.randomStringFromStorage(stateKey); } return this.state; }; AuthService.prototype.randomStringFromStorage = function (key) { var fromStorage = this.getStore().getItem(key); if (fromStorage === null) { this.getStore().setItem(key, lib_typedarrays_1.default.random(64)); } return this.getStore().getItem(key) || ''; }; AuthService.prototype.getStore = function () { var _a; return ((_a = this.config) === null || _a === void 0 ? void 0 : _a.storage) || sessionStorage; }; return AuthService; }()); exports.default = AuthService;