UNPKG

@kinde-oss/kinde-nodejs-sdk

Version:

Kinde Nodejs SDK allows integrate with Express server using middleware, helpers function

110 lines (103 loc) 5.21 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getSessionId = getSessionId; exports.parseJWT = parseJWT; exports.pkceChallengeFromVerifier = pkceChallengeFromVerifier; exports.randomString = randomString; var _crypto = _interopRequireDefault(require("crypto")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } function _iterableToArrayLimit(arr, i) { var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; if (null != _i) { var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1; try { if (_x = (_i = _i.call(arr)).next, 0 === i) { if (Object(_i) !== _i) return; _n = !1; } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); } catch (err) { _d = !0, _e = err; } finally { try { if (!_n && null != _i["return"] && (_r = _i["return"](), Object(_r) !== _r)) return; } finally { if (_d) throw _e; } } return _arr; } } function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } /** * Generates a random string using the crypto module in Node.js * @returns {string} a random string of 28 hexadecimal characters */ function randomString() { return _crypto["default"].randomBytes(28).toString('hex'); } /** * Generates SHA-256 hash of the input string. * @param {string} plain - The input string to be hashed. * @return {Buffer} - The generated hash as a buffer object. */ function sha256(plain) { var encoder = new TextEncoder(); var data = encoder.encode(plain); return _crypto["default"].createHash('sha256').update(data).digest(); } /** * Converts a binary string to a base64 URL encoded string * @param {string} str - The binary string to encode * @returns {string} The base64 URL encoded string */ function base64UrlEncode(str) { return Buffer.from(str).toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); } /** * Function to generate a PKCE challenge from the codeVerifier * @param {string} codeVerifier - The verifier used to generate the PKCE challenge * @returns {string} A base64 URL encoded SHA-256 hash of the verifier */ function pkceChallengeFromVerifier(codeVerifier) { var hashed = sha256(codeVerifier); return base64UrlEncode(hashed); } /** * parseJWT - a function to parse a JSON Web Token (JWT) * @param {string} token - the JWT to parse * @returns {Object|null} - the JSON object represented by the token or null if the parsing fails */ function parseJWT(token) { if (typeof token !== 'string') { throw new Error('Token must be a string'); } var parts = token.split('.'); if (parts.length !== 3) { throw new Error('Invalid token format'); } var base64Payload = parts[1]; try { return JSON.parse(Buffer.from(base64Payload, 'base64').toString('utf8')); } catch (error) { return null; } } /** * Returns an object with key-value pairs of cookies extracted from the request headers * @param {Object} request - The HTTP request object that contains headers with cookie information * @returns {Object} - An object containing key-value pairs of cookies */ function getCookie(request) { var cookies = {}; var cookieString = request.headers && request.headers.cookie; if (cookieString) { cookieString.split(';').forEach(function (cookie) { var _cookie$trim$split = cookie.trim().split('='), _cookie$trim$split2 = _slicedToArray(_cookie$trim$split, 2), name = _cookie$trim$split2[0], value = _cookie$trim$split2[1]; cookies[name] = value; }); } return cookies; } /** * Returns the session ID if it exists in the cookie header of the HTTP request object, otherwise generates a new session ID and returns it. * @param {Object} request - The HTTP request object * @returns {string} - A session ID string */ function getSessionId(request) { var _request$headers; if (!((_request$headers = request.headers) !== null && _request$headers !== void 0 && _request$headers.cookie)) { var sessionId = _crypto["default"].randomBytes(16).toString('hex'); return sessionId; } var cookies = getCookie(request); return cookies.kindeSessionId || _crypto["default"].randomBytes(16).toString('hex'); }