@block-auth.io/core 0.13.1 → 0.15.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,15 @@ 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 | false;
856
+ sessionCheckSeconds?: number;
857
+ onSessionEnded?: () => void;
855
858
  /** blockauth-api base url, first-party apps only (its CORS admits no other
856
859
  * origin). With it, the session lives in the httpOnly cookie
857
860
  * (POST /auth/session, POST /auth/logout, GET /auth/ws-ticket). Without
@@ -1220,7 +1223,16 @@ declare function createBlockAuthClient(config: BlockAuthClientConfig): {
1220
1223
  connectBlockAuth: () => void;
1221
1224
  loginWithPopup: () => Promise<PopupLoginResult>;
1222
1225
  authorizeWithPopup: () => Promise<PopupAuthCode>;
1223
- rememberHostedLogin: (user: HostedLoginUser) => void;
1226
+ rememberHostedLogin: (user: HostedLoginUser, options?: {
1227
+ ownsAuthCode?: boolean;
1228
+ }) => void;
1229
+ forgetHostedLogin: () => void;
1230
+ hasAuthEndpoint: boolean;
1231
+ usesAuthEndpoint: (ownsAuthCode?: boolean) => boolean;
1232
+ loginWithAuthEndpoint: () => Promise<HostedLoginUser>;
1233
+ getAccountLinkStatus: () => Promise<boolean | null>;
1234
+ linkWithAuthEndpoint: () => Promise<void>;
1235
+ restoreHostedLogin: () => Promise<HostedLoginUser | null>;
1224
1236
  oauth: {
1225
1237
  signupGoogle: (flow?: "auth-code" | "implicit") => Promise<void>;
1226
1238
  signupMicrosoft: () => Promise<void>;
@@ -1261,6 +1273,13 @@ declare function createBlockAuthClient(config: BlockAuthClientConfig): {
1261
1273
  };
1262
1274
  type BlockAuthClient = ReturnType<typeof createBlockAuthClient>;
1263
1275
 
1276
+ type AccountLinkErrorReason = 'already_linked' | 'not_signed_in' | 'failed';
1277
+ declare class AccountLinkError extends Error {
1278
+ readonly reason: AccountLinkErrorReason;
1279
+ readonly status: number;
1280
+ constructor(reason: AccountLinkErrorReason, status: number);
1281
+ }
1282
+
1264
1283
  type TxnDataMode = 'required' | 'optional';
1265
1284
  type TxnDataStatus = 'shared' | 'granted' | 'consent' | 'missing';
1266
1285
  interface TxnDataEmail {
@@ -2217,4 +2236,4 @@ declare function resetExtensionSyncModuleState(): void;
2217
2236
  */
2218
2237
  declare function startExtensionSync(): () => void;
2219
2238
 
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 };
2239
+ 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,15 @@ 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 | false;
856
+ sessionCheckSeconds?: number;
857
+ onSessionEnded?: () => void;
855
858
  /** blockauth-api base url, first-party apps only (its CORS admits no other
856
859
  * origin). With it, the session lives in the httpOnly cookie
857
860
  * (POST /auth/session, POST /auth/logout, GET /auth/ws-ticket). Without
@@ -1220,7 +1223,16 @@ declare function createBlockAuthClient(config: BlockAuthClientConfig): {
1220
1223
  connectBlockAuth: () => void;
1221
1224
  loginWithPopup: () => Promise<PopupLoginResult>;
1222
1225
  authorizeWithPopup: () => Promise<PopupAuthCode>;
1223
- rememberHostedLogin: (user: HostedLoginUser) => void;
1226
+ rememberHostedLogin: (user: HostedLoginUser, options?: {
1227
+ ownsAuthCode?: boolean;
1228
+ }) => void;
1229
+ forgetHostedLogin: () => void;
1230
+ hasAuthEndpoint: boolean;
1231
+ usesAuthEndpoint: (ownsAuthCode?: boolean) => boolean;
1232
+ loginWithAuthEndpoint: () => Promise<HostedLoginUser>;
1233
+ getAccountLinkStatus: () => Promise<boolean | null>;
1234
+ linkWithAuthEndpoint: () => Promise<void>;
1235
+ restoreHostedLogin: () => Promise<HostedLoginUser | null>;
1224
1236
  oauth: {
1225
1237
  signupGoogle: (flow?: "auth-code" | "implicit") => Promise<void>;
1226
1238
  signupMicrosoft: () => Promise<void>;
@@ -1261,6 +1273,13 @@ declare function createBlockAuthClient(config: BlockAuthClientConfig): {
1261
1273
  };
1262
1274
  type BlockAuthClient = ReturnType<typeof createBlockAuthClient>;
1263
1275
 
1276
+ type AccountLinkErrorReason = 'already_linked' | 'not_signed_in' | 'failed';
1277
+ declare class AccountLinkError extends Error {
1278
+ readonly reason: AccountLinkErrorReason;
1279
+ readonly status: number;
1280
+ constructor(reason: AccountLinkErrorReason, status: number);
1281
+ }
1282
+
1264
1283
  type TxnDataMode = 'required' | 'optional';
1265
1284
  type TxnDataStatus = 'shared' | 'granted' | 'consent' | 'missing';
1266
1285
  interface TxnDataEmail {
@@ -2217,4 +2236,4 @@ declare function resetExtensionSyncModuleState(): void;
2217
2236
  */
