@smart-cloud/gatey-core 2.3.4 → 2.3.6

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.
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";var R=Object.defineProperty;var Z=Object.getOwnPropertyDescriptor;var ee=Object.getOwnPropertyNames;var te=Object.prototype.hasOwnProperty;var ne=(e,t)=>{for(var n in t)R(e,n,{get:t[n],enumerable:!0})},re=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of ee(t))!te.call(e,o)&&o!==n&&R(e,o,{get:()=>t[o],enumerable:!(r=Z(t,o))||r.enumerable});return e};var oe=e=>re(R({},"__esModule",{value:!0}),e);var me={};ne(me,{TEXT_DOMAIN:()=>j,clearMfaPreferences:()=>_,configureAmplify:()=>T,getAmplifyConfig:()=>E,getGateyPlugin:()=>s,getGroups:()=>x,getMfaPreferences:()=>D,getPreferredRole:()=>B,getRoles:()=>z,getScopes:()=>V,getStore:()=>g,getStoreDispatch:()=>f,getStoreSelect:()=>G,getUserAttributes:()=>k,initializeGatey:()=>ye,isAuthenticated:()=>M,isInGroup:()=>W,loadAuthSession:()=>y,loadMFAPreferences:()=>L,loadUserAttributes:()=>N,login:()=>H,logout:()=>b,observeStore:()=>C,resolveGateyTarget:()=>d,sanitizeAuthenticatorConfig:()=>O,store:()=>fe,waitForGateyReady:()=>U});module.exports=oe(me);var a=require("aws-amplify/api");function s(){return globalThis.WpSuite?.plugins?.gatey}function d(e){let t=e?.trim();if(t)try{if(/^[a-z][a-z\d+.-]*:/i.test(t))return new URL(t).toString();let r=s()?.siteUrl?.trim()||window.location.href,o=t.startsWith("/")?t.replace(/^\/+/,""):t;return new URL(o,r).toString()}catch{return t}}async function U(e=8e3){let t=s();if(t?.status!=="available"){if(t?.status==="error")throw new Error("Gatey failed");await new Promise((n,r)=>{let o=()=>l(n),m=()=>l(()=>r(new Error("Gatey failed"))),l=u=>{window.removeEventListener("wpsuite:gatey:ready",o),window.removeEventListener("wpsuite:gatey:error",m),S&&clearTimeout(S),u()};window.addEventListener("wpsuite:gatey:ready",o,{once:!0}),window.addEventListener("wpsuite:gatey:error",m,{once:!0});let S=e?window.setTimeout(()=>l(()=>r(new Error("Gatey timeout"))),e):0})}}async function g(e=1e4){await U(e);let n=s()?.cognito?.store;if(!n)throw new Error("Gatey store is not available");return n}var F=require("aws-amplify"),i=require("aws-amplify/auth");var K=require("aws-amplify/auth"),v=require("aws-amplify/utils"),c=require("@wordpress/data"),X=require("@smart-cloud/wpsuite-core");var P="gatey_account",j="gatey";var I;typeof WpSuite<"u"?I=WpSuite.siteSettings:I={};var w=e=>{e?.username?window.localStorage.setItem(P,JSON.stringify(e)):window.localStorage.removeItem(P)},A=async e=>{let t=JSON.parse(window.localStorage.getItem(P)??"{}"),n=!1;if(t?.username)try{let r=await(0,K.fetchAuthSession)();r?.tokens?.accessToken?.payload?.exp&&r.tokens.accessToken.payload.exp>new Date().getTime()/1e3&&(n=!0)}catch(r){console.error(r)}else try{t=await Y(!1),t?.username&&(w(t),t.loaded=!0,n=!0)}catch(r){console.error(r)}return!n&&t?.username&&(w({}),g().then(async r=>{await b(e?.signOutHook),f(r).clearAccount()})),t},ie=async e=>{let t=window.location.hostname.toLowerCase().split(":")[0],n=s();if(!n)throw new Error("Gatey plugin is not available");let r=d(n.settings?.signInPage)??window.location.origin,o=n.settings?.secondaryUserPoolDomains&&t.toLowerCase().match(n.settings.secondaryUserPoolDomains.toLowerCase())&&n.settings?.userPoolConfigurations.secondary?.Auth?.Cognito?.userPoolId?n.settings?.userPoolConfigurations.secondary:n.settings?.userPoolConfigurations.default,m={Auth:{Cognito:{userPoolClientId:"",userPoolId:"",identityPoolId:"",...o.Auth?.Cognito,loginWith:{oauth:{domain:"",scopes:[],responseType:"code",...o.Auth?.Cognito?.loginWith?.oauth,redirectSignIn:[r],redirectSignOut:[r]}}}},API:{...o.API,REST:{...o.API?.REST,admin:{endpoint:n.restUrl}}}},l=e?.apiConfigurations?.secondary?.domains&&t.toLowerCase().match(e.apiConfigurations.secondary?.domains.toLowerCase())&&e.apiConfigurations?.secondary?.apis?.length?e.apiConfigurations.secondary:e?.apiConfigurations?.default;l?.apis?.forEach(u=>{let h=m.API?.REST;h&&(h[u.name]={endpoint:u.endpoint,region:u.region})}),T(m,{API:{REST:{headers:async u=>{let h=l?.apis?.find(p=>p.name===u.apiName);if(u.apiName==="admin"||h?.authorization==="ID_TOKEN"||h?.authorization==="ACCESS_TOKEN")try{let p=await y();if(p?.tokens?.idToken&&p?.tokens?.accessToken)return{Authorization:`Bearer ${u.apiName==="admin"||h?.authorization==="ID_TOKEN"?p.tokens.idToken.toString():p.tokens.accessToken.toString()}`}}catch(p){console.error(p),g().then(Q=>{f(Q).clearAccount()})}return{}}}}})},se=async()=>{let e=s();if(!e)throw new Error("Gatey plugin is not available");let t=null;return e.settings.customTranslationsUrl&&(t=await fetch(e.settings.customTranslationsUrl+(e.settings.customTranslationsUrl.includes("?")?"&":"?")+"t="+I.lastUpdate).then(n=>n.ok?n.text():null).then(n=>n?JSON.parse(n):null).catch(()=>null)),t??null},O=e=>{let t=e&&typeof e=="object"?e:{},n={customProviders:Array.isArray(t.customProviders)?t.customProviders:[],formFields:Array.isArray(t.formFields)?t.formFields:[],apiConfigurations:typeof t.apiConfigurations=="object"&&t.apiConfigurations?t.apiConfigurations:{default:{apis:[]}}};return typeof t.subscriptionType=="string"&&(n.subscriptionType=t.subscriptionType),n},ae=async()=>{let e=O(await(0,X.getConfig)("gatey"));ie(e);let t=window.location.hostname.toLowerCase().split(":")[0],n=e?.apiConfigurations?.secondary?.domains&&t.toLowerCase().match(e.apiConfigurations.secondary?.domains.toLowerCase())&&e.apiConfigurations?.secondary?.apis?.length?e.apiConfigurations.secondary:e?.apiConfigurations?.default,r=await A(n),o=await se();return{config:e,amplifyConfig:{},account:r,signedIn:!!r?.username&&!r.loaded,nextUrl:void 0,language:void 0,direction:void 0,customTranslations:o,reloadAuthSession:0,reloadUserAttributes:0,reloadMFAPreferences:0}},ue={setAmplifyConfig(e){return{type:"SET_AMPLIFY_CONFIG",amplifyConfig:e}},setAccount(e){return{type:"SET_ACCOUNT",account:e}},clearAccount(){return{type:"CLEAR_ACCOUNT"}},setSignedIn(e){return{type:"SET_SIGNED_IN",signedIn:e}},setNextUrl(e){return{type:"SET_NEXT_URL",nextUrl:e}},setLanguage(e){return!e||e==="system"?v.I18n.setLanguage(""):v.I18n.setLanguage(e),{type:"SET_LANGUAGE",language:e}},setDirection(e){return{type:"SET_DIRECTION",direction:e}},reloadAuthSession(){return{type:"RELOAD_AUTH_SESSION"}},reloadUserAttributes(){return{type:"RELOAD_USER_ATTRIBUTES"}},reloadMFAPreferences(){return{type:"RELOAD_MFA_PREFERENCE"}}},ce={getAmplifyConfig(e){return e.amplifyConfig},getAccount(e){return e.account},getNextUrl(e){return e.nextUrl},isSignedIn(e){return e.signedIn},getConfig(e){return e.config},getCustomTranslations(e){return e.customTranslations},getLanguage(e){return e.language},getDirection(e){return e.direction},getState(e){return e}},ge={},f=e=>(0,c.dispatch)(e),G=e=>(0,c.select)(e),J=async()=>{let e=await ae(),t=(0,c.createReduxStore)("smartcloud/gatey",{reducer(n=e,r){switch(r.type){case"SET_AMPLIFY_CONFIG":return{...n,amplifyConfig:r.amplifyConfig};case"SET_ACCOUNT":return w(r.account),{...n,account:r.account};case"CLEAR_ACCOUNT":return w({}),{...n,account:{}};case"RELOAD_AUTH_SESSION":{let o=Math.random();return{...n,reloadAuthSession:n.reloadAuthSession!==o?o:o+1}}case"RELOAD_USER_ATTRIBUTES":{let o=Math.random();return{...n,reloadUserAttributes:n.reloadUserAttributes!==o?o:o+1}}case"RELOAD_MFA_PREFERENCE":{let o=Math.random();return{...n,reloadMFAPreferences:n.reloadMFAPreferences!==o?o:o+1}}case"SET_SIGNED_IN":return{...n,signedIn:r.signedIn};case"SET_NEXT_URL":return{...n,nextUrl:r.nextUrl};case"SET_LANGUAGE":return{...n,language:r.language};case"SET_DIRECTION":return{...n,direction:r.direction}}return n},actions:ue,selectors:ce,resolvers:ge});return(0,c.register)(t),t},C=(e,t,n)=>{let r;function o(){let l=G(e).getState(),S=t(l);if(S!==r){let u=r;r=S,n(r,u)}}let m=(0,c.subscribe)(o,e);return o(),m};var E=()=>F.Amplify.getConfig(),T=(e,t)=>{F.Amplify.configure(e,t)},y=e=>(0,i.fetchAuthSession)(e),N=()=>(0,i.fetchUserAttributes)(),L=()=>(0,i.fetchMFAPreference)(),Y=async(e=!0)=>{let t=e?await A():{};if(t?.username)return t;try{if((await(0,i.fetchAuthSession)()).tokens)return{username:(await(0,i.getCurrentUser)()).username,userAttributes:await N(),mfaPreferences:await L()}}catch(n){console.error(n);try{await(0,i.signOut)()}catch{}}return{}},_=async()=>{await(0,i.updateMFAPreference)({totp:"DISABLED"})},q=()=>A().then(e=>e?.username),k=()=>A().then(e=>e?.userAttributes),D=()=>A().then(e=>e?.mfaPreferences),M=()=>A().then(e=>!!e?.username),W=e=>x().then(t=>t?.includes(e)||!1),x=()=>y().then(e=>e.tokens?.idToken?.payload["cognito:groups"]instanceof Array?e.tokens.idToken.payload["cognito:groups"].map(t=>t):[]).catch(e=>{console.error(e)}),z=async()=>y().then(e=>e.tokens?.idToken?.payload["cognito:roles"]instanceof Array?e.tokens.idToken.payload["cognito:roles"].map(t=>t).map(t=>t.substring(t.indexOf("/")+1)):[]).catch(e=>{console.error(e)}),B=async()=>y().then(e=>{if(!e.tokens?.idToken?.payload["cognito:preferred_role"])return;let t=e.tokens.idToken.payload["cognito:preferred_role"];return t.substring(t.indexOf("/")+1)}).catch(e=>{console.error(e)}),V=()=>y().then(e=>e.tokens?.accessToken.payload.scope?.split(" ")??[]).catch(e=>{console.error(e)}),H=async e=>{let t,n=s();if(!n)throw new Error("Gatey plugin is not available");return n.settings.integrateWpLogin&&n.restUrl?.startsWith("http")&&(t=await n.cognito.post({apiName:"admin",path:"/login"}).response.then(o=>o.body.json()).then(o=>{if(o instanceof Object&&"redirect"in o)return o?.redirect}).catch(o=>{console.error(o)})),e&&await n.cognito.get({apiName:e.apiName,path:e.path,options:e.options}).response.catch(r=>console.error(r)),d(n.settings.redirectSignIn)??t},b=async e=>{let t=s();if(!t)throw new Error("Gatey plugin is not available");let n;t.settings.integrateWpLogin&&(n=await t.cognito.get({apiName:"admin",path:"/logout"}).response.then(r=>r.body.json()).then(r=>{if(r instanceof Object&&"redirect"in r)return r?.redirect}).catch(r=>{console.error(r)})),e&&await t.cognito.get({apiName:e.apiName,path:e.path,options:e.options}).response.catch(r=>console.error(r));try{await(0,i.signOut)()}catch{}return d(t.settings.redirectSignOut)??n??d(t.settings.signInPage)??"/"};var $=require("@smart-cloud/wpsuite-core");var le=()=>{g().then(e=>{C(e,t=>t.nextUrl,async t=>{t&&window.location.assign(t)}),f(e).clearAccount()}).catch(e=>{console.error("Gatey signOut error:",e)})},pe=e=>{g().then(t=>{f(t).setLanguage(e??"en")}).catch(t=>{console.error("Gatey setLanguage error:",t)})},de=e=>{g().then(t=>{f(t).setDirection(e??"auto")}).catch(t=>{console.error("Gatey setDirection error:",t)})};var fe=async()=>g(),ye=()=>{let e=globalThis.WpSuite,t=s();if(!t)throw new Error("Gatey plugin is not available");(0,$.attachDefaultPluginRuntime)(t),t.status=t.status??"initializing";let n=J();return t.cognito={store:n,observeStore:C,setLanguage:pe,setDirection:de,getAmplifyConfig:E,isAuthenticated:M,isInGroup:W,getUsername:q,getUserAttributes:k,getMfaPreferences:D,clearMfaPreferences:_,getGroups:x,getRoles:z,getPreferredRole:B,getScopes:V,signOut:le,get:a.get,post:a.post,put:a.put,del:a.del,head:a.head,patch:a.patch},n.then(()=>{t.status="available",e?.events?.emit("wpsuite:gatey:ready",{key:t.key,version:t.version})}).catch(r=>{t.status="error",e?.events?.emit("wpsuite:gatey:error",{key:t.key,error:String(r)})}),t};0&&(module.exports={TEXT_DOMAIN,clearMfaPreferences,configureAmplify,getAmplifyConfig,getGateyPlugin,getGroups,getMfaPreferences,getPreferredRole,getRoles,getScopes,getStore,getStoreDispatch,getStoreSelect,getUserAttributes,initializeGatey,isAuthenticated,isInGroup,loadAuthSession,loadMFAPreferences,loadUserAttributes,login,logout,observeStore,resolveGateyTarget,sanitizeAuthenticatorConfig,store,waitForGateyReady});
1
+ "use strict";var x=Object.defineProperty;var te=Object.getOwnPropertyDescriptor;var re=Object.getOwnPropertyNames;var ne=Object.prototype.hasOwnProperty;var oe=(e,t)=>{for(var r in t)x(e,r,{get:t[r],enumerable:!0})},ie=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of re(t))!ne.call(e,o)&&o!==r&&x(e,o,{get:()=>t[o],enumerable:!(n=te(t,o))||n.enumerable});return e};var se=e=>ie(x({},"__esModule",{value:!0}),e);var Se={};oe(Se,{TEXT_DOMAIN:()=>K,clearMfaPreferences:()=>_,configureAmplify:()=>T,getAmplifyConfig:()=>E,getGateyPlugin:()=>s,getGroups:()=>R,getMfaPreferences:()=>D,getPreferredRole:()=>V,getRoles:()=>z,getScopes:()=>B,getStore:()=>p,getStoreDispatch:()=>y,getStoreSelect:()=>O,getUserAttributes:()=>k,initializeGatey:()=>Ae,isAuthenticated:()=>M,isInGroup:()=>W,loadAuthSession:()=>m,loadMFAPreferences:()=>N,loadUserAttributes:()=>L,login:()=>Q,logout:()=>b,observeStore:()=>C,resolveGateyRedirectTarget:()=>j,resolveGateyTarget:()=>l,sanitizeAuthenticatorConfig:()=>G,store:()=>me,waitForGateyReady:()=>U});module.exports=se(Se);var a=require("aws-amplify/api");function s(){return globalThis.WpSuite?.plugins?.gatey}function l(e){let t=e?.trim();if(t)try{if(/^[a-z][a-z\d+.-]*:/i.test(t))return new URL(t).toString();let n=s()?.siteUrl?.trim()||window.location.href,o=t.startsWith("/")?t.replace(/^\/+/,""):t;return new URL(o,n).toString()}catch{return t}}function j(e){let t=e?.trim();if(!t)return;let r=/^[a-z][a-z\d+.-]*:/i.test(t),n=t.startsWith("/");if(!r&&!n)return l(t);try{let o=new URL(window.location.href),c=new URL(t,o.origin);return c.origin===o.origin?c.toString():void 0}catch{return}}async function U(e=8e3){let t=s();if(t?.status!=="available"){if(t?.status==="error")throw new Error("Gatey failed");await new Promise((r,n)=>{let o=()=>d(r),c=()=>d(()=>n(new Error("Gatey failed"))),d=u=>{window.removeEventListener("wpsuite:gatey:ready",o),window.removeEventListener("wpsuite:gatey:error",c),S&&clearTimeout(S),u()};window.addEventListener("wpsuite:gatey:ready",o,{once:!0}),window.addEventListener("wpsuite:gatey:error",c,{once:!0});let S=e?window.setTimeout(()=>d(()=>n(new Error("Gatey timeout"))),e):0})}}async function p(e=1e4){await U(e);let r=s()?.cognito?.store;if(!r)throw new Error("Gatey store is not available");return r}var F=require("aws-amplify"),i=require("aws-amplify/auth");var X=require("@smart-cloud/wpsuite-core"),J=require("aws-amplify/auth"),v=require("aws-amplify/utils"),g=require("@wordpress/data"),Y=require("@smart-cloud/wpsuite-core");var P="gatey_account",K="gatey";var I;typeof WpSuite<"u"?I=WpSuite.siteSettings:I={};var w=e=>{e?.username?window.localStorage.setItem(P,JSON.stringify(e)):window.localStorage.removeItem(P)},A=async e=>{let t=JSON.parse(window.localStorage.getItem(P)??"{}"),r=!1;if(t?.username)try{let n=await(0,J.fetchAuthSession)();n?.tokens?.accessToken?.payload?.exp&&n.tokens.accessToken.payload.exp>new Date().getTime()/1e3&&(r=!0)}catch(n){console.error(n)}else try{t=await H(!1),t?.username&&(w(t),t.loaded=!0,r=!0)}catch(n){console.error(n)}return!r&&t?.username&&(w({}),p().then(async n=>{await b(e?.signOutHook),y(n).clearAccount()})),t},ae=async e=>{let t=window.location.hostname.toLowerCase().split(":")[0],r=s();if(!r)throw new Error("Gatey plugin is not available");let n=l(r.settings?.signInPage)??window.location.origin,o=r.settings?.secondaryUserPoolDomains&&t.toLowerCase().match(r.settings.secondaryUserPoolDomains.toLowerCase())&&r.settings?.userPoolConfigurations.secondary?.Auth?.Cognito?.userPoolId?r.settings?.userPoolConfigurations.secondary:r.settings?.userPoolConfigurations.default,c={Auth:{Cognito:{userPoolClientId:"",userPoolId:"",identityPoolId:"",...o.Auth?.Cognito,loginWith:{oauth:{domain:"",scopes:[],responseType:"code",...o.Auth?.Cognito?.loginWith?.oauth,redirectSignIn:[n],redirectSignOut:[n]}}}},API:{...o.API,REST:{...o.API?.REST,admin:{endpoint:r.restUrl}}}},d=e?.apiConfigurations?.secondary?.domains&&t.toLowerCase().match(e.apiConfigurations.secondary?.domains.toLowerCase())&&e.apiConfigurations?.secondary?.apis?.length?e.apiConfigurations.secondary:e?.apiConfigurations?.default;d?.apis?.forEach(u=>{let h=c.API?.REST;h&&(h[u.name]={endpoint:u.endpoint,region:u.region})}),T(c,{API:{REST:{headers:async u=>{let h=d?.apis?.find(f=>f.name===u.apiName);if(u.apiName==="admin"||h?.authorization==="ID_TOKEN"||h?.authorization==="ACCESS_TOKEN")try{let f=await m();if(f?.tokens?.idToken&&f?.tokens?.accessToken)return{Authorization:`Bearer ${u.apiName==="admin"||h?.authorization==="ID_TOKEN"?f.tokens.idToken.toString():f.tokens.accessToken.toString()}`}}catch(f){console.error(f),p().then(ee=>{y(ee).clearAccount()})}return{}}}}})},ue=async()=>{let e=s();if(!e)throw new Error("Gatey plugin is not available");return(0,X.loadTranslationCatalogs)(e.settings.customTranslationsUrl,{cacheVersion:I.lastUpdate})},G=e=>{let t=e&&typeof e=="object"?e:{},r={customProviders:Array.isArray(t.customProviders)?t.customProviders:[],formFields:Array.isArray(t.formFields)?t.formFields:[],apiConfigurations:typeof t.apiConfigurations=="object"&&t.apiConfigurations?t.apiConfigurations:{default:{apis:[]}}};return typeof t.subscriptionType=="string"&&(r.subscriptionType=t.subscriptionType),r},ce=async()=>{let e=G(await(0,Y.getConfig)("gatey"));ae(e);let t=window.location.hostname.toLowerCase().split(":")[0],r=e?.apiConfigurations?.secondary?.domains&&t.toLowerCase().match(e.apiConfigurations.secondary?.domains.toLowerCase())&&e.apiConfigurations?.secondary?.apis?.length?e.apiConfigurations.secondary:e?.apiConfigurations?.default,n=await A(r),o=await ue();return{config:e,amplifyConfig:{},account:n,signedIn:!!n?.username&&!n.loaded,nextUrl:void 0,language:void 0,direction:void 0,customTranslations:o,reloadAuthSession:0,reloadUserAttributes:0,reloadMFAPreferences:0}},ge={setAmplifyConfig(e){return{type:"SET_AMPLIFY_CONFIG",amplifyConfig:e}},setAccount(e){return{type:"SET_ACCOUNT",account:e}},clearAccount(){return{type:"CLEAR_ACCOUNT"}},setSignedIn(e){return{type:"SET_SIGNED_IN",signedIn:e}},setNextUrl(e){return{type:"SET_NEXT_URL",nextUrl:e}},setLanguage(e){return!e||e==="system"?v.I18n.setLanguage(""):v.I18n.setLanguage(e),{type:"SET_LANGUAGE",language:e}},setDirection(e){return{type:"SET_DIRECTION",direction:e}},reloadAuthSession(){return{type:"RELOAD_AUTH_SESSION"}},reloadUserAttributes(){return{type:"RELOAD_USER_ATTRIBUTES"}},reloadMFAPreferences(){return{type:"RELOAD_MFA_PREFERENCE"}}},le={getAmplifyConfig(e){return e.amplifyConfig},getAccount(e){return e.account},getNextUrl(e){return e.nextUrl},isSignedIn(e){return e.signedIn},getConfig(e){return e.config},getCustomTranslations(e){return e.customTranslations},getLanguage(e){return e.language},getDirection(e){return e.direction},getState(e){return e}},pe={},y=e=>(0,g.dispatch)(e),O=e=>(0,g.select)(e),q=async()=>{let e=await ce(),t=(0,g.createReduxStore)("smartcloud/gatey",{reducer(r=e,n){switch(n.type){case"SET_AMPLIFY_CONFIG":return{...r,amplifyConfig:n.amplifyConfig};case"SET_ACCOUNT":return w(n.account),{...r,account:n.account};case"CLEAR_ACCOUNT":return w({}),{...r,account:{}};case"RELOAD_AUTH_SESSION":{let o=Math.random();return{...r,reloadAuthSession:r.reloadAuthSession!==o?o:o+1}}case"RELOAD_USER_ATTRIBUTES":{let o=Math.random();return{...r,reloadUserAttributes:r.reloadUserAttributes!==o?o:o+1}}case"RELOAD_MFA_PREFERENCE":{let o=Math.random();return{...r,reloadMFAPreferences:r.reloadMFAPreferences!==o?o:o+1}}case"SET_SIGNED_IN":return{...r,signedIn:n.signedIn};case"SET_NEXT_URL":return{...r,nextUrl:n.nextUrl};case"SET_LANGUAGE":return{...r,language:n.language};case"SET_DIRECTION":return{...r,direction:n.direction}}return r},actions:ge,selectors:le,resolvers:pe});return(0,g.register)(t),t},C=(e,t,r)=>{let n;function o(){let d=O(e).getState(),S=t(d);if(S!==n){let u=n;n=S,r(n,u)}}let c=(0,g.subscribe)(o,e);return o(),c};var E=()=>F.Amplify.getConfig(),T=(e,t)=>{F.Amplify.configure(e,t)},m=e=>(0,i.fetchAuthSession)(e),L=()=>(0,i.fetchUserAttributes)(),N=()=>(0,i.fetchMFAPreference)(),H=async(e=!0)=>{let t=e?await A():{};if(t?.username)return t;try{if((await(0,i.fetchAuthSession)()).tokens)return{username:(await(0,i.getCurrentUser)()).username,userAttributes:await L(),mfaPreferences:await N()}}catch(r){console.error(r);try{await(0,i.signOut)()}catch{}}return{}},_=async()=>{await(0,i.updateMFAPreference)({totp:"DISABLED"})},$=()=>A().then(e=>e?.username),k=()=>A().then(e=>e?.userAttributes),D=()=>A().then(e=>e?.mfaPreferences),M=()=>A().then(e=>!!e?.username),W=e=>R().then(t=>t?.includes(e)||!1),R=()=>m().then(e=>e.tokens?.idToken?.payload["cognito:groups"]instanceof Array?e.tokens.idToken.payload["cognito:groups"].map(t=>t):[]).catch(e=>{console.error(e)}),z=async()=>m().then(e=>e.tokens?.idToken?.payload["cognito:roles"]instanceof Array?e.tokens.idToken.payload["cognito:roles"].map(t=>t).map(t=>t.substring(t.indexOf("/")+1)):[]).catch(e=>{console.error(e)}),V=async()=>m().then(e=>{if(!e.tokens?.idToken?.payload["cognito:preferred_role"])return;let t=e.tokens.idToken.payload["cognito:preferred_role"];return t.substring(t.indexOf("/")+1)}).catch(e=>{console.error(e)}),B=()=>m().then(e=>e.tokens?.accessToken.payload.scope?.split(" ")??[]).catch(e=>{console.error(e)}),Q=async e=>{let t,r=s();if(!r)throw new Error("Gatey plugin is not available");return r.settings.integrateWpLogin&&r.restUrl?.startsWith("http")&&(t=await r.cognito.post({apiName:"admin",path:"/login"}).response.then(o=>o.body.json()).then(o=>{if(o instanceof Object&&"redirect"in o)return o?.redirect}).catch(o=>{console.error(o)})),e&&await r.cognito.get({apiName:e.apiName,path:e.path,options:e.options}).response.catch(n=>console.error(n)),l(r.settings.redirectSignIn)??t},b=async e=>{let t=s();if(!t)throw new Error("Gatey plugin is not available");let r;t.settings.integrateWpLogin&&(r=await t.cognito.get({apiName:"admin",path:"/logout"}).response.then(n=>n.body.json()).then(n=>{if(n instanceof Object&&"redirect"in n)return n?.redirect}).catch(n=>{console.error(n)})),e&&await t.cognito.get({apiName:e.apiName,path:e.path,options:e.options}).response.catch(n=>console.error(n));try{await(0,i.signOut)()}catch{}return l(t.settings.redirectSignOut)??r??l(t.settings.signInPage)??"/"};var Z=require("@smart-cloud/wpsuite-core");var de=()=>{p().then(e=>{C(e,t=>t.nextUrl,async t=>{t&&window.location.assign(t)}),y(e).clearAccount()}).catch(e=>{console.error("Gatey signOut error:",e)})},fe=e=>{p().then(t=>{y(t).setLanguage(e??"en")}).catch(t=>{console.error("Gatey setLanguage error:",t)})},ye=e=>{p().then(t=>{y(t).setDirection(e??"auto")}).catch(t=>{console.error("Gatey setDirection error:",t)})};var me=async()=>p(),Ae=()=>{let e=globalThis.WpSuite,t=s();if(!t)throw new Error("Gatey plugin is not available");(0,Z.attachDefaultPluginRuntime)(t),t.status=t.status??"initializing";let r=q();return t.cognito={store:r,observeStore:C,setLanguage:fe,setDirection:ye,getAmplifyConfig:E,isAuthenticated:M,isInGroup:W,getUsername:$,getUserAttributes:k,getMfaPreferences:D,clearMfaPreferences:_,getGroups:R,getRoles:z,getPreferredRole:V,getScopes:B,signOut:de,get:a.get,post:a.post,put:a.put,del:a.del,head:a.head,patch:a.patch},r.then(()=>{t.status="available",e?.events?.emit("wpsuite:gatey:ready",{key:t.key,version:t.version})}).catch(n=>{t.status="error",e?.events?.emit("wpsuite:gatey:error",{key:t.key,error:String(n)})}),t};0&&(module.exports={TEXT_DOMAIN,clearMfaPreferences,configureAmplify,getAmplifyConfig,getGateyPlugin,getGroups,getMfaPreferences,getPreferredRole,getRoles,getScopes,getStore,getStoreDispatch,getStoreSelect,getUserAttributes,initializeGatey,isAuthenticated,isInGroup,loadAuthSession,loadMFAPreferences,loadUserAttributes,login,logout,observeStore,resolveGateyRedirectTarget,resolveGateyTarget,sanitizeAuthenticatorConfig,store,waitForGateyReady});
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { PasswordlessSettings, type InitialRoute, type LoginMechanism, type SignUpAttribute, type SocialProvider } from "@smart-cloud/aws-amplify-ui";
2
2
  import { type ResourcesConfig } from "aws-amplify";
