@block-auth.io/core 0.11.1 → 0.13.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.cjs CHANGED
@@ -24,13 +24,11 @@ var __export = (target, all) => {
24
24
  };
25
25
 
26
26
  // src/utils/apiBridge.ts
27
- var DEFAULT_API_URL = "https://api.block-auth.io";
28
27
  function buildApiUrl(path, apiUrl) {
29
- const base = (apiUrl || DEFAULT_API_URL).replace(/\/+$/, "");
30
- return `${base}${path}`;
28
+ return `${apiUrl.replace(/\/+$/, "")}${path}`;
31
29
  }
32
30
  async function bridgeSessionCookie(token, apiUrl) {
33
- if (!token || typeof fetch === "undefined") return false;
31
+ if (!apiUrl || !token || typeof fetch === "undefined") return false;
34
32
  try {
35
33
  const response = await fetch(buildApiUrl("/auth/session", apiUrl), {
36
34
  method: "POST",
@@ -45,7 +43,7 @@ async function bridgeSessionCookie(token, apiUrl) {
45
43
  }
46
44
  }
47
45
  async function clearSessionCookie(apiUrl) {
48
- if (typeof fetch === "undefined") return false;
46
+ if (!apiUrl || typeof fetch === "undefined") return false;
49
47
  try {
50
48
  const response = await fetch(buildApiUrl("/auth/logout", apiUrl), {
51
49
  method: "POST",
@@ -58,7 +56,9 @@ async function clearSessionCookie(apiUrl) {
58
56
  }
59
57
  }
60
58
  async function requestWsTicket(apiUrl) {
61
- if (typeof fetch === "undefined") return { ticket: null, refused: false };
59
+ if (!apiUrl || typeof fetch === "undefined") {
60
+ return { ticket: null, refused: false };
61
+ }
62
62
  try {
63
63
  const response = await fetch(buildApiUrl("/auth/ws-ticket", apiUrl), {
64
64
  method: "GET",
@@ -89,14 +89,11 @@ function buildWsServerApiUrl(path, wsUrl) {
89
89
  async function fetchBrowserToken(apiKey, wsUrl) {
90
90
  if (!apiKey || typeof fetch === "undefined") return null;
91
91
  try {
92
- const response = await fetch(
93
- buildWsServerApiUrl("/browser-token", wsUrl),
94
- {
95
- method: "POST",
96
- headers: { "Content-Type": "application/json" },
97
- body: JSON.stringify({ apiKey })
98
- }
99
- );
92
+ const response = await fetch(buildWsServerApiUrl("/browser-token", wsUrl), {
93
+ method: "POST",
94
+ headers: { "Content-Type": "application/json" },
95
+ body: JSON.stringify({ apiKey })
96
+ });
100
97
  const payload = await response.json();
101
98
  if (!response.ok || !payload?.success) return null;
102
99
  return payload.message?.accessToken || null;
@@ -127,6 +124,7 @@ var WsClient = class {
127
124
  this._roles = [];
128
125
  this._logs = [];
129
126
  this._kycIssuerByAddress = {};
127
+ this._connecting = null;
130
128
  this._wsUrl = url || "wss://wss.block-auth.io/";
131
129
  this._apiUrl = apiUrl;
132
130
  this._wsConfig = {
@@ -158,6 +156,14 @@ var WsClient = class {
158
156
  * @returns Promise<void>
159
157
  */
160
158
  async connect(url = "", waitMs = 5e3, retries = 3) {
159
+ if (this.isConnected()) return;
160
+ if (this._connecting) return this._connecting;
161
+ this._connecting = this._doConnect(url, waitMs, retries).finally(() => {
162
+ this._connecting = null;
163
+ });
164
+ return this._connecting;
165
+ }
166
+ async _doConnect(url, waitMs, retries) {
161
167
  const _url = url || this._wsUrl;
162
168
  this._wsConfig.auth = (done) => {
163
169
  fetchWsTicket(this._apiUrl).then((ticket) => done(ticket ? { ticket } : {})).catch(() => done({}));
@@ -1003,6 +1009,7 @@ var initial2 = {
1003
1009
  isSigned: false,
1004
1010
  isSigningLoader: false,
1005
1011
  isAcceptingTxn: false,
1012
+ isRejectingTxn: false,
1006
1013
  acceptTxnError: null,
1007
1014
  waitingForSuccessLogInSince: 0,
1008
1015
  isOtpRequired: false,
@@ -1022,6 +1029,7 @@ var setIsSigning = (v) => $ui.setKey("isSigning", v);
1022
1029
  var setIsSigned = (v) => $ui.setKey("isSigned", v);
1023
1030
  var setIsSigningLoader = (v) => $ui.setKey("isSigningLoader", v);
1024
1031
  var setIsAcceptingTxn = (v) => $ui.setKey("isAcceptingTxn", v);
1032
+ var setIsRejectingTxn = (v) => $ui.setKey("isRejectingTxn", v);
1025
1033
  var setAcceptTxnError = (v) => $ui.setKey("acceptTxnError", v);
1026
1034
  var setWaitingForSuccessLogInSince = (v) => $ui.setKey("waitingForSuccessLogInSince", v);
1027
1035
  var setIsOtpRequired = (v) => $ui.setKey("isOtpRequired", v);
@@ -1566,13 +1574,27 @@ var toTxnDataParam = (raw) => {
1566
1574
  if (!raw || typeof raw.slug !== "string") return null;
1567
1575
  if (!TXN_DATA_MODES.includes(raw.mode)) return null;
1568
1576
  if (!TXN_DATA_STATUSES.includes(raw.status)) return null;
1569
- return {
1577
+ const param = {
1570
1578
  slug: raw.slug,
1571
1579
  mode: raw.mode,
1572
1580
  status: raw.status,
1573
1581
  value: typeof raw.value === "string" ? raw.value : null
1574
1582
  };
1583
+ if (Array.isArray(raw.emails)) {
1584
+ param.emails = raw.emails.filter(isTxnDataEmail).map((email) => ({
1585
+ id: email.id,
1586
+ label: typeof email.label === "string" ? email.label : "",
1587
+ email: email.email,
1588
+ isDefault: email.isDefault === true,
1589
+ ...typeof email.verified === "boolean" && { verified: email.verified }
1590
+ }));
1591
+ param.selectedEmailId = typeof raw.selectedEmailId === "number" ? raw.selectedEmailId : null;
1592
+ param.emailsMax = typeof raw.emailsMax === "number" ? raw.emailsMax : 0;
1593
+ param.emailsManageUrl = typeof raw.emailsManageUrl === "string" && /^https?:\/\//i.test(raw.emailsManageUrl) ? raw.emailsManageUrl : null;
1594
+ }
1595
+ return param;
1575
1596
  };
1597
+ var isTxnDataEmail = (raw) => !!raw && typeof raw.id === "number" && typeof raw.email === "string";
1576
1598
  function requestSignin(args) {
1577
1599
  const { wsc, token, url, service, apiKey, sessionId } = args;
1578
1600
  wsc.emit("user:txns:create", { token, url, service, apiKey, sessionId });
@@ -1592,6 +1614,7 @@ function acceptTxn(args) {
1592
1614
  userParams,
1593
1615
  grantedParams,
1594
1616
  revokedParams,
1617
+ sharedEmailId,
1595
1618
  sessionId
1596
1619
  } = args;
1597
1620
  wsc.emit("provider:signin", {
@@ -1602,6 +1625,7 @@ function acceptTxn(args) {
1602
1625
  userParams: userParams ?? {},
1603
1626
  grantedParams: grantedParams ?? [],
1604
1627
  revokedParams: revokedParams ?? [],
1628
+ sharedEmailId,
1605
1629
  sessionId
1606
1630
  });
1607
1631
  }
@@ -2088,21 +2112,147 @@ function connectBlockAuth(apiUrl) {
2088
2112
  requestExtensionStateSync();
2089
2113
  }
2090
2114
 
2091
- // src/auth/logout.ts
2092
- async function performLogout(args) {
2093
- const { wsc, token, apiKey, sessionId, apiUrl } = args;
2094
- await new Promise((resolve) => {
2115
+ // src/auth/popupSize.ts
2116
+ var LOGIN_POPUP_WIDTH = 380;
2117
+ var LOGIN_POPUP_HEIGHT = 640;
2118
+
2119
+ // src/auth/loginWithPopup.ts
2120
+ var AUTH_CODE_MESSAGE = "blockauth:auth-code";
2121
+ var POPUP_CLOSED_POLL_MS = 500;
2122
+ var LOGIN_TIMEOUT_MS = 15 * 60 * 1e3;
2123
+ function base64url(bytes) {
2124
+ let binary = "";
2125
+ for (const b of bytes) binary += String.fromCharCode(b);
2126
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
2127
+ }
2128
+ function randomString(byteLength) {
2129
+ return base64url(crypto.getRandomValues(new Uint8Array(byteLength)));
2130
+ }
2131
+ async function sha256Base64url(value) {
2132
+ const digest = await crypto.subtle.digest(
2133
+ "SHA-256",
2134
+ new TextEncoder().encode(value)
2135
+ );
2136
+ return base64url(new Uint8Array(digest));
2137
+ }
2138
+ async function postWsServer(path, body, wsUrl) {
2139
+ const response = await fetch(buildWsServerApiUrl(path, wsUrl), {
2140
+ method: "POST",
2141
+ headers: { "Content-Type": "application/json" },
2142
+ body: JSON.stringify(body)
2143
+ });
2144
+ const payload = await response.json();
2145
+ if (!response.ok || !payload?.success) {
2146
+ const reason = typeof payload?.message === "string" ? payload.message : "Login failed";
2147
+ throw new Error(reason);
2148
+ }
2149
+ return payload.message;
2150
+ }
2151
+ function waitForCode(popup, authOrigin, state) {
2152
+ return new Promise((resolve, reject) => {
2095
2153
  let done = false;
2096
- const finish = () => {
2097
- if (!done) {
2098
- done = true;
2099
- resolve();
2100
- }
2154
+ const finish = (error, code) => {
2155
+ if (done) return;
2156
+ done = true;
2157
+ window.removeEventListener("message", onMessage);
2158
+ clearInterval(closedPoll);
2159
+ clearTimeout(timeout);
2160
+ if (error) reject(error);
2161
+ else resolve(code);
2162
+ };
2163
+ const onMessage = (event) => {
2164
+ if (event.origin !== authOrigin || event.source !== popup) return;
2165
+ const data = event.data;
2166
+ if (data?.type !== AUTH_CODE_MESSAGE || data.state !== state) return;
2167
+ if (data.code) finish(null, data.code);
2101
2168
  };
2102
- wsc.ws?.once?.("signout", finish);
2103
- wsc.emit("signout", { token, apiKey, sessionId });
2104
- setTimeout(finish, 1500);
2169
+ window.addEventListener("message", onMessage);
2170
+ const closedPoll = setInterval(() => {
2171
+ if (!popup.closed) return;
2172
+ setTimeout(
2173
+ () => finish(new Error("Login window closed")),
2174
+ POPUP_CLOSED_POLL_MS
2175
+ );
2176
+ }, POPUP_CLOSED_POLL_MS);
2177
+ const timeout = setTimeout(
2178
+ () => finish(new Error("Login timed out")),
2179
+ LOGIN_TIMEOUT_MS
2180
+ );
2105
2181
  });
2182
+ }
2183
+ function popupFeatures() {
2184
+ const left = Math.max(
2185
+ 0,
2186
+ Math.round(window.screenX + (window.outerWidth - LOGIN_POPUP_WIDTH) / 2)
2187
+ );
2188
+ const top = Math.max(
2189
+ 0,
2190
+ Math.round(window.screenY + (window.outerHeight - LOGIN_POPUP_HEIGHT) / 2)
2191
+ );
2192
+ return `popup,width=${LOGIN_POPUP_WIDTH},height=${LOGIN_POPUP_HEIGHT},left=${left},top=${top}`;
2193
+ }
2194
+ async function runAuthorize(options) {
2195
+ const popup = window.open("about:blank", "blockauth-login", popupFeatures());
2196
+ if (!popup) throw new Error("Login popup blocked");
2197
+ const redirectUri = `${window.location.origin}/`;
2198
+ try {
2199
+ const codeVerifier = randomString(32);
2200
+ const state = randomString(16);
2201
+ const codeChallenge = await sha256Base64url(codeVerifier);
2202
+ const { url } = await postWsServer(
2203
+ "/auth/authorize",
2204
+ { apiKey: options.apiKey, redirectUri, state, codeChallenge },
2205
+ options.wsUrl
2206
+ );
2207
+ popup.location.href = url;
2208
+ const code = await waitForCode(popup, new URL(url).origin, state);
2209
+ return { code, codeVerifier, redirectUri };
2210
+ } catch (error) {
2211
+ popup.close();
2212
+ throw error;
2213
+ }
2214
+ }
2215
+ var inFlight = null;
2216
+ var loginInFlight = null;
2217
+ function authorizeWithPopup(options) {
2218
+ inFlight ?? (inFlight = runAuthorize(options).finally(() => {
2219
+ inFlight = null;
2220
+ }));
2221
+ return inFlight;
2222
+ }
2223
+ function loginWithPopup(options) {
2224
+ loginInFlight ?? (loginInFlight = authorizeWithPopup(options).then(
2225
+ ({ code, codeVerifier, redirectUri }) => postWsServer(
2226
+ "/auth/token",
2227
+ { apiKey: options.apiKey, code, redirectUri, codeVerifier },
2228
+ options.wsUrl
2229
+ )
2230
+ ).finally(() => {
2231
+ loginInFlight = null;
2232
+ }));
2233
+ return loginInFlight;
2234
+ }
2235
+
2236
+ // src/auth/logout.ts
2237
+ async function performLogout(args) {
2238
+ const { wsc, token, apiKey, sessionId, apiUrl } = args;
2239
+ if (apiUrl) {
2240
+ await new Promise((resolve) => {
2241
+ let done = false;
2242
+ const finish = () => {
2243
+ if (!done) {
2244
+ done = true;
2245
+ resolve();
2246
+ }
2247
+ };
2248
+ wsc.ws?.once?.("signout", finish);
2249
+ wsc.emit("signout", { token, apiKey, sessionId });
2250
+ setTimeout(finish, 1500);
2251
+ });
2252
+ } else {
2253
+ resetUser();
2254
+ browserBase.reset("session");
2255
+ }
2106
2256
  if (typeof localStorage !== "undefined") {
2107
2257
  localStorage.setItem("blockauth-logged-out", "true");
2108
2258
  }
@@ -2337,6 +2487,19 @@ async function signInWithMicrosoft(overrides = {}) {
2337
2487
  setServiceIcon(imgUrlByService("microsoft"));
2338
2488
  return { accessToken: response.accessToken, response };
2339
2489
  }
2490
+ function rememberHostedLogin(result) {
2491
+ const did = result.did ?? result.address;
2492
+ browserBase.setSession({ did, serviceName: "blockauth" });
2493
+ setUser({
2494
+ address: result.address,
2495
+ did,
2496
+ roles: result.roles ?? []
2497
+ });
2498
+ setServiceName("blockauth");
2499
+ setIsServiceConnected(true);
2500
+ setIsSigned(true);
2501
+ setIsSignedFirstCheck(true);
2502
+ }
2340
2503
  function createBlockAuthClient(config3) {
2341
2504
  if (config3.locale) setLocale(config3.locale);
2342
2505
  const provider = new BlockAuthProvider(
@@ -2381,13 +2544,15 @@ function createBlockAuthClient(config3) {
2381
2544
  const ext = browserBase.getExternalService();
2382
2545
  return ext.service !== "blockauth" ? ext.token ?? "" : s.token ?? "";
2383
2546
  }
2547
+ let runtimeBridge = null;
2384
2548
  return {
2385
2549
  state: {
2386
2550
  $ws,
2387
2551
  $ui,
2388
2552
  $wallet,
2389
2553
  $openModals,
2390
- $user
2554
+ $user,
2555
+ $extension
2391
2556
  },
2392
2557
  /** App apiKey from client config (also seeded into $ws). */
2393
2558
  apiKey: config3.apiKey,
@@ -2414,6 +2579,23 @@ function createBlockAuthClient(config3) {
2414
2579
  // BlockAuth extension connect (sets blockauth as the active service);
2415
2580
  // the txn-signing flow is driven by the caller via requestSignin.
2416
2581
  connectBlockAuth: () => connectBlockAuth(config3.apiUrl),
2582
+ // Login for an app without a backend: hosted login in a popup, PKCE
2583
+ // instead of the apiSecret (see auth/loginWithPopup.ts). Call it from a
2584
+ // click handler.
2585
+ loginWithPopup: async () => {
2586
+ const result = await loginWithPopup({
2587
+ apiKey: config3.apiKey,
2588
+ wsUrl: config3.wsUrl
2589
+ });
2590
+ rememberHostedLogin(result);
2591
+ return result;
2592
+ },
2593
+ // Same popup, but the code goes to the app's backend, which redeems it
2594
+ // with its apiSecret (see PopupAuthCode). Call it from a click handler.
2595
+ authorizeWithPopup: () => authorizeWithPopup({ apiKey: config3.apiKey, wsUrl: config3.wsUrl }),
2596
+ // After the backend redeemed the code: shows the user in the page's UI
2597
+ // (profile dropdown, roles). The backend's answer is the source of truth.
2598
+ rememberHostedLogin: (user) => rememberHostedLogin(user),
2417
2599
  // oauth
2418
2600
  oauth: {
2419
2601
  ...oauth_exports,
@@ -2454,10 +2636,13 @@ function createBlockAuthClient(config3) {
2454
2636
  }),
2455
2637
  // transaction accept/reject
2456
2638
  txns: {
2457
- reject: () => rejectTxn({
2458
- wsc: provider.wsc,
2459
- token: userToken()
2460
- }),
2639
+ reject: () => {
2640
+ setIsRejectingTxn(true);
2641
+ rejectTxn({
2642
+ wsc: provider.wsc,
2643
+ token: userToken()
2644
+ });
2645
+ },
2461
2646
  accept: (opts) => acceptTxn({
2462
2647
  wsc: provider.wsc,
2463
2648
  token: userToken(),
@@ -2466,6 +2651,7 @@ function createBlockAuthClient(config3) {
2466
2651
  userParams: opts.userParams,
2467
2652
  grantedParams: opts.grantedParams,
2468
2653
  revokedParams: opts.revokedParams,
2654
+ sharedEmailId: opts.sharedEmailId,
2469
2655
  sessionId: browserBase.getDeviceSessionId()
2470
2656
  }),
2471
2657
  dataRequest: (txnId) => requestTxnData({
@@ -2497,6 +2683,10 @@ function createBlockAuthClient(config3) {
2497
2683
  openModal,
2498
2684
  closeModal,
2499
2685
  closeAllModals,
2686
+ registerRuntime: (bridge) => {
2687
+ runtimeBridge = bridge;
2688
+ },
2689
+ switchAccount: () => runtimeBridge?.switchAccount() ?? Promise.resolve(),
2500
2690
  // opciones del connect inicial del WS (las consume createAuthRuntime)
2501
2691
  wsConnectTimeout: config3.wsConnectTimeout ?? 300,
2502
2692
  wsConnectRetries: config3.wsConnectRetries ?? 3,
@@ -2747,6 +2937,21 @@ var EMPTY_SOLICITED_DATA_FORM = {
2747
2937
  shared: {},
2748
2938
  saved: {}
2749
2939
  };
2940
+ var EMAIL_SLUG = "users-email";
2941
+ var isSolicitedEmailSelectable = (email) => email.verified !== false;
2942
+ function emailChoiceOf(item, form) {
2943
+ if (item.slug !== EMAIL_SLUG || !item.emails) return void 0;
2944
+ if (form.emailChoice !== void 0) return form.emailChoice;
2945
+ const selectable = item.emails.filter(isSolicitedEmailSelectable);
2946
+ const selected = selectable.find(
2947
+ (email) => email.id === item.selectedEmailId
2948
+ );
2949
+ return selected?.id ?? selectable.find((email) => email.isDefault)?.id ?? selectable[0]?.id ?? null;
2950
+ }
2951
+ var formatSolicitedEmailOption = (email, unverifiedText = "") => {
2952
+ const text = email.label ? `${email.label} \xB7 ${email.email}` : email.email;
2953
+ return email.verified === false && unverifiedText ? `${text} (${unverifiedText})` : text;
2954
+ };
2750
2955
  var omitKey = (record, key) => Object.fromEntries(
2751
2956
  Object.entries(record).filter(([entryKey]) => entryKey !== key)
2752
2957
  );
@@ -2782,14 +2987,18 @@ function getSolicitedParams({
2782
2987
  }
2783
2988
  function getSolicitedFields(items, form = EMPTY_SOLICITED_DATA_FORM, withConsent = true) {
2784
2989
  return items.map((item) => {
2785
- const profileValue = item.value ?? "";
2786
- const inputValue = form.values[item.slug] ?? profileValue;
2990
+ const emailChoice = emailChoiceOf(item, form);
2991
+ const chosenEmail = typeof emailChoice === "number" ? item.emails?.find((email) => email.id === emailChoice)?.email : void 0;
2992
+ const emailFields = emailChoice !== void 0 ? { emailChoice } : {};
2993
+ const profileValue = chosenEmail ?? (emailChoice === null ? "" : item.value ?? "");
2994
+ const inputValue = chosenEmail ?? form.values[item.slug] ?? profileValue;
2787
2995
  const trimmed = inputValue.trim();
2788
2996
  const isEmpty = !trimmed;
2789
2997
  const isValid = isValidParamValue(item.slug, inputValue);
2790
2998
  if (!withConsent) {
2791
2999
  return {
2792
3000
  ...item,
3001
+ ...emailFields,
2793
3002
  profileValue,
2794
3003
  inputValue,
2795
3004
  isEmpty,
@@ -2807,6 +3016,7 @@ function getSolicitedFields(items, form = EMPTY_SOLICITED_DATA_FORM, withConsent
2807
3016
  const isComplete = isShared ? isValid && (!isChanged || isSaved) : item.mode !== "required";
2808
3017
  return {
2809
3018
  ...item,
3019
+ ...emailFields,
2810
3020
  profileValue,
2811
3021
  inputValue,
2812
3022
  isEmpty,
@@ -2829,6 +3039,7 @@ function getSolicitedAcceptParams(fields) {
2829
3039
  const userParams = {};
2830
3040
  const grantedParams = [];
2831
3041
  const revokedParams = [];
3042
+ const email = {};
2832
3043
  fields.forEach((field) => {
2833
3044
  if (!field.isShared) {
2834
3045
  if ((field.status === "granted" || field.status === "shared") && field.mode === "optional")
@@ -2837,17 +3048,20 @@ function getSolicitedAcceptParams(fields) {
2837
3048
  }
2838
3049
  if (!field.isValid) return;
2839
3050
  if (field.isChanged) {
2840
- if (field.isSaved)
3051
+ if (field.isSaved) {
2841
3052
  userParams[field.slug] = normalizeParamValue(
2842
3053
  field.slug,
2843
3054
  field.inputValue
2844
3055
  );
3056
+ }
2845
3057
  return;
2846
3058
  }
3059
+ if (typeof field.emailChoice === "number")
3060
+ email.sharedEmailId = field.emailChoice;
2847
3061
  if (field.status === "consent" || field.status === "granted")
2848
3062
  grantedParams.push(field.slug);
2849
3063
  });
2850
- return { userParams, grantedParams, revokedParams };
3064
+ return { userParams, grantedParams, revokedParams, ...email };
2851
3065
  }
2852
3066
  var setSolicitedValue = (form, item, value) => ({
2853
3067
  ...form,
@@ -2866,10 +3080,99 @@ var saveSolicitedValue = (form, slug) => {
2866
3080
  };
2867
3081
  };
2868
3082
  var undoSolicitedValue = (form, item) => ({
3083
+ ...form,
2869
3084
  values: omitKey(form.values, item.slug),
2870
3085
  saved: omitKey(form.saved, item.slug),
2871
3086
  shared: (item.value ?? "").trim() ? form.shared : omitKey(form.shared, item.slug)
2872
3087
  });
3088
+ var setSolicitedEmailChoice = (form, emailChoice) => ({
3089
+ ...form,
3090
+ emailChoice,
3091
+ values: omitKey(form.values, EMAIL_SLUG),
3092
+ saved: omitKey(form.saved, EMAIL_SLUG),
3093
+ shared: omitKey(form.shared, EMAIL_SLUG)
3094
+ });
3095
+
3096
+ // src/auth/redirectPopup.ts
3097
+ var AUTH_CODE_MESSAGE2 = "blockauth:auth-code";
3098
+ function centeredPopupFeatures(width, height) {
3099
+ const base = `popup,width=${width},height=${height}`;
3100
+ if (typeof window === "undefined") return base;
3101
+ const screenLeft = window.screenLeft ?? window.screenX ?? 0;
3102
+ const screenTop = window.screenTop ?? window.screenY ?? 0;
3103
+ const viewportWidth = window.innerWidth || document.documentElement?.clientWidth || window.screen?.width || width;
3104
+ const viewportHeight = window.innerHeight || document.documentElement?.clientHeight || window.screen?.height || height;
3105
+ const left = Math.max(
3106
+ 0,
3107
+ Math.round(screenLeft + (viewportWidth - width) / 2)
3108
+ );
3109
+ const top = Math.max(
3110
+ 0,
3111
+ Math.round(screenTop + (viewportHeight - height) / 2)
3112
+ );
3113
+ return `${base},left=${left},top=${top}`;
3114
+ }
3115
+ function openLoginPopup({
3116
+ url,
3117
+ expectedOrigin,
3118
+ timeoutMs = 3e5,
3119
+ windowName = "blockauth-login",
3120
+ windowFeatures,
3121
+ width = LOGIN_POPUP_WIDTH,
3122
+ height = LOGIN_POPUP_HEIGHT
3123
+ }) {
3124
+ return new Promise((resolve, reject) => {
3125
+ if (typeof window === "undefined" || typeof window.open !== "function") {
3126
+ reject(new Error("Popup login is only available in a browser"));
3127
+ return;
3128
+ }
3129
+ const features = windowFeatures ?? centeredPopupFeatures(width, height);
3130
+ const popup = window.open(url, windowName, features);
3131
+ if (!popup) {
3132
+ reject(new Error("Popup blocked"));
3133
+ return;
3134
+ }
3135
+ let settled = false;
3136
+ let closedTimer = null;
3137
+ let timeoutTimer = null;
3138
+ const cleanup = () => {
3139
+ window.removeEventListener("message", onMessage);
3140
+ if (closedTimer !== null) clearInterval(closedTimer);
3141
+ if (timeoutTimer !== null) clearTimeout(timeoutTimer);
3142
+ };
3143
+ const finish = (action) => {
3144
+ if (settled) return;
3145
+ settled = true;
3146
+ cleanup();
3147
+ action();
3148
+ };
3149
+ const onMessage = (event) => {
3150
+ if (event.origin !== expectedOrigin) return;
3151
+ if (event.source !== popup) return;
3152
+ const data = event.data;
3153
+ if (!data || data.type !== AUTH_CODE_MESSAGE2) return;
3154
+ if (typeof data.code !== "string" || typeof data.state !== "string") {
3155
+ finish(() => reject(new Error("Malformed auth code message")));
3156
+ return;
3157
+ }
3158
+ finish(
3159
+ () => resolve({ code: data.code, state: data.state })
3160
+ );
3161
+ };
3162
+ window.addEventListener("message", onMessage);
3163
+ closedTimer = setInterval(() => {
3164
+ if (popup.closed) {
3165
+ finish(() => reject(new Error("Login popup closed")));
3166
+ }
3167
+ }, 500);
3168
+ timeoutTimer = setTimeout(() => {
3169
+ finish(() => {
3170
+ if (!popup.closed) popup.close();
3171
+ reject(new Error("Login popup timed out"));
3172
+ });
3173
+ }, timeoutMs);
3174
+ });
3175
+ }
2873
3176
 
2874
3177
  // src/session/sessionExpired.ts
2875
3178
  var USER_SESSION_REQUIRED = "USER_SESSION_REQUIRED";
@@ -2917,8 +3220,8 @@ function createAuthRuntime(client, callbacks = {}) {
2917
3220
  let unsignTimeout = null;
2918
3221
  let signinTimeout = null;
2919
3222
  const wsc = () => provider.wsc;
2920
- const emitSdkSign = (token, address) => {
2921
- wsc().emit("sdk:sign", { token, address });
3223
+ const emitSdkSign = (token, address, afterSign = false) => {
3224
+ wsc().emit("sdk:sign", { token, address, afterSign });
2922
3225
  };
2923
3226
  const ownTxnItems = (items) => {
2924
3227
  const apiKey = client.apiKey;
@@ -2953,6 +3256,8 @@ function createAuthRuntime(client, callbacks = {}) {
2953
3256
  });
2954
3257
  const onLogout = callbacks.onLogout ?? (async () => {
2955
3258
  });
3259
+ const onCancel = callbacks.onCancel ?? (async () => {
3260
+ });
2956
3261
  const _onSuccess = async (address) => {
2957
3262
  deletion.resetHandlingState();
2958
3263
  await onSuccess(address);
@@ -3290,7 +3595,10 @@ function createAuthRuntime(client, callbacks = {}) {
3290
3595
  hookState.pendingSignin = null;
3291
3596
  hookState.pendingTxnId = null;
3292
3597
  hookState.settledAttemptId = hookState.signinAttemptId;
3293
- if (!hookState.isSigned) closeAllModals();
3598
+ if (!hookState.isSigned) {
3599
+ closeAllModals();
3600
+ void onCancel();
3601
+ }
3294
3602
  return;
3295
3603
  }
3296
3604
  if (hookState.settledAttemptId === hookState.signinAttemptId) {
@@ -3301,18 +3609,24 @@ function createAuthRuntime(client, callbacks = {}) {
3301
3609
  hookState.pendingSignin = null;
3302
3610
  const willVerifySign = outcome === "resolved" && !hookState.isSigned && !!pendingSignin;
3303
3611
  if (willVerifySign) {
3304
- emitSdkSign(pendingSignin.accessToken, pendingSignin.did);
3612
+ emitSdkSign(pendingSignin.accessToken, pendingSignin.did, true);
3305
3613
  } else if (!hookState.isSigned) {
3306
3614
  closeAllModals();
3307
3615
  }
3308
3616
  };
3617
+ const consumePendingReject = () => {
3618
+ if (!$ui.get().isRejectingTxn) return false;
3619
+ setIsRejectingTxn(false);
3620
+ settleSigningAttempt("cancelled");
3621
+ return true;
3622
+ };
3309
3623
  const onUserTxns = async (data) => {
3310
3624
  const { success, message } = data;
3311
3625
  if (!success) return;
3312
3626
  const items = ownTxnItems(message.items ?? []);
3313
3627
  captureOwnTxnId(items);
3314
3628
  const hasInitialTxns = items.some((item) => item.state === "initial");
3315
- if (!hasInitialTxns) {
3629
+ if (!hasInitialTxns && !consumePendingReject()) {
3316
3630
  settleSigningAttempt("resolved");
3317
3631
  }
3318
3632
  setRequests(items);
@@ -3323,7 +3637,7 @@ function createAuthRuntime(client, callbacks = {}) {
3323
3637
  const items = ownTxnItems(message.items ?? []);
3324
3638
  captureOwnTxnId(items);
3325
3639
  const hasInitialTxns = items.some((item) => item.state === "initial");
3326
- if (!hasInitialTxns) {
3640
+ if (!hasInitialTxns && !consumePendingReject()) {
3327
3641
  const txnId = hookState.pendingTxnId;
3328
3642
  const wasCancelled = txnId != null && !items.some((item) => item.id === txnId);
3329
3643
  settleSigningAttempt(
@@ -3335,6 +3649,7 @@ function createAuthRuntime(client, callbacks = {}) {
3335
3649
  const onUserTxnsCreate = async (data) => {
3336
3650
  const { success, message } = data;
3337
3651
  if (success) {
3652
+ setIsRejectingTxn(false);
3338
3653
  setIsSigning(true);
3339
3654
  hookState.isSigning = true;
3340
3655
  const attemptId = ++hookState.signinAttemptId;
@@ -3383,6 +3698,7 @@ function createAuthRuntime(client, callbacks = {}) {
3383
3698
  setToken(_token);
3384
3699
  setIsSigned(success);
3385
3700
  hookState.isSigned = success;
3701
+ if (success) setIsAcceptingTxn(false);
3386
3702
  if (success) clearSessionExpiredMark();
3387
3703
  if (success && hookState.isUnsignTimeoutSet && message?.signedExpiredAt) {
3388
3704
  rearmUnsignTimeout(message.signedExpiredAt, _did);
@@ -3551,10 +3867,10 @@ function createAuthRuntime(client, callbacks = {}) {
3551
3867
  _token = externalService.token;
3552
3868
  _did = externalService.did;
3553
3869
  }
3554
- setDid(_did);
3555
- setToken(_token);
3556
- setApiKey(client.apiKey ?? $ws.get().apiKey);
3557
3870
  const isLoggedOut = typeof localStorage !== "undefined" && localStorage.getItem("blockauth-logged-out") === "true";
3871
+ setDid(isLoggedOut ? null : _did);
3872
+ setToken(isLoggedOut ? "" : _token);
3873
+ setApiKey(client.apiKey ?? $ws.get().apiKey);
3558
3874
  setIsServiceConnected(isLoggedOut ? false : externalService.connected);
3559
3875
  setServiceName(externalService.service);
3560
3876
  setServiceIcon(imgUrlByService(externalService.service));
@@ -3668,7 +3984,46 @@ function createAuthRuntime(client, callbacks = {}) {
3668
3984
  const logout = async () => {
3669
3985
  await _onLogout();
3670
3986
  };
3671
- return { start, stop, logout };
3987
+ const switchAccount = async () => {
3988
+ if (hookState.isLoggingOut) return;
3989
+ if (unsignTimeout) {
3990
+ clearTimeout(unsignTimeout);
3991
+ unsignTimeout = null;
3992
+ }
3993
+ if (signinTimeout) {
3994
+ clearTimeout(signinTimeout);
3995
+ signinTimeout = null;
3996
+ }
3997
+ if (getUserTxnsInterval) {
3998
+ clearInterval(getUserTxnsInterval);
3999
+ getUserTxnsInterval = null;
4000
+ }
4001
+ hookState.isUnsignTimeoutSet = false;
4002
+ hookState.isSigning = false;
4003
+ hookState.pendingSignin = null;
4004
+ hookState.pendingTxnId = null;
4005
+ hookState.settledAttemptId = hookState.signinAttemptId;
4006
+ setIsSigning(false);
4007
+ setIsSigningLoader(false);
4008
+ setIsAcceptingTxn(false);
4009
+ setIsOtpRequired(false);
4010
+ setWaitingForSuccessLogInSince(0);
4011
+ closeAllModals();
4012
+ openModal("signup");
4013
+ const s = browserBase.getSession();
4014
+ const ext = browserBase.getExternalService();
4015
+ const token = ext.service !== "blockauth" ? ext.token : s.token;
4016
+ const apiKey = $ws.get().apiKey ?? client.apiKey;
4017
+ const sessionId = browserBase.getDeviceSessionId();
4018
+ await performLogout({
4019
+ wsc: wsc(),
4020
+ token: token ?? "",
4021
+ apiKey,
4022
+ sessionId,
4023
+ apiUrl: client.apiUrl
4024
+ });
4025
+ };
4026
+ return { start, stop, logout, switchAccount };
3672
4027
  }
3673
4028
  function deepLinkFor(service, domain) {
3674
4029
  switch (service) {
@@ -3743,6 +4098,7 @@ var TEXTS = {
3743
4098
  solicitedData: { es: "Datos solicitados", en: "Solicited data" },
3744
4099
  reject: { es: "RECHAZAR", en: "REJECT" },
3745
4100
  accept: { es: "ACEPTAR", en: "ACCEPT" },
4101
+ useAnotherAccount: { es: "Usar otra cuenta", en: "Use another account" },
3746
4102
  iAuthorizeThe: { es: "Autorizo la", en: "I authorize the" },
3747
4103
  privacyPolicy: { es: "Pol\xEDtica de Privacidad", en: "Privacy Policy" },
3748
4104
  andThe: { es: "y los", en: "and the" },
@@ -3771,6 +4127,15 @@ var TEXTS = {
3771
4127
  },
3772
4128
  shareData: { es: "Ceder", en: "Share" },
3773
4129
  saveData: { es: "Guardar", en: "Save" },
4130
+ emailUnverified: { es: "no verificado", en: "not verified" },
4131
+ emailNoneVerified: {
4132
+ es: "Ning\xFAn correo verificado",
4133
+ en: "No verified email"
4134
+ },
4135
+ emailsManage: {
4136
+ es: "A\xF1adir o gestionar correos en Identity",
4137
+ en: "Add or manage emails in Identity"
4138
+ },
3774
4139
  undoChange: { es: "Deshacer", en: "Undo" },
3775
4140
  savedToProfileHint: {
3776
4141
  es: "Se guardar\xE1 en tu perfil al aceptar",
@@ -3786,6 +4151,7 @@ var TEXTS = {
3786
4151
  },
3787
4152
  clearField: { es: "Limpiar campo", en: "Clear field" },
3788
4153
  acceptData: { es: "Aceptar", en: "Accept" },
4154
+ cancelData: { es: "Cancelar", en: "Cancel" },
3789
4155
  noTransactionsFound: {
3790
4156
  es: "No se encontraron transacciones",
3791
4157
  en: "No transactions found"
@@ -3846,7 +4212,10 @@ var TEXTS = {
3846
4212
  en: "Enter a valid phone number"
3847
4213
  },
3848
4214
  phoneCountry: { es: "Pa\xEDs", en: "Country" },
3849
- searchPhoneCountry: { es: "Buscar pa\xEDs o prefijo", en: "Search country or code" },
4215
+ searchPhoneCountry: {
4216
+ es: "Buscar pa\xEDs o prefijo",
4217
+ en: "Search country or code"
4218
+ },
3850
4219
  noPhoneCountryResults: {
3851
4220
  es: "No hay pa\xEDses que coincidan",
3852
4221
  en: "No matching countries"
@@ -3915,6 +4284,7 @@ exports.fetchUserProfile = fetchUserProfile;
3915
4284
  exports.finalizeAfterRestorationExpired = finalizeAfterRestorationExpired;
3916
4285
  exports.formatParamValue = formatParamValue;
3917
4286
  exports.formatPhoneForDisplay = formatPhoneForDisplay;
4287
+ exports.formatSolicitedEmailOption = formatSolicitedEmailOption;
3918
4288
  exports.getDefaultPhoneCountry = getDefaultPhoneCountry;
3919
4289
  exports.getExtensionStoreUrl = getExtensionStoreUrl;
3920
4290
  exports.getPhoneCountries = getPhoneCountries;
@@ -3942,6 +4312,7 @@ exports.isRestorationExpiredMessage = isRestorationExpiredMessage;
3942
4312
  exports.isSdkPage = isSdkPage;
3943
4313
  exports.isShowSignin = isShowSignin;
3944
4314
  exports.isSolicitedDataComplete = isSolicitedDataComplete;
4315
+ exports.isSolicitedEmailSelectable = isSolicitedEmailSelectable;
3945
4316
  exports.isSolicitedHintSuccess = isSolicitedHintSuccess;
3946
4317
  exports.isValidParamValue = isValidParamValue;
3947
4318
  exports.isValidPhoneValue = isValidPhoneValue;
@@ -3954,6 +4325,7 @@ exports.oauth = oauth_exports;
3954
4325
  exports.onExtensionRemoved = onExtensionRemoved;
3955
4326
  exports.onExtensionStatePublished = onExtensionStatePublished;
3956
4327
  exports.openExtensionOnTxn = openExtensionOnTxn;
4328
+ exports.openLoginPopup = openLoginPopup;
3957
4329
  exports.openModal = openModal;
3958
4330
  exports.parsePhoneValue = parsePhoneValue;
3959
4331
  exports.probeExtensionPresence = probeExtensionPresence;
@@ -3987,6 +4359,7 @@ exports.setIsCheckingAppActive = setIsCheckingAppActive;
3987
4359
  exports.setIsLoadingUser = setIsLoadingUser;
3988
4360
  exports.setIsOnDeletion = setIsOnDeletion;
3989
4361
  exports.setIsOtpRequired = setIsOtpRequired;
4362
+ exports.setIsRejectingTxn = setIsRejectingTxn;
3990
4363
  exports.setIsSdkSignedIn = setIsSdkSignedIn;
3991
4364
  exports.setIsServiceConnected = setIsServiceConnected;
3992
4365
  exports.setIsSigned = setIsSigned;
@@ -4000,6 +4373,7 @@ exports.setServiceIcon = setServiceIcon;
4000
4373
  exports.setServiceName = setServiceName;
4001
4374
  exports.setSignature = setSignature;
4002
4375
  exports.setSignedBy = setSignedBy;
4376
+ exports.setSolicitedEmailChoice = setSolicitedEmailChoice;
4003
4377
  exports.setSolicitedShared = setSolicitedShared;
4004
4378
  exports.setSolicitedValue = setSolicitedValue;
4005
4379
  exports.setToken = setToken;