@block-auth.io/core 0.10.0 → 0.11.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.d.cts CHANGED
@@ -137,9 +137,11 @@ declare class WsClient {
137
137
  * requestSignin -> user:txns:create -> sign) - this avoids that.
138
138
  * No-op if there is no open connection yet (connect() will pick up a
139
139
  * ticket on its own once one exists).
140
- * @returns Promise<void>
140
+ * @returns 'renewed' when a ticket was sent, 'refused' when the API answered
141
+ * 401 (no session behind the cookie), 'unavailable' otherwise (not
142
+ * connected yet, or a transient failure).
141
143
  */
142
- refreshAuth(): Promise<void>;
144
+ refreshAuth(): Promise<'renewed' | 'refused' | 'unavailable'>;
143
145
  /**
144
146
  * Allow you to subscribe to an event, and
145
147
  * verify if the event is already subscribed
@@ -1380,13 +1382,17 @@ declare const TEXTS: {
1380
1382
  readonly es: "No se encontraron transacciones";
1381
1383
  readonly en: "No transactions found";
1382
1384
  };
1385
+ readonly otpExpiredTitle: {
1386
+ readonly es: "Verificación caducada";
1387
+ readonly en: "Verification expired";
1388
+ };
1383
1389
  readonly otpExpiredExtension: {
1384
- readonly es: "Tu verificación ha caducado. Introduce tu código en la extensión de Block-Auth para aprobar este acceso.";
1385
- readonly en: "Your verification has expired. Enter your code in the Block-Auth extension to approve this access.";
1390
+ readonly es: "Introduce tu código en la extensión de Block-Auth para aprobar este acceso.";
1391
+ readonly en: "Enter your code in the Block-Auth extension to approve this access.";
1386
1392
  };
1387
1393
  readonly otpExpiredApp: {
1388
- readonly es: "Tu verificación ha caducado. Introduce tu código en la app de Block-Auth para aprobar este acceso.";
1389
- readonly en: "Your verification has expired. Enter your code in the Block-Auth app to approve this access.";
1394
+ readonly es: "Introduce tu código en la app de Block-Auth para aprobar este acceso.";
1395
+ readonly en: "Enter your code in the Block-Auth app to approve this access.";
1390
1396
  };
1391
1397
  readonly openExtension: {
1392
1398
  readonly es: "Abrir extensión";
package/dist/index.d.ts CHANGED
@@ -137,9 +137,11 @@ declare class WsClient {
137
137
  * requestSignin -> user:txns:create -> sign) - this avoids that.
138
138
  * No-op if there is no open connection yet (connect() will pick up a
139
139
  * ticket on its own once one exists).
140
- * @returns Promise<void>
140
+ * @returns 'renewed' when a ticket was sent, 'refused' when the API answered
141
+ * 401 (no session behind the cookie), 'unavailable' otherwise (not
142
+ * connected yet, or a transient failure).
141
143
  */