3
3
  import { del, get, head, patch, post, put } from "aws-amplify/api";
4
- import { getGateyPlugin, getStore, resolveGateyTarget, waitForGateyReady, type GateyErrorEvent, type GateyPlugin, type GateyReadyEvent } from "./runtime";
4
+ import { getGateyPlugin, getStore, resolveGateyRedirectTarget, resolveGateyTarget, waitForGateyReady, type GateyErrorEvent, type GateyPlugin, type GateyReadyEvent } from "./runtime";
5
5
  import { clearMfaPreferences, getAmplifyConfig, getGroups, getMfaPreferences, getPreferredRole, getRoles, getScopes, getUserAttributes, getUsername, isAuthenticated, isInGroup } from "./auth";
6
6
  import { observeStore, type Store } from "./store";
7
7
  export interface RoleMapping {
@@ -72,7 +72,7 @@ export interface GateySiteRuntime {
72
72
  /** Current WordPress site's canonical URL, including a Multisite path. */
73
73
  siteUrl?: string;
74
74
  }
75
- export { getGateyPlugin, getStore, resolveGateyTarget, waitForGateyReady, type GateyErrorEvent, type GateyPlugin, type GateyReadyEvent, };
75
+ export { getGateyPlugin, getStore, resolveGateyRedirectTarget, resolveGateyTarget, waitForGateyReady, type GateyErrorEvent, type GateyPlugin, type GateyReadyEvent, };
76
76
  export { clearMfaPreferences, getGroups, getMfaPreferences, getPreferredRole, getRoles, getScopes, getUserAttributes, isAuthenticated, isInGroup, };
77
77
  export { configureAmplify, getAmplifyConfig, loadAuthSession, loadMFAPreferences, loadUserAttributes, login, logout, type Account, } from "./auth";
78
78
  export { getStoreDispatch, getStoreSelect, observeStore, sanitizeAuthenticatorConfig, type AuthenticatorConfig, type CustomTranslations, type FormField, type State, type Store, } from "./store";
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{del as le,get as pe,head as de,patch as fe,post as ye,put as me}from"aws-amplify/api";function s(){return globalThis.WpSuite?.plugins?.gatey}function l(e){let t=e?.trim();if(t)try{if(/^[a-z][a-z\d+.-]*:/i.test(t))return new URL(t).toString();let r=s()?.siteUrl?.trim()||window.location.href,o=t.startsWith("/")?t.replace(/^\/+/,""):t;return new URL(o,r).toString()}catch{return t}}async function E(e=8e3){let t=s();if(t?.status!=="available"){if(t?.status==="error")throw new Error("Gatey failed");await new Promise((n,r)=>{let o=()=>a(n),g=()=>a(()=>r(new Error("Gatey failed"))),a=i=>{window.removeEventListener("wpsuite:gatey:ready",o),window.removeEventListener("wpsuite:gatey:error",g),y&&clearTimeout(y),i()};window.addEventListener("wpsuite:gatey:ready",o,{once:!0}),window.addEventListener("wpsuite:gatey:error",g,{once:!0});let y=e?window.setTimeout(()=>a(()=>r(new Error("Gatey timeout"))),e):0})}}async function c(e=1e4){await E(e);let n=s()?.cognito?.store;if(!n)throw new Error("Gatey store is not available");return n}import{Amplify as O}from"aws-amplify";import{fetchAuthSession as G,fetchMFAPreference as se,fetchUserAttributes as ae,getCurrentUser as ue,signOut as F,updateMFAPreference as ce}from"aws-amplify/auth";import{fetchAuthSession as J}from"aws-amplify/auth";import{I18n as x}from"aws-amplify/utils";import{createReduxStore as Y,dispatch as q,register as H,select as $,subscribe as Q}from"@wordpress/data";import{getConfig as Z}from"@smart-cloud/wpsuite-core";var A="gatey_account",X="gatey";var C;typeof WpSuite<"u"?C=WpSuite.siteSettings:C={};var S=e=>{e?.username?window.localStorage.setItem(A,JSON.stringify(e)):window.localStorage.removeItem(A)},p=async e=>{let t=JSON.parse(window.localStorage.getItem(A)??"{}"),n=!1;if(t?.username)try{let r=await J();r?.tokens?.accessToken?.payload?.exp&&r.tokens.accessToken.payload.exp>new Date().getTime()/1e3&&(n=!0)}catch(r){console.error(r)}else try{t=await I(!1),t?.username&&(S(t),t.loaded=!0,n=!0)}catch(r){console.error(r)}return!n&&t?.username&&(S({}),c().then(async r=>{await w(e?.signOutHook),d(r).clearAccount()})),t},ee=async e=>{let t=window.location.hostname.toLowerCase().split(":")[0],n=s();if(!n)throw new Error("Gatey plugin is not available");let r=l(n.settings?.signInPage)??window.location.origin,o=n.settings?.secondaryUserPoolDomains&&t.toLowerCase().match(n.settings.secondaryUserPoolDomains.toLowerCase())&&n.settings?.userPoolConfigurations.secondary?.Auth?.Cognito?.userPoolId?n.settings?.userPoolConfigurations.secondary:n.settings?.userPoolConfigurations.default,g={Auth:{Cognito:{userPoolClientId:"",userPoolId:"",identityPoolId:"",...o.Auth?.Cognito,loginWith:{oauth:{domain:"",scopes:[],responseType:"code",...o.Auth?.Cognito?.loginWith?.oauth,redirectSignIn:[r],redirectSignOut:[r]}}}},API:{...o.API,REST:{...o.API?.REST,admin:{endpoint:n.restUrl}}}},a=e?.apiConfigurations?.secondary?.domains&&t.toLowerCase().match(e.apiConfigurations.secondary?.domains.toLowerCase())&&e.apiConfigurations?.secondary?.apis?.length?e.apiConfigurations.secondary:e?.apiConfigurations?.default;a?.apis?.forEach(i=>{let m=g.API?.REST;m&&(m[i.name]={endpoint:i.endpoint,region:i.region})}),P(g,{API:{REST:{headers:async i=>{let m=a?.apis?.find(u=>u.name===i.apiName);if(i.apiName==="admin"||m?.authorization==="ID_TOKEN"||m?.authorization==="ACCESS_TOKEN")try{let u=await f();if(u?.tokens?.idToken&&u?.tokens?.accessToken)return{Authorization:`Bearer ${i.apiName==="admin"||m?.authorization==="ID_TOKEN"?u.tokens.idToken.toString():u.tokens.accessToken.toString()}`}}catch(u){console.error(u),c().then(K=>{d(K).clearAccount()})}return{}}}}})},te=async()=>{let e=s();if(!e)throw new Error("Gatey plugin is not available");let t=null;return e.settings.customTranslationsUrl&&(t=await fetch(e.settings.customTranslationsUrl+(e.settings.customTranslationsUrl.includes("?")?"&":"?")+"t="+C.lastUpdate).then(n=>n.ok?n.text():null).then(n=>n?JSON.parse(n):null).catch(()=>null)),t??null},R=e=>{let t=e&&typeof e=="object"?e:{},n={customProviders:Array.isArray(t.customProviders)?t.customProviders:[],formFields:Array.isArray(t.formFields)?t.formFields:[],apiConfigurations:typeof t.apiConfigurations=="object"&&t.apiConfigurations?t.apiConfigurations:{default:{apis:[]}}};return typeof t.subscriptionType=="string"&&(n.subscriptionType=t.subscriptionType),n},ne=async()=>{let e=R(await Z("gatey"));ee(e);let t=window.location.hostname.toLowerCase().split(":")[0],n=e?.apiConfigurations?.secondary?.domains&&t.toLowerCase().match(e.apiConfigurations.secondary?.domains.toLowerCase())&&e.apiConfigurations?.secondary?.apis?.length?e.apiConfigurations.secondary:e?.apiConfigurations?.default,r=await p(n),o=await te();return{config:e,amplifyConfig:{},account:r,signedIn:!!r?.username&&!r.loaded,nextUrl:void 0,language:void 0,direction:void 0,customTranslations:o,reloadAuthSession:0,reloadUserAttributes:0,reloadMFAPreferences:0}},re={setAmplifyConfig(e){return{type:"SET_AMPLIFY_CONFIG",amplifyConfig:e}},setAccount(e){return{type:"SET_ACCOUNT",account:e}},clearAccount(){return{type:"CLEAR_ACCOUNT"}},setSignedIn(e){return{type:"SET_SIGNED_IN",signedIn:e}},setNextUrl(e){return{type:"SET_NEXT_URL",nextUrl:e}},setLanguage(e){return!e||e==="system"?x.setLanguage(""):x.setLanguage(e),{type:"SET_LANGUAGE",language:e}},setDirection(e){return{type:"SET_DIRECTION",direction:e}},reloadAuthSession(){return{type:"RELOAD_AUTH_SESSION"}},reloadUserAttributes(){return{type:"RELOAD_USER_ATTRIBUTES"}},reloadMFAPreferences(){return{type:"RELOAD_MFA_PREFERENCE"}}},oe={getAmplifyConfig(e){return e.amplifyConfig},getAccount(e){return e.account},getNextUrl(e){return e.nextUrl},isSignedIn(e){return e.signedIn},getConfig(e){return e.config},getCustomTranslations(e){return e.customTranslations},getLanguage(e){return e.language},getDirection(e){return e.direction},getState(e){return e}},ie={},d=e=>q(e),U=e=>$(e),v=async()=>{let e=await ne(),t=Y("smartcloud/gatey",{reducer(n=e,r){switch(r.type){case"SET_AMPLIFY_CONFIG":return{...n,amplifyConfig:r.amplifyConfig};case"SET_ACCOUNT":return S(r.account),{...n,account:r.account};case"CLEAR_ACCOUNT":return S({}),{...n,account:{}};case"RELOAD_AUTH_SESSION":{let o=Math.random();return{...n,reloadAuthSession:n.reloadAuthSession!==o?o:o+1}}case"RELOAD_USER_ATTRIBUTES":{let o=Math.random();return{...n,reloadUserAttributes:n.reloadUserAttributes!==o?o:o+1}}case"RELOAD_MFA_PREFERENCE":{let o=Math.random();return{...n,reloadMFAPreferences:n.reloadMFAPreferences!==o?o:o+1}}case"SET_SIGNED_IN":return{...n,signedIn:r.signedIn};case"SET_NEXT_URL":return{...n,nextUrl:r.nextUrl};case"SET_LANGUAGE":return{...n,language:r.language};case"SET_DIRECTION":return{...n,direction:r.direction}}return n},actions:re,selectors:oe,resolvers:ie});return H(t),t},h=(e,t,n)=>{let r;function o(){let a=U(e).getState(),y=t(a);if(y!==r){let i=r;r=y,n(r,i)}}let g=Q(o,e);return o(),g};var T=()=>O.getConfig(),P=(e,t)=>{O.configure(e,t)},f=e=>G(e),N=()=>ae(),L=()=>se(),I=async(e=!0)=>{let t=e?await p():{};if(t?.username)return t;try{if((await G()).tokens)return{username:(await ue()).username,userAttributes:await N(),mfaPreferences:await L()}}catch(n){console.error(n);try{await F()}catch{}}return{}},_=async()=>{await ce({totp:"DISABLED"})},k=()=>p().then(e=>e?.username),D=()=>p().then(e=>e?.userAttributes),M=()=>p().then(e=>e?.mfaPreferences),W=()=>p().then(e=>!!e?.username),z=e=>b().then(t=>t?.includes(e)||!1),b=()=>f().then(e=>e.tokens?.idToken?.payload["cognito:groups"]instanceof Array?e.tokens.idToken.payload["cognito:groups"].map(t=>t):[]).catch(e=>{console.error(e)}),B=async()=>f().then(e=>e.tokens?.idToken?.payload["cognito:roles"]instanceof Array?e.tokens.idToken.payload["cognito:roles"].map(t=>t).map(t=>t.substring(t.indexOf("/")+1)):[]).catch(e=>{console.error(e)}),V=async()=>f().then(e=>{if(!e.tokens?.idToken?.payload["cognito:preferred_role"])return;let t=e.tokens.idToken.payload["cognito:preferred_role"];return t.substring(t.indexOf("/")+1)}).catch(e=>{console.error(e)}),j=()=>f().then(e=>e.tokens?.accessToken.payload.scope?.split(" ")??[]).catch(e=>{console.error(e)}),ge=async e=>{let t,n=s();if(!n)throw new Error("Gatey plugin is not available");return n.settings.integrateWpLogin&&n.restUrl?.startsWith("http")&&(t=await n.cognito.post({apiName:"admin",path:"/login"}).response.then(o=>o.body.json()).then(o=>{if(o instanceof Object&&"redirect"in o)return o?.redirect}).catch(o=>{console.error(o)})),e&&await n.cognito.get({apiName:e.apiName,path:e.path,options:e.options}).response.catch(r=>console.error(r)),l(n.settings.redirectSignIn)??t},w=async e=>{let t=s();if(!t)throw new Error("Gatey plugin is not available");let n;t.settings.integrateWpLogin&&(n=await t.cognito.get({apiName:"admin",path:"/logout"}).response.then(r=>r.body.json()).then(r=>{if(r instanceof Object&&"redirect"in r)return r?.redirect}).catch(r=>{console.error(r)})),e&&await t.cognito.get({apiName:e.apiName,path:e.path,options:e.options}).response.catch(r=>console.error(r));try{await F()}catch{}return l(t.settings.redirectSignOut)??n??l(t.settings.signInPage)??"/"};import{attachDefaultPluginRuntime as Ae}from"@smart-cloud/wpsuite-core";var Se=()=>{c().then(e=>{h(e,t=>t.nextUrl,async t=>{t&&window.location.assign(t)}),d(e).clearAccount()}).catch(e=>{console.error("Gatey signOut error:",e)})},he=e=>{c().then(t=>{d(t).setLanguage(e??"en")}).catch(t=>{console.error("Gatey setLanguage error:",t)})},Ce=e=>{c().then(t=>{d(t).setDirection(e??"auto")}).catch(t=>{console.error("Gatey setDirection error:",t)})};var Be=async()=>c(),Ve=()=>{let e=globalThis.WpSuite,t=s();if(!t)throw new Error("Gatey plugin is not available");Ae(t),t.status=t.status??"initializing";let n=v();return t.cognito={store:n,observeStore:h,setLanguage:he,setDirection:Ce,getAmplifyConfig:T,isAuthenticated:W,isInGroup:z,getUsername:k,getUserAttributes:D,getMfaPreferences:M,clearMfaPreferences:_,getGroups:b,getRoles:B,getPreferredRole:V,getScopes:j,signOut:Se,get:pe,post:ye,put:me,del:le,head:de,patch:fe},n.then(()=>{t.status="available",e?.events?.emit("wpsuite:gatey:ready",{key:t.key,version:t.version})}).catch(r=>{t.status="error",e?.events?.emit("wpsuite:gatey:error",{key:t.key,error:String(r)})}),t};export{X as TEXT_DOMAIN,_ as clearMfaPreferences,P as configureAmplify,T as getAmplifyConfig,s as getGateyPlugin,b as getGroups,M as getMfaPreferences,V as getPreferredRole,B as getRoles,j as getScopes,c as getStore,d as getStoreDispatch,U as getStoreSelect,D as getUserAttributes,Ve as initializeGatey,W as isAuthenticated,z as isInGroup,f as loadAuthSession,L as loadMFAPreferences,N as loadUserAttributes,ge as login,w as logout,h as observeStore,l as resolveGateyTarget,R as sanitizeAuthenticatorConfig,Be as store,E as waitForGateyReady};
1
+ import{del as de,get as fe,head as ye,patch as me,post as Ae,put as Se}from"aws-amplify/api";function s(){return globalThis.WpSuite?.plugins?.gatey}function g(e){let t=e?.trim();if(t)try{if(/^[a-z][a-z\d+.-]*:/i.test(t))return new URL(t).toString();let n=s()?.siteUrl?.trim()||window.location.href,o=t.startsWith("/")?t.replace(/^\/+/,""):t;return new URL(o,n).toString()}catch{return t}}function X(e){let t=e?.trim();if(!t)return;let r=/^[a-z][a-z\d+.-]*:/i.test(t),n=t.startsWith("/");if(!r&&!n)return g(t);try{let o=new URL(window.location.href),a=new URL(t,o.origin);return a.origin===o.origin?a.toString():void 0}catch{return}}async function E(e=8e3){let t=s();if(t?.status!=="available"){if(t?.status==="error")throw new Error("Gatey failed");await new Promise((r,n)=>{let o=()=>u(r),a=()=>u(()=>n(new Error("Gatey failed"))),u=i=>{window.removeEventListener("wpsuite:gatey:ready",o),window.removeEventListener("wpsuite:gatey:error",a),y&&clearTimeout(y),i()};window.addEventListener("wpsuite:gatey:ready",o,{once:!0}),window.addEventListener("wpsuite:gatey:error",a,{once:!0});let y=e?window.setTimeout(()=>u(()=>n(new Error("Gatey timeout"))),e):0})}}async function l(e=1e4){await E(e);let r=s()?.cognito?.store;if(!r)throw new Error("Gatey store is not available");return r}import{Amplify as G}from"aws-amplify";import{fetchAuthSession as O,fetchMFAPreference as ue,fetchUserAttributes as ce,getCurrentUser as ge,signOut as F,updateMFAPreference as le}from"aws-amplify/auth";import{loadTranslationCatalogs as Y}from"@smart-cloud/wpsuite-core";import{fetchAuthSession as q}from"aws-amplify/auth";import{I18n as R}from"aws-amplify/utils";import{createReduxStore as H,dispatch as $,register as Q,select as Z,subscribe as ee}from"@wordpress/data";import{getConfig as te}from"@smart-cloud/wpsuite-core";var A="gatey_account",J="gatey";var C;typeof WpSuite<"u"?C=WpSuite.siteSettings:C={};var S=e=>{e?.username?window.localStorage.setItem(A,JSON.stringify(e)):window.localStorage.removeItem(A)},p=async e=>{let t=JSON.parse(window.localStorage.getItem(A)??"{}"),r=!1;if(t?.username)try{let n=await q();n?.tokens?.accessToken?.payload?.exp&&n.tokens.accessToken.payload.exp>new Date().getTime()/1e3&&(r=!0)}catch(n){console.error(n)}else try{t=await I(!1),t?.username&&(S(t),t.loaded=!0,r=!0)}catch(n){console.error(n)}return!r&&t?.username&&(S({}),l().then(async n=>{await w(e?.signOutHook),d(n).clearAccount()})),t},re=async e=>{let t=window.location.hostname.toLowerCase().split(":")[0],r=s();if(!r)throw new Error("Gatey plugin is not available");let n=g(r.settings?.signInPage)??window.location.origin,o=r.settings?.secondaryUserPoolDomains&&t.toLowerCase().match(r.settings.secondaryUserPoolDomains.toLowerCase())&&r.settings?.userPoolConfigurations.secondary?.Auth?.Cognito?.userPoolId?r.settings?.userPoolConfigurations.secondary:r.settings?.userPoolConfigurations.default,a={Auth:{Cognito:{userPoolClientId:"",userPoolId:"",identityPoolId:"",...o.Auth?.Cognito,loginWith:{oauth:{domain:"",scopes:[],responseType:"code",...o.Auth?.Cognito?.loginWith?.oauth,redirectSignIn:[n],redirectSignOut:[n]}}}},API:{...o.API,REST:{...o.API?.REST,admin:{endpoint:r.restUrl}}}},u=e?.apiConfigurations?.secondary?.domains&&t.toLowerCase().match(e.apiConfigurations.secondary?.domains.toLowerCase())&&e.apiConfigurations?.secondary?.apis?.length?e.apiConfigurations.secondary:e?.apiConfigurations?.default;u?.apis?.forEach(i=>{let m=a.API?.REST;m&&(m[i.name]={endpoint:i.endpoint,region:i.region})}),P(a,{API:{REST:{headers:async i=>{let m=u?.apis?.find(c=>c.name===i.apiName);if(i.apiName==="admin"||m?.authorization==="ID_TOKEN"||m?.authorization==="ACCESS_TOKEN")try{let c=await f();if(c?.tokens?.idToken&&c?.tokens?.accessToken)return{Authorization:`Bearer ${i.apiName==="admin"||m?.authorization==="ID_TOKEN"?c.tokens.idToken.toString():c.tokens.accessToken.toString()}`}}catch(c){console.error(c),l().then(K=>{d(K).clearAccount()})}return{}}}}})},ne=async()=>{let e=s();if(!e)throw new Error("Gatey plugin is not available");return Y(e.settings.customTranslationsUrl,{cacheVersion:C.lastUpdate})},x=e=>{let t=e&&typeof e=="object"?e:{},r={customProviders:Array.isArray(t.customProviders)?t.customProviders:[],formFields:Array.isArray(t.formFields)?t.formFields:[],apiConfigurations:typeof t.apiConfigurations=="object"&&t.apiConfigurations?t.apiConfigurations:{default:{apis:[]}}};return typeof t.subscriptionType=="string"&&(r.subscriptionType=t.subscriptionType),r},oe=async()=>{let e=x(await te("gatey"));re(e);let t=window.location.hostname.toLowerCase().split(":")[0],r=e?.apiConfigurations?.secondary?.domains&&t.toLowerCase().match(e.apiConfigurations.secondary?.domains.toLowerCase())&&e.apiConfigurations?.secondary?.apis?.length?e.apiConfigurations.secondary:e?.apiConfigurations?.default,n=await p(r),o=await ne();return{config:e,amplifyConfig:{},account:n,signedIn:!!n?.username&&!n.loaded,nextUrl:void 0,language:void 0,direction:void 0,customTranslations:o,reloadAuthSession:0,reloadUserAttributes:0,reloadMFAPreferences:0}},ie={setAmplifyConfig(e){return{type:"SET_AMPLIFY_CONFIG",amplifyConfig:e}},setAccount(e){return{type:"SET_ACCOUNT",account:e}},clearAccount(){return{type:"CLEAR_ACCOUNT"}},setSignedIn(e){return{type:"SET_SIGNED_IN",signedIn:e}},setNextUrl(e){return{type:"SET_NEXT_URL",nextUrl:e}},setLanguage(e){return!e||e==="system"?R.setLanguage(""):R.setLanguage(e),{type:"SET_LANGUAGE",language:e}},setDirection(e){return{type:"SET_DIRECTION",direction:e}},reloadAuthSession(){return{type:"RELOAD_AUTH_SESSION"}},reloadUserAttributes(){return{type:"RELOAD_USER_ATTRIBUTES"}},reloadMFAPreferences(){return{type:"RELOAD_MFA_PREFERENCE"}}},se={getAmplifyConfig(e){return e.amplifyConfig},getAccount(e){return e.account},getNextUrl(e){return e.nextUrl},isSignedIn(e){return e.signedIn},getConfig(e){return e.config},getCustomTranslations(e){return e.customTranslations},getLanguage(e){return e.language},getDirection(e){return e.direction},getState(e){return e}},ae={},d=e=>$(e),U=e=>Z(e),v=async()=>{let e=await oe(),t=H("smartcloud/gatey",{reducer(r=e,n){switch(n.type){case"SET_AMPLIFY_CONFIG":return{...r,amplifyConfig:n.amplifyConfig};case"SET_ACCOUNT":return S(n.account),{...r,account:n.account};case"CLEAR_ACCOUNT":return S({}),{...r,account:{}};case"RELOAD_AUTH_SESSION":{let o=Math.random();return{...r,reloadAuthSession:r.reloadAuthSession!==o?o:o+1}}case"RELOAD_USER_ATTRIBUTES":{let o=Math.random();return{...r,reloadUserAttributes:r.reloadUserAttributes!==o?o:o+1}}case"RELOAD_MFA_PREFERENCE":{let o=Math.random();return{...r,reloadMFAPreferences:r.reloadMFAPreferences!==o?o:o+1}}case"SET_SIGNED_IN":return{...r,signedIn:n.signedIn};case"SET_NEXT_URL":return{...r,nextUrl:n.nextUrl};case"SET_LANGUAGE":return{...r,language:n.language};case"SET_DIRECTION":return{...r,direction:n.direction}}return r},actions:ie,selectors:se,resolvers:ae});return Q(t),t},h=(e,t,r)=>{let n;function o(){let u=U(e).getState(),y=t(u);if(y!==n){let i=n;n=y,r(n,i)}}let a=ee(o,e);return o(),a};var T=()=>G.getConfig(),P=(e,t)=>{G.configure(e,t)},f=e=>O(e),L=()=>ce(),N=()=>ue(),I=async(e=!0)=>{let t=e?await p():{};if(t?.username)return t;try{if((await O()).tokens)return{username:(await ge()).username,userAttributes:await L(),mfaPreferences:await N()}}catch(r){console.error(r);try{await F()}catch{}}return{}},_=async()=>{await le({totp:"DISABLED"})},k=()=>p().then(e=>e?.username),D=()=>p().then(e=>e?.userAttributes),M=()=>p().then(e=>e?.mfaPreferences),W=()=>p().then(e=>!!e?.username),z=e=>b().then(t=>t?.includes(e)||!1),b=()=>f().then(e=>e.tokens?.idToken?.payload["cognito:groups"]instanceof Array?e.tokens.idToken.payload["cognito:groups"].map(t=>t):[]).catch(e=>{console.error(e)}),V=async()=>f().then(e=>e.tokens?.idToken?.payload["cognito:roles"]instanceof Array?e.tokens.idToken.payload["cognito:roles"].map(t=>t).map(t=>t.substring(t.indexOf("/")+1)):[]).catch(e=>{console.error(e)}),B=async()=>f().then(e=>{if(!e.tokens?.idToken?.payload["cognito:preferred_role"])return;let t=e.tokens.idToken.payload["cognito:preferred_role"];return t.substring(t.indexOf("/")+1)}).catch(e=>{console.error(e)}),j=()=>f().then(e=>e.tokens?.accessToken.payload.scope?.split(" ")??[]).catch(e=>{console.error(e)}),pe=async e=>{let t,r=s();if(!r)throw new Error("Gatey plugin is not available");return r.settings.integrateWpLogin&&r.restUrl?.startsWith("http")&&(t=await r.cognito.post({apiName:"admin",path:"/login"}).response.then(o=>o.body.json()).then(o=>{if(o instanceof Object&&"redirect"in o)return o?.redirect}).catch(o=>{console.error(o)})),e&&await r.cognito.get({apiName:e.apiName,path:e.path,options:e.options}).response.catch(n=>console.error(n)),g(r.settings.redirectSignIn)??t},w=async e=>{let t=s();if(!t)throw new Error("Gatey plugin is not available");let r;t.settings.integrateWpLogin&&(r=await t.cognito.get({apiName:"admin",path:"/logout"}).response.then(n=>n.body.json()).then(n=>{if(n instanceof Object&&"redirect"in n)return n?.redirect}).catch(n=>{console.error(n)})),e&&await t.cognito.get({apiName:e.apiName,path:e.path,options:e.options}).response.catch(n=>console.error(n));try{await F()}catch{}return g(t.settings.redirectSignOut)??r??g(t.settings.signInPage)??"/"};import{attachDefaultPluginRuntime as he}from"@smart-cloud/wpsuite-core";var Ce=()=>{l().then(e=>{h(e,t=>t.nextUrl,async t=>{t&&window.location.assign(t)}),d(e).clearAccount()}).catch(e=>{console.error("Gatey signOut error:",e)})},Pe=e=>{l().then(t=>{d(t).setLanguage(e??"en")}).catch(t=>{console.error("Gatey setLanguage error:",t)})},we=e=>{l().then(t=>{d(t).setDirection(e??"auto")}).catch(t=>{console.error("Gatey setDirection error:",t)})};var Ke=async()=>l(),Xe=()=>{let e=globalThis.WpSuite,t=s();if(!t)throw new Error("Gatey plugin is not available");he(t),t.status=t.status??"initializing";let r=v();return t.cognito={store:r,observeStore:h,setLanguage:Pe,setDirection:we,getAmplifyConfig:T,isAuthenticated:W,isInGroup:z,getUsername:k,getUserAttributes:D,getMfaPreferences:M,clearMfaPreferences:_,getGroups:b,getRoles:V,getPreferredRole:B,getScopes:j,signOut:Ce,get:fe,post:Ae,put:Se,del:de,head:ye,patch:me},r.then(()=>{t.status="available",e?.events?.emit("wpsuite:gatey:ready",{key:t.key,version:t.version})}).catch(n=>{t.status="error",e?.events?.emit("wpsuite:gatey:error",{key:t.key,error:String(n)})}),t};export{J as TEXT_DOMAIN,_ as clearMfaPreferences,P as configureAmplify,T as getAmplifyConfig,s as getGateyPlugin,b as getGroups,M as getMfaPreferences,B as getPreferredRole,V as getRoles,j as getScopes,l as getStore,d as getStoreDispatch,U as getStoreSelect,D as getUserAttributes,Xe as initializeGatey,W as isAuthenticated,z as isInGroup,f as loadAuthSession,N as loadMFAPreferences,L as loadUserAttributes,pe as login,w as logout,h as observeStore,X as resolveGateyRedirectTarget,g as resolveGateyTarget,x as sanitizeAuthenticatorConfig,Ke as store,E as waitForGateyReady};
package/dist/runtime.d.ts CHANGED
@@ -11,9 +11,24 @@ export declare function getGateyPlugin(): GateyPlugin;
11
11
  * browser navigation interprets that path from the domain root. On a
12
12
  * subdirectory Multisite that would escape `/saas-launch/`. PHP's `site_url()`
13
13
  * already uses the current blog; this helper gives the browser runtime the
14
- * same current-site behavior while preserving explicit absolute URLs (for
15
- * example the WordPress `redirect_to` return URL).
14
+ * same current-site behavior while preserving explicitly configured absolute
15
+ * URLs. Query-string `redirect_to` return URLs use
16
+ * `resolveGateyRedirectTarget()` instead.
16
17
  */
17
18
  export declare function resolveGateyTarget(target: string | null | undefined): string | undefined;
19
+ /**
20
+ * Resolve an explicit return URL supplied by a `redirect_to` query parameter.
21
+ *
22
+ * This has deliberately different semantics from a saved Gatey page setting:
23
+ * `/sign-in` in settings is portable and site-relative, whereas a return URL
24
+ * such as `/saas-launch/profile` already names an origin-relative request.
25
+ * Do not rebase the latter on the current Multisite blog path.
26
+ *
27
+ * Absolute return URLs are accepted only when they remain on the current
28
+ * browser origin. This prevents an untrusted query parameter becoming an open
29
+ * redirect after a successful sign-in. Bare legacy values keep the normal
30
+ * site-relative resolution behaviour.
31
+ */
32
+ export declare function resolveGateyRedirectTarget(target: string | null | undefined): string | undefined;
18
33
  export declare function waitForGateyReady(timeoutMs?: number): Promise<void>;
19
34
  export declare function getStore(timeoutMs?: number): Promise<import("./store").Store>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@smart-cloud/gatey-core",
3
- "version": "2.3.4",
3
+ "version": "2.3.6",
4
4
  "description": "Login & SSO with Amazon Cognito",
5
5
  "author": "Smart Cloud Solutions Inc.",
6
6
  "license": "MIT",
@@ -40,35 +40,35 @@
40
40
  "rollup": "^4.62.3"
41
41
  },