2218
2237
  declare function startExtensionSync(): () => void;
2219
2238
 
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 };
2239
+ 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,189 @@ function loginWithPopup(options) {
2225
2225
  return loginInFlight;
2226
2226
  }
2227
2227
 
2228
+ // src/auth/authEndpoint.ts
2229
+ var DEFAULT_AUTH_ENDPOINT = "/auth/blockauth";
2230
+ var BACKEND_ROUTES_GUIDE = "https://docs.block-auth.io/sdk-integration-spa-backend/#backend-routes";
2231
+ var AccountLinkError = class extends Error {
2232
+ constructor(reason, status) {
2233
+ super(`authEndpoint /link failed (${status})`);
2234
+ this.reason = reason;
2235
+ this.status = status;
2236
+ this.name = "AccountLinkError";
2237
+ }
2238
+ };
2239
+ function toUser(payload) {
2240
+ const { address, did, roles } = payload ?? {};
2241
+ if (typeof address !== "string" || !address) {
2242
+ throw new Error("Invalid user from authEndpoint");
2243
+ }
2244
+ const user = {
2245
+ address,
2246
+ roles: Array.isArray(roles) ? roles : []
2247
+ };
2248
+ if (typeof did === "string" && did) user.did = did;
2249
+ return user;
2250
+ }
2251
+ function createAuthEndpoint(baseUrl) {
2252
+ const base = baseUrl.replace(/\/+$/, "");
2253
+ const hinted = /* @__PURE__ */ new Set();
2254
+ const hint = (key, message) => {
2255
+ if (hinted.has(key)) return;
2256
+ hinted.add(key);
2257
+ console.error(
2258
+ `[Block-Auth] ${message} authEndpoint is "${base}". Guide: ${BACKEND_ROUTES_GUIDE}`
2259
+ );
2260
+ };
2261
+ const request = async (path, init) => {
2262
+ try {
2263
+ return await fetch(`${base}${path}`, {
2264
+ ...init,
2265
+ credentials: "include",
2266
+ cache: "no-store",
2267
+ redirect: "error"
2268
+ });
2269
+ } catch (error) {
2270
+ if (error instanceof TypeError) {
2271
+ hint(
2272
+ `network ${path}`,
2273
+ `${init.method} ${base}${path} did not reach your backend. If it runs on another origin, allow this origin in its CORS with credentials, or serve it under this origin. It must answer without redirects.`
2274
+ );
2275
+ }
2276
+ throw error;
2277
+ }
2278
+ };
2279
+ const readJson = async (path, response) => {
2280
+ try {
2281
+ return await response.json();
2282
+ } catch (error) {
2283
+ hint(
2284
+ `json ${path}`,
2285
+ `${base}${path} answered ${response.status} without JSON. The request is probably served by your frontend (a SPA fallback or a dev server without a proxy to your backend).`
2286
+ );
2287
+ throw error;
2288
+ }
2289
+ };
2290
+ const postJson = (path, body) => request(path, {
2291
+ method: "POST",
2292
+ headers: { "Content-Type": "application/json" },
2293
+ body: JSON.stringify(body)
2294
+ });
2295
+ const readUser = async (path, response) => {
2296
+ const payload = await readJson(path, response);
2297
+ try {
2298
+ return toUser(payload);
2299
+ } catch (error) {
2300
+ hint(
2301
+ `user ${path}`,
2302
+ `${base}${path} must answer { address, did, roles } from the user Block-Auth returned.`
2303
+ );
2304
+ throw error;
2305
+ }
2306
+ };
2307
+ const fail = (path, response) => {
2308
+ if (response.status === 404 || response.status === 405) {
2309
+ hint(
2310
+ `missing ${path}`,
2311
+ `${base}${path} answered ${response.status}: add the ${path} route to your backend.`
2312
+ );
2313
+ } else if (path === "/code" && response.status >= 500) {
2314
+ hint(
2315
+ `redeem ${response.status}`,
2316
+ `${base}/code answered ${response.status}: your backend could not redeem the code. Check its logs and the apiKey, apiSecret hash and redirectUri it sends to /api/auth/token.`
2317
+ );
2318
+ }
2319
+ throw new Error(`authEndpoint ${path} failed (${response.status})`);
2320
+ };
2321
+ return {
2322
+ redeem: async ({ code, codeVerifier, redirectUri }) => {
2323
+ const response = await postJson("/code", {
2324
+ code,
2325
+ codeVerifier,
2326
+ redirectUri
2327
+ });
2328
+ if (!response.ok) fail("/code", response);
2329
+ return readUser("/code", response);
2330
+ },
2331
+ me: async () => {
2332
+ const response = await request("/me", { method: "GET" });
2333
+ if (response.status === 401) return null;
2334
+ if (!response.ok) fail("/me", response);
2335
+ return readUser("/me", response);
2336
+ },
2337
+ logout: async () => {
2338
+ const response = await postJson("/logout", {});
2339
+ if (!response.ok) fail("/logout", response);
2340
+ },
2341
+ linkStatus: async () => {
2342
+ const response = await request("/link", { method: "GET" });
2343
+ if (response.status === 401) return null;
2344
+ if (!response.ok) fail("/link", response);
2345
+ const { linked } = await readJson("/link", response);
2346
+ return linked === true;
2347
+ },
2348
+ link: async ({ code, codeVerifier, redirectUri }) => {
2349
+ const response = await postJson("/link", {
2350
+ code,
2351
+ codeVerifier,
2352
+ redirectUri
2353
+ });
2354
+ if (response.ok) return;
2355
+ const reason = response.status === 409 ? "already_linked" : response.status === 401 ? "not_signed_in" : "failed";
2356
+ throw new AccountLinkError(reason, response.status);
2357
+ }
2358
+ };
2359
+ }
2360
+
2361
+ // src/session/sessionWatch.ts
2362
+ var MAX_TIMER_MS = 2147483647;
2363
+ function createSessionWatch({
2364
+ check,
2365
+ onEnded,
2366
+ intervalMs,
2367
+ minGapMs = 5e3
2368
+ }) {
2369
+ let active = false;
2370
+ let timer = null;
2371
+ let running = false;
2372
+ let lastRun = 0;
2373
+ const run = async () => {
2374
+ if (!active || running || Date.now() - lastRun < minGapMs) return;
2375
+ running = true;
2376
+ lastRun = Date.now();
2377
+ try {
2378
+ const alive = await check();
2379
+ if (active && alive === false) {
2380
+ stop();
2381
+ onEnded();
2382
+ }
2383
+ } finally {
2384
+ running = false;
2385
+ }
2386
+ };
2387
+ const onVisible = () => {
2388
+ if (document.visibilityState === "visible") void run();
2389
+ };
2390
+ const onFocus = () => void run();
2391
+ function start() {
2392
+ if (active || !Number.isFinite(intervalMs) || intervalMs <= 0 || typeof window === "undefined")
2393
+ return;
2394
+ active = true;
2395
+ lastRun = Date.now();
2396
+ timer = setInterval(() => void run(), Math.min(intervalMs, MAX_TIMER_MS));
2397
+ document.addEventListener("visibilitychange", onVisible);
2398
+ window.addEventListener("focus", onFocus);
2399
+ }
2400
+ function stop() {
2401
+ if (!active) return;
2402
+ active = false;
2403
+ if (timer !== null) clearInterval(timer);
2404
+ timer = null;
2405
+ document.removeEventListener("visibilitychange", onVisible);
2406
+ window.removeEventListener("focus", onFocus);
2407
+ }
2408
+ return { start, stop };
2409
+ }
2410
+
2228
2411
  // src/auth/logout.ts
