@imtbl/auth 2.12.7-alpha.3 → 2.12.7-alpha.4
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.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { UserManager, User, ErrorTimeout, ErrorResponse, InMemoryWebStorage, WebStorageStateStore } from 'oidc-client-ts';
|
|
2
|
-
import
|
|
2
|
+
import Ge from 'localforage';
|
|
3
3
|
import { track, identify, getDetail, Detail, trackFlow, trackError } from '@imtbl/metrics';
|
|
4
4
|
|
|
5
|
-
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
|
|
5
|
+
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=`
|
|
6
6
|
<svg
|
|
7
7
|
viewBox="0 0 20 20"
|
|
8
8
|
fill="none"
|
|
@@ -14,7 +14,7 @@ var b=(p=>(p.AUTHENTICATION_ERROR="AUTHENTICATION_ERROR",p.INVALID_CONFIGURATION
|
|
|
14
14
|
fill="#F3F3F3"
|
|
15
15
|
/>
|
|
16
16
|
</svg>
|
|
17
|
-
`,
|
|
17
|
+
`,j=`
|
|
18
18
|
<svg
|
|
19
19
|
viewBox="0 0 17 16"
|
|
20
20
|
fill="none"
|
|
@@ -28,7 +28,7 @@ var b=(p=>(p.AUTHENTICATION_ERROR="AUTHENTICATION_ERROR",p.INVALID_CONFIGURATION
|
|
|
28
28
|
fill="#E01A3D"
|
|
29
29
|
/>
|
|
30
30
|
</svg>
|
|
31
|
-
`,
|
|
31
|
+
`,G=`
|
|
32
32
|
<svg
|
|
33
33
|
style="
|
|
34
34
|
max-width: 123px !important;
|
|
@@ -211,9 +211,9 @@ var b=(p=>(p.AUTHENTICATION_ERROR="AUTHENTICATION_ERROR",p.INVALID_CONFIGURATION
|
|
|
211
211
|
</clipPath>
|
|
212
212
|
</defs>
|
|
213
213
|
</svg>
|
|
214
|
-
`;var
|
|
214
|
+
`;var Le=()=>`
|
|
215
215
|
<button
|
|
216
|
-
id="${
|
|
216
|
+
id="${A}"
|
|
217
217
|
style="
|
|
218
218
|
background: #f3f3f326 !important;
|
|
219
219
|
border: none !important;
|
|
@@ -229,11 +229,11 @@ var b=(p=>(p.AUTHENTICATION_ERROR="AUTHENTICATION_ERROR",p.INVALID_CONFIGURATION
|
|
|
229
229
|
justify-content: center !important;
|
|
230
230
|
"
|
|
231
231
|
>
|
|
232
|
-
${
|
|
232
|
+
${X}
|
|
233
233
|
</button>
|
|
234
|
-
`,
|
|
234
|
+
`,ee=()=>`
|
|
235
235
|
<button
|
|
236
|
-
id="${
|
|
236
|
+
id="${U}"
|
|
237
237
|
style="
|
|
238
238
|
margin-top: 27px !important;
|
|
239
239
|
color: #f3f3f3 !important;
|
|
@@ -248,8 +248,8 @@ var b=(p=>(p.AUTHENTICATION_ERROR="AUTHENTICATION_ERROR",p.INVALID_CONFIGURATION
|
|
|
248
248
|
>
|
|
249
249
|
Try again
|
|
250
250
|
</button>
|
|
251
|
-
`,
|
|
252
|
-
${
|
|
251
|
+
`,we=()=>`
|
|
252
|
+
${G}
|
|
253
253
|
<div
|
|
254
254
|
style="
|
|
255
255
|
color: #e01a3d !important;
|
|
@@ -259,7 +259,7 @@ var b=(p=>(p.AUTHENTICATION_ERROR="AUTHENTICATION_ERROR",p.INVALID_CONFIGURATION
|
|
|
259
259
|
margin-bottom: 10px !important;
|
|
260
260
|
"
|
|
261
261
|
>
|
|
262
|
-
${
|
|
262
|
+
${j}
|
|
263
263
|
Pop-up blocked
|
|
264
264
|
</div>
|
|
265
265
|
<p style="
|
|
@@ -272,9 +272,9 @@ var b=(p=>(p.AUTHENTICATION_ERROR="AUTHENTICATION_ERROR",p.INVALID_CONFIGURATION
|
|
|
272
272
|
If the problem continues, adjust your<br />
|
|
273
273
|
browser settings.
|
|
274
274
|
</p>
|
|
275
|
-
${
|
|
276
|
-
`,
|
|
277
|
-
${
|
|
275
|
+
${ee()}
|
|
276
|
+
`,Pe=()=>`
|
|
277
|
+
${G}
|
|
278
278
|
<p style="
|
|
279
279
|
color: #b6b6b6 !important;
|
|
280
280
|
text-align: center !important;
|
|
@@ -283,8 +283,8 @@ var b=(p=>(p.AUTHENTICATION_ERROR="AUTHENTICATION_ERROR",p.INVALID_CONFIGURATION
|
|
|
283
283
|
>
|
|
284
284
|
Secure pop-up not showing?<br />We'll help you re-launch
|
|
285
285
|
</p>
|
|
286
|
-
${
|
|
287
|
-
`,
|
|
286
|
+
${ee()}
|
|
287
|
+
`,te=n=>`
|
|
288
288
|
<div
|
|
289
289
|
id="${C}"
|
|
290
290
|
style="
|
|
@@ -309,9 +309,9 @@ var b=(p=>(p.AUTHENTICATION_ERROR="AUTHENTICATION_ERROR",p.INVALID_CONFIGURATION
|
|
|
309
309
|
z-index: 2147483647 !important;
|
|
310
310
|
"
|
|
311
311
|
>
|
|
312
|
-
${
|
|
312
|
+
${Le()}
|
|
313
313
|
<div
|
|
314
|
-
id="${
|
|
314
|
+
id="${y}"
|
|
315
315
|
style="
|
|
316
316
|
display: flex !important;
|
|
317
317
|
flex-direction: column !important;
|
|
@@ -322,7 +322,7 @@ var b=(p=>(p.AUTHENTICATION_ERROR="AUTHENTICATION_ERROR",p.INVALID_CONFIGURATION
|
|
|
322
322
|
${n??""}
|
|
323
323
|
</div>
|
|
324
324
|
</div>
|
|
325
|
-
`,
|
|
325
|
+
`,re=()=>`
|
|
326
326
|
<div
|
|
327
327
|
id="${C}"
|
|
328
328
|
style="
|
|
@@ -342,7 +342,7 @@ var b=(p=>(p.AUTHENTICATION_ERROR="AUTHENTICATION_ERROR",p.INVALID_CONFIGURATION
|
|
|
342
342
|
"
|
|
343
343
|
>
|
|
344
344
|
<div
|
|
345
|
-
id="${
|
|
345
|
+
id="${y}"
|
|
346
346
|
style="
|
|
347
347
|
display: flex;
|
|
348
348
|
flex-direction: column;
|
|
@@ -351,7 +351,7 @@ var b=(p=>(p.AUTHENTICATION_ERROR="AUTHENTICATION_ERROR",p.INVALID_CONFIGURATION
|
|
|
351
351
|
"
|
|
352
352
|
/>
|
|
353
353
|
</div>
|
|
354
|
-
`;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
|
|
354
|
+
`;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=${getDetail(Detail.RUNTIME_ID)}`;static appendIFrameStylesIfNeeded=()=>{if(document.getElementById(ie))return;let e=document.createElement("style");e.id=ie,e.textContent=`
|
|
355
355
|
@keyframes passportEmbeddedLoginPromptPopBounceIn {
|
|
356
356
|
0% {
|
|
357
357
|
opacity: 0.5;
|
|
@@ -370,7 +370,7 @@ var b=(p=>(p.AUTHENTICATION_ERROR="AUTHENTICATION_ERROR",p.INVALID_CONFIGURATION
|
|
|
370
370
|
}
|
|
371
371
|
|
|
372
372
|
@media (max-height: 400px) {
|
|
373
|
-
#${
|
|
373
|
+
#${se} {
|
|
374
374
|
width: 100% !important;
|
|
375
375
|
max-width: none !important;
|
|
376
376
|
}
|
|
@@ -384,7 +384,7 @@ var b=(p=>(p.AUTHENTICATION_ERROR="AUTHENTICATION_ERROR",p.INVALID_CONFIGURATION
|
|
|
384
384
|
opacity: 1;
|
|
385
385
|
}
|
|
386
386
|
}
|
|
387
|
-
`,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=trackFlow("passport",e,t);try{return await n(o)}catch(i){throw i instanceof Error?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.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.INDEXEDDB):typeof window<"u"?r=window.localStorage:r=new InMemoryWebStorage;let o=new 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 UserManager(ct(this.config)),this.deviceCredentialsManager=new P,this.logoutMode=this.config.oidcConfiguration.logoutMode||"redirect",this.eventEmitter=new R,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")&&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),identify({passportId:e.profile.sub});}buildExtraQueryParams(e,t){let r={...this.userManager.settings?.extraQueryParams??{},rid:getDetail(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 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 ErrorTimeout?(o="SILENT_LOGIN_ERROR",i=`${i}: ${r.message}`,s=!1):r instanceof 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=`
|
|
387
|
+
`,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=trackFlow("passport",e,t);try{return await n(o)}catch(i){throw i instanceof Error?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.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.INDEXEDDB):typeof window<"u"?r=window.localStorage:r=new InMemoryWebStorage;let o=new 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 UserManager(lt(this.config)),this.deviceCredentialsManager=new w,this.logoutMode=this.config.oidcConfiguration.logoutMode||"redirect",this.eventEmitter=new R,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")&&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),identify({passportId:e.profile.sub});}buildExtraQueryParams(e,t){let r={...this.userManager.settings?.extraQueryParams??{},rid:getDetail(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 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 ErrorTimeout?(o="SILENT_LOGIN_ERROR",i=`${i}: ${r.message}`,s=!1):r instanceof 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=`
|
|
388
388
|
@keyframes passportEmbeddedLoginPromptPopBounceIn {
|
|
389
389
|
0% {
|
|
390
390
|
opacity: 0.5;
|
|
@@ -403,7 +403,7 @@ var b=(p=>(p.AUTHENTICATION_ERROR="AUTHENTICATION_ERROR",p.INVALID_CONFIGURATION
|
|
|
403
403
|
}
|
|
404
404
|
|
|
405
405
|
@media (max-height: 400px) {
|
|
406
|
-
#${
|
|
406
|
+
#${me} {
|
|
407
407
|
width: 100% !important;
|
|
408
408
|
max-width: none !important;
|
|
409
409
|
}
|
|
@@ -417,7 +417,7 @@ var b=(p=>(p.AUTHENTICATION_ERROR="AUTHENTICATION_ERROR",p.INVALID_CONFIGURATION
|
|
|
417
417
|
opacity: 1;
|
|
418
418
|
}
|
|
419
419
|
}
|
|
420
|
-
`,document.head.appendChild(e);}function
|
|
420
|
+
`,document.head.appendChild(e);}function Lt(n,e){let t=getDetail(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=`
|
|
421
421
|
position: fixed;
|
|
422
422
|
top: 0;
|
|
423
423
|
left: 0;
|
|
@@ -431,11 +431,11 @@ var b=(p=>(p.AUTHENTICATION_ERROR="AUTHENTICATION_ERROR",p.INVALID_CONFIGURATION
|
|
|
431
431
|
background: rgba(247, 247, 247, 0.24);
|
|
432
432
|
animation-name: passportEmbeddedLoginPromptOverlayFadeIn;
|
|
433
433
|
animation-duration: 0.8s;
|
|
434
|
-
`;let e=document.createElement("div");return e.id=
|
|
434
|
+
`;let e=document.createElement("div");return e.id=y,e.style.cssText=`
|
|
435
435
|
display: flex;
|
|
436
436
|
flex-direction: column;
|
|
437
437
|
align-items: center;
|
|
438
438
|
width: 100%;
|
|
439
|
-
`,n.appendChild(e),n}function I(){document.getElementById(
|
|
439
|
+
`,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){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){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){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(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){track("passport","standaloneLogoutWithRedirect");let e=Z(n);window.location.href=e;}async function Ut(n,e=5e3){return 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);})}
|
|
440
440
|
|
|
441
|
-
export {
|
|
441
|
+
export { K as Auth, O as AuthConfiguration, V as AuthEvents, Q as MarketingConsentStatus, f as PassportError, b as PassportErrorType, J as RollupType, R as TypedEventEmitter, Z as buildLogoutUrl, m as decodeJwtPayload, bt as handleLoginCallback, H as isAPIError, F as isUserZkEvm, It as loginWithEmbedded, ye as loginWithPopup, kt as loginWithRedirect, Ut as logoutSilent, At as logoutWithRedirect, E as withPassportError };
|
package/dist/types/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
export { Auth } from './Auth';
|
|
2
2
|
export { AuthConfiguration, type IAuthConfiguration } from './config';
|
|
3
|
-
export type { User, UserProfile, UserZkEvm, DirectLoginMethod, DirectLoginOptions, LoginOptions, DeviceTokenResponse, OidcConfiguration, AuthModuleConfiguration, PopupOverlayOptions, PassportMetadata,
|
|
4
|
-
export { isUserZkEvm, RollupType,
|
|
3
|
+
export type { User, UserProfile, UserZkEvm, DirectLoginMethod, DirectLoginOptions, LoginOptions, DeviceTokenResponse, OidcConfiguration, AuthModuleConfiguration, PopupOverlayOptions, PassportMetadata, IdTokenPayload, PKCEData, AuthEventMap, UserRemovedReason, } from './types';
|
|
4
|
+
export { isUserZkEvm, RollupType, MarketingConsentStatus, AuthEvents, } from './types';
|
|
5
5
|
export { default as TypedEventEmitter } from './utils/typedEventEmitter';
|
|
6
6
|
export { PassportError, PassportErrorType, withPassportError, isAPIError, } from './errors';
|
|
7
7
|
export { decodeJwtPayload } from './utils/jwt';
|
package/dist/types/types.d.ts
CHANGED
|
@@ -13,14 +13,6 @@ export type UserProfile = {
|
|
|
13
13
|
export declare enum RollupType {
|
|
14
14
|
ZKEVM = "zkEvm"
|
|
15
15
|
}
|
|
16
|
-
/**
|
|
17
|
-
* Supported EVM chains for user registration
|
|
18
|
-
* Matches EvmChain from @imtbl/wallet but defined here to avoid circular dependency
|
|
19
|
-
*/
|
|
20
|
-
export declare enum EvmChain {
|
|
21
|
-
ZKEVM = "zkevm",
|
|
22
|
-
ARBITRUM_ONE = "arbitrum_one"
|
|
23
|
-
}
|
|
24
16
|
export type ChainAddress = {
|
|
25
17
|
ethAddress: `0x${string}`;
|
|
26
18
|
userAdminAddress: `0x${string}`;
|
|
@@ -33,22 +25,11 @@ export type User = {
|
|
|
33
25
|
profile: UserProfile;
|
|
34
26
|
expired?: boolean;
|
|
35
27
|
[RollupType.ZKEVM]?: ChainAddress;
|
|
36
|
-
} & {
|
|
37
|
-
[K in Exclude<EvmChain, EvmChain.ZKEVM>]?: ChainAddress;
|
|
38
|
-
};
|
|
39
|
-
export type PassportChainMetadata = {
|
|
40
|
-
eth_address: string;
|
|
41
|
-
user_admin_address: string;
|
|
42
28
|
};
|
|
43
|
-
/**
|
|
44
|
-
* Passport metadata
|
|
45
|
-
* - zkEVM: flat fields (zkevm_eth_address, zkevm_user_admin_address)
|
|
46
|
-
* - Other chains: nested objects (arbitrum_one: { eth_address, user_admin_address })
|
|
47
|
-
*/
|
|
48
29
|
export type PassportMetadata = {
|
|
49
30
|
zkevm_eth_address?: string;
|
|
50
31
|
zkevm_user_admin_address?: string;
|
|
51
|
-
}
|
|
32
|
+
};
|
|
52
33
|
export interface OidcConfiguration {
|
|
53
34
|
clientId: string;
|
|
54
35
|
logoutRedirectUri?: string;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@imtbl/auth",
|
|
3
|
-
"version": "2.12.7-alpha.
|
|
3
|
+
"version": "2.12.7-alpha.4",
|
|
4
4
|
"description": "Authentication SDK for Immutable",
|
|
5
5
|
"author": "Immutable",
|
|
6
6
|
"bugs": "https://github.com/immutable/ts-immutable-sdk/issues",
|
|
@@ -25,8 +25,8 @@
|
|
|
25
25
|
}
|
|
26
26
|
},
|
|
27
27
|
"dependencies": {
|
|
28
|
-
"@imtbl/generated-clients": "2.12.7-alpha.
|
|
29
|
-
"@imtbl/metrics": "2.12.7-alpha.
|
|
28
|
+
"@imtbl/generated-clients": "2.12.7-alpha.4",
|
|
29
|
+
"@imtbl/metrics": "2.12.7-alpha.4",
|
|
30
30
|
"localforage": "^1.10.0",
|
|
31
31
|
"oidc-client-ts": "3.4.1"
|
|
32
32
|
},
|
package/src/Auth.test.ts
CHANGED
|
@@ -137,7 +137,7 @@ describe('Auth', () => {
|
|
|
137
137
|
});
|
|
138
138
|
});
|
|
139
139
|
|
|
140
|
-
describe('
|
|
140
|
+
describe('username extraction', () => {
|
|
141
141
|
it('extracts username from id token when present', () => {
|
|
142
142
|
const mockOidcUser = {
|
|
143
143
|
id_token: 'token',
|
|
@@ -158,88 +158,6 @@ describe('Auth', () => {
|
|
|
158
158
|
expect(result.profile.username).toEqual('username123');
|
|
159
159
|
});
|
|
160
160
|
|
|
161
|
-
it('extracts zkEvm chain data from passport metadata', () => {
|
|
162
|
-
const mockOidcUser = {
|
|
163
|
-
id_token: 'token',
|
|
164
|
-
access_token: 'access',
|
|
165
|
-
refresh_token: 'refresh',
|
|
166
|
-
expired: false,
|
|
167
|
-
profile: { sub: 'user-123', email: 'test@example.com', nickname: 'tester' },
|
|
168
|
-
};
|
|
169
|
-
|
|
170
|
-
(decodeJwtPayload as jest.Mock).mockReturnValue({
|
|
171
|
-
passport: {
|
|
172
|
-
zkevm_eth_address: '0xzkevmaddress',
|
|
173
|
-
zkevm_user_admin_address: '0xzkevmadmin',
|
|
174
|
-
},
|
|
175
|
-
});
|
|
176
|
-
|
|
177
|
-
const result = (Auth as any).mapOidcUserToDomainModel(mockOidcUser);
|
|
178
|
-
|
|
179
|
-
expect(result.zkEvm).toEqual({
|
|
180
|
-
ethAddress: '0xzkevmaddress',
|
|
181
|
-
userAdminAddress: '0xzkevmadmin',
|
|
182
|
-
});
|
|
183
|
-
});
|
|
184
|
-
|
|
185
|
-
it('extracts arbitrum_one chain data from nested passport metadata', () => {
|
|
186
|
-
const mockOidcUser = {
|
|
187
|
-
id_token: 'token',
|
|
188
|
-
access_token: 'access',
|
|
189
|
-
refresh_token: 'refresh',
|
|
190
|
-
expired: false,
|
|
191
|
-
profile: { sub: 'user-123', email: 'test@example.com', nickname: 'tester' },
|
|
192
|
-
};
|
|
193
|
-
|
|
194
|
-
(decodeJwtPayload as jest.Mock).mockReturnValue({
|
|
195
|
-
passport: {
|
|
196
|
-
arbitrum_one: {
|
|
197
|
-
eth_address: '0xarbaddress',
|
|
198
|
-
user_admin_address: '0xarbadmin',
|
|
199
|
-
},
|
|
200
|
-
},
|
|
201
|
-
});
|
|
202
|
-
|
|
203
|
-
const result = (Auth as any).mapOidcUserToDomainModel(mockOidcUser);
|
|
204
|
-
|
|
205
|
-
expect(result.arbitrum_one).toEqual({
|
|
206
|
-
ethAddress: '0xarbaddress',
|
|
207
|
-
userAdminAddress: '0xarbadmin',
|
|
208
|
-
});
|
|
209
|
-
});
|
|
210
|
-
|
|
211
|
-
it('extracts both zkEvm and arbitrum_one when present', () => {
|
|
212
|
-
const mockOidcUser = {
|
|
213
|
-
id_token: 'token',
|
|
214
|
-
access_token: 'access',
|
|
215
|
-
refresh_token: 'refresh',
|
|
216
|
-
expired: false,
|
|
217
|
-
profile: { sub: 'user-123', email: 'test@example.com', nickname: 'tester' },
|
|
218
|
-
};
|
|
219
|
-
|
|
220
|
-
(decodeJwtPayload as jest.Mock).mockReturnValue({
|
|
221
|
-
passport: {
|
|
222
|
-
zkevm_eth_address: '0xzkevmaddress',
|
|
223
|
-
zkevm_user_admin_address: '0xzkevmadmin',
|
|
224
|
-
arbitrum_one: {
|
|
225
|
-
eth_address: '0xarbaddress',
|
|
226
|
-
user_admin_address: '0xarbadmin',
|
|
227
|
-
},
|
|
228
|
-
},
|
|
229
|
-
});
|
|
230
|
-
|
|
231
|
-
const result = (Auth as any).mapOidcUserToDomainModel(mockOidcUser);
|
|
232
|
-
|
|
233
|
-
expect(result.zkEvm).toEqual({
|
|
234
|
-
ethAddress: '0xzkevmaddress',
|
|
235
|
-
userAdminAddress: '0xzkevmadmin',
|
|
236
|
-
});
|
|
237
|
-
expect(result.arbitrum_one).toEqual({
|
|
238
|
-
ethAddress: '0xarbaddress',
|
|
239
|
-
userAdminAddress: '0xarbadmin',
|
|
240
|
-
});
|
|
241
|
-
});
|
|
242
|
-
|
|
243
161
|
it('maps username when creating OIDC user from device tokens', () => {
|
|
244
162
|
const tokenResponse = {
|
|
245
163
|
id_token: 'token',
|
package/src/Auth.ts
CHANGED
|
@@ -29,7 +29,6 @@ import {
|
|
|
29
29
|
PassportMetadata,
|
|
30
30
|
IdTokenPayload,
|
|
31
31
|
isUserZkEvm,
|
|
32
|
-
EvmChain,
|
|
33
32
|
ChainAddress,
|
|
34
33
|
} from './types';
|
|
35
34
|
import EmbeddedLoginPrompt from './login/embeddedLoginPrompt';
|
|
@@ -570,19 +569,9 @@ export class Auth {
|
|
|
570
569
|
username,
|
|
571
570
|
},
|
|
572
571
|
};
|
|
573
|
-
|
|
574
572
|
if (passport?.zkevm_eth_address && passport?.zkevm_user_admin_address) {
|
|
575
573
|
user.zkEvm = toChainAddress(passport.zkevm_eth_address, passport.zkevm_user_admin_address);
|
|
576
574
|
}
|
|
577
|
-
|
|
578
|
-
const chains = Object.values(EvmChain).filter((chain) => chain !== EvmChain.ZKEVM);
|
|
579
|
-
for (const chain of chains) {
|
|
580
|
-
const chainMetadata = passport?.[chain as Exclude<EvmChain, EvmChain.ZKEVM>];
|
|
581
|
-
if (chainMetadata?.eth_address && chainMetadata?.user_admin_address) {
|
|
582
|
-
user[chain] = toChainAddress(chainMetadata.eth_address, chainMetadata.user_admin_address);
|
|
583
|
-
}
|
|
584
|
-
}
|
|
585
|
-
|
|
586
575
|
return user;
|
|
587
576
|
};
|
|
588
577
|
|
package/src/index.ts
CHANGED
|
@@ -17,20 +17,13 @@ export type {
|
|
|
17
17
|
AuthModuleConfiguration,
|
|
18
18
|
PopupOverlayOptions,
|
|
19
19
|
PassportMetadata,
|
|
20
|
-
PassportChainMetadata,
|
|
21
|
-
ChainAddress,
|
|
22
|
-
ZkEvmInfo,
|
|
23
20
|
IdTokenPayload,
|
|
24
21
|
PKCEData,
|
|
25
22
|
AuthEventMap,
|
|
26
23
|
UserRemovedReason,
|
|
27
24
|
} from './types';
|
|
28
25
|
export {
|
|
29
|
-
isUserZkEvm,
|
|
30
|
-
RollupType,
|
|
31
|
-
EvmChain,
|
|
32
|
-
MarketingConsentStatus,
|
|
33
|
-
AuthEvents,
|
|
26
|
+
isUserZkEvm, RollupType, MarketingConsentStatus, AuthEvents,
|
|
34
27
|
} from './types';
|
|
35
28
|
|
|
36
29
|
// Export TypedEventEmitter
|
package/src/types.ts
CHANGED
|
@@ -16,15 +16,6 @@ export enum RollupType {
|
|
|
16
16
|
ZKEVM = 'zkEvm',
|
|
17
17
|
}
|
|
18
18
|
|
|
19
|
-
/**
|
|
20
|
-
* Supported EVM chains for user registration
|
|
21
|
-
* Matches EvmChain from @imtbl/wallet but defined here to avoid circular dependency
|
|
22
|
-
*/
|
|
23
|
-
export enum EvmChain {
|
|
24
|
-
ZKEVM = 'zkevm',
|
|
25
|
-
ARBITRUM_ONE = 'arbitrum_one',
|
|
26
|
-
}
|
|
27
|
-
|
|
28
19
|
export type ChainAddress = {
|
|
29
20
|
ethAddress: `0x${string}`;
|
|
30
21
|
userAdminAddress: `0x${string}`;
|
|
@@ -39,24 +30,12 @@ export type User = {
|
|
|
39
30
|
profile: UserProfile;
|
|
40
31
|
expired?: boolean;
|
|
41
32
|
[RollupType.ZKEVM]?: ChainAddress;
|
|
42
|
-
} & {
|
|
43
|
-
[K in Exclude<EvmChain, EvmChain.ZKEVM>]?: ChainAddress;
|
|
44
33
|
};
|
|
45
34
|
|
|
46
|
-
export type PassportChainMetadata = {
|
|
47
|
-
eth_address: string;
|
|
48
|
-
user_admin_address: string;
|
|
49
|
-
};
|
|
50
|
-
|
|
51
|
-
/**
|
|
52
|
-
* Passport metadata
|
|
53
|
-
* - zkEVM: flat fields (zkevm_eth_address, zkevm_user_admin_address)
|
|
54
|
-
* - Other chains: nested objects (arbitrum_one: { eth_address, user_admin_address })
|
|
55
|
-
*/
|
|
56
35
|
export type PassportMetadata = {
|
|
57
36
|
zkevm_eth_address?: string;
|
|
58
37
|
zkevm_user_admin_address?: string;
|
|
59
|
-
}
|
|
38
|
+
};
|
|
60
39
|
|
|
61
40
|
export interface OidcConfiguration {
|
|
62
41
|
clientId: string;
|