@smart-cloud/gatey-core 2.3.3 → 2.3.5

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 E=Object.defineProperty;var $=Object.getOwnPropertyDescriptor;var Q=Object.getOwnPropertyNames;var Z=Object.prototype.hasOwnProperty;var ee=(e,t)=>{for(var n in t)E(e,n,{get:t[n],enumerable:!0})},te=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Q(t))!Z.call(e,r)&&r!==n&&E(e,r,{get:()=>t[r],enumerable:!(o=$(t,r))||o.enumerable});return e};var ne=e=>te(E({},"__esModule",{value:!0}),e);var fe={};ee(fe,{TEXT_DOMAIN:()=>B,clearMfaPreferences:()=>N,configureAmplify:()=>P,getAmplifyConfig:()=>T,getGateyPlugin:()=>u,getGroups:()=>b,getMfaPreferences:()=>_,getPreferredRole:()=>W,getRoles:()=>M,getScopes:()=>z,getStore:()=>l,getStoreDispatch:()=>d,getStoreSelect:()=>O,getUserAttributes:()=>L,initializeGatey:()=>de,isAuthenticated:()=>k,isInGroup:()=>D,loadAuthSession:()=>f,loadMFAPreferences:()=>G,loadUserAttributes:()=>F,login:()=>Y,logout:()=>w,observeStore:()=>S,sanitizeAuthenticatorConfig:()=>I,store:()=>pe,waitForGateyReady:()=>x});module.exports=ne(fe);var a=require("aws-amplify/api");function u(){return globalThis.WpSuite?.plugins?.gatey}async function x(e=8e3){let t=u();if(t?.status!=="available"){if(t?.status==="error")throw new Error("Gatey failed");await new Promise((n,o)=>{let r=()=>A(n),y=()=>A(()=>o(new Error("Gatey failed"))),A=c=>{window.removeEventListener("wpsuite:gatey:ready",r),window.removeEventListener("wpsuite:gatey:error",y),s&&clearTimeout(s),c()};window.addEventListener("wpsuite:gatey:ready",r,{once:!0}),window.addEventListener("wpsuite:gatey:error",y,{once:!0});let s=e?window.setTimeout(()=>A(()=>o(new Error("Gatey timeout"))),e):0})}}async function l(e=1e4){await x(e);let n=u()?.cognito?.store;if(!n)throw new Error("Gatey store is not available");return n}var v=require("aws-amplify"),i=require("aws-amplify/auth");var V=require("aws-amplify/auth"),R=require("aws-amplify/utils"),g=require("@wordpress/data"),j=require("@smart-cloud/wpsuite-core");var h="gatey_account",B="gatey";var U;typeof WpSuite<"u"?U=WpSuite.siteSettings:U={};var C=e=>{e?.username?window.localStorage.setItem(h,JSON.stringify(e)):window.localStorage.removeItem(h)},m=async e=>{let t=JSON.parse(window.localStorage.getItem(h)??"{}"),n=!1;if(t?.username)try{let o=await(0,V.fetchAuthSession)();o?.tokens?.accessToken?.payload?.exp&&o.tokens.accessToken.payload.exp>new Date().getTime()/1e3&&(n=!0)}catch(o){console.error(o)}else try{t=await X(!1),t?.username&&(C(t),t.loaded=!0,n=!0)}catch(o){console.error(o)}return!n&&t?.username&&(C({}),l().then(async o=>{await w(e?.signOutHook),d(o).clearAccount()})),t},oe=async e=>{let t=window.location.hostname.toLowerCase().split(":")[0],n=u();if(!n)throw new Error("Gatey plugin is not available");let 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,r={Auth:{Cognito:{userPoolClientId:"",userPoolId:"",identityPoolId:"",...o.Auth?.Cognito,loginWith:{oauth:{domain:"",scopes:[],responseType:"code",...o.Auth?.Cognito?.loginWith?.oauth,redirectSignIn:[window.location.origin+n.settings?.signInPage],redirectSignOut:[window.location.origin+n.settings?.signInPage]}}}},API:{...o.API,REST:{...o.API?.REST,admin:{endpoint:n.restUrl}}}},y=e?.apiConfigurations?.secondary?.domains&&t.toLowerCase().match(e.apiConfigurations.secondary?.domains.toLowerCase())&&e.apiConfigurations?.secondary?.apis?.length?e.apiConfigurations.secondary:e?.apiConfigurations?.default;y?.apis?.forEach(s=>{let c=r.API?.REST;c&&(c[s.name]={endpoint:s.endpoint,region:s.region})}),P(r,{API:{REST:{headers:async s=>{let c=y?.apis?.find(p=>p.name===s.apiName);if(s.apiName==="admin"||c?.authorization==="ID_TOKEN"||c?.authorization==="ACCESS_TOKEN")try{let p=await f();if(p?.tokens?.idToken&&p?.tokens?.accessToken)return{Authorization:`Bearer ${s.apiName==="admin"||c?.authorization==="ID_TOKEN"?p.tokens.idToken.toString():p.tokens.accessToken.toString()}`}}catch(p){console.error(p),l().then(H=>{d(H).clearAccount()})}return{}}}}})},re=async()=>{let e=u();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="+U.lastUpdate).then(n=>n.ok?n.text():null).then(n=>n?JSON.parse(n):null).catch(()=>null)),t??null},I=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},ie=async()=>{let e=I(await(0,j.getConfig)("gatey"));oe(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,o=await m(n),r=await re();return{config:e,amplifyConfig:{},account:o,signedIn:!!o?.username&&!o.loaded,nextUrl:void 0,language:void 0,direction:void 0,customTranslations:r,reloadAuthSession:0,reloadUserAttributes:0,reloadMFAPreferences:0}},se={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.I18n.setLanguage(""):R.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"}}},ae={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}},ue={},d=e=>(0,g.dispatch)(e),O=e=>(0,g.select)(e),K=async()=>{let e=await ie(),t=(0,g.createReduxStore)("smartcloud/gatey",{reducer(n=e,o){switch(o.type){case"SET_AMPLIFY_CONFIG":return{...n,amplifyConfig:o.amplifyConfig};case"SET_ACCOUNT":return C(o.account),{...n,account:o.account};case"CLEAR_ACCOUNT":return C({}),{...n,account:{}};case"RELOAD_AUTH_SESSION":{let r=Math.random();return{...n,reloadAuthSession:n.reloadAuthSession!==r?r:r+1}}case"RELOAD_USER_ATTRIBUTES":{let r=Math.random();return{...n,reloadUserAttributes:n.reloadUserAttributes!==r?r:r+1}}case"RELOAD_MFA_PREFERENCE":{let r=Math.random();return{...n,reloadMFAPreferences:n.reloadMFAPreferences!==r?r:r+1}}case"SET_SIGNED_IN":return{...n,signedIn:o.signedIn};case"SET_NEXT_URL":return{...n,nextUrl:o.nextUrl};case"SET_LANGUAGE":return{...n,language:o.language};case"SET_DIRECTION":return{...n,direction:o.direction}}return n},actions:se,selectors:ae,resolvers:ue});return(0,g.register)(t),t},S=(e,t,n)=>{let o;function r(){let A=O(e).getState(),s=t(A);if(s!==o){let c=o;o=s,n(o,c)}}let y=(0,g.subscribe)(r,e);return r(),y};var T=()=>v.Amplify.getConfig(),P=(e,t)=>{v.Amplify.configure(e,t)},f=e=>(0,i.fetchAuthSession)(e),F=()=>(0,i.fetchUserAttributes)(),G=()=>(0,i.fetchMFAPreference)(),X=async(e=!0)=>{let t=e?await m():{};if(t?.username)return t;try{if((await(0,i.fetchAuthSession)()).tokens)return{username:(await(0,i.getCurrentUser)()).username,userAttributes:await F(),mfaPreferences:await G()}}catch(n){console.error(n);try{await(0,i.signOut)()}catch{}}return{}},N=async()=>{await(0,i.updateMFAPreference)({totp:"DISABLED"})},J=()=>m().then(e=>e?.username),L=()=>m().then(e=>e?.userAttributes),_=()=>m().then(e=>e?.mfaPreferences),k=()=>m().then(e=>!!e?.username),D=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)}),M=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)}),W=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)}),z=()=>f().then(e=>e.tokens?.accessToken.payload.scope?.split(" ")??[]).catch(e=>{console.error(e)}),Y=async e=>{let t,n=u();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(r=>r.body.json()).then(r=>{if(r instanceof Object&&"redirect"in r)return r?.redirect}).catch(r=>{console.error(r)})),e&&await n.cognito.get({apiName:e.apiName,path:e.path,options:e.options}).response.catch(o=>console.error(o)),n.settings.redirectSignIn??t},w=async e=>{let t=u();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(o=>o.body.json()).then(o=>{if(o instanceof Object&&"redirect"in o)return o?.redirect}).catch(o=>{console.error(o)})),e&&await t.cognito.get({apiName:e.apiName,path:e.path,options:e.options}).response.catch(o=>console.error(o));try{await(0,i.signOut)()}catch{}return t.settings.redirectSignOut??n??t.settings.signInPage??"/"};var q=require("@smart-cloud/wpsuite-core");var ce=()=>{l().then(e=>{S(e,t=>t.nextUrl,async t=>{t&&window.location.assign(t)}),d(e).clearAccount()}).catch(e=>{console.error("Gatey signOut error:",e)})},ge=e=>{l().then(t=>{d(t).setLanguage(e??"en")}).catch(t=>{console.error("Gatey setLanguage error:",t)})},le=e=>{l().then(t=>{d(t).setDirection(e??"auto")}).catch(t=>{console.error("Gatey setDirection error:",t)})};var pe=async()=>l(),de=()=>{let e=globalThis.WpSuite,t=u();if(!t)throw new Error("Gatey plugin is not available");(0,q.attachDefaultPluginRuntime)(t),t.status=t.status??"initializing";let n=K();return t.cognito={store:n,observeStore:S,setLanguage:ge,setDirection:le,getAmplifyConfig:T,isAuthenticated:k,isInGroup:D,getUsername:J,getUserAttributes:L,getMfaPreferences:_,clearMfaPreferences:N,getGroups:b,getRoles:M,getPreferredRole:W,getScopes:z,signOut:ce,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(o=>{t.status="error",e?.events?.emit("wpsuite:gatey:error",{key:t.key,error:String(o)})}),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,sanitizeAuthenticatorConfig,store,waitForGateyReady});
1
+ "use strict";var x=Object.defineProperty;var ee=Object.getOwnPropertyDescriptor;var te=Object.getOwnPropertyNames;var ne=Object.prototype.hasOwnProperty;var re=(e,t)=>{for(var n in t)x(e,n,{get:t[n],enumerable:!0})},oe=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of te(t))!ne.call(e,o)&&o!==n&&x(e,o,{get:()=>t[o],enumerable:!(r=ee(t,o))||r.enumerable});return e};var ie=e=>oe(x({},"__esModule",{value:!0}),e);var Ae={};re(Ae,{TEXT_DOMAIN:()=>K,clearMfaPreferences:()=>_,configureAmplify:()=>T,getAmplifyConfig:()=>E,getGateyPlugin:()=>s,getGroups:()=>R,getMfaPreferences:()=>D,getPreferredRole:()=>B,getRoles:()=>z,getScopes:()=>V,getStore:()=>p,getStoreDispatch:()=>y,getStoreSelect:()=>O,getUserAttributes:()=>k,initializeGatey:()=>me,isAuthenticated:()=>M,isInGroup:()=>W,loadAuthSession:()=>m,loadMFAPreferences:()=>N,loadUserAttributes:()=>L,login:()=>$,logout:()=>b,observeStore:()=>C,resolveGateyRedirectTarget:()=>j,resolveGateyTarget:()=>l,sanitizeAuthenticatorConfig:()=>G,store:()=>ye,waitForGateyReady:()=>U});module.exports=ie(Ae);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 r=s()?.siteUrl?.trim()||window.location.href,o=t.startsWith("/")?t.replace(/^\/+/,""):t;return new URL(o,r).toString()}catch{return t}}function j(e){let t=e?.trim();if(!t)return;let n=/^[a-z][a-z\d+.-]*:/i.test(t),r=t.startsWith("/");if(!n&&!r)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((n,r)=>{let o=()=>d(n),c=()=>d(()=>r(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(()=>r(new Error("Gatey timeout"))),e):0})}}async function p(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 X=require("aws-amplify/auth"),v=require("aws-amplify/utils"),g=require("@wordpress/data"),J=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)??"{}"),n=!1;if(t?.username)try{let r=await(0,X.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 q(!1),t?.username&&(w(t),t.loaded=!0,n=!0)}catch(r){console.error(r)}return!n&&t?.username&&(w({}),p().then(async r=>{await b(e?.signOutHook),y(r).clearAccount()})),t},se=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,c={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}}}},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(Z=>{y(Z).clearAccount()})}return{}}}}})},ae=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},G=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},ue=async()=>{let e=G(await(0,J.getConfig)("gatey"));se(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 ae();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}},ce={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"}}},ge={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}},le={},y=e=>(0,g.dispatch)(e),O=e=>(0,g.select)(e),Y=async()=>{let e=await ue(),t=(0,g.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:ce,selectors:ge,resolvers:le});return(0,g.register)(t),t},C=(e,t,n)=>{let r;function o(){let d=O(e).getState(),S=t(d);if(S!==r){let u=r;r=S,n(r,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)(),q=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(n){console.error(n);try{await(0,i.signOut)()}catch{}}return{}},_=async()=>{await(0,i.updateMFAPreference)({totp:"DISABLED"})},H=()=>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)}),B=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)}),V=()=>m().then(e=>e.tokens?.accessToken.payload.scope?.split(" ")??[]).catch(e=>{console.error(e)}),$=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},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 l(t.settings.redirectSignOut)??n??l(t.settings.signInPage)??"/"};var Q=require("@smart-cloud/wpsuite-core");var pe=()=>{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)})},de=e=>{p().then(t=>{y(t).setLanguage(e??"en")}).catch(t=>{console.error("Gatey setLanguage error:",t)})},fe=e=>{p().then(t=>{y(t).setDirection(e??"auto")}).catch(t=>{console.error("Gatey setDirection error:",t)})};var ye=async()=>p(),me=()=>{let e=globalThis.WpSuite,t=s();if(!t)throw new Error("Gatey plugin is not available");(0,Q.attachDefaultPluginRuntime)(t),t.status=t.status??"initializing";let n=Y();return t.cognito={store:n,observeStore:C,setLanguage:de,setDirection:fe,getAmplifyConfig:E,isAuthenticated:M,isInGroup:W,getUsername:H,getUserAttributes:k,getMfaPreferences:D,clearMfaPreferences:_,getGroups:R,getRoles:z,getPreferredRole:B,getScopes:V,signOut:pe,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,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, 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 {
@@ -68,7 +68,11 @@ export interface Gatey {
68
68
  nonce: string;
69
69
  restUrl: string;
70
70
  }
71
- export { getGateyPlugin, getStore, waitForGateyReady, type GateyErrorEvent, type GateyPlugin, type GateyReadyEvent, };
71
+ export interface GateySiteRuntime {
72
+ /** Current WordPress site's canonical URL, including a Multisite path. */
73
+ siteUrl?: string;
74
+ }
75
+ export { getGateyPlugin, getStore, resolveGateyRedirectTarget, resolveGateyTarget, waitForGateyReady, type GateyErrorEvent, type GateyPlugin, type GateyReadyEvent, };
72
76
  export { clearMfaPreferences, getGroups, getMfaPreferences, getPreferredRole, getRoles, getScopes, getUserAttributes, isAuthenticated, isInGroup, };
73
77
  export { configureAmplify, getAmplifyConfig, loadAuthSession, loadMFAPreferences, loadUserAttributes, login, logout, type Account, } from "./auth";
74
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 ce,get as ge,head as le,patch as pe,post as de,put as fe}from"aws-amplify/api";function a(){return globalThis.WpSuite?.plugins?.gatey}async function T(e=8e3){let t=a();if(t?.status!=="available"){if(t?.status==="error")throw new Error("Gatey failed");await new Promise((n,o)=>{let r=()=>f(n),g=()=>f(()=>o(new Error("Gatey failed"))),f=s=>{window.removeEventListener("wpsuite:gatey:ready",r),window.removeEventListener("wpsuite:gatey:error",g),i&&clearTimeout(i),s()};window.addEventListener("wpsuite:gatey:ready",r,{once:!0}),window.addEventListener("wpsuite:gatey:error",g,{once:!0});let i=e?window.setTimeout(()=>f(()=>o(new Error("Gatey timeout"))),e):0})}}async function c(e=1e4){await T(e);let n=a()?.cognito?.store;if(!n)throw new Error("Gatey store is not available");return n}import{Amplify as I}from"aws-amplify";import{fetchAuthSession as O,fetchMFAPreference as re,fetchUserAttributes as ie,getCurrentUser as se,signOut as v,updateMFAPreference as ae}from"aws-amplify/auth";import{fetchAuthSession as K}from"aws-amplify/auth";import{I18n as b}from"aws-amplify/utils";import{createReduxStore as X,dispatch as J,register as Y,select as q,subscribe as H}from"@wordpress/data";import{getConfig as $}from"@smart-cloud/wpsuite-core";var y="gatey_account",j="gatey";var S;typeof WpSuite<"u"?S=WpSuite.siteSettings:S={};var m=e=>{e?.username?window.localStorage.setItem(y,JSON.stringify(e)):window.localStorage.removeItem(y)},l=async e=>{let t=JSON.parse(window.localStorage.getItem(y)??"{}"),n=!1;if(t?.username)try{let o=await K();o?.tokens?.accessToken?.payload?.exp&&o.tokens.accessToken.payload.exp>new Date().getTime()/1e3&&(n=!0)}catch(o){console.error(o)}else try{t=await U(!1),t?.username&&(m(t),t.loaded=!0,n=!0)}catch(o){console.error(o)}return!n&&t?.username&&(m({}),c().then(async o=>{await C(e?.signOutHook),p(o).clearAccount()})),t},Q=async e=>{let t=window.location.hostname.toLowerCase().split(":")[0],n=a();if(!n)throw new Error("Gatey plugin is not available");let 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,r={Auth:{Cognito:{userPoolClientId:"",userPoolId:"",identityPoolId:"",...o.Auth?.Cognito,loginWith:{oauth:{domain:"",scopes:[],responseType:"code",...o.Auth?.Cognito?.loginWith?.oauth,redirectSignIn:[window.location.origin+n.settings?.signInPage],redirectSignOut:[window.location.origin+n.settings?.signInPage]}}}},API:{...o.API,REST:{...o.API?.REST,admin:{endpoint:n.restUrl}}}},g=e?.apiConfigurations?.secondary?.domains&&t.toLowerCase().match(e.apiConfigurations.secondary?.domains.toLowerCase())&&e.apiConfigurations?.secondary?.apis?.length?e.apiConfigurations.secondary:e?.apiConfigurations?.default;g?.apis?.forEach(i=>{let s=r.API?.REST;s&&(s[i.name]={endpoint:i.endpoint,region:i.region})}),h(r,{API:{REST:{headers:async i=>{let s=g?.apis?.find(u=>u.name===i.apiName);if(i.apiName==="admin"||s?.authorization==="ID_TOKEN"||s?.authorization==="ACCESS_TOKEN")try{let u=await d();if(u?.tokens?.idToken&&u?.tokens?.accessToken)return{Authorization:`Bearer ${i.apiName==="admin"||s?.authorization==="ID_TOKEN"?u.tokens.idToken.toString():u.tokens.accessToken.toString()}`}}catch(u){console.error(u),c().then(V=>{p(V).clearAccount()})}return{}}}}})},Z=async()=>{let e=a();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="+S.lastUpdate).then(n=>n.ok?n.text():null).then(n=>n?JSON.parse(n):null).catch(()=>null)),t??null},E=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},ee=async()=>{let e=E(await $("gatey"));Q(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,o=await l(n),r=await Z();return{config:e,amplifyConfig:{},account:o,signedIn:!!o?.username&&!o.loaded,nextUrl:void 0,language:void 0,direction:void 0,customTranslations:r,reloadAuthSession:0,reloadUserAttributes:0,reloadMFAPreferences:0}},te={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"?b.setLanguage(""):b.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"}}},ne={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}},oe={},p=e=>J(e),x=e=>q(e),R=async()=>{let e=await ee(),t=X("smartcloud/gatey",{reducer(n=e,o){switch(o.type){case"SET_AMPLIFY_CONFIG":return{...n,amplifyConfig:o.amplifyConfig};case"SET_ACCOUNT":return m(o.account),{...n,account:o.account};case"CLEAR_ACCOUNT":return m({}),{...n,account:{}};case"RELOAD_AUTH_SESSION":{let r=Math.random();return{...n,reloadAuthSession:n.reloadAuthSession!==r?r:r+1}}case"RELOAD_USER_ATTRIBUTES":{let r=Math.random();return{...n,reloadUserAttributes:n.reloadUserAttributes!==r?r:r+1}}case"RELOAD_MFA_PREFERENCE":{let r=Math.random();return{...n,reloadMFAPreferences:n.reloadMFAPreferences!==r?r:r+1}}case"SET_SIGNED_IN":return{...n,signedIn:o.signedIn};case"SET_NEXT_URL":return{...n,nextUrl:o.nextUrl};case"SET_LANGUAGE":return{...n,language:o.language};case"SET_DIRECTION":return{...n,direction:o.direction}}return n},actions:te,selectors:ne,resolvers:oe});return Y(t),t},A=(e,t,n)=>{let o;function r(){let f=x(e).getState(),i=t(f);if(i!==o){let s=o;o=i,n(o,s)}}let g=H(r,e);return r(),g};var P=()=>I.getConfig(),h=(e,t)=>{I.configure(e,t)},d=e=>O(e),F=()=>ie(),G=()=>re(),U=async(e=!0)=>{let t=e?await l():{};if(t?.username)return t;try{if((await O()).tokens)return{username:(await se()).username,userAttributes:await F(),mfaPreferences:await G()}}catch(n){console.error(n);try{await v()}catch{}}return{}},N=async()=>{await ae({totp:"DISABLED"})},L=()=>l().then(e=>e?.username),_=()=>l().then(e=>e?.userAttributes),k=()=>l().then(e=>e?.mfaPreferences),D=()=>l().then(e=>!!e?.username),M=e=>w().then(t=>t?.includes(e)||!1),w=()=>d().then(e=>e.tokens?.idToken?.payload["cognito:groups"]instanceof Array?e.tokens.idToken.payload["cognito:groups"].map(t=>t):[]).catch(e=>{console.error(e)}),W=async()=>d().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)}),z=async()=>d().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=()=>d().then(e=>e.tokens?.accessToken.payload.scope?.split(" ")??[]).catch(e=>{console.error(e)}),ue=async e=>{let t,n=a();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(r=>r.body.json()).then(r=>{if(r instanceof Object&&"redirect"in r)return r?.redirect}).catch(r=>{console.error(r)})),e&&await n.cognito.get({apiName:e.apiName,path:e.path,options:e.options}).response.catch(o=>console.error(o)),n.settings.redirectSignIn??t},C=async e=>{let t=a();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(o=>o.body.json()).then(o=>{if(o instanceof Object&&"redirect"in o)return o?.redirect}).catch(o=>{console.error(o)})),e&&await t.cognito.get({apiName:e.apiName,path:e.path,options:e.options}).response.catch(o=>console.error(o));try{await v()}catch{}return t.settings.redirectSignOut??n??t.settings.signInPage??"/"};import{attachDefaultPluginRuntime as ye}from"@smart-cloud/wpsuite-core";var me=()=>{c().then(e=>{A(e,t=>t.nextUrl,async t=>{t&&window.location.assign(t)}),p(e).clearAccount()}).catch(e=>{console.error("Gatey signOut error:",e)})},Ae=e=>{c().then(t=>{p(t).setLanguage(e??"en")}).catch(t=>{console.error("Gatey setLanguage error:",t)})},Se=e=>{c().then(t=>{p(t).setDirection(e??"auto")}).catch(t=>{console.error("Gatey setDirection error:",t)})};var We=async()=>c(),ze=()=>{let e=globalThis.WpSuite,t=a();if(!t)throw new Error("Gatey plugin is not available");ye(t),t.status=t.status??"initializing";let n=R();return t.cognito={store:n,observeStore:A,setLanguage:Ae,setDirection:Se,getAmplifyConfig:P,isAuthenticated:D,isInGroup:M,getUsername:L,getUserAttributes:_,getMfaPreferences:k,clearMfaPreferences:N,getGroups:w,getRoles:W,getPreferredRole:z,getScopes:B,signOut:me,get:ge,post:de,put:fe,del:ce,head:le,patch:pe},n.then(()=>{t.status="available",e?.events?.emit("wpsuite:gatey:ready",{key:t.key,version:t.version})}).catch(o=>{t.status="error",e?.events?.emit("wpsuite:gatey:error",{key:t.key,error:String(o)})}),t};export{j as TEXT_DOMAIN,N as clearMfaPreferences,h as configureAmplify,P as getAmplifyConfig,a as getGateyPlugin,w as getGroups,k as getMfaPreferences,z as getPreferredRole,W as getRoles,B as getScopes,c as getStore,p as getStoreDispatch,x as getStoreSelect,_ as getUserAttributes,ze as initializeGatey,D as isAuthenticated,M as isInGroup,d as loadAuthSession,G as loadMFAPreferences,F as loadUserAttributes,ue as login,C as logout,A as observeStore,E as sanitizeAuthenticatorConfig,We as store,T as waitForGateyReady};
1
+ import{del as pe,get as de,head as fe,patch as ye,post as me,put as Ae}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 r=s()?.siteUrl?.trim()||window.location.href,o=t.startsWith("/")?t.replace(/^\/+/,""):t;return new URL(o,r).toString()}catch{return t}}function X(e){let t=e?.trim();if(!t)return;let n=/^[a-z][a-z\d+.-]*:/i.test(t),r=t.startsWith("/");if(!n&&!r)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((n,r)=>{let o=()=>u(n),a=()=>u(()=>r(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(()=>r(new Error("Gatey timeout"))),e):0})}}async function l(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 G}from"aws-amplify";import{fetchAuthSession as O,fetchMFAPreference as ae,fetchUserAttributes as ue,getCurrentUser as ce,signOut as F,updateMFAPreference as ge}from"aws-amplify/auth";import{fetchAuthSession as Y}from"aws-amplify/auth";import{I18n as R}from"aws-amplify/utils";import{createReduxStore as q,dispatch as H,register as $,select as Q,subscribe as Z}from"@wordpress/data";import{getConfig as ee}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)??"{}"),n=!1;if(t?.username)try{let r=await Y();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({}),l().then(async r=>{await w(e?.signOutHook),d(r).clearAccount()})),t},te=async e=>{let t=window.location.hostname.toLowerCase().split(":")[0],n=s();if(!n)throw new Error("Gatey plugin is not available");let r=g(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,a={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}}}},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");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},x=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},re=async()=>{let e=x(await ee("gatey"));te(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 ne();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}},oe={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"}}},ie={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}},se={},d=e=>H(e),U=e=>Q(e),v=async()=>{let e=await re(),t=q("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:oe,selectors:ie,resolvers:se});return $(t),t},h=(e,t,n)=>{let r;function o(){let u=U(e).getState(),y=t(u);if(y!==r){let i=r;r=y,n(r,i)}}let a=Z(o,e);return o(),a};var T=()=>G.getConfig(),P=(e,t)=>{G.configure(e,t)},f=e=>O(e),L=()=>ue(),N=()=>ae(),I=async(e=!0)=>{let t=e?await p():{};if(t?.username)return t;try{if((await O()).tokens)return{username:(await ce()).username,userAttributes:await L(),mfaPreferences:await N()}}catch(n){console.error(n);try{await F()}catch{}}return{}},_=async()=>{await ge({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)}),le=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)),g(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 g(t.settings.redirectSignOut)??n??g(t.settings.signInPage)??"/"};import{attachDefaultPluginRuntime as Se}from"@smart-cloud/wpsuite-core";var he=()=>{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)})},Ce=e=>{l().then(t=>{d(t).setLanguage(e??"en")}).catch(t=>{console.error("Gatey setLanguage error:",t)})},Pe=e=>{l().then(t=>{d(t).setDirection(e??"auto")}).catch(t=>{console.error("Gatey setDirection error:",t)})};var Ve=async()=>l(),je=()=>{let e=globalThis.WpSuite,t=s();if(!t)throw new Error("Gatey plugin is not available");Se(t),t.status=t.status??"initializing";let n=v();return t.cognito={store:n,observeStore:h,setLanguage:Ce,setDirection:Pe,getAmplifyConfig:T,isAuthenticated:W,isInGroup:z,getUsername:k,getUserAttributes:D,getMfaPreferences:M,clearMfaPreferences:_,getGroups:b,getRoles:B,getPreferredRole:V,getScopes:j,signOut:he,get:de,post:me,put:Ae,del:pe,head:fe,patch:ye},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{J 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,l as getStore,d as getStoreDispatch,U as getStoreSelect,D as getUserAttributes,je as initializeGatey,W as isAuthenticated,z as isInGroup,f as loadAuthSession,N as loadMFAPreferences,L as loadUserAttributes,le as login,w as logout,h as observeStore,X as resolveGateyRedirectTarget,g as resolveGateyTarget,x as sanitizeAuthenticatorConfig,Ve as store,E as waitForGateyReady};
package/dist/runtime.d.ts CHANGED
@@ -1,8 +1,33 @@
1
- import { WpSuitePluginBase } from "@smart-cloud/wpsuite-core";
2
- import { Gatey } from "./index";
1
+ import type { WpSuitePluginBase } from "@smart-cloud/wpsuite-core";
2
+ import type { Gatey, GateySiteRuntime } from "./index";
3
3
  export type GateyReadyEvent = "wpsuite:gatey:ready";
4
4
  export type GateyErrorEvent = "wpsuite:gatey:error";
5
- export type GateyPlugin = WpSuitePluginBase & Gatey;
5
+ export type GateyPlugin = WpSuitePluginBase & Gatey & GateySiteRuntime;
6
6
  export declare function getGateyPlugin(): GateyPlugin;
7
+ /**
8
+ * Resolve a page selected in Gatey's WordPress settings to its site's URL.
9
+ *
10
+ * Settings deliberately store a portable page path such as `/sign-in`, but
11
+ * browser navigation interprets that path from the domain root. On a
12
+ * subdirectory Multisite that would escape `/saas-launch/`. PHP's `site_url()`
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).
16
+ */
17
+ export declare function resolveGateyTarget(target: string | null | undefined): string | undefined;
18
+ /**
19
+ * Resolve an explicit return URL supplied by a `redirect_to` query parameter.
20
+ *
21
+ * This has deliberately different semantics from a saved Gatey page setting:
22
+ * `/sign-in` in settings is portable and site-relative, whereas a return URL
23
+ * such as `/saas-launch/profile` already names an origin-relative request.
24
+ * Do not rebase the latter on the current Multisite blog path.
25
+ *
26
+ * Absolute return URLs are accepted only when they remain on the current
27
+ * browser origin. This prevents an untrusted query parameter becoming an open
28
+ * redirect after a successful sign-in. Bare legacy values keep the normal
29
+ * site-relative resolution behaviour.
30
+ */
31
+ export declare function resolveGateyRedirectTarget(target: string | null | undefined): string | undefined;
7
32
  export declare function waitForGateyReady(timeoutMs?: number): Promise<void>;
8
33
  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.3",
3
+ "version": "2.3.5",
4
4
  "description": "Login & SSO with Amazon Cognito",
5
5
  "author": "Smart Cloud Solutions Inc.",
6
6
  "license": "MIT",
@@ -23,7 +23,7 @@
23
23
  "build:js": "tsup --minify",
24
24
  "build:types": "tsc -p tsconfig.types.json",
25
25
  "lint": "eslint 'src/**/*.ts' --report-unused-disable-directives --max-warnings 0",
26
- "test": "echo \"Error: no test specified\" && exit 1",
26
+ "test": "node --test tests/*.test.ts",
27
27
  "release:npm": "WPSUITE_PREMIUM=true yarn build && npm publish --access=public --registry=https://registry.npmjs.org/"
28
28
  },
29
29
  "publishConfig": {