@block-auth.io/core 0.10.0 → 0.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -57,21 +57,26 @@ async function clearSessionCookie(apiUrl) {
57
57
  return false;
58
58
  }
59
59
  }
60
- async function fetchWsTicket(apiUrl) {
61
- if (typeof fetch === "undefined") return null;
60
+ async function requestWsTicket(apiUrl) {
61
+ if (typeof fetch === "undefined") return { ticket: null, refused: false };
62
62
  try {
63
63
  const response = await fetch(buildApiUrl("/auth/ws-ticket", apiUrl), {
64
64
  method: "GET",
65
65
  credentials: "include"
66
66
  });
67
- if (!response.ok) return null;
67
+ if (!response.ok) {
68
+ return { ticket: null, refused: response.status === 401 };
69
+ }
68
70
  const data = await response.json();
69
- return data?.ticket || null;
71
+ return { ticket: data?.ticket || null, refused: false };
70
72
  } catch (error) {
71
73
  console.warn("[block-auth] failed to fetch ws ticket", error);
72
- return null;
74
+ return { ticket: null, refused: false };
73
75
  }
74
76
  }
77
+ async function fetchWsTicket(apiUrl) {
78
+ return (await requestWsTicket(apiUrl)).ticket;
79
+ }
75
80
  var DEFAULT_WS_URL = "wss://wss.block-auth.io";
76
81
  function buildWsServerApiUrl(path, wsUrl) {
77
82
  const url = new URL(wsUrl || DEFAULT_WS_URL);
@@ -220,13 +225,17 @@ var WsClient = class {
220
225
  * requestSignin -> user:txns:create -> sign) - this avoids that.
221
226
  * No-op if there is no open connection yet (connect() will pick up a
222
227
  * ticket on its own once one exists).
223
- * @returns Promise<void>
228
+ * @returns 'renewed' when a ticket was sent, 'refused' when the API answered
229
+ * 401 (no session behind the cookie), 'unavailable' otherwise (not
230
+ * connected yet, or a transient failure).
224
231
  */
225
232
  async refreshAuth() {
226
- if (!this.isConnected()) return;
227
- const ticket = await fetchWsTicket(this._apiUrl);
228
- if (!ticket) return;
233
+ if (!this.isConnected()) return "unavailable";
234
+ const { ticket, refused } = await requestWsTicket(this._apiUrl);
235
+ if (refused) return "refused";
236
+ if (!ticket) return "unavailable";
229
237
  this._ws.emit("auth:refresh", ticket);
238
+ return "renewed";
230
239
  }
231
240
  /**
232
241
  * Allow you to subscribe to an event, and
@@ -1094,6 +1103,7 @@ var setExtensionIsUser = (v) => $extension.setKey("isUser", v);
1094
1103
  var setExtensionIsUserActive = (v) => $extension.setKey("isUserActive", v);
1095
1104
  var resetExtension = () => $extension.set({ ...initial5 });
1096
1105
  var isShowSignin = (state = $extension.get()) => Boolean(state.installed && state.isUser && state.isUserActive && !state.isLocked);
1106
+ var needsExtensionUnlock = (serviceName, did, isLocked) => serviceName === "blockauth" && (isLocked || !did);
1097
1107
  var initial6 = { backendMessage: null, signature: null, signedBy: null };
1098
1108
  var $web3 = nanostores.map({ ...initial6 });
1099
1109
  var setBackendMessage = (v) => $web3.setKey("backendMessage", v);
@@ -2861,6 +2871,29 @@ var undoSolicitedValue = (form, item) => ({
2861
2871
  shared: (item.value ?? "").trim() ? form.shared : omitKey(form.shared, item.slug)
2862
2872
  });
2863
2873
 
2874
+ // src/session/sessionExpired.ts
2875
+ var USER_SESSION_REQUIRED = "USER_SESSION_REQUIRED";
2876
+ var SESSION_EXPIRED_MARK = "blockauth-session-expired";
2877
+ function markSessionExpired() {
2878
+ try {
2879
+ sessionStorage.setItem(SESSION_EXPIRED_MARK, "1");
2880
+ } catch {
2881
+ }
2882
+ }
2883
+ function hasSessionExpiredMark() {
2884
+ try {
2885
+ return sessionStorage.getItem(SESSION_EXPIRED_MARK) === "1";
2886
+ } catch {
2887
+ return false;
2888
+ }
2889
+ }
2890
+ function clearSessionExpiredMark() {
2891
+ try {
2892
+ sessionStorage.removeItem(SESSION_EXPIRED_MARK);
2893
+ } catch {
2894
+ }
2895
+ }
2896
+
2864
2897
  // src/runtime/authRuntime.ts
2865
2898
  var SIGNIN_TIMEOUT_MS = 12e4;
2866
2899
  var USER_TXNS_POLL_MS = 1500;
@@ -3031,6 +3064,45 @@ function createAuthRuntime(client, callbacks = {}) {
3031
3064
  });
3032
3065
  return logoutInFlight;
3033
3066
  };
3067
+ const reactToLostSession = (isLoggingIn) => {
3068
+ if (browserBase.getExternalService().service === "blockauth") {
3069
+ if (isLoggingIn) {
3070
+ markSessionExpired();
3071
+ setIsSigningLoader(false);
3072
+ awaitOtpInExtension();
3073
+ } else if (!hasSessionExpiredMark()) {
3074
+ markSessionExpired();
3075
+ void _onError();
3076
+ }
3077
+ return;
3078
+ }
3079
+ void applyLocalLogout().then(() => {
3080
+ if (!isLoggingIn) return;
3081
+ closeModal("signin");
3082
+ openModal("signup");
3083
+ }).catch((err) => {
3084
+ console.error("[sdk] applyLocalLogout failed (session required):", err);
3085
+ });
3086
+ };
3087
+ let stopped = false;
3088
+ let sessionBridge = Promise.resolve();
3089
+ let sessionCheck = null;
3090
+ const canLoseSession = () => !hookState.isLoggingOut && !$ui.get().isOtpRequired && ($ui.get().isServiceConnected || hookState.isSigned);
3091
+ const onAnyServerEvent = (_event, data) => {
3092
+ if (data?.code !== USER_SESSION_REQUIRED || !canLoseSession()) return;
3093
+ if (sessionCheck) return;
3094
+ sessionCheck = (async () => {
3095
+ await sessionBridge.catch(() => {
3096
+ });
3097
+ const result = await wsc().refreshAuth();
3098
+ if (result !== "refused" || stopped || !canLoseSession()) return;
3099
+ reactToLostSession($openModals.get().includes("signin"));
3100
+ })().catch((err) => {
3101
+ console.error("[sdk] session check failed:", err);
3102
+ }).finally(() => {
3103
+ sessionCheck = null;
3104
+ });
3105
+ };
3034
3106
  const onStorageLogout = (event) => {
3035
3107
  if (event.key !== "blockauth-logged-out" || event.newValue !== "true") {
3036
3108
  return;
@@ -3041,9 +3113,18 @@ function createAuthRuntime(client, callbacks = {}) {
3041
3113
  });
3042
3114
  };
3043
3115
  let sessionBridged = false;
3044
- const onExtensionSessionBridged = () => {
3116
+ const onExtensionSessionBridged = async () => {
3045
3117
  sessionBridged = true;
3046
- void wsc().refreshAuth();
3118
+ const result = await wsc().refreshAuth();
3119
+ if (result === "refused" || !hasSessionExpiredMark()) return;
3120
+ clearSessionExpiredMark();
3121
+ const awaitedSession = $ui.get().isOtpRequired && !hookState.isSigning;
3122
+ if (awaitedSession) setIsOtpRequired(false);
3123
+ if (awaitedSession && $openModals.get().includes("signin")) {
3124
+ client.requestSignin();
3125
+ return;
3126
+ }
3127
+ if ($ws.get().ready) void isUserSignedIn();
3047
3128
  };
3048
3129
  const deletion = createDeletionService({ provider });
3049
3130
  const handleUserDeleted = (forAddress = null) => {
@@ -3067,7 +3148,7 @@ function createAuthRuntime(client, callbacks = {}) {
3067
3148
  if (service === "blockauth" || prevDid && prevDid.toLowerCase() !== String(did).toLowerCase()) {
3068
3149
  browserBase.clearBrowserState({ keepExtensionInstalled: keepInstalled });
3069
3150
  }
3070
- void browserBase.setSession({
3151
+ sessionBridge = browserBase.setSession({
3071
3152
  ...result,
3072
3153
  serviceName: service,
3073
3154
  apiUrl: client.apiUrl
@@ -3302,6 +3383,7 @@ function createAuthRuntime(client, callbacks = {}) {
3302
3383
  setToken(_token);
3303
3384
  setIsSigned(success);
3304
3385
  hookState.isSigned = success;
3386
+ if (success) clearSessionExpiredMark();
3305
3387
  if (success && hookState.isUnsignTimeoutSet && message?.signedExpiredAt) {
3306
3388
  rearmUnsignTimeout(message.signedExpiredAt, _did);
3307
3389
  }
@@ -3460,6 +3542,7 @@ function createAuthRuntime(client, callbacks = {}) {
3460
3542
  }
3461
3543
  };
3462
3544
  const start = async () => {
3545
+ stopped = false;
3463
3546
  const s = browserBase.getSession();
3464
3547
  const externalService = browserBase.getExternalService();
3465
3548
  let _token = s.token;
@@ -3520,15 +3603,21 @@ function createAuthRuntime(client, callbacks = {}) {
3520
3603
  wsc().on("sdk:session:invalidated", onSdkSessionInvalidated);
3521
3604
  wsc().on("sdk:user:roles:changed", onSdkUserRolesChanged);
3522
3605
  wsc().on("sdk:restore", onSdkRestore);
3606
+ wsc().ws?.onAny(onAnyServerEvent);
3523
3607
  if (typeof window !== "undefined") {
3524
3608
  window.addEventListener("storage", onStorageLogout);
3525
3609
  }
3526
3610
  const { domain, signinCallbackUrl, config: config3 } = await provider.app();
3527
3611
  setUiConfig({ domain, signinCallbackUrl, config: config3 });
3528
3612
  setReady(true);
3613
+ if (externalService.service === "blockauth" && hasSessionExpiredMark()) {
3614
+ setIsSignedFirstCheck(true);
3615
+ return;
3616
+ }
3529
3617
  await isUserSignedIn();
3530
3618
  };
3531
3619
  const stop = () => {
3620
+ stopped = true;
3532
3621
  if (unsignTimeout) {
3533
3622
  clearTimeout(unsignTimeout);
3534
3623
  unsignTimeout = null;
@@ -3563,6 +3652,7 @@ function createAuthRuntime(client, callbacks = {}) {
3563
3652
  w.off("sdk:session:invalidated", onSdkSessionInvalidated);
3564
3653
  w.off("sdk:user:roles:changed", onSdkUserRolesChanged);
3565
3654
  w.off("sdk:restore", onSdkRestore);
3655
+ w.ws?.offAny(onAnyServerEvent);
3566
3656
  }
3567
3657
  if (typeof window !== "undefined") {
3568
3658
  window.removeEventListener("storage", onStorageLogout);
@@ -3700,13 +3790,17 @@ var TEXTS = {
3700
3790
  es: "No se encontraron transacciones",
3701
3791
  en: "No transactions found"
3702
3792
  },
3793
+ otpExpiredTitle: {
3794
+ es: "Verificaci\xF3n caducada",
3795
+ en: "Verification expired"
3796
+ },
3703
3797
  otpExpiredExtension: {
3704
- es: "Tu verificaci\xF3n ha caducado. Introduce tu c\xF3digo en la extensi\xF3n de Block-Auth para aprobar este acceso.",
3705
- en: "Your verification has expired. Enter your code in the Block-Auth extension to approve this access."
3798
+ es: "Introduce tu c\xF3digo en la extensi\xF3n de Block-Auth para aprobar este acceso.",
3799
+ en: "Enter your code in the Block-Auth extension to approve this access."
3706
3800
  },
3707
3801
  otpExpiredApp: {
3708
- es: "Tu verificaci\xF3n ha caducado. Introduce tu c\xF3digo en la app de Block-Auth para aprobar este acceso.",
3709
- en: "Your verification has expired. Enter your code in the Block-Auth app to approve this access."
3802
+ es: "Introduce tu c\xF3digo en la app de Block-Auth para aprobar este acceso.",
3803
+ en: "Enter your code in the Block-Auth app to approve this access."
3710
3804
  },
3711
3805
  openExtension: { es: "Abrir extensi\xF3n", en: "Open extension" },
3712
3806
  noAppKeyFound: {
@@ -3854,6 +3948,7 @@ exports.isValidPhoneValue = isValidPhoneValue;
3854
3948
  exports.loadUserProfile = loadUserProfile;
3855
3949
  exports.makeQrDataUrl = makeQrDataUrl;
3856
3950
  exports.markSdkPresence = markSdkPresence;
3951
+ exports.needsExtensionUnlock = needsExtensionUnlock;
3857
3952
  exports.normalizeParamValue = normalizeParamValue;
3858
3953
  exports.oauth = oauth_exports;
3859
3954
  exports.onExtensionRemoved = onExtensionRemoved;