42
42
  "dependencies": {
43
- "@smart-cloud/wpsuite-core": "^2.3.2"
43
+ "@smart-cloud/wpsuite-core": "^2.4.0"
44
44
  },
45
45
  "peerDependencies": {
46
46
  "@aws-amplify/core": "^6.18.0",
47
- "@smart-cloud/aws-amplify-ui": "6.15.5",
48
- "@smart-cloud/aws-amplify-ui-react": "6.15.5",
49
- "@wordpress/data": "^10.52.0",
47
+ "@smart-cloud/aws-amplify-ui": "6.15.7-preview.1",
48
+ "@smart-cloud/aws-amplify-ui-react": "6.15.7-preview.1",
49
+ "@wordpress/data": "^10.54.0",
50
50
  "aws-amplify": "^6.20.0",
51
- "jose": "^6.2.5"
51
+ "jose": "^6.2.12"
52
52
  },
53
53
  "devDependencies": {
54
54
  "@aws-amplify/core": "^6.18.0",
55
- "@smart-cloud/aws-amplify-ui": "6.15.5",
56
- "@smart-cloud/aws-amplify-ui-react": "6.15.5",
57
55
  "@eslint/js": "^10.0.1",
58
- "@types/node": "^26.1.2",
59
- "@types/react": "^18.3.28",
56
+ "@smart-cloud/aws-amplify-ui": "6.15.7-preview.1",
57
+ "@smart-cloud/aws-amplify-ui-react": "6.15.7-preview.1",
58
+ "@types/node": "^26.4.1",
59
+ "@types/react": "^18.3.31",
60
60
  "@types/react-dom": "^18.3.7",
61
- "@typescript-eslint/eslint-plugin": "^8.65.0",
62
- "@typescript-eslint/parser": "^8.65.0",
63
- "@wordpress/data": "^10.52.0",
61
+ "@typescript-eslint/eslint-plugin": "^8.69.0",
62
+ "@typescript-eslint/parser": "^8.69.0",
63
+ "@wordpress/data": "^10.54.0",
64
64
  "aws-amplify": "^6.20.0",
65
- "eslint": "^10.8.0",
66
- "globals": "^17.8.0",
67
- "jose": "^6.2.5",
65
+ "eslint": "^10.10.0",
66
+ "globals": "^17.12.0",
67
+ "jose": "^6.2.12",
68
68
  "react": "^18.3.1",
69
69
  "react-dom": "^18.3.1",
70
70
  "tsup": "^8.5.1",
71
71
  "typescript": "^6.0.3",
72
- "typescript-eslint": "^8.65.0"
72
+ "typescript-eslint": "^8.69.0"
73
73
  }
74
74
  }