2229
2412
  async function performLogout(args) {
2230
2413
  const { wsc, token, apiKey, sessionId, apiUrl } = args;
@@ -2479,9 +2662,9 @@ async function signInWithMicrosoft(overrides = {}) {
2479
2662
  setServiceIcon(imgUrlByService("microsoft"));
2480
2663
  return { accessToken: response.accessToken, response };
2481
2664
  }
2482
- function rememberHostedLogin(result) {
2665
+ function showHostedUser(result) {
2483
2666
  const did = result.did ?? result.address;
2484
- browserBase.setSession({ did, serviceName: "blockauth" });
2667
+ setDid(did);
2485
2668
  setUser({
2486
2669
  address: result.address,
2487
2670
  did,
@@ -2491,9 +2674,34 @@ function rememberHostedLogin(result) {
2491
2674
  setIsServiceConnected(true);
2492
2675
  setIsSigned(true);
2493
2676
  setIsSignedFirstCheck(true);
2677
+ return did;
2678
+ }
2679
+ function rememberHostedLogin(result) {
2680
+ const did = showHostedUser(result);
2681
+ browserBase.setSession({ did, serviceName: "blockauth" });
2682
+ }
2683
+ function forgetHostedUser() {
2684
+ resetUser();
2685
+ setDid(null);
2686
+ setIsServiceConnected(false);
2687
+ setIsSigned(false);
2688
+ setIsSignedFirstCheck(true);
2494
2689
  }
2495
2690
  function createBlockAuthClient(config3) {
2496
2691
  if (config3.locale) setLocale(config3.locale);
2692
+ const authEndpointUrl = config3.authEndpoint === false ? null : config3.authEndpoint || (config3.apiUrl ? null : DEFAULT_AUTH_ENDPOINT);
2693
+ const authEndpoint = authEndpointUrl ? createAuthEndpoint(authEndpointUrl) : null;
2694
+ const isDefaultAuthEndpoint = Boolean(authEndpoint) && !config3.authEndpoint;
2695
+ const usesAuthEndpoint = (ownsAuthCode = false) => Boolean(authEndpoint) && !(ownsAuthCode && isDefaultAuthEndpoint);
2696
+ let sessionOnAuthEndpoint = Boolean(authEndpoint);
2697
+ const sessionWatch = authEndpoint ? createSessionWatch({
2698
+ check: () => authEndpoint.me().then((user) => user !== null).catch(() => null),
2699
+ onEnded: () => {
2700
+ forgetHostedUser();
2701
+ config3.onSessionEnded?.();
2702
+ },
2703
+ intervalMs: (config3.sessionCheckSeconds ?? 60) * 1e3
2704
+ }) : null;
2497
2705
  const provider = new BlockAuthProvider(
2498
2706
  config3.apiKey,
2499
2707
  config3.apiSecret,
@@ -2587,7 +2795,50 @@ function createBlockAuthClient(config3) {
2587
2795
  authorizeWithPopup: () => authorizeWithPopup({ apiKey: config3.apiKey, wsUrl: config3.wsUrl }),
2588
2796
  // After the backend redeemed the code: shows the user in the page's UI
2589
2797
  // (profile dropdown, roles). The backend's answer is the source of truth.
2590
- rememberHostedLogin: (user) => rememberHostedLogin(user),
2798
+ rememberHostedLogin: (user, options = {}) => {
2799
+ showHostedUser(user);
2800
+ sessionOnAuthEndpoint = usesAuthEndpoint(options.ownsAuthCode);
2801
+ if (sessionOnAuthEndpoint) sessionWatch?.start();
2802
+ },
2803
+ forgetHostedLogin: () => {
2804
+ sessionWatch?.stop();
2805
+ forgetHostedUser();
2806
+ },
2807
+ hasAuthEndpoint: Boolean(authEndpoint),
2808
+ usesAuthEndpoint,
2809
+ loginWithAuthEndpoint: async () => {
2810
+ if (!authEndpoint) throw new Error("authEndpoint not configured");
2811
+ const user = await authEndpoint.redeem(
2812
+ await authorizeWithPopup({ apiKey: config3.apiKey, wsUrl: config3.wsUrl })
2813
+ );
2814
+ showHostedUser(user);
2815
+ sessionOnAuthEndpoint = true;
2816
+ sessionWatch?.start();
2817
+ return user;
2818
+ },
2819
+ getAccountLinkStatus: async () => {
2820
+ if (!authEndpoint) return null;
2821
+ return authEndpoint.linkStatus();
2822
+ },
2823
+ linkWithAuthEndpoint: async () => {
2824
+ if (!authEndpoint) throw new Error("authEndpoint not configured");
2825
+ await authEndpoint.link(
2826
+ await authorizeWithPopup({ apiKey: config3.apiKey, wsUrl: config3.wsUrl })
2827
+ );
2828
+ },
2829
+ restoreHostedLogin: async () => {
2830
+ if (!authEndpoint) return null;
2831
+ const user = await authEndpoint.me();
2832
+ if (user) {
2833
+ showHostedUser(user);
2834
+ sessionOnAuthEndpoint = true;
2835
+ sessionWatch?.start();
2836
+ } else {
2837
+ sessionWatch?.stop();
2838
+ forgetHostedUser();
2839
+ }
2840
+ return user;
2841
+ },
2591
2842
  // oauth
2592
2843
  oauth: {
2593
2844
  ...oauth_exports,
@@ -2664,13 +2915,18 @@ function createBlockAuthClient(config3) {
2664
2915
  // full deletion-state teardown after the user confirms the
2665
2916
  // restoration-expired modal.
2666
2917
  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
- }),
2918
+ logout: async () => {
2919
+ if (authEndpoint && !config3.apiUrl && sessionOnAuthEndpoint)
2920
+ await authEndpoint.logout();
2921
+ sessionWatch?.stop();
2922
+ await performLogout({
2923
+ wsc: provider.wsc,
2924
+ token: userToken(),
2925
+ apiKey: config3.apiKey,
2926
+ sessionId: browserBase.getDeviceSessionId(),
2927
+ apiUrl: config3.apiUrl
2928
+ });
2929
+ },
2674
2930
  // modals (stack — supports overlaying signin on top of signup)
2675
2931
  openModal,
2676
2932
  closeModal,
@@ -2798,7 +3054,7 @@ function getDefaultPhoneCountry(languages) {
2798
3054
  }
2799
3055
  return DEFAULT_PHONE_COUNTRY;
2800
3056
  }
2801
- function parsePhoneValue(value, fallbackCountry = getDefaultPhoneCountry()) {
3057
+ function parsePhoneValue(value, fallbackCountry = DEFAULT_PHONE_COUNTRY) {
2802
3058
  const raw = (value ?? "").trim();
2803
3059
  if (!raw) return { country: fallbackCountry, nationalNumber: "" };
2804
3060
  const legacy = raw.match(LEGACY_PHONE_PATTERN);
@@ -2862,7 +3118,7 @@ function updatePhoneDraft(country, nationalNumber) {
2862
3118
  function resolvePhoneDraft(value, draft, fallbackCountry) {
2863
3119
  const current = value ?? "";
2864
3120
  if (draft && draft.value === current) return draft;
2865
- const country = draft?.country ?? fallbackCountry ?? getDefaultPhoneCountry();
3121
+ const country = draft?.country ?? fallbackCountry ?? DEFAULT_PHONE_COUNTRY;
2866
3122
  const parsed = parsePhoneValue(current, country);
2867
3123
  const keepCountry = !!draft && getCountryCallingCode(draft.country) === getCountryCallingCode(parsed.country);
2868
3124
  return {
@@ -4241,6 +4497,6 @@ function t(key, locale = "en") {
4241
4497
  return entry?.[locale] ?? entry?.en ?? key;
4242
4498
  }
4243
4499
 
4244
- 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 };
4500
+ 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 };
4245
4501
  //# sourceMappingURL=index.js.map
4246
4502
  //# sourceMappingURL=index.js.map