@block-auth.io/core 0.13.0 → 0.14.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
@@ -846,12 +846,13 @@ declare namespace index$1 {
846
846
 
847
847
  interface BlockAuthClientConfig {
848
848
  apiKey: string;
849
- apiSecret: string;
849
+ apiSecret?: string;
850
850
  /** Opcional: token emitido por tu backend vía POST /api/browser-token.
851
851
  * Si está presente, signin() lo usa en lugar del apiSecret — en navegador
852
852
  * deja apiSecret vacío para que el secreto nunca llegue al cliente. */
853
853
  browserToken?: string;
854
854
  wsUrl?: string;
855
+ authEndpoint?: string;
855
856
  /** blockauth-api base url, first-party apps only (its CORS admits no other
856
857
  * origin). With it, the session lives in the httpOnly cookie
857
858
  * (POST /auth/session, POST /auth/logout, GET /auth/ws-ticket). Without
@@ -1221,6 +1222,12 @@ declare function createBlockAuthClient(config: BlockAuthClientConfig): {
1221
1222
  loginWithPopup: () => Promise<PopupLoginResult>;
1222
1223
  authorizeWithPopup: () => Promise<PopupAuthCode>;
1223
1224
  rememberHostedLogin: (user: HostedLoginUser) => void;
1225
+ forgetHostedLogin: () => void;
1226
+ hasAuthEndpoint: boolean;
1227
+ loginWithAuthEndpoint: () => Promise<HostedLoginUser>;
1228
+ getAccountLinkStatus: () => Promise<boolean | null>;
1229
+ linkWithAuthEndpoint: () => Promise<void>;
1230
+ restoreHostedLogin: () => Promise<HostedLoginUser | null>;
1224
1231
  oauth: {
1225
1232
  signupGoogle: (flow?: "auth-code" | "implicit") => Promise<void>;
1226
1233
  signupMicrosoft: () => Promise<void>;
@@ -1261,6 +1268,13 @@ declare function createBlockAuthClient(config: BlockAuthClientConfig): {
1261
1268
  };
1262
1269
  type BlockAuthClient = ReturnType<typeof createBlockAuthClient>;
1263
1270
 
1271
+ type AccountLinkErrorReason = 'already_linked' | 'not_signed_in' | 'failed';
1272
+ declare class AccountLinkError extends Error {
1273
+ readonly reason: AccountLinkErrorReason;
1274
+ readonly status: number;
1275
+ constructor(reason: AccountLinkErrorReason, status: number);
1276
+ }
1277
+
1264
1278
  type TxnDataMode = 'required' | 'optional';
1265
1279
  type TxnDataStatus = 'shared' | 'granted' | 'consent' | 'missing';
1266
1280
  interface TxnDataEmail {
@@ -2217,4 +2231,4 @@ declare function resetExtensionSyncModuleState(): void;
2217
2231
  */
2218
2232
  declare function startExtensionSync(): () => void;
2219
2233
 
2220
- export { $extension, $locale, $openModals, $ui, $user, $wallet, $web3, $ws, type AuthRuntime, type AuthRuntimeCallbacks, type BlockAuthClient, type BlockAuthClientConfig, BlockAuthProvider, type BlockAuthProviderOptions, type BlockAuthUserProfile, type BlockAuthUserRole, DEFAULT_PHONE_COUNTRY, DISCOVERY_TIMEOUT_MS, type DeletionServiceDeps, EMPTY_SOLICITED_DATA_FORM, type EvmOptions, type EvmWallet, type ExtensionState, type HostedLoginUser, type Locale, type LoginPopupResult, type ModalName, type OpenLoginPopupOptions, PARAM_DISPLAY_FORMATTERS, PARAM_DISPLAY_ORDER, PARAM_ERROR_KEYS, PARAM_INPUT_TYPE, PARAM_LABEL_KEYS, PARAM_NORMALIZERS, PARAM_VALIDATORS, type PhoneCountry, type PhoneCountryCode, type PhoneDraft, type PhoneParts, type PopupAuthCode, type PopupLoginOptions, type PopupLoginResult, type RestoreResult, RpcClient, SDK_PAGE_MARKER, SYNC_TIMEOUT_MS, type SolanaWallet, type SolicitedAcceptParams, type SolicitedDataForm, type SolicitedEmailChoice, type SolicitedField, type SolicitedParam, TEXTS, type TextKey, type TxnDataEmail, type TxnDataMode, type TxnDataParam, type TxnDataRequest, type TxnDataStatus, type TxnRequest, type UiState, type UserProfileProvider, type UserState, type WalletKind, type WalletState, type Web3SignupState, WsClient, type WsState, appearsExtensionInstalled, buildPhoneE164, buildPhoneValue, clearExtensionDomMarkers, clearRemainingAuthData, clearSdkPresence, closeAllModals, closeModal, confirmExtensionPresence, createAuthRuntime, createBlockAuthClient, createDeletionService, createEvmWallet, createSolanaWallet, deepLinkFor, discoverExtensionOnce, fetchUserProfile, finalizeAfterRestorationExpired, formatParamValue, formatPhoneForDisplay, formatSolicitedEmailOption, 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, isSolicitedEmailSelectable, isSolicitedHintSuccess, isValidParamValue, isValidPhoneValue, loadUserProfile, makeQrDataUrl, markSdkPresence, needsExtensionUnlock, normalizeParamValue, index$1 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, setSolicitedEmailChoice, setSolicitedShared, setSolicitedValue, setToken, setUiConfig, setUser, setWaitingForSuccessLogInSince, startExtensionSync, syncExtensionStateFromStorage, t, toPhoneE164, undoSolicitedValue, updatePhoneDraft, index as utils };
2234
+ export { $extension, $locale, $openModals, $ui, $user, $wallet, $web3, $ws, AccountLinkError, type AccountLinkErrorReason, type AuthRuntime, type AuthRuntimeCallbacks, type BlockAuthClient, type BlockAuthClientConfig, BlockAuthProvider, type BlockAuthProviderOptions, type BlockAuthUserProfile, type BlockAuthUserRole, DEFAULT_PHONE_COUNTRY, DISCOVERY_TIMEOUT_MS, type DeletionServiceDeps, EMPTY_SOLICITED_DATA_FORM, type EvmOptions, type EvmWallet, type ExtensionState, type HostedLoginUser, type Locale, type LoginPopupResult, type ModalName, type OpenLoginPopupOptions, PARAM_DISPLAY_FORMATTERS, PARAM_DISPLAY_ORDER, PARAM_ERROR_KEYS, PARAM_INPUT_TYPE, PARAM_LABEL_KEYS, PARAM_NORMALIZERS, PARAM_VALIDATORS, type PhoneCountry, type PhoneCountryCode, type PhoneDraft, type PhoneParts, type PopupAuthCode, type PopupLoginOptions, type PopupLoginResult, type RestoreResult, RpcClient, SDK_PAGE_MARKER, SYNC_TIMEOUT_MS, type SolanaWallet, type SolicitedAcceptParams, type SolicitedDataForm, type SolicitedEmailChoice, type SolicitedField, type SolicitedParam, TEXTS, type TextKey, type TxnDataEmail, type TxnDataMode, type TxnDataParam, type TxnDataRequest, type TxnDataStatus, type TxnRequest, type UiState, type UserProfileProvider, type UserState, type WalletKind, type WalletState, type Web3SignupState, WsClient, type WsState, appearsExtensionInstalled, buildPhoneE164, buildPhoneValue, clearExtensionDomMarkers, clearRemainingAuthData, clearSdkPresence, closeAllModals, closeModal, confirmExtensionPresence, createAuthRuntime, createBlockAuthClient, createDeletionService, createEvmWallet, createSolanaWallet, deepLinkFor, discoverExtensionOnce, fetchUserProfile, finalizeAfterRestorationExpired, formatParamValue, formatPhoneForDisplay, formatSolicitedEmailOption, 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, isSolicitedEmailSelectable, isSolicitedHintSuccess, isValidParamValue, isValidPhoneValue, loadUserProfile, makeQrDataUrl, markSdkPresence, needsExtensionUnlock, normalizeParamValue, index$1 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, setSolicitedEmailChoice, setSolicitedShared, setSolicitedValue, setToken, setUiConfig, setUser, setWaitingForSuccessLogInSince, startExtensionSync, syncExtensionStateFromStorage, t, toPhoneE164, undoSolicitedValue, updatePhoneDraft, index as utils };
package/dist/index.d.ts CHANGED
@@ -846,12 +846,13 @@ declare namespace index$1 {
846
846
 
847
847
  interface BlockAuthClientConfig {
848
848
  apiKey: string;
849
- apiSecret: string;
849
+ apiSecret?: string;
850
850
  /** Opcional: token emitido por tu backend vía POST /api/browser-token.
851
851
  * Si está presente, signin() lo usa en lugar del apiSecret — en navegador
852
852
  * deja apiSecret vacío para que el secreto nunca llegue al cliente. */
853
853
  browserToken?: string;
854
854
  wsUrl?: string;
855
+ authEndpoint?: string;
855
856
  /** blockauth-api base url, first-party apps only (its CORS admits no other
856
857
  * origin). With it, the session lives in the httpOnly cookie
857
858
  * (POST /auth/session, POST /auth/logout, GET /auth/ws-ticket). Without
@@ -1221,6 +1222,12 @@ declare function createBlockAuthClient(config: BlockAuthClientConfig): {
1221
1222
  loginWithPopup: () => Promise<PopupLoginResult>;
1222
1223
  authorizeWithPopup: () => Promise<PopupAuthCode>;
1223
1224
  rememberHostedLogin: (user: HostedLoginUser) => void;
1225
+ forgetHostedLogin: () => void;
1226
+ hasAuthEndpoint: boolean;
1227
+ loginWithAuthEndpoint: () => Promise<HostedLoginUser>;
1228
+ getAccountLinkStatus: () => Promise<boolean | null>;
1229
+ linkWithAuthEndpoint: () => Promise<void>;
1230
+ restoreHostedLogin: () => Promise<HostedLoginUser | null>;
1224
1231
  oauth: {
1225
1232
  signupGoogle: (flow?: "auth-code" | "implicit") => Promise<void>;
1226
1233
  signupMicrosoft: () => Promise<void>;
@@ -1261,6 +1268,13 @@ declare function createBlockAuthClient(config: BlockAuthClientConfig): {
1261
1268
  };
1262
1269
  type BlockAuthClient = ReturnType<typeof createBlockAuthClient>;
1263
1270
 
1271
+ type AccountLinkErrorReason = 'already_linked' | 'not_signed_in' | 'failed';
1272
+ declare class AccountLinkError extends Error {
1273
+ readonly reason: AccountLinkErrorReason;
1274
+ readonly status: number;
1275
+ constructor(reason: AccountLinkErrorReason, status: number);
1276
+ }
1277
+
1264
1278
  type TxnDataMode = 'required' | 'optional';
1265
1279
  type TxnDataStatus = 'shared' | 'granted' | 'consent' | 'missing';
1266
1280
  interface TxnDataEmail {
@@ -2217,4 +2231,4 @@ declare function resetExtensionSyncModuleState(): void;
2217
2231
  */
2218
2232
  declare function startExtensionSync(): () => void;
2219
2233
 
2220
- export { $extension, $locale, $openModals, $ui, $user, $wallet, $web3, $ws, type AuthRuntime, type AuthRuntimeCallbacks, type BlockAuthClient, type BlockAuthClientConfig, BlockAuthProvider, type BlockAuthProviderOptions, type BlockAuthUserProfile, type BlockAuthUserRole, DEFAULT_PHONE_COUNTRY, DISCOVERY_TIMEOUT_MS, type DeletionServiceDeps, EMPTY_SOLICITED_DATA_FORM, type EvmOptions, type EvmWallet, type ExtensionState, type HostedLoginUser, type Locale, type LoginPopupResult, type ModalName, type OpenLoginPopupOptions, PARAM_DISPLAY_FORMATTERS, PARAM_DISPLAY_ORDER, PARAM_ERROR_KEYS, PARAM_INPUT_TYPE, PARAM_LABEL_KEYS, PARAM_NORMALIZERS, PARAM_VALIDATORS, type PhoneCountry, type PhoneCountryCode, type PhoneDraft, type PhoneParts, type PopupAuthCode, type PopupLoginOptions, type PopupLoginResult, type RestoreResult, RpcClient, SDK_PAGE_MARKER, SYNC_TIMEOUT_MS, type SolanaWallet, type SolicitedAcceptParams, type SolicitedDataForm, type SolicitedEmailChoice, type SolicitedField, type SolicitedParam, TEXTS, type TextKey, type TxnDataEmail, type TxnDataMode, type TxnDataParam, type TxnDataRequest, type TxnDataStatus, type TxnRequest, type UiState, type UserProfileProvider, type UserState, type WalletKind, type WalletState, type Web3SignupState, WsClient, type WsState, appearsExtensionInstalled, buildPhoneE164, buildPhoneValue, clearExtensionDomMarkers, clearRemainingAuthData, clearSdkPresence, closeAllModals, closeModal, confirmExtensionPresence, createAuthRuntime, createBlockAuthClient, createDeletionService, createEvmWallet, createSolanaWallet, deepLinkFor, discoverExtensionOnce, fetchUserProfile, finalizeAfterRestorationExpired, formatParamValue, formatPhoneForDisplay, formatSolicitedEmailOption, 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, isSolicitedEmailSelectable, isSolicitedHintSuccess, isValidParamValue, isValidPhoneValue, loadUserProfile, makeQrDataUrl, markSdkPresence, needsExtensionUnlock, normalizeParamValue, index$1 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, setSolicitedEmailChoice, setSolicitedShared, setSolicitedValue, setToken, setUiConfig, setUser, setWaitingForSuccessLogInSince, startExtensionSync, syncExtensionStateFromStorage, t, toPhoneE164, undoSolicitedValue, updatePhoneDraft, index as utils };
2234
+ export { $extension, $locale, $openModals, $ui, $user, $wallet, $web3, $ws, AccountLinkError, type AccountLinkErrorReason, type AuthRuntime, type AuthRuntimeCallbacks, type BlockAuthClient, type BlockAuthClientConfig, BlockAuthProvider, type BlockAuthProviderOptions, type BlockAuthUserProfile, type BlockAuthUserRole, DEFAULT_PHONE_COUNTRY, DISCOVERY_TIMEOUT_MS, type DeletionServiceDeps, EMPTY_SOLICITED_DATA_FORM, type EvmOptions, type EvmWallet, type ExtensionState, type HostedLoginUser, type Locale, type LoginPopupResult, type ModalName, type OpenLoginPopupOptions, PARAM_DISPLAY_FORMATTERS, PARAM_DISPLAY_ORDER, PARAM_ERROR_KEYS, PARAM_INPUT_TYPE, PARAM_LABEL_KEYS, PARAM_NORMALIZERS, PARAM_VALIDATORS, type PhoneCountry, type PhoneCountryCode, type PhoneDraft, type PhoneParts, type PopupAuthCode, type PopupLoginOptions, type PopupLoginResult, type RestoreResult, RpcClient, SDK_PAGE_MARKER, SYNC_TIMEOUT_MS, type SolanaWallet, type SolicitedAcceptParams, type SolicitedDataForm, type SolicitedEmailChoice, type SolicitedField, type SolicitedParam, TEXTS, type TextKey, type TxnDataEmail, type TxnDataMode, type TxnDataParam, type TxnDataRequest, type TxnDataStatus, type TxnRequest, type UiState, type UserProfileProvider, type UserState, type WalletKind, type WalletState, type Web3SignupState, WsClient, type WsState, appearsExtensionInstalled, buildPhoneE164, buildPhoneValue, clearExtensionDomMarkers, clearRemainingAuthData, clearSdkPresence, closeAllModals, closeModal, confirmExtensionPresence, createAuthRuntime, createBlockAuthClient, createDeletionService, createEvmWallet, createSolanaWallet, deepLinkFor, discoverExtensionOnce, fetchUserProfile, finalizeAfterRestorationExpired, formatParamValue, formatPhoneForDisplay, formatSolicitedEmailOption, 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, isSolicitedEmailSelectable, isSolicitedHintSuccess, isValidParamValue, isValidPhoneValue, loadUserProfile, makeQrDataUrl, markSdkPresence, needsExtensionUnlock, normalizeParamValue, index$1 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, setSolicitedEmailChoice, setSolicitedShared, setSolicitedValue, setToken, setUiConfig, setUser, setWaitingForSuccessLogInSince, startExtensionSync, syncExtensionStateFromStorage, t, toPhoneE164, undoSolicitedValue, updatePhoneDraft, index as utils };
package/dist/index.js CHANGED
@@ -2225,6 +2225,83 @@ function loginWithPopup(options) {
2225
2225
  return loginInFlight;
2226
2226
  }
2227
2227
 
2228
+ // src/auth/authEndpoint.ts
2229
+ var AccountLinkError = class extends Error {
2230
+ constructor(reason, status) {
2231
+ super(`authEndpoint /link failed (${status})`);
2232
+ this.reason = reason;
2233
+ this.status = status;
2234
+ this.name = "AccountLinkError";
2235
+ }
2236
+ };
2237
+ function toUser(payload) {
2238
+ const { address, did, roles } = payload ?? {};
2239
+ if (typeof address !== "string" || !address) {
2240
+ throw new Error("Invalid user from authEndpoint");
2241
+ }
2242
+ const user = {
2243
+ address,
2244
+ roles: Array.isArray(roles) ? roles : []
2245
+ };
2246
+ if (typeof did === "string" && did) user.did = did;
2247
+ return user;
2248
+ }
2249
+ function createAuthEndpoint(baseUrl) {
2250
+ const base = baseUrl.replace(/\/+$/, "");
2251
+ const request = (path, init) => fetch(`${base}${path}`, {
2252
+ ...init,
2253
+ credentials: "include",
2254
+ cache: "no-store",
2255
+ redirect: "error"
2256
+ });
2257
+ const postJson = (path, body) => request(path, {
2258
+ method: "POST",
2259
+ headers: { "Content-Type": "application/json" },
2260
+ body: JSON.stringify(body)
2261
+ });
2262
+ const fail = (path, response) => {
2263
+ throw new Error(`authEndpoint ${path} failed (${response.status})`);
2264
+ };
2265
+ return {
2266
+ redeem: async ({ code, codeVerifier, redirectUri }) => {
2267
+ const response = await postJson("/code", {
2268
+ code,
2269
+ codeVerifier,
2270
+ redirectUri
2271
+ });
2272
+ if (!response.ok) fail("/code", response);
2273
+ return toUser(await response.json());
2274
+ },
2275
+ me: async () => {
2276
+ const response = await request("/me", { method: "GET" });
2277
+ if (response.status === 401) return null;
2278
+ if (!response.ok) fail("/me", response);
2279
+ return toUser(await response.json());
2280
+ },
2281
+ logout: async () => {
2282
+ const response = await postJson("/logout", {});
2283
+ if (!response.ok) fail("/logout", response);
2284
+ },
2285
+ linkStatus: async () => {
2286
+ const response = await request("/link", { method: "GET" });
2287
+ if (response.status === 401) return null;
2288
+ if (!response.ok) fail("/link", response);
2289
+ const { linked } = await response.json();
2290
+ return linked === true;
2291
+ },
2292
+ link: async ({ code, codeVerifier, redirectUri }) => {
2293
+ const response = await postJson("/link", {
2294
+ code,
2295
+ codeVerifier,
2296
+ redirectUri
2297
+ });
2298
+ if (response.ok) return;
2299
+ const reason = response.status === 409 ? "already_linked" : response.status === 401 ? "not_signed_in" : "failed";
2300
+ throw new AccountLinkError(reason, response.status);
2301
+ }
2302
+ };
2303
+ }
2304
+
2228
2305
  // src/auth/logout.ts
2229
2306
  async function performLogout(args) {
2230
2307
  const { wsc, token, apiKey, sessionId, apiUrl } = args;
@@ -2479,9 +2556,9 @@ async function signInWithMicrosoft(overrides = {}) {
2479
2556
  setServiceIcon(imgUrlByService("microsoft"));
2480
2557
  return { accessToken: response.accessToken, response };
2481
2558
  }
2482
- function rememberHostedLogin(result) {
2559
+ function showHostedUser(result) {
2483
2560
  const did = result.did ?? result.address;
2484
- browserBase.setSession({ did, serviceName: "blockauth" });
2561
+ setDid(did);
2485
2562
  setUser({
2486
2563
  address: result.address,
2487
2564
  did,
@@ -2491,9 +2568,22 @@ function rememberHostedLogin(result) {
2491
2568
  setIsServiceConnected(true);
2492
2569
  setIsSigned(true);
2493
2570
  setIsSignedFirstCheck(true);
2571
+ return did;
2572
+ }
2573
+ function rememberHostedLogin(result) {
2574
+ const did = showHostedUser(result);
2575
+ browserBase.setSession({ did, serviceName: "blockauth" });
2576
+ }
2577
+ function forgetHostedUser() {
2578
+ resetUser();
2579
+ setDid(null);
2580
+ setIsServiceConnected(false);
2581
+ setIsSigned(false);
2582
+ setIsSignedFirstCheck(true);
2494
2583
  }
2495
2584
  function createBlockAuthClient(config3) {
2496
2585
  if (config3.locale) setLocale(config3.locale);
2586
+ const authEndpoint = config3.authEndpoint ? createAuthEndpoint(config3.authEndpoint) : null;
2497
2587
  const provider = new BlockAuthProvider(
2498
2588
  config3.apiKey,
2499
2589
  config3.apiSecret,
@@ -2587,7 +2677,36 @@ function createBlockAuthClient(config3) {
2587
2677
  authorizeWithPopup: () => authorizeWithPopup({ apiKey: config3.apiKey, wsUrl: config3.wsUrl }),
2588
2678
  // After the backend redeemed the code: shows the user in the page's UI
2589
2679
  // (profile dropdown, roles). The backend's answer is the source of truth.
2590
- rememberHostedLogin: (user) => rememberHostedLogin(user),
2680
+ rememberHostedLogin: (user) => {
2681
+ showHostedUser(user);
2682
+ },
2683
+ forgetHostedLogin: () => forgetHostedUser(),
2684
+ hasAuthEndpoint: Boolean(authEndpoint),
2685
+ loginWithAuthEndpoint: async () => {
2686
+ if (!authEndpoint) throw new Error("authEndpoint not configured");
2687
+ const user = await authEndpoint.redeem(
2688
+ await authorizeWithPopup({ apiKey: config3.apiKey, wsUrl: config3.wsUrl })
2689
+ );
2690
+ showHostedUser(user);
2691
+ return user;
2692
+ },
2693
+ getAccountLinkStatus: async () => {
2694
+ if (!authEndpoint) return null;
2695
+ return authEndpoint.linkStatus();
2696
+ },
2697
+ linkWithAuthEndpoint: async () => {
2698
+ if (!authEndpoint) throw new Error("authEndpoint not configured");
2699
+ await authEndpoint.link(
2700
+ await authorizeWithPopup({ apiKey: config3.apiKey, wsUrl: config3.wsUrl })
2701
+ );
2702
+ },
2703
+ restoreHostedLogin: async () => {
2704
+ if (!authEndpoint) return null;
2705
+ const user = await authEndpoint.me();
2706
+ if (user) showHostedUser(user);
2707
+ else forgetHostedUser();
2708
+ return user;
2709
+ },
2591
2710
  // oauth
2592
2711
  oauth: {
2593
2712
  ...oauth_exports,
@@ -2664,13 +2783,16 @@ function createBlockAuthClient(config3) {
2664
2783
  // full deletion-state teardown after the user confirms the
2665
2784
  // restoration-expired modal.
2666
2785
  finalizeRestorationExpired: () => finalizeAfterRestorationExpired(),
2667
- logout: () => performLogout({
2668
- wsc: provider.wsc,
2669
- token: userToken(),
2670
- apiKey: config3.apiKey,
2671
- sessionId: browserBase.getDeviceSessionId(),
2672
- apiUrl: config3.apiUrl
2673
- }),
2786
+ logout: async () => {
2787
+ if (authEndpoint && !config3.apiUrl) await authEndpoint.logout();
2788
+ await performLogout({
2789
+ wsc: provider.wsc,
2790
+ token: userToken(),
2791
+ apiKey: config3.apiKey,
2792
+ sessionId: browserBase.getDeviceSessionId(),
2793
+ apiUrl: config3.apiUrl
2794
+ });
2795
+ },
2674
2796
  // modals (stack — supports overlaying signin on top of signup)
2675
2797
  openModal,
2676
2798
  closeModal,
@@ -3803,6 +3925,13 @@ function createAuthRuntime(client, callbacks = {}) {
3803
3925
  );
3804
3926
  });
3805
3927
  };
3928
+ const onSocketReconnect = () => {
3929
+ if (stopped || hookState.isLoggingOut || !hookState.isSigned) return;
3930
+ const externalService = browserBase.getExternalService();
3931
+ const did = externalService.service && externalService.service !== "blockauth" ? externalService.did : browserBase.getSession().did;
3932
+ if (!did) return;
3933
+ emitSdkSign(wsc().accessToken, did);
3934
+ };
3806
3935
  const onSdkUserRolesChanged = async (data) => {
3807
3936
  const { success, message } = data || {};
3808
3937
  if (!success || !message?.address) return;
@@ -3912,6 +4041,7 @@ function createAuthRuntime(client, callbacks = {}) {
3912
4041
  wsc().on("sdk:user:roles:changed", onSdkUserRolesChanged);
3913
4042
  wsc().on("sdk:restore", onSdkRestore);
3914
4043
  wsc().ws?.onAny(onAnyServerEvent);
4044
+ wsc().ws?.on("connect", onSocketReconnect);
3915
4045
  if (typeof window !== "undefined") {
3916
4046
  window.addEventListener("storage", onStorageLogout);
3917
4047
  }
@@ -3961,6 +4091,7 @@ function createAuthRuntime(client, callbacks = {}) {
3961
4091
  w.off("sdk:user:roles:changed", onSdkUserRolesChanged);
3962
4092
  w.off("sdk:restore", onSdkRestore);
3963
4093
  w.ws?.offAny(onAnyServerEvent);
4094
+ w.ws?.off("connect", onSocketReconnect);
3964
4095
  }
3965
4096
  if (typeof window !== "undefined") {
3966
4097
  window.removeEventListener("storage", onStorageLogout);
@@ -4232,6 +4363,6 @@ function t(key, locale = "en") {
4232
4363
  return entry?.[locale] ?? entry?.en ?? key;
4233
4364
  }
4234
4365
 
4235
- 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, formatSolicitedEmailOption, 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, isSolicitedEmailSelectable, 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, setSolicitedEmailChoice, setSolicitedShared, setSolicitedValue, setToken, setUiConfig, setUser, setWaitingForSuccessLogInSince, startExtensionSync, syncExtensionStateFromStorage, t, toPhoneE164, undoSolicitedValue, updatePhoneDraft, utils_exports as utils };
4366
+ export { $extension, $locale, $openModals, $ui, $user, $wallet, $web3, $ws, AccountLinkError, 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, formatSolicitedEmailOption, 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, isSolicitedEmailSelectable, 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, setSolicitedEmailChoice, setSolicitedShared, setSolicitedValue, setToken, setUiConfig, setUser, setWaitingForSuccessLogInSince, startExtensionSync, syncExtensionStateFromStorage, t, toPhoneE164, undoSolicitedValue, updatePhoneDraft, utils_exports as utils };
4236
4367
  //# sourceMappingURL=index.js.map
4237
4368
  //# sourceMappingURL=index.js.map