@block-auth.io/core 0.11.1 → 0.12.0

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/index.js CHANGED
@@ -16,13 +16,11 @@ var __export = (target, all) => {
16
16
  };
17
17
 
18
18
  // src/utils/apiBridge.ts
19
- var DEFAULT_API_URL = "https://api.block-auth.io";
20
19
  function buildApiUrl(path, apiUrl) {
21
- const base = (apiUrl || DEFAULT_API_URL).replace(/\/+$/, "");
22
- return `${base}${path}`;
20
+ return `${apiUrl.replace(/\/+$/, "")}${path}`;
23
21
  }
24
22
  async function bridgeSessionCookie(token, apiUrl) {
25
- if (!token || typeof fetch === "undefined") return false;
23
+ if (!apiUrl || !token || typeof fetch === "undefined") return false;
26
24
  try {
27
25
  const response = await fetch(buildApiUrl("/auth/session", apiUrl), {
28
26
  method: "POST",
@@ -37,7 +35,7 @@ async function bridgeSessionCookie(token, apiUrl) {
37
35
  }
38
36
  }
39
37
  async function clearSessionCookie(apiUrl) {
40
- if (typeof fetch === "undefined") return false;
38
+ if (!apiUrl || typeof fetch === "undefined") return false;
41
39
  try {
42
40
  const response = await fetch(buildApiUrl("/auth/logout", apiUrl), {
43
41
  method: "POST",
@@ -50,7 +48,9 @@ async function clearSessionCookie(apiUrl) {
50
48
  }
51
49
  }
52
50
  async function requestWsTicket(apiUrl) {
53
- if (typeof fetch === "undefined") return { ticket: null, refused: false };
51
+ if (!apiUrl || typeof fetch === "undefined") {
52
+ return { ticket: null, refused: false };
53
+ }
54
54
  try {
55
55
  const response = await fetch(buildApiUrl("/auth/ws-ticket", apiUrl), {
56
56
  method: "GET",
@@ -81,14 +81,11 @@ function buildWsServerApiUrl(path, wsUrl) {
81
81
  async function fetchBrowserToken(apiKey, wsUrl) {
82
82
  if (!apiKey || typeof fetch === "undefined") return null;
83
83
  try {
84
- const response = await fetch(
85
- buildWsServerApiUrl("/browser-token", wsUrl),
86
- {
87
- method: "POST",
88
- headers: { "Content-Type": "application/json" },
89
- body: JSON.stringify({ apiKey })
90
- }
91
- );
84
+ const response = await fetch(buildWsServerApiUrl("/browser-token", wsUrl), {
85
+ method: "POST",
86
+ headers: { "Content-Type": "application/json" },
87
+ body: JSON.stringify({ apiKey })
88
+ });
92
89
  const payload = await response.json();
93
90
  if (!response.ok || !payload?.success) return null;
94
91
  return payload.message?.accessToken || null;
@@ -119,6 +116,7 @@ var WsClient = class {
119
116
  this._roles = [];
120
117
  this._logs = [];
121
118
  this._kycIssuerByAddress = {};
119
+ this._connecting = null;
122
120
  this._wsUrl = url || "wss://wss.block-auth.io/";
123
121
  this._apiUrl = apiUrl;
124
122
  this._wsConfig = {
@@ -150,6 +148,14 @@ var WsClient = class {
150
148
  * @returns Promise<void>
151
149
  */
152
150
  async connect(url = "", waitMs = 5e3, retries = 3) {
151
+ if (this.isConnected()) return;
152
+ if (this._connecting) return this._connecting;
153
+ this._connecting = this._doConnect(url, waitMs, retries).finally(() => {
154
+ this._connecting = null;
155
+ });
156
+ return this._connecting;
157
+ }
158
+ async _doConnect(url, waitMs, retries) {
153
159
  const _url = url || this._wsUrl;
154
160
  this._wsConfig.auth = (done) => {
155
161
  fetchWsTicket(this._apiUrl).then((ticket) => done(ticket ? { ticket } : {})).catch(() => done({}));
@@ -995,6 +1001,7 @@ var initial2 = {
995
1001
  isSigned: false,
996
1002
  isSigningLoader: false,
997
1003
  isAcceptingTxn: false,
1004
+ isRejectingTxn: false,
998
1005
  acceptTxnError: null,
999
1006
  waitingForSuccessLogInSince: 0,
1000
1007
  isOtpRequired: false,
@@ -1014,6 +1021,7 @@ var setIsSigning = (v) => $ui.setKey("isSigning", v);
1014
1021
  var setIsSigned = (v) => $ui.setKey("isSigned", v);
1015
1022
  var setIsSigningLoader = (v) => $ui.setKey("isSigningLoader", v);
1016
1023
  var setIsAcceptingTxn = (v) => $ui.setKey("isAcceptingTxn", v);
1024
+ var setIsRejectingTxn = (v) => $ui.setKey("isRejectingTxn", v);
1017
1025
  var setAcceptTxnError = (v) => $ui.setKey("acceptTxnError", v);
1018
1026
  var setWaitingForSuccessLogInSince = (v) => $ui.setKey("waitingForSuccessLogInSince", v);
1019
1027
  var setIsOtpRequired = (v) => $ui.setKey("isOtpRequired", v);
@@ -2080,21 +2088,147 @@ function connectBlockAuth(apiUrl) {
2080
2088
  requestExtensionStateSync();
2081
2089
  }
2082
2090
 
2083
- // src/auth/logout.ts
2084
- async function performLogout(args) {
2085
- const { wsc, token, apiKey, sessionId, apiUrl } = args;
2086
- await new Promise((resolve) => {
2091
+ // src/auth/popupSize.ts
2092
+ var LOGIN_POPUP_WIDTH = 380;
2093
+ var LOGIN_POPUP_HEIGHT = 640;
2094
+
2095
+ // src/auth/loginWithPopup.ts
2096
+ var AUTH_CODE_MESSAGE = "blockauth:auth-code";
2097
+ var POPUP_CLOSED_POLL_MS = 500;
2098
+ var LOGIN_TIMEOUT_MS = 15 * 60 * 1e3;
2099
+ function base64url(bytes) {
2100
+ let binary = "";
2101
+ for (const b of bytes) binary += String.fromCharCode(b);
2102
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
2103
+ }
2104
+ function randomString(byteLength) {
2105
+ return base64url(crypto.getRandomValues(new Uint8Array(byteLength)));
2106
+ }
2107
+ async function sha256Base64url(value) {
2108
+ const digest = await crypto.subtle.digest(
2109
+ "SHA-256",
2110
+ new TextEncoder().encode(value)
2111
+ );
2112
+ return base64url(new Uint8Array(digest));
2113
+ }
2114
+ async function postWsServer(path, body, wsUrl) {
2115
+ const response = await fetch(buildWsServerApiUrl(path, wsUrl), {
2116
+ method: "POST",
2117
+ headers: { "Content-Type": "application/json" },
2118
+ body: JSON.stringify(body)
2119
+ });
2120
+ const payload = await response.json();
2121
+ if (!response.ok || !payload?.success) {
2122
+ const reason = typeof payload?.message === "string" ? payload.message : "Login failed";
2123
+ throw new Error(reason);
2124
+ }
2125
+ return payload.message;
2126
+ }
2127
+ function waitForCode(popup, authOrigin, state) {
2128
+ return new Promise((resolve, reject) => {
2087
2129
  let done = false;
2088
- const finish = () => {
2089
- if (!done) {
2090
- done = true;
2091
- resolve();
2092
- }
2130
+ const finish = (error, code) => {
2131
+ if (done) return;
2132
+ done = true;
2133
+ window.removeEventListener("message", onMessage);
2134
+ clearInterval(closedPoll);
2135
+ clearTimeout(timeout);
2136
+ if (error) reject(error);
2137
+ else resolve(code);
2138
+ };
2139
+ const onMessage = (event) => {
2140
+ if (event.origin !== authOrigin || event.source !== popup) return;
2141
+ const data = event.data;
2142
+ if (data?.type !== AUTH_CODE_MESSAGE || data.state !== state) return;
2143
+ if (data.code) finish(null, data.code);
2093
2144
  };
2094
- wsc.ws?.once?.("signout", finish);
2095
- wsc.emit("signout", { token, apiKey, sessionId });
2096
- setTimeout(finish, 1500);
2145
+ window.addEventListener("message", onMessage);
2146
+ const closedPoll = setInterval(() => {
2147
+ if (!popup.closed) return;
2148
+ setTimeout(
2149
+ () => finish(new Error("Login window closed")),
2150
+ POPUP_CLOSED_POLL_MS
2151
+ );
2152
+ }, POPUP_CLOSED_POLL_MS);
2153
+ const timeout = setTimeout(
2154
+ () => finish(new Error("Login timed out")),
2155
+ LOGIN_TIMEOUT_MS
2156
+ );
2097
2157
  });
2158
+ }
2159
+ function popupFeatures() {
2160
+ const left = Math.max(
2161
+ 0,
2162
+ Math.round(window.screenX + (window.outerWidth - LOGIN_POPUP_WIDTH) / 2)
2163
+ );
2164
+ const top = Math.max(
2165
+ 0,
2166
+ Math.round(window.screenY + (window.outerHeight - LOGIN_POPUP_HEIGHT) / 2)
2167
+ );
2168
+ return `popup,width=${LOGIN_POPUP_WIDTH},height=${LOGIN_POPUP_HEIGHT},left=${left},top=${top}`;
2169
+ }
2170
+ async function runAuthorize(options) {
2171
+ const popup = window.open("about:blank", "blockauth-login", popupFeatures());
2172
+ if (!popup) throw new Error("Login popup blocked");
2173
+ const redirectUri = `${window.location.origin}/`;
2174
+ try {
2175
+ const codeVerifier = randomString(32);
2176
+ const state = randomString(16);
2177
+ const codeChallenge = await sha256Base64url(codeVerifier);
2178
+ const { url } = await postWsServer(
2179
+ "/auth/authorize",
2180
+ { apiKey: options.apiKey, redirectUri, state, codeChallenge },
2181
+ options.wsUrl
2182
+ );
2183
+ popup.location.href = url;
2184
+ const code = await waitForCode(popup, new URL(url).origin, state);
2185
+ return { code, codeVerifier, redirectUri };
2186
+ } catch (error) {
2187
+ popup.close();
2188
+ throw error;
2189
+ }
2190
+ }
2191
+ var inFlight = null;
2192
+ var loginInFlight = null;
2193
+ function authorizeWithPopup(options) {
2194
+ inFlight ?? (inFlight = runAuthorize(options).finally(() => {
2195
+ inFlight = null;
2196
+ }));
2197
+ return inFlight;
2198
+ }
2199
+ function loginWithPopup(options) {
2200
+ loginInFlight ?? (loginInFlight = authorizeWithPopup(options).then(
2201
+ ({ code, codeVerifier, redirectUri }) => postWsServer(
2202
+ "/auth/token",
2203
+ { apiKey: options.apiKey, code, redirectUri, codeVerifier },
2204
+ options.wsUrl
2205
+ )
2206
+ ).finally(() => {
2207
+ loginInFlight = null;
2208
+ }));
2209
+ return loginInFlight;
2210
+ }
2211
+
2212
+ // src/auth/logout.ts
2213
+ async function performLogout(args) {
2214
+ const { wsc, token, apiKey, sessionId, apiUrl } = args;
2215
+ if (apiUrl) {
2216
+ await new Promise((resolve) => {
2217
+ let done = false;
2218
+ const finish = () => {
2219
+ if (!done) {
2220
+ done = true;
2221
+ resolve();
2222
+ }
2223
+ };
2224
+ wsc.ws?.once?.("signout", finish);
2225
+ wsc.emit("signout", { token, apiKey, sessionId });
2226
+ setTimeout(finish, 1500);
2227
+ });
2228
+ } else {
2229
+ resetUser();
2230
+ browserBase.reset("session");
2231
+ }
2098
2232
  if (typeof localStorage !== "undefined") {
2099
2233
  localStorage.setItem("blockauth-logged-out", "true");
2100
2234
  }
@@ -2329,6 +2463,19 @@ async function signInWithMicrosoft(overrides = {}) {
2329
2463
  setServiceIcon(imgUrlByService("microsoft"));
2330
2464
  return { accessToken: response.accessToken, response };
2331
2465
  }
2466
+ function rememberHostedLogin(result) {
2467
+ const did = result.did ?? result.address;
2468
+ browserBase.setSession({ did, serviceName: "blockauth" });
2469
+ setUser({
2470
+ address: result.address,
2471
+ did,
2472
+ roles: result.roles ?? []
2473
+ });
2474
+ setServiceName("blockauth");
2475
+ setIsServiceConnected(true);
2476
+ setIsSigned(true);
2477
+ setIsSignedFirstCheck(true);
2478
+ }
2332
2479
  function createBlockAuthClient(config3) {
2333
2480
  if (config3.locale) setLocale(config3.locale);
2334
2481
  const provider = new BlockAuthProvider(
@@ -2373,13 +2520,15 @@ function createBlockAuthClient(config3) {
2373
2520
  const ext = browserBase.getExternalService();
2374
2521
  return ext.service !== "blockauth" ? ext.token ?? "" : s.token ?? "";
2375
2522
  }
2523
+ let runtimeBridge = null;
2376
2524
  return {
2377
2525
  state: {
2378
2526
  $ws,
2379
2527
  $ui,
2380
2528
  $wallet,
2381
2529
  $openModals,
2382
- $user
2530
+ $user,
2531
+ $extension
2383
2532
  },
2384
2533
  /** App apiKey from client config (also seeded into $ws). */
2385
2534
  apiKey: config3.apiKey,
@@ -2406,6 +2555,23 @@ function createBlockAuthClient(config3) {
2406
2555
  // BlockAuth extension connect (sets blockauth as the active service);
2407
2556
  // the txn-signing flow is driven by the caller via requestSignin.
2408
2557
  connectBlockAuth: () => connectBlockAuth(config3.apiUrl),
2558
+ // Login for an app without a backend: hosted login in a popup, PKCE
2559
+ // instead of the apiSecret (see auth/loginWithPopup.ts). Call it from a
2560
+ // click handler.
2561
+ loginWithPopup: async () => {
2562
+ const result = await loginWithPopup({
2563
+ apiKey: config3.apiKey,
2564
+ wsUrl: config3.wsUrl
2565
+ });
2566
+ rememberHostedLogin(result);
2567
+ return result;
2568
+ },
2569
+ // Same popup, but the code goes to the app's backend, which redeems it
2570
+ // with its apiSecret (see PopupAuthCode). Call it from a click handler.
2571
+ authorizeWithPopup: () => authorizeWithPopup({ apiKey: config3.apiKey, wsUrl: config3.wsUrl }),
2572
+ // After the backend redeemed the code: shows the user in the page's UI
2573
+ // (profile dropdown, roles). The backend's answer is the source of truth.
2574
+ rememberHostedLogin: (user) => rememberHostedLogin(user),
2409
2575
  // oauth
2410
2576
  oauth: {
2411
2577
  ...oauth_exports,
@@ -2446,10 +2612,13 @@ function createBlockAuthClient(config3) {
2446
2612
  }),
2447
2613
  // transaction accept/reject
2448
2614
  txns: {
2449
- reject: () => rejectTxn({
2450
- wsc: provider.wsc,
2451
- token: userToken()
2452
- }),
2615
+ reject: () => {
2616
+ setIsRejectingTxn(true);
2617
+ rejectTxn({
2618
+ wsc: provider.wsc,
2619
+ token: userToken()
2620
+ });
2621
+ },
2453
2622
  accept: (opts) => acceptTxn({
2454
2623
  wsc: provider.wsc,
2455
2624
  token: userToken(),
@@ -2489,6 +2658,10 @@ function createBlockAuthClient(config3) {
2489
2658
  openModal,
2490
2659
  closeModal,
2491
2660
  closeAllModals,
2661
+ registerRuntime: (bridge) => {
2662
+ runtimeBridge = bridge;
2663
+ },
2664
+ switchAccount: () => runtimeBridge?.switchAccount() ?? Promise.resolve(),
2492
2665
  // opciones del connect inicial del WS (las consume createAuthRuntime)
2493
2666
  wsConnectTimeout: config3.wsConnectTimeout ?? 300,
2494
2667
  wsConnectRetries: config3.wsConnectRetries ?? 3,
@@ -2863,6 +3036,87 @@ var undoSolicitedValue = (form, item) => ({
2863
3036
  shared: (item.value ?? "").trim() ? form.shared : omitKey(form.shared, item.slug)
2864
3037
  });
2865
3038
 
3039
+ // src/auth/redirectPopup.ts
3040
+ var AUTH_CODE_MESSAGE2 = "blockauth:auth-code";
3041
+ function centeredPopupFeatures(width, height) {
3042
+ const base = `popup,width=${width},height=${height}`;
3043
+ if (typeof window === "undefined") return base;
3044
+ const screenLeft = window.screenLeft ?? window.screenX ?? 0;
3045
+ const screenTop = window.screenTop ?? window.screenY ?? 0;
3046
+ const viewportWidth = window.innerWidth || document.documentElement?.clientWidth || window.screen?.width || width;
3047
+ const viewportHeight = window.innerHeight || document.documentElement?.clientHeight || window.screen?.height || height;
3048
+ const left = Math.max(
3049
+ 0,
3050
+ Math.round(screenLeft + (viewportWidth - width) / 2)
3051
+ );
3052
+ const top = Math.max(
3053
+ 0,
3054
+ Math.round(screenTop + (viewportHeight - height) / 2)
3055
+ );
3056
+ return `${base},left=${left},top=${top}`;
3057
+ }
3058
+ function openLoginPopup({
3059
+ url,
3060
+ expectedOrigin,
3061
+ timeoutMs = 3e5,
3062
+ windowName = "blockauth-login",
3063
+ windowFeatures,
3064
+ width = LOGIN_POPUP_WIDTH,
3065
+ height = LOGIN_POPUP_HEIGHT
3066
+ }) {
3067
+ return new Promise((resolve, reject) => {
3068
+ if (typeof window === "undefined" || typeof window.open !== "function") {
3069
+ reject(new Error("Popup login is only available in a browser"));
3070
+ return;
3071
+ }
3072
+ const features = windowFeatures ?? centeredPopupFeatures(width, height);
3073
+ const popup = window.open(url, windowName, features);
3074
+ if (!popup) {
3075
+ reject(new Error("Popup blocked"));
3076
+ return;
3077
+ }
3078
+ let settled = false;
3079
+ let closedTimer = null;
3080
+ let timeoutTimer = null;
3081
+ const cleanup = () => {
3082
+ window.removeEventListener("message", onMessage);
3083
+ if (closedTimer !== null) clearInterval(closedTimer);
3084
+ if (timeoutTimer !== null) clearTimeout(timeoutTimer);
3085
+ };
3086
+ const finish = (action) => {
3087
+ if (settled) return;
3088
+ settled = true;
3089
+ cleanup();
3090
+ action();
3091
+ };
3092
+ const onMessage = (event) => {
3093
+ if (event.origin !== expectedOrigin) return;
3094
+ if (event.source !== popup) return;
3095
+ const data = event.data;
3096
+ if (!data || data.type !== AUTH_CODE_MESSAGE2) return;
3097
+ if (typeof data.code !== "string" || typeof data.state !== "string") {
3098
+ finish(() => reject(new Error("Malformed auth code message")));
3099
+ return;
3100
+ }
3101
+ finish(
3102
+ () => resolve({ code: data.code, state: data.state })
3103
+ );
3104
+ };
3105
+ window.addEventListener("message", onMessage);
3106
+ closedTimer = setInterval(() => {
3107
+ if (popup.closed) {
3108
+ finish(() => reject(new Error("Login popup closed")));
3109
+ }
3110
+ }, 500);
3111
+ timeoutTimer = setTimeout(() => {
3112
+ finish(() => {
3113
+ if (!popup.closed) popup.close();
3114
+ reject(new Error("Login popup timed out"));
3115
+ });
3116
+ }, timeoutMs);
3117
+ });
3118
+ }
3119
+
2866
3120
  // src/session/sessionExpired.ts
2867
3121
  var USER_SESSION_REQUIRED = "USER_SESSION_REQUIRED";
2868
3122
  var SESSION_EXPIRED_MARK = "blockauth-session-expired";
@@ -2909,8 +3163,8 @@ function createAuthRuntime(client, callbacks = {}) {
2909
3163
  let unsignTimeout = null;
2910
3164
  let signinTimeout = null;
2911
3165
  const wsc = () => provider.wsc;
2912
- const emitSdkSign = (token, address) => {
2913
- wsc().emit("sdk:sign", { token, address });
3166
+ const emitSdkSign = (token, address, afterSign = false) => {
3167
+ wsc().emit("sdk:sign", { token, address, afterSign });
2914
3168
  };
2915
3169
  const ownTxnItems = (items) => {
2916
3170
  const apiKey = client.apiKey;
@@ -2945,6 +3199,8 @@ function createAuthRuntime(client, callbacks = {}) {
2945
3199
  });
2946
3200
  const onLogout = callbacks.onLogout ?? (async () => {
2947
3201
  });
3202
+ const onCancel = callbacks.onCancel ?? (async () => {
3203
+ });
2948
3204
  const _onSuccess = async (address) => {
2949
3205
  deletion.resetHandlingState();
2950
3206
  await onSuccess(address);
@@ -3282,7 +3538,10 @@ function createAuthRuntime(client, callbacks = {}) {
3282
3538
  hookState.pendingSignin = null;
3283
3539
  hookState.pendingTxnId = null;
3284
3540
  hookState.settledAttemptId = hookState.signinAttemptId;
3285
- if (!hookState.isSigned) closeAllModals();
3541
+ if (!hookState.isSigned) {
3542
+ closeAllModals();
3543
+ void onCancel();
3544
+ }
3286
3545
  return;
3287
3546
  }
3288
3547
  if (hookState.settledAttemptId === hookState.signinAttemptId) {
@@ -3293,18 +3552,24 @@ function createAuthRuntime(client, callbacks = {}) {
3293
3552
  hookState.pendingSignin = null;
3294
3553
  const willVerifySign = outcome === "resolved" && !hookState.isSigned && !!pendingSignin;
3295
3554
  if (willVerifySign) {
3296
- emitSdkSign(pendingSignin.accessToken, pendingSignin.did);
3555
+ emitSdkSign(pendingSignin.accessToken, pendingSignin.did, true);
3297
3556
  } else if (!hookState.isSigned) {
3298
3557
  closeAllModals();
3299
3558
  }
3300
3559
  };
3560
+ const consumePendingReject = () => {
3561
+ if (!$ui.get().isRejectingTxn) return false;
3562
+ setIsRejectingTxn(false);
3563
+ settleSigningAttempt("cancelled");
3564
+ return true;
3565
+ };
3301
3566
  const onUserTxns = async (data) => {
3302
3567
  const { success, message } = data;
3303
3568
  if (!success) return;
3304
3569
  const items = ownTxnItems(message.items ?? []);
3305
3570
  captureOwnTxnId(items);
3306
3571
  const hasInitialTxns = items.some((item) => item.state === "initial");
3307
- if (!hasInitialTxns) {
3572
+ if (!hasInitialTxns && !consumePendingReject()) {
3308
3573
  settleSigningAttempt("resolved");
3309
3574
  }
3310
3575
  setRequests(items);
@@ -3315,7 +3580,7 @@ function createAuthRuntime(client, callbacks = {}) {
3315
3580
  const items = ownTxnItems(message.items ?? []);
3316
3581
  captureOwnTxnId(items);
3317
3582
  const hasInitialTxns = items.some((item) => item.state === "initial");
3318
- if (!hasInitialTxns) {
3583
+ if (!hasInitialTxns && !consumePendingReject()) {
3319
3584
  const txnId = hookState.pendingTxnId;
3320
3585
  const wasCancelled = txnId != null && !items.some((item) => item.id === txnId);
3321
3586
  settleSigningAttempt(
@@ -3327,6 +3592,7 @@ function createAuthRuntime(client, callbacks = {}) {
3327
3592
  const onUserTxnsCreate = async (data) => {
3328
3593
  const { success, message } = data;
3329
3594
  if (success) {
3595
+ setIsRejectingTxn(false);
3330
3596
  setIsSigning(true);
3331
3597
  hookState.isSigning = true;
3332
3598
  const attemptId = ++hookState.signinAttemptId;
@@ -3375,6 +3641,7 @@ function createAuthRuntime(client, callbacks = {}) {
3375
3641
  setToken(_token);
3376
3642
  setIsSigned(success);
3377
3643
  hookState.isSigned = success;
3644
+ if (success) setIsAcceptingTxn(false);
3378
3645
  if (success) clearSessionExpiredMark();
3379
3646
  if (success && hookState.isUnsignTimeoutSet && message?.signedExpiredAt) {
3380
3647
  rearmUnsignTimeout(message.signedExpiredAt, _did);
@@ -3543,10 +3810,10 @@ function createAuthRuntime(client, callbacks = {}) {
3543
3810
  _token = externalService.token;
3544
3811
  _did = externalService.did;
3545
3812
  }
3546
- setDid(_did);
3547
- setToken(_token);
3548
- setApiKey(client.apiKey ?? $ws.get().apiKey);
3549
3813
  const isLoggedOut = typeof localStorage !== "undefined" && localStorage.getItem("blockauth-logged-out") === "true";
3814
+ setDid(isLoggedOut ? null : _did);
3815
+ setToken(isLoggedOut ? "" : _token);
3816
+ setApiKey(client.apiKey ?? $ws.get().apiKey);
3550
3817
  setIsServiceConnected(isLoggedOut ? false : externalService.connected);
3551
3818
  setServiceName(externalService.service);
3552
3819
  setServiceIcon(imgUrlByService(externalService.service));
@@ -3660,7 +3927,46 @@ function createAuthRuntime(client, callbacks = {}) {
3660
3927
  const logout = async () => {
3661
3928
  await _onLogout();
3662
3929
  };
3663
- return { start, stop, logout };
3930
+ const switchAccount = async () => {
3931
+ if (hookState.isLoggingOut) return;
3932
+ if (unsignTimeout) {
3933
+ clearTimeout(unsignTimeout);
3934
+ unsignTimeout = null;
3935
+ }
3936
+ if (signinTimeout) {
3937
+ clearTimeout(signinTimeout);
3938
+ signinTimeout = null;
3939
+ }
3940
+ if (getUserTxnsInterval) {
3941
+ clearInterval(getUserTxnsInterval);
3942
+ getUserTxnsInterval = null;
3943
+ }
3944
+ hookState.isUnsignTimeoutSet = false;
3945
+ hookState.isSigning = false;
3946
+ hookState.pendingSignin = null;
3947
+ hookState.pendingTxnId = null;
3948
+ hookState.settledAttemptId = hookState.signinAttemptId;
3949
+ setIsSigning(false);
3950
+ setIsSigningLoader(false);
3951
+ setIsAcceptingTxn(false);
3952
+ setIsOtpRequired(false);
3953
+ setWaitingForSuccessLogInSince(0);
3954
+ closeAllModals();
3955
+ openModal("signup");
3956
+ const s = browserBase.getSession();
3957
+ const ext = browserBase.getExternalService();
3958
+ const token = ext.service !== "blockauth" ? ext.token : s.token;
3959
+ const apiKey = $ws.get().apiKey ?? client.apiKey;
3960
+ const sessionId = browserBase.getDeviceSessionId();
3961
+ await performLogout({
3962
+ wsc: wsc(),
3963
+ token: token ?? "",
3964
+ apiKey,
3965
+ sessionId,
3966
+ apiUrl: client.apiUrl
3967
+ });
3968
+ };
3969
+ return { start, stop, logout, switchAccount };
3664
3970
  }
3665
3971
  function deepLinkFor(service, domain) {
3666
3972
  switch (service) {
@@ -3735,6 +4041,7 @@ var TEXTS = {
3735
4041
  solicitedData: { es: "Datos solicitados", en: "Solicited data" },
3736
4042
  reject: { es: "RECHAZAR", en: "REJECT" },
3737
4043
  accept: { es: "ACEPTAR", en: "ACCEPT" },
4044
+ useAnotherAccount: { es: "Usar otra cuenta", en: "Use another account" },
3738
4045
  iAuthorizeThe: { es: "Autorizo la", en: "I authorize the" },
3739
4046
  privacyPolicy: { es: "Pol\xEDtica de Privacidad", en: "Privacy Policy" },
3740
4047
  andThe: { es: "y los", en: "and the" },
@@ -3778,6 +4085,7 @@ var TEXTS = {
3778
4085
  },
3779
4086
  clearField: { es: "Limpiar campo", en: "Clear field" },
3780
4087
  acceptData: { es: "Aceptar", en: "Accept" },
4088
+ cancelData: { es: "Cancelar", en: "Cancel" },
3781
4089
  noTransactionsFound: {
3782
4090
  es: "No se encontraron transacciones",
3783
4091
  en: "No transactions found"
@@ -3838,7 +4146,10 @@ var TEXTS = {
3838
4146
  en: "Enter a valid phone number"
3839
4147
  },
3840
4148
  phoneCountry: { es: "Pa\xEDs", en: "Country" },
3841
- searchPhoneCountry: { es: "Buscar pa\xEDs o prefijo", en: "Search country or code" },
4149
+ searchPhoneCountry: {
4150
+ es: "Buscar pa\xEDs o prefijo",
4151
+ en: "Search country or code"
4152
+ },
3842
4153
  noPhoneCountryResults: {
3843
4154
  es: "No hay pa\xEDses que coincidan",
3844
4155
  en: "No matching countries"
@@ -3863,6 +4174,6 @@ function t(key, locale = "en") {
3863
4174
  return entry?.[locale] ?? entry?.en ?? key;
3864
4175
  }
3865
4176
 
3866
- export { $extension, $locale, $openModals, $ui, $user, $wallet, $web3, $ws, BlockAuthProvider, DEFAULT_PHONE_COUNTRY, DISCOVERY_TIMEOUT_MS, EMPTY_SOLICITED_DATA_FORM, PARAM_DISPLAY_FORMATTERS, PARAM_DISPLAY_ORDER, PARAM_ERROR_KEYS, PARAM_INPUT_TYPE, PARAM_LABEL_KEYS, PARAM_NORMALIZERS, PARAM_VALIDATORS, RpcClient, SDK_PAGE_MARKER, SYNC_TIMEOUT_MS, TEXTS, WsClient, appearsExtensionInstalled, buildPhoneE164, buildPhoneValue, clearExtensionDomMarkers, clearRemainingAuthData, clearSdkPresence, closeAllModals, closeModal, confirmExtensionPresence, createAuthRuntime, createBlockAuthClient, createDeletionService, createEvmWallet, createSolanaWallet, deepLinkFor, discoverExtensionOnce, fetchUserProfile, finalizeAfterRestorationExpired, formatParamValue, formatPhoneForDisplay, getDefaultPhoneCountry, getExtensionStoreUrl, getPhoneCountries, getPhoneCountryFlag, getPhoneDialCode, getSolicitedAcceptParams, getSolicitedFields, getSolicitedHintKey, getSolicitedParams, getUserRoleNames, getUserRoleSlugs, getUserRoles, handleRestorationExpired, handleRestoreFailure, hasAnyRole, hasAnyRoleBySlug, hasRole, hasRoleBySlug, isExtensionPresent, isExtensionStateComplete, isFirefox, isModalOpen, isPhoneCountry, isRestorationExpiredMessage, isSdkPage, isShowSignin, isSolicitedDataComplete, isSolicitedHintSuccess, isValidParamValue, isValidPhoneValue, loadUserProfile, makeQrDataUrl, markSdkPresence, needsExtensionUnlock, normalizeParamValue, oauth_exports as oauth, onExtensionRemoved, onExtensionStatePublished, openExtensionOnTxn, openModal, parsePhoneValue, probeExtensionPresence, reconcileExtensionState, requestExtensionRefresh, requestExtensionStateSync, requestSdkRestore, resetExtension, resetExtensionAbsentState, resetExtensionSyncModuleState, resetUi, resetUser, resetWallet, resetWeb3, resetWs, resolvePhoneDraft, saveSolicitedValue, searchPhoneCountries, setAcceptTxnError, setApiKey, setBackendMessage, setDeletionAddress, setDid, setExtensionInstalled, setExtensionIsLocked, setExtensionIsUser, setExtensionIsUserActive, setIsAcceptingTxn, setIsAppActive, setIsCheckingAppActive, setIsLoadingUser, setIsOnDeletion, setIsOtpRequired, setIsSdkSignedIn, setIsServiceConnected, setIsSigned, setIsSignedFirstCheck, setIsSigning, setIsSigningLoader, setLocale, setReady, setRequests, setServiceIcon, setServiceName, setSignature, setSignedBy, setSolicitedShared, setSolicitedValue, setToken, setUiConfig, setUser, setWaitingForSuccessLogInSince, startExtensionSync, syncExtensionStateFromStorage, t, toPhoneE164, undoSolicitedValue, updatePhoneDraft, utils_exports as utils };
4177
+ export { $extension, $locale, $openModals, $ui, $user, $wallet, $web3, $ws, BlockAuthProvider, DEFAULT_PHONE_COUNTRY, DISCOVERY_TIMEOUT_MS, EMPTY_SOLICITED_DATA_FORM, PARAM_DISPLAY_FORMATTERS, PARAM_DISPLAY_ORDER, PARAM_ERROR_KEYS, PARAM_INPUT_TYPE, PARAM_LABEL_KEYS, PARAM_NORMALIZERS, PARAM_VALIDATORS, RpcClient, SDK_PAGE_MARKER, SYNC_TIMEOUT_MS, TEXTS, WsClient, appearsExtensionInstalled, buildPhoneE164, buildPhoneValue, clearExtensionDomMarkers, clearRemainingAuthData, clearSdkPresence, closeAllModals, closeModal, confirmExtensionPresence, createAuthRuntime, createBlockAuthClient, createDeletionService, createEvmWallet, createSolanaWallet, deepLinkFor, discoverExtensionOnce, fetchUserProfile, finalizeAfterRestorationExpired, formatParamValue, formatPhoneForDisplay, getDefaultPhoneCountry, getExtensionStoreUrl, getPhoneCountries, getPhoneCountryFlag, getPhoneDialCode, getSolicitedAcceptParams, getSolicitedFields, getSolicitedHintKey, getSolicitedParams, getUserRoleNames, getUserRoleSlugs, getUserRoles, handleRestorationExpired, handleRestoreFailure, hasAnyRole, hasAnyRoleBySlug, hasRole, hasRoleBySlug, isExtensionPresent, isExtensionStateComplete, isFirefox, isModalOpen, isPhoneCountry, isRestorationExpiredMessage, isSdkPage, isShowSignin, isSolicitedDataComplete, isSolicitedHintSuccess, isValidParamValue, isValidPhoneValue, loadUserProfile, makeQrDataUrl, markSdkPresence, needsExtensionUnlock, normalizeParamValue, oauth_exports as oauth, onExtensionRemoved, onExtensionStatePublished, openExtensionOnTxn, openLoginPopup, openModal, parsePhoneValue, probeExtensionPresence, reconcileExtensionState, requestExtensionRefresh, requestExtensionStateSync, requestSdkRestore, resetExtension, resetExtensionAbsentState, resetExtensionSyncModuleState, resetUi, resetUser, resetWallet, resetWeb3, resetWs, resolvePhoneDraft, saveSolicitedValue, searchPhoneCountries, setAcceptTxnError, setApiKey, setBackendMessage, setDeletionAddress, setDid, setExtensionInstalled, setExtensionIsLocked, setExtensionIsUser, setExtensionIsUserActive, setIsAcceptingTxn, setIsAppActive, setIsCheckingAppActive, setIsLoadingUser, setIsOnDeletion, setIsOtpRequired, setIsRejectingTxn, setIsSdkSignedIn, setIsServiceConnected, setIsSigned, setIsSignedFirstCheck, setIsSigning, setIsSigningLoader, setLocale, setReady, setRequests, setServiceIcon, setServiceName, setSignature, setSignedBy, setSolicitedShared, setSolicitedValue, setToken, setUiConfig, setUser, setWaitingForSuccessLogInSince, startExtensionSync, syncExtensionStateFromStorage, t, toPhoneE164, undoSolicitedValue, updatePhoneDraft, utils_exports as utils };
3867
4178
  //# sourceMappingURL=index.js.map
3868
4179
  //# sourceMappingURL=index.js.map