@imtbl/auth 2.12.7-alpha.3 → 2.12.7-alpha.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser/index.js +26 -26
- package/dist/node/index.cjs +42 -43
- package/dist/node/index.js +29 -29
- package/dist/types/index.d.ts +2 -2
- package/dist/types/types.d.ts +1 -20
- package/package.json +3 -3
- package/src/Auth.test.ts +1 -83
- package/src/Auth.ts +0 -11
- package/src/index.ts +1 -8
- package/src/types.ts +1 -22
package/dist/node/index.cjs
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
3
|
var oidcClientTs = require('oidc-client-ts');
|
|
4
|
-
var
|
|
4
|
+
var Ge = require('localforage');
|
|
5
5
|
var metrics = require('@imtbl/metrics');
|
|
6
6
|
|
|
7
7
|
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
|
|
8
8
|
|
|
9
|
-
var
|
|
9
|
+
var Ge__default = /*#__PURE__*/_interopDefault(Ge);
|
|
10
10
|
|
|
11
|
-
var b=(p=>(p.AUTHENTICATION_ERROR="AUTHENTICATION_ERROR",p.INVALID_CONFIGURATION="INVALID_CONFIGURATION",p.WALLET_CONNECTION_ERROR="WALLET_CONNECTION_ERROR",p.NOT_LOGGED_IN_ERROR="NOT_LOGGED_IN_ERROR",p.SILENT_LOGIN_ERROR="SILENT_LOGIN_ERROR",p.REFRESH_TOKEN_ERROR="REFRESH_TOKEN_ERROR",p.USER_REGISTRATION_ERROR="USER_REGISTRATION_ERROR",p.USER_NOT_REGISTERED_ERROR="USER_NOT_REGISTERED_ERROR",p.LOGOUT_ERROR="LOGOUT_ERROR",p.TRANSFER_ERROR="TRANSFER_ERROR",p.CREATE_ORDER_ERROR="CREATE_ORDER_ERROR",p.CANCEL_ORDER_ERROR="CANCEL_ORDER_ERROR",p.EXCHANGE_TRANSFER_ERROR="EXCHANGE_TRANSFER_ERROR",p.CREATE_TRADE_ERROR="CREATE_TRADE_ERROR",p.OPERATION_NOT_SUPPORTED_ERROR="OPERATION_NOT_SUPPORTED_ERROR",p.LINK_WALLET_ALREADY_LINKED_ERROR="LINK_WALLET_ALREADY_LINKED_ERROR",p.LINK_WALLET_MAX_WALLETS_LINKED_ERROR="LINK_WALLET_MAX_WALLETS_LINKED_ERROR",p.LINK_WALLET_VALIDATION_ERROR="LINK_WALLET_VALIDATION_ERROR",p.LINK_WALLET_DUPLICATE_NONCE_ERROR="LINK_WALLET_DUPLICATE_NONCE_ERROR",p.LINK_WALLET_GENERIC_ERROR="LINK_WALLET_GENERIC_ERROR",p.SERVICE_UNAVAILABLE_ERROR="SERVICE_UNAVAILABLE_ERROR",p.TRANSACTION_REJECTED="TRANSACTION_REJECTED",p))(b||{});function
|
|
11
|
+
var b=(p=>(p.AUTHENTICATION_ERROR="AUTHENTICATION_ERROR",p.INVALID_CONFIGURATION="INVALID_CONFIGURATION",p.WALLET_CONNECTION_ERROR="WALLET_CONNECTION_ERROR",p.NOT_LOGGED_IN_ERROR="NOT_LOGGED_IN_ERROR",p.SILENT_LOGIN_ERROR="SILENT_LOGIN_ERROR",p.REFRESH_TOKEN_ERROR="REFRESH_TOKEN_ERROR",p.USER_REGISTRATION_ERROR="USER_REGISTRATION_ERROR",p.USER_NOT_REGISTERED_ERROR="USER_NOT_REGISTERED_ERROR",p.LOGOUT_ERROR="LOGOUT_ERROR",p.TRANSFER_ERROR="TRANSFER_ERROR",p.CREATE_ORDER_ERROR="CREATE_ORDER_ERROR",p.CANCEL_ORDER_ERROR="CANCEL_ORDER_ERROR",p.EXCHANGE_TRANSFER_ERROR="EXCHANGE_TRANSFER_ERROR",p.CREATE_TRADE_ERROR="CREATE_TRADE_ERROR",p.OPERATION_NOT_SUPPORTED_ERROR="OPERATION_NOT_SUPPORTED_ERROR",p.LINK_WALLET_ALREADY_LINKED_ERROR="LINK_WALLET_ALREADY_LINKED_ERROR",p.LINK_WALLET_MAX_WALLETS_LINKED_ERROR="LINK_WALLET_MAX_WALLETS_LINKED_ERROR",p.LINK_WALLET_VALIDATION_ERROR="LINK_WALLET_VALIDATION_ERROR",p.LINK_WALLET_DUPLICATE_NONCE_ERROR="LINK_WALLET_DUPLICATE_NONCE_ERROR",p.LINK_WALLET_GENERIC_ERROR="LINK_WALLET_GENERIC_ERROR",p.SERVICE_UNAVAILABLE_ERROR="SERVICE_UNAVAILABLE_ERROR",p.TRANSACTION_REJECTED="TRANSACTION_REJECTED",p))(b||{});function H(n){return typeof n=="object"&&n!==null&&"code"in n&&"message"in n}var ve=n=>{if(H(n))return n;if(typeof n=="object"&&n!==null&&"response"in n){let{response:e}=n;if(e?.data&&H(e.data))return e.data}},Te=(n,e)=>{let t=e,r=t?.response?.status,o=t?.config?.url,i=t?.config?.baseURL,s=typeof o=="string"&&typeof i=="string"&&!/^https?:\/\//i.test(o)?`${i}${o}`:o;return r==null&&s==null||n.includes("[httpStatus=")?n:`${n} [httpStatus=${r??"unknown"} url=${s??"unknown"}]`},f=class extends Error{type;constructor(e,t){super(e),this.type=t;}},E=async(n,e)=>{try{return await n()}catch(t){let r;if(t instanceof f&&t.type==="SERVICE_UNAVAILABLE_ERROR")throw new f(t.message,t.type);let o=ve(t);throw o?r=o.message:r=t.message,e==="USER_REGISTRATION_ERROR"&&(r=Te(r,t)),new f(r,e)}};var Oe=(n,e,t)=>{let r=e.map(o=>!n[o]&&o).filter(o=>o).join(", ");if(r!==""){let o=`${r} cannot be null`;throw new f(o,"INVALID_CONFIGURATION")}},O=class{authenticationDomain;passportDomain;oidcConfiguration;crossSdkBridgeEnabled;popupOverlayOptions;constructor({authenticationDomain:e,passportDomain:t,crossSdkBridgeEnabled:r,popupOverlayOptions:o,...i}){Oe(i,["clientId","redirectUri"]),this.oidcConfiguration=i,this.crossSdkBridgeEnabled=r||!1,this.popupOverlayOptions=o,this.authenticationDomain=e||"https://auth.immutable.com",this.passportDomain=t||"https://passport.immutable.com";}};var J=(e=>(e.ZKEVM="zkEvm",e))(J||{}),F=n=>!!n.zkEvm,Q=(r=>(r.OptedIn="opted_in",r.Unsubscribed="unsubscribed",r.Subscribed="subscribed",r))(Q||{}),V=(o=>(o.LOGGED_OUT="loggedOut",o.LOGGED_IN="loggedIn",o.TOKEN_REFRESHED="tokenRefreshed",o.USER_REMOVED="userRemoved",o))(V||{});var q="im_passport_embedded_login_prompt";var C="passport-overlay",y="passport-overlay-contents",A=`${C}-close`,U=`${C}-try-again`,X=`
|
|
12
12
|
<svg
|
|
13
13
|
viewBox="0 0 20 20"
|
|
14
14
|
fill="none"
|
|
@@ -20,7 +20,7 @@ var b=(p=>(p.AUTHENTICATION_ERROR="AUTHENTICATION_ERROR",p.INVALID_CONFIGURATION
|
|
|
20
20
|
fill="#F3F3F3"
|
|
21
21
|
/>
|
|
22
22
|
</svg>
|
|
23
|
-
`,
|
|
23
|
+
`,j=`
|
|
24
24
|
<svg
|
|
25
25
|
viewBox="0 0 17 16"
|
|
26
26
|
fill="none"
|
|
@@ -34,7 +34,7 @@ var b=(p=>(p.AUTHENTICATION_ERROR="AUTHENTICATION_ERROR",p.INVALID_CONFIGURATION
|
|
|
34
34
|
fill="#E01A3D"
|
|
35
35
|
/>
|
|
36
36
|
</svg>
|
|
37
|
-
`,
|
|
37
|
+
`,G=`
|
|
38
38
|
<svg
|
|
39
39
|
style="
|
|
40
40
|
max-width: 123px !important;
|
|
@@ -217,9 +217,9 @@ var b=(p=>(p.AUTHENTICATION_ERROR="AUTHENTICATION_ERROR",p.INVALID_CONFIGURATION
|
|
|
217
217
|
</clipPath>
|
|
218
218
|
</defs>
|
|
219
219
|
</svg>
|
|
220
|
-
`;var
|
|
220
|
+
`;var Le=()=>`
|
|
221
221
|
<button
|
|
222
|
-
id="${
|
|
222
|
+
id="${A}"
|
|
223
223
|
style="
|
|
224
224
|
background: #f3f3f326 !important;
|
|
225
225
|
border: none !important;
|
|
@@ -235,11 +235,11 @@ var b=(p=>(p.AUTHENTICATION_ERROR="AUTHENTICATION_ERROR",p.INVALID_CONFIGURATION
|
|
|
235
235
|
justify-content: center !important;
|
|
236
236
|
"
|
|
237
237
|
>
|
|
238
|
-
${
|
|
238
|
+
${X}
|
|
239
239
|
</button>
|
|
240
|
-
`,
|
|
240
|
+
`,ee=()=>`
|
|
241
241
|
<button
|
|
242
|
-
id="${
|
|
242
|
+
id="${U}"
|
|
243
243
|
style="
|
|
244
244
|
margin-top: 27px !important;
|
|
245
245
|
color: #f3f3f3 !important;
|
|
@@ -254,8 +254,8 @@ var b=(p=>(p.AUTHENTICATION_ERROR="AUTHENTICATION_ERROR",p.INVALID_CONFIGURATION
|
|
|
254
254
|
>
|
|
255
255
|
Try again
|
|
256
256
|
</button>
|
|
257
|
-
`,
|
|
258
|
-
${
|
|
257
|
+
`,we=()=>`
|
|
258
|
+
${G}
|
|
259
259
|
<div
|
|
260
260
|
style="
|
|
261
261
|
color: #e01a3d !important;
|
|
@@ -265,7 +265,7 @@ var b=(p=>(p.AUTHENTICATION_ERROR="AUTHENTICATION_ERROR",p.INVALID_CONFIGURATION
|
|
|
265
265
|
margin-bottom: 10px !important;
|
|
266
266
|
"
|
|
267
267
|
>
|
|
268
|
-
${
|
|
268
|
+
${j}
|
|
269
269
|
Pop-up blocked
|
|
270
270
|
</div>
|
|
271
271
|
<p style="
|
|
@@ -278,9 +278,9 @@ var b=(p=>(p.AUTHENTICATION_ERROR="AUTHENTICATION_ERROR",p.INVALID_CONFIGURATION
|
|
|
278
278
|
If the problem continues, adjust your<br />
|
|
279
279
|
browser settings.
|
|
280
280
|
</p>
|
|
281
|
-
${
|
|
282
|
-
`,
|
|
283
|
-
${
|
|
281
|
+
${ee()}
|
|
282
|
+
`,Pe=()=>`
|
|
283
|
+
${G}
|
|
284
284
|
<p style="
|
|
285
285
|
color: #b6b6b6 !important;
|
|
286
286
|
text-align: center !important;
|
|
@@ -289,8 +289,8 @@ var b=(p=>(p.AUTHENTICATION_ERROR="AUTHENTICATION_ERROR",p.INVALID_CONFIGURATION
|
|
|
289
289
|
>
|
|
290
290
|
Secure pop-up not showing?<br />We'll help you re-launch
|
|
291
291
|
</p>
|
|
292
|
-
${
|
|
293
|
-
`,
|
|
292
|
+
${ee()}
|
|
293
|
+
`,te=n=>`
|
|
294
294
|
<div
|
|
295
295
|
id="${C}"
|
|
296
296
|
style="
|
|
@@ -315,9 +315,9 @@ var b=(p=>(p.AUTHENTICATION_ERROR="AUTHENTICATION_ERROR",p.INVALID_CONFIGURATION
|
|
|
315
315
|
z-index: 2147483647 !important;
|
|
316
316
|
"
|
|
317
317
|
>
|
|
318
|
-
${
|
|
318
|
+
${Le()}
|
|
319
319
|
<div
|
|
320
|
-
id="${
|
|
320
|
+
id="${y}"
|
|
321
321
|
style="
|
|
322
322
|
display: flex !important;
|
|
323
323
|
flex-direction: column !important;
|
|
@@ -328,7 +328,7 @@ var b=(p=>(p.AUTHENTICATION_ERROR="AUTHENTICATION_ERROR",p.INVALID_CONFIGURATION
|
|
|
328
328
|
${n??""}
|
|
329
329
|
</div>
|
|
330
330
|
</div>
|
|
331
|
-
`,
|
|
331
|
+
`,re=()=>`
|
|
332
332
|
<div
|
|
333
333
|
id="${C}"
|
|
334
334
|
style="
|
|
@@ -348,7 +348,7 @@ var b=(p=>(p.AUTHENTICATION_ERROR="AUTHENTICATION_ERROR",p.INVALID_CONFIGURATION
|
|
|
348
348
|
"
|
|
349
349
|
>
|
|
350
350
|
<div
|
|
351
|
-
id="${
|
|
351
|
+
id="${y}"
|
|
352
352
|
style="
|
|
353
353
|
display: flex;
|
|
354
354
|
flex-direction: column;
|
|
@@ -357,7 +357,7 @@ var b=(p=>(p.AUTHENTICATION_ERROR="AUTHENTICATION_ERROR",p.INVALID_CONFIGURATION
|
|
|
357
357
|
"
|
|
358
358
|
/>
|
|
359
359
|
</div>
|
|
360
|
-
`;function S({id:n,href:e,rel:t,crossOrigin:r}){let o=`${C}-${n}`;if(!document.getElementById(o)){let i=document.createElement("link");i.id=o,i.href=e,t&&(i.rel=t),r&&(i.crossOrigin=r),document.head.appendChild(i);}}var
|
|
360
|
+
`;function S({id:n,href:e,rel:t,crossOrigin:r}){let o=`${C}-${n}`;if(!document.getElementById(o)){let i=document.createElement("link");i.id=o,i.href=e,t&&(i.rel=t),r&&(i.crossOrigin=r),document.head.appendChild(i);}}var ne=()=>te(we()),oe=()=>te(Pe());var h=class{static overlay;static onCloseListener;static closeButton;static remove(){this.onCloseListener&&this.closeButton?.removeEventListener?.("click",this.onCloseListener),this.overlay?.remove(),this.closeButton=void 0,this.onCloseListener=void 0,this.overlay=void 0;}static appendOverlay(e,t){if(!this.overlay){let r=document.createElement("div");r.innerHTML=re(),document.body.insertAdjacentElement("beforeend",r);let o=document.querySelector(`#${y}`);o&&o.appendChild(e),r.addEventListener("click",t),this.overlay=r;}}};var be=660,Ae=440,Ue="16px",ie="passport-embedded-login-keyframes",se="passport-embedded-login-iframe",L=class n{config;constructor(e){this.config=e;}getHref=()=>`${this.config.authenticationDomain}/im-embedded-login-prompt?client_id=${this.config.oidcConfiguration.clientId}&rid=${metrics.getDetail(metrics.Detail.RUNTIME_ID)}`;static appendIFrameStylesIfNeeded=()=>{if(document.getElementById(ie))return;let e=document.createElement("style");e.id=ie,e.textContent=`
|
|
361
361
|
@keyframes passportEmbeddedLoginPromptPopBounceIn {
|
|
362
362
|
0% {
|
|
363
363
|
opacity: 0.5;
|
|
@@ -376,7 +376,7 @@ var b=(p=>(p.AUTHENTICATION_ERROR="AUTHENTICATION_ERROR",p.INVALID_CONFIGURATION
|
|
|
376
376
|
}
|
|
377
377
|
|
|
378
378
|
@media (max-height: 400px) {
|
|
379
|
-
#${
|
|
379
|
+
#${se} {
|
|
380
380
|
width: 100% !important;
|
|
381
381
|
max-width: none !important;
|
|
382
382
|
}
|
|
@@ -390,7 +390,7 @@ var b=(p=>(p.AUTHENTICATION_ERROR="AUTHENTICATION_ERROR",p.INVALID_CONFIGURATION
|
|
|
390
390
|
opacity: 1;
|
|
391
391
|
}
|
|
392
392
|
}
|
|
393
|
-
`,document.head.appendChild(e);};getEmbeddedLoginIFrame=()=>{let e=document.createElement("iframe");return e.id=ae,e.src=this.getHref(),e.style.height="100vh",e.style.width="100vw",e.style.maxHeight=`${Ue}px`,e.style.maxWidth=`${xe}px`,e.style.borderRadius=Se,e.style.opacity="0",e.style.transform="scale(0.6)",e.style.animation="passportEmbeddedLoginPromptPopBounceIn 1s ease forwards",n.appendIFrameStylesIfNeeded(),e};displayEmbeddedLoginPrompt(){return new Promise((e,t)=>{let r=this.getEmbeddedLoginIFrame(),o=({data:i,origin:s})=>{if(!(s!==this.config.authenticationDomain||i.eventType!==X))switch(i.messageType){case"login_method_selected":{let a=i.payload;window.removeEventListener("message",o),h.remove(),e(a);break}case"login_prompt_error":{window.removeEventListener("message",o),h.remove(),t(new Error("Error during embedded login prompt",{cause:i.payload}));break}case"login_prompt_closed":{window.removeEventListener("message",o),h.remove(),t(new Error("Popup closed by user"));break}default:window.removeEventListener("message",o),h.remove(),t(new Error(`Unsupported message type: ${i.messageType}`));break}};window.addEventListener("message",o),h.appendOverlay(r,()=>{window.removeEventListener("message",o),h.remove(),t(new Error("Popup closed by user"));});})}};var R=class{listeners=new Map;emit(e,...t){let r=this.listeners.get(e);!r||r.size===0||[...r].forEach(o=>{o(...t);});}on(e,t){let r=this.listeners.get(e)??new Set;r.add(t),this.listeners.set(e,r);}removeListener(e,t){let r=this.listeners.get(e);r&&(r.delete(t),r.size===0&&this.listeners.delete(e));}};var u=async(n,e,t=!0,r=!0)=>{let o=metrics.trackFlow("passport",e,t);try{return await n(o)}catch(i){throw i instanceof Error?metrics.trackError("passport",e,i,{flowId:o.details.flowId}):o.addEvent("errored"),i}finally{r&&o.addEvent("End");}};var Ne=()=>typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{},He=n=>{let e=n.replace(/-/g,"+").replace(/_/g,"/"),t=e.length%4===0?"":"=".repeat(4-e.length%4);return e+t},Fe=n=>{let e=Ne();if(typeof e.atob!="function")return null;let t=e.atob(n),r=new Uint8Array(t.length);for(let i=0;i<t.length;i+=1)r[i]=t.charCodeAt(i);if(typeof e.TextDecoder=="function")return new e.TextDecoder("utf-8").decode(r);let o="";for(let i=0;i<r.length;i+=1)o+=String.fromCharCode(r[i]);return o},Ve=n=>{if(typeof Buffer<"u")return Buffer.from(n,"base64").toString("utf-8");let e=Fe(n);if(e===null)throw new Error("Base64 decoding is not supported in this environment");return e},m=n=>{if(typeof n!="string")throw new Error("JWT must be a string");let e=n.split(".");if(e.length<2)throw new Error("Invalid JWT: payload segment is missing");let t=e[1],r=Ve(He(t));try{return JSON.parse(r)}catch{throw new Error("Invalid JWT payload: unable to parse JSON")}};var de="pkce_state",le="pkce_verifier",Ge=3600,P=class{isTokenValid(e){try{let r=m(e).exp??0,o=Date.now()/1e3+Ge;return r>o}catch{return !1}}savePKCEData(e){localStorage.setItem(de,e.state),localStorage.setItem(le,e.verifier);}getPKCEData(){let e=localStorage.getItem(de),t=localStorage.getItem(le);return e&&t?{state:e,verifier:t}:null}};var Be=(...n)=>{if(typeof process>"u")return;process?.env?.JEST_WORKER_ID===void 0&&console.warn(...n);},v={warn:Be};function ce(n){try{let e=m(n),t=Math.floor(Date.now()/1e3);return e.exp?e.exp<=t+30:!0}catch{return !0}}function pe(n){let{id_token:e,access_token:t}=n;return !t||!e?!0:ce(t)||ce(e)}var w=class{disableGenericPopupOverlay;disableBlockedPopupOverlay;overlay;isBlockedOverlay;tryAgainListener;onCloseListener;constructor(e,t=!1){this.disableBlockedPopupOverlay=e.disableBlockedPopupOverlay||!1,this.disableGenericPopupOverlay=e.disableGenericPopupOverlay||!1,this.isBlockedOverlay=t;}append(e,t){this.shouldAppendOverlay()&&(this.appendOverlay(),this.updateTryAgainButton(e),this.updateCloseButton(t));}update(e){this.updateTryAgainButton(e);}remove(){this.overlay&&this.overlay.remove();}shouldAppendOverlay(){return !(this.disableGenericPopupOverlay&&this.disableBlockedPopupOverlay||this.disableGenericPopupOverlay&&!this.isBlockedOverlay||this.disableBlockedPopupOverlay&&this.isBlockedOverlay)}appendOverlay(){if(!this.overlay){S({id:"link-googleapis",href:"https://fonts.googleapis.com"}),S({id:"link-gstatic",href:"https://fonts.gstatic.com",crossOrigin:"anonymous"}),S({id:"link-roboto",href:"https://fonts.googleapis.com/css2?family=Roboto:ital,wght@0,400;0,500;0,700;1,400;1,500;1,700&display=swap",rel:"stylesheet"});let t=document.createElement("div");t.innerHTML=this.isBlockedOverlay?oe():ie(),document.body.insertAdjacentElement("beforeend",t),this.overlay=t;}}updateTryAgainButton(e){let t=document.getElementById(x);t&&(this.tryAgainListener&&t.removeEventListener("click",this.tryAgainListener),this.tryAgainListener=e,t.addEventListener("click",e));}updateCloseButton(e){let t=document.getElementById(U);t&&(this.onCloseListener&&t.removeEventListener("click",this.onCloseListener),this.onCloseListener=e,t.addEventListener("click",e));}};var D=class{storage;constructor(e,t){this.storage=Ke__default.default.createInstance({name:e,driver:t});}get length(){return this.storage.length()}clear(){return this.storage.clear()}getItem(e){return this.storage.getItem(e)}key(e){return this.storage.key(e)}async removeItem(e){await this.storage.removeItem(e);}async setItem(e,t){await this.storage.setItem(e,t);}};var $e="/v2/logout",Ze="/im-logged-out",We="https://auth.immutable.com";function ze(n){return n.replace(/^(?:https?:\/\/)?(.*)/,"https://$1")}function M(n){let e=ze(n.authenticationDomain||We),t=n.crossSdkBridgeEnabled?Ze:$e,r=new URL(t,e);return r.searchParams.set("client_id",n.clientId),n.logoutRedirectUri&&r.searchParams.set("returnTo",n.logoutRedirectUri),r.toString()}var st={"Content-Type":"application/x-www-form-urlencoded"},at=n=>{if(n)try{return JSON.parse(n)}catch{return}},dt=(n,e,t)=>{if(n&&typeof n=="object"){let r=n,o=r.error_description??r.message??r.error;if(typeof o=="string"&&o.trim().length>0)return o}return e.trim().length>0?e:`Token request failed with status ${t}`},ue=(n,e)=>({ethAddress:n,userAdminAddress:e}),lt="/authorize",ct=n=>{let{authenticationDomain:e,oidcConfiguration:t}=n,r;n.crossSdkBridgeEnabled?r=new D("ImmutableSDKPassport",Ke__default.default.INDEXEDDB):typeof window<"u"?r=window.localStorage:r=new oidcClientTs.InMemoryWebStorage;let o=new oidcClientTs.WebStorageStateStore({store:r}),i=M({clientId:t.clientId,authenticationDomain:e,logoutRedirectUri:t.logoutRedirectUri,crossSdkBridgeEnabled:n.crossSdkBridgeEnabled});return {authority:e,redirect_uri:t.redirectUri,popup_redirect_uri:t.popupRedirectUri||t.redirectUri,client_id:t.clientId,metadata:{authorization_endpoint:`${e}/authorize`,token_endpoint:`${e}/oauth/token`,userinfo_endpoint:`${e}/userinfo`,end_session_endpoint:i,revocation_endpoint:`${e}/oauth/revoke`},automaticSilentRenew:!1,scope:t.scope,userStore:o,revokeTokenTypes:["refresh_token"],extraQueryParams:{...t.audience?{audience:t.audience}:{}}}};function K(n){return btoa(String.fromCharCode(...new Uint8Array(n))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}async function pt(n){let t=new TextEncoder().encode(n);return window.crypto.subtle.digest("SHA-256",t)}var $=class n{config;userManager;deviceCredentialsManager;embeddedLoginPrompt;logoutMode;refreshingPromise=null;eventEmitter;constructor(e){this.config=new O(e),this.embeddedLoginPrompt=new L(this.config),this.userManager=new oidcClientTs.UserManager(ct(this.config)),this.deviceCredentialsManager=new P,this.logoutMode=this.config.oidcConfiguration.logoutMode||"redirect",this.eventEmitter=new R,metrics.track("passport","initialise");}async login(e){return u(async()=>{let{useCachedSession:t=!1,useSilentLogin:r}=e||{},o=null;try{o=await this.getUserInternal();}catch(i){if(i instanceof Error&&!i.message.includes("Unknown or invalid refresh token")&&metrics.trackError("passport","login",i),t)throw i;v.warn("Failed to retrieve a cached user session",i);}if(!o&&r)o=await this.forceUserRefreshInternal();else if(!o&&!t){if(e?.useRedirectFlow)return await this.loginWithRedirectInternal(e?.directLoginOptions),null;o=await this.loginWithPopup(e?.directLoginOptions);}return o&&this.handleSuccessfulLogin(o),o},"login")}async loginWithRedirect(e){await this.loginWithRedirectInternal(e);}async loginCallback(){return u(async()=>{let e=await this.loginCallbackInternal();return e&&this.handleSuccessfulLogin(e),e},"loginCallback")}async logout(){await u(async()=>{await this.logoutInternal(),this.eventEmitter.emit("loggedOut");},"logout");}async getUser(){return this.getUserInternal()}async getUserOrLogin(){let e=null;try{e=await this.getUserInternal();}catch(r){v.warn("Failed to retrieve a cached user session",r);}if(e)return e;let t=await this.loginWithPopup();return this.handleSuccessfulLogin(t),t}async getUserZkEvm(){return this.getUserZkEvmInternal()}async getIdToken(){return u(async()=>(await this.getUserInternal())?.idToken,"getIdToken",!1)}async getAccessToken(){return u(async()=>(await this.getUserInternal())?.accessToken,"getAccessToken",!1,!1)}async isLoggedIn(){return await this.getUser()!==null}async forceUserRefresh(){return this.forceUserRefreshInternal()}forceUserRefreshInBackground(){this.forceUserRefreshInBackgroundInternal();}async loginWithPKCEFlow(e,t){return u(async()=>this.getPKCEAuthorizationUrl(e,t),"loginWithPKCEFlow")}async loginWithPKCEFlowCallback(e,t){return u(async()=>{let r=await this.loginWithPKCEFlowCallbackInternal(e,t);return this.handleSuccessfulLogin(r),r},"loginWithPKCEFlowCallback")}async storeTokens(e){return u(async()=>{let t=await this.storeTokensInternal(e);return this.handleSuccessfulLogin(t),t},"storeTokens")}async getLogoutUrl(){return u(async()=>(await this.userManager.removeUser(),this.eventEmitter.emit("loggedOut"),await this.getLogoutUrlInternal()||void 0),"getLogoutUrl")}async logoutSilentCallback(e){return u(()=>this.userManager.signoutSilentCallback(e),"logoutSilentCallback")}getConfig(){return this.config}async getClientId(){return this.config.oidcConfiguration.clientId}handleSuccessfulLogin(e){this.eventEmitter.emit("loggedIn",e),metrics.identify({passportId:e.profile.sub});}buildExtraQueryParams(e,t){let r={...this.userManager.settings?.extraQueryParams??{},rid:metrics.getDetail(metrics.Detail.RUNTIME_ID)||""};if(e){if(e.directLoginMethod==="email"){let o=e.email;o&&(r.direct=e.directLoginMethod,r.email=o);}else r.direct=e.directLoginMethod;e.marketingConsentStatus&&(r.marketingConsent=e.marketingConsentStatus);}return t&&(r.im_passport_trace_id=t),r}async loginWithRedirectInternal(e){await this.userManager.clearStaleState(),await E(async()=>{let t=this.buildExtraQueryParams(e);await this.userManager.signinRedirect({extraQueryParams:t});},"AUTHENTICATION_ERROR");}async loginWithPopup(e){return E(async()=>{let t,r;if(e)t=e;else if(!this.config.popupOverlayOptions?.disableHeadlessLoginPromptOverlay){let{imPassportTraceId:s,...a}=await this.embeddedLoginPrompt.displayEmbeddedLoginPrompt();t=a,r=s;}let o=window.crypto.randomUUID(),i=async()=>{let s=this.buildExtraQueryParams(t,r);return this.userManager.signinPopup({extraQueryParams:s,popupWindowFeatures:{width:410,height:450},popupWindowTarget:o,popupAbortOnClose:!0})};return new Promise((s,a)=>{i().then(d=>s(n.mapOidcUserToDomainModel(d))).catch(d=>{if(!(d instanceof Error)||d.message!=="Attempted to navigate on a disposed window"){a(d);return}let c=!1,l=new w(this.config.popupOverlayOptions||{},!0);l.append(async()=>{try{if(c)window.open("",o);else {c=!0;let g=await i();l.remove(),s(n.mapOidcUserToDomainModel(g));}}catch(g){l.remove(),a(g);}},()=>{l.remove(),a(new Error("Popup closed by user"));});});})},"AUTHENTICATION_ERROR")}static mapOidcUserToDomainModel=e=>{let t,r;if(e.id_token){let s=m(e.id_token);t=s?.passport,s?.username&&(r=s?.username);}let o={expired:e.expired,idToken:e.id_token,accessToken:e.access_token,refreshToken:e.refresh_token,profile:{sub:e.profile.sub,email:e.profile.email,nickname:e.profile.nickname,username:r}};t?.zkevm_eth_address&&t?.zkevm_user_admin_address&&(o.zkEvm=ue(t.zkevm_eth_address,t.zkevm_user_admin_address));let i=Object.values(A).filter(s=>s!=="zkevm");for(let s of i){let a=t?.[s];a?.eth_address&&a?.user_admin_address&&(o[s]=ue(a.eth_address,a.user_admin_address));}return o};static mapDeviceTokenResponseToOidcUser=e=>{let t=m(e.id_token);return new oidcClientTs.User({id_token:e.id_token,access_token:e.access_token,refresh_token:e.refresh_token,token_type:e.token_type,profile:{sub:t.sub,iss:t.iss,aud:t.aud,exp:t.exp,iat:t.iat,email:t.email,nickname:t.nickname,passport:t.passport,...t.username?{username:t.username}:{}}})};async loginCallbackInternal(){return E(async()=>{let e=await this.userManager.signinCallback();if(e)return n.mapOidcUserToDomainModel(e)},"AUTHENTICATION_ERROR")}async getPKCEAuthorizationUrl(e,t){let r=K(window.crypto.getRandomValues(new Uint8Array(32))),o=K(await pt(r)),i=K(window.crypto.getRandomValues(new Uint8Array(32))),{redirectUri:s,scope:a,audience:d,clientId:c}=this.config.oidcConfiguration;this.deviceCredentialsManager.savePKCEData({state:i,verifier:r});let l=new URL(lt,this.config.authenticationDomain);if(l.searchParams.set("response_type","code"),l.searchParams.set("code_challenge",o),l.searchParams.set("code_challenge_method","S256"),l.searchParams.set("client_id",c),l.searchParams.set("redirect_uri",s),l.searchParams.set("state",i),a&&l.searchParams.set("scope",a),d&&l.searchParams.set("audience",d),e){if(e.directLoginMethod==="email"){let g=e.email;g&&(l.searchParams.set("direct",e.directLoginMethod),l.searchParams.set("email",g));}else l.searchParams.set("direct",e.directLoginMethod);e.marketingConsentStatus&&l.searchParams.set("marketingConsent",e.marketingConsentStatus);}return t&&l.searchParams.set("im_passport_trace_id",t),l.toString()}async loginWithPKCEFlowCallbackInternal(e,t){return E(async()=>{let r=this.deviceCredentialsManager.getPKCEData();if(!r)throw new Error("No code verifier or state for PKCE");if(t!==r.state)throw new Error("Provided state does not match stored state");let o=await this.getPKCEToken(e,r.verifier),i=n.mapDeviceTokenResponseToOidcUser(o),s=n.mapOidcUserToDomainModel(i);return await this.userManager.storeUser(i),s},"AUTHENTICATION_ERROR")}async getPKCEToken(e,t){let r=await fetch(`${this.config.authenticationDomain}/oauth/token`,{method:"POST",headers:st,body:new URLSearchParams({client_id:this.config.oidcConfiguration.clientId,grant_type:"authorization_code",code_verifier:t,code:e,redirect_uri:this.config.oidcConfiguration.redirectUri})}),o=await r.text(),i=at(o);if(!r.ok)throw new Error(dt(i,o,r.status));if(!i||typeof i!="object")throw new Error("Token endpoint returned an invalid response");return i}async storeTokensInternal(e){return E(async()=>{let t=n.mapDeviceTokenResponseToOidcUser(e),r=n.mapOidcUserToDomainModel(t);return await this.userManager.storeUser(t),r},"AUTHENTICATION_ERROR")}async logoutInternal(){await E(async()=>{await this.userManager.revokeTokens(["refresh_token"]),this.logoutMode==="silent"?await this.userManager.signoutSilent():await this.userManager.signoutRedirect();},"LOGOUT_ERROR");}async getLogoutUrlInternal(){let e=this.userManager.settings?.metadata?.end_session_endpoint;return e||(v.warn("Failed to get logout URL"),null)}forceUserRefreshInBackgroundInternal(){this.refreshTokenAndUpdatePromise().catch(e=>{v.warn("Failed to refresh user token",e);});}async forceUserRefreshInternal(){return this.refreshTokenAndUpdatePromise().catch(e=>(v.warn("Failed to refresh user token",e),null))}async refreshTokenAndUpdatePromise(){return this.refreshingPromise?this.refreshingPromise:(this.refreshingPromise=new Promise((e,t)=>{(async()=>{try{let r=await this.userManager.signinSilent();if(r){let o=n.mapOidcUserToDomainModel(r);this.eventEmitter.emit("tokenRefreshed",o),e(o);return}e(null);}catch(r){let o="AUTHENTICATION_ERROR",i="Failed to refresh token",s=!0;if(r instanceof oidcClientTs.ErrorTimeout?(o="SILENT_LOGIN_ERROR",i=`${i}: ${r.message}`,s=!1):r instanceof oidcClientTs.ErrorResponse?(o="NOT_LOGGED_IN_ERROR",i=`${i}: ${r.message||r.error_description}`):r instanceof Error?i=`${i}: ${r.message}`:typeof r=="string"&&(i=`${i}: ${r}`),s){this.eventEmitter.emit("userRemoved",{reason:"refresh_failed",error:i});try{await this.userManager.removeUser();}catch(a){a instanceof Error&&(i=`${i}: Failed to remove user: ${a.message}`);}}t(new f(i,o));}finally{this.refreshingPromise=null;}})();}),this.refreshingPromise)}async getUserInternal(e=t=>!0){if(this.refreshingPromise){let r=await this.refreshingPromise;return r&&e(r)?r:null}let t=await this.userManager.getUser();if(!t)return null;if(!pe(t)){let r=n.mapOidcUserToDomainModel(t);if(r&&e(r))return r}if(t.refresh_token){let r=await this.refreshTokenAndUpdatePromise();if(r&&e(r))return r}return null}async getUserZkEvmInternal(){let e=await this.getUserInternal(V);if(!e)throw new Error("Failed to obtain a User with the required ZkEvm attributes");return e}};var gt="im_passport_embedded_login_prompt",fe="passport-embedded-login-iframe",he="passport-overlay";var ft="https://auth.immutable.com",ht="platform_api",Et="openid profile email offline_access transact",_t="/authorize",yt="/oauth/token",Z="imtbl_pkce_data";function Ee(n){return btoa(String.fromCharCode(...new Uint8Array(n))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}async function Ct(n){let t=new TextEncoder().encode(n);return window.crypto.subtle.digest("SHA-256",t)}function me(){return Ee(window.crypto.getRandomValues(new Uint8Array(32)))}function W(n){return n.authenticationDomain||ft}function Rt(n){try{let e=m(n);if(e.exp)return e.exp*1e3}catch{}return Date.now()+3600*1e3}function vt(n){let{access_token:e,refresh_token:t,id_token:r}=n,o={sub:""},i;if(r)try{let{sub:s,email:a,nickname:d,passport:c}=m(r);o={sub:s,email:a,nickname:d},c?.zkevm_eth_address&&c?.zkevm_user_admin_address&&(i={ethAddress:c.zkevm_eth_address,userAdminAddress:c.zkevm_user_admin_address});}catch{}return {accessToken:e,refreshToken:t,idToken:r,accessTokenExpires:Rt(e),profile:o,zkEvm:i}}function Tt(n){typeof window<"u"&&window.sessionStorage&&window.sessionStorage.setItem(Z,JSON.stringify(n));}function Ot(){if(typeof window<"u"&&window.sessionStorage){let n=window.sessionStorage.getItem(Z);if(n)try{return JSON.parse(n)}catch{return null}}return null}function ge(){typeof window<"u"&&window.sessionStorage&&window.sessionStorage.removeItem(Z);}function Lt(){let n="passport-embedded-login-keyframes";if(document.getElementById(n))return;let e=document.createElement("style");e.id=n,e.textContent=`
|
|
393
|
+
`,document.head.appendChild(e);};getEmbeddedLoginIFrame=()=>{let e=document.createElement("iframe");return e.id=se,e.src=this.getHref(),e.style.height="100vh",e.style.width="100vw",e.style.maxHeight=`${be}px`,e.style.maxWidth=`${Ae}px`,e.style.borderRadius=Ue,e.style.opacity="0",e.style.transform="scale(0.6)",e.style.animation="passportEmbeddedLoginPromptPopBounceIn 1s ease forwards",n.appendIFrameStylesIfNeeded(),e};displayEmbeddedLoginPrompt(){return new Promise((e,t)=>{let r=this.getEmbeddedLoginIFrame(),o=({data:i,origin:s})=>{if(!(s!==this.config.authenticationDomain||i.eventType!==q))switch(i.messageType){case"login_method_selected":{let a=i.payload;window.removeEventListener("message",o),h.remove(),e(a);break}case"login_prompt_error":{window.removeEventListener("message",o),h.remove(),t(new Error("Error during embedded login prompt",{cause:i.payload}));break}case"login_prompt_closed":{window.removeEventListener("message",o),h.remove(),t(new Error("Popup closed by user"));break}default:window.removeEventListener("message",o),h.remove(),t(new Error(`Unsupported message type: ${i.messageType}`));break}};window.addEventListener("message",o),h.appendOverlay(r,()=>{window.removeEventListener("message",o),h.remove(),t(new Error("Popup closed by user"));});})}};var R=class{listeners=new Map;emit(e,...t){let r=this.listeners.get(e);!r||r.size===0||[...r].forEach(o=>{o(...t);});}on(e,t){let r=this.listeners.get(e)??new Set;r.add(t),this.listeners.set(e,r);}removeListener(e,t){let r=this.listeners.get(e);r&&(r.delete(t),r.size===0&&this.listeners.delete(e));}};var u=async(n,e,t=!0,r=!0)=>{let o=metrics.trackFlow("passport",e,t);try{return await n(o)}catch(i){throw i instanceof Error?metrics.trackError("passport",e,i,{flowId:o.details.flowId}):o.addEvent("errored"),i}finally{r&&o.addEvent("End");}};var De=()=>typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{},Ne=n=>{let e=n.replace(/-/g,"+").replace(/_/g,"/"),t=e.length%4===0?"":"=".repeat(4-e.length%4);return e+t},Me=n=>{let e=De();if(typeof e.atob!="function")return null;let t=e.atob(n),r=new Uint8Array(t.length);for(let i=0;i<t.length;i+=1)r[i]=t.charCodeAt(i);if(typeof e.TextDecoder=="function")return new e.TextDecoder("utf-8").decode(r);let o="";for(let i=0;i<r.length;i+=1)o+=String.fromCharCode(r[i]);return o},He=n=>{if(typeof Buffer<"u")return Buffer.from(n,"base64").toString("utf-8");let e=Me(n);if(e===null)throw new Error("Base64 decoding is not supported in this environment");return e},m=n=>{if(typeof n!="string")throw new Error("JWT must be a string");let e=n.split(".");if(e.length<2)throw new Error("Invalid JWT: payload segment is missing");let t=e[1],r=He(Ne(t));try{return JSON.parse(r)}catch{throw new Error("Invalid JWT payload: unable to parse JSON")}};var ae="pkce_state",de="pkce_verifier",Fe=3600,w=class{isTokenValid(e){try{let r=m(e).exp??0,o=Date.now()/1e3+Fe;return r>o}catch{return !1}}savePKCEData(e){localStorage.setItem(ae,e.state),localStorage.setItem(de,e.verifier);}getPKCEData(){let e=localStorage.getItem(ae),t=localStorage.getItem(de);return e&&t?{state:e,verifier:t}:null}};var Ve=(...n)=>{if(typeof process>"u")return;process?.env?.JEST_WORKER_ID===void 0&&console.warn(...n);},v={warn:Ve};function le(n){try{let e=m(n),t=Math.floor(Date.now()/1e3);return e.exp?e.exp<=t+30:!0}catch{return !0}}function ce(n){let{id_token:e,access_token:t}=n;return !t||!e?!0:le(t)||le(e)}var P=class{disableGenericPopupOverlay;disableBlockedPopupOverlay;overlay;isBlockedOverlay;tryAgainListener;onCloseListener;constructor(e,t=!1){this.disableBlockedPopupOverlay=e.disableBlockedPopupOverlay||!1,this.disableGenericPopupOverlay=e.disableGenericPopupOverlay||!1,this.isBlockedOverlay=t;}append(e,t){this.shouldAppendOverlay()&&(this.appendOverlay(),this.updateTryAgainButton(e),this.updateCloseButton(t));}update(e){this.updateTryAgainButton(e);}remove(){this.overlay&&this.overlay.remove();}shouldAppendOverlay(){return !(this.disableGenericPopupOverlay&&this.disableBlockedPopupOverlay||this.disableGenericPopupOverlay&&!this.isBlockedOverlay||this.disableBlockedPopupOverlay&&this.isBlockedOverlay)}appendOverlay(){if(!this.overlay){S({id:"link-googleapis",href:"https://fonts.googleapis.com"}),S({id:"link-gstatic",href:"https://fonts.gstatic.com",crossOrigin:"anonymous"}),S({id:"link-roboto",href:"https://fonts.googleapis.com/css2?family=Roboto:ital,wght@0,400;0,500;0,700;1,400;1,500;1,700&display=swap",rel:"stylesheet"});let t=document.createElement("div");t.innerHTML=this.isBlockedOverlay?ne():oe(),document.body.insertAdjacentElement("beforeend",t),this.overlay=t;}}updateTryAgainButton(e){let t=document.getElementById(U);t&&(this.tryAgainListener&&t.removeEventListener("click",this.tryAgainListener),this.tryAgainListener=e,t.addEventListener("click",e));}updateCloseButton(e){let t=document.getElementById(A);t&&(this.onCloseListener&&t.removeEventListener("click",this.onCloseListener),this.onCloseListener=e,t.addEventListener("click",e));}};var x=class{storage;constructor(e,t){this.storage=Ge__default.default.createInstance({name:e,driver:t});}get length(){return this.storage.length()}clear(){return this.storage.clear()}getItem(e){return this.storage.getItem(e)}key(e){return this.storage.key(e)}async removeItem(e){await this.storage.removeItem(e);}async setItem(e,t){await this.storage.setItem(e,t);}};var Be="/v2/logout",Ke="/im-logged-out",$e="https://auth.immutable.com";function We(n){return n.replace(/^(?:https?:\/\/)?(.*)/,"https://$1")}function D(n){let e=We(n.authenticationDomain||$e),t=n.crossSdkBridgeEnabled?Ke:Be,r=new URL(t,e);return r.searchParams.set("client_id",n.clientId),n.logoutRedirectUri&&r.searchParams.set("returnTo",n.logoutRedirectUri),r.toString()}var ot={"Content-Type":"application/x-www-form-urlencoded"},it=n=>{if(n)try{return JSON.parse(n)}catch{return}},st=(n,e,t)=>{if(n&&typeof n=="object"){let r=n,o=r.error_description??r.message??r.error;if(typeof o=="string"&&o.trim().length>0)return o}return e.trim().length>0?e:`Token request failed with status ${t}`},at=(n,e)=>({ethAddress:n,userAdminAddress:e}),dt="/authorize",lt=n=>{let{authenticationDomain:e,oidcConfiguration:t}=n,r;n.crossSdkBridgeEnabled?r=new x("ImmutableSDKPassport",Ge__default.default.INDEXEDDB):typeof window<"u"?r=window.localStorage:r=new oidcClientTs.InMemoryWebStorage;let o=new oidcClientTs.WebStorageStateStore({store:r}),i=D({clientId:t.clientId,authenticationDomain:e,logoutRedirectUri:t.logoutRedirectUri,crossSdkBridgeEnabled:n.crossSdkBridgeEnabled});return {authority:e,redirect_uri:t.redirectUri,popup_redirect_uri:t.popupRedirectUri||t.redirectUri,client_id:t.clientId,metadata:{authorization_endpoint:`${e}/authorize`,token_endpoint:`${e}/oauth/token`,userinfo_endpoint:`${e}/userinfo`,end_session_endpoint:i,revocation_endpoint:`${e}/oauth/revoke`},automaticSilentRenew:!1,scope:t.scope,userStore:o,revokeTokenTypes:["refresh_token"],extraQueryParams:{...t.audience?{audience:t.audience}:{}}}};function B(n){return btoa(String.fromCharCode(...new Uint8Array(n))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}async function ct(n){let t=new TextEncoder().encode(n);return window.crypto.subtle.digest("SHA-256",t)}var K=class n{config;userManager;deviceCredentialsManager;embeddedLoginPrompt;logoutMode;refreshingPromise=null;eventEmitter;constructor(e){this.config=new O(e),this.embeddedLoginPrompt=new L(this.config),this.userManager=new oidcClientTs.UserManager(lt(this.config)),this.deviceCredentialsManager=new w,this.logoutMode=this.config.oidcConfiguration.logoutMode||"redirect",this.eventEmitter=new R,metrics.track("passport","initialise");}async login(e){return u(async()=>{let{useCachedSession:t=!1,useSilentLogin:r}=e||{},o=null;try{o=await this.getUserInternal();}catch(i){if(i instanceof Error&&!i.message.includes("Unknown or invalid refresh token")&&metrics.trackError("passport","login",i),t)throw i;v.warn("Failed to retrieve a cached user session",i);}if(!o&&r)o=await this.forceUserRefreshInternal();else if(!o&&!t){if(e?.useRedirectFlow)return await this.loginWithRedirectInternal(e?.directLoginOptions),null;o=await this.loginWithPopup(e?.directLoginOptions);}return o&&this.handleSuccessfulLogin(o),o},"login")}async loginWithRedirect(e){await this.loginWithRedirectInternal(e);}async loginCallback(){return u(async()=>{let e=await this.loginCallbackInternal();return e&&this.handleSuccessfulLogin(e),e},"loginCallback")}async logout(){await u(async()=>{await this.logoutInternal(),this.eventEmitter.emit("loggedOut");},"logout");}async getUser(){return this.getUserInternal()}async getUserOrLogin(){let e=null;try{e=await this.getUserInternal();}catch(r){v.warn("Failed to retrieve a cached user session",r);}if(e)return e;let t=await this.loginWithPopup();return this.handleSuccessfulLogin(t),t}async getUserZkEvm(){return this.getUserZkEvmInternal()}async getIdToken(){return u(async()=>(await this.getUserInternal())?.idToken,"getIdToken",!1)}async getAccessToken(){return u(async()=>(await this.getUserInternal())?.accessToken,"getAccessToken",!1,!1)}async isLoggedIn(){return await this.getUser()!==null}async forceUserRefresh(){return this.forceUserRefreshInternal()}forceUserRefreshInBackground(){this.forceUserRefreshInBackgroundInternal();}async loginWithPKCEFlow(e,t){return u(async()=>this.getPKCEAuthorizationUrl(e,t),"loginWithPKCEFlow")}async loginWithPKCEFlowCallback(e,t){return u(async()=>{let r=await this.loginWithPKCEFlowCallbackInternal(e,t);return this.handleSuccessfulLogin(r),r},"loginWithPKCEFlowCallback")}async storeTokens(e){return u(async()=>{let t=await this.storeTokensInternal(e);return this.handleSuccessfulLogin(t),t},"storeTokens")}async getLogoutUrl(){return u(async()=>(await this.userManager.removeUser(),this.eventEmitter.emit("loggedOut"),await this.getLogoutUrlInternal()||void 0),"getLogoutUrl")}async logoutSilentCallback(e){return u(()=>this.userManager.signoutSilentCallback(e),"logoutSilentCallback")}getConfig(){return this.config}async getClientId(){return this.config.oidcConfiguration.clientId}handleSuccessfulLogin(e){this.eventEmitter.emit("loggedIn",e),metrics.identify({passportId:e.profile.sub});}buildExtraQueryParams(e,t){let r={...this.userManager.settings?.extraQueryParams??{},rid:metrics.getDetail(metrics.Detail.RUNTIME_ID)||""};if(e){if(e.directLoginMethod==="email"){let o=e.email;o&&(r.direct=e.directLoginMethod,r.email=o);}else r.direct=e.directLoginMethod;e.marketingConsentStatus&&(r.marketingConsent=e.marketingConsentStatus);}return t&&(r.im_passport_trace_id=t),r}async loginWithRedirectInternal(e){await this.userManager.clearStaleState(),await E(async()=>{let t=this.buildExtraQueryParams(e);await this.userManager.signinRedirect({extraQueryParams:t});},"AUTHENTICATION_ERROR");}async loginWithPopup(e){return E(async()=>{let t,r;if(e)t=e;else if(!this.config.popupOverlayOptions?.disableHeadlessLoginPromptOverlay){let{imPassportTraceId:s,...a}=await this.embeddedLoginPrompt.displayEmbeddedLoginPrompt();t=a,r=s;}let o=window.crypto.randomUUID(),i=async()=>{let s=this.buildExtraQueryParams(t,r);return this.userManager.signinPopup({extraQueryParams:s,popupWindowFeatures:{width:410,height:450},popupWindowTarget:o,popupAbortOnClose:!0})};return new Promise((s,a)=>{i().then(d=>s(n.mapOidcUserToDomainModel(d))).catch(d=>{if(!(d instanceof Error)||d.message!=="Attempted to navigate on a disposed window"){a(d);return}let c=!1,l=new P(this.config.popupOverlayOptions||{},!0);l.append(async()=>{try{if(c)window.open("",o);else {c=!0;let g=await i();l.remove(),s(n.mapOidcUserToDomainModel(g));}}catch(g){l.remove(),a(g);}},()=>{l.remove(),a(new Error("Popup closed by user"));});});})},"AUTHENTICATION_ERROR")}static mapOidcUserToDomainModel=e=>{let t,r;if(e.id_token){let i=m(e.id_token);t=i?.passport,i?.username&&(r=i?.username);}let o={expired:e.expired,idToken:e.id_token,accessToken:e.access_token,refreshToken:e.refresh_token,profile:{sub:e.profile.sub,email:e.profile.email,nickname:e.profile.nickname,username:r}};return t?.zkevm_eth_address&&t?.zkevm_user_admin_address&&(o.zkEvm=at(t.zkevm_eth_address,t.zkevm_user_admin_address)),o};static mapDeviceTokenResponseToOidcUser=e=>{let t=m(e.id_token);return new oidcClientTs.User({id_token:e.id_token,access_token:e.access_token,refresh_token:e.refresh_token,token_type:e.token_type,profile:{sub:t.sub,iss:t.iss,aud:t.aud,exp:t.exp,iat:t.iat,email:t.email,nickname:t.nickname,passport:t.passport,...t.username?{username:t.username}:{}}})};async loginCallbackInternal(){return E(async()=>{let e=await this.userManager.signinCallback();if(e)return n.mapOidcUserToDomainModel(e)},"AUTHENTICATION_ERROR")}async getPKCEAuthorizationUrl(e,t){let r=B(window.crypto.getRandomValues(new Uint8Array(32))),o=B(await ct(r)),i=B(window.crypto.getRandomValues(new Uint8Array(32))),{redirectUri:s,scope:a,audience:d,clientId:c}=this.config.oidcConfiguration;this.deviceCredentialsManager.savePKCEData({state:i,verifier:r});let l=new URL(dt,this.config.authenticationDomain);if(l.searchParams.set("response_type","code"),l.searchParams.set("code_challenge",o),l.searchParams.set("code_challenge_method","S256"),l.searchParams.set("client_id",c),l.searchParams.set("redirect_uri",s),l.searchParams.set("state",i),a&&l.searchParams.set("scope",a),d&&l.searchParams.set("audience",d),e){if(e.directLoginMethod==="email"){let g=e.email;g&&(l.searchParams.set("direct",e.directLoginMethod),l.searchParams.set("email",g));}else l.searchParams.set("direct",e.directLoginMethod);e.marketingConsentStatus&&l.searchParams.set("marketingConsent",e.marketingConsentStatus);}return t&&l.searchParams.set("im_passport_trace_id",t),l.toString()}async loginWithPKCEFlowCallbackInternal(e,t){return E(async()=>{let r=this.deviceCredentialsManager.getPKCEData();if(!r)throw new Error("No code verifier or state for PKCE");if(t!==r.state)throw new Error("Provided state does not match stored state");let o=await this.getPKCEToken(e,r.verifier),i=n.mapDeviceTokenResponseToOidcUser(o),s=n.mapOidcUserToDomainModel(i);return await this.userManager.storeUser(i),s},"AUTHENTICATION_ERROR")}async getPKCEToken(e,t){let r=await fetch(`${this.config.authenticationDomain}/oauth/token`,{method:"POST",headers:ot,body:new URLSearchParams({client_id:this.config.oidcConfiguration.clientId,grant_type:"authorization_code",code_verifier:t,code:e,redirect_uri:this.config.oidcConfiguration.redirectUri})}),o=await r.text(),i=it(o);if(!r.ok)throw new Error(st(i,o,r.status));if(!i||typeof i!="object")throw new Error("Token endpoint returned an invalid response");return i}async storeTokensInternal(e){return E(async()=>{let t=n.mapDeviceTokenResponseToOidcUser(e),r=n.mapOidcUserToDomainModel(t);return await this.userManager.storeUser(t),r},"AUTHENTICATION_ERROR")}async logoutInternal(){await E(async()=>{await this.userManager.revokeTokens(["refresh_token"]),this.logoutMode==="silent"?await this.userManager.signoutSilent():await this.userManager.signoutRedirect();},"LOGOUT_ERROR");}async getLogoutUrlInternal(){let e=this.userManager.settings?.metadata?.end_session_endpoint;return e||(v.warn("Failed to get logout URL"),null)}forceUserRefreshInBackgroundInternal(){this.refreshTokenAndUpdatePromise().catch(e=>{v.warn("Failed to refresh user token",e);});}async forceUserRefreshInternal(){return this.refreshTokenAndUpdatePromise().catch(e=>(v.warn("Failed to refresh user token",e),null))}async refreshTokenAndUpdatePromise(){return this.refreshingPromise?this.refreshingPromise:(this.refreshingPromise=new Promise((e,t)=>{(async()=>{try{let r=await this.userManager.signinSilent();if(r){let o=n.mapOidcUserToDomainModel(r);this.eventEmitter.emit("tokenRefreshed",o),e(o);return}e(null);}catch(r){let o="AUTHENTICATION_ERROR",i="Failed to refresh token",s=!0;if(r instanceof oidcClientTs.ErrorTimeout?(o="SILENT_LOGIN_ERROR",i=`${i}: ${r.message}`,s=!1):r instanceof oidcClientTs.ErrorResponse?(o="NOT_LOGGED_IN_ERROR",i=`${i}: ${r.message||r.error_description}`):r instanceof Error?i=`${i}: ${r.message}`:typeof r=="string"&&(i=`${i}: ${r}`),s){this.eventEmitter.emit("userRemoved",{reason:"refresh_failed",error:i});try{await this.userManager.removeUser();}catch(a){a instanceof Error&&(i=`${i}: Failed to remove user: ${a.message}`);}}t(new f(i,o));}finally{this.refreshingPromise=null;}})();}),this.refreshingPromise)}async getUserInternal(e=t=>!0){if(this.refreshingPromise){let r=await this.refreshingPromise;return r&&e(r)?r:null}let t=await this.userManager.getUser();if(!t)return null;if(!ce(t)){let r=n.mapOidcUserToDomainModel(t);if(r&&e(r))return r}if(t.refresh_token){let r=await this.refreshTokenAndUpdatePromise();if(r&&e(r))return r}return null}async getUserZkEvmInternal(){let e=await this.getUserInternal(F);if(!e)throw new Error("Failed to obtain a User with the required ZkEvm attributes");return e}};var mt="im_passport_embedded_login_prompt",me="passport-embedded-login-iframe",ge="passport-overlay";var gt="https://auth.immutable.com",ft="platform_api",ht="openid profile email offline_access transact",Et="/authorize",yt="/oauth/token",$="imtbl_pkce_data";function fe(n){return btoa(String.fromCharCode(...new Uint8Array(n))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}async function _t(n){let t=new TextEncoder().encode(n);return window.crypto.subtle.digest("SHA-256",t)}function pe(){return fe(window.crypto.getRandomValues(new Uint8Array(32)))}function W(n){return n.authenticationDomain||gt}function Ct(n){try{let e=m(n);if(e.exp)return e.exp*1e3}catch{}return Date.now()+3600*1e3}function Rt(n){let{access_token:e,refresh_token:t,id_token:r}=n,o={sub:""},i;if(r)try{let{sub:s,email:a,nickname:d,passport:c}=m(r);o={sub:s,email:a,nickname:d},c?.zkevm_eth_address&&c?.zkevm_user_admin_address&&(i={ethAddress:c.zkevm_eth_address,userAdminAddress:c.zkevm_user_admin_address});}catch{}return {accessToken:e,refreshToken:t,idToken:r,accessTokenExpires:Ct(e),profile:o,zkEvm:i}}function vt(n){typeof window<"u"&&window.sessionStorage&&window.sessionStorage.setItem($,JSON.stringify(n));}function Tt(){if(typeof window<"u"&&window.sessionStorage){let n=window.sessionStorage.getItem($);if(n)try{return JSON.parse(n)}catch{return null}}return null}function ue(){typeof window<"u"&&window.sessionStorage&&window.sessionStorage.removeItem($);}function Ot(){let n="passport-embedded-login-keyframes";if(document.getElementById(n))return;let e=document.createElement("style");e.id=n,e.textContent=`
|
|
394
394
|
@keyframes passportEmbeddedLoginPromptPopBounceIn {
|
|
395
395
|
0% {
|
|
396
396
|
opacity: 0.5;
|
|
@@ -409,7 +409,7 @@ var b=(p=>(p.AUTHENTICATION_ERROR="AUTHENTICATION_ERROR",p.INVALID_CONFIGURATION
|
|
|
409
409
|
}
|
|
410
410
|
|
|
411
411
|
@media (max-height: 400px) {
|
|
412
|
-
#${
|
|
412
|
+
#${me} {
|
|
413
413
|
width: 100% !important;
|
|
414
414
|
max-width: none !important;
|
|
415
415
|
}
|
|
@@ -423,7 +423,7 @@ var b=(p=>(p.AUTHENTICATION_ERROR="AUTHENTICATION_ERROR",p.INVALID_CONFIGURATION
|
|
|
423
423
|
opacity: 1;
|
|
424
424
|
}
|
|
425
425
|
}
|
|
426
|
-
`,document.head.appendChild(e);}function
|
|
426
|
+
`,document.head.appendChild(e);}function Lt(n,e){let t=metrics.getDetail(metrics.Detail.RUNTIME_ID),r=document.createElement("iframe");return r.id=me,r.src=`${n}/im-embedded-login-prompt?client_id=${e}&rid=${t}`,r.style.height="100vh",r.style.width="100vw",r.style.maxHeight="660px",r.style.maxWidth="440px",r.style.borderRadius="16px",r.style.border="none",r.style.opacity="0",r.style.transform="scale(0.6)",r.style.animation="passportEmbeddedLoginPromptPopBounceIn 1s ease forwards",Ot(),r}function wt(){let n=document.createElement("div");n.id=ge,n.style.cssText=`
|
|
427
427
|
position: fixed;
|
|
428
428
|
top: 0;
|
|
429
429
|
left: 0;
|
|
@@ -437,30 +437,29 @@ var b=(p=>(p.AUTHENTICATION_ERROR="AUTHENTICATION_ERROR",p.INVALID_CONFIGURATION
|
|
|
437
437
|
background: rgba(247, 247, 247, 0.24);
|
|
438
438
|
animation-name: passportEmbeddedLoginPromptOverlayFadeIn;
|
|
439
439
|
animation-duration: 0.8s;
|
|
440
|
-
`;let e=document.createElement("div");return e.id=
|
|
440
|
+
`;let e=document.createElement("div");return e.id=y,e.style.cssText=`
|
|
441
441
|
display: flex;
|
|
442
442
|
flex-direction: column;
|
|
443
443
|
align-items: center;
|
|
444
444
|
width: 100%;
|
|
445
|
-
`,n.appendChild(e),n}function I(){document.getElementById(
|
|
445
|
+
`,n.appendChild(e),n}function I(){document.getElementById(ge)?.remove();}function Pt(n,e){return new Promise((t,r)=>{let o=Lt(n,e),i=wt(),s=({data:c,origin:l})=>{if(!(l!==n||c.eventType!==mt))switch(c.messageType){case"login_method_selected":{let g=c.payload;window.removeEventListener("message",s),I(),t(g);break}case"login_prompt_error":{window.removeEventListener("message",s),I(),r(new Error("Error during embedded login prompt",{cause:c.payload}));break}case"login_prompt_closed":{window.removeEventListener("message",s),I(),r(new Error("Login closed by user"));break}default:window.removeEventListener("message",s),I(),r(new Error(`Unsupported message type: ${c.messageType}`));break}},a=c=>{c.target===i&&(window.removeEventListener("message",s),i.removeEventListener("click",a),I(),r(new Error("Login closed by user")));};window.addEventListener("message",s),i.addEventListener("click",a);let d=i.querySelector(`#${y}`);d&&d.appendChild(o),document.body.appendChild(i);})}async function he(n,e){let t=W(n),r=pe(),o=fe(await _t(r)),i=pe(),s=new URL(Et,t);s.searchParams.set("response_type","code"),s.searchParams.set("code_challenge",o),s.searchParams.set("code_challenge_method","S256"),s.searchParams.set("client_id",n.clientId),s.searchParams.set("redirect_uri",n.redirectUri),s.searchParams.set("state",i),s.searchParams.set("scope",n.scope||ht),n.audience?s.searchParams.set("audience",n.audience):s.searchParams.set("audience",ft);let a=e?.directLoginOptions;return a&&(a.directLoginMethod==="email"?a.email&&(s.searchParams.set("direct","email"),s.searchParams.set("email",a.email)):s.searchParams.set("direct",a.directLoginMethod),a.marketingConsentStatus&&s.searchParams.set("marketingConsent",a.marketingConsentStatus)),{url:s.toString(),verifier:r,state:i}}async function Ee(n,e,t,r){let i=`${W(n)}${yt}`,s=await fetch(i,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",client_id:n.clientId,code_verifier:t,code:e,redirect_uri:r})});if(!s.ok){let d=await s.text(),c=`Token exchange failed with status ${s.status}`;try{let l=JSON.parse(d);l.error_description?c=l.error_description:l.error&&(c=l.error);}catch{d&&(c=d);}throw new Error(c)}let a=await s.json();return Rt(a)}async function ye(n,e){metrics.track("passport","standaloneLoginWithPopup");let t=n.popupRedirectUri||n.redirectUri,r={...n,redirectUri:t},{url:o,verifier:i,state:s}=await he(r,e);return new Promise((a,d)=>{let g=window.screenX+(window.outerWidth-500)/2,_e=window.screenY+(window.outerHeight-600)/2,_=window.open(o,"immutable_login",`width=500,height=600,left=${g},top=${_e},toolbar=no,menubar=no`);if(!_){d(new Error("Popup was blocked. Please allow popups for this site."));return}let N=setInterval(()=>{try{if(_.closed){clearInterval(N),d(new Error("Login popup was closed"));return}let M=_.location.href;if(M&&M.startsWith(t)){clearInterval(N),_.close();let k=new URL(M),z=k.searchParams.get("code"),Ce=k.searchParams.get("state"),Y=k.searchParams.get("error"),Re=k.searchParams.get("error_description");if(Y){d(new Error(Re||Y));return}if(!z){d(new Error("No authorization code received"));return}if(Ce!==s){d(new Error("State mismatch - possible CSRF attack"));return}Ee(r,z,i,t).then(a).catch(d);}}catch{}},100);setTimeout(()=>{clearInterval(N),_.closed||_.close(),d(new Error("Login timed out"));},5*60*1e3);})}async function It(n){metrics.track("passport","standaloneLoginWithEmbedded");let e=W(n),t=await Pt(e,n.clientId),r={directLoginOptions:{directLoginMethod:t.directLoginMethod,marketingConsentStatus:t.marketingConsentStatus,...t.directLoginMethod==="email"&&t.email?{email:t.email}:{}}};return ye(n,r)}async function kt(n,e){metrics.track("passport","standaloneLoginWithRedirect");let{url:t,verifier:r,state:o}=await he(n,e);vt({state:o,verifier:r,redirectUri:n.redirectUri}),window.location.href=t;}async function bt(n){if(metrics.track("passport","standaloneHandleCallback"),typeof window>"u")return;let e=new URLSearchParams(window.location.search),t=e.get("code"),r=e.get("state"),o=e.get("error"),i=e.get("error_description");if(o)throw new Error(i||o);if(!t)return;let s=Tt();if(!s)throw new Error("No PKCE data found. Login may have been initiated in a different session.");if(r!==s.state)throw ue(),new Error("State mismatch - possible CSRF attack");let a=await Ee(n,t,s.verifier,s.redirectUri);return ue(),a}function Z(n){return D(n)}function At(n){metrics.track("passport","standaloneLogoutWithRedirect");let e=Z(n);window.location.href=e;}async function Ut(n,e=5e3){return metrics.track("passport","standaloneLogoutSilent"),new Promise((t,r)=>{let o=Z(n),i=document.createElement("iframe");i.style.display="none",i.setAttribute("aria-hidden","true");let s,a=!1,d=()=>{s&&clearTimeout(s),i.remove();},c=()=>{a||(a=!0,d(),t());},l=()=>{a||(a=!0,d(),r(new Error("Silent logout failed: iframe load error")));};i.addEventListener("load",c),i.addEventListener("error",l),s=setTimeout(()=>{a||(a=!0,d(),t());},e),i.src=o,document.body.appendChild(i);})}
|
|
446
446
|
|
|
447
|
-
exports.Auth =
|
|
447
|
+
exports.Auth = K;
|
|
448
448
|
exports.AuthConfiguration = O;
|
|
449
|
-
exports.AuthEvents =
|
|
450
|
-
exports.
|
|
451
|
-
exports.MarketingConsentStatus = q;
|
|
449
|
+
exports.AuthEvents = V;
|
|
450
|
+
exports.MarketingConsentStatus = Q;
|
|
452
451
|
exports.PassportError = f;
|
|
453
452
|
exports.PassportErrorType = b;
|
|
454
|
-
exports.RollupType =
|
|
453
|
+
exports.RollupType = J;
|
|
455
454
|
exports.TypedEventEmitter = R;
|
|
456
|
-
exports.buildLogoutUrl =
|
|
455
|
+
exports.buildLogoutUrl = Z;
|
|
457
456
|
exports.decodeJwtPayload = m;
|
|
458
|
-
exports.handleLoginCallback =
|
|
459
|
-
exports.isAPIError =
|
|
460
|
-
exports.isUserZkEvm =
|
|
461
|
-
exports.loginWithEmbedded =
|
|
462
|
-
exports.loginWithPopup =
|
|
463
|
-
exports.loginWithRedirect =
|
|
464
|
-
exports.logoutSilent =
|
|
465
|
-
exports.logoutWithRedirect =
|
|
457
|
+
exports.handleLoginCallback = bt;
|
|
458
|
+
exports.isAPIError = H;
|
|
459
|
+
exports.isUserZkEvm = F;
|
|
460
|
+
exports.loginWithEmbedded = It;
|
|
461
|
+
exports.loginWithPopup = ye;
|
|
462
|
+
exports.loginWithRedirect = kt;
|
|
463
|
+
exports.logoutSilent = Ut;
|
|
464
|
+
exports.logoutWithRedirect = At;
|
|
466
465
|
exports.withPassportError = E;
|