@descope/web-component 4.0.1 → 4.0.2
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/cjs/descope-wc/BaseDescopeWc.js +1 -1
- package/dist/cjs/mixins/passwordManagerMixin.js +1 -1
- package/dist/cjs/mixins/passwordManagerMixin.js.map +1 -1
- package/dist/esm/descope-wc/BaseDescopeWc.js +1 -1
- package/dist/esm/mixins/passwordManagerMixin.js +1 -1
- package/dist/esm/mixins/passwordManagerMixin.js.map +1 -1
- package/dist/index.js +2 -2
- package/package.json +2 -2
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var t=require("tslib"),e=require("@descope/sdk-helpers"),i=require("@descope/sdk-mixins/static-resources-mixin"),r=require("@descope/sdk-mixins/theme-mixin"),s=require("@descope/sdk-mixins/inject-style-mixin"),o=require("@descope/web-js-sdk"),n=require("../constants/index.js"),a=require("../helpers/helpers.js"),l=require("../helpers/state.js");require("@descope/escape-markdown"),require("../helpers/webauthn.js");var u,d,c,h,g,f,p,v,_,m,b,w,C,k,x,F,P,y,A,E,I,j,G=require("../helpers/storage.js"),S=require("../helpers/flowInputs.js"),M=require("../mixins/formMountMixin.js"),O=require("../mixins/componentConditionsMixin.js"),U=require("../mixins/duplicateFlowWarningMixin.js"),L=require("../mixins/passwordManagerMixin.js"),q=require("../constants/content.js"),R=require("../constants/general.js");function N(t){return Object.freeze({__proto__:null,default:t})}const W=e.compose(r.themeMixin,i.staticResourcesMixin,M.formMountMixin,O.componentConditionsMixin,U.duplicateFlowWarningMixin,L.passwordManagerMixin,s.injectStyleMixin)(HTMLElement);class D extends W{static get observedAttributes(){return["project-id","flow-id","base-url","tenant","locale","debug","storage-prefix","preview","redirect-url","auto-focus","store-last-authenticated-user","refresh-cookie-name","keep-last-authenticated-user-after-logout","validate-on-blur","style-id"]}constructor(e){super(),u.add(this),c.set(this,!1),h.set(this,void 0),this.flowStatus="initial",this.loggerWrapper={error:(e,i="")=>{this.logger.error(e,i,new Error),t.__classPrivateFieldGet(this,u,"m",j).call(this,e,i)},warn:(t,e="")=>{this.logger.warn(t,e)},info:(t,e="",i={})=>{this.logger.info(t,e,i)},debug:(t,e="")=>{this.logger.debug(t,e)}},g.set(this,new l),f.set(this,new l),p.set(this,{}),this.getComponentsContext=()=>t.__classPrivateFieldGet(this,p,"f"),this.nextRequestStatus=new l({isLoading:!1}),v.set(this,void 0),_.set(this,{popstate:t.__classPrivateFieldGet(this,u,"m",k).bind(this),componentsContext:t.__classPrivateFieldGet(this,u,"m",A).bind(this)}),m.set(this,void 0),this.getConfig=()=>t.__awaiter(this,void 0,void 0,(function*(){return(yield this.config)||{isMissingConfig:!0}})),t.__classPrivateFieldSet(this,m,e,"f"),t.__classPrivateFieldGet(this,u,"m",w).call(this)}get flowId(){return this.getAttribute("flow-id")}get client(){try{return JSON.parse(this.getAttribute("client"))||{}}catch(t){return{}}}get redirectUrl(){return this.getAttribute("redirect-url")||void 0}get debug(){return"true"===this.getAttribute("debug")}get locale(){return this.getAttribute("locale")||void 0}get autoFocus(){var t;const e=null!==(t=this.getAttribute("auto-focus"))&&void 0!==t?t:"true";return"skipFirstScreen"===e?e:"true"===e}get validateOnBlur(){return"true"===this.getAttribute("validate-on-blur")}get storeLastAuthenticatedUser(){var t;return"true"===(null!==(t=this.getAttribute("store-last-authenticated-user"))&&void 0!==t?t:"true")}get refreshCookieName(){return this.getAttribute("refresh-cookie-name")||""}get keepLastAuthenticatedUserAfterLogout(){return"true"===this.getAttribute("keep-last-authenticated-user-after-logout")}get storagePrefix(){return this.getAttribute("storage-prefix")||""}get preview(){return!!this.getAttribute("preview")}get formConfig(){return S.transformFlowInputFormData(this.form)}get form(){return this.getAttribute("form")}get formConfigValues(){return S.extractNestedAttribute(this.formConfig,"value")}get outboundAppId(){return this.getAttribute("outbound-app-id")}get outboundAppScopes(){try{const t=JSON.parse(this.getAttribute("outbound-app-scopes"));return t||null}catch(t){return null}}get popupOrigin(){return this.getAttribute("popup-origin")}get customStorage(){return t.__classPrivateFieldGet(this,h,"f")}set customStorage(e){if(e&&"function"!=typeof e.getItem)throw new Error("Custom storage must have a getItem method");if(e&&"function"!=typeof e.setItem)throw new Error("Custom storage must have a setItem method");if(e&&"function"!=typeof e.removeItem)throw new Error("Custom storage must have a removeItem method");t.__classPrivateFieldSet(this,h,e,"f"),G.setCustomStorage(e)}get isRestartOnError(){return"true"===this.getAttribute("restart-on-error")}getExecutionContext(){return t.__awaiter(this,void 0,void 0,(function*(){const t=yield this.getConfig();return"executionContext"in t?t.executionContext:void 0}))}getProjectConfig(){return t.__awaiter(this,void 0,void 0,(function*(){const t=yield this.getConfig();return"projectConfig"in t?t.projectConfig:void 0}))}getFlowConfig(){return t.__awaiter(this,void 0,void 0,(function*(){var t,e;const i=yield this.getProjectConfig(),r=(null===(t=null==i?void 0:i.flows)||void 0===t?void 0:t[this.flowId])||{};return null!==(e=r.version)&&void 0!==e||(r.version=0),r}))}getTargetLocales(){return t.__awaiter(this,void 0,void 0,(function*(){const t=yield this.getFlowConfig();return((null==t?void 0:t.targetLocales)||[]).map((t=>t.toLowerCase()))}))}handleKeyPress(){this.logger.debug("Enable key press handler"),this.rootElement.onkeydown=t=>{var e,i,r;const s=!!(null===(e=this.shadowRoot.activeElement)||void 0===e?void 0:e.getAttribute("href")),o=n.ELEMENTS_TO_IGNORE_ENTER_KEY_ON.includes(null!==(r=null===(i=this.shadowRoot.activeElement)||void 0===i?void 0:i.localName)&&void 0!==r?r:"");if("Enter"!==t.key||s||o)return;t.preventDefault();const a=this.rootElement.querySelectorAll("descope-button");if(1===a.length&&"false"!==a[0].getAttribute("auto-submit"))return void a[0].click();const l=Array.from(a).filter((t=>"true"===t.getAttribute("auto-submit")));if(1===l.length)return void l[0].click();const u=Array.from(a).filter((t=>"button"===t.getAttribute("data-type")));if(1===u.length)"false"!==u[0].getAttribute("auto-submit")&&u[0].click();else if(0===u.length){const t=Array.from(a).filter((t=>"sso"===t.getAttribute("data-type")));1===t.length&&"false"!==t[0].getAttribute("auto-submit")&&t[0].click()}}}disableKeyPressHandler(){this.logger.debug("Disable key press handler"),this.rootElement.onkeydown=null}getComponentsVersion(){return t.__awaiter(this,void 0,void 0,(function*(){var t;const e=yield this.getConfig(),i="projectConfig"in e?null===(t=e.projectConfig)||void 0===t?void 0:t.componentsVersion:{};return i||(this.logger.error("Did not get components version, using latest version"),"latest")}))}init(){const e=Object.create(null,{init:{get:()=>super.init}});return t.__awaiter(this,void 0,void 0,(function*(){var i;if(this.flowStatus="loading",["ready","error","success"].forEach((t=>this.addEventListener(t,(()=>{this.flowStatus=t})))),yield null===(i=e.init)||void 0===i?void 0:i.call(this),t.__classPrivateFieldGet(this,f,"f").subscribe(t.__classPrivateFieldGet(this,u,"m",I).bind(this)),t.__classPrivateFieldGet(this,f,"f").update({isDebug:this.debug}),t.__classPrivateFieldGet(this,u,"m",C).call(this),yield t.__classPrivateFieldGet(this,u,"m",P).call(this))return void this.loggerWrapper.error("This SDK version does not support your flows version","Make sure to upgrade your flows to the latest version or use an older SDK version");const r=yield this.getConfig();if("isMissingConfig"in r&&r.isMissingConfig)return void this.loggerWrapper.error("Cannot get config file","Make sure that your projectId & flowId are correct");const{executionId:s,stepId:o,token:n,code:l,isPopup:d,exchangeError:h,redirectAuthCallbackUrl:p,redirectAuthBackupCallbackUri:v,redirectAuthCodeChallenge:m,redirectAuthInitiator:b,ssoQueryParams:w}=a.handleUrlParams(this.flowId,this.loggerWrapper);window.addEventListener("popstate",t.__classPrivateFieldGet(this,_,"f").popstate),window.addEventListener("components-context",t.__classPrivateFieldGet(this,_,"f").componentsContext),t.__classPrivateFieldGet(this,g,"f").subscribe(t.__classPrivateFieldGet(this,u,"m",F).bind(this)),t.__classPrivateFieldGet(this,g,"f").update(Object.assign({projectId:this.projectId,flowId:this.flowId,baseUrl:this.baseUrl,tenant:this.tenantId,redirectUrl:this.redirectUrl,locale:this.locale,stepId:o,executionId:s,token:n,code:l,isPopup:d,exchangeError:h,redirectAuthCallbackUrl:p,redirectAuthBackupCallbackUri:v,redirectAuthCodeChallenge:m,redirectAuthInitiator:b},w)),t.__classPrivateFieldSet(this,c,!0,"f")}))}disconnectedCallback(){var e;t.__classPrivateFieldGet(this,g,"f").unsubscribeAll(),t.__classPrivateFieldGet(this,f,"f").unsubscribeAll(),t.__classPrivateFieldGet(this,u,"m",E).call(this),window.removeEventListener("popstate",t.__classPrivateFieldGet(this,_,"f").popstate),window.removeEventListener("components-context",t.__classPrivateFieldGet(this,_,"f").componentsContext),null===(e=super.disconnectedCallback)||void 0===e||e.call(this)}attributeChangedCallback(e,i,r){var s;if(null===(s=super.attributeChangedCallback)||void 0===s||s.call(this,e,i,r),this.shadowRoot.isConnected&&t.__classPrivateFieldGet(this,c,"f")&&i!==r&&d.observedAttributes.includes(e)){t.__classPrivateFieldGet(this,u,"m",C).call(this);const s=null===i;t.__classPrivateFieldGet(this,g,"f").update((({stepId:t,executionId:i})=>{let o=t,n=i;return s||(n=null,o=null,a.clearRunIdsFromUrl()),{[a.camelCase(e)]:r,stepId:o,executionId:n}})),t.__classPrivateFieldGet(this,f,"f").update({isDebug:this.debug})}}}d=D,c=new WeakMap,h=new WeakMap,g=new WeakMap,f=new WeakMap,p=new WeakMap,v=new WeakMap,_=new WeakMap,m=new WeakMap,u=new WeakSet,b=function(){this.injectStyle("\n :host {\n\t\t\twidth: 100%;\n display: block;\n\t\t}\n\n\t\t#root {\n\t\t\theight: 100%;\n display: flex;\n flex-direction: column;\n\t\t}\n\n #content-root {\n all: initial;\n transition: opacity 200ms ease-in-out;\n }\n\n\t\t#root[data-theme] {\n\t\t\tbackground-color: transparent;\n\t\t}\n\n\t\t.fade-out {\n\t\t\topacity: 0.1!important;\n\t\t}\n\n .hidden {\n display: none;\n }\n ")},w=function(){t.__classPrivateFieldGet(this,u,"m",b).call(this),this.slotElement=document.createElement("slot"),this.slotElement.classList.add("hidden"),this.rootElement.appendChild(this.slotElement)},C=function(){const t=["base-url","tenant","locale","debug","redirect-url","auto-focus","store-last-authenticated-user","refresh-cookie-name","keep-last-authenticated-user-after-logout","preview","storage-prefix","form","client","validate-on-blur","style-id","outbound-app-id","outbound-app-scopes","theme-override"];d.observedAttributes.forEach((e=>{if(!t.includes(e)&&!this[a.camelCase(e)])throw Error(`${e} cannot be empty`)}))},k=function(){const{stepId:e,executionId:i}=a.getRunIdsFromUrl(this.flowId);t.__classPrivateFieldGet(this,g,"f").update({stepId:e,executionId:i})},x=function(e,i){o.createSdk&&"function"==typeof o.createSdk||this.logger.error("SDK was not loaded properly",o.createSdk,JSON.stringify(o.createSdk));const r=Object.assign(Object.assign({persistTokens:!0,preview:this.preview,storagePrefix:this.storagePrefix,storeLastAuthenticatedUser:this.storeLastAuthenticatedUser,keepLastAuthenticatedUserAfterLogout:this.keepLastAuthenticatedUserAfterLogout,refreshCookieName:this.refreshCookieName},d.sdkConfigOverrides),{projectId:e,baseUrl:i});t.__classPrivateFieldGet(this,h,"f")&&(r.customStorage=t.__classPrivateFieldGet(this,h,"f")),this.sdk=o.createSdk(r),["start","next"].forEach((e=>{const i=this.sdk.flow[e],r=a.withRetry(i,1e3,3);this.sdk.flow[e]=(...i)=>t.__awaiter(this,void 0,void 0,(function*(){try{return yield r(...i)}catch(t){return this.logger.error(`Error in sdk flow ${e} function`,t),{error:{errorCode:R.FETCH_EXCEPTION_ERROR_CODE,errorDescription:t.toString()}}}}))}))},F=function(e,i,r){return t.__awaiter(this,void 0,void 0,(function*(){const{projectId:i,baseUrl:s}=e;if(r("projectId")||r("baseUrl")){if(!i)return;t.__classPrivateFieldGet(this,u,"m",x).call(this,i,s)}t.__classPrivateFieldGet(this,m,"f").call(this,e)}))},P=function(){return t.__awaiter(this,void 0,void 0,(function*(){const e=yield this.getConfig();return"isMissingConfig"in e&&e.isMissingConfig&&(yield t.__classPrivateFieldGet(this,u,"m",y).call(this))}))},y=function(){return t.__awaiter(this,void 0,void 0,(function*(){const t=a.getContentUrl({projectId:this.projectId,filename:q.CONFIG_FILENAME,assetsFolder:q.PREV_VER_ASSETS_FOLDER,baseUrl:this.baseStaticUrl});try{return yield a.fetchContent(t,"json"),!0}catch(t){return!1}}))},A=function(e){t.__classPrivateFieldSet(this,p,Object.assign(Object.assign({},t.__classPrivateFieldGet(this,p,"f")),e.detail),"f")},E=function(){var e;null===(e=t.__classPrivateFieldGet(this,v,"f"))||void 0===e||e.remove(),t.__classPrivateFieldSet(this,v,null,"f")},I=function(e){return t.__awaiter(this,arguments,void 0,(function*({isDebug:e}){e?(t.__classPrivateFieldSet(this,v,document.createElement("descope-debugger"),"f"),Object.assign(t.__classPrivateFieldGet(this,v,"f").style,{position:"fixed",top:"0",right:"0",height:"100vh",width:"100vw",pointerEvents:"none",zIndex:99999}),yield Promise.resolve().then((function(){return N(require("../debugger-wc.js"))})),document.body.appendChild(t.__classPrivateFieldGet(this,v,"f"))):t.__classPrivateFieldGet(this,u,"m",E).call(this)}))},j=function(e,i){var r;e&&this.debug&&(null===(r=t.__classPrivateFieldGet(this,v,"f"))||void 0===r||r.updateData({title:e,description:i}))},D.sdkConfigOverrides={baseHeaders:{"x-descope-sdk-name":"web-component","x-descope-sdk-version":"4.0.1"}},module.exports=D;
|
|
1
|
+
"use strict";var t=require("tslib"),e=require("@descope/sdk-helpers"),i=require("@descope/sdk-mixins/static-resources-mixin"),r=require("@descope/sdk-mixins/theme-mixin"),s=require("@descope/sdk-mixins/inject-style-mixin"),o=require("@descope/web-js-sdk"),n=require("../constants/index.js"),a=require("../helpers/helpers.js"),l=require("../helpers/state.js");require("@descope/escape-markdown"),require("../helpers/webauthn.js");var u,d,c,h,g,f,p,v,_,m,b,w,C,k,x,F,P,y,A,E,I,j,G=require("../helpers/storage.js"),S=require("../helpers/flowInputs.js"),M=require("../mixins/formMountMixin.js"),O=require("../mixins/componentConditionsMixin.js"),U=require("../mixins/duplicateFlowWarningMixin.js"),L=require("../mixins/passwordManagerMixin.js"),q=require("../constants/content.js"),R=require("../constants/general.js");function N(t){return Object.freeze({__proto__:null,default:t})}const W=e.compose(r.themeMixin,i.staticResourcesMixin,M.formMountMixin,O.componentConditionsMixin,U.duplicateFlowWarningMixin,L.passwordManagerMixin,s.injectStyleMixin)(HTMLElement);class D extends W{static get observedAttributes(){return["project-id","flow-id","base-url","tenant","locale","debug","storage-prefix","preview","redirect-url","auto-focus","store-last-authenticated-user","refresh-cookie-name","keep-last-authenticated-user-after-logout","validate-on-blur","style-id"]}constructor(e){super(),u.add(this),c.set(this,!1),h.set(this,void 0),this.flowStatus="initial",this.loggerWrapper={error:(e,i="")=>{this.logger.error(e,i,new Error),t.__classPrivateFieldGet(this,u,"m",j).call(this,e,i)},warn:(t,e="")=>{this.logger.warn(t,e)},info:(t,e="",i={})=>{this.logger.info(t,e,i)},debug:(t,e="")=>{this.logger.debug(t,e)}},g.set(this,new l),f.set(this,new l),p.set(this,{}),this.getComponentsContext=()=>t.__classPrivateFieldGet(this,p,"f"),this.nextRequestStatus=new l({isLoading:!1}),v.set(this,void 0),_.set(this,{popstate:t.__classPrivateFieldGet(this,u,"m",k).bind(this),componentsContext:t.__classPrivateFieldGet(this,u,"m",A).bind(this)}),m.set(this,void 0),this.getConfig=()=>t.__awaiter(this,void 0,void 0,(function*(){return(yield this.config)||{isMissingConfig:!0}})),t.__classPrivateFieldSet(this,m,e,"f"),t.__classPrivateFieldGet(this,u,"m",w).call(this)}get flowId(){return this.getAttribute("flow-id")}get client(){try{return JSON.parse(this.getAttribute("client"))||{}}catch(t){return{}}}get redirectUrl(){return this.getAttribute("redirect-url")||void 0}get debug(){return"true"===this.getAttribute("debug")}get locale(){return this.getAttribute("locale")||void 0}get autoFocus(){var t;const e=null!==(t=this.getAttribute("auto-focus"))&&void 0!==t?t:"true";return"skipFirstScreen"===e?e:"true"===e}get validateOnBlur(){return"true"===this.getAttribute("validate-on-blur")}get storeLastAuthenticatedUser(){var t;return"true"===(null!==(t=this.getAttribute("store-last-authenticated-user"))&&void 0!==t?t:"true")}get refreshCookieName(){return this.getAttribute("refresh-cookie-name")||""}get keepLastAuthenticatedUserAfterLogout(){return"true"===this.getAttribute("keep-last-authenticated-user-after-logout")}get storagePrefix(){return this.getAttribute("storage-prefix")||""}get preview(){return!!this.getAttribute("preview")}get formConfig(){return S.transformFlowInputFormData(this.form)}get form(){return this.getAttribute("form")}get formConfigValues(){return S.extractNestedAttribute(this.formConfig,"value")}get outboundAppId(){return this.getAttribute("outbound-app-id")}get outboundAppScopes(){try{const t=JSON.parse(this.getAttribute("outbound-app-scopes"));return t||null}catch(t){return null}}get popupOrigin(){return this.getAttribute("popup-origin")}get customStorage(){return t.__classPrivateFieldGet(this,h,"f")}set customStorage(e){if(e&&"function"!=typeof e.getItem)throw new Error("Custom storage must have a getItem method");if(e&&"function"!=typeof e.setItem)throw new Error("Custom storage must have a setItem method");if(e&&"function"!=typeof e.removeItem)throw new Error("Custom storage must have a removeItem method");t.__classPrivateFieldSet(this,h,e,"f"),G.setCustomStorage(e)}get isRestartOnError(){return"true"===this.getAttribute("restart-on-error")}getExecutionContext(){return t.__awaiter(this,void 0,void 0,(function*(){const t=yield this.getConfig();return"executionContext"in t?t.executionContext:void 0}))}getProjectConfig(){return t.__awaiter(this,void 0,void 0,(function*(){const t=yield this.getConfig();return"projectConfig"in t?t.projectConfig:void 0}))}getFlowConfig(){return t.__awaiter(this,void 0,void 0,(function*(){var t,e;const i=yield this.getProjectConfig(),r=(null===(t=null==i?void 0:i.flows)||void 0===t?void 0:t[this.flowId])||{};return null!==(e=r.version)&&void 0!==e||(r.version=0),r}))}getTargetLocales(){return t.__awaiter(this,void 0,void 0,(function*(){const t=yield this.getFlowConfig();return((null==t?void 0:t.targetLocales)||[]).map((t=>t.toLowerCase()))}))}handleKeyPress(){this.logger.debug("Enable key press handler"),this.rootElement.onkeydown=t=>{var e,i,r;const s=!!(null===(e=this.shadowRoot.activeElement)||void 0===e?void 0:e.getAttribute("href")),o=n.ELEMENTS_TO_IGNORE_ENTER_KEY_ON.includes(null!==(r=null===(i=this.shadowRoot.activeElement)||void 0===i?void 0:i.localName)&&void 0!==r?r:"");if("Enter"!==t.key||s||o)return;t.preventDefault();const a=this.rootElement.querySelectorAll("descope-button");if(1===a.length&&"false"!==a[0].getAttribute("auto-submit"))return void a[0].click();const l=Array.from(a).filter((t=>"true"===t.getAttribute("auto-submit")));if(1===l.length)return void l[0].click();const u=Array.from(a).filter((t=>"button"===t.getAttribute("data-type")));if(1===u.length)"false"!==u[0].getAttribute("auto-submit")&&u[0].click();else if(0===u.length){const t=Array.from(a).filter((t=>"sso"===t.getAttribute("data-type")));1===t.length&&"false"!==t[0].getAttribute("auto-submit")&&t[0].click()}}}disableKeyPressHandler(){this.logger.debug("Disable key press handler"),this.rootElement.onkeydown=null}getComponentsVersion(){return t.__awaiter(this,void 0,void 0,(function*(){var t;const e=yield this.getConfig(),i="projectConfig"in e?null===(t=e.projectConfig)||void 0===t?void 0:t.componentsVersion:{};return i||(this.logger.error("Did not get components version, using latest version"),"latest")}))}init(){const e=Object.create(null,{init:{get:()=>super.init}});return t.__awaiter(this,void 0,void 0,(function*(){var i;if(this.flowStatus="loading",["ready","error","success"].forEach((t=>this.addEventListener(t,(()=>{this.flowStatus=t})))),yield null===(i=e.init)||void 0===i?void 0:i.call(this),t.__classPrivateFieldGet(this,f,"f").subscribe(t.__classPrivateFieldGet(this,u,"m",I).bind(this)),t.__classPrivateFieldGet(this,f,"f").update({isDebug:this.debug}),t.__classPrivateFieldGet(this,u,"m",C).call(this),yield t.__classPrivateFieldGet(this,u,"m",P).call(this))return void this.loggerWrapper.error("This SDK version does not support your flows version","Make sure to upgrade your flows to the latest version or use an older SDK version");const r=yield this.getConfig();if("isMissingConfig"in r&&r.isMissingConfig)return void this.loggerWrapper.error("Cannot get config file","Make sure that your projectId & flowId are correct");const{executionId:s,stepId:o,token:n,code:l,isPopup:d,exchangeError:h,redirectAuthCallbackUrl:p,redirectAuthBackupCallbackUri:v,redirectAuthCodeChallenge:m,redirectAuthInitiator:b,ssoQueryParams:w}=a.handleUrlParams(this.flowId,this.loggerWrapper);window.addEventListener("popstate",t.__classPrivateFieldGet(this,_,"f").popstate),window.addEventListener("components-context",t.__classPrivateFieldGet(this,_,"f").componentsContext),t.__classPrivateFieldGet(this,g,"f").subscribe(t.__classPrivateFieldGet(this,u,"m",F).bind(this)),t.__classPrivateFieldGet(this,g,"f").update(Object.assign({projectId:this.projectId,flowId:this.flowId,baseUrl:this.baseUrl,tenant:this.tenantId,redirectUrl:this.redirectUrl,locale:this.locale,stepId:o,executionId:s,token:n,code:l,isPopup:d,exchangeError:h,redirectAuthCallbackUrl:p,redirectAuthBackupCallbackUri:v,redirectAuthCodeChallenge:m,redirectAuthInitiator:b},w)),t.__classPrivateFieldSet(this,c,!0,"f")}))}disconnectedCallback(){var e;t.__classPrivateFieldGet(this,g,"f").unsubscribeAll(),t.__classPrivateFieldGet(this,f,"f").unsubscribeAll(),t.__classPrivateFieldGet(this,u,"m",E).call(this),window.removeEventListener("popstate",t.__classPrivateFieldGet(this,_,"f").popstate),window.removeEventListener("components-context",t.__classPrivateFieldGet(this,_,"f").componentsContext),null===(e=super.disconnectedCallback)||void 0===e||e.call(this)}attributeChangedCallback(e,i,r){var s;if(null===(s=super.attributeChangedCallback)||void 0===s||s.call(this,e,i,r),this.shadowRoot.isConnected&&t.__classPrivateFieldGet(this,c,"f")&&i!==r&&d.observedAttributes.includes(e)){t.__classPrivateFieldGet(this,u,"m",C).call(this);const s=null===i;t.__classPrivateFieldGet(this,g,"f").update((({stepId:t,executionId:i})=>{let o=t,n=i;return s||(n=null,o=null,a.clearRunIdsFromUrl()),{[a.camelCase(e)]:r,stepId:o,executionId:n}})),t.__classPrivateFieldGet(this,f,"f").update({isDebug:this.debug})}}}d=D,c=new WeakMap,h=new WeakMap,g=new WeakMap,f=new WeakMap,p=new WeakMap,v=new WeakMap,_=new WeakMap,m=new WeakMap,u=new WeakSet,b=function(){this.injectStyle("\n :host {\n\t\t\twidth: 100%;\n display: block;\n\t\t}\n\n\t\t#root {\n\t\t\theight: 100%;\n display: flex;\n flex-direction: column;\n\t\t}\n\n #content-root {\n all: initial;\n transition: opacity 200ms ease-in-out;\n }\n\n\t\t#root[data-theme] {\n\t\t\tbackground-color: transparent;\n\t\t}\n\n\t\t.fade-out {\n\t\t\topacity: 0.1!important;\n\t\t}\n\n .hidden {\n display: none;\n }\n ")},w=function(){t.__classPrivateFieldGet(this,u,"m",b).call(this),this.slotElement=document.createElement("slot"),this.slotElement.classList.add("hidden"),this.rootElement.appendChild(this.slotElement)},C=function(){const t=["base-url","tenant","locale","debug","redirect-url","auto-focus","store-last-authenticated-user","refresh-cookie-name","keep-last-authenticated-user-after-logout","preview","storage-prefix","form","client","validate-on-blur","style-id","outbound-app-id","outbound-app-scopes","theme-override"];d.observedAttributes.forEach((e=>{if(!t.includes(e)&&!this[a.camelCase(e)])throw Error(`${e} cannot be empty`)}))},k=function(){const{stepId:e,executionId:i}=a.getRunIdsFromUrl(this.flowId);t.__classPrivateFieldGet(this,g,"f").update({stepId:e,executionId:i})},x=function(e,i){o.createSdk&&"function"==typeof o.createSdk||this.logger.error("SDK was not loaded properly",o.createSdk,JSON.stringify(o.createSdk));const r=Object.assign(Object.assign({persistTokens:!0,preview:this.preview,storagePrefix:this.storagePrefix,storeLastAuthenticatedUser:this.storeLastAuthenticatedUser,keepLastAuthenticatedUserAfterLogout:this.keepLastAuthenticatedUserAfterLogout,refreshCookieName:this.refreshCookieName},d.sdkConfigOverrides),{projectId:e,baseUrl:i});t.__classPrivateFieldGet(this,h,"f")&&(r.customStorage=t.__classPrivateFieldGet(this,h,"f")),this.sdk=o.createSdk(r),["start","next"].forEach((e=>{const i=this.sdk.flow[e],r=a.withRetry(i,1e3,3);this.sdk.flow[e]=(...i)=>t.__awaiter(this,void 0,void 0,(function*(){try{return yield r(...i)}catch(t){return this.logger.error(`Error in sdk flow ${e} function`,t),{error:{errorCode:R.FETCH_EXCEPTION_ERROR_CODE,errorDescription:t.toString()}}}}))}))},F=function(e,i,r){return t.__awaiter(this,void 0,void 0,(function*(){const{projectId:i,baseUrl:s}=e;if(r("projectId")||r("baseUrl")){if(!i)return;t.__classPrivateFieldGet(this,u,"m",x).call(this,i,s)}t.__classPrivateFieldGet(this,m,"f").call(this,e)}))},P=function(){return t.__awaiter(this,void 0,void 0,(function*(){const e=yield this.getConfig();return"isMissingConfig"in e&&e.isMissingConfig&&(yield t.__classPrivateFieldGet(this,u,"m",y).call(this))}))},y=function(){return t.__awaiter(this,void 0,void 0,(function*(){const t=a.getContentUrl({projectId:this.projectId,filename:q.CONFIG_FILENAME,assetsFolder:q.PREV_VER_ASSETS_FOLDER,baseUrl:this.baseStaticUrl});try{return yield a.fetchContent(t,"json"),!0}catch(t){return!1}}))},A=function(e){t.__classPrivateFieldSet(this,p,Object.assign(Object.assign({},t.__classPrivateFieldGet(this,p,"f")),e.detail),"f")},E=function(){var e;null===(e=t.__classPrivateFieldGet(this,v,"f"))||void 0===e||e.remove(),t.__classPrivateFieldSet(this,v,null,"f")},I=function(e){return t.__awaiter(this,arguments,void 0,(function*({isDebug:e}){e?(t.__classPrivateFieldSet(this,v,document.createElement("descope-debugger"),"f"),Object.assign(t.__classPrivateFieldGet(this,v,"f").style,{position:"fixed",top:"0",right:"0",height:"100vh",width:"100vw",pointerEvents:"none",zIndex:99999}),yield Promise.resolve().then((function(){return N(require("../debugger-wc.js"))})),document.body.appendChild(t.__classPrivateFieldGet(this,v,"f"))):t.__classPrivateFieldGet(this,u,"m",E).call(this)}))},j=function(e,i){var r;e&&this.debug&&(null===(r=t.__classPrivateFieldGet(this,v,"f"))||void 0===r||r.updateData({title:e,description:i}))},D.sdkConfigOverrides={baseHeaders:{"x-descope-sdk-name":"web-component","x-descope-sdk-version":"4.0.2"}},module.exports=D;
|
|
2
2
|
//# sourceMappingURL=BaseDescopeWc.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var e=require("tslib"),t=require("@descope/sdk-helpers"),i=require("@descope/sdk-mixins"),r=require("../constants/index.js"),s=require("../helpers/helpers.js");require("../helpers/state.js"),require("@descope/escape-markdown"),require("../helpers/webauthn.js");const n=["externalId","email","phone"],o=["newPassword","password"],a="data-username-anchor",l=e=>{var t;if(!e)return"";try{const i=null===(t=window.sessionStorage)||void 0===t?void 0:t.getItem(r.DESCOPE_LAST_SUBMITTED_LOGIN_ID_SESSION_STORAGE_KEY);if(!i)return"";const s=JSON.parse(i);return s.executionId===e&&s.loginId||""}catch(e){return""}},d=(e,t,i,s)=>{var o;const l=(null==i?void 0:i.email)||(null===(o=null==i?void 0:i.loginIds)||void 0===o?void 0:o[0]);(e=>e.querySelector("descope-new-password")||e.querySelector("descope-password"))(t)?l?(e=>{const t=['input[autocomplete="username"]',...n.map((e=>`[name="${e}"]`))].join(", ");return e.some((e=>e.querySelector(t)))})([e,t])?s.debug("Username anchor: screen already has an identifier field"):(s.debug("Username anchor: injecting hidden username input"),e.appendChild((e=>{const t=document.createElement("input");return t.setAttribute("autocomplete","username"),t.setAttribute("name","username"),t.setAttribute("type","email"),t.setAttribute("readonly","true"),t.setAttribute("tabindex","-1"),t.setAttribute("aria-hidden","true"),t.setAttribute(r.DESCOPE_ATTRIBUTE_EXCLUDE_FIELD,"true"),t.setAttribute(a,"true"),t.setAttribute("value",e),t.value=e,Object.assign(t.style,{position:"absolute",opacity:"0",pointerEvents:"none",height:"0",border:"0"}),t})(l))):s.debug("Username anchor: no user identifier available"):s.debug("Username anchor: no password component on screen")},u=t.createSingletonMixin((u=>{var c,v,
|
|
1
|
+
"use strict";var e=require("tslib"),t=require("@descope/sdk-helpers"),i=require("@descope/sdk-mixins"),r=require("../constants/index.js"),s=require("../helpers/helpers.js");require("../helpers/state.js"),require("@descope/escape-markdown"),require("../helpers/webauthn.js");const n=["externalId","email","phone"],o=["newPassword","password"],a="data-username-anchor",l=e=>{var t;if(!e)return"";try{const i=null===(t=window.sessionStorage)||void 0===t?void 0:t.getItem(r.DESCOPE_LAST_SUBMITTED_LOGIN_ID_SESSION_STORAGE_KEY);if(!i)return"";const s=JSON.parse(i);return s.executionId===e&&s.loginId||""}catch(e){return""}},d=(e,t,i,s)=>{var o;const l=(null==i?void 0:i.email)||(null===(o=null==i?void 0:i.loginIds)||void 0===o?void 0:o[0]);(e=>e.querySelector("descope-new-password")||e.querySelector("descope-password"))(t)?l?(e=>{const t=['input[autocomplete="username"]',...n.map((e=>`[name="${e}"]`))].join(", ");return e.some((e=>e.querySelector(t)))})([e,t])?s.debug("Username anchor: screen already has an identifier field"):(s.debug("Username anchor: injecting hidden username input"),e.appendChild((e=>{const t=document.createElement("input");return t.setAttribute("autocomplete","username"),t.setAttribute("name","username"),t.setAttribute("type","email"),t.setAttribute("readonly","true"),t.setAttribute("tabindex","-1"),t.setAttribute("aria-hidden","true"),t.setAttribute(r.DESCOPE_ATTRIBUTE_EXCLUDE_FIELD,"true"),t.setAttribute(a,"true"),t.setAttribute("value",e),t.value=e,Object.assign(t.style,{position:"absolute",opacity:"0",pointerEvents:"none",height:"0",border:"0"}),t})(l))):s.debug("Username anchor: no user identifier available"):s.debug("Username anchor: no password component on screen")},u=t.createSingletonMixin((u=>{var c,v,h,g,p;const m=t.compose(i.loggerMixin)(u);return p=class extends m{constructor(){super(...arguments),c.add(this),v.set(this,void 0)}updateScreenUser(t){var i,r,s;e.__classPrivateFieldSet(this,v,{email:null==t?void 0:t.email,loginIds:(null===(i=null==t?void 0:t.loginIds)||void 0===i?void 0:i.length)?t.loginIds:[l(e.__classPrivateFieldGet(this,c,"a",g))||(null===(s=null===(r=e.__classPrivateFieldGet(this,c,"a",h).sdk)||void 0===r?void 0:r.getLastUserLoginId)||void 0===s?void 0:s.call(r))].filter(Boolean)},"f")}updateUsernameAnchor(){document.querySelectorAll(`[${a}="true"]`).forEach((e=>e.remove())),d(this,e.__classPrivateFieldGet(this,c,"a",h).contentRootElement,e.__classPrivateFieldGet(this,v,"f"),this.logger)}captureLastSubmittedLoginId(t={},i){const o=s.getFirstNonEmptyValue(t,n);o&&((e,t)=>{var i;if(e&&t)try{null===(i=window.sessionStorage)||void 0===i||i.setItem(r.DESCOPE_LAST_SUBMITTED_LOGIN_ID_SESSION_STORAGE_KEY,JSON.stringify({executionId:t,loginId:e}))}catch(e){}})(o,i||e.__classPrivateFieldGet(this,c,"a",g))}storeCredentials(t={}){var i,r,a,l,d,u;const c=s.getFirstNonEmptyValue(t,n)||(null===(i=e.__classPrivateFieldGet(this,v,"f"))||void 0===i?void 0:i.email)||(null===(a=null===(r=e.__classPrivateFieldGet(this,v,"f"))||void 0===r?void 0:r.loginIds)||void 0===a?void 0:a[0]),h=s.getFirstNonEmptyValue(t,o);if(c&&h)try{if(!globalThis.PasswordCredential)return;const e=new globalThis.PasswordCredential({id:c,password:h});null===(u=null===(d=null===(l=null===navigator||void 0===navigator?void 0:navigator.credentials)||void 0===l?void 0:l.store)||void 0===d?void 0:d.call(l,e))||void 0===u||u.catch((e=>{this.logger.error("Could not store credentials",null==e?void 0:e.message)}))}catch(e){this.logger.error("Could not store credentials",e.message)}}},v=new WeakMap,c=new WeakSet,h=function(){return this},g=function(){var t,i;return(null===(i=null===(t=e.__classPrivateFieldGet(this,c,"a",h).flowState)||void 0===t?void 0:t.current)||void 0===i?void 0:i.executionId)||""},p}));exports.passwordManagerMixin=u;
|
|
2
2
|
//# sourceMappingURL=passwordManagerMixin.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"passwordManagerMixin.js","sources":["../../../src/lib/mixins/passwordManagerMixin.ts"],"sourcesContent":["/* eslint-disable import/prefer-default-export */\nimport { compose, createSingletonMixin } from '@descope/sdk-helpers';\nimport { loggerMixin } from '@descope/sdk-mixins';\nimport {\n DESCOPE_ATTRIBUTE_EXCLUDE_FIELD,\n DESCOPE_LAST_SUBMITTED_LOGIN_ID_SESSION_STORAGE_KEY,\n} from '../constants';\nimport { getFirstNonEmptyValue } from '../helpers';\nimport type { ScreenStateUser } from '../types';\n\nconst LOGIN_ID_FIELDS = ['externalId', 'email', 'phone'];\nconst PASSWORD_FIELDS = ['newPassword', 'password'];\n\nconst USERNAME_ANCHOR_ATTRIBUTE = 'data-username-anchor';\n\n// What the mixin needs from its host. Defined as an interface (not imported)\n// to avoid a circular dependency on DescopeWc. Exported so declaration emit\n// can name it from BaseDescopeWc's composed base class.\nexport interface PasswordManagerHost {\n contentRootElement?: HTMLElement;\n flowState?: { current?: { executionId?: string } };\n sdk?: { getLastUserLoginId?: () => string };\n}\n\n// the last identifier the user submitted on a previous screen in this flow\n// (e.g. the email entered before a magic link was sent), used when neither\n// the flow state nor a previous authentication provides one.\n// kept in sessionStorage (tab scoped, cleared when the tab closes) so it\n// survives page reloads during the flow, and scoped to the flow execution so\n// a stale identifier is never carried into another flow (or another user)\n// running in the same tab\nconst getLastSubmittedLoginId = (executionId: string): string => {\n // a missing execution id must never match anything, otherwise two flows\n // without one would share the stored identifier\n if (!executionId) {\n return '';\n }\n try {\n const raw = window.sessionStorage?.getItem(\n DESCOPE_LAST_SUBMITTED_LOGIN_ID_SESSION_STORAGE_KEY,\n );\n if (!raw) {\n return '';\n }\n const stored = JSON.parse(raw);\n return stored.executionId === executionId ? stored.loginId || '' : '';\n } catch (e) {\n return '';\n }\n};\n\nconst setLastSubmittedLoginId = (loginId: string, executionId: string) => {\n if (!loginId || !executionId) {\n return;\n }\n try {\n window.sessionStorage?.setItem(\n DESCOPE_LAST_SUBMITTED_LOGIN_ID_SESSION_STORAGE_KEY,\n JSON.stringify({ executionId, loginId }),\n );\n } catch (e) {\n // sessionStorage unavailable, losing reload persistence is acceptable\n }\n};\n\nconst clearUsernameAnchorIfExists = () => {\n document\n .querySelectorAll(`[${USERNAME_ANCHOR_ATTRIBUTE}=\"true\"]`)\n .forEach((ele) => ele.remove());\n};\n\nconst findPasswordComponent = (contentRootEle: Element) =>\n contentRootEle.querySelector('descope-new-password') ||\n contentRootEle.querySelector('descope-password');\n\n// an identifier is already on screen when there is an autocomplete=\"username\"\n// input, or a component collecting one of the login id fields (e.g.\n// descope-email-field renders its input inside a closed shadow root, so only\n// its name attribute is visible from here)\nconst hasLoginIdField = (roots: Element[]) => {\n const selector = [\n 'input[autocomplete=\"username\"]',\n ...LOGIN_ID_FIELDS.map((field) => `[name=\"${field}\"]`),\n ].join(', ');\n return roots.some((root) => root.querySelector(selector));\n};\n\nconst createUsernameAnchor = (loginId: string) => {\n const input = document.createElement('input');\n input.setAttribute('autocomplete', 'username');\n input.setAttribute('name', 'username');\n input.setAttribute('type', 'email');\n input.setAttribute('readonly', 'true');\n input.setAttribute('tabindex', '-1');\n input.setAttribute('aria-hidden', 'true');\n // never collect the anchor's value into the submitted form data\n input.setAttribute(DESCOPE_ATTRIBUTE_EXCLUDE_FIELD, 'true');\n // cleaned up by clearUsernameAnchorIfExists between screens\n input.setAttribute(USERNAME_ANCHOR_ATTRIBUTE, 'true');\n // some password managers read the markup value rather than the property\n input.setAttribute('value', loginId);\n input.value = loginId;\n // real input hidden via CSSOM: managers ignore type=\"hidden\", and strict\n // CSP style-src blocks style attributes\n Object.assign(input.style, {\n position: 'absolute',\n opacity: '0',\n pointerEvents: 'none',\n height: '0',\n border: '0',\n });\n return input;\n};\n\n// Anchors a hidden autocomplete=\"username\" input on password screens that\n// have no identifier input, so password managers can associate the credential\n// with a user (descope/etc#16712). Appended to the host light DOM — password\n// manager save heuristics (verified on WebKit) do not scan shadow trees\nconst injectUsernameAnchorIfNeeded = (\n hostEle: HTMLElement,\n contentRootEle: Element,\n user: ScreenStateUser | undefined,\n logger: { debug: (...args: string[]) => void },\n) => {\n const loginId = user?.email || user?.loginIds?.[0];\n\n if (!findPasswordComponent(contentRootEle)) {\n logger.debug('Username anchor: no password component on screen');\n return;\n }\n if (!loginId) {\n logger.debug('Username anchor: no user identifier available');\n return;\n }\n if (hasLoginIdField([hostEle, contentRootEle])) {\n logger.debug('Username anchor: screen already has an identifier field');\n return;\n }\n\n logger.debug('Username anchor: injecting hidden username input');\n hostEle.appendChild(createUsernameAnchor(loginId));\n};\n\n/**\n * Password manager integrations: keeps track of the current screen's user\n * identifier, anchors a hidden username input on password screens that have\n * no identifier input, and stores submitted credentials via the Credential\n * Management API.\n */\nexport const passwordManagerMixin = createSingletonMixin(\n <T extends CustomElementConstructor>(superclass: T) => {\n const BaseClass = compose(loggerMixin)(superclass);\n\n return class PasswordManagerMixinClass extends BaseClass {\n // the authenticated user of the current screen (if any), used as a\n // fallback identifier for password manager integrations on screens that\n // have no identifier input (e.g. step-up password change)\n #screenUser?: ScreenStateUser;\n\n get #host() {\n return this as unknown as PasswordManagerHost;\n }\n\n get #executionId() {\n return this.#host.flowState?.current?.executionId || '';\n }\n\n // called on every screen render. flow state does not always carry the\n // user (e.g. after magic link auth), so fall back to the login id\n // submitted earlier in this flow, then to the last authenticated user\n updateScreenUser(stateUser?: ScreenStateUser) {\n this.#screenUser = {\n email: stateUser?.email,\n loginIds: stateUser?.loginIds?.length\n ? stateUser.loginIds\n : [\n getLastSubmittedLoginId(this.#executionId) ||\n this.#host.sdk?.getLastUserLoginId?.(),\n ].filter(Boolean),\n };\n }\n\n updateUsernameAnchor() {\n // clear the previous screen's anchor, so each screen gets an anchor\n // only if it needs one\n clearUsernameAnchorIfExists();\n\n injectUsernameAnchorIfNeeded(\n this,\n this.#host.contentRootElement,\n this.#screenUser,\n this.logger,\n );\n }\n\n // called after a successful next(): on flows that render their first\n // screen before the flow starts, the execution id only exists on the\n // response, so prefer it over the current flow state\n captureLastSubmittedLoginId(formData = {}, responseExecutionId?: string) {\n const loginId = getFirstNonEmptyValue(formData, LOGIN_ID_FIELDS);\n if (loginId) {\n setLastSubmittedLoginId(\n loginId,\n responseExecutionId || this.#executionId,\n );\n }\n }\n\n // handle storing passwords in password managers\n storeCredentials(formData = {}) {\n const id =\n getFirstNonEmptyValue(formData, LOGIN_ID_FIELDS) ||\n this.#screenUser?.email ||\n this.#screenUser?.loginIds?.[0];\n const password = getFirstNonEmptyValue(formData, PASSWORD_FIELDS);\n\n // PasswordCredential not supported in Firefox\n if (id && password) {\n try {\n if (!globalThis.PasswordCredential) {\n return;\n }\n const cred = new globalThis.PasswordCredential({ id, password });\n\n navigator?.credentials?.store?.(cred);\n } catch (e) {\n this.logger.error('Could not store credentials', e.message);\n }\n }\n }\n };\n },\n);\n"],"names":["LOGIN_ID_FIELDS","PASSWORD_FIELDS","USERNAME_ANCHOR_ATTRIBUTE","getLastSubmittedLoginId","executionId","raw","_a","window","sessionStorage","getItem","DESCOPE_LAST_SUBMITTED_LOGIN_ID_SESSION_STORAGE_KEY","stored","JSON","parse","loginId","e","injectUsernameAnchorIfNeeded","hostEle","contentRootEle","user","logger","email","loginIds","querySelector","findPasswordComponent","roots","selector","map","field","join","some","root","hasLoginIdField","debug","appendChild","input","document","createElement","setAttribute","DESCOPE_ATTRIBUTE_EXCLUDE_FIELD","value","Object","assign","style","position","opacity","pointerEvents","height","border","createUsernameAnchor","passwordManagerMixin","createSingletonMixin","superclass","BaseClass","compose","loggerMixin","constructor","_PasswordManagerMixinClass_screenUser","set","this","updateScreenUser","stateUser","__classPrivateFieldSet","_b","length","__classPrivateFieldGet","_PasswordManagerMixinClass_instances","_PasswordManagerMixinClass_executionId_get","_d","_c","_PasswordManagerMixinClass_host_get","sdk","getLastUserLoginId","call","filter","Boolean","updateUsernameAnchor","querySelectorAll","forEach","ele","remove","contentRootElement","captureLastSubmittedLoginId","formData","responseExecutionId","getFirstNonEmptyValue","setItem","stringify","setLastSubmittedLoginId","storeCredentials","id","password","globalThis","PasswordCredential","cred","_f","_e","navigator","credentials","store","error","message","flowState","current"],"mappings":"kRAUA,MAAMA,EAAkB,CAAC,aAAc,QAAS,SAC1CC,EAAkB,CAAC,cAAe,YAElCC,EAA4B,uBAkB5BC,EAA2BC,UAG/B,IAAKA,EACH,MAAO,GAET,IACE,MAAMC,EAA2B,QAArBC,EAAAC,OAAOC,sBAAc,IAAAF,OAAA,EAAAA,EAAEG,QACjCC,EAAmDA,qDAErD,IAAKL,EACH,MAAO,GAET,MAAMM,EAASC,KAAKC,MAAMR,GAC1B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AA,EAAE/C,gBAAW,IAAA8C,OAAA,EAAAA,EAAA,IACzBuB,EAAWN,EAAAA,sBAAsBF,EAAUlF,GAGjD,GAAIyF,GAAMC,EACR,IACE,IAAKC,WAAWC,mBACd,OAEF,MAAMC,EAAO,IAAIF,WAAWC,mBAAmB,CAAEH,KAAIC,aAErB,QAAhCI,EAAwB,QAAxBC,EAAA,OAAAC,gBAAA,IAAAA,eAAA,EAAAA,UAAWC,mBAAa,IAAAF,OAAA,EAAAA,EAAAG,aAAQ,IAAAJ,GAAAA,EAAAtB,KAAAuB,EAAAF,EACjC,CAAC,MAAO/E,GACP4C,KAAKvC,OAAOgF,MAAM,8BAA+BrF,EAAEsF,QACpD,CAEJ,4CArEC,OAAO1C,IACR,uBAGC,OAAoC,QAA7BU,EAAoB,QAApBN,EAAAE,EAAAA,uBAAAN,KAAUO,EAAA,IAAAI,GAACgC,iBAAS,IAAAvC,OAAA,EAAAA,EAAEwC,eAAO,IAAAlC,OAAA,EAAAA,EAAEjE,cAAe,EACtD,EAiEDE,CAAA"}
|
|
1
|
+
{"version":3,"file":"passwordManagerMixin.js","sources":["../../../src/lib/mixins/passwordManagerMixin.ts"],"sourcesContent":["/* eslint-disable import/prefer-default-export */\nimport { compose, createSingletonMixin } from '@descope/sdk-helpers';\nimport { loggerMixin } from '@descope/sdk-mixins';\nimport {\n DESCOPE_ATTRIBUTE_EXCLUDE_FIELD,\n DESCOPE_LAST_SUBMITTED_LOGIN_ID_SESSION_STORAGE_KEY,\n} from '../constants';\nimport { getFirstNonEmptyValue } from '../helpers';\nimport type { ScreenStateUser } from '../types';\n\nconst LOGIN_ID_FIELDS = ['externalId', 'email', 'phone'];\nconst PASSWORD_FIELDS = ['newPassword', 'password'];\n\nconst USERNAME_ANCHOR_ATTRIBUTE = 'data-username-anchor';\n\n// What the mixin needs from its host. Defined as an interface (not imported)\n// to avoid a circular dependency on DescopeWc. Exported so declaration emit\n// can name it from BaseDescopeWc's composed base class.\nexport interface PasswordManagerHost {\n contentRootElement?: HTMLElement;\n flowState?: { current?: { executionId?: string } };\n sdk?: { getLastUserLoginId?: () => string };\n}\n\n// the last identifier the user submitted on a previous screen in this flow\n// (e.g. the email entered before a magic link was sent), used when neither\n// the flow state nor a previous authentication provides one.\n// kept in sessionStorage (tab scoped, cleared when the tab closes) so it\n// survives page reloads during the flow, and scoped to the flow execution so\n// a stale identifier is never carried into another flow (or another user)\n// running in the same tab\nconst getLastSubmittedLoginId = (executionId: string): string => {\n // a missing execution id must never match anything, otherwise two flows\n // without one would share the stored identifier\n if (!executionId) {\n return '';\n }\n try {\n const raw = window.sessionStorage?.getItem(\n DESCOPE_LAST_SUBMITTED_LOGIN_ID_SESSION_STORAGE_KEY,\n );\n if (!raw) {\n return '';\n }\n const stored = JSON.parse(raw);\n return stored.executionId === executionId ? stored.loginId || '' : '';\n } catch (e) {\n return '';\n }\n};\n\nconst setLastSubmittedLoginId = (loginId: string, executionId: string) => {\n if (!loginId || !executionId) {\n return;\n }\n try {\n window.sessionStorage?.setItem(\n DESCOPE_LAST_SUBMITTED_LOGIN_ID_SESSION_STORAGE_KEY,\n JSON.stringify({ executionId, loginId }),\n );\n } catch (e) {\n // sessionStorage unavailable, losing reload persistence is acceptable\n }\n};\n\nconst clearUsernameAnchorIfExists = () => {\n document\n .querySelectorAll(`[${USERNAME_ANCHOR_ATTRIBUTE}=\"true\"]`)\n .forEach((ele) => ele.remove());\n};\n\nconst findPasswordComponent = (contentRootEle: Element) =>\n contentRootEle.querySelector('descope-new-password') ||\n contentRootEle.querySelector('descope-password');\n\n// an identifier is already on screen when there is an autocomplete=\"username\"\n// input, or a component collecting one of the login id fields (e.g.\n// descope-email-field renders its input inside a closed shadow root, so only\n// its name attribute is visible from here)\nconst hasLoginIdField = (roots: Element[]) => {\n const selector = [\n 'input[autocomplete=\"username\"]',\n ...LOGIN_ID_FIELDS.map((field) => `[name=\"${field}\"]`),\n ].join(', ');\n return roots.some((root) => root.querySelector(selector));\n};\n\nconst createUsernameAnchor = (loginId: string) => {\n const input = document.createElement('input');\n input.setAttribute('autocomplete', 'username');\n input.setAttribute('name', 'username');\n input.setAttribute('type', 'email');\n input.setAttribute('readonly', 'true');\n input.setAttribute('tabindex', '-1');\n input.setAttribute('aria-hidden', 'true');\n // never collect the anchor's value into the submitted form data\n input.setAttribute(DESCOPE_ATTRIBUTE_EXCLUDE_FIELD, 'true');\n // cleaned up by clearUsernameAnchorIfExists between screens\n input.setAttribute(USERNAME_ANCHOR_ATTRIBUTE, 'true');\n // some password managers read the markup value rather than the property\n input.setAttribute('value', loginId);\n input.value = loginId;\n // real input hidden via CSSOM: managers ignore type=\"hidden\", and strict\n // CSP style-src blocks style attributes\n Object.assign(input.style, {\n position: 'absolute',\n opacity: '0',\n pointerEvents: 'none',\n height: '0',\n border: '0',\n });\n return input;\n};\n\n// Anchors a hidden autocomplete=\"username\" input on password screens that\n// have no identifier input, so password managers can associate the credential\n// with a user (descope/etc#16712). Appended to the host light DOM — password\n// manager save heuristics (verified on WebKit) do not scan shadow trees\nconst injectUsernameAnchorIfNeeded = (\n hostEle: HTMLElement,\n contentRootEle: Element,\n user: ScreenStateUser | undefined,\n logger: { debug: (...args: string[]) => void },\n) => {\n const loginId = user?.email || user?.loginIds?.[0];\n\n if (!findPasswordComponent(contentRootEle)) {\n logger.debug('Username anchor: no password component on screen');\n return;\n }\n if (!loginId) {\n logger.debug('Username anchor: no user identifier available');\n return;\n }\n if (hasLoginIdField([hostEle, contentRootEle])) {\n logger.debug('Username anchor: screen already has an identifier field');\n return;\n }\n\n logger.debug('Username anchor: injecting hidden username input');\n hostEle.appendChild(createUsernameAnchor(loginId));\n};\n\n/**\n * Password manager integrations: keeps track of the current screen's user\n * identifier, anchors a hidden username input on password screens that have\n * no identifier input, and stores submitted credentials via the Credential\n * Management API.\n */\nexport const passwordManagerMixin = createSingletonMixin(\n <T extends CustomElementConstructor>(superclass: T) => {\n const BaseClass = compose(loggerMixin)(superclass);\n\n return class PasswordManagerMixinClass extends BaseClass {\n // the authenticated user of the current screen (if any), used as a\n // fallback identifier for password manager integrations on screens that\n // have no identifier input (e.g. step-up password change)\n #screenUser?: ScreenStateUser;\n\n get #host() {\n return this as unknown as PasswordManagerHost;\n }\n\n get #executionId() {\n return this.#host.flowState?.current?.executionId || '';\n }\n\n // called on every screen render. flow state does not always carry the\n // user (e.g. after magic link auth), so fall back to the login id\n // submitted earlier in this flow, then to the last authenticated user\n updateScreenUser(stateUser?: ScreenStateUser) {\n this.#screenUser = {\n email: stateUser?.email,\n loginIds: stateUser?.loginIds?.length\n ? stateUser.loginIds\n : [\n getLastSubmittedLoginId(this.#executionId) ||\n this.#host.sdk?.getLastUserLoginId?.(),\n ].filter(Boolean),\n };\n }\n\n updateUsernameAnchor() {\n // clear the previous screen's anchor, so each screen gets an anchor\n // only if it needs one\n clearUsernameAnchorIfExists();\n\n injectUsernameAnchorIfNeeded(\n this,\n this.#host.contentRootElement,\n this.#screenUser,\n this.logger,\n );\n }\n\n // called after a successful next(): on flows that render their first\n // screen before the flow starts, the execution id only exists on the\n // response, so prefer it over the current flow state\n captureLastSubmittedLoginId(formData = {}, responseExecutionId?: string) {\n const loginId = getFirstNonEmptyValue(formData, LOGIN_ID_FIELDS);\n if (loginId) {\n setLastSubmittedLoginId(\n loginId,\n responseExecutionId || this.#executionId,\n );\n }\n }\n\n // handle storing passwords in password managers\n storeCredentials(formData = {}) {\n const id =\n getFirstNonEmptyValue(formData, LOGIN_ID_FIELDS) ||\n this.#screenUser?.email ||\n this.#screenUser?.loginIds?.[0];\n const password = getFirstNonEmptyValue(formData, PASSWORD_FIELDS);\n\n // PasswordCredential not supported in Firefox\n if (id && password) {\n try {\n if (!globalThis.PasswordCredential) {\n return;\n }\n const cred = new globalThis.PasswordCredential({ id, password });\n\n navigator?.credentials?.store?.(cred)?.catch((e) => {\n this.logger.error('Could not store credentials', e?.message);\n });\n } catch (e) {\n this.logger.error('Could not store credentials', e.message);\n }\n }\n }\n };\n },\n);\n"],"names":["LOGIN_ID_FIELDS","PASSWORD_FIELDS","USERNAME_ANCHOR_ATTRIBUTE","getLastSubmittedLoginId","executionId","raw","_a","window","sessionStorage","getItem","DESCOPE_LAST_SUBMITTED_LOGIN_ID_SESSION_STORAGE_KEY","stored","JSON","parse","loginId","e","injectUsernameAnchorIfNeeded","hostEle","contentRootEle","user","logger","email","loginIds","querySelector","findPasswordComponent","roots","selector","map","field","join","some","root","hasLoginIdField","debug","appendChild","input","document","createElement","setAttribute","DESCOPE_ATTRIBUTE_EXCLUDE_FIELD","value","Object","assign","style","position","opacity","pointerEvents","height","border","createUsernameAnchor","passwordManagerMixin","createSingletonMixin","superclass","BaseClass","compose","loggerMixin","constructor","_PasswordManagerMixinClass_screenUser","set","this","updateScreenUser","stateUser","__classPrivateFieldSet","_b","length","__classPrivateFieldGet","_PasswordManagerMixinClass_instances","_PasswordManagerMixinClass_executionId_get","_d","_c","_PasswordManagerMixinClass_host_get","sdk","getLastUserLoginId","call","filter","Boolean","updateUsernameAnchor","querySelectorAll","forEach","ele","remove","contentRootElement","captureLastSubmittedLoginId","formData","responseExecutionId","getFirstNonEmptyValue","setItem","stringify","setLastSubmittedLoginId","storeCredentials","id","password","globalThis","PasswordCredential","cred","_g","_f","navigator","credentials","_e","store","catch","error","message","flowState","current"],"mappings":"kRAUA,MAAMA,EAAkB,CAAC,aAAc,QAAS,SAC1CC,EAAkB,CAAC,cAAe,YAElCC,EAA4B,uBAkB5BC,EAA2BC,UAG/B,IAAKA,EACH,MAAO,GAET,IACE,MAAMC,EAA2B,QAArBC,EAAAC,OAAOC,sBAAc,IAAAF,OAAA,EAAAA,EAAEG,QACjCC,EAAmDA,qDAErD,IAAKL,EACH,MAAO,GAET,MAAMM,EAASC,KAAKC,MAAMR,GAC1B,OAAOM,EAAOP,cAAgBA,GAAcO,EAAOG,SAAgB,EACpE,CAAC,MAAOC,GACP,MAAO,EACR,GAsEGC,EAA+B,CACnCC,EACAC,EACAC,EACAC,WAEA,MAAMN,GAAUK,aAAI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MAAMC,EAAO,IAAIF,WAAWC,mBAAmB,CAAEH,KAAIC,aAEd,QAAvCI,EAAgC,QAAhCC,EAAsB,UAAb,OAATC,gBAAA,IAAAA,eAAA,EAAAA,UAAWC,mBAAW,IAAAC,OAAA,EAAAA,EAAEC,aAAQ,IAAAJ,OAAA,EAAAA,EAAAvB,KAAA0B,EAAAL,UAAO,IAAAC,GAAAA,EAAAM,OAAOtF,IAC5C4C,KAAKvC,OAAOkF,MAAM,8BAA+BvF,aAAA,EAAAA,EAAGwF,QAAQ,GAE/D,CAAC,MAAOxF,GACP4C,KAAKvC,OAAOkF,MAAM,8BAA+BvF,EAAEwF,QACpD,CAEJ,4CAvEC,OAAO5C,IACR,uBAGC,OAAoC,QAA7BU,EAAoB,QAApBN,EAAAE,EAAAA,uBAAAN,KAAUO,EAAA,IAAAI,GAACkC,iBAAS,IAAAzC,OAAA,EAAAA,EAAE0C,eAAO,IAAApC,OAAA,EAAAA,EAAEjE,cAAe,EACtD,EAmEDE,CAAA"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{__classPrivateFieldGet as t,__awaiter as e,__classPrivateFieldSet as i}from"tslib";import{compose as r}from"@descope/sdk-helpers";import{staticResourcesMixin as o}from"@descope/sdk-mixins/static-resources-mixin";import{themeMixin as s}from"@descope/sdk-mixins/theme-mixin";import{injectStyleMixin as n}from"@descope/sdk-mixins/inject-style-mixin";import{createSdk as a}from"@descope/web-js-sdk";import{ELEMENTS_TO_IGNORE_ENTER_KEY_ON as u}from"../constants/index.js";import{handleUrlParams as l,clearRunIdsFromUrl as d,camelCase as c,getRunIdsFromUrl as h,getContentUrl as f,fetchContent as g,withRetry as p}from"../helpers/helpers.js";import m from"../helpers/state.js";import"@descope/escape-markdown";import"../helpers/webauthn.js";import{setCustomStorage as b}from"../helpers/storage.js";import{transformFlowInputFormData as v,extractNestedAttribute as w}from"../helpers/flowInputs.js";import{formMountMixin as k}from"../mixins/formMountMixin.js";import{componentConditionsMixin as C}from"../mixins/componentConditionsMixin.js";import{duplicateFlowWarningMixin as y}from"../mixins/duplicateFlowWarningMixin.js";import{passwordManagerMixin as A}from"../mixins/passwordManagerMixin.js";import{CONFIG_FILENAME as x,PREV_VER_ASSETS_FOLDER as j}from"../constants/content.js";import{FETCH_EXCEPTION_ERROR_CODE as I}from"../constants/general.js";var E,M,L,S,U,O,W,D,P,N,F,K,R,T,B,H,J,V,q,$,z,Q;const G=r(s,o,k,C,y,A,n)(HTMLElement);class X extends G{static get observedAttributes(){return["project-id","flow-id","base-url","tenant","locale","debug","storage-prefix","preview","redirect-url","auto-focus","store-last-authenticated-user","refresh-cookie-name","keep-last-authenticated-user-after-logout","validate-on-blur","style-id"]}constructor(r){super(),E.add(this),L.set(this,!1),S.set(this,void 0),this.flowStatus="initial",this.loggerWrapper={error:(e,i="")=>{this.logger.error(e,i,new Error),t(this,E,"m",Q).call(this,e,i)},warn:(t,e="")=>{this.logger.warn(t,e)},info:(t,e="",i={})=>{this.logger.info(t,e,i)},debug:(t,e="")=>{this.logger.debug(t,e)}},U.set(this,new m),O.set(this,new m),W.set(this,{}),this.getComponentsContext=()=>t(this,W,"f"),this.nextRequestStatus=new m({isLoading:!1}),D.set(this,void 0),P.set(this,{popstate:t(this,E,"m",T).bind(this),componentsContext:t(this,E,"m",q).bind(this)}),N.set(this,void 0),this.getConfig=()=>e(this,void 0,void 0,(function*(){return(yield this.config)||{isMissingConfig:!0}})),i(this,N,r,"f"),t(this,E,"m",K).call(this)}get flowId(){return this.getAttribute("flow-id")}get client(){try{return JSON.parse(this.getAttribute("client"))||{}}catch(t){return{}}}get redirectUrl(){return this.getAttribute("redirect-url")||void 0}get debug(){return"true"===this.getAttribute("debug")}get locale(){return this.getAttribute("locale")||void 0}get autoFocus(){var t;const e=null!==(t=this.getAttribute("auto-focus"))&&void 0!==t?t:"true";return"skipFirstScreen"===e?e:"true"===e}get validateOnBlur(){return"true"===this.getAttribute("validate-on-blur")}get storeLastAuthenticatedUser(){var t;return"true"===(null!==(t=this.getAttribute("store-last-authenticated-user"))&&void 0!==t?t:"true")}get refreshCookieName(){return this.getAttribute("refresh-cookie-name")||""}get keepLastAuthenticatedUserAfterLogout(){return"true"===this.getAttribute("keep-last-authenticated-user-after-logout")}get storagePrefix(){return this.getAttribute("storage-prefix")||""}get preview(){return!!this.getAttribute("preview")}get formConfig(){return v(this.form)}get form(){return this.getAttribute("form")}get formConfigValues(){return w(this.formConfig,"value")}get outboundAppId(){return this.getAttribute("outbound-app-id")}get outboundAppScopes(){try{const t=JSON.parse(this.getAttribute("outbound-app-scopes"));return t||null}catch(t){return null}}get popupOrigin(){return this.getAttribute("popup-origin")}get customStorage(){return t(this,S,"f")}set customStorage(t){if(t&&"function"!=typeof t.getItem)throw new Error("Custom storage must have a getItem method");if(t&&"function"!=typeof t.setItem)throw new Error("Custom storage must have a setItem method");if(t&&"function"!=typeof t.removeItem)throw new Error("Custom storage must have a removeItem method");i(this,S,t,"f"),b(t)}get isRestartOnError(){return"true"===this.getAttribute("restart-on-error")}getExecutionContext(){return e(this,void 0,void 0,(function*(){const t=yield this.getConfig();return"executionContext"in t?t.executionContext:void 0}))}getProjectConfig(){return e(this,void 0,void 0,(function*(){const t=yield this.getConfig();return"projectConfig"in t?t.projectConfig:void 0}))}getFlowConfig(){return e(this,void 0,void 0,(function*(){var t,e;const i=yield this.getProjectConfig(),r=(null===(t=null==i?void 0:i.flows)||void 0===t?void 0:t[this.flowId])||{};return null!==(e=r.version)&&void 0!==e||(r.version=0),r}))}getTargetLocales(){return e(this,void 0,void 0,(function*(){const t=yield this.getFlowConfig();return((null==t?void 0:t.targetLocales)||[]).map((t=>t.toLowerCase()))}))}handleKeyPress(){this.logger.debug("Enable key press handler"),this.rootElement.onkeydown=t=>{var e,i,r;const o=!!(null===(e=this.shadowRoot.activeElement)||void 0===e?void 0:e.getAttribute("href")),s=u.includes(null!==(r=null===(i=this.shadowRoot.activeElement)||void 0===i?void 0:i.localName)&&void 0!==r?r:"");if("Enter"!==t.key||o||s)return;t.preventDefault();const n=this.rootElement.querySelectorAll("descope-button");if(1===n.length&&"false"!==n[0].getAttribute("auto-submit"))return void n[0].click();const a=Array.from(n).filter((t=>"true"===t.getAttribute("auto-submit")));if(1===a.length)return void a[0].click();const l=Array.from(n).filter((t=>"button"===t.getAttribute("data-type")));if(1===l.length)"false"!==l[0].getAttribute("auto-submit")&&l[0].click();else if(0===l.length){const t=Array.from(n).filter((t=>"sso"===t.getAttribute("data-type")));1===t.length&&"false"!==t[0].getAttribute("auto-submit")&&t[0].click()}}}disableKeyPressHandler(){this.logger.debug("Disable key press handler"),this.rootElement.onkeydown=null}getComponentsVersion(){return e(this,void 0,void 0,(function*(){var t;const e=yield this.getConfig(),i="projectConfig"in e?null===(t=e.projectConfig)||void 0===t?void 0:t.componentsVersion:{};return i||(this.logger.error("Did not get components version, using latest version"),"latest")}))}init(){const r=Object.create(null,{init:{get:()=>super.init}});return e(this,void 0,void 0,(function*(){var e;if(this.flowStatus="loading",["ready","error","success"].forEach((t=>this.addEventListener(t,(()=>{this.flowStatus=t})))),yield null===(e=r.init)||void 0===e?void 0:e.call(this),t(this,O,"f").subscribe(t(this,E,"m",z).bind(this)),t(this,O,"f").update({isDebug:this.debug}),t(this,E,"m",R).call(this),yield t(this,E,"m",J).call(this))return void this.loggerWrapper.error("This SDK version does not support your flows version","Make sure to upgrade your flows to the latest version or use an older SDK version");const o=yield this.getConfig();if("isMissingConfig"in o&&o.isMissingConfig)return void this.loggerWrapper.error("Cannot get config file","Make sure that your projectId & flowId are correct");const{executionId:s,stepId:n,token:a,code:u,isPopup:d,exchangeError:c,redirectAuthCallbackUrl:h,redirectAuthBackupCallbackUri:f,redirectAuthCodeChallenge:g,redirectAuthInitiator:p,ssoQueryParams:m}=l(this.flowId,this.loggerWrapper);window.addEventListener("popstate",t(this,P,"f").popstate),window.addEventListener("components-context",t(this,P,"f").componentsContext),t(this,U,"f").subscribe(t(this,E,"m",H).bind(this)),t(this,U,"f").update(Object.assign({projectId:this.projectId,flowId:this.flowId,baseUrl:this.baseUrl,tenant:this.tenantId,redirectUrl:this.redirectUrl,locale:this.locale,stepId:n,executionId:s,token:a,code:u,isPopup:d,exchangeError:c,redirectAuthCallbackUrl:h,redirectAuthBackupCallbackUri:f,redirectAuthCodeChallenge:g,redirectAuthInitiator:p},m)),i(this,L,!0,"f")}))}disconnectedCallback(){var e;t(this,U,"f").unsubscribeAll(),t(this,O,"f").unsubscribeAll(),t(this,E,"m",$).call(this),window.removeEventListener("popstate",t(this,P,"f").popstate),window.removeEventListener("components-context",t(this,P,"f").componentsContext),null===(e=super.disconnectedCallback)||void 0===e||e.call(this)}attributeChangedCallback(e,i,r){var o;if(null===(o=super.attributeChangedCallback)||void 0===o||o.call(this,e,i,r),this.shadowRoot.isConnected&&t(this,L,"f")&&i!==r&&M.observedAttributes.includes(e)){t(this,E,"m",R).call(this);const o=null===i;t(this,U,"f").update((({stepId:t,executionId:i})=>{let s=t,n=i;return o||(n=null,s=null,d()),{[c(e)]:r,stepId:s,executionId:n}})),t(this,O,"f").update({isDebug:this.debug})}}}M=X,L=new WeakMap,S=new WeakMap,U=new WeakMap,O=new WeakMap,W=new WeakMap,D=new WeakMap,P=new WeakMap,N=new WeakMap,E=new WeakSet,F=function(){this.injectStyle("\n :host {\n\t\t\twidth: 100%;\n display: block;\n\t\t}\n\n\t\t#root {\n\t\t\theight: 100%;\n display: flex;\n flex-direction: column;\n\t\t}\n\n #content-root {\n all: initial;\n transition: opacity 200ms ease-in-out;\n }\n\n\t\t#root[data-theme] {\n\t\t\tbackground-color: transparent;\n\t\t}\n\n\t\t.fade-out {\n\t\t\topacity: 0.1!important;\n\t\t}\n\n .hidden {\n display: none;\n }\n ")},K=function(){t(this,E,"m",F).call(this),this.slotElement=document.createElement("slot"),this.slotElement.classList.add("hidden"),this.rootElement.appendChild(this.slotElement)},R=function(){const t=["base-url","tenant","locale","debug","redirect-url","auto-focus","store-last-authenticated-user","refresh-cookie-name","keep-last-authenticated-user-after-logout","preview","storage-prefix","form","client","validate-on-blur","style-id","outbound-app-id","outbound-app-scopes","theme-override"];M.observedAttributes.forEach((e=>{if(!t.includes(e)&&!this[c(e)])throw Error(`${e} cannot be empty`)}))},T=function(){const{stepId:e,executionId:i}=h(this.flowId);t(this,U,"f").update({stepId:e,executionId:i})},B=function(i,r){a&&"function"==typeof a||this.logger.error("SDK was not loaded properly",a,JSON.stringify(a));const o=Object.assign(Object.assign({persistTokens:!0,preview:this.preview,storagePrefix:this.storagePrefix,storeLastAuthenticatedUser:this.storeLastAuthenticatedUser,keepLastAuthenticatedUserAfterLogout:this.keepLastAuthenticatedUserAfterLogout,refreshCookieName:this.refreshCookieName},M.sdkConfigOverrides),{projectId:i,baseUrl:r});t(this,S,"f")&&(o.customStorage=t(this,S,"f")),this.sdk=a(o),["start","next"].forEach((t=>{const i=this.sdk.flow[t],r=p(i,1e3,3);this.sdk.flow[t]=(...i)=>e(this,void 0,void 0,(function*(){try{return yield r(...i)}catch(e){return this.logger.error(`Error in sdk flow ${t} function`,e),{error:{errorCode:I,errorDescription:e.toString()}}}}))}))},H=function(i,r,o){return e(this,void 0,void 0,(function*(){const{projectId:e,baseUrl:r}=i;if(o("projectId")||o("baseUrl")){if(!e)return;t(this,E,"m",B).call(this,e,r)}t(this,N,"f").call(this,i)}))},J=function(){return e(this,void 0,void 0,(function*(){const e=yield this.getConfig();return"isMissingConfig"in e&&e.isMissingConfig&&(yield t(this,E,"m",V).call(this))}))},V=function(){return e(this,void 0,void 0,(function*(){const t=f({projectId:this.projectId,filename:x,assetsFolder:j,baseUrl:this.baseStaticUrl});try{return yield g(t,"json"),!0}catch(t){return!1}}))},q=function(e){i(this,W,Object.assign(Object.assign({},t(this,W,"f")),e.detail),"f")},$=function(){var e;null===(e=t(this,D,"f"))||void 0===e||e.remove(),i(this,D,null,"f")},z=function(r){return e(this,arguments,void 0,(function*({isDebug:e}){e?(i(this,D,document.createElement("descope-debugger"),"f"),Object.assign(t(this,D,"f").style,{position:"fixed",top:"0",right:"0",height:"100vh",width:"100vw",pointerEvents:"none",zIndex:99999}),yield import("../debugger-wc.js"),document.body.appendChild(t(this,D,"f"))):t(this,E,"m",$).call(this)}))},Q=function(e,i){var r;e&&this.debug&&(null===(r=t(this,D,"f"))||void 0===r||r.updateData({title:e,description:i}))},X.sdkConfigOverrides={baseHeaders:{"x-descope-sdk-name":"web-component","x-descope-sdk-version":"4.0.1"}};export{X as default};
|
|
1
|
+
import{__classPrivateFieldGet as t,__awaiter as e,__classPrivateFieldSet as i}from"tslib";import{compose as r}from"@descope/sdk-helpers";import{staticResourcesMixin as o}from"@descope/sdk-mixins/static-resources-mixin";import{themeMixin as s}from"@descope/sdk-mixins/theme-mixin";import{injectStyleMixin as n}from"@descope/sdk-mixins/inject-style-mixin";import{createSdk as a}from"@descope/web-js-sdk";import{ELEMENTS_TO_IGNORE_ENTER_KEY_ON as u}from"../constants/index.js";import{handleUrlParams as l,clearRunIdsFromUrl as d,camelCase as c,getRunIdsFromUrl as h,getContentUrl as f,fetchContent as g,withRetry as p}from"../helpers/helpers.js";import m from"../helpers/state.js";import"@descope/escape-markdown";import"../helpers/webauthn.js";import{setCustomStorage as b}from"../helpers/storage.js";import{transformFlowInputFormData as v,extractNestedAttribute as w}from"../helpers/flowInputs.js";import{formMountMixin as k}from"../mixins/formMountMixin.js";import{componentConditionsMixin as C}from"../mixins/componentConditionsMixin.js";import{duplicateFlowWarningMixin as y}from"../mixins/duplicateFlowWarningMixin.js";import{passwordManagerMixin as A}from"../mixins/passwordManagerMixin.js";import{CONFIG_FILENAME as x,PREV_VER_ASSETS_FOLDER as j}from"../constants/content.js";import{FETCH_EXCEPTION_ERROR_CODE as I}from"../constants/general.js";var E,M,L,S,U,O,W,D,P,N,F,K,R,T,B,H,J,V,q,$,z,Q;const G=r(s,o,k,C,y,A,n)(HTMLElement);class X extends G{static get observedAttributes(){return["project-id","flow-id","base-url","tenant","locale","debug","storage-prefix","preview","redirect-url","auto-focus","store-last-authenticated-user","refresh-cookie-name","keep-last-authenticated-user-after-logout","validate-on-blur","style-id"]}constructor(r){super(),E.add(this),L.set(this,!1),S.set(this,void 0),this.flowStatus="initial",this.loggerWrapper={error:(e,i="")=>{this.logger.error(e,i,new Error),t(this,E,"m",Q).call(this,e,i)},warn:(t,e="")=>{this.logger.warn(t,e)},info:(t,e="",i={})=>{this.logger.info(t,e,i)},debug:(t,e="")=>{this.logger.debug(t,e)}},U.set(this,new m),O.set(this,new m),W.set(this,{}),this.getComponentsContext=()=>t(this,W,"f"),this.nextRequestStatus=new m({isLoading:!1}),D.set(this,void 0),P.set(this,{popstate:t(this,E,"m",T).bind(this),componentsContext:t(this,E,"m",q).bind(this)}),N.set(this,void 0),this.getConfig=()=>e(this,void 0,void 0,(function*(){return(yield this.config)||{isMissingConfig:!0}})),i(this,N,r,"f"),t(this,E,"m",K).call(this)}get flowId(){return this.getAttribute("flow-id")}get client(){try{return JSON.parse(this.getAttribute("client"))||{}}catch(t){return{}}}get redirectUrl(){return this.getAttribute("redirect-url")||void 0}get debug(){return"true"===this.getAttribute("debug")}get locale(){return this.getAttribute("locale")||void 0}get autoFocus(){var t;const e=null!==(t=this.getAttribute("auto-focus"))&&void 0!==t?t:"true";return"skipFirstScreen"===e?e:"true"===e}get validateOnBlur(){return"true"===this.getAttribute("validate-on-blur")}get storeLastAuthenticatedUser(){var t;return"true"===(null!==(t=this.getAttribute("store-last-authenticated-user"))&&void 0!==t?t:"true")}get refreshCookieName(){return this.getAttribute("refresh-cookie-name")||""}get keepLastAuthenticatedUserAfterLogout(){return"true"===this.getAttribute("keep-last-authenticated-user-after-logout")}get storagePrefix(){return this.getAttribute("storage-prefix")||""}get preview(){return!!this.getAttribute("preview")}get formConfig(){return v(this.form)}get form(){return this.getAttribute("form")}get formConfigValues(){return w(this.formConfig,"value")}get outboundAppId(){return this.getAttribute("outbound-app-id")}get outboundAppScopes(){try{const t=JSON.parse(this.getAttribute("outbound-app-scopes"));return t||null}catch(t){return null}}get popupOrigin(){return this.getAttribute("popup-origin")}get customStorage(){return t(this,S,"f")}set customStorage(t){if(t&&"function"!=typeof t.getItem)throw new Error("Custom storage must have a getItem method");if(t&&"function"!=typeof t.setItem)throw new Error("Custom storage must have a setItem method");if(t&&"function"!=typeof t.removeItem)throw new Error("Custom storage must have a removeItem method");i(this,S,t,"f"),b(t)}get isRestartOnError(){return"true"===this.getAttribute("restart-on-error")}getExecutionContext(){return e(this,void 0,void 0,(function*(){const t=yield this.getConfig();return"executionContext"in t?t.executionContext:void 0}))}getProjectConfig(){return e(this,void 0,void 0,(function*(){const t=yield this.getConfig();return"projectConfig"in t?t.projectConfig:void 0}))}getFlowConfig(){return e(this,void 0,void 0,(function*(){var t,e;const i=yield this.getProjectConfig(),r=(null===(t=null==i?void 0:i.flows)||void 0===t?void 0:t[this.flowId])||{};return null!==(e=r.version)&&void 0!==e||(r.version=0),r}))}getTargetLocales(){return e(this,void 0,void 0,(function*(){const t=yield this.getFlowConfig();return((null==t?void 0:t.targetLocales)||[]).map((t=>t.toLowerCase()))}))}handleKeyPress(){this.logger.debug("Enable key press handler"),this.rootElement.onkeydown=t=>{var e,i,r;const o=!!(null===(e=this.shadowRoot.activeElement)||void 0===e?void 0:e.getAttribute("href")),s=u.includes(null!==(r=null===(i=this.shadowRoot.activeElement)||void 0===i?void 0:i.localName)&&void 0!==r?r:"");if("Enter"!==t.key||o||s)return;t.preventDefault();const n=this.rootElement.querySelectorAll("descope-button");if(1===n.length&&"false"!==n[0].getAttribute("auto-submit"))return void n[0].click();const a=Array.from(n).filter((t=>"true"===t.getAttribute("auto-submit")));if(1===a.length)return void a[0].click();const l=Array.from(n).filter((t=>"button"===t.getAttribute("data-type")));if(1===l.length)"false"!==l[0].getAttribute("auto-submit")&&l[0].click();else if(0===l.length){const t=Array.from(n).filter((t=>"sso"===t.getAttribute("data-type")));1===t.length&&"false"!==t[0].getAttribute("auto-submit")&&t[0].click()}}}disableKeyPressHandler(){this.logger.debug("Disable key press handler"),this.rootElement.onkeydown=null}getComponentsVersion(){return e(this,void 0,void 0,(function*(){var t;const e=yield this.getConfig(),i="projectConfig"in e?null===(t=e.projectConfig)||void 0===t?void 0:t.componentsVersion:{};return i||(this.logger.error("Did not get components version, using latest version"),"latest")}))}init(){const r=Object.create(null,{init:{get:()=>super.init}});return e(this,void 0,void 0,(function*(){var e;if(this.flowStatus="loading",["ready","error","success"].forEach((t=>this.addEventListener(t,(()=>{this.flowStatus=t})))),yield null===(e=r.init)||void 0===e?void 0:e.call(this),t(this,O,"f").subscribe(t(this,E,"m",z).bind(this)),t(this,O,"f").update({isDebug:this.debug}),t(this,E,"m",R).call(this),yield t(this,E,"m",J).call(this))return void this.loggerWrapper.error("This SDK version does not support your flows version","Make sure to upgrade your flows to the latest version or use an older SDK version");const o=yield this.getConfig();if("isMissingConfig"in o&&o.isMissingConfig)return void this.loggerWrapper.error("Cannot get config file","Make sure that your projectId & flowId are correct");const{executionId:s,stepId:n,token:a,code:u,isPopup:d,exchangeError:c,redirectAuthCallbackUrl:h,redirectAuthBackupCallbackUri:f,redirectAuthCodeChallenge:g,redirectAuthInitiator:p,ssoQueryParams:m}=l(this.flowId,this.loggerWrapper);window.addEventListener("popstate",t(this,P,"f").popstate),window.addEventListener("components-context",t(this,P,"f").componentsContext),t(this,U,"f").subscribe(t(this,E,"m",H).bind(this)),t(this,U,"f").update(Object.assign({projectId:this.projectId,flowId:this.flowId,baseUrl:this.baseUrl,tenant:this.tenantId,redirectUrl:this.redirectUrl,locale:this.locale,stepId:n,executionId:s,token:a,code:u,isPopup:d,exchangeError:c,redirectAuthCallbackUrl:h,redirectAuthBackupCallbackUri:f,redirectAuthCodeChallenge:g,redirectAuthInitiator:p},m)),i(this,L,!0,"f")}))}disconnectedCallback(){var e;t(this,U,"f").unsubscribeAll(),t(this,O,"f").unsubscribeAll(),t(this,E,"m",$).call(this),window.removeEventListener("popstate",t(this,P,"f").popstate),window.removeEventListener("components-context",t(this,P,"f").componentsContext),null===(e=super.disconnectedCallback)||void 0===e||e.call(this)}attributeChangedCallback(e,i,r){var o;if(null===(o=super.attributeChangedCallback)||void 0===o||o.call(this,e,i,r),this.shadowRoot.isConnected&&t(this,L,"f")&&i!==r&&M.observedAttributes.includes(e)){t(this,E,"m",R).call(this);const o=null===i;t(this,U,"f").update((({stepId:t,executionId:i})=>{let s=t,n=i;return o||(n=null,s=null,d()),{[c(e)]:r,stepId:s,executionId:n}})),t(this,O,"f").update({isDebug:this.debug})}}}M=X,L=new WeakMap,S=new WeakMap,U=new WeakMap,O=new WeakMap,W=new WeakMap,D=new WeakMap,P=new WeakMap,N=new WeakMap,E=new WeakSet,F=function(){this.injectStyle("\n :host {\n\t\t\twidth: 100%;\n display: block;\n\t\t}\n\n\t\t#root {\n\t\t\theight: 100%;\n display: flex;\n flex-direction: column;\n\t\t}\n\n #content-root {\n all: initial;\n transition: opacity 200ms ease-in-out;\n }\n\n\t\t#root[data-theme] {\n\t\t\tbackground-color: transparent;\n\t\t}\n\n\t\t.fade-out {\n\t\t\topacity: 0.1!important;\n\t\t}\n\n .hidden {\n display: none;\n }\n ")},K=function(){t(this,E,"m",F).call(this),this.slotElement=document.createElement("slot"),this.slotElement.classList.add("hidden"),this.rootElement.appendChild(this.slotElement)},R=function(){const t=["base-url","tenant","locale","debug","redirect-url","auto-focus","store-last-authenticated-user","refresh-cookie-name","keep-last-authenticated-user-after-logout","preview","storage-prefix","form","client","validate-on-blur","style-id","outbound-app-id","outbound-app-scopes","theme-override"];M.observedAttributes.forEach((e=>{if(!t.includes(e)&&!this[c(e)])throw Error(`${e} cannot be empty`)}))},T=function(){const{stepId:e,executionId:i}=h(this.flowId);t(this,U,"f").update({stepId:e,executionId:i})},B=function(i,r){a&&"function"==typeof a||this.logger.error("SDK was not loaded properly",a,JSON.stringify(a));const o=Object.assign(Object.assign({persistTokens:!0,preview:this.preview,storagePrefix:this.storagePrefix,storeLastAuthenticatedUser:this.storeLastAuthenticatedUser,keepLastAuthenticatedUserAfterLogout:this.keepLastAuthenticatedUserAfterLogout,refreshCookieName:this.refreshCookieName},M.sdkConfigOverrides),{projectId:i,baseUrl:r});t(this,S,"f")&&(o.customStorage=t(this,S,"f")),this.sdk=a(o),["start","next"].forEach((t=>{const i=this.sdk.flow[t],r=p(i,1e3,3);this.sdk.flow[t]=(...i)=>e(this,void 0,void 0,(function*(){try{return yield r(...i)}catch(e){return this.logger.error(`Error in sdk flow ${t} function`,e),{error:{errorCode:I,errorDescription:e.toString()}}}}))}))},H=function(i,r,o){return e(this,void 0,void 0,(function*(){const{projectId:e,baseUrl:r}=i;if(o("projectId")||o("baseUrl")){if(!e)return;t(this,E,"m",B).call(this,e,r)}t(this,N,"f").call(this,i)}))},J=function(){return e(this,void 0,void 0,(function*(){const e=yield this.getConfig();return"isMissingConfig"in e&&e.isMissingConfig&&(yield t(this,E,"m",V).call(this))}))},V=function(){return e(this,void 0,void 0,(function*(){const t=f({projectId:this.projectId,filename:x,assetsFolder:j,baseUrl:this.baseStaticUrl});try{return yield g(t,"json"),!0}catch(t){return!1}}))},q=function(e){i(this,W,Object.assign(Object.assign({},t(this,W,"f")),e.detail),"f")},$=function(){var e;null===(e=t(this,D,"f"))||void 0===e||e.remove(),i(this,D,null,"f")},z=function(r){return e(this,arguments,void 0,(function*({isDebug:e}){e?(i(this,D,document.createElement("descope-debugger"),"f"),Object.assign(t(this,D,"f").style,{position:"fixed",top:"0",right:"0",height:"100vh",width:"100vw",pointerEvents:"none",zIndex:99999}),yield import("../debugger-wc.js"),document.body.appendChild(t(this,D,"f"))):t(this,E,"m",$).call(this)}))},Q=function(e,i){var r;e&&this.debug&&(null===(r=t(this,D,"f"))||void 0===r||r.updateData({title:e,description:i}))},X.sdkConfigOverrides={baseHeaders:{"x-descope-sdk-name":"web-component","x-descope-sdk-version":"4.0.2"}};export{X as default};
|
|
2
2
|
//# sourceMappingURL=BaseDescopeWc.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{__classPrivateFieldSet as e,__classPrivateFieldGet as t}from"tslib";import{createSingletonMixin as o,compose as r}from"@descope/sdk-helpers";import{loggerMixin as n}from"@descope/sdk-mixins";import{DESCOPE_LAST_SUBMITTED_LOGIN_ID_SESSION_STORAGE_KEY as i,DESCOPE_ATTRIBUTE_EXCLUDE_FIELD as s}from"../constants/index.js";import{getFirstNonEmptyValue as a}from"../helpers/helpers.js";import"../helpers/state.js";import"@descope/escape-markdown";import"../helpers/webauthn.js";const
|
|
1
|
+
import{__classPrivateFieldSet as e,__classPrivateFieldGet as t}from"tslib";import{createSingletonMixin as o,compose as r}from"@descope/sdk-helpers";import{loggerMixin as n}from"@descope/sdk-mixins";import{DESCOPE_LAST_SUBMITTED_LOGIN_ID_SESSION_STORAGE_KEY as i,DESCOPE_ATTRIBUTE_EXCLUDE_FIELD as s}from"../constants/index.js";import{getFirstNonEmptyValue as a}from"../helpers/helpers.js";import"../helpers/state.js";import"@descope/escape-markdown";import"../helpers/webauthn.js";const l=["externalId","email","phone"],d=["newPassword","password"],u="data-username-anchor",c=e=>{var t;if(!e)return"";try{const o=null===(t=window.sessionStorage)||void 0===t?void 0:t.getItem(i);if(!o)return"";const r=JSON.parse(o);return r.executionId===e&&r.loginId||""}catch(e){return""}},v=(e,t,o,r)=>{var n;const i=(null==o?void 0:o.email)||(null===(n=null==o?void 0:o.loginIds)||void 0===n?void 0:n[0]);(e=>e.querySelector("descope-new-password")||e.querySelector("descope-password"))(t)?i?(e=>{const t=['input[autocomplete="username"]',...l.map((e=>`[name="${e}"]`))].join(", ");return e.some((e=>e.querySelector(t)))})([e,t])?r.debug("Username anchor: screen already has an identifier field"):(r.debug("Username anchor: injecting hidden username input"),e.appendChild((e=>{const t=document.createElement("input");return t.setAttribute("autocomplete","username"),t.setAttribute("name","username"),t.setAttribute("type","email"),t.setAttribute("readonly","true"),t.setAttribute("tabindex","-1"),t.setAttribute("aria-hidden","true"),t.setAttribute(s,"true"),t.setAttribute(u,"true"),t.setAttribute("value",e),t.value=e,Object.assign(t.style,{position:"absolute",opacity:"0",pointerEvents:"none",height:"0",border:"0"}),t})(i))):r.debug("Username anchor: no user identifier available"):r.debug("Username anchor: no password component on screen")},m=o((o=>{var s,m,p,h,g;const b=r(n)(o);return g=class extends b{constructor(){super(...arguments),s.add(this),m.set(this,void 0)}updateScreenUser(o){var r,n,i;e(this,m,{email:null==o?void 0:o.email,loginIds:(null===(r=null==o?void 0:o.loginIds)||void 0===r?void 0:r.length)?o.loginIds:[c(t(this,s,"a",h))||(null===(i=null===(n=t(this,s,"a",p).sdk)||void 0===n?void 0:n.getLastUserLoginId)||void 0===i?void 0:i.call(n))].filter(Boolean)},"f")}updateUsernameAnchor(){document.querySelectorAll(`[${u}="true"]`).forEach((e=>e.remove())),v(this,t(this,s,"a",p).contentRootElement,t(this,m,"f"),this.logger)}captureLastSubmittedLoginId(e={},o){const r=a(e,l);r&&((e,t)=>{var o;if(e&&t)try{null===(o=window.sessionStorage)||void 0===o||o.setItem(i,JSON.stringify({executionId:t,loginId:e}))}catch(e){}})(r,o||t(this,s,"a",h))}storeCredentials(e={}){var o,r,n,i,s,u;const c=a(e,l)||(null===(o=t(this,m,"f"))||void 0===o?void 0:o.email)||(null===(n=null===(r=t(this,m,"f"))||void 0===r?void 0:r.loginIds)||void 0===n?void 0:n[0]),v=a(e,d);if(c&&v)try{if(!globalThis.PasswordCredential)return;const e=new globalThis.PasswordCredential({id:c,password:v});null===(u=null===(s=null===(i=null===navigator||void 0===navigator?void 0:navigator.credentials)||void 0===i?void 0:i.store)||void 0===s?void 0:s.call(i,e))||void 0===u||u.catch((e=>{this.logger.error("Could not store credentials",null==e?void 0:e.message)}))}catch(e){this.logger.error("Could not store credentials",e.message)}}},m=new WeakMap,s=new WeakSet,p=function(){return this},h=function(){var e,o;return(null===(o=null===(e=t(this,s,"a",p).flowState)||void 0===e?void 0:e.current)||void 0===o?void 0:o.executionId)||""},g}));export{m as passwordManagerMixin};
|
|
2
2
|
//# sourceMappingURL=passwordManagerMixin.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"passwordManagerMixin.js","sources":["../../../src/lib/mixins/passwordManagerMixin.ts"],"sourcesContent":["/* eslint-disable import/prefer-default-export */\nimport { compose, createSingletonMixin } from '@descope/sdk-helpers';\nimport { loggerMixin } from '@descope/sdk-mixins';\nimport {\n DESCOPE_ATTRIBUTE_EXCLUDE_FIELD,\n DESCOPE_LAST_SUBMITTED_LOGIN_ID_SESSION_STORAGE_KEY,\n} from '../constants';\nimport { getFirstNonEmptyValue } from '../helpers';\nimport type { ScreenStateUser } from '../types';\n\nconst LOGIN_ID_FIELDS = ['externalId', 'email', 'phone'];\nconst PASSWORD_FIELDS = ['newPassword', 'password'];\n\nconst USERNAME_ANCHOR_ATTRIBUTE = 'data-username-anchor';\n\n// What the mixin needs from its host. Defined as an interface (not imported)\n// to avoid a circular dependency on DescopeWc. Exported so declaration emit\n// can name it from BaseDescopeWc's composed base class.\nexport interface PasswordManagerHost {\n contentRootElement?: HTMLElement;\n flowState?: { current?: { executionId?: string } };\n sdk?: { getLastUserLoginId?: () => string };\n}\n\n// the last identifier the user submitted on a previous screen in this flow\n// (e.g. the email entered before a magic link was sent), used when neither\n// the flow state nor a previous authentication provides one.\n// kept in sessionStorage (tab scoped, cleared when the tab closes) so it\n// survives page reloads during the flow, and scoped to the flow execution so\n// a stale identifier is never carried into another flow (or another user)\n// running in the same tab\nconst getLastSubmittedLoginId = (executionId: string): string => {\n // a missing execution id must never match anything, otherwise two flows\n // without one would share the stored identifier\n if (!executionId) {\n return '';\n }\n try {\n const raw = window.sessionStorage?.getItem(\n DESCOPE_LAST_SUBMITTED_LOGIN_ID_SESSION_STORAGE_KEY,\n );\n if (!raw) {\n return '';\n }\n const stored = JSON.parse(raw);\n return stored.executionId === executionId ? stored.loginId || '' : '';\n } catch (e) {\n return '';\n }\n};\n\nconst setLastSubmittedLoginId = (loginId: string, executionId: string) => {\n if (!loginId || !executionId) {\n return;\n }\n try {\n window.sessionStorage?.setItem(\n DESCOPE_LAST_SUBMITTED_LOGIN_ID_SESSION_STORAGE_KEY,\n JSON.stringify({ executionId, loginId }),\n );\n } catch (e) {\n // sessionStorage unavailable, losing reload persistence is acceptable\n }\n};\n\nconst clearUsernameAnchorIfExists = () => {\n document\n .querySelectorAll(`[${USERNAME_ANCHOR_ATTRIBUTE}=\"true\"]`)\n .forEach((ele) => ele.remove());\n};\n\nconst findPasswordComponent = (contentRootEle: Element) =>\n contentRootEle.querySelector('descope-new-password') ||\n contentRootEle.querySelector('descope-password');\n\n// an identifier is already on screen when there is an autocomplete=\"username\"\n// input, or a component collecting one of the login id fields (e.g.\n// descope-email-field renders its input inside a closed shadow root, so only\n// its name attribute is visible from here)\nconst hasLoginIdField = (roots: Element[]) => {\n const selector = [\n 'input[autocomplete=\"username\"]',\n ...LOGIN_ID_FIELDS.map((field) => `[name=\"${field}\"]`),\n ].join(', ');\n return roots.some((root) => root.querySelector(selector));\n};\n\nconst createUsernameAnchor = (loginId: string) => {\n const input = document.createElement('input');\n input.setAttribute('autocomplete', 'username');\n input.setAttribute('name', 'username');\n input.setAttribute('type', 'email');\n input.setAttribute('readonly', 'true');\n input.setAttribute('tabindex', '-1');\n input.setAttribute('aria-hidden', 'true');\n // never collect the anchor's value into the submitted form data\n input.setAttribute(DESCOPE_ATTRIBUTE_EXCLUDE_FIELD, 'true');\n // cleaned up by clearUsernameAnchorIfExists between screens\n input.setAttribute(USERNAME_ANCHOR_ATTRIBUTE, 'true');\n // some password managers read the markup value rather than the property\n input.setAttribute('value', loginId);\n input.value = loginId;\n // real input hidden via CSSOM: managers ignore type=\"hidden\", and strict\n // CSP style-src blocks style attributes\n Object.assign(input.style, {\n position: 'absolute',\n opacity: '0',\n pointerEvents: 'none',\n height: '0',\n border: '0',\n });\n return input;\n};\n\n// Anchors a hidden autocomplete=\"username\" input on password screens that\n// have no identifier input, so password managers can associate the credential\n// with a user (descope/etc#16712). Appended to the host light DOM — password\n// manager save heuristics (verified on WebKit) do not scan shadow trees\nconst injectUsernameAnchorIfNeeded = (\n hostEle: HTMLElement,\n contentRootEle: Element,\n user: ScreenStateUser | undefined,\n logger: { debug: (...args: string[]) => void },\n) => {\n const loginId = user?.email || user?.loginIds?.[0];\n\n if (!findPasswordComponent(contentRootEle)) {\n logger.debug('Username anchor: no password component on screen');\n return;\n }\n if (!loginId) {\n logger.debug('Username anchor: no user identifier available');\n return;\n }\n if (hasLoginIdField([hostEle, contentRootEle])) {\n logger.debug('Username anchor: screen already has an identifier field');\n return;\n }\n\n logger.debug('Username anchor: injecting hidden username input');\n hostEle.appendChild(createUsernameAnchor(loginId));\n};\n\n/**\n * Password manager integrations: keeps track of the current screen's user\n * identifier, anchors a hidden username input on password screens that have\n * no identifier input, and stores submitted credentials via the Credential\n * Management API.\n */\nexport const passwordManagerMixin = createSingletonMixin(\n <T extends CustomElementConstructor>(superclass: T) => {\n const BaseClass = compose(loggerMixin)(superclass);\n\n return class PasswordManagerMixinClass extends BaseClass {\n // the authenticated user of the current screen (if any), used as a\n // fallback identifier for password manager integrations on screens that\n // have no identifier input (e.g. step-up password change)\n #screenUser?: ScreenStateUser;\n\n get #host() {\n return this as unknown as PasswordManagerHost;\n }\n\n get #executionId() {\n return this.#host.flowState?.current?.executionId || '';\n }\n\n // called on every screen render. flow state does not always carry the\n // user (e.g. after magic link auth), so fall back to the login id\n // submitted earlier in this flow, then to the last authenticated user\n updateScreenUser(stateUser?: ScreenStateUser) {\n this.#screenUser = {\n email: stateUser?.email,\n loginIds: stateUser?.loginIds?.length\n ? stateUser.loginIds\n : [\n getLastSubmittedLoginId(this.#executionId) ||\n this.#host.sdk?.getLastUserLoginId?.(),\n ].filter(Boolean),\n };\n }\n\n updateUsernameAnchor() {\n // clear the previous screen's anchor, so each screen gets an anchor\n // only if it needs one\n clearUsernameAnchorIfExists();\n\n injectUsernameAnchorIfNeeded(\n this,\n this.#host.contentRootElement,\n this.#screenUser,\n this.logger,\n );\n }\n\n // called after a successful next(): on flows that render their first\n // screen before the flow starts, the execution id only exists on the\n // response, so prefer it over the current flow state\n captureLastSubmittedLoginId(formData = {}, responseExecutionId?: string) {\n const loginId = getFirstNonEmptyValue(formData, LOGIN_ID_FIELDS);\n if (loginId) {\n setLastSubmittedLoginId(\n loginId,\n responseExecutionId || this.#executionId,\n );\n }\n }\n\n // handle storing passwords in password managers\n storeCredentials(formData = {}) {\n const id =\n getFirstNonEmptyValue(formData, LOGIN_ID_FIELDS) ||\n this.#screenUser?.email ||\n this.#screenUser?.loginIds?.[0];\n const password = getFirstNonEmptyValue(formData, PASSWORD_FIELDS);\n\n // PasswordCredential not supported in Firefox\n if (id && password) {\n try {\n if (!globalThis.PasswordCredential) {\n return;\n }\n const cred = new globalThis.PasswordCredential({ id, password });\n\n navigator?.credentials?.store?.(cred);\n } catch (e) {\n this.logger.error('Could not store credentials', e.message);\n }\n }\n }\n };\n },\n);\n"],"names":["LOGIN_ID_FIELDS","PASSWORD_FIELDS","USERNAME_ANCHOR_ATTRIBUTE","getLastSubmittedLoginId","executionId","raw","_a","window","sessionStorage","getItem","DESCOPE_LAST_SUBMITTED_LOGIN_ID_SESSION_STORAGE_KEY","stored","JSON","parse","loginId","e","injectUsernameAnchorIfNeeded","hostEle","contentRootEle","user","logger","email","loginIds","querySelector","findPasswordComponent","roots","selector","map","field","join","some","root","hasLoginIdField","debug","appendChild","input","document","createElement","setAttribute","DESCOPE_ATTRIBUTE_EXCLUDE_FIELD","value","Object","assign","style","position","opacity","pointerEvents","height","border","createUsernameAnchor","passwordManagerMixin","createSingletonMixin","superclass","BaseClass","compose","loggerMixin","constructor","_PasswordManagerMixinClass_screenUser","set","this","updateScreenUser","stateUser","__classPrivateFieldSet","_b","length","__classPrivateFieldGet","_PasswordManagerMixinClass_instances","_PasswordManagerMixinClass_executionId_get","_d","_c","_PasswordManagerMixinClass_host_get","sdk","getLastUserLoginId","call","filter","Boolean","updateUsernameAnchor","querySelectorAll","forEach","ele","remove","contentRootElement","captureLastSubmittedLoginId","formData","responseExecutionId","getFirstNonEmptyValue","setItem","stringify","setLastSubmittedLoginId","storeCredentials","id","password","globalThis","PasswordCredential","cred","_f","_e","navigator","credentials","store","error","message","flowState","current"],"mappings":"ieAUA,MAAMA,EAAkB,CAAC,aAAc,QAAS,SAC1CC,EAAkB,CAAC,cAAe,YAElCC,EAA4B,uBAkB5BC,EAA2BC,UAG/B,IAAKA,EACH,MAAO,GAET,IACE,MAAMC,EAA2B,QAArBC,EAAAC,OAAOC,sBAAc,IAAAF,OAAA,EAAAA,EAAEG,QACjCC,GAEF,IAAKL,EACH,MAAO,GAET,MAAMM,EAASC,KAAKC,MAAMR,GAC1B,OAAOM,EAAOP,cAAgBA,GAAcO,EAAOG,SAAgB,EACpE,CAAC,MAAOC,GACP,MAAO,EACR,GAsEGC,EAA+B,CACnCC,EACAC,EACAC,EACAC,WAEA,MAAMN,GAAUK,aAAI,EAAJA,EAAME,SAA0B,UAAjBF,aAAI,EAAJA,EAAMG,gBAAW,IAAAhB,OAAA,EAAAA,EAAA,IArDpB,CAACY,GAC7BA,EAAeK,cAAc,yBAC7BL,EAAeK,cAAc,oBAqDxBC,CAAsBN,GAItBJ,EAnDiB,CAACW,IACvB,MAAMC,EAAW,CACf,oCACG1B,EAAgB2B,KAAKC,GAAU,UAAUA,SAC5CC,KAAK,MACP,OAAOJ,EAAMK,MAAMC,GAASA,EAAKR,cAAcG,IAAU,EAkDrDM,CAAgB,CAACf,EAASC,IAC5BE,EAAOa,MAAM,4DAIfb,EAAOa,MAAM,oDACbhB,EAAQiB,YArDmB,CAACpB,IAC5B,MAAMqB,EAAQC,SAASC,cAAc,SAuBrC,OAtBAF,EAAMG,aAAa,eAAgB,YACnCH,EAAMG,aAAa,OAAQ,YAC3BH,EAAMG,aAAa,OAAQ,SAC3BH,EAAMG,aAAa,WAAY,QAC/BH,EAAMG,aAAa,WAAY,MAC/BH,EAAMG,aAAa,cAAe,QAElCH,EAAMG,aAAaC,EAAiC,QAEpDJ,EAAMG,aAAapC,EAA2B,QAE9CiC,EAA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B,EAAAN,KAAiBO,EAAA,IAAAC,GAG7C,CAGD,gBAAAsB,CAAiBN,EAAW,kBAC1B,MAAMO,EACJL,EAAsBF,EAAUnF,KAChB,QAAhB+D,EAAAE,EAAAN,KAAgBF,EAAA,YAAA,IAAAM,OAAA,EAAAA,EAAE1C,SACW,QAA7B+C,EAAgB,QAAhBC,EAAAJ,EAAAN,KAAgBF,EAAA,YAAA,IAAAY,OAAA,EAAAA,EAAE/C,gBAAW,IAAA8C,OAAA,EAAAA,EAAA,IACzBuB,EAAWN,EAAsBF,EAAUlF,GAGjD,GAAIyF,GAAMC,EACR,IACE,IAAKC,WAAWC,mBACd,OAEF,MAAMC,EAAO,IAAIF,WAAWC,mBAAmB,CAAEH,KAAIC,aAErB,QAAhCI,EAAwB,QAAxBC,EAAA,OAAAC,gBAAA,IAAAA,eAAA,EAAAA,UAAWC,mBAAa,IAAAF,OAAA,EAAAA,EAAAG,aAAQ,IAAAJ,GAAAA,EAAAtB,KAAAuB,EAAAF,EACjC,CAAC,MAAO/E,GACP4C,KAAKvC,OAAOgF,MAAM,8BAA+BrF,EAAEsF,QACpD,CAEJ,4CArEC,OAAO1C,IACR,uBAGC,OAAoC,QAA7BU,EAAoB,QAApBN,EAAAE,EAAAN,KAAUO,EAAA,IAAAI,GAACgC,iBAAS,IAAAvC,OAAA,EAAAA,EAAEwC,eAAO,IAAAlC,OAAA,EAAAA,EAAEjE,cAAe,EACtD,EAiEDE,CAAA"}
|
|
1
|
+
{"version":3,"file":"passwordManagerMixin.js","sources":["../../../src/lib/mixins/passwordManagerMixin.ts"],"sourcesContent":["/* eslint-disable import/prefer-default-export */\nimport { compose, createSingletonMixin } from '@descope/sdk-helpers';\nimport { loggerMixin } from '@descope/sdk-mixins';\nimport {\n DESCOPE_ATTRIBUTE_EXCLUDE_FIELD,\n DESCOPE_LAST_SUBMITTED_LOGIN_ID_SESSION_STORAGE_KEY,\n} from '../constants';\nimport { getFirstNonEmptyValue } from '../helpers';\nimport type { ScreenStateUser } from '../types';\n\nconst LOGIN_ID_FIELDS = ['externalId', 'email', 'phone'];\nconst PASSWORD_FIELDS = ['newPassword', 'password'];\n\nconst USERNAME_ANCHOR_ATTRIBUTE = 'data-username-anchor';\n\n// What the mixin needs from its host. Defined as an interface (not imported)\n// to avoid a circular dependency on DescopeWc. Exported so declaration emit\n// can name it from BaseDescopeWc's composed base class.\nexport interface PasswordManagerHost {\n contentRootElement?: HTMLElement;\n flowState?: { current?: { executionId?: string } };\n sdk?: { getLastUserLoginId?: () => string };\n}\n\n// the last identifier the user submitted on a previous screen in this flow\n// (e.g. the email entered before a magic link was sent), used when neither\n// the flow state nor a previous authentication provides one.\n// kept in sessionStorage (tab scoped, cleared when the tab closes) so it\n// survives page reloads during the flow, and scoped to the flow execution so\n// a stale identifier is never carried into another flow (or another user)\n// running in the same tab\nconst getLastSubmittedLoginId = (executionId: string): string => {\n // a missing execution id must never match anything, otherwise two flows\n // without one would share the stored identifier\n if (!executionId) {\n return '';\n }\n try {\n const raw = window.sessionStorage?.getItem(\n DESCOPE_LAST_SUBMITTED_LOGIN_ID_SESSION_STORAGE_KEY,\n );\n if (!raw) {\n return '';\n }\n const stored = JSON.parse(raw);\n return stored.executionId === executionId ? stored.loginId || '' : '';\n } catch (e) {\n return '';\n }\n};\n\nconst setLastSubmittedLoginId = (loginId: string, executionId: string) => {\n if (!loginId || !executionId) {\n return;\n }\n try {\n window.sessionStorage?.setItem(\n DESCOPE_LAST_SUBMITTED_LOGIN_ID_SESSION_STORAGE_KEY,\n JSON.stringify({ executionId, loginId }),\n );\n } catch (e) {\n // sessionStorage unavailable, losing reload persistence is acceptable\n }\n};\n\nconst clearUsernameAnchorIfExists = () => {\n document\n .querySelectorAll(`[${USERNAME_ANCHOR_ATTRIBUTE}=\"true\"]`)\n .forEach((ele) => ele.remove());\n};\n\nconst findPasswordComponent = (contentRootEle: Element) =>\n contentRootEle.querySelector('descope-new-password') ||\n contentRootEle.querySelector('descope-password');\n\n// an identifier is already on screen when there is an autocomplete=\"username\"\n// input, or a component collecting one of the login id fields (e.g.\n// descope-email-field renders its input inside a closed shadow root, so only\n// its name attribute is visible from here)\nconst hasLoginIdField = (roots: Element[]) => {\n const selector = [\n 'input[autocomplete=\"username\"]',\n ...LOGIN_ID_FIELDS.map((field) => `[name=\"${field}\"]`),\n ].join(', ');\n return roots.some((root) => root.querySelector(selector));\n};\n\nconst createUsernameAnchor = (loginId: string) => {\n const input = document.createElement('input');\n input.setAttribute('autocomplete', 'username');\n input.setAttribute('name', 'username');\n input.setAttribute('type', 'email');\n input.setAttribute('readonly', 'true');\n input.setAttribute('tabindex', '-1');\n input.setAttribute('aria-hidden', 'true');\n // never collect the anchor's value into the submitted form data\n input.setAttribute(DESCOPE_ATTRIBUTE_EXCLUDE_FIELD, 'true');\n // cleaned up by clearUsernameAnchorIfExists between screens\n input.setAttribute(USERNAME_ANCHOR_ATTRIBUTE, 'true');\n // some password managers read the markup value rather than the property\n input.setAttribute('value', loginId);\n input.value = loginId;\n // real input hidden via CSSOM: managers ignore type=\"hidden\", and strict\n // CSP style-src blocks style attributes\n Object.assign(input.style, {\n position: 'absolute',\n opacity: '0',\n pointerEvents: 'none',\n height: '0',\n border: '0',\n });\n return input;\n};\n\n// Anchors a hidden autocomplete=\"username\" input on password screens that\n// have no identifier input, so password managers can associate the credential\n// with a user (descope/etc#16712). Appended to the host light DOM — password\n// manager save heuristics (verified on WebKit) do not scan shadow trees\nconst injectUsernameAnchorIfNeeded = (\n hostEle: HTMLElement,\n contentRootEle: Element,\n user: ScreenStateUser | undefined,\n logger: { debug: (...args: string[]) => void },\n) => {\n const loginId = user?.email || user?.loginIds?.[0];\n\n if (!findPasswordComponent(contentRootEle)) {\n logger.debug('Username anchor: no password component on screen');\n return;\n }\n if (!loginId) {\n logger.debug('Username anchor: no user identifier available');\n return;\n }\n if (hasLoginIdField([hostEle, contentRootEle])) {\n logger.debug('Username anchor: screen already has an identifier field');\n return;\n }\n\n logger.debug('Username anchor: injecting hidden username input');\n hostEle.appendChild(createUsernameAnchor(loginId));\n};\n\n/**\n * Password manager integrations: keeps track of the current screen's user\n * identifier, anchors a hidden username input on password screens that have\n * no identifier input, and stores submitted credentials via the Credential\n * Management API.\n */\nexport const passwordManagerMixin = createSingletonMixin(\n <T extends CustomElementConstructor>(superclass: T) => {\n const BaseClass = compose(loggerMixin)(superclass);\n\n return class PasswordManagerMixinClass extends BaseClass {\n // the authenticated user of the current screen (if any), used as a\n // fallback identifier for password manager integrations on screens that\n // have no identifier input (e.g. step-up password change)\n #screenUser?: ScreenStateUser;\n\n get #host() {\n return this as unknown as PasswordManagerHost;\n }\n\n get #executionId() {\n return this.#host.flowState?.current?.executionId || '';\n }\n\n // called on every screen render. flow state does not always carry the\n // user (e.g. after magic link auth), so fall back to the login id\n // submitted earlier in this flow, then to the last authenticated user\n updateScreenUser(stateUser?: ScreenStateUser) {\n this.#screenUser = {\n email: stateUser?.email,\n loginIds: stateUser?.loginIds?.length\n ? stateUser.loginIds\n : [\n getLastSubmittedLoginId(this.#executionId) ||\n this.#host.sdk?.getLastUserLoginId?.(),\n ].filter(Boolean),\n };\n }\n\n updateUsernameAnchor() {\n // clear the previous screen's anchor, so each screen gets an anchor\n // only if it needs one\n clearUsernameAnchorIfExists();\n\n injectUsernameAnchorIfNeeded(\n this,\n this.#host.contentRootElement,\n this.#screenUser,\n this.logger,\n );\n }\n\n // called after a successful next(): on flows that render their first\n // screen before the flow starts, the execution id only exists on the\n // response, so prefer it over the current flow state\n captureLastSubmittedLoginId(formData = {}, responseExecutionId?: string) {\n const loginId = getFirstNonEmptyValue(formData, LOGIN_ID_FIELDS);\n if (loginId) {\n setLastSubmittedLoginId(\n loginId,\n responseExecutionId || this.#executionId,\n );\n }\n }\n\n // handle storing passwords in password managers\n storeCredentials(formData = {}) {\n const id =\n getFirstNonEmptyValue(formData, LOGIN_ID_FIELDS) ||\n this.#screenUser?.email ||\n this.#screenUser?.loginIds?.[0];\n const password = getFirstNonEmptyValue(formData, PASSWORD_FIELDS);\n\n // PasswordCredential not supported in Firefox\n if (id && password) {\n try {\n if (!globalThis.PasswordCredential) {\n return;\n }\n const cred = new globalThis.PasswordCredential({ id, password });\n\n navigator?.credentials?.store?.(cred)?.catch((e) => {\n this.logger.error('Could not store credentials', e?.message);\n });\n } catch (e) {\n this.logger.error('Could not store credentials', e.message);\n }\n }\n }\n };\n },\n);\n"],"names":["LOGIN_ID_FIELDS","PASSWORD_FIELDS","USERNAME_ANCHOR_ATTRIBUTE","getLastSubmittedLoginId","executionId","raw","_a","window","sessionStorage","getItem","DESCOPE_LAST_SUBMITTED_LOGIN_ID_SESSION_STORAGE_KEY","stored","JSON","parse","loginId","e","injectUsernameAnchorIfNeeded","hostEle","contentRootEle","user","logger","email","loginIds","querySelector","findPasswordComponent","roots","selector","map","field","join","some","root","hasLoginIdField","debug","appendChild","input","document","createElement","setAttribute","DESCOPE_ATTRIBUTE_EXCLUDE_FIELD","value","Object","assign","style","position","opacity","pointerEvents","height","border","createUsernameAnchor","passwordManagerMixin","createSingletonMixin","superclass","BaseClass","compose","loggerMixin","constructor","_PasswordManagerMixinClass_screenUser","set","this","updateScreenUser","stateUser","__classPrivateFieldSet","_b","length","__classPrivateFieldGet","_PasswordManagerMixinClass_instances","_PasswordManagerMixinClass_executionId_get","_d","_c","_PasswordManagerMixinClass_host_get","sdk","getLastUserLoginId","call","filter","Boolean","updateUsernameAnchor","querySelectorAll","forEach","ele","remove","contentRootElement","captureLastSubmittedLoginId","formData","responseExecutionId","getFirstNonEmptyValue","setItem","stringify","setLastSubmittedLoginId","storeCredentials","id","password","globalThis","PasswordCredential","cred","_g","_f","navigator","credentials","_e","store","catch","error","message","flowState","current"],"mappings":"ieAUA,MAAMA,EAAkB,CAAC,aAAc,QAAS,SAC1CC,EAAkB,CAAC,cAAe,YAElCC,EAA4B,uBAkB5BC,EAA2BC,UAG/B,IAAKA,EACH,MAAO,GAET,IACE,MAAMC,EAA2B,QAArBC,EAAAC,OAAOC,sBAAc,I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