142
- refreshAuth(): Promise<void>;
144
+ refreshAuth(): Promise<'renewed' | 'refused' | 'unavailable'>;
143
145
  /**
144
146
  * Allow you to subscribe to an event, and
145
147
  * verify if the event is already subscribed
@@ -1380,13 +1382,17 @@ declare const TEXTS: {
1380
1382
  readonly es: "No se encontraron transacciones";
1381
1383
  readonly en: "No transactions found";
1382
1384
  };
1385
+ readonly otpExpiredTitle: {
1386
+ readonly es: "Verificación caducada";
1387
+ readonly en: "Verification expired";
1388
+ };
1383
1389
  readonly otpExpiredExtension: {
1384
- readonly es: "Tu verificación ha caducado. Introduce tu código en la extensión de Block-Auth para aprobar este acceso.";
1385
- readonly en: "Your verification has expired. Enter your code in the Block-Auth extension to approve this access.";
1390
+ readonly es: "Introduce tu código en la extensión de Block-Auth para aprobar este acceso.";
1391
+ readonly en: "Enter your code in the Block-Auth extension to approve this access.";
1386
1392
  };
1387
1393
  readonly otpExpiredApp: {
1388
- readonly es: "Tu verificación ha caducado. Introduce tu código en la app de Block-Auth para aprobar este acceso.";
1389
- readonly en: "Your verification has expired. Enter your code in the Block-Auth app to approve this access.";
1394
+ readonly es: "Introduce tu código en la app de Block-Auth para aprobar este acceso.";
1395
+ readonly en: "Enter your code in the Block-Auth app to approve this access.";
1390
1396
  };
1391
1397
  readonly openExtension: {
1392
1398
  readonly es: "Abrir extensión";
package/dist/index.js CHANGED
@@ -49,21 +49,26 @@ async function clearSessionCookie(apiUrl) {
49
49
  return false;
50
50
  }
51
51
  }
52
- async function fetchWsTicket(apiUrl) {
53
- if (typeof fetch === "undefined") return null;
52
+ async function requestWsTicket(apiUrl) {
53
+ if (typeof fetch === "undefined") return { ticket: null, refused: false };
54
54
  try {
55
55
  const response = await fetch(buildApiUrl("/auth/ws-ticket", apiUrl), {
56
56
  method: "GET",
57
57
  credentials: "include"
58
58
  });
59
- if (!response.ok) return null;
59
+ if (!response.ok) {
60
+ return { ticket: null, refused: response.status === 401 };
61
+ }
60
62
  const data = await response.json();
61
- return data?.ticket || null;
63
+ return { ticket: data?.ticket || null, refused: false };
62
64
  } catch (error) {
63
65
  console.warn("[block-auth] failed to fetch ws ticket", error);
64
- return null;
66
+ return { ticket: null, refused: false };
65
67
  }
66
68
  }
69
+ async function fetchWsTicket(apiUrl) {
70
+ return (await requestWsTicket(apiUrl)).ticket;
71
+ }
67
72
  var DEFAULT_WS_URL = "wss://wss.block-auth.io";
68
73
  function buildWsServerApiUrl(path, wsUrl) {
69
74
  const url = new URL(wsUrl || DEFAULT_WS_URL);
@@ -212,13 +217,17 @@ var WsClient = class {
212
217
  * requestSignin -> user:txns:create -> sign) - this avoids that.
213
218
  * No-op if there is no open connection yet (connect() will pick up a
214
219
  * ticket on its own once one exists).
215
- * @returns Promise<void>
220
+ * @returns 'renewed' when a ticket was sent, 'refused' when the API answered
221
+ * 401 (no session behind the cookie), 'unavailable' otherwise (not
222
+ * connected yet, or a transient failure).
216
223
  */
217
224
  async refreshAuth() {
218
- if (!this.isConnected()) return;
219
- const ticket = await fetchWsTicket(this._apiUrl);
220
- if (!ticket) return;
225
+ if (!this.isConnected()) return "unavailable";
226
+ const { ticket, refused } = await requestWsTicket(this._apiUrl);
227
+ if (refused) return "refused";
228
+ if (!ticket) return "unavailable";
221
229
  this._ws.emit("auth:refresh", ticket);
230
+ return "renewed";
222
231
  }
