@twintag/twintag-core 0.2.230 → 0.2.232

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -801,8 +801,11 @@ class Auth {
801
801
  static callback(code, state) {
802
802
  let decodedState = JSON.parse(atob(state));
803
803
  if (decodedState.viewId) {
804
- const lsState = JSON.parse(localStorage.getItem(`${decodedState.viewId}-state`));
805
- if (lsState.isBackendAuth) {
804
+ let lsState = JSON.parse(localStorage.getItem(`${decodedState.viewId}-state`));
805
+ if (!lsState) {
806
+ lsState = JSON.parse(localStorage.getItem(`${btoa(window.origin)}-state`));
807
+ }
808
+ if (lsState === null || lsState === void 0 ? void 0 : lsState.isBackendAuth) {
806
809
  return backendauthService.handleCallback(code, decodedState);
807
810
  }
808
811
  return webAuthservice.handleCallback(code, decodedState);
@@ -2,7 +2,7 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- const auth = require('./auth-9d028a4a.js');
5
+ const auth = require('./auth-05c98744.js');
6
6
 
7
7
  /**
8
8
  * The view object represents the current active view.
@@ -3,7 +3,7 @@
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
5
  const index = require('./index-f155c6cc.js');
6
- const auth = require('./auth-9d028a4a.js');
6
+ const auth = require('./auth-05c98744.js');
7
7
 
8
8
  const twintagAuthCallbackCss = ":host{display:block}";
9
9
 
@@ -113,8 +113,11 @@ export class Auth {
113
113
  static callback(code, state) {
114
114
  let decodedState = JSON.parse(atob(state));
115
115
  if (decodedState.viewId) {
116
- const lsState = JSON.parse(localStorage.getItem(`${decodedState.viewId}-state`));
117
- if (lsState.isBackendAuth) {
116
+ let lsState = JSON.parse(localStorage.getItem(`${decodedState.viewId}-state`));
117
+ if (!lsState) {
118
+ lsState = JSON.parse(localStorage.getItem(`${btoa(window.origin)}-state`));
119
+ }
120
+ if (lsState === null || lsState === void 0 ? void 0 : lsState.isBackendAuth) {
118
121
  return backendauthService.handleCallback(code, decodedState);
119
122
  }
120
123
  return webAuthservice.handleCallback(code, decodedState);
@@ -2,4 +2,4 @@
2
2
  /**
3
3
  * The library version.
4
4
  */
5
- export const VERSION = '0.2.230';
5
+ export const VERSION = '0.2.232';
@@ -801,8 +801,11 @@ class Auth {
801
801
  static callback(code, state) {
802
802
  let decodedState = JSON.parse(atob(state));
803
803
  if (decodedState.viewId) {
804
- const lsState = JSON.parse(localStorage.getItem(`${decodedState.viewId}-state`));
805
- if (lsState.isBackendAuth) {
804
+ let lsState = JSON.parse(localStorage.getItem(`${decodedState.viewId}-state`));
805
+ if (!lsState) {
806
+ lsState = JSON.parse(localStorage.getItem(`${btoa(window.origin)}-state`));
807
+ }
808
+ if (lsState === null || lsState === void 0 ? void 0 : lsState.isBackendAuth) {
806
809
  return backendauthService.handleCallback(code, decodedState);
807
810
  }
808
811
  return webAuthservice.handleCallback(code, decodedState);
@@ -799,8 +799,11 @@ class Auth {
799
799
  static callback(code, state) {
800
800
  let decodedState = JSON.parse(atob(state));
801
801
  if (decodedState.viewId) {
802
- const lsState = JSON.parse(localStorage.getItem(`${decodedState.viewId}-state`));
803
- if (lsState.isBackendAuth) {
802
+ let lsState = JSON.parse(localStorage.getItem(`${decodedState.viewId}-state`));
803
+ if (!lsState) {
804
+ lsState = JSON.parse(localStorage.getItem(`${btoa(window.origin)}-state`));
805
+ }
806
+ if (lsState === null || lsState === void 0 ? void 0 : lsState.isBackendAuth) {
804
807
  return backendauthService.handleCallback(code, decodedState);
805
808
  }
806
809
  return webAuthservice.handleCallback(code, decodedState);
package/dist/esm/index.js CHANGED
@@ -1,5 +1,5 @@
1
- import { i as inIframe } from './auth-3611a215.js';
2
- export { A as Auth, a as AuthConfigTemplate } from './auth-3611a215.js';
1
+ import { i as inIframe } from './auth-2bcf438f.js';
2
+ export { A as Auth, a as AuthConfigTemplate } from './auth-2bcf438f.js';
3
3
 
4
4
  /**
5
5
  * The view object represents the current active view.
@@ -1,5 +1,5 @@
1
1
  import { r as registerInstance } from './index-5af90e2f.js';
2
- import { A as Auth } from './auth-3611a215.js';
2
+ import { A as Auth } from './auth-2bcf438f.js';
3
3
 
4
4
  const twintagAuthCallbackCss = ":host{display:block}";
5
5
 
@@ -1 +1 @@
1
- import{i as t}from"./p-66b7d42b.js";export{A as Auth,a as AuthConfigTemplate}from"./p-66b7d42b.js";class s{static getId(){let s=window.location.pathname.split("/");return s&&s.length>0?t()&&-1!=s.indexOf("views")?s[s.indexOf("views")+1]:s[s.length-1]:""}}export{s as View}
1
+ import{i as t}from"./p-15f24ca8.js";export{A as Auth,a as AuthConfigTemplate}from"./p-15f24ca8.js";class s{static getId(){let s=window.location.pathname.split("/");return s&&s.length>0?t()&&-1!=s.indexOf("views")?s[s.indexOf("views")+1]:s[s.length-1]:""}}export{s as View}
@@ -1 +1 @@
1
- const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~";class e{constructor(t){this.description=t}}class o extends e{}class i extends e{}class s extends e{}const n={invalid_request:class extends e{},invalid_grant:class extends s{},unauthorized_client:class extends i{},access_denied:class extends i{},unsupported_response_type:class extends i{},invalid_scope:class extends e{},server_error:class extends i{},temporarily_unavailable:class extends i{},invalid_client:class extends s{},unsupported_grant_type:class extends s{},invalid_json:class extends e{},invalid_token:class extends e{}},r={authorizationUrl:"/v1/authorize",logoutUrl:"/v1/logout",tokenUrl:"/v1/token",userInfoUrl:"/v1/userinfo",logoutRedirectParam:"post_logout_redirect_uri"},a={authorizationUrl:"/authorize",logoutUrl:"/v2/logout",tokenUrl:"/oauth/token",userInfoUrl:"/userinfo",logoutRedirectParam:"returnTo"},c={authorizationUrl:"/oauth2/v2.0/authorize",logoutUrl:"/oauth2/v2.0/logout",tokenUrl:"/oauth2/v2.0/token",userInfoUrl:"/oidc/userinfo",logoutRedirectParam:"post_logout_redirect_uri"},h={authorizationUrl:"/oauth/v2/authorization",logoutUrl:"/oauth/v2/revoke",tokenUrl:"/oauth/v2/accessToken",userInfoUrl:"/v2/me",logoutRedirectParam:"redirect_uri"};function l(){try{return window.self!==window.top}catch(t){return!0}}class u{constructor(){}getEndpoints(t,e){switch(t){case"Auth0":return a;case"Okta":return r;case"Azure":return c;case"LinkedIn":return h;default:return e||r}}assertStateAndConfigArePresent(t,e){if(!t||!e)throw console.error("state:",t,"config:",e),new Error("state or config is not set.")}hasIDTokenExpired(t){if(!t.idToken)return!0;const e=t.idToken.split(".");if(3!=e.length)return!0;const o=JSON.parse(atob(e[1]));return!o.exp||new Date>new Date(1e3*parseInt(o.exp))}}class d{constructor(){this.host=window.origin,this.state={},this._base=new u}static get Instance(){return this._instance||(this._instance=new this)}async authenticate(t,e){return this.setConfig(e,{issuer:(t=t).issuer?t.issuer:"",endpoints:{authorizationUrl:t.configDetails&&t.configDetails.AuthorizationUrl?t.configDetails.AuthorizationUrl:"",tokenUrl:t.configDetails&&t.configDetails.TokenUrl?t.configDetails.TokenUrl:"",userInfoUrl:t.configDetails&&t.configDetails.UserInfoUrl?t.configDetails.UserInfoUrl:"",logoutUrl:t.configDetails&&t.configDetails.LogoutUrl?t.configDetails.LogoutUrl:"",logoutRedirectParam:t.configDetails&&t.configDetails.LogoutRedirectParam?t.configDetails.LogoutRedirectParam:""},template:t.template?t.template:"",clientId:t.clientId?t.clientId:"",redirectUrl:this.host+"/oauth2callback",scopes:t.scopes||["openid","profile"],onAccessTokenExpiry:void 0,async onInvalidGrant(e){await e(t)}}),this.fetchAuthorizationCode(t,e)}async userInfo(t){var e,o;if(this.setConfig(t,void 0),!(null===(o=null===(e=this.state)||void 0===e?void 0:e.accessToken)||void 0===o?void 0:o.value))try{await this.exchangeAuthCodeForAccessToken(t)}catch(t){throw t}if(!this.state||!this.state.accessToken||!this.state.stateQueryParam)return null;const i=JSON.parse(atob(this.state.stateQueryParam)),s=this.getUserInfoDomain(i)+i.endpoints.userInfoUrl;let n=await fetch(s,{method:"GET",headers:{Authorization:`Bearer ${this.state.accessToken.value}`}});return await n.json()}async isLoggedIn(t){var e,o;this.setConfig(t,void 0);try{return(null===(o=null===(e=this.state)||void 0===e?void 0:e.accessToken)||void 0===o?void 0:o.value)||await this.exchangeAuthCodeForAccessToken(t),!!this.state.accessToken&&!this.isAccessTokenExpired()}catch(t){return!1}}async idToken(t){var e;if(this.setConfig(t,void 0),!(null===(e=this.state)||void 0===e?void 0:e.idToken)||this._base.hasIDTokenExpired(this.state))try{await this.exchangeAuthCodeForAccessToken(t)}catch(t){return}return this.state.idToken}async accessToken(t){var e,o,i;if(this.setConfig(t,void 0),!(null===(o=null===(e=this.state)||void 0===e?void 0:e.accessToken)||void 0===o?void 0:o.value)||this.isAccessTokenExpired())try{await this.exchangeAuthCodeForAccessToken(t)}catch(t){return}return null===(i=this.state.accessToken)||void 0===i?void 0:i.value}async logout(t,e){var o;if(this.setConfig(t,void 0),!this.state||!this.state.stateQueryParam)return;const i=JSON.parse(atob(this.state.stateQueryParam));if("LinkedIn"===i.template)throw"Not Implemented!";localStorage.removeItem(i.viewId+"-state"),localStorage.removeItem(i.viewId+"-code");const s=i.issuer+i.endpoints.logoutUrl+`?id_token_hint=${this.state.idToken}`+`&${this.getPostLogoutRedirect(i.template,e,this.state.stateQueryParam?this.state.stateQueryParam:"",null===(o=i.endpoints)||void 0===o?void 0:o.logoutRedirectParam)}`;this.state={},location.replace(s)}getPostLogoutRedirect(t,e,o,i=""){switch(t){case"Okta":return`${this.getLogoutRedirectParam(t,i)}=${encodeURIComponent(e)}/logout&state=${encodeURIComponent(o)}`;default:return`${this.getLogoutRedirectParam(t,i)}=${encodeURIComponent(e)}/logout?state=${encodeURIComponent(o)}`}}getLogoutRedirectParam(t,e){if(e)return e;switch(t){case"Auth0":return"returnTo";default:return"post_logout_redirect_uri"}}isAccessTokenExpired(){const{accessToken:t}=this.state;return Boolean(t&&new Date>=new Date(t.expiry))}async exchangeAuthCodeForAccessToken(t){const e=localStorage.getItem(t+"-code");let i;e&&(i=JSON.parse(e));let s=localStorage.getItem(t+"-state"),r={};if(s&&(r=JSON.parse(s)),!i||!r)throw"Not Authenticated!";this.state=r;let a={};if(this.state&&this.state.stateQueryParam&&(a=JSON.parse(atob(this.state.stateQueryParam))),!a.clientId)throw"Not Authenticated";if("LinkedIn"===a.template)throw"Not Implemented!";this.setConfig(a.viewId,{issuer:a.issuer,endpoints:{authorizationUrl:a.endpoints.authorizationUrl,tokenUrl:a.endpoints.tokenUrl,logoutUrl:a.endpoints.logoutUrl,userInfoUrl:a.endpoints.userInfoUrl,logoutRedirectParam:a.endpoints.logoutRedirectParam},template:a.template,clientId:a.clientId,redirectUrl:a.redirectUrl,scopes:a.scopes||["openid","profile"],onAccessTokenExpiry:void 0,async onInvalidGrant(t){await t(a)}}),this._base.assertStateAndConfigArePresent(this.state,this.config);const{authorizationCode:c=i,codeVerifier:h=""}=this.state,l=this.config,{clientId:u,onInvalidGrant:d,redirectUrl:g}=l;h?c||console.warn("No authorization grant code is being passed."):console.warn("No code verifier is being sent.");const v=l.issuer+l.endpoints.tokenUrl,p=`grant_type=authorization_code&code=${encodeURIComponent(c||"")}&redirect_uri=${encodeURIComponent(g)}&client_id=${encodeURIComponent(u)}&code_verifier=${h}`;return fetch(v,{method:"POST",body:p,headers:{"Content-Type":"application/x-www-form-urlencoded"}}).then((e=>e.json().catch((()=>({error:"invalid_json"}))).then(e.ok?({access_token:e,id_token:o,expires_in:i,refresh_token:s,scope:n})=>{let r=[];this.state.hasAuthCodeBeenExchangedForAccessToken=!0;const a={value:e,expiry:new Date(Date.now()+1e3*parseInt(i)).toString()};return this.state.accessToken=a,this.state.idToken=o,s&&(this.state.refreshToken={value:s}),n&&(r=n.split(" "),this.state.scopes=r),localStorage.setItem(t+"-state",JSON.stringify(this.state)),{token:a,scopes:r}}:({error:e,error_description:i})=>{switch(e){case"invalid_grant":d((()=>this.fetchAuthorizationCode(this.state,t)))}return Promise.reject(new(n[e]||o)(i))})))}async handleCallback(t,e){localStorage.setItem(e.viewId+"-code",JSON.stringify(t)),location.replace(window.origin+"/"+e.viewId)}async fetchAuthorizationCode(t,e){t.viewId=e,this._base.assertStateAndConfigArePresent(this.state,this.config);const o=this.config,i=(null==t?void 0:t.stateQueryParam)?t.stateQueryParam:btoa(JSON.stringify(Object.assign(Object.assign({},t),{clientId:o.clientId,issuer:o.issuer,endpoints:o.endpoints,redirectUrl:o.redirectUrl}))),{clientId:s,redirectUrl:n,scopes:r}=o,{codeChallenge:a,codeVerifier:c}=await d.generatePKCECodes();this.state={codeChallenge:a,codeVerifier:c,stateQueryParam:i,isHTTPDecoratorActive:!0},localStorage.setItem(e+"-state",JSON.stringify(this.state));const h=o.issuer+o.endpoints.authorizationUrl+"?response_type=code&"+`client_id=${encodeURIComponent(s)}&`+`redirect_uri=${encodeURIComponent(n)}&`+`scope=${encodeURIComponent(r.join(" "))}&`+`state=${this.state.stateQueryParam}&`+`code_challenge=${encodeURIComponent(a)}&code_challenge_method=S256`;l()?window.parent.location.replace(h):location.replace(h)}static generatePKCECodes(){const e=new Uint32Array(96);crypto.getRandomValues(e);const o=d.base64urlEncode(Array.from(e).map((e=>t[e%t.length])).join(""));return crypto.subtle.digest("SHA-256",(new TextEncoder).encode(o)).then((t=>{const e=new Uint8Array(t);let o="";const i=e.byteLength;for(let t=0;t<i;t++)o+=String.fromCharCode(e[t]);return o})).then(d.base64urlEncode).then((t=>({codeChallenge:t,codeVerifier:o})))}setConfig(t,e){this.recoverState(t),e&&(this.config=e,(this.config.template||this.config.endpoints)&&(this.config.endpoints=this._base.getEndpoints(this.config.template,this.config.endpoints)))}recoverState(t){return this.state=JSON.parse(localStorage.getItem(t+"-state")||"{}"),this}static base64urlEncode(t){let e=btoa(t);return e=e.replace(/\+/g,"-"),e=e.replace(/\//g,"_"),e=e.replace(/=/g,""),e}getUserInfoDomain(t){switch(t.template){case"Azure":return"https://graph.microsoft.com";case"LinkedIn":return"https://api.linkedin.com";default:return t.issuer}}}const g=d.Instance,v=class{constructor(){this.state={},this.host=window.origin,this._base=new u}static get Instance(){return this._instance||(this._instance=new this)}async authenticate(t,e){return this.setConfig(e,{arguments:t.arguments,secretId:t.secretId}),this.fetchAuthorizationCode(t,e)}async fetchAuthorizationCode(t,e){t.viewId=e,this._base.assertStateAndConfigArePresent(this.state,this.config);const o=this.config;o.arguments&&(t.arguments=o.arguments);const i=(null==t?void 0:t.stateQueryParam)?t.stateQueryParam:btoa(JSON.stringify(Object.assign({},t)));this.state={stateQueryParam:i,isHTTPDecoratorActive:!0,isBackendAuth:!0,viewId:e},localStorage.setItem(btoa(this.host)+"-state",JSON.stringify(this.state));let s=`${this.host}/${e}/auth/${t.secretId}/login?state=${this.state.stateQueryParam}`;o.arguments&&Object.entries(o.arguments).forEach((([t,e])=>{s+=`&${t}=${e}`})),l()?window.parent.location.replace(s):location.replace(s)}async userInfo(t){return this.recoverState(t),this.decode()}async isLoggedIn(t){return this.recoverState(t),!this._base.hasIDTokenExpired(this.state)&&await this.isValidToken()}async idToken(t){var e;return this.recoverState(t),null===(e=this.state)||void 0===e?void 0:e.idToken}async accessToken(t){return null}async logout(t,e){console.log(t,e)}async handleCallback(t,e){let o=localStorage.getItem(btoa(this.host)+"-state"),i={};if(o&&(i=JSON.parse(o)),!i)throw"Not Authenticated!";this.state=i,this.state.idToken=t,localStorage.setItem(btoa(this.host)+"-state",JSON.stringify(this.state)),location.replace(window.origin+"/"+e.viewId)}setConfig(t,e){this.recoverState(t),e&&(this.config=e)}recoverState(t){return this.state=JSON.parse(localStorage.getItem(btoa(this.host)+"-state")||"{}"),this}decode(){if(!this.state.idToken)return null;const t=this.state.idToken.split(".");return 3!=t.length||JSON.parse(atob(t[1]))}async isValidToken(){if(!this.state||!this.state.idToken)return!1;const t=JSON.parse(atob(this.state.stateQueryParam));let e=await fetch(`${this.host}/auth/${t.secretId}/verify-id-token?id-token=${this.state.idToken}`,{method:"GET"});return!!e.ok&&"true"==await e.text()}}.Instance;var p;!function(t){t.Okta="Okta",t.Auth0="Auth0",t.Azure="Azure",t.LinkedIn="LinkedIn"}(p||(p={}));class w{constructor(t,e){this._vid="",this._vid=t,this._authInstance=e?v:g}async isLoggedIn(){return await this._authInstance.isLoggedIn(this._vid)}async idToken(){return await this._authInstance.idToken(this._vid)}async accessToken(){return await this._authInstance.accessToken(this._vid)}async logOut(t){return await this._authInstance.logout(this._vid,t)}async userInfo(){return await this._authInstance.userInfo(this._vid)}async authenticate(t){return await this._authInstance.authenticate(t,this._vid)}static async handleCallback(t,e){return this.callback(t,e)}static callback(t,e){let o=JSON.parse(atob(e));if(o.viewId)return JSON.parse(localStorage.getItem(`${o.viewId}-state`)).isBackendAuth?v.handleCallback(t,o):g.handleCallback(t,o)}}export{w as A,p as a,l as i}
1
+ const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~";class e{constructor(t){this.description=t}}class o extends e{}class i extends e{}class s extends e{}const n={invalid_request:class extends e{},invalid_grant:class extends s{},unauthorized_client:class extends i{},access_denied:class extends i{},unsupported_response_type:class extends i{},invalid_scope:class extends e{},server_error:class extends i{},temporarily_unavailable:class extends i{},invalid_client:class extends s{},unsupported_grant_type:class extends s{},invalid_json:class extends e{},invalid_token:class extends e{}},r={authorizationUrl:"/v1/authorize",logoutUrl:"/v1/logout",tokenUrl:"/v1/token",userInfoUrl:"/v1/userinfo",logoutRedirectParam:"post_logout_redirect_uri"},a={authorizationUrl:"/authorize",logoutUrl:"/v2/logout",tokenUrl:"/oauth/token",userInfoUrl:"/userinfo",logoutRedirectParam:"returnTo"},c={authorizationUrl:"/oauth2/v2.0/authorize",logoutUrl:"/oauth2/v2.0/logout",tokenUrl:"/oauth2/v2.0/token",userInfoUrl:"/oidc/userinfo",logoutRedirectParam:"post_logout_redirect_uri"},h={authorizationUrl:"/oauth/v2/authorization",logoutUrl:"/oauth/v2/revoke",tokenUrl:"/oauth/v2/accessToken",userInfoUrl:"/v2/me",logoutRedirectParam:"redirect_uri"};function l(){try{return window.self!==window.top}catch(t){return!0}}class d{constructor(){}getEndpoints(t,e){switch(t){case"Auth0":return a;case"Okta":return r;case"Azure":return c;case"LinkedIn":return h;default:return e||r}}assertStateAndConfigArePresent(t,e){if(!t||!e)throw console.error("state:",t,"config:",e),new Error("state or config is not set.")}hasIDTokenExpired(t){if(!t.idToken)return!0;const e=t.idToken.split(".");if(3!=e.length)return!0;const o=JSON.parse(atob(e[1]));return!o.exp||new Date>new Date(1e3*parseInt(o.exp))}}class u{constructor(){this.host=window.origin,this.state={},this._base=new d}static get Instance(){return this._instance||(this._instance=new this)}async authenticate(t,e){return this.setConfig(e,{issuer:(t=t).issuer?t.issuer:"",endpoints:{authorizationUrl:t.configDetails&&t.configDetails.AuthorizationUrl?t.configDetails.AuthorizationUrl:"",tokenUrl:t.configDetails&&t.configDetails.TokenUrl?t.configDetails.TokenUrl:"",userInfoUrl:t.configDetails&&t.configDetails.UserInfoUrl?t.configDetails.UserInfoUrl:"",logoutUrl:t.configDetails&&t.configDetails.LogoutUrl?t.configDetails.LogoutUrl:"",logoutRedirectParam:t.configDetails&&t.configDetails.LogoutRedirectParam?t.configDetails.LogoutRedirectParam:""},template:t.template?t.template:"",clientId:t.clientId?t.clientId:"",redirectUrl:this.host+"/oauth2callback",scopes:t.scopes||["openid","profile"],onAccessTokenExpiry:void 0,async onInvalidGrant(e){await e(t)}}),this.fetchAuthorizationCode(t,e)}async userInfo(t){var e,o;if(this.setConfig(t,void 0),!(null===(o=null===(e=this.state)||void 0===e?void 0:e.accessToken)||void 0===o?void 0:o.value))try{await this.exchangeAuthCodeForAccessToken(t)}catch(t){throw t}if(!this.state||!this.state.accessToken||!this.state.stateQueryParam)return null;const i=JSON.parse(atob(this.state.stateQueryParam)),s=this.getUserInfoDomain(i)+i.endpoints.userInfoUrl;let n=await fetch(s,{method:"GET",headers:{Authorization:`Bearer ${this.state.accessToken.value}`}});return await n.json()}async isLoggedIn(t){var e,o;this.setConfig(t,void 0);try{return(null===(o=null===(e=this.state)||void 0===e?void 0:e.accessToken)||void 0===o?void 0:o.value)||await this.exchangeAuthCodeForAccessToken(t),!!this.state.accessToken&&!this.isAccessTokenExpired()}catch(t){return!1}}async idToken(t){var e;if(this.setConfig(t,void 0),!(null===(e=this.state)||void 0===e?void 0:e.idToken)||this._base.hasIDTokenExpired(this.state))try{await this.exchangeAuthCodeForAccessToken(t)}catch(t){return}return this.state.idToken}async accessToken(t){var e,o,i;if(this.setConfig(t,void 0),!(null===(o=null===(e=this.state)||void 0===e?void 0:e.accessToken)||void 0===o?void 0:o.value)||this.isAccessTokenExpired())try{await this.exchangeAuthCodeForAccessToken(t)}catch(t){return}return null===(i=this.state.accessToken)||void 0===i?void 0:i.value}async logout(t,e){var o;if(this.setConfig(t,void 0),!this.state||!this.state.stateQueryParam)return;const i=JSON.parse(atob(this.state.stateQueryParam));if("LinkedIn"===i.template)throw"Not Implemented!";localStorage.removeItem(i.viewId+"-state"),localStorage.removeItem(i.viewId+"-code");const s=i.issuer+i.endpoints.logoutUrl+`?id_token_hint=${this.state.idToken}`+`&${this.getPostLogoutRedirect(i.template,e,this.state.stateQueryParam?this.state.stateQueryParam:"",null===(o=i.endpoints)||void 0===o?void 0:o.logoutRedirectParam)}`;this.state={},location.replace(s)}getPostLogoutRedirect(t,e,o,i=""){switch(t){case"Okta":return`${this.getLogoutRedirectParam(t,i)}=${encodeURIComponent(e)}/logout&state=${encodeURIComponent(o)}`;default:return`${this.getLogoutRedirectParam(t,i)}=${encodeURIComponent(e)}/logout?state=${encodeURIComponent(o)}`}}getLogoutRedirectParam(t,e){if(e)return e;switch(t){case"Auth0":return"returnTo";default:return"post_logout_redirect_uri"}}isAccessTokenExpired(){const{accessToken:t}=this.state;return Boolean(t&&new Date>=new Date(t.expiry))}async exchangeAuthCodeForAccessToken(t){const e=localStorage.getItem(t+"-code");let i;e&&(i=JSON.parse(e));let s=localStorage.getItem(t+"-state"),r={};if(s&&(r=JSON.parse(s)),!i||!r)throw"Not Authenticated!";this.state=r;let a={};if(this.state&&this.state.stateQueryParam&&(a=JSON.parse(atob(this.state.stateQueryParam))),!a.clientId)throw"Not Authenticated";if("LinkedIn"===a.template)throw"Not Implemented!";this.setConfig(a.viewId,{issuer:a.issuer,endpoints:{authorizationUrl:a.endpoints.authorizationUrl,tokenUrl:a.endpoints.tokenUrl,logoutUrl:a.endpoints.logoutUrl,userInfoUrl:a.endpoints.userInfoUrl,logoutRedirectParam:a.endpoints.logoutRedirectParam},template:a.template,clientId:a.clientId,redirectUrl:a.redirectUrl,scopes:a.scopes||["openid","profile"],onAccessTokenExpiry:void 0,async onInvalidGrant(t){await t(a)}}),this._base.assertStateAndConfigArePresent(this.state,this.config);const{authorizationCode:c=i,codeVerifier:h=""}=this.state,l=this.config,{clientId:d,onInvalidGrant:u,redirectUrl:g}=l;h?c||console.warn("No authorization grant code is being passed."):console.warn("No code verifier is being sent.");const v=l.issuer+l.endpoints.tokenUrl,w=`grant_type=authorization_code&code=${encodeURIComponent(c||"")}&redirect_uri=${encodeURIComponent(g)}&client_id=${encodeURIComponent(d)}&code_verifier=${h}`;return fetch(v,{method:"POST",body:w,headers:{"Content-Type":"application/x-www-form-urlencoded"}}).then((e=>e.json().catch((()=>({error:"invalid_json"}))).then(e.ok?({access_token:e,id_token:o,expires_in:i,refresh_token:s,scope:n})=>{let r=[];this.state.hasAuthCodeBeenExchangedForAccessToken=!0;const a={value:e,expiry:new Date(Date.now()+1e3*parseInt(i)).toString()};return this.state.accessToken=a,this.state.idToken=o,s&&(this.state.refreshToken={value:s}),n&&(r=n.split(" "),this.state.scopes=r),localStorage.setItem(t+"-state",JSON.stringify(this.state)),{token:a,scopes:r}}:({error:e,error_description:i})=>{switch(e){case"invalid_grant":u((()=>this.fetchAuthorizationCode(this.state,t)))}return Promise.reject(new(n[e]||o)(i))})))}async handleCallback(t,e){localStorage.setItem(e.viewId+"-code",JSON.stringify(t)),location.replace(window.origin+"/"+e.viewId)}async fetchAuthorizationCode(t,e){t.viewId=e,this._base.assertStateAndConfigArePresent(this.state,this.config);const o=this.config,i=(null==t?void 0:t.stateQueryParam)?t.stateQueryParam:btoa(JSON.stringify(Object.assign(Object.assign({},t),{clientId:o.clientId,issuer:o.issuer,endpoints:o.endpoints,redirectUrl:o.redirectUrl}))),{clientId:s,redirectUrl:n,scopes:r}=o,{codeChallenge:a,codeVerifier:c}=await u.generatePKCECodes();this.state={codeChallenge:a,codeVerifier:c,stateQueryParam:i,isHTTPDecoratorActive:!0},localStorage.setItem(e+"-state",JSON.stringify(this.state));const h=o.issuer+o.endpoints.authorizationUrl+"?response_type=code&"+`client_id=${encodeURIComponent(s)}&`+`redirect_uri=${encodeURIComponent(n)}&`+`scope=${encodeURIComponent(r.join(" "))}&`+`state=${this.state.stateQueryParam}&`+`code_challenge=${encodeURIComponent(a)}&code_challenge_method=S256`;l()?window.parent.location.replace(h):location.replace(h)}static generatePKCECodes(){const e=new Uint32Array(96);crypto.getRandomValues(e);const o=u.base64urlEncode(Array.from(e).map((e=>t[e%t.length])).join(""));return crypto.subtle.digest("SHA-256",(new TextEncoder).encode(o)).then((t=>{const e=new Uint8Array(t);let o="";const i=e.byteLength;for(let t=0;t<i;t++)o+=String.fromCharCode(e[t]);return o})).then(u.base64urlEncode).then((t=>({codeChallenge:t,codeVerifier:o})))}setConfig(t,e){this.recoverState(t),e&&(this.config=e,(this.config.template||this.config.endpoints)&&(this.config.endpoints=this._base.getEndpoints(this.config.template,this.config.endpoints)))}recoverState(t){return this.state=JSON.parse(localStorage.getItem(t+"-state")||"{}"),this}static base64urlEncode(t){let e=btoa(t);return e=e.replace(/\+/g,"-"),e=e.replace(/\//g,"_"),e=e.replace(/=/g,""),e}getUserInfoDomain(t){switch(t.template){case"Azure":return"https://graph.microsoft.com";case"LinkedIn":return"https://api.linkedin.com";default:return t.issuer}}}const g=u.Instance,v=class{constructor(){this.state={},this.host=window.origin,this._base=new d}static get Instance(){return this._instance||(this._instance=new this)}async authenticate(t,e){return this.setConfig(e,{arguments:t.arguments,secretId:t.secretId}),this.fetchAuthorizationCode(t,e)}async fetchAuthorizationCode(t,e){t.viewId=e,this._base.assertStateAndConfigArePresent(this.state,this.config);const o=this.config;o.arguments&&(t.arguments=o.arguments);const i=(null==t?void 0:t.stateQueryParam)?t.stateQueryParam:btoa(JSON.stringify(Object.assign({},t)));this.state={stateQueryParam:i,isHTTPDecoratorActive:!0,isBackendAuth:!0,viewId:e},localStorage.setItem(btoa(this.host)+"-state",JSON.stringify(this.state));let s=`${this.host}/${e}/auth/${t.secretId}/login?state=${this.state.stateQueryParam}`;o.arguments&&Object.entries(o.arguments).forEach((([t,e])=>{s+=`&${t}=${e}`})),l()?window.parent.location.replace(s):location.replace(s)}async userInfo(t){return this.recoverState(t),this.decode()}async isLoggedIn(t){return this.recoverState(t),!this._base.hasIDTokenExpired(this.state)&&await this.isValidToken()}async idToken(t){var e;return this.recoverState(t),null===(e=this.state)||void 0===e?void 0:e.idToken}async accessToken(t){return null}async logout(t,e){console.log(t,e)}async handleCallback(t,e){let o=localStorage.getItem(btoa(this.host)+"-state"),i={};if(o&&(i=JSON.parse(o)),!i)throw"Not Authenticated!";this.state=i,this.state.idToken=t,localStorage.setItem(btoa(this.host)+"-state",JSON.stringify(this.state)),location.replace(window.origin+"/"+e.viewId)}setConfig(t,e){this.recoverState(t),e&&(this.config=e)}recoverState(t){return this.state=JSON.parse(localStorage.getItem(btoa(this.host)+"-state")||"{}"),this}decode(){if(!this.state.idToken)return null;const t=this.state.idToken.split(".");return 3!=t.length||JSON.parse(atob(t[1]))}async isValidToken(){if(!this.state||!this.state.idToken)return!1;const t=JSON.parse(atob(this.state.stateQueryParam));let e=await fetch(`${this.host}/auth/${t.secretId}/verify-id-token?id-token=${this.state.idToken}`,{method:"GET"});return!!e.ok&&"true"==await e.text()}}.Instance;var w;!function(t){t.Okta="Okta",t.Auth0="Auth0",t.Azure="Azure",t.LinkedIn="LinkedIn"}(w||(w={}));class p{constructor(t,e){this._vid="",this._vid=t,this._authInstance=e?v:g}async isLoggedIn(){return await this._authInstance.isLoggedIn(this._vid)}async idToken(){return await this._authInstance.idToken(this._vid)}async accessToken(){return await this._authInstance.accessToken(this._vid)}async logOut(t){return await this._authInstance.logout(this._vid,t)}async userInfo(){return await this._authInstance.userInfo(this._vid)}async authenticate(t){return await this._authInstance.authenticate(t,this._vid)}static async handleCallback(t,e){return this.callback(t,e)}static callback(t,e){let o=JSON.parse(atob(e));if(o.viewId){let e=JSON.parse(localStorage.getItem(`${o.viewId}-state`));return e||(e=JSON.parse(localStorage.getItem(`${btoa(window.origin)}-state`))),(null==e?void 0:e.isBackendAuth)?v.handleCallback(t,o):g.handleCallback(t,o)}}}export{p as A,w as a,l as i}
@@ -1 +1 @@
1
- import{r as t}from"./p-a5bd6d6a.js";import{A as a}from"./p-66b7d42b.js";const o=class{constructor(o){t(this,o);const s=window.location.search;let c,e,r=new URLSearchParams(s);s.includes("id_token=")?c=r.get("id_token"):s.includes("code=")&&(c=r.get("code")),s.includes("state=")&&(e=r.get("state")),a.handleCallback(c,e)}};o.style=":host{display:block}";export{o as twintag_auth_callback}
1
+ import{r as t}from"./p-a5bd6d6a.js";import{A as a}from"./p-15f24ca8.js";const o=class{constructor(o){t(this,o);const s=window.location.search;let c,e,r=new URLSearchParams(s);s.includes("id_token=")?c=r.get("id_token"):s.includes("code=")&&(c=r.get("code")),s.includes("state=")&&(e=r.get("state")),a.handleCallback(c,e)}};o.style=":host{display:block}";export{o as twintag_auth_callback}
@@ -1 +1 @@
1
- import{p as e,b as t}from"./p-a5bd6d6a.js";(()=>{const t=import.meta.url,a={};return""!==t&&(a.resourcesUrl=new URL(".",t).href),e(a)})().then((e=>t([["p-a4460603",[[1,"twintag-preview",{item:[1],extension:[1],showButtons:[4,"show-buttons"],previewableItem:[32],type:[32]}]]],["p-2fffdaee",[[1,"twintag-auth-callback"]]],["p-7a693673",[[1,"twintag-auth-logout"]]],["p-538b0134",[[1,"twintag-media",{first:[1],middle:[1],last:[1]}]]],["p-da1594ad",[[1,"twintag-scanner",{customCheckIcon:[1,"custom-check-icon"],targetVideoSize:[2,"target-video-size"],targetFrameRate:[2,"target-frame-rate"],zoom:[2],cropX:[2,"crop-x"],cropY:[2,"crop-y"],ocrScanner:[4,"ocr-scanner"],available:[32],frameCapture:[32],ocrIsScanning:[32]},[[2,"ocr","ocrHandler"],[2,"openCamera","openCameraHandler"],[2,"closeCamera","closeHandler"]]]]],["p-251c896d",[[1,"twintag-share",{url:[1],title:[1],subtitle:[1],closeBtn:[1,"close-btn"],copyClipboardBtn:[1,"copy-clipboard-btn"],open:[1540]},[[0,"keydown","handleKeyDown"]]]]],["p-541f059e",[[1,"twintag-spinner",{color:[513],duration:[2],name:[1]}]]],["p-630f0ec3",[[0,"pdf-error",{message:[1]}],[0,"pdf-toolbar",{url:[1],showButtons:[4,"show-buttons"],totalPages:[2,"total-pages"],currentPage:[2,"current-page"],activePage:[32]}]]],["p-065c58d7",[[0,"twintag-pdf-viewer",{canvasWidth:[2,"canvas-width"],src:[1],showButtons:[4,"show-buttons"],currentPage:[32],totalPages:[32],error:[32],pdfViewer:[32],pdfContainer:[32]},[[0,"activePageEvent","setActivePage"]]]]]],e)));
1
+ import{p as e,b as t}from"./p-a5bd6d6a.js";(()=>{const t=import.meta.url,a={};return""!==t&&(a.resourcesUrl=new URL(".",t).href),e(a)})().then((e=>t([["p-a4460603",[[1,"twintag-preview",{item:[1],extension:[1],showButtons:[4,"show-buttons"],previewableItem:[32],type:[32]}]]],["p-26fb2cc6",[[1,"twintag-auth-callback"]]],["p-7a693673",[[1,"twintag-auth-logout"]]],["p-538b0134",[[1,"twintag-media",{first:[1],middle:[1],last:[1]}]]],["p-da1594ad",[[1,"twintag-scanner",{customCheckIcon:[1,"custom-check-icon"],targetVideoSize:[2,"target-video-size"],targetFrameRate:[2,"target-frame-rate"],zoom:[2],cropX:[2,"crop-x"],cropY:[2,"crop-y"],ocrScanner:[4,"ocr-scanner"],available:[32],frameCapture:[32],ocrIsScanning:[32]},[[2,"ocr","ocrHandler"],[2,"openCamera","openCameraHandler"],[2,"closeCamera","closeHandler"]]]]],["p-251c896d",[[1,"twintag-share",{url:[1],title:[1],subtitle:[1],closeBtn:[1,"close-btn"],copyClipboardBtn:[1,"copy-clipboard-btn"],open:[1540]},[[0,"keydown","handleKeyDown"]]]]],["p-541f059e",[[1,"twintag-spinner",{color:[513],duration:[2],name:[1]}]]],["p-630f0ec3",[[0,"pdf-error",{message:[1]}],[0,"pdf-toolbar",{url:[1],showButtons:[4,"show-buttons"],totalPages:[2,"total-pages"],currentPage:[2,"current-page"],activePage:[32]}]]],["p-065c58d7",[[0,"twintag-pdf-viewer",{canvasWidth:[2,"canvas-width"],src:[1],showButtons:[4,"show-buttons"],currentPage:[32],totalPages:[32],error:[32],pdfViewer:[32],pdfContainer:[32]},[[0,"activePageEvent","setActivePage"]]]]]],e)));
@@ -1,4 +1,4 @@
1
1
  /**
2
2
  * The library version.
3
3
  */
4
- export declare const VERSION = "0.2.230";
4
+ export declare const VERSION = "0.2.232";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@twintag/twintag-core",
3
- "version": "0.2.230",
3
+ "version": "0.2.232",
4
4
  "author": "Twintag",
5
5
  "main": "dist/index.cjs.js",
6
6
  "module": "dist/index.js",