@imtbl/auth 2.12.5 → 2.12.6-alpha.1
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/README.md +163 -0
- package/dist/browser/index.js +80 -28
- package/dist/node/index.cjs +99 -40
- package/dist/node/index.js +79 -27
- package/dist/types/index.d.ts +3 -1
- package/dist/types/login/standalone.d.ts +223 -0
- package/dist/types/logout/index.d.ts +27 -0
- package/dist/types/types.d.ts +32 -3
- package/package.json +6 -6
- package/src/Auth.test.ts +225 -0
- package/src/Auth.ts +31 -25
- package/src/index.ts +27 -0
- package/src/login/standalone.ts +906 -0
- package/src/logout/index.ts +52 -0
- package/src/types.ts +36 -2
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 Be = 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 Be__default = /*#__PURE__*/_interopDefault(Be);
|
|
10
10
|
|
|
11
|
-
var
|
|
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 F(n){return typeof n=="object"&&n!==null&&"code"in n&&"message"in n}var Oe=n=>{if(F(n))return n;if(typeof n=="object"&&n!==null&&"response"in n){let{response:e}=n;if(e?.data&&F(e.data))return e.data}},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=Oe(t);throw o?r=o.message:r=t.message,new f(r,e)}};var Le=(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}){Le(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 Q=(e=>(e.ZKEVM="zkEvm",e))(Q||{}),A=(t=>(t.ZKEVM="zkevm",t.ARBITRUM_ONE="arbitrum_one",t))(A||{}),V=n=>!!n.zkEvm,q=(r=>(r.OptedIn="opted_in",r.Unsubscribed="unsubscribed",r.Subscribed="subscribed",r))(q||{}),G=(o=>(o.LOGGED_OUT="loggedOut",o.LOGGED_IN="loggedIn",o.TOKEN_REFRESHED="tokenRefreshed",o.USER_REMOVED="userRemoved",o))(G||{});var X="im_passport_embedded_login_prompt";var C="passport-overlay",_="passport-overlay-contents",U=`${C}-close`,x=`${C}-try-again`,j=`
|
|
12
12
|
<svg
|
|
13
13
|
viewBox="0 0 20 20"
|
|
14
14
|
fill="none"
|
|
@@ -20,7 +20,7 @@ var P=(a=>(a.AUTHENTICATION_ERROR="AUTHENTICATION_ERROR",a.INVALID_CONFIGURATION
|
|
|
20
20
|
fill="#F3F3F3"
|
|
21
21
|
/>
|
|
22
22
|
</svg>
|
|
23
|
-
`,
|
|
23
|
+
`,ee=`
|
|
24
24
|
<svg
|
|
25
25
|
viewBox="0 0 17 16"
|
|
26
26
|
fill="none"
|
|
@@ -34,7 +34,7 @@ var P=(a=>(a.AUTHENTICATION_ERROR="AUTHENTICATION_ERROR",a.INVALID_CONFIGURATION
|
|
|
34
34
|
fill="#E01A3D"
|
|
35
35
|
/>
|
|
36
36
|
</svg>
|
|
37
|
-
`,
|
|
37
|
+
`,B=`
|
|
38
38
|
<svg
|
|
39
39
|
style="
|
|
40
40
|
max-width: 123px !important;
|
|
@@ -217,9 +217,9 @@ var P=(a=>(a.AUTHENTICATION_ERROR="AUTHENTICATION_ERROR",a.INVALID_CONFIGURATION
|
|
|
217
217
|
</clipPath>
|
|
218
218
|
</defs>
|
|
219
219
|
</svg>
|
|
220
|
-
`;var
|
|
220
|
+
`;var Pe=()=>`
|
|
221
221
|
<button
|
|
222
|
-
id="${
|
|
222
|
+
id="${U}"
|
|
223
223
|
style="
|
|
224
224
|
background: #f3f3f326 !important;
|
|
225
225
|
border: none !important;
|
|
@@ -235,11 +235,11 @@ var P=(a=>(a.AUTHENTICATION_ERROR="AUTHENTICATION_ERROR",a.INVALID_CONFIGURATION
|
|
|
235
235
|
justify-content: center !important;
|
|
236
236
|
"
|
|
237
237
|
>
|
|
238
|
-
${
|
|
238
|
+
${j}
|
|
239
239
|
</button>
|
|
240
|
-
`,
|
|
240
|
+
`,te=()=>`
|
|
241
241
|
<button
|
|
242
|
-
id="${
|
|
242
|
+
id="${x}"
|
|
243
243
|
style="
|
|
244
244
|
margin-top: 27px !important;
|
|
245
245
|
color: #f3f3f3 !important;
|
|
@@ -254,8 +254,8 @@ var P=(a=>(a.AUTHENTICATION_ERROR="AUTHENTICATION_ERROR",a.INVALID_CONFIGURATION
|
|
|
254
254
|
>
|
|
255
255
|
Try again
|
|
256
256
|
</button>
|
|
257
|
-
`,
|
|
258
|
-
${
|
|
257
|
+
`,we=()=>`
|
|
258
|
+
${B}
|
|
259
259
|
<div
|
|
260
260
|
style="
|
|
261
261
|
color: #e01a3d !important;
|
|
@@ -265,7 +265,7 @@ var P=(a=>(a.AUTHENTICATION_ERROR="AUTHENTICATION_ERROR",a.INVALID_CONFIGURATION
|
|
|
265
265
|
margin-bottom: 10px !important;
|
|
266
266
|
"
|
|
267
267
|
>
|
|
268
|
-
${
|
|
268
|
+
${ee}
|
|
269
269
|
Pop-up blocked
|
|
270
270
|
</div>
|
|
271
271
|
<p style="
|
|
@@ -278,9 +278,9 @@ var P=(a=>(a.AUTHENTICATION_ERROR="AUTHENTICATION_ERROR",a.INVALID_CONFIGURATION
|
|
|
278
278
|
If the problem continues, adjust your<br />
|
|
279
279
|
browser settings.
|
|
280
280
|
</p>
|
|
281
|
-
${
|
|
282
|
-
`,
|
|
283
|
-
${
|
|
281
|
+
${te()}
|
|
282
|
+
`,Ie=()=>`
|
|
283
|
+
${B}
|
|
284
284
|
<p style="
|
|
285
285
|
color: #b6b6b6 !important;
|
|
286
286
|
text-align: center !important;
|
|
@@ -289,10 +289,10 @@ var P=(a=>(a.AUTHENTICATION_ERROR="AUTHENTICATION_ERROR",a.INVALID_CONFIGURATION
|
|
|
289
289
|
>
|
|
290
290
|
Secure pop-up not showing?<br />We'll help you re-launch
|
|
291
291
|
</p>
|
|
292
|
-
${
|
|
293
|
-
`,
|
|
292
|
+
${te()}
|
|
293
|
+
`,re=n=>`
|
|
294
294
|
<div
|
|
295
|
-
id="${
|
|
295
|
+
id="${C}"
|
|
296
296
|
style="
|
|
297
297
|
position: fixed !important;
|
|
298
298
|
top: 0 !important;
|
|
@@ -315,9 +315,9 @@ var P=(a=>(a.AUTHENTICATION_ERROR="AUTHENTICATION_ERROR",a.INVALID_CONFIGURATION
|
|
|
315
315
|
z-index: 2147483647 !important;
|
|
316
316
|
"
|
|
317
317
|
>
|
|
318
|
-
${
|
|
318
|
+
${Pe()}
|
|
319
319
|
<div
|
|
320
|
-
id="${
|
|
320
|
+
id="${_}"
|
|
321
321
|
style="
|
|
322
322
|
display: flex !important;
|
|
323
323
|
flex-direction: column !important;
|
|
@@ -328,9 +328,9 @@ var P=(a=>(a.AUTHENTICATION_ERROR="AUTHENTICATION_ERROR",a.INVALID_CONFIGURATION
|
|
|
328
328
|
${n??""}
|
|
329
329
|
</div>
|
|
330
330
|
</div>
|
|
331
|
-
`,
|
|
331
|
+
`,ne=()=>`
|
|
332
332
|
<div
|
|
333
|
-
id="${
|
|
333
|
+
id="${C}"
|
|
334
334
|
style="
|
|
335
335
|
position: fixed;
|
|
336
336
|
top: 0;
|
|
@@ -348,7 +348,7 @@ var P=(a=>(a.AUTHENTICATION_ERROR="AUTHENTICATION_ERROR",a.INVALID_CONFIGURATION
|
|
|
348
348
|
"
|
|
349
349
|
>
|
|
350
350
|
<div
|
|
351
|
-
id="${
|
|
351
|
+
id="${_}"
|
|
352
352
|
style="
|
|
353
353
|
display: flex;
|
|
354
354
|
flex-direction: column;
|
|
@@ -357,7 +357,7 @@ var P=(a=>(a.AUTHENTICATION_ERROR="AUTHENTICATION_ERROR",a.INVALID_CONFIGURATION
|
|
|
357
357
|
"
|
|
358
358
|
/>
|
|
359
359
|
</div>
|
|
360
|
-
`;function
|
|
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 oe=()=>re(we()),ie=()=>re(Ie());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=ne(),document.body.insertAdjacentElement("beforeend",r);let o=document.querySelector(`#${_}`);o&&o.appendChild(e),r.addEventListener("click",t),this.overlay=r;}}};var Ae=660,Ue=440,xe="16px",se="passport-embedded-login-keyframes",ae="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(se))return;let e=document.createElement("style");e.id=se,e.textContent=`
|
|
361
361
|
@keyframes passportEmbeddedLoginPromptPopBounceIn {
|
|
362
362
|
0% {
|
|
363
363
|
opacity: 0.5;
|
|
@@ -376,7 +376,7 @@ var P=(a=>(a.AUTHENTICATION_ERROR="AUTHENTICATION_ERROR",a.INVALID_CONFIGURATION
|
|
|
376
376
|
}
|
|
377
377
|
|
|
378
378
|
@media (max-height: 400px) {
|
|
379
|
-
#${
|
|
379
|
+
#${ae} {
|
|
380
380
|
width: 100% !important;
|
|
381
381
|
max-width: none !important;
|
|
382
382
|
}
|
|
@@ -390,18 +390,77 @@ var P=(a=>(a.AUTHENTICATION_ERROR="AUTHENTICATION_ERROR",a.INVALID_CONFIGURATION
|
|
|
390
390
|
opacity: 1;
|
|
391
391
|
}
|
|
392
392
|
}
|
|
393
|
-
`,document.head.appendChild(e);};getEmbeddedLoginIFrame=()=>{let e=document.createElement("iframe");return e.id=J,e.src=this.getHref(),e.style.height="100vh",e.style.width="100vw",e.style.maxHeight=`${ae}px`,e.style.maxWidth=`${de}px`,e.style.borderRadius=le,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(),i=({data:o,origin:s})=>{if(!(s!==this.config.authenticationDomain||o.eventType!==V))switch(o.messageType){case"login_method_selected":{let l=o.payload;window.removeEventListener("message",i),u.remove(),e(l);break}case"login_prompt_error":{window.removeEventListener("message",i),u.remove(),t(new Error("Error during embedded login prompt",{cause:o.payload}));break}case"login_prompt_closed":{window.removeEventListener("message",i),u.remove(),t(new Error("Popup closed by user"));break}default:window.removeEventListener("message",i),u.remove(),t(new Error(`Unsupported message type: ${o.messageType}`));break}};window.addEventListener("message",i),u.appendOverlay(r,()=>{window.removeEventListener("message",i),u.remove(),t(new Error("Popup closed by user"));});})}};var C=class{listeners=new Map;emit(e,...t){let r=this.listeners.get(e);!r||r.size===0||[...r].forEach(i=>{i(...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 c=async(n,e,t=!0,r=!0)=>{let i=metrics.trackFlow("passport",e,t);try{return await n(i)}catch(o){throw o instanceof Error?metrics.trackError("passport",e,o,{flowId:i.details.flowId}):i.addEvent("errored"),o}finally{r&&i.addEvent("End");}};var ue=()=>typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{},me=n=>{let e=n.replace(/-/g,"+").replace(/_/g,"/"),t=e.length%4===0?"":"=".repeat(4-e.length%4);return e+t},ge=n=>{let e=ue();if(typeof e.atob!="function")return null;let t=e.atob(n),r=new Uint8Array(t.length);for(let o=0;o<t.length;o+=1)r[o]=t.charCodeAt(o);if(typeof e.TextDecoder=="function")return new e.TextDecoder("utf-8").decode(r);let i="";for(let o=0;o<r.length;o+=1)i+=String.fromCharCode(r[o]);return i},fe=n=>{if(typeof Buffer<"u")return Buffer.from(n,"base64").toString("utf-8");let e=ge(n);if(e===null)throw new Error("Base64 decoding is not supported in this environment");return e},f=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=fe(me(t));try{return JSON.parse(r)}catch{throw new Error("Invalid JWT payload: unable to parse JSON")}};var j="pkce_state",Q="pkce_verifier",Ee=3600,O=class{isTokenValid(e){try{let r=f(e).exp??0,i=Date.now()/1e3+Ee;return r>i}catch{return !1}}savePKCEData(e){localStorage.setItem(j,e.state),localStorage.setItem(Q,e.verifier);}getPKCEData(){let e=localStorage.getItem(j),t=localStorage.getItem(Q);return e&&t?{state:e,verifier:t}:null}};var he=(...n)=>{if(typeof process>"u")return;process?.env?.JEST_WORKER_ID===void 0&&console.warn(...n);},_={warn:he};function q(n){try{let e=f(n),t=Math.floor(Date.now()/1e3);return e.exp?e.exp<=t+30:!0}catch{return !0}}function X(n){let{id_token:e,access_token:t}=n;return !t||!e?!0:q(t)||q(e)}var T=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){k({id:"link-googleapis",href:"https://fonts.googleapis.com"}),k({id:"link-gstatic",href:"https://fonts.gstatic.com",crossOrigin:"anonymous"}),k({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?$():z(),document.body.insertAdjacentElement("beforeend",t),this.overlay=t;}}updateTryAgainButton(e){let t=document.getElementById(w);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 b=class{storage;constructor(e,t){this.storage=Ce__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={"Content-Type":"application/x-www-form-urlencoded"},Ue=n=>{if(n)try{return JSON.parse(n)}catch{return}},xe=(n,e,t)=>{if(n&&typeof n=="object"){let r=n,i=r.error_description??r.message??r.error;if(typeof i=="string"&&i.trim().length>0)return i}return e.trim().length>0?e:`Token request failed with status ${t}`},Me="/v2/logout",Se="/im-logged-out",Ne="/authorize",De=n=>n?Se:Me,Fe=n=>{let{authenticationDomain:e,oidcConfiguration:t}=n,r;n.crossSdkBridgeEnabled?r=new b("ImmutableSDKPassport",Ce__default.default.INDEXEDDB):typeof window<"u"?r=window.localStorage:r=new oidcClientTs.InMemoryWebStorage;let i=new oidcClientTs.WebStorageStateStore({store:r}),o=new URL(De(n.crossSdkBridgeEnabled),e.replace(/^(?:https?:\/\/)?(.*)/,"https://$1"));return o.searchParams.set("client_id",t.clientId),t.logoutRedirectUri&&o.searchParams.set("returnTo",t.logoutRedirectUri),{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:o.toString(),revocation_endpoint:`${e}/oauth/revoke`},automaticSilentRenew:!1,scope:t.scope,userStore:i,revokeTokenTypes:["refresh_token"],extraQueryParams:{...t.audience?{audience:t.audience}:{}}}};function N(n){return btoa(String.fromCharCode(...new Uint8Array(n))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}async function He(n){let t=new TextEncoder().encode(n);return window.crypto.subtle.digest("SHA-256",t)}var D=class n{config;userManager;deviceCredentialsManager;embeddedLoginPrompt;logoutMode;refreshingPromise=null;eventEmitter;constructor(e){this.config=new y(e),this.embeddedLoginPrompt=new v(this.config),this.userManager=new oidcClientTs.UserManager(Fe(this.config)),this.deviceCredentialsManager=new O,this.logoutMode=this.config.oidcConfiguration.logoutMode||"redirect",this.eventEmitter=new C,metrics.track("passport","initialise");}async login(e){return c(async()=>{let{useCachedSession:t=!1,useSilentLogin:r}=e||{},i=null;try{i=await this.getUserInternal();}catch(o){if(o instanceof Error&&!o.message.includes("Unknown or invalid refresh token")&&metrics.trackError("passport","login",o),t)throw o;_.warn("Failed to retrieve a cached user session",o);}if(!i&&r)i=await this.forceUserRefreshInternal();else if(!i&&!t){if(e?.useRedirectFlow)return await this.loginWithRedirectInternal(e?.directLoginOptions),null;i=await this.loginWithPopup(e?.directLoginOptions);}return i&&this.handleSuccessfulLogin(i),i},"login")}async loginWithRedirect(e){await this.loginWithRedirectInternal(e);}async loginCallback(){return c(async()=>{let e=await this.loginCallbackInternal();return e&&this.handleSuccessfulLogin(e),e},"loginCallback")}async logout(){await c(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){_.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 c(async()=>(await this.getUserInternal())?.idToken,"getIdToken",!1)}async getAccessToken(){return c(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 c(async()=>this.getPKCEAuthorizationUrl(e,t),"loginWithPKCEFlow")}async loginWithPKCEFlowCallback(e,t){return c(async()=>{let r=await this.loginWithPKCEFlowCallbackInternal(e,t);return this.handleSuccessfulLogin(r),r},"loginWithPKCEFlowCallback")}async storeTokens(e){return c(async()=>{let t=await this.storeTokensInternal(e);return this.handleSuccessfulLogin(t),t},"storeTokens")}async getLogoutUrl(){return c(async()=>(await this.userManager.removeUser(),this.eventEmitter.emit("loggedOut"),await this.getLogoutUrlInternal()||void 0),"getLogoutUrl")}async logoutSilentCallback(e){return c(()=>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 i=e.email;i&&(r.direct=e.directLoginMethod,r.email=i);}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 g(async()=>{let t=this.buildExtraQueryParams(e);await this.userManager.signinRedirect({extraQueryParams:t});},"AUTHENTICATION_ERROR");}async loginWithPopup(e){return g(async()=>{let t,r;if(e)t=e;else if(!this.config.popupOverlayOptions?.disableHeadlessLoginPromptOverlay){let{imPassportTraceId:s,...l}=await this.embeddedLoginPrompt.displayEmbeddedLoginPrompt();t=l,r=s;}let i=window.crypto.randomUUID(),o=async()=>{let s=this.buildExtraQueryParams(t,r);return this.userManager.signinPopup({extraQueryParams:s,popupWindowFeatures:{width:410,height:450},popupWindowTarget:i,popupAbortOnClose:!0})};return new Promise((s,l)=>{o().then(m=>s(n.mapOidcUserToDomainModel(m))).catch(m=>{if(!(m instanceof Error)||m.message!=="Attempted to navigate on a disposed window"){l(m);return}let L=!1,d=new T(this.config.popupOverlayOptions||{},!0);d.append(async()=>{try{if(L)window.open("",i);else {L=!0;let E=await o();d.remove(),s(n.mapOidcUserToDomainModel(E));}}catch(E){d.remove(),l(E);}},()=>{d.remove(),l(new Error("Popup closed by user"));});});})},"AUTHENTICATION_ERROR")}static mapOidcUserToDomainModel=e=>{let t,r;if(e.id_token){let s=f(e.id_token);t=s?.passport,s?.username&&(r=s?.username);}let i={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&&(i.zkEvm={ethAddress:t.zkevm_eth_address,userAdminAddress:t.zkevm_user_admin_address});let o=Object.values(I).filter(s=>s!=="zkevm");for(let s of o){let l=t?.[s];l?.eth_address&&l?.user_admin_address&&(i[s]={ethAddress:l.eth_address,userAdminAddress:l.user_admin_address});}return i};static mapDeviceTokenResponseToOidcUser=e=>{let t=f(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 g(async()=>{let e=await this.userManager.signinCallback();if(e)return n.mapOidcUserToDomainModel(e)},"AUTHENTICATION_ERROR")}async getPKCEAuthorizationUrl(e,t){let r=N(window.crypto.getRandomValues(new Uint8Array(32))),i=N(await He(r)),o=N(window.crypto.getRandomValues(new Uint8Array(32))),{redirectUri:s,scope:l,audience:m,clientId:L}=this.config.oidcConfiguration;this.deviceCredentialsManager.savePKCEData({state:o,verifier:r});let d=new URL(Ne,this.config.authenticationDomain);if(d.searchParams.set("response_type","code"),d.searchParams.set("code_challenge",i),d.searchParams.set("code_challenge_method","S256"),d.searchParams.set("client_id",L),d.searchParams.set("redirect_uri",s),d.searchParams.set("state",o),l&&d.searchParams.set("scope",l),m&&d.searchParams.set("audience",m),e){if(e.directLoginMethod==="email"){let E=e.email;E&&(d.searchParams.set("direct",e.directLoginMethod),d.searchParams.set("email",E));}else d.searchParams.set("direct",e.directLoginMethod);e.marketingConsentStatus&&d.searchParams.set("marketingConsent",e.marketingConsentStatus);}return t&&d.searchParams.set("im_passport_trace_id",t),d.toString()}async loginWithPKCEFlowCallbackInternal(e,t){return g(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 i=await this.getPKCEToken(e,r.verifier),o=n.mapDeviceTokenResponseToOidcUser(i),s=n.mapOidcUserToDomainModel(o);return await this.userManager.storeUser(o),s},"AUTHENTICATION_ERROR")}async getPKCEToken(e,t){let r=await fetch(`${this.config.authenticationDomain}/oauth/token`,{method:"POST",headers:be,body:new URLSearchParams({client_id:this.config.oidcConfiguration.clientId,grant_type:"authorization_code",code_verifier:t,code:e,redirect_uri:this.config.oidcConfiguration.redirectUri})}),i=await r.text(),o=Ue(i);if(!r.ok)throw new Error(xe(o,i,r.status));if(!o||typeof o!="object")throw new Error("Token endpoint returned an invalid response");return o}async storeTokensInternal(e){return g(async()=>{let t=n.mapDeviceTokenResponseToOidcUser(e),r=n.mapOidcUserToDomainModel(t);return await this.userManager.storeUser(t),r},"AUTHENTICATION_ERROR")}async logoutInternal(){await g(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||(_.warn("Failed to get logout URL"),null)}forceUserRefreshInBackgroundInternal(){this.refreshTokenAndUpdatePromise().catch(e=>{_.warn("Failed to refresh user token",e);});}async forceUserRefreshInternal(){return this.refreshTokenAndUpdatePromise().catch(e=>(_.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){e(n.mapOidcUserToDomainModel(r));return}e(null);}catch(r){let i="AUTHENTICATION_ERROR",o="Failed to refresh token",s=!0;if(r instanceof oidcClientTs.ErrorTimeout?(i="SILENT_LOGIN_ERROR",o=`${o}: ${r.message}`,s=!1):r instanceof oidcClientTs.ErrorResponse?(i="NOT_LOGGED_IN_ERROR",o=`${o}: ${r.message||r.error_description}`):r instanceof Error?o=`${o}: ${r.message}`:typeof r=="string"&&(o=`${o}: ${r}`),s)try{await this.userManager.removeUser();}catch(l){l instanceof Error&&(o=`${o}: Failed to remove user: ${l.message}`);}t(new p(o,i));}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(!X(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(x);if(!e)throw new Error("Failed to obtain a User with the required ZkEvm attributes");return e}};
|
|
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=`${Ae}px`,e.style.maxWidth=`${Ue}px`,e.style.borderRadius=xe,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 Me=()=>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},He=n=>{let e=Me();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},Fe=n=>{if(typeof Buffer<"u")return Buffer.from(n,"base64").toString("utf-8");let e=He(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=Fe(Ne(t));try{return JSON.parse(r)}catch{throw new Error("Invalid JWT payload: unable to parse JSON")}};var de="pkce_state",le="pkce_verifier",Ve=3600,P=class{isTokenValid(e){try{let r=m(e).exp??0,o=Date.now()/1e3+Ve;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 Ge=(...n)=>{if(typeof process>"u")return;process?.env?.JEST_WORKER_ID===void 0&&console.warn(...n);},v={warn:Ge};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=Be__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 Ke="/v2/logout",Ze="/im-logged-out",$e="https://auth.immutable.com";function We(n){return n.replace(/^(?:https?:\/\/)?(.*)/,"https://$1")}function M(n){let e=We(n.authenticationDomain||$e),t=n.crossSdkBridgeEnabled?Ze:Ke,r=new URL(t,e);return r.searchParams.set("client_id",n.clientId),n.logoutRedirectUri&&r.searchParams.set("returnTo",n.logoutRedirectUri),r.toString()}var it={"Content-Type":"application/x-www-form-urlencoded"},st=n=>{if(n)try{return JSON.parse(n)}catch{return}},at=(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}),dt="/authorize",lt=n=>{let{authenticationDomain:e,oidcConfiguration:t}=n,r;n.crossSdkBridgeEnabled?r=new D("ImmutableSDKPassport",Be__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 ct(n){let t=new TextEncoder().encode(n);return window.crypto.subtle.digest("SHA-256",t)}var Z=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 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 ct(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(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:it,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=st(o);if(!r.ok)throw new Error(at(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 mt="im_passport_embedded_login_prompt",fe="passport-embedded-login-iframe",he="passport-overlay";var gt="https://auth.immutable.com",ft="platform_api",ht="openid profile email offline_access transact",Et="/authorize",_t="/oauth/token",$="imtbl_pkce_data";function Ee(n){return btoa(String.fromCharCode(...new Uint8Array(n))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}async function yt(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||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 ge(){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
|
+
@keyframes passportEmbeddedLoginPromptPopBounceIn {
|
|
395
|
+
0% {
|
|
396
|
+
opacity: 0.5;
|
|
397
|
+
}
|
|
398
|
+
50% {
|
|
399
|
+
opacity: 1;
|
|
400
|
+
transform: scale(1.05);
|
|
401
|
+
}
|
|
402
|
+
75% {
|
|
403
|
+
transform: scale(0.98);
|
|
404
|
+
}
|
|
405
|
+
100% {
|
|
406
|
+
opacity: 1;
|
|
407
|
+
transform: scale(1);
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
@media (max-height: 400px) {
|
|
412
|
+
#${fe} {
|
|
413
|
+
width: 100% !important;
|
|
414
|
+
max-width: none !important;
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
@keyframes passportEmbeddedLoginPromptOverlayFadeIn {
|
|
419
|
+
from {
|
|
420
|
+
opacity: 0;
|
|
421
|
+
}
|
|
422
|
+
to {
|
|
423
|
+
opacity: 1;
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
`,document.head.appendChild(e);}function Lt(n,e){let t=metrics.getDetail(metrics.Detail.RUNTIME_ID),r=document.createElement("iframe");return r.id=fe,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 Pt(){let n=document.createElement("div");n.id=he,n.style.cssText=`
|
|
427
|
+
position: fixed;
|
|
428
|
+
top: 0;
|
|
429
|
+
left: 0;
|
|
430
|
+
width: 100%;
|
|
431
|
+
height: 100%;
|
|
432
|
+
display: flex;
|
|
433
|
+
flex-direction: column;
|
|
434
|
+
justify-content: center;
|
|
435
|
+
align-items: center;
|
|
436
|
+
z-index: 2147483647;
|
|
437
|
+
background: rgba(247, 247, 247, 0.24);
|
|
438
|
+
animation-name: passportEmbeddedLoginPromptOverlayFadeIn;
|
|
439
|
+
animation-duration: 0.8s;
|
|
440
|
+
`;let e=document.createElement("div");return e.id=_,e.style.cssText=`
|
|
441
|
+
display: flex;
|
|
442
|
+
flex-direction: column;
|
|
443
|
+
align-items: center;
|
|
444
|
+
width: 100%;
|
|
445
|
+
`,n.appendChild(e),n}function I(){document.getElementById(he)?.remove();}function wt(n,e){return new Promise((t,r)=>{let o=Lt(n,e),i=Pt(),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(`#${_}`);d&&d.appendChild(o),document.body.appendChild(i);})}async function _e(n,e){let t=W(n),r=me(),o=Ee(await yt(r)),i=me(),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 ye(n,e,t,r){let i=`${W(n)}${_t}`,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 Ce(n,e){metrics.track("passport","standaloneLoginWithPopup");let t=n.popupRedirectUri||n.redirectUri,r={...n,redirectUri:t},{url:o,verifier:i,state:s}=await _e(r,e);return new Promise((a,d)=>{let g=window.screenX+(window.outerWidth-500)/2,Re=window.screenY+(window.outerHeight-600)/2,y=window.open(o,"immutable_login",`width=500,height=600,left=${g},top=${Re},toolbar=no,menubar=no`);if(!y){d(new Error("Popup was blocked. Please allow popups for this site."));return}let N=setInterval(()=>{try{if(y.closed){clearInterval(N),d(new Error("Login popup was closed"));return}let H=y.location.href;if(H&&H.startsWith(t)){clearInterval(N),y.close();let k=new URL(H),Y=k.searchParams.get("code"),ve=k.searchParams.get("state"),J=k.searchParams.get("error"),Te=k.searchParams.get("error_description");if(J){d(new Error(Te||J));return}if(!Y){d(new Error("No authorization code received"));return}if(ve!==s){d(new Error("State mismatch - possible CSRF attack"));return}ye(r,Y,i,t).then(a).catch(d);}}catch{}},100);setTimeout(()=>{clearInterval(N),y.closed||y.close(),d(new Error("Login timed out"));},5*60*1e3);})}async function It(n){metrics.track("passport","standaloneLoginWithEmbedded");let e=W(n),t=await wt(e,n.clientId),r={directLoginOptions:{directLoginMethod:t.directLoginMethod,marketingConsentStatus:t.marketingConsentStatus,...t.directLoginMethod==="email"&&t.email?{email:t.email}:{}}};return Ce(n,r)}async function kt(n,e){metrics.track("passport","standaloneLoginWithRedirect");let{url:t,verifier:r,state:o}=await _e(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 ge(),new Error("State mismatch - possible CSRF attack");let a=await ye(n,t,s.verifier,s.redirectUri);return ge(),a}function z(n){return M(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);})}
|
|
394
446
|
|
|
395
|
-
exports.Auth =
|
|
396
|
-
exports.AuthConfiguration =
|
|
397
|
-
exports.AuthEvents =
|
|
398
|
-
exports.EvmChain =
|
|
399
|
-
exports.MarketingConsentStatus =
|
|
400
|
-
exports.PassportError =
|
|
401
|
-
exports.PassportErrorType =
|
|
402
|
-
exports.RollupType =
|
|
403
|
-
exports.TypedEventEmitter =
|
|
404
|
-
exports.
|
|
405
|
-
exports.
|
|
406
|
-
exports.
|
|
407
|
-
exports.
|
|
447
|
+
exports.Auth = Z;
|
|
448
|
+
exports.AuthConfiguration = O;
|
|
449
|
+
exports.AuthEvents = G;
|
|
450
|
+
exports.EvmChain = A;
|
|
451
|
+
exports.MarketingConsentStatus = q;
|
|
452
|
+
exports.PassportError = f;
|
|
453
|
+
exports.PassportErrorType = b;
|
|
454
|
+
exports.RollupType = Q;
|
|
455
|
+
exports.TypedEventEmitter = R;
|
|
456
|
+
exports.buildLogoutUrl = z;
|
|
457
|
+
exports.decodeJwtPayload = m;
|
|
458
|
+
exports.handleLoginCallback = bt;
|
|
459
|
+
exports.isAPIError = F;
|
|
460
|
+
exports.isUserZkEvm = V;
|
|
461
|
+
exports.loginWithEmbedded = It;
|
|
462
|
+
exports.loginWithPopup = Ce;
|
|
463
|
+
exports.loginWithRedirect = kt;
|
|
464
|
+
exports.logoutSilent = Ut;
|
|
465
|
+
exports.logoutWithRedirect = At;
|
|
466
|
+
exports.withPassportError = E;
|