@smart-cloud/gatey-core 2.2.6 → 2.2.8
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/auth.d.ts +27 -0
- package/dist/constants.d.ts +2 -0
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +17 -169
- package/dist/index.js +1 -1
- package/dist/runtime.d.ts +8 -0
- package/dist/store.d.ts +126 -0
- package/package.json +17 -15
- package/dist/index.d.cts +0 -229
package/dist/auth.d.ts
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { type ResourcesConfig } from "aws-amplify";
|
|
2
|
+
import { type AuthSession, type FetchAuthSessionOptions, type FetchMFAPreferenceOutput, type FetchUserAttributesOutput } from "aws-amplify/auth";
|
|
3
|
+
import { type ApiConfiguration } from "./store";
|
|
4
|
+
export interface Account {
|
|
5
|
+
username?: string;
|
|
6
|
+
loaded?: boolean;
|
|
7
|
+
userAttributes?: FetchUserAttributesOutput;
|
|
8
|
+
mfaPreferences?: FetchMFAPreferenceOutput;
|
|
9
|
+
}
|
|
10
|
+
export declare const getAmplifyConfig: () => ResourcesConfig;
|
|
11
|
+
export declare const configureAmplify: (resourcesConfig: ResourcesConfig, libraryOptions?: Record<string, unknown>) => void;
|
|
12
|
+
export declare const loadAuthSession: (options?: FetchAuthSessionOptions) => Promise<AuthSession>;
|
|
13
|
+
export declare const loadUserAttributes: () => Promise<FetchUserAttributesOutput>;
|
|
14
|
+
export declare const loadMFAPreferences: () => Promise<FetchMFAPreferenceOutput>;
|
|
15
|
+
export declare const loadUser: (checkStorage?: boolean) => Promise<Account>;
|
|
16
|
+
export declare const clearMfaPreferences: () => Promise<void>;
|
|
17
|
+
export declare const getUsername: () => Promise<string | undefined>;
|
|
18
|
+
export declare const getUserAttributes: () => Promise<FetchUserAttributesOutput | undefined>;
|
|
19
|
+
export declare const getMfaPreferences: () => Promise<FetchMFAPreferenceOutput | undefined>;
|
|
20
|
+
export declare const isAuthenticated: () => Promise<boolean>;
|
|
21
|
+
export declare const isInGroup: (group: string) => Promise<boolean>;
|
|
22
|
+
export declare const getGroups: () => Promise<string[] | undefined>;
|
|
23
|
+
export declare const getRoles: () => Promise<string[] | undefined>;
|
|
24
|
+
export declare const getPreferredRole: () => Promise<string | undefined>;
|
|
25
|
+
export declare const getScopes: () => Promise<string[] | undefined>;
|
|
26
|
+
export declare const login: (signInHook: ApiConfiguration["signInHook"]) => Promise<string | undefined>;
|
|
27
|
+
export declare const logout: (signOutHook: ApiConfiguration["signOutHook"]) => Promise<string | undefined>;
|
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var b=Object.defineProperty;var $=Object.getOwnPropertyDescriptor;var Q=Object.getOwnPropertyNames;var Z=Object.prototype.hasOwnProperty;var ee=(e,t)=>{for(var n in t)b(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&&b(e,r,{get:()=>t[r],enumerable:!(o=$(t,r))||o.enumerable});return e};var ne=e=>te(b({},"__esModule",{value:!0}),e);var fe={};ee(fe,{TEXT_DOMAIN:()=>B,clearMfaPreferences:()=>N,configureAmplify:()=>P,getAmplifyConfig:()=>T,getGateyPlugin:()=>u,getGroups:()=>E,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=>E().then(t=>t?.includes(e)||!1),E=()=>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};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:E,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 b=Object.defineProperty;var $=Object.getOwnPropertyDescriptor;var Q=Object.getOwnPropertyNames;var Z=Object.prototype.hasOwnProperty;var ee=(e,t)=>{for(var n in t)b(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&&b(e,r,{get:()=>t[r],enumerable:!(o=$(t,r))||o.enumerable});return e};var ne=e=>te(b({},"__esModule",{value:!0}),e);var fe={};ee(fe,{TEXT_DOMAIN:()=>B,clearMfaPreferences:()=>N,configureAmplify:()=>P,getAmplifyConfig:()=>T,getGateyPlugin:()=>u,getGroups:()=>E,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=>E().then(t=>t?.includes(e)||!1),E=()=>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:E,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});
|
package/dist/index.d.ts
CHANGED
|
@@ -1,167 +1,14 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { ResourcesConfig } from
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
interface Account {
|
|
10
|
-
username?: string;
|
|
11
|
-
loaded?: boolean;
|
|
12
|
-
userAttributes?: FetchUserAttributesOutput;
|
|
13
|
-
mfaPreferences?: FetchMFAPreferenceOutput;
|
|
14
|
-
}
|
|
15
|
-
declare const getAmplifyConfig: () => ResourcesConfig;
|
|
16
|
-
declare const configureAmplify: (resourcesConfig: ResourcesConfig, libraryOptions?: Record<string, unknown>) => void;
|
|
17
|
-
declare const loadAuthSession: (options?: FetchAuthSessionOptions) => Promise<AuthSession>;
|
|
18
|
-
declare const loadUserAttributes: () => Promise<FetchUserAttributesOutput>;
|
|
19
|
-
declare const loadMFAPreferences: () => Promise<FetchMFAPreferenceOutput>;
|
|
20
|
-
declare const clearMfaPreferences: () => Promise<void>;
|
|
21
|
-
declare const getUsername: () => Promise<string | undefined>;
|
|
22
|
-
declare const getUserAttributes: () => Promise<FetchUserAttributesOutput | undefined>;
|
|
23
|
-
declare const getMfaPreferences: () => Promise<FetchMFAPreferenceOutput | undefined>;
|
|
24
|
-
declare const isAuthenticated: () => Promise<boolean>;
|
|
25
|
-
declare const isInGroup: (group: string) => Promise<boolean>;
|
|
26
|
-
declare const getGroups: () => Promise<string[] | undefined>;
|
|
27
|
-
declare const getRoles: () => Promise<string[] | undefined>;
|
|
28
|
-
declare const getPreferredRole: () => Promise<string | undefined>;
|
|
29
|
-
declare const getScopes: () => Promise<string[] | undefined>;
|
|
30
|
-
declare const login: (signInHook: ApiConfiguration["signInHook"]) => Promise<string | undefined>;
|
|
31
|
-
declare const logout: (signOutHook: ApiConfiguration["signOutHook"]) => Promise<string | undefined>;
|
|
32
|
-
|
|
33
|
-
/**
|
|
34
|
-
* Ensures we only keep runtime keys that are part of AuthenticatorConfig.
|
|
35
|
-
*
|
|
36
|
-
* Defensive: upstream getConfig("gatey") or persisted site.settings may include
|
|
37
|
-
* additional keys, but the admin UI and core should only operate on AuthenticatorConfig.
|
|
38
|
-
*/
|
|
39
|
-
declare const sanitizeAuthenticatorConfig: (input: unknown) => AuthenticatorConfig;
|
|
40
|
-
declare const actions: {
|
|
41
|
-
setAmplifyConfig(amplifyConfig: ResourcesConfig): {
|
|
42
|
-
type: string;
|
|
43
|
-
amplifyConfig: ResourcesConfig;
|
|
44
|
-
};
|
|
45
|
-
setAccount(account: Account): {
|
|
46
|
-
type: string;
|
|
47
|
-
account: Account;
|
|
48
|
-
};
|
|
49
|
-
clearAccount(): {
|
|
50
|
-
type: string;
|
|
51
|
-
};
|
|
52
|
-
setSignedIn(signedIn: boolean): {
|
|
53
|
-
type: string;
|
|
54
|
-
signedIn: boolean;
|
|
55
|
-
};
|
|
56
|
-
setNextUrl(nextUrl: string | undefined | null): {
|
|
57
|
-
type: string;
|
|
58
|
-
nextUrl: string | null | undefined;
|
|
59
|
-
};
|
|
60
|
-
setLanguage(language: string | undefined | null): {
|
|
61
|
-
type: string;
|
|
62
|
-
language: string | null | undefined;
|
|
63
|
-
};
|
|
64
|
-
setDirection(direction: "ltr" | "rtl" | "auto" | undefined | null): {
|
|
65
|
-
type: string;
|
|
66
|
-
direction: "ltr" | "rtl" | "auto" | null | undefined;
|
|
67
|
-
};
|
|
68
|
-
reloadAuthSession(): {
|
|
69
|
-
type: string;
|
|
70
|
-
};
|
|
71
|
-
reloadUserAttributes(): {
|
|
72
|
-
type: string;
|
|
73
|
-
};
|
|
74
|
-
reloadMFAPreferences(): {
|
|
75
|
-
type: string;
|
|
76
|
-
};
|
|
77
|
-
};
|
|
78
|
-
interface FormField {
|
|
79
|
-
name: string;
|
|
80
|
-
type: string;
|
|
81
|
-
values?: Array<FormFieldOptionValue>;
|
|
82
|
-
}
|
|
83
|
-
interface ApiOptions {
|
|
84
|
-
headers?: Record<string, string>;
|
|
85
|
-
queryParams?: Record<string, string>;
|
|
86
|
-
body?: never;
|
|
87
|
-
withCredentials?: boolean;
|
|
88
|
-
}
|
|
89
|
-
interface API {
|
|
90
|
-
name: string;
|
|
91
|
-
endpoint: string;
|
|
92
|
-
region?: string;
|
|
93
|
-
authorization: "IAM" | "ID_TOKEN" | "ACCESS_TOKEN";
|
|
94
|
-
}
|
|
95
|
-
interface ApiConfiguration {
|
|
96
|
-
domains?: string;
|
|
97
|
-
apis: API[];
|
|
98
|
-
signInHook?: {
|
|
99
|
-
apiName: string;
|
|
100
|
-
path: string;
|
|
101
|
-
options?: ApiOptions;
|
|
102
|
-
};
|
|
103
|
-
signOutHook?: {
|
|
104
|
-
apiName: string;
|
|
105
|
-
path: string;
|
|
106
|
-
options?: ApiOptions;
|
|
107
|
-
};
|
|
108
|
-
}
|
|
109
|
-
interface AuthenticatorConfig {
|
|
110
|
-
customProviders: CustomProvider[];
|
|
111
|
-
formFields: FormField[];
|
|
112
|
-
apiConfigurations: {
|
|
113
|
-
default: ApiConfiguration;
|
|
114
|
-
secondary?: ApiConfiguration;
|
|
115
|
-
};
|
|
116
|
-
subscriptionType?: SubscriptionType;
|
|
117
|
-
}
|
|
118
|
-
interface CustomTranslations {
|
|
119
|
-
[key: string]: Record<string, string>;
|
|
120
|
-
}
|
|
121
|
-
interface State {
|
|
122
|
-
amplifyConfig: ResourcesConfig;
|
|
123
|
-
account: Account;
|
|
124
|
-
signedIn: boolean;
|
|
125
|
-
nextUrl: string | undefined | null;
|
|
126
|
-
config: AuthenticatorConfig | null;
|
|
127
|
-
language: string | undefined | null;
|
|
128
|
-
direction: "ltr" | "rtl" | "auto" | undefined | null;
|
|
129
|
-
customTranslations: CustomTranslations | null;
|
|
130
|
-
reloadAuthSession: number;
|
|
131
|
-
reloadUserAttributes: number;
|
|
132
|
-
reloadMFAPreferences: number;
|
|
133
|
-
}
|
|
134
|
-
type Store = StoreDescriptor;
|
|
135
|
-
type StoreSelectors = {
|
|
136
|
-
getAmplifyConfig(): ResourcesConfig;
|
|
137
|
-
getAccount(): Account;
|
|
138
|
-
getNextUrl(): string | null | undefined;
|
|
139
|
-
isSignedIn(): boolean;
|
|
140
|
-
getConfig(): AuthenticatorConfig | null;
|
|
141
|
-
getCustomTranslations(): CustomTranslations | null;
|
|
142
|
-
getLanguage(): string | undefined | null;
|
|
143
|
-
getDirection(): "ltr" | "rtl" | "auto" | undefined | null;
|
|
144
|
-
getState(): State;
|
|
145
|
-
};
|
|
146
|
-
type StoreActions = typeof actions;
|
|
147
|
-
declare const getStoreDispatch: (store: Store) => StoreActions;
|
|
148
|
-
declare const getStoreSelect: (store: Store) => StoreSelectors;
|
|
149
|
-
declare const observeStore: (observableStore: Store, selector: (state: State) => ResourcesConfig | Account | boolean | number | string | null | undefined, onChange: (nextValue: ResourcesConfig | Account | boolean | number | string | null | undefined, previousValue: ResourcesConfig | Account | boolean | number | string | null | undefined) => void) => () => void;
|
|
150
|
-
|
|
151
|
-
type GateyReadyEvent = "wpsuite:gatey:ready";
|
|
152
|
-
type GateyErrorEvent = "wpsuite:gatey:error";
|
|
153
|
-
type GateyPlugin = WpSuitePluginBase & Gatey;
|
|
154
|
-
declare function getGateyPlugin(): GateyPlugin;
|
|
155
|
-
declare function waitForGateyReady(timeoutMs?: number): Promise<void>;
|
|
156
|
-
declare function getStore(timeoutMs?: number): Promise<Store>;
|
|
157
|
-
|
|
158
|
-
declare const TEXT_DOMAIN = "gatey";
|
|
159
|
-
|
|
160
|
-
interface RoleMapping {
|
|
1
|
+
import { PasswordlessSettings, type LoginMechanism, type SignUpAttribute, type SocialProvider } from "@aws-amplify/ui";
|
|
2
|
+
import { type ResourcesConfig } from "aws-amplify";
|
|
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";
|
|
5
|
+
import { clearMfaPreferences, getAmplifyConfig, getGroups, getMfaPreferences, getPreferredRole, getRoles, getScopes, getUserAttributes, getUsername, isAuthenticated, isInGroup } from "./auth";
|
|
6
|
+
import { observeStore, type Store } from "./store";
|
|
7
|
+
export interface RoleMapping {
|
|
161
8
|
cognitoGroup?: string;
|
|
162
9
|
wordpressRole?: string;
|
|
163
10
|
}
|
|
164
|
-
interface Settings {
|
|
11
|
+
export interface Settings {
|
|
165
12
|
userPoolConfigurations: {
|
|
166
13
|
default: ResourcesConfig;
|
|
167
14
|
secondary?: ResourcesConfig;
|
|
@@ -185,7 +32,7 @@ interface Settings {
|
|
|
185
32
|
declare const signOut: () => void;
|
|
186
33
|
declare const setLanguage: (language?: string) => void;
|
|
187
34
|
declare const setDirection: (direction?: "ltr" | "rtl" | "auto") => void;
|
|
188
|
-
interface Cognito {
|
|
35
|
+
export interface Cognito {
|
|
189
36
|
readonly store: Promise<Store>;
|
|
190
37
|
readonly observeStore: typeof observeStore;
|
|
191
38
|
readonly setLanguage: typeof setLanguage;
|
|
@@ -212,18 +59,19 @@ interface Cognito {
|
|
|
212
59
|
toSignUp?: () => void;
|
|
213
60
|
toForgotPassword?: () => void;
|
|
214
61
|
}
|
|
215
|
-
interface Gatey {
|
|
62
|
+
export interface Gatey {
|
|
216
63
|
cognito: Cognito;
|
|
217
64
|
settings: Settings;
|
|
218
65
|
nonce: string;
|
|
219
66
|
restUrl: string;
|
|
220
67
|
}
|
|
221
|
-
|
|
68
|
+
export { getGateyPlugin, getStore, waitForGateyReady, type GateyErrorEvent, type GateyPlugin, type GateyReadyEvent, };
|
|
69
|
+
export { clearMfaPreferences, getGroups, getMfaPreferences, getPreferredRole, getRoles, getScopes, getUserAttributes, isAuthenticated, isInGroup, };
|
|
70
|
+
export { configureAmplify, getAmplifyConfig, loadAuthSession, loadMFAPreferences, loadUserAttributes, login, logout, type Account, } from "./auth";
|
|
71
|
+
export { getStoreDispatch, getStoreSelect, observeStore, sanitizeAuthenticatorConfig, type AuthenticatorConfig, type CustomTranslations, type FormField, type State, type Store, } from "./store";
|
|
222
72
|
/**
|
|
223
73
|
* @deprecated Use `getStore()` instead. Import with `import { getStore } from '@smart-cloud/gatey-core';`
|
|
224
74
|
*/
|
|
225
|
-
declare const store: () => Promise<Store>;
|
|
226
|
-
|
|
227
|
-
declare const initializeGatey: () => GateyPlugin;
|
|
228
|
-
|
|
229
|
-
export { type Account, type AuthenticatorConfig, type Cognito, type CustomTranslations, type FormField, type Gatey, type GateyErrorEvent, type GateyPlugin, type GateyReadyEvent, type RoleMapping, type Settings, type State, type Store, 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 };
|
|
75
|
+
export declare const store: () => Promise<Store>;
|
|
76
|
+
export { TEXT_DOMAIN } from "./constants";
|
|
77
|
+
export declare const initializeGatey: () => GateyPlugin;
|
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 E}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},b=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=b(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"?E.setLanguage(""):E.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};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,b as sanitizeAuthenticatorConfig,We as store,T as waitForGateyReady};
|
|
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 E}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},b=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=b(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"?E.setLanguage(""):E.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,b as sanitizeAuthenticatorConfig,We as store,T as waitForGateyReady};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { WpSuitePluginBase } from "@smart-cloud/wpsuite-core";
|
|
2
|
+
import { Gatey } from "./index";
|
|
3
|
+
export type GateyReadyEvent = "wpsuite:gatey:ready";
|
|
4
|
+
export type GateyErrorEvent = "wpsuite:gatey:error";
|
|
5
|
+
export type GateyPlugin = WpSuitePluginBase & Gatey;
|
|
6
|
+
export declare function getGateyPlugin(): GateyPlugin;
|
|
7
|
+
export declare function waitForGateyReady(timeoutMs?: number): Promise<void>;
|
|
8
|
+
export declare function getStore(timeoutMs?: number): Promise<import("./store").Store>;
|
package/dist/store.d.ts
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import { type FormFieldOptionValue } from "@aws-amplify/ui";
|
|
2
|
+
import { type CustomProvider } from "@aws-amplify/ui-react";
|
|
3
|
+
import { type ResourcesConfig } from "aws-amplify";
|
|
4
|
+
import { StoreDescriptor } from "@wordpress/data";
|
|
5
|
+
import { type SubscriptionType } from "@smart-cloud/wpsuite-core";
|
|
6
|
+
import { type Account } from "./auth";
|
|
7
|
+
export declare const getAccountFromStorage: (apiConfiguration?: ApiConfiguration) => Promise<Account>;
|
|
8
|
+
/**
|
|
9
|
+
* Ensures we only keep runtime keys that are part of AuthenticatorConfig.
|
|
10
|
+
*
|
|
11
|
+
* Defensive: upstream getConfig("gatey") or persisted site.settings may include
|
|
12
|
+
* additional keys, but the admin UI and core should only operate on AuthenticatorConfig.
|
|
13
|
+
*/
|
|
14
|
+
export declare const sanitizeAuthenticatorConfig: (input: unknown) => AuthenticatorConfig;
|
|
15
|
+
declare const actions: {
|
|
16
|
+
setAmplifyConfig(amplifyConfig: ResourcesConfig): {
|
|
17
|
+
type: string;
|
|
18
|
+
amplifyConfig: ResourcesConfig;
|
|
19
|
+
};
|
|
20
|
+
setAccount(account: Account): {
|
|
21
|
+
type: string;
|
|
22
|
+
account: Account;
|
|
23
|
+
};
|
|
24
|
+
clearAccount(): {
|
|
25
|
+
type: string;
|
|
26
|
+
};
|
|
27
|
+
setSignedIn(signedIn: boolean): {
|
|
28
|
+
type: string;
|
|
29
|
+
signedIn: boolean;
|
|
30
|
+
};
|
|
31
|
+
setNextUrl(nextUrl: string | undefined | null): {
|
|
32
|
+
type: string;
|
|
33
|
+
nextUrl: string | null | undefined;
|
|
34
|
+
};
|
|
35
|
+
setLanguage(language: string | undefined | null): {
|
|
36
|
+
type: string;
|
|
37
|
+
language: string | null | undefined;
|
|
38
|
+
};
|
|
39
|
+
setDirection(direction: "ltr" | "rtl" | "auto" | undefined | null): {
|
|
40
|
+
type: string;
|
|
41
|
+
direction: "ltr" | "rtl" | "auto" | null | undefined;
|
|
42
|
+
};
|
|
43
|
+
reloadAuthSession(): {
|
|
44
|
+
type: string;
|
|
45
|
+
};
|
|
46
|
+
reloadUserAttributes(): {
|
|
47
|
+
type: string;
|
|
48
|
+
};
|
|
49
|
+
reloadMFAPreferences(): {
|
|
50
|
+
type: string;
|
|
51
|
+
};
|
|
52
|
+
};
|
|
53
|
+
export interface FormField {
|
|
54
|
+
name: string;
|
|
55
|
+
type: string;
|
|
56
|
+
values?: Array<FormFieldOptionValue>;
|
|
57
|
+
}
|
|
58
|
+
export interface ApiOptions {
|
|
59
|
+
headers?: Record<string, string>;
|
|
60
|
+
queryParams?: Record<string, string>;
|
|
61
|
+
body?: never;
|
|
62
|
+
withCredentials?: boolean;
|
|
63
|
+
}
|
|
64
|
+
export interface API {
|
|
65
|
+
name: string;
|
|
66
|
+
endpoint: string;
|
|
67
|
+
region?: string;
|
|
68
|
+
authorization: "IAM" | "ID_TOKEN" | "ACCESS_TOKEN";
|
|
69
|
+
}
|
|
70
|
+
export interface ApiConfiguration {
|
|
71
|
+
domains?: string;
|
|
72
|
+
apis: API[];
|
|
73
|
+
signInHook?: {
|
|
74
|
+
apiName: string;
|
|
75
|
+
path: string;
|
|
76
|
+
options?: ApiOptions;
|
|
77
|
+
};
|
|
78
|
+
signOutHook?: {
|
|
79
|
+
apiName: string;
|
|
80
|
+
path: string;
|
|
81
|
+
options?: ApiOptions;
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
export interface AuthenticatorConfig {
|
|
85
|
+
customProviders: CustomProvider[];
|
|
86
|
+
formFields: FormField[];
|
|
87
|
+
apiConfigurations: {
|
|
88
|
+
default: ApiConfiguration;
|
|
89
|
+
secondary?: ApiConfiguration;
|
|
90
|
+
};
|
|
91
|
+
subscriptionType?: SubscriptionType;
|
|
92
|
+
}
|
|
93
|
+
export interface CustomTranslations {
|
|
94
|
+
[key: string]: Record<string, string>;
|
|
95
|
+
}
|
|
96
|
+
export interface State {
|
|
97
|
+
amplifyConfig: ResourcesConfig;
|
|
98
|
+
account: Account;
|
|
99
|
+
signedIn: boolean;
|
|
100
|
+
nextUrl: string | undefined | null;
|
|
101
|
+
config: AuthenticatorConfig | null;
|
|
102
|
+
language: string | undefined | null;
|
|
103
|
+
direction: "ltr" | "rtl" | "auto" | undefined | null;
|
|
104
|
+
customTranslations: CustomTranslations | null;
|
|
105
|
+
reloadAuthSession: number;
|
|
106
|
+
reloadUserAttributes: number;
|
|
107
|
+
reloadMFAPreferences: number;
|
|
108
|
+
}
|
|
109
|
+
export type Store = StoreDescriptor;
|
|
110
|
+
export type StoreSelectors = {
|
|
111
|
+
getAmplifyConfig(): ResourcesConfig;
|
|
112
|
+
getAccount(): Account;
|
|
113
|
+
getNextUrl(): string | null | undefined;
|
|
114
|
+
isSignedIn(): boolean;
|
|
115
|
+
getConfig(): AuthenticatorConfig | null;
|
|
116
|
+
getCustomTranslations(): CustomTranslations | null;
|
|
117
|
+
getLanguage(): string | undefined | null;
|
|
118
|
+
getDirection(): "ltr" | "rtl" | "auto" | undefined | null;
|
|
119
|
+
getState(): State;
|
|
120
|
+
};
|
|
121
|
+
export type StoreActions = typeof actions;
|
|
122
|
+
export declare const getStoreDispatch: (store: Store) => StoreActions;
|
|
123
|
+
export declare const getStoreSelect: (store: Store) => StoreSelectors;
|
|
124
|
+
export declare const createStore: () => Promise<Store>;
|
|
125
|
+
export declare const observeStore: (observableStore: Store, selector: (state: State) => ResourcesConfig | Account | boolean | number | string | null | undefined, onChange: (nextValue: ResourcesConfig | Account | boolean | number | string | null | undefined, previousValue: ResourcesConfig | Account | boolean | number | string | null | undefined) => void) => () => void;
|
|
126
|
+
export {};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@smart-cloud/gatey-core",
|
|
3
|
-
"version": "2.2.
|
|
3
|
+
"version": "2.2.8",
|
|
4
4
|
"description": "Login & SSO with Amazon Cognito",
|
|
5
5
|
"author": "Smart Cloud Solutions Inc.",
|
|
6
6
|
"license": "MIT",
|
|
@@ -19,35 +19,37 @@
|
|
|
19
19
|
"dist"
|
|
20
20
|
],
|
|
21
21
|
"scripts": {
|
|
22
|
-
"build": "
|
|
22
|
+
"build": "yarn build:js && yarn build:types",
|
|
23
|
+
"build:js": "tsup --minify",
|
|
24
|
+
"build:types": "tsc -p tsconfig.types.json",
|
|
23
25
|
"lint": "eslint 'src/**/*.ts' --report-unused-disable-directives --max-warnings 0",
|
|
24
26
|
"test": "echo \"Error: no test specified\" && exit 1",
|
|
25
|
-
"publish": "WPSUITE_PREMIUM=true
|
|
27
|
+
"publish": "WPSUITE_PREMIUM=true yarn build && npm publish --access=public"
|
|
26
28
|
},
|
|
27
29
|
"publishConfig": {
|
|
28
30
|
"registry": "https://registry.npmjs.org/",
|
|
29
31
|
"scope": "@smart-cloud/gatey-core"
|
|
30
32
|
},
|
|
31
33
|
"dependencies": {
|
|
32
|
-
"@smart-cloud/wpsuite-core": "^2.2.
|
|
34
|
+
"@smart-cloud/wpsuite-core": "^2.2.11"
|
|
33
35
|
},
|
|
34
36
|
"peerDependencies": {
|
|
35
37
|
"@aws-amplify/ui-react": "^6.15.0",
|
|
36
|
-
"@wordpress/data": "^10.
|
|
37
|
-
"aws-amplify": "^6.16.
|
|
38
|
+
"@wordpress/data": "^10.44.0",
|
|
39
|
+
"aws-amplify": "^6.16.4"
|
|
38
40
|
},
|
|
39
41
|
"devDependencies": {
|
|
40
42
|
"@aws-amplify/ui-react": "^6.15.0",
|
|
41
43
|
"@eslint/js": "^10.0.1",
|
|
42
|
-
"@types/node": "^25.
|
|
43
|
-
"@typescript-eslint/eslint-plugin": "^8.
|
|
44
|
-
"@typescript-eslint/parser": "^8.
|
|
45
|
-
"@wordpress/data": "^10.
|
|
46
|
-
"aws-amplify": "^6.16.
|
|
47
|
-
"eslint": "^10.
|
|
48
|
-
"globals": "^17.
|
|
44
|
+
"@types/node": "^25.6.0",
|
|
45
|
+
"@typescript-eslint/eslint-plugin": "^8.58.2",
|
|
46
|
+
"@typescript-eslint/parser": "^8.58.2",
|
|
47
|
+
"@wordpress/data": "^10.44.0",
|
|
48
|
+
"aws-amplify": "^6.16.4",
|
|
49
|
+
"eslint": "^10.2.1",
|
|
50
|
+
"globals": "^17.5.0",
|
|
49
51
|
"tsup": "^8.5.1",
|
|
50
|
-
"typescript": "^
|
|
51
|
-
"typescript-eslint": "^8.
|
|
52
|
+
"typescript": "^6.0.3",
|
|
53
|
+
"typescript-eslint": "^8.58.2"
|
|
52
54
|
}
|
|
53
55
|
}
|
package/dist/index.d.cts
DELETED
|
@@ -1,229 +0,0 @@
|
|
|
1
|
-
import { FormFieldOptionValue, LoginMechanism, SignUpAttribute, SocialProvider, PasswordlessSettings } from '@aws-amplify/ui';
|
|
2
|
-
import { ResourcesConfig } from 'aws-amplify';
|
|
3
|
-
import { get, post, put, del, head, patch } from 'aws-amplify/api';
|
|
4
|
-
import { CustomProvider } from '@aws-amplify/ui-react';
|
|
5
|
-
import { StoreDescriptor } from '@wordpress/data';
|
|
6
|
-
import { SubscriptionType, WpSuitePluginBase } from '@smart-cloud/wpsuite-core';
|
|
7
|
-
import { FetchUserAttributesOutput, FetchMFAPreferenceOutput, FetchAuthSessionOptions, AuthSession } from 'aws-amplify/auth';
|
|
8
|
-
|
|
9
|
-
interface Account {
|
|
10
|
-
username?: string;
|
|
11
|
-
loaded?: boolean;
|
|
12
|
-
userAttributes?: FetchUserAttributesOutput;
|
|
13
|
-
mfaPreferences?: FetchMFAPreferenceOutput;
|
|
14
|
-
}
|
|
15
|
-
declare const getAmplifyConfig: () => ResourcesConfig;
|
|
16
|
-
declare const configureAmplify: (resourcesConfig: ResourcesConfig, libraryOptions?: Record<string, unknown>) => void;
|
|
17
|
-
declare const loadAuthSession: (options?: FetchAuthSessionOptions) => Promise<AuthSession>;
|
|
18
|
-
declare const loadUserAttributes: () => Promise<FetchUserAttributesOutput>;
|
|
19
|
-
declare const loadMFAPreferences: () => Promise<FetchMFAPreferenceOutput>;
|
|
20
|
-
declare const clearMfaPreferences: () => Promise<void>;
|
|
21
|
-
declare const getUsername: () => Promise<string | undefined>;
|
|
22
|
-
declare const getUserAttributes: () => Promise<FetchUserAttributesOutput | undefined>;
|
|
23
|
-
declare const getMfaPreferences: () => Promise<FetchMFAPreferenceOutput | undefined>;
|
|
24
|
-
declare const isAuthenticated: () => Promise<boolean>;
|
|
25
|
-
declare const isInGroup: (group: string) => Promise<boolean>;
|
|
26
|
-
declare const getGroups: () => Promise<string[] | undefined>;
|
|
27
|
-
declare const getRoles: () => Promise<string[] | undefined>;
|
|
28
|
-
declare const getPreferredRole: () => Promise<string | undefined>;
|
|
29
|
-
declare const getScopes: () => Promise<string[] | undefined>;
|
|
30
|
-
declare const login: (signInHook: ApiConfiguration["signInHook"]) => Promise<string | undefined>;
|
|
31
|
-
declare const logout: (signOutHook: ApiConfiguration["signOutHook"]) => Promise<string | undefined>;
|
|
32
|
-
|
|
33
|
-
/**
|
|
34
|
-
* Ensures we only keep runtime keys that are part of AuthenticatorConfig.
|
|
35
|
-
*
|
|
36
|
-
* Defensive: upstream getConfig("gatey") or persisted site.settings may include
|
|
37
|
-
* additional keys, but the admin UI and core should only operate on AuthenticatorConfig.
|
|
38
|
-
*/
|
|
39
|
-
declare const sanitizeAuthenticatorConfig: (input: unknown) => AuthenticatorConfig;
|
|
40
|
-
declare const actions: {
|
|
41
|
-
setAmplifyConfig(amplifyConfig: ResourcesConfig): {
|
|
42
|
-
type: string;
|
|
43
|
-
amplifyConfig: ResourcesConfig;
|
|
44
|
-
};
|
|
45
|
-
setAccount(account: Account): {
|
|
46
|
-
type: string;
|
|
47
|
-
account: Account;
|
|
48
|
-
};
|
|
49
|
-
clearAccount(): {
|
|
50
|
-
type: string;
|
|
51
|
-
};
|
|
52
|
-
setSignedIn(signedIn: boolean): {
|
|
53
|
-
type: string;
|
|
54
|
-
signedIn: boolean;
|
|
55
|
-
};
|
|
56
|
-
setNextUrl(nextUrl: string | undefined | null): {
|
|
57
|
-
type: string;
|
|
58
|
-
nextUrl: string | null | undefined;
|
|
59
|
-
};
|
|
60
|
-
setLanguage(language: string | undefined | null): {
|
|
61
|
-
type: string;
|
|
62
|
-
language: string | null | undefined;
|
|
63
|
-
};
|
|
64
|
-
setDirection(direction: "ltr" | "rtl" | "auto" | undefined | null): {
|
|
65
|
-
type: string;
|
|
66
|
-
direction: "ltr" | "rtl" | "auto" | null | undefined;
|
|
67
|
-
};
|
|
68
|
-
reloadAuthSession(): {
|
|
69
|
-
type: string;
|
|
70
|
-
};
|
|
71
|
-
reloadUserAttributes(): {
|
|
72
|
-
type: string;
|
|
73
|
-
};
|
|
74
|
-
reloadMFAPreferences(): {
|
|
75
|
-
type: string;
|
|
76
|
-
};
|
|
77
|
-
};
|
|
78
|
-
interface FormField {
|
|
79
|
-
name: string;
|
|
80
|
-
type: string;
|
|
81
|
-
values?: Array<FormFieldOptionValue>;
|
|
82
|
-
}
|
|
83
|
-
interface ApiOptions {
|
|
84
|
-
headers?: Record<string, string>;
|
|
85
|
-
queryParams?: Record<string, string>;
|
|
86
|
-
body?: never;
|
|
87
|
-
withCredentials?: boolean;
|
|
88
|
-
}
|
|
89
|
-
interface API {
|
|
90
|
-
name: string;
|
|
91
|
-
endpoint: string;
|
|
92
|
-
region?: string;
|
|
93
|
-
authorization: "IAM" | "ID_TOKEN" | "ACCESS_TOKEN";
|
|
94
|
-
}
|
|
95
|
-
interface ApiConfiguration {
|
|
96
|
-
domains?: string;
|
|
97
|
-
apis: API[];
|
|
98
|
-
signInHook?: {
|
|
99
|
-
apiName: string;
|
|
100
|
-
path: string;
|
|
101
|
-
options?: ApiOptions;
|
|
102
|
-
};
|
|
103
|
-
signOutHook?: {
|
|
104
|
-
apiName: string;
|
|
105
|
-
path: string;
|
|
106
|
-
options?: ApiOptions;
|
|
107
|
-
};
|
|
108
|
-
}
|
|
109
|
-
interface AuthenticatorConfig {
|
|
110
|
-
customProviders: CustomProvider[];
|
|
111
|
-
formFields: FormField[];
|
|
112
|
-
apiConfigurations: {
|
|
113
|
-
default: ApiConfiguration;
|
|
114
|
-
secondary?: ApiConfiguration;
|
|
115
|
-
};
|
|
116
|
-
subscriptionType?: SubscriptionType;
|
|
117
|
-
}
|
|
118
|
-
interface CustomTranslations {
|
|
119
|
-
[key: string]: Record<string, string>;
|
|
120
|
-
}
|
|
121
|
-
interface State {
|
|
122
|
-
amplifyConfig: ResourcesConfig;
|
|
123
|
-
account: Account;
|
|
124
|
-
signedIn: boolean;
|
|
125
|
-
nextUrl: string | undefined | null;
|
|
126
|
-
config: AuthenticatorConfig | null;
|
|
127
|
-
language: string | undefined | null;
|
|
128
|
-
direction: "ltr" | "rtl" | "auto" | undefined | null;
|
|
129
|
-
customTranslations: CustomTranslations | null;
|
|
130
|
-
reloadAuthSession: number;
|
|
131
|
-
reloadUserAttributes: number;
|
|
132
|
-
reloadMFAPreferences: number;
|
|
133
|
-
}
|
|
134
|
-
type Store = StoreDescriptor;
|
|
135
|
-
type StoreSelectors = {
|
|
136
|
-
getAmplifyConfig(): ResourcesConfig;
|
|
137
|
-
getAccount(): Account;
|
|
138
|
-
getNextUrl(): string | null | undefined;
|
|
139
|
-
isSignedIn(): boolean;
|
|
140
|
-
getConfig(): AuthenticatorConfig | null;
|
|
141
|
-
getCustomTranslations(): CustomTranslations | null;
|
|
142
|
-
getLanguage(): string | undefined | null;
|
|
143
|
-
getDirection(): "ltr" | "rtl" | "auto" | undefined | null;
|
|
144
|
-
getState(): State;
|
|
145
|
-
};
|
|
146
|
-
type StoreActions = typeof actions;
|
|
147
|
-
declare const getStoreDispatch: (store: Store) => StoreActions;
|
|
148
|
-
declare const getStoreSelect: (store: Store) => StoreSelectors;
|
|
149
|
-
declare const observeStore: (observableStore: Store, selector: (state: State) => ResourcesConfig | Account | boolean | number | string | null | undefined, onChange: (nextValue: ResourcesConfig | Account | boolean | number | string | null | undefined, previousValue: ResourcesConfig | Account | boolean | number | string | null | undefined) => void) => () => void;
|
|
150
|
-
|
|
151
|
-
type GateyReadyEvent = "wpsuite:gatey:ready";
|
|
152
|
-
type GateyErrorEvent = "wpsuite:gatey:error";
|
|
153
|
-
type GateyPlugin = WpSuitePluginBase & Gatey;
|
|
154
|
-
declare function getGateyPlugin(): GateyPlugin;
|
|
155
|
-
declare function waitForGateyReady(timeoutMs?: number): Promise<void>;
|
|
156
|
-
declare function getStore(timeoutMs?: number): Promise<Store>;
|
|
157
|
-
|
|
158
|
-
declare const TEXT_DOMAIN = "gatey";
|
|
159
|
-
|
|
160
|
-
interface RoleMapping {
|
|
161
|
-
cognitoGroup?: string;
|
|
162
|
-
wordpressRole?: string;
|
|
163
|
-
}
|
|
164
|
-
interface Settings {
|
|
165
|
-
userPoolConfigurations: {
|
|
166
|
-
default: ResourcesConfig;
|
|
167
|
-
secondary?: ResourcesConfig;
|
|
168
|
-
};
|
|
169
|
-
secondaryUserPoolDomains?: string;
|
|
170
|
-
mappings: RoleMapping[];
|
|
171
|
-
loginMechanisms: LoginMechanism[];
|
|
172
|
-
signUpAttributes: SignUpAttribute[];
|
|
173
|
-
socialProviders?: SocialProvider[];
|
|
174
|
-
integrateWpLogin: boolean;
|
|
175
|
-
cookieExpiration?: number;
|
|
176
|
-
signInPage?: string;
|
|
177
|
-
redirectSignIn?: string;
|
|
178
|
-
redirectSignOut?: string;
|
|
179
|
-
customTranslationsUrl?: string;
|
|
180
|
-
enablePoweredBy?: boolean;
|
|
181
|
-
debugLoggingEnabled?: boolean;
|
|
182
|
-
hideSignUp?: boolean;
|
|
183
|
-
passwordlessSettings?: PasswordlessSettings;
|
|
184
|
-
}
|
|
185
|
-
declare const signOut: () => void;
|
|
186
|
-
declare const setLanguage: (language?: string) => void;
|
|
187
|
-
declare const setDirection: (direction?: "ltr" | "rtl" | "auto") => void;
|
|
188
|
-
interface Cognito {
|
|
189
|
-
readonly store: Promise<Store>;
|
|
190
|
-
readonly observeStore: typeof observeStore;
|
|
191
|
-
readonly setLanguage: typeof setLanguage;
|
|
192
|
-
readonly setDirection: typeof setDirection;
|
|
193
|
-
readonly getUsername: typeof getUsername;
|
|
194
|
-
readonly getUserAttributes: typeof getUserAttributes;
|
|
195
|
-
readonly getMfaPreferences: typeof getMfaPreferences;
|
|
196
|
-
readonly clearMfaPreferences: typeof clearMfaPreferences;
|
|
197
|
-
readonly isAuthenticated: typeof isAuthenticated;
|
|
198
|
-
readonly isInGroup: typeof isInGroup;
|
|
199
|
-
readonly getGroups: typeof getGroups;
|
|
200
|
-
readonly getRoles: typeof getRoles;
|
|
201
|
-
readonly getScopes: typeof getScopes;
|
|
202
|
-
readonly getPreferredRole: typeof getPreferredRole;
|
|
203
|
-
readonly signOut: typeof signOut;
|
|
204
|
-
readonly getAmplifyConfig: typeof getAmplifyConfig;
|
|
205
|
-
readonly get: typeof get;
|
|
206
|
-
readonly post: typeof post;
|
|
207
|
-
readonly put: typeof put;
|
|
208
|
-
readonly del: typeof del;
|
|
209
|
-
readonly head: typeof head;
|
|
210
|
-
readonly patch: typeof patch;
|
|
211
|
-
toSignIn?: () => void;
|
|
212
|
-
toSignUp?: () => void;
|
|
213
|
-
toForgotPassword?: () => void;
|
|
214
|
-
}
|
|
215
|
-
interface Gatey {
|
|
216
|
-
cognito: Cognito;
|
|
217
|
-
settings: Settings;
|
|
218
|
-
nonce: string;
|
|
219
|
-
restUrl: string;
|
|
220
|
-
}
|
|
221
|
-
|
|
222
|
-
/**
|
|
223
|
-
* @deprecated Use `getStore()` instead. Import with `import { getStore } from '@smart-cloud/gatey-core';`
|
|
224
|
-
*/
|
|
225
|
-
declare const store: () => Promise<Store>;
|
|
226
|
-
|
|
227
|
-
declare const initializeGatey: () => GateyPlugin;
|
|
228
|
-
|
|
229
|
-
export { type Account, type AuthenticatorConfig, type Cognito, type CustomTranslations, type FormField, type Gatey, type GateyErrorEvent, type GateyPlugin, type GateyReadyEvent, type RoleMapping, type Settings, type State, type Store, 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 };
|