223
232
  /**
224
233
  * Allow you to subscribe to an event, and
@@ -2853,6 +2862,29 @@ var undoSolicitedValue = (form, item) => ({
2853
2862
  shared: (item.value ?? "").trim() ? form.shared : omitKey(form.shared, item.slug)
2854
2863
  });
2855
2864
 
2865
+ // src/session/sessionExpired.ts
2866
+ var USER_SESSION_REQUIRED = "USER_SESSION_REQUIRED";
2867
+ var SESSION_EXPIRED_MARK = "blockauth-session-expired";
2868
+ function markSessionExpired() {
2869
+ try {
2870
+ sessionStorage.setItem(SESSION_EXPIRED_MARK, "1");
2871
+ } catch {
2872
+ }
2873
+ }
2874
+ function hasSessionExpiredMark() {
2875
+ try {
2876
+ return sessionStorage.getItem(SESSION_EXPIRED_MARK) === "1";
2877
+ } catch {
2878
+ return false;
2879
+ }
2880
+ }
2881
+ function clearSessionExpiredMark() {
2882
+ try {
2883
+ sessionStorage.removeItem(SESSION_EXPIRED_MARK);
2884
+ } catch {
2885
+ }
2886
+ }
2887
+
2856
2888
  // src/runtime/authRuntime.ts
2857
2889
  var SIGNIN_TIMEOUT_MS = 12e4;
2858
2890
  var USER_TXNS_POLL_MS = 1500;
@@ -3023,6 +3055,45 @@ function createAuthRuntime(client, callbacks = {}) {
3023
3055
  });
3024
3056
  return logoutInFlight;
3025
3057
  };
3058
+ const reactToLostSession = (isLoggingIn) => {
3059
+ if (browserBase.getExternalService().service === "blockauth") {
3060
+ if (isLoggingIn) {
3061
+ markSessionExpired();
3062
+ setIsSigningLoader(false);
3063
+ awaitOtpInExtension();
3064
+ } else if (!hasSessionExpiredMark()) {
3065
+ markSessionExpired();
3066
+ void _onError();
3067
+ }
3068
+ return;
3069
+ }
3070
+ void applyLocalLogout().then(() => {
3071
+ if (!isLoggingIn) return;
3072
+ closeModal("signin");
3073
+ openModal("signup");
3074
+ }).catch((err) => {
3075
+ console.error("[sdk] applyLocalLogout failed (session required):", err);
3076
+ });
3077
+ };
3078
+ let stopped = false;
3079
+ let sessionBridge = Promise.resolve();
3080
+ let sessionCheck = null;
3081
+ const canLoseSession = () => !hookState.isLoggingOut && !$ui.get().isOtpRequired && ($ui.get().isServiceConnected || hookState.isSigned);
3082
+ const onAnyServerEvent = (_event, data) => {
3083
+ if (data?.code !== USER_SESSION_REQUIRED || !canLoseSession()) return;
3084
+ if (sessionCheck) return;
3085
+ sessionCheck = (async () => {
3086
+ await sessionBridge.catch(() => {
3087
+ });
3088
+ const result = await wsc().refreshAuth();
3089
+ if (result !== "refused" || stopped || !canLoseSession()) return;
3090
+ reactToLostSession($openModals.get().includes("signin"));
3091
+ })().catch((err) => {
3092
+ console.error("[sdk] session check failed:", err);
3093
+ }).finally(() => {
3094
+ sessionCheck = null;
3095
+ });
3096
+ };
3026
3097
  const onStorageLogout = (event) => {
3027
3098
  if (event.key !== "blockauth-logged-out" || event.newValue !== "true") {
3028
3099
  return;
@@ -3033,9 +3104,18 @@ function createAuthRuntime(client, callbacks = {}) {
3033
3104
  });
3034
3105
  };
3035
3106
  let sessionBridged = false;
3036
- const onExtensionSessionBridged = () => {
3107
+ const onExtensionSessionBridged = async () => {
3037
3108
  sessionBridged = true;
3038
- void wsc().refreshAuth();
3109
+ const result = await wsc().refreshAuth();
3110
+ if (result === "refused" || !hasSessionExpiredMark()) return;
3111
+ clearSessionExpiredMark();
3112
+ const awaitedSession = $ui.get().isOtpRequired && !hookState.isSigning;
3113
+ if (awaitedSession) setIsOtpRequired(false);
3114
+ if (awaitedSession && $openModals.get().includes("signin")) {
3115
+ client.requestSignin();
3116
+ return;
3117
+ }
3118
+ if ($ws.get().ready) void isUserSignedIn();
3039
3119
  };
3040
3120
  const deletion = createDeletionService({ provider });
3041
3121
  const handleUserDeleted = (forAddress = null) => {
@@ -3059,7 +3139,7 @@ function createAuthRuntime(client, callbacks = {}) {
3059
3139
  if (service === "blockauth" || prevDid && prevDid.toLowerCase() !== String(did).toLowerCase()) {
3060
3140
  browserBase.clearBrowserState({ keepExtensionInstalled: keepInstalled });
3061
3141
  }
3062
- void browserBase.setSession({
3142
+ sessionBridge = browserBase.setSession({
3063
3143
  ...result,
3064
3144
  serviceName: service,
3065
3145
  apiUrl: client.apiUrl
@@ -3294,6 +3374,7 @@ function createAuthRuntime(client, callbacks = {}) {
3294
3374
  setToken(_token);
3295
3375
  setIsSigned(success);
3296
3376
  hookState.isSigned = success;
3377
+ if (success) clearSessionExpiredMark();
3297
3378
  if (success && hookState.isUnsignTimeoutSet && message?.signedExpiredAt) {
3298
3379
  rearmUnsignTimeout(message.signedExpiredAt, _did);
3299
3380
  }
@@ -3452,6 +3533,7 @@ function createAuthRuntime(client, callbacks = {}) {
3452
3533
  }
3453
3534
  };
3454
3535
  const start = async () => {
3536
+ stopped = false;
3455
3537
  const s = browserBase.getSession();
3456
3538
  const externalService = browserBase.getExternalService();
3457
3539
  let _token = s.token;
@@ -3512,15 +3594,21 @@ function createAuthRuntime(client, callbacks = {}) {
3512
3594
  wsc().on("sdk:session:invalidated", onSdkSessionInvalidated);
3513
3595
  wsc().on("sdk:user:roles:changed", onSdkUserRolesChanged);
3514
3596
  wsc().on("sdk:restore", onSdkRestore);
3597
+ wsc().ws?.onAny(onAnyServerEvent);
3515
3598
  if (typeof window !== "undefined") {
3516
3599
  window.addEventListener("storage", onStorageLogout);
3517
3600
  }
3518
3601
  const { domain, signinCallbackUrl, config: config3 } = await provider.app();
3519
3602
  setUiConfig({ domain, signinCallbackUrl, config: config3 });
3520
3603
  setReady(true);
3604
+ if (externalService.service === "blockauth" && hasSessionExpiredMark()) {
3605
+ setIsSignedFirstCheck(true);
3606
+ return;
3607
+ }
3521
3608
  await isUserSignedIn();
3522
3609
  };
3523
3610
  const stop = () => {
3611
+ stopped = true;
3524
3612
  if (unsignTimeout) {
3525
3613
  clearTimeout(unsignTimeout);
3526
3614
  unsignTimeout = null;
@@ -3555,6 +3643,7 @@ function createAuthRuntime(client, callbacks = {}) {
3555
3643
  w.off("sdk:session:invalidated", onSdkSessionInvalidated);
3556
3644
  w.off("sdk:user:roles:changed", onSdkUserRolesChanged);
3557
3645
  w.off("sdk:restore", onSdkRestore);
3646
+ w.ws?.offAny(onAnyServerEvent);
3558
3647
  }
3559
3648
  if (typeof window !== "undefined") {
3560
3649
  window.removeEventListener("storage", onStorageLogout);
@@ -3692,13 +3781,17 @@ var TEXTS = {
3692
3781
  es: "No se encontraron transacciones",
3693
3782
  en: "No transactions found"
3694
3783
  },
3784
+ otpExpiredTitle: {
3785
+ es: "Verificaci\xF3n caducada",
3786
+ en: "Verification expired"
3787
+ },
3695
3788
  otpExpiredExtension: {
3696
- es: "Tu verificaci\xF3n ha caducado. Introduce tu c\xF3digo en la extensi\xF3n de Block-Auth para aprobar este acceso.",
3697
- en: "Your verification has expired. Enter your code in the Block-Auth extension to approve this access."
3789
+ es: "Introduce tu c\xF3digo en la extensi\xF3n de Block-Auth para aprobar este acceso.",
3790
+ en: "Enter your code in the Block-Auth extension to approve this access."
3698
3791
  },
3699
3792
  otpExpiredApp: {
3700
- es: "Tu verificaci\xF3n ha caducado. Introduce tu c\xF3digo en la app de Block-Auth para aprobar este acceso.",
3701
- en: "Your verification has expired. Enter your code in the Block-Auth app to approve this access."
3793
+ es: "Introduce tu c\xF3digo en la app de Block-Auth para aprobar este acceso.",
3794
+ en: "Enter your code in the Block-Auth app to approve this access."
3702
3795
  },
3703
3796
  openExtension: { es: "Abrir extensi\xF3n", en: "Open extension" },
3704
3797
  noAppKeyFound: {