Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@livechat/customer-auth

Package Overview
Dependencies
Maintainers
5
Versions
9
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@livechat/customer-auth - npm Package Compare versions

Comparing version 0.4.0-alpha.0 to 0.4.0-alpha.1

dist/customer-auth.esm.js

404

dist/customer-auth.cjs.js

@@ -8,266 +8,286 @@ 'use strict';

var urlUtils = require('@livechat/url-utils');
var domUtils = require('@livechat/dom-utils');
var storage = _interopDefault(require('@livechat/isomorphic-storage'));
var buildParams = function buildParams(_ref, state) {
var clientId = _ref.clientId,
license = _ref.license,
redirectUri = _ref.redirectUri;
function _extends() {
_extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
var params = {};
params.license_id = license;
params.flow = 'button';
params.response_type = 'token';
params.client_id = clientId;
params.redirect_uri = redirectUri;
params.post_message_uri = redirectUri;
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
if (state) {
params.state = state;
}
return target;
};
return params;
return _extends.apply(this, arguments);
}
function _objectWithoutPropertiesLoose(source, excluded) {
if (source == null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i;
for (i = 0; i < sourceKeys.length; i++) {
key = sourceKeys[i];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
var buildParams = function buildParams(_ref) {
var clientId = _ref.clientId,
license = _ref.license,
redirectUri = _ref.redirectUri,
state = _ref.state;
var params = {
license_id: license,
flow: 'button',
response_type: 'token',
client_id: clientId,
redirect_uri: redirectUri,
post_message_uri: redirectUri
};
if (state) {
params.state = state;
}
return params;
};
var buildPath = function buildPath(_ref2) {
var uniqueGroups = _ref2.uniqueGroups,
license = _ref2.license,
group = _ref2.group;
return (uniqueGroups ? '/licence/g' + license + '_' + group : '') + '/customer';
var uniqueGroups = _ref2.uniqueGroups,
license = _ref2.license,
group = _ref2.group;
return (uniqueGroups ? "/licence/g" + license + "_" + group : '') + "/customer";
};
var buildSrc = (function (config, state, env) {
var url = env === 'production' ? "https://accounts.livechatinc.com" : "https://accounts.livechatinc.com".replace('accounts.', 'accounts.' + env + '.');
var path = buildPath(config);
var query = urlUtils.buildQueryString(buildParams(config, state));
return '' + url + path + '?' + query;
var url = env === 'production' ? "https://accounts.livechatinc.com" : "https://accounts.livechatinc.com".replace('accounts.', "accounts." + env + ".");
var path = buildPath(config);
var query = urlUtils.buildQueryString(buildParams(_extends({}, config, {
state: state
})));
return "" + url + path + "?" + query;
});
var ok = function ok(value) {
return { type: 'ok', value: value };
return {
type: 'ok',
value: value
};
};
var error = function error(err) {
return { type: 'error', error: err };
return {
type: 'error',
error: err
};
};
var fold = function fold(foldErr, foldValue, result) {
return result.type === 'ok' ? foldValue(result.value) : foldErr(result.error);
return result.type === 'ok' ? foldValue(result.value) : foldErr(result.error);
};
var parseTokenResponse = function parseTokenResponse(tokenResponse, _ref) {
var license = _ref.license;
return {
accessToken: tokenResponse.access_token,
entityId: tokenResponse.entity_id,
expiresIn: tokenResponse.expires_in * 1000,
tokenType: tokenResponse.token_type,
creationDate: Date.now(),
license: license
};
var license = _ref.license;
return {
accessToken: tokenResponse.access_token,
entityId: tokenResponse.entity_id,
expiresIn: tokenResponse.expires_in * 1000,
tokenType: tokenResponse.token_type,
creationDate: Date.now(),
license: license
};
};
var parseToken = (function (token, extraData) {
if (token.identity_exception) {
return error({ code: 'SSO_IDENTITY_EXCEPTION', message: token.identity_exception });
}
if (token.oauth_exception) {
return error({ code: 'SSO_OAUTH_EXCEPTION', message: token.oauth_exception });
}
if (token.identity_exception) {
return error({
code: 'SSO_IDENTITY_EXCEPTION',
message: token.identity_exception
});
}
return ok(parseTokenResponse(token, extraData));
});
var _extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
if (token.oauth_exception) {
return error({
code: 'SSO_OAUTH_EXCEPTION',
message: token.oauth_exception
});
}
return target;
};
return ok(parseTokenResponse(token, extraData));
});
var objectWithoutProperties = function (obj, keys) {
var target = {};
// it's hardcoded here because chat.io has its own ACCOUNTS_URL
// but this variable has to have the same value for both LiveChat and chat.io
for (var i in obj) {
if (keys.indexOf(i) >= 0) continue;
if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
target[i] = obj[i];
}
var POST_MESSAGE_ORIGIN = 'https://accounts.livechatinc.com';
return target;
};
var getPostMessageOrigin = function getPostMessageOrigin(env) {
return env === 'production' ? "https://cdn.livechat-static.com" : "https://cdn.livechat-static.com".replace('cdn.', 'cdn-' + env + '.');
return env === 'production' ? POST_MESSAGE_ORIGIN : POST_MESSAGE_ORIGIN.replace('accounts.', "accounts." + env + ".");
};
var LEGACY_POST_MESSAGE_ORIGIN = 'https://cdn.chatio-static.com';
var getLegacyPostMessageOrigin = function getLegacyPostMessageOrigin(env) {
return env === 'production' ? LEGACY_POST_MESSAGE_ORIGIN : LEGACY_POST_MESSAGE_ORIGIN.replace('cdn.', 'cdn-' + env + '.');
};
var CUSTOMER_AUTH_FOOTPRINT = '@livechat/customer-auth';
var buildIframe = function buildIframe(config, env) {
var iframe = document.createElement('iframe');
iframe.style.display = 'none';
iframe.setAttribute('src', buildSrc(_extends({}, config, {
redirectUri: urlUtils.getOrigin(String(location)) + location.pathname
}), null, env));
return iframe;
var iframe = document.createElement('iframe');
iframe.style.display = 'none';
iframe.setAttribute('src', buildSrc(_extends({}, config, {
redirectUri: urlUtils.getOrigin(String(location)) + location.pathname
}), CUSTOMER_AUTH_FOOTPRINT, env));
return iframe;
};
var appendBodyChild = function appendBodyChild(node) {
if (!document.body) {
setTimeout(appendBodyChild, 100, node);
return;
}
document.body.appendChild(node);
};
var removeNode = function removeNode(node) {
if (!node.parentNode) {
return;
}
if (!node.parentNode) {
return;
}
node.parentNode.removeChild(node);
node.parentNode.removeChild(node);
};
var createError = function createError(_ref) {
var code = _ref.code,
message = _ref.message;
var err = new Error(message);
// $FlowFixMe
err.code = code;
return err;
var code = _ref.code,
message = _ref.message;
var err = new Error(message);
err.code = code;
return err;
};
var fetchToken = (function (config, env) {
var license = config.license;
var license = config.license;
var postMessageOrigin = getPostMessageOrigin(env);
return new Promise(function (resolve, reject) {
var _window2;
var postMessageOrigin = getPostMessageOrigin(env);
var legacyPostMessageOrigin = getLegacyPostMessageOrigin(env);
var iframe = buildIframe(config, env);
return new Promise(function (resolve, reject) {
var _window2;
var cleanup = function cleanup() {
var _window;
var iframe = buildIframe(config, env);
removeNode(iframe); // eslint-disable-next-line no-use-before-define
var cleanup = function cleanup() {
var _window;
(_window = window).removeEventListener.apply(_window, listener);
};
removeNode(iframe);
// eslint-disable-next-line no-use-before-define
(_window = window).removeEventListener.apply(_window, listener);
};
var timeoutId = setTimeout(function () {
cleanup();
reject(createError({
message: 'Request timed out.',
code: 'REQUEST_TIMEOUT'
}));
}, 15 * 1000);
var listener = ['message', function (_ref2) {
var origin = _ref2.origin,
data = _ref2.data;
var timeoutId = setTimeout(function () {
cleanup();
reject(createError({ message: 'Request timed out.', code: 'REQUEST_TIMEOUT' }));
}, 15 * 1000);
if (origin !== postMessageOrigin) {
return;
}
var listener = ['message', function (_ref2) {
var origin = _ref2.origin,
data = _ref2.data;
if (!data || data.state !== CUSTOMER_AUTH_FOOTPRINT) {
return;
}
if (origin !== postMessageOrigin && origin !== legacyPostMessageOrigin) {
return;
}
clearTimeout(timeoutId);
cleanup();
fold(function (err) {
return reject(createError(err));
}, resolve, parseToken(data, {
license: license
}));
}, false];
clearTimeout(timeoutId);
cleanup();
fold(function (err) {
return reject(createError(err));
}, resolve, parseToken(data, { license: license }));
}, false];
(_window2 = window).addEventListener.apply(_window2, listener);
appendBodyChild(iframe);
});
(_window2 = window).addEventListener.apply(_window2, listener);
domUtils.getRoot().then(function (body) {
body.appendChild(iframe);
});
});
});
var validateConfig = (function (_ref) {
var license = _ref.license,
clientId = _ref.clientId;
var license = _ref.license,
clientId = _ref.clientId;
if (typeof license !== 'number' || typeof clientId !== 'string') {
throw new Error('You need to pass valid configuration object: { license, clientId }.');
}
if (typeof license !== 'number' || typeof clientId !== 'string') {
throw new Error('You need to pass valid configuration object: { license, clientId }.');
}
});
var isExpiredToken = function isExpiredToken(token) {
return Date.now() >= token.creationDate + token.expiresIn;
return Date.now() >= token.creationDate + token.expiresIn;
};
var withDefaults = function withDefaults(_ref) {
var _ref$uniqueGroups = _ref.uniqueGroups,
uniqueGroups = _ref$uniqueGroups === undefined ? false : _ref$uniqueGroups,
rest = objectWithoutProperties(_ref, ['uniqueGroups']);
return _extends({ uniqueGroups: uniqueGroups }, rest);
var _ref$uniqueGroups = _ref.uniqueGroups,
uniqueGroups = _ref$uniqueGroups === void 0 ? false : _ref$uniqueGroups,
rest = _objectWithoutPropertiesLoose(_ref, ["uniqueGroups"]);
return _extends({
uniqueGroups: uniqueGroups
}, rest);
};
var auth = (function (inputConfig) {
var env = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'production';
var auth = (function (inputConfig, env) {
validateConfig(inputConfig);
var config = withDefaults(inputConfig);
var pendingTokenRequest;
var cachedToken;
var cacheKey = "@@lc_auth_token:" + config.license + (config.uniqueGroups ? ":" + config.group : '');
var retrievingToken = storage.getItem(cacheKey).then(function (token) {
if (retrievingToken === null) {
return;
}
validateConfig(inputConfig);
var config = withDefaults(inputConfig);
retrievingToken = null;
var pendingTokenRequest = void 0;
var cachedToken = void 0;
var cacheKey = '' + "@@lc_auth_token:" + config.license + (config.uniqueGroups ? ':' + config.group : '');
if (!token) {
return;
}
var retrievingToken = storage.getItem(cacheKey).then(function (token) {
if (retrievingToken === null) {
return;
}
cachedToken = JSON.parse(token);
});
var auth = Object.freeze({
getFreshToken: function getFreshToken() {
pendingTokenRequest = fetchToken(config, env).then(function (token) {
pendingTokenRequest = null;
storage.setItem(cacheKey, JSON.stringify(token));
cachedToken = token;
return token;
}).catch(function (err) {
pendingTokenRequest = null;
throw err;
});
return pendingTokenRequest;
},
getToken: function getToken() {
if (pendingTokenRequest) {
return pendingTokenRequest;
}
retrievingToken = null;
if (cachedToken && !isExpiredToken(cachedToken)) {
return Promise.resolve(cachedToken);
}
if (!token) {
return;
}
if (retrievingToken) {
return retrievingToken.then(auth.getToken);
}
cachedToken = JSON.parse(token);
});
var auth = Object.freeze({
getFreshToken: function getFreshToken() {
pendingTokenRequest = fetchToken(config, env).then(function (token) {
pendingTokenRequest = null;
storage.setItem(cacheKey, JSON.stringify(token));
cachedToken = token;
return token;
}).catch(function (err) {
pendingTokenRequest = null;
throw err;
});
return pendingTokenRequest;
},
getToken: function getToken() {
if (pendingTokenRequest) {
return pendingTokenRequest;
}
if (cachedToken && !isExpiredToken(cachedToken)) {
return Promise.resolve(cachedToken);
}
if (retrievingToken) {
return retrievingToken.then(auth.getToken);
}
return auth.getFreshToken();
},
invalidate: function invalidate() {
storage.removeItem(cacheKey);
cachedToken = null;
retrievingToken = null;
}
});
return auth;
return auth.getFreshToken();
},
invalidate: function invalidate() {
storage.removeItem(cacheKey);
cachedToken = null;
retrievingToken = null;
}
});
return auth;
});

@@ -274,0 +294,0 @@

@@ -7,4 +7,36 @@ (function (global, factory) {

function _extends() {
_extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
return _extends.apply(this, arguments);
}
function _objectWithoutPropertiesLoose(source, excluded) {
if (source == null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i;
for (i = 0; i < sourceKeys.length; i++) {
key = sourceKeys[i];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
var testKey = '__test_storage_support__';
var testStorageSupport = function testStorageSupport() {

@@ -23,3 +55,2 @@ var type = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'local';

};
var createStorage = function createStorage() {

@@ -62,51 +93,24 @@ var memoryStorage = Object.defineProperties({}, {

};
var memoryStorage = /*#__PURE__*/
createStorage();
var memoryStorage = /*#__PURE__*/createStorage();
var storage = testStorageSupport() ? window.localStorage : memoryStorage;
var storage$1 = {
setItem: function setItem(key, data) {
return new Promise(function (resolve) {
return resolve(storage.setItem(key, data));
});
},
getItem: function getItem(key) {
return new Promise(function (resolve) {
return resolve(storage.getItem(key));
});
},
removeItem: function removeItem(key) {
return new Promise(function (resolve) {
return resolve(storage.removeItem(key));
});
}
};
var _extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
setItem: function setItem(key, data) {
return new Promise(function (resolve) {
return resolve(storage.setItem(key, data));
});
},
getItem: function getItem(key) {
return new Promise(function (resolve) {
return resolve(storage.getItem(key));
});
},
removeItem: function removeItem(key) {
return new Promise(function (resolve) {
return resolve(storage.removeItem(key));
});
}
return target;
};
var objectWithoutProperties = function (obj, keys) {
var target = {};
for (var i in obj) {
if (keys.indexOf(i) >= 0) continue;
if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
target[i] = obj[i];
}
return target;
};
// slightly simplified version of https://github.com/sindresorhus/camelcase/blob/a526ef0399f9a1310eaacafa0ae4a69da4a2f1ad/index.js

@@ -120,6 +124,6 @@

// previous version was written like this, but it seems that TS can't intersect function types like this? it infers (any, any) => any from this
// based on https://github.com/developit/dlv/blob/d7ec976d12665f1c25dec2acf955dfc2e8757a9c/index.js
// based on https://github.com/lukeed/dset/blob/f8ce2f65d4adae7842492eb519a7e55de9abdf38/src/index.js
// https://github.com/reactjs/react-redux/blob/5d792a283554cff3d2f54fad1be1f79cbcab33fe/src/utils/shallowEqual.js

@@ -129,256 +133,284 @@

function toPairs(obj) {
return Object.keys(obj).map(function (key) {
return [key, obj[key]];
});
var toPairs = function toPairs(obj) {
return Object.keys(obj).map(function (key) {
return [key, obj[key]];
});
};
function getRoot() {
return new Promise(function (resolve) {
var next = function next() {
if (!document.body) {
setTimeout(next, 100);
return;
}
resolve(document.body);
};
next();
});
}
var buildQueryString = (function (obj) {
return toPairs(obj).map(function (pair) {
return pair.map(encodeURIComponent).join('=');
}).join('&');
});
var buildQueryString = function buildQueryString(obj) {
return toPairs(obj).map(function (pair) {
return pair.map(encodeURIComponent).join('=');
}).join('&');
};
var originRegexp = /[^:]+:\/\/[^(\/|\?)\s]+/;
var getOrigin = (function (url) {
var domain = url.match(originRegexp);
return domain && domain[0];
});
var buildParams = function buildParams(_ref, state) {
var clientId = _ref.clientId,
license = _ref.license,
redirectUri = _ref.redirectUri;
var getOrigin = function getOrigin(url) {
var domain = url.match(originRegexp);
return domain && domain[0];
};
var params = {};
params.license_id = license;
params.flow = 'button';
params.response_type = 'token';
params.client_id = clientId;
params.redirect_uri = redirectUri;
params.post_message_uri = redirectUri;
var buildParams = function buildParams(_ref) {
var clientId = _ref.clientId,
license = _ref.license,
redirectUri = _ref.redirectUri,
state = _ref.state;
var params = {
license_id: license,
flow: 'button',
response_type: 'token',
client_id: clientId,
redirect_uri: redirectUri,
post_message_uri: redirectUri
};
if (state) {
params.state = state;
}
if (state) {
params.state = state;
}
return params;
return params;
};
var buildPath = function buildPath(_ref2) {
var uniqueGroups = _ref2.uniqueGroups,
license = _ref2.license,
group = _ref2.group;
return (uniqueGroups ? '/licence/g' + license + '_' + group : '') + '/customer';
var uniqueGroups = _ref2.uniqueGroups,
license = _ref2.license,
group = _ref2.group;
return (uniqueGroups ? "/licence/g" + license + "_" + group : '') + "/customer";
};
var buildSrc = (function (config, state, env) {
var url = env === 'production' ? "https://accounts.livechatinc.com" : "https://accounts.livechatinc.com".replace('accounts.', 'accounts.' + env + '.');
var path = buildPath(config);
var query = buildQueryString(buildParams(config, state));
return '' + url + path + '?' + query;
var url = env === 'production' ? "https://accounts.livechatinc.com" : "https://accounts.livechatinc.com".replace('accounts.', "accounts." + env + ".");
var path = buildPath(config);
var query = buildQueryString(buildParams(_extends({}, config, {
state: state
})));
return "" + url + path + "?" + query;
});
var ok = function ok(value) {
return { type: 'ok', value: value };
return {
type: 'ok',
value: value
};
};
var error = function error(err) {
return { type: 'error', error: err };
return {
type: 'error',
error: err
};
};
var fold = function fold(foldErr, foldValue, result) {
return result.type === 'ok' ? foldValue(result.value) : foldErr(result.error);
return result.type === 'ok' ? foldValue(result.value) : foldErr(result.error);
};
var parseTokenResponse = function parseTokenResponse(tokenResponse, _ref) {
var license = _ref.license;
return {
accessToken: tokenResponse.access_token,
entityId: tokenResponse.entity_id,
expiresIn: tokenResponse.expires_in * 1000,
tokenType: tokenResponse.token_type,
creationDate: Date.now(),
license: license
};
var license = _ref.license;
return {
accessToken: tokenResponse.access_token,
entityId: tokenResponse.entity_id,
expiresIn: tokenResponse.expires_in * 1000,
tokenType: tokenResponse.token_type,
creationDate: Date.now(),
license: license
};
};
var parseToken = (function (token, extraData) {
if (token.identity_exception) {
return error({ code: 'SSO_IDENTITY_EXCEPTION', message: token.identity_exception });
}
if (token.oauth_exception) {
return error({ code: 'SSO_OAUTH_EXCEPTION', message: token.oauth_exception });
}
if (token.identity_exception) {
return error({
code: 'SSO_IDENTITY_EXCEPTION',
message: token.identity_exception
});
}
return ok(parseTokenResponse(token, extraData));
if (token.oauth_exception) {
return error({
code: 'SSO_OAUTH_EXCEPTION',
message: token.oauth_exception
});
}
return ok(parseTokenResponse(token, extraData));
});
// it's hardcoded here because chat.io has its own ACCOUNTS_URL
// but this variable has to have the same value for both LiveChat and chat.io
var POST_MESSAGE_ORIGIN = 'https://accounts.livechatinc.com';
var getPostMessageOrigin = function getPostMessageOrigin(env) {
return env === 'production' ? "https://cdn.livechat-static.com" : "https://cdn.livechat-static.com".replace('cdn.', 'cdn-' + env + '.');
return env === 'production' ? POST_MESSAGE_ORIGIN : POST_MESSAGE_ORIGIN.replace('accounts.', "accounts." + env + ".");
};
var LEGACY_POST_MESSAGE_ORIGIN = 'https://cdn.chatio-static.com';
var getLegacyPostMessageOrigin = function getLegacyPostMessageOrigin(env) {
return env === 'production' ? LEGACY_POST_MESSAGE_ORIGIN : LEGACY_POST_MESSAGE_ORIGIN.replace('cdn.', 'cdn-' + env + '.');
};
var CUSTOMER_AUTH_FOOTPRINT = '@livechat/customer-auth';
var buildIframe = function buildIframe(config, env) {
var iframe = document.createElement('iframe');
iframe.style.display = 'none';
iframe.setAttribute('src', buildSrc(_extends({}, config, {
redirectUri: getOrigin(String(location)) + location.pathname
}), null, env));
return iframe;
var iframe = document.createElement('iframe');
iframe.style.display = 'none';
iframe.setAttribute('src', buildSrc(_extends({}, config, {
redirectUri: getOrigin(String(location)) + location.pathname
}), CUSTOMER_AUTH_FOOTPRINT, env));
return iframe;
};
var appendBodyChild = function appendBodyChild(node) {
if (!document.body) {
setTimeout(appendBodyChild, 100, node);
return;
}
document.body.appendChild(node);
};
var removeNode$1 = function removeNode$$1(node) {
if (!node.parentNode) {
return;
}
var removeNode = function removeNode(node) {
if (!node.parentNode) {
return;
}
node.parentNode.removeChild(node);
node.parentNode.removeChild(node);
};
var createError = function createError(_ref) {
var code = _ref.code,
message = _ref.message;
var err = new Error(message);
// $FlowFixMe
err.code = code;
return err;
var code = _ref.code,
message = _ref.message;
var err = new Error(message);
err.code = code;
return err;
};
var fetchToken = (function (config, env) {
var license = config.license;
var license = config.license;
var postMessageOrigin = getPostMessageOrigin(env);
return new Promise(function (resolve, reject) {
var _window2;
var postMessageOrigin = getPostMessageOrigin(env);
var legacyPostMessageOrigin = getLegacyPostMessageOrigin(env);
var iframe = buildIframe(config, env);
return new Promise(function (resolve, reject) {
var _window2;
var cleanup = function cleanup() {
var _window;
var iframe = buildIframe(config, env);
removeNode$1(iframe); // eslint-disable-next-line no-use-before-define
var cleanup = function cleanup() {
var _window;
(_window = window).removeEventListener.apply(_window, listener);
};
removeNode(iframe);
// eslint-disable-next-line no-use-before-define
(_window = window).removeEventListener.apply(_window, listener);
};
var timeoutId = setTimeout(function () {
cleanup();
reject(createError({
message: 'Request timed out.',
code: 'REQUEST_TIMEOUT'
}));
}, 15 * 1000);
var listener = ['message', function (_ref2) {
var origin = _ref2.origin,
data = _ref2.data;
var timeoutId = setTimeout(function () {
cleanup();
reject(createError({ message: 'Request timed out.', code: 'REQUEST_TIMEOUT' }));
}, 15 * 1000);
if (origin !== postMessageOrigin) {
return;
}
var listener = ['message', function (_ref2) {
var origin = _ref2.origin,
data = _ref2.data;
if (!data || data.state !== CUSTOMER_AUTH_FOOTPRINT) {
return;
}
if (origin !== postMessageOrigin && origin !== legacyPostMessageOrigin) {
return;
}
clearTimeout(timeoutId);
cleanup();
fold(function (err) {
return reject(createError(err));
}, resolve, parseToken(data, {
license: license
}));
}, false];
clearTimeout(timeoutId);
cleanup();
fold(function (err) {
return reject(createError(err));
}, resolve, parseToken(data, { license: license }));
}, false];
(_window2 = window).addEventListener.apply(_window2, listener);
appendBodyChild(iframe);
});
(_window2 = window).addEventListener.apply(_window2, listener);
getRoot().then(function (body) {
body.appendChild(iframe);
});
});
});
var validateConfig = (function (_ref) {
var license = _ref.license,
clientId = _ref.clientId;
var license = _ref.license,
clientId = _ref.clientId;
if (typeof license !== 'number' || typeof clientId !== 'string') {
throw new Error('You need to pass valid configuration object: { license, clientId }.');
}
if (typeof license !== 'number' || typeof clientId !== 'string') {
throw new Error('You need to pass valid configuration object: { license, clientId }.');
}
});
var isExpiredToken = function isExpiredToken(token) {
return Date.now() >= token.creationDate + token.expiresIn;
return Date.now() >= token.creationDate + token.expiresIn;
};
var withDefaults = function withDefaults(_ref) {
var _ref$uniqueGroups = _ref.uniqueGroups,
uniqueGroups = _ref$uniqueGroups === undefined ? false : _ref$uniqueGroups,
rest = objectWithoutProperties(_ref, ['uniqueGroups']);
return _extends({ uniqueGroups: uniqueGroups }, rest);
var _ref$uniqueGroups = _ref.uniqueGroups,
uniqueGroups = _ref$uniqueGroups === void 0 ? false : _ref$uniqueGroups,
rest = _objectWithoutPropertiesLoose(_ref, ["uniqueGroups"]);
return _extends({
uniqueGroups: uniqueGroups
}, rest);
};
var auth = (function (inputConfig) {
var env = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'production';
var auth = (function (inputConfig, env) {
validateConfig(inputConfig);
var config = withDefaults(inputConfig);
var pendingTokenRequest;
var cachedToken;
var cacheKey = "@@lc_auth_token:" + config.license + (config.uniqueGroups ? ":" + config.group : '');
var retrievingToken = storage$1.getItem(cacheKey).then(function (token) {
if (retrievingToken === null) {
return;
}
validateConfig(inputConfig);
var config = withDefaults(inputConfig);
retrievingToken = null;
var pendingTokenRequest = void 0;
var cachedToken = void 0;
var cacheKey = '' + "@@lc_auth_token:" + config.license + (config.uniqueGroups ? ':' + config.group : '');
if (!token) {
return;
}
var retrievingToken = storage$1.getItem(cacheKey).then(function (token) {
if (retrievingToken === null) {
return;
}
cachedToken = JSON.parse(token);
});
var auth = Object.freeze({
getFreshToken: function getFreshToken() {
pendingTokenRequest = fetchToken(config, env).then(function (token) {
pendingTokenRequest = null;
storage$1.setItem(cacheKey, JSON.stringify(token));
cachedToken = token;
return token;
}).catch(function (err) {
pendingTokenRequest = null;
throw err;
});
return pendingTokenRequest;
},
getToken: function getToken() {
if (pendingTokenRequest) {
return pendingTokenRequest;
}
retrievingToken = null;
if (cachedToken && !isExpiredToken(cachedToken)) {
return Promise.resolve(cachedToken);
}
if (!token) {
return;
}
if (retrievingToken) {
return retrievingToken.then(auth.getToken);
}
cachedToken = JSON.parse(token);
});
var auth = Object.freeze({
getFreshToken: function getFreshToken() {
pendingTokenRequest = fetchToken(config, env).then(function (token) {
pendingTokenRequest = null;
storage$1.setItem(cacheKey, JSON.stringify(token));
cachedToken = token;
return token;
}).catch(function (err) {
pendingTokenRequest = null;
throw err;
});
return pendingTokenRequest;
},
getToken: function getToken() {
if (pendingTokenRequest) {
return pendingTokenRequest;
}
if (cachedToken && !isExpiredToken(cachedToken)) {
return Promise.resolve(cachedToken);
}
if (retrievingToken) {
return retrievingToken.then(auth.getToken);
}
return auth.getFreshToken();
},
invalidate: function invalidate() {
storage$1.removeItem(cacheKey);
cachedToken = null;
retrievingToken = null;
}
});
return auth;
return auth.getFreshToken();
},
invalidate: function invalidate() {
storage$1.removeItem(cacheKey);
cachedToken = null;
retrievingToken = null;
}
});
return auth;
});

@@ -385,0 +417,0 @@

@@ -1,1 +0,1 @@

!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t(e.CustomerAuth={})}(this,function(e){"use strict";var n="__test_storage_support__",t=function(){var n=Object.defineProperties({},{getItem:{value:function(e){return n[e]||null}},setItem:{value:function(e,t){try{n[e]=t+""}catch(e){}}},removeItem:{value:function(e){delete n[e]}},clear:{value:function(){Object.keys(n).forEach(n.removeItem)}},key:{value:function(e){return Object.keys(n)[e]||null}},length:{get:function(){return Object.keys(n).length}}});return n}(),o=function(){var e=0<arguments.length&&void 0!==arguments[0]?arguments[0]:"local";try{var t=window[e+"Storage"];return t.setItem(n,!0),t.getItem(n),t.removeItem(n),!0}catch(e){return!1}}()?window.localStorage:t,a=function(t,n){return new Promise(function(e){return e(o.setItem(t,n))})},s=function(t){return new Promise(function(e){return e(o.getItem(t))})},l=function(t){return new Promise(function(e){return e(o.removeItem(t))})},m=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(e[o]=n[o])}return e};var v=function(e){return(t=e,Object.keys(t).map(function(e){return[e,t[e]]})).map(function(e){return e.map(encodeURIComponent).join("=")}).join("&");var t},h=/[^:]+:\/\/[^(\/|\?)\s]+/,r=function(e){return{type:"error",error:e}},f=function(e,t){return e.identity_exception?r({code:"SSO_IDENTITY_EXCEPTION",message:e.identity_exception}):e.oauth_exception?r({code:"SSO_OAUTH_EXCEPTION",message:e.oauth_exception}):(o=t.license,{type:"ok",value:{accessToken:(n=e).access_token,entityId:n.entity_id,expiresIn:1e3*n.expires_in,tokenType:n.token_type,creationDate:Date.now(),license:o}});var n,o},i="https://cdn.chatio-static.com",y=function(e,t){var n,o,r,i,c,u,a,s,l,d,p,f=document.createElement("iframe");return f.style.display="none",f.setAttribute("src",(n=m({},e,{redirectUri:(d=location+"",p=d.match(h),(p&&p[0])+location.pathname)}),o=null,("production"===(r=t)?"https://accounts.livechatinc.com":"https://accounts.livechatinc.com".replace("accounts.","accounts."+r+"."))+((i=n).uniqueGroups?"/licence/g"+i.license+"_"+i.group:"")+"/customer?"+v((u=o,a=(c=n).clientId,s=c.redirectUri,(l={}).license_id=c.license,l.flow="button",l.response_type="token",l.client_id=a,l.redirect_uri=s,l.post_message_uri=s,u&&(l.state=u),l)))),f},g=function(e){var t=e.code,n=Error(e.message);return n.code=t,n},d=function(t,r){var e,n,l=t.license,d="production"===(e=r)?"https://cdn.livechat-static.com":"https://cdn.livechat-static.com".replace("cdn.","cdn-"+e+"."),p="production"===(n=r)?i:i.replace("cdn.","cdn-"+n+".");return new Promise(function(c,u){var e,n=y(t,r),a=function(){var e,t;(t=n).parentNode&&t.parentNode.removeChild(t),(e=window).removeEventListener.apply(e,o)},s=setTimeout(function(){a(),u(g({message:"Request timed out.",code:"REQUEST_TIMEOUT"}))},15e3),o=["message",function(e){var t,n,o,r=e.origin,i=e.data;r!==d&&r!==p||(clearTimeout(s),a(),t=function(e){return u(g(e))},n=c,"ok"===(o=f(i,{license:l})).type?n(o.value):t(o.error))},!1];(e=window).addEventListener.apply(e,o),function e(t){document.body?document.body.appendChild(t):setTimeout(e,100,t)}(n)})},p=function(e){if("number"!=typeof e.license||"string"!=typeof e.clientId)throw Error("You need to pass valid configuration object: { license, clientId }.")},_=function(e){return Date.now()>=e.creationDate+e.expiresIn},I=function(e){var t=e.uniqueGroups,n=void 0!==t&&t,o=function(e,t){var n={};for(var o in e)t.indexOf(o)<0&&Object.prototype.hasOwnProperty.call(e,o)&&(n[o]=e[o]);return n}(e,["uniqueGroups"]);return m({uniqueGroups:n},o)};e.default=function(e){var t=1<arguments.length&&void 0!==arguments[1]?arguments[1]:"production";p(e);var n=I(e),o=void 0,r=void 0,i="@@lc_auth_token:"+n.license+(n.uniqueGroups?":"+n.group:""),c=s(i).then(function(e){null!==c&&(c=null,e&&(r=JSON.parse(e)))}),u=Object.freeze({getFreshToken:function(){return o=d(n,t).then(function(e){return o=null,a(i,JSON.stringify(e)),r=e}).catch(function(e){throw o=null,e})},getToken:function(){return o||(r&&!_(r)?Promise.resolve(r):c?c.then(u.getToken):u.getFreshToken())},invalidate:function(){l(i),c=r=null}});return u},e.isExpiredToken=_,e.validateConfig=p,Object.defineProperty(e,"__esModule",{value:!0})});
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t(e.CustomerAuth={})}(this,function(e){"use strict";function d(){return(d=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(e[o]=n[o])}return e}).apply(this,arguments)}var n="__test_storage_support__",t=function(){var n=Object.defineProperties({},{getItem:{value:function(e){return n[e]||null}},setItem:{value:function(e,t){try{n[e]=t+""}catch(e){}}},removeItem:{value:function(e){delete n[e]}},clear:{value:function(){Object.keys(n).forEach(n.removeItem)}},key:{value:function(e){return Object.keys(n)[e]||null}},length:{get:function(){return Object.keys(n).length}}});return n}(),o=function(){var e=0<arguments.length&&void 0!==arguments[0]?arguments[0]:"local";try{var t=window[e+"Storage"];return t.setItem(n,!0),t.getItem(n),t.removeItem(n),!0}catch(e){return!1}}()?window.localStorage:t,a=function(t,n){return new Promise(function(e){return e(o.setItem(t,n))})},s=function(t){return new Promise(function(e){return e(o.getItem(t))})},l=function(t){return new Promise(function(e){return e(o.removeItem(t))})};var m=function(e){return(t=e,Object.keys(t).map(function(e){return[e,t[e]]})).map(function(e){return e.map(encodeURIComponent).join("=")}).join("&");var t},v=/[^:]+:\/\/[^(\/|\?)\s]+/,r=function(e){return{type:"error",error:e}},f=function(e,t){return e.identity_exception?r({code:"SSO_IDENTITY_EXCEPTION",message:e.identity_exception}):e.oauth_exception?r({code:"SSO_OAUTH_EXCEPTION",message:e.oauth_exception}):(o=t.license,{type:"ok",value:{accessToken:(n=e).access_token,entityId:n.entity_id,expiresIn:1e3*n.expires_in,tokenType:n.token_type,creationDate:Date.now(),license:o}});var n,o},i="https://accounts.livechatinc.com",h="@livechat/customer-auth",p=function(e,t){var n,o,r,i,u,c,a,s,l,f,p=document.createElement("iframe");return p.style.display="none",p.setAttribute("src",(n=d({},e,{redirectUri:(l=location+"",f=l.match(v),(f&&f[0])+location.pathname)}),o=h,("production"===(r=t)?"https://accounts.livechatinc.com":"https://accounts.livechatinc.com".replace("accounts.","accounts."+r+"."))+((i=n).uniqueGroups?"/licence/g"+i.license+"_"+i.group:"")+"/customer?"+m((u=d({},n,{state:o}),s={license_id:u.license,flow:"button",response_type:"token",client_id:u.clientId,redirect_uri:c=u.redirectUri,post_message_uri:c},(a=u.state)&&(s.state=a),s)))),p},y=function(e){var t=e.code,n=Error(e.message);return n.code=t,n},g=function(t,r){var e,s=t.license,l="production"===(e=r)?i:i.replace("accounts.","accounts."+e+".");return new Promise(function(i,u){var e,n=p(t,r),c=function(){var e,t;(t=n).parentNode&&t.parentNode.removeChild(t),(e=window).removeEventListener.apply(e,o)},a=setTimeout(function(){c(),u(y({message:"Request timed out.",code:"REQUEST_TIMEOUT"}))},15e3),o=["message",function(e){var t,n,o,r=e.data;e.origin===l&&(r&&r.state===h&&(clearTimeout(a),c(),t=function(e){return u(y(e))},n=i,"ok"===(o=f(r,{license:s})).type?n(o.value):t(o.error)))},!1];(e=window).addEventListener.apply(e,o),new Promise(function(t){!function e(){document.body?t(document.body):setTimeout(e,100)}()}).then(function(e){e.appendChild(n)})})},_=function(e){if("number"!=typeof e.license||"string"!=typeof e.clientId)throw Error("You need to pass valid configuration object: { license, clientId }.")},I=function(e){return Date.now()>=e.creationDate+e.expiresIn},O=function(e){var t=e.uniqueGroups;return d({uniqueGroups:void 0!==t&&t},function(e,t){if(null==e)return{};var n,o,r={},i=Object.keys(e);for(o=0;o<i.length;o++)t.indexOf(n=i[o])<0&&(r[n]=e[n]);return r}(e,["uniqueGroups"]))};e.default=function(e,t){_(e);var n,o,r=O(e),i="@@lc_auth_token:"+r.license+(r.uniqueGroups?":"+r.group:""),u=s(i).then(function(e){null!==u&&(u=null,e&&(o=JSON.parse(e)))}),c=Object.freeze({getFreshToken:function(){return n=g(r,t).then(function(e){return n=null,a(i,JSON.stringify(e)),o=e}).catch(function(e){throw n=null,e})},getToken:function(){return n||(o&&!I(o)?Promise.resolve(o):u?u.then(c.getToken):c.getFreshToken())},invalidate:function(){l(i),u=o=null}});return c},e.isExpiredToken=I,e.validateConfig=_,Object.defineProperty(e,"__esModule",{value:!0})});
{
"name": "@livechat/customer-auth",
"version": "0.4.0-alpha.0",
"description":
"Authorization library for connecting to LiveChat as a customer",
"version": "0.4.0-alpha.1",
"description": "Authorization library for connecting to LiveChat as a customer.",
"contributors": [

@@ -11,26 +10,27 @@ "Konrad Kruk <k.kruk@livechatinc.com>",

"license": "UNLICENSED",
"main": "dist/customer-auth.cjs.js",
"module": "dist/customer-auth.es.js",
"jsnext:main": "dist/customer-auth.es.js",
"react-native": "dist/customer-auth.rn.js",
"main": "./dist/customer-auth.cjs.js",
"module": "./dist/customer-auth.esm.js",
"react-native": "./dist/customer-auth.native.js",
"files": ["dist"],
"keywords": ["livechat", "auth", "accounts", "oauth"],
"dependencies": {
"@livechat/dom-utils": "^0.1.0",
"@livechat/isomorphic-storage": "^0.1.0",
"@livechat/mitt": "^0.1.0",
"@livechat/url-utils": "^0.1.1",
"@livechat/mitt": "^0.1.2",
"@livechat/url-utils": "^0.1.2",
"memory-web-storage": "^0.1.0"
},
"devDependencies": {
"babel-plugin-external-helpers": "^6.22.0",
"babel-plugin-transform-flow-strip-types": "^6.22.0",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.3.13",
"babel-preset-stage-2": "^6.24.1",
"lerna-alias": "^1.0.0",
"@babel/core": "^7.0.0",
"@babel/plugin-proposal-class-properties": "^7.0.0",
"@babel/plugin-syntax-dynamic-import": "^7.0.0",
"@babel/preset-env": "^7.0.0",
"@babel/preset-react": "^7.0.0",
"@babel/preset-typescript": "^7.1.0",
"lerna-alias": "3.0.3-0",
"rimraf": "^2.6.1",
"rollup": "^0.63.5",
"rollup-plugin-alias": "^1.3.1",
"rollup-plugin-babel": "^2.7.1",
"rollup-plugin-commonjs": "^8.2.1",
"rollup-plugin-babel": "^4.0.1",
"rollup-plugin-commonjs": "^9.2.0",
"rollup-plugin-dotenv": "^0.1.0",

@@ -42,5 +42,4 @@ "rollup-plugin-node-resolve": "^3.0.0",

"scripts": {
"prebuild": "rimraf es lib dist",
"prebuild": "rimraf dist",
"build": "rollup -c",
"watch": "npm run build:es -- --watch",
"prepare": "npm run build",

@@ -47,0 +46,0 @@ "prepublish": "test $(npm -v | tr . '\\n' | head -n 1) -ge '4' || exit 1"

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc