@block-auth.io/core 0.9.1 → 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.js CHANGED
@@ -6,6 +6,7 @@ import { injected, walletConnect } from '@wagmi/connectors';
6
6
  import { mainnet } from 'viem/chains';
7
7
  import { PublicClientApplication } from '@azure/msal-browser';
8
8
  import bs58 from 'bs58';
9
+ import { getCountries, getCountryCallingCode, AsYouType, parsePhoneNumberFromString } from 'libphonenumber-js/min';
9
10
  import QRCode from 'qrcode';
10
11
 
11
12
  var __defProp = Object.defineProperty;
@@ -48,21 +49,26 @@ async function clearSessionCookie(apiUrl) {
48
49
  return false;
49
50
  }
50
51
  }
51
- async function fetchWsTicket(apiUrl) {
52
- if (typeof fetch === "undefined") return null;
52
+ async function requestWsTicket(apiUrl) {
53
+ if (typeof fetch === "undefined") return { ticket: null, refused: false };
53
54
  try {
54
55
  const response = await fetch(buildApiUrl("/auth/ws-ticket", apiUrl), {
55
56
  method: "GET",
56
57
  credentials: "include"
57
58
  });
58
- if (!response.ok) return null;
59
+ if (!response.ok) {
60
+ return { ticket: null, refused: response.status === 401 };
61
+ }
59
62
  const data = await response.json();
60
- return data?.ticket || null;
63
+ return { ticket: data?.ticket || null, refused: false };
61
64
  } catch (error) {
62
65
  console.warn("[block-auth] failed to fetch ws ticket", error);
63
- return null;
66
+ return { ticket: null, refused: false };
64
67
  }
65
68
  }
69
+ async function fetchWsTicket(apiUrl) {
70
+ return (await requestWsTicket(apiUrl)).ticket;
71
+ }
66
72
  var DEFAULT_WS_URL = "wss://wss.block-auth.io";
67
73
  function buildWsServerApiUrl(path, wsUrl) {
68
74
  const url = new URL(wsUrl || DEFAULT_WS_URL);
@@ -211,13 +217,17 @@ var WsClient = class {
211
217
  * requestSignin -> user:txns:create -> sign) - this avoids that.
212
218
  * No-op if there is no open connection yet (connect() will pick up a
213
219
  * ticket on its own once one exists).
214
- * @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).
215
223
  */
216
224
  async refreshAuth() {
217
- if (!this.isConnected()) return;
218
- const ticket = await fetchWsTicket(this._apiUrl);
219
- 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";
220
229
  this._ws.emit("auth:refresh", ticket);
230
+ return "renewed";
221
231
  }
222
232
  /**
223
233
  * Allow you to subscribe to an event, and
@@ -985,6 +995,7 @@ var initial2 = {
985
995
  isSigned: false,
986
996
  isSigningLoader: false,
987
997
  isAcceptingTxn: false,
998
+ acceptTxnError: null,
988
999
  waitingForSuccessLogInSince: 0,
989
1000
  isOtpRequired: false,
990
1001
  isOnDeletion: false,
@@ -1003,6 +1014,7 @@ var setIsSigning = (v) => $ui.setKey("isSigning", v);
1003
1014
  var setIsSigned = (v) => $ui.setKey("isSigned", v);
1004
1015
  var setIsSigningLoader = (v) => $ui.setKey("isSigningLoader", v);
1005
1016
  var setIsAcceptingTxn = (v) => $ui.setKey("isAcceptingTxn", v);
1017
+ var setAcceptTxnError = (v) => $ui.setKey("acceptTxnError", v);
1006
1018
  var setWaitingForSuccessLogInSince = (v) => $ui.setKey("waitingForSuccessLogInSince", v);
1007
1019
  var setIsOtpRequired = (v) => $ui.setKey("isOtpRequired", v);
1008
1020
  var setIsOnDeletion = (v) => $ui.setKey("isOnDeletion", v);
@@ -1532,6 +1544,26 @@ async function emitOauthSignup(deps) {
1532
1544
  }
1533
1545
 
1534
1546
  // src/auth/txns.ts
1547
+ var TXN_DATA_TIMEOUT_MS = 3e3;
1548
+ var TXN_DATA_ERROR_KEY = "txn_data_required";
1549
+ var TXN_DATA_MODES = ["required", "optional"];
1550
+ var TXN_DATA_STATUSES = [
1551
+ "shared",
1552
+ "granted",
1553
+ "consent",
1554
+ "missing"
1555
+ ];
1556
+ var toTxnDataParam = (raw) => {
1557
+ if (!raw || typeof raw.slug !== "string") return null;
1558
+ if (!TXN_DATA_MODES.includes(raw.mode)) return null;
1559
+ if (!TXN_DATA_STATUSES.includes(raw.status)) return null;
1560
+ return {
1561
+ slug: raw.slug,
1562
+ mode: raw.mode,
1563
+ status: raw.status,
1564
+ value: typeof raw.value === "string" ? raw.value : null
1565
+ };
1566
+ };
1535
1567
  function requestSignin(args) {
1536
1568
  const { wsc, token, url, service, apiKey, sessionId } = args;
1537
1569
  wsc.emit("user:txns:create", { token, url, service, apiKey, sessionId });
@@ -1543,16 +1575,53 @@ function rejectTxn(args) {
1543
1575
  args.wsc.emit("user:txns:update", { token: args.token, state: "cancelled" });
1544
1576
  }
1545
1577
  function acceptTxn(args) {
1546
- const { wsc, token, lifetime, providerSlug, userParams, sessionId } = args;
1578
+ const {
1579
+ wsc,
1580
+ token,
1581
+ lifetime,
1582
+ providerSlug,
1583
+ userParams,
1584
+ grantedParams,
1585
+ revokedParams,
1586
+ sessionId
1587
+ } = args;
1547
1588
  wsc.emit("provider:signin", {
1548
1589
  token,
1549
1590
  lifetime,
1550
1591
  state: "approved",
1551
1592
  providerSlug,
1552
1593
  userParams: userParams ?? {},
1594
+ grantedParams: grantedParams ?? [],
1595
+ revokedParams: revokedParams ?? [],
1553
1596
  sessionId
1554
1597
  });
1555
1598
  }
1599
+ function requestTxnData(args) {
1600
+ const { wsc, token, txnId, timeoutMs = TXN_DATA_TIMEOUT_MS } = args;
1601
+ const ws = wsc?.ws;
1602
+ if (!ws?.connected) return Promise.resolve(null);
1603
+ return new Promise((resolve) => {
1604
+ const finish = (result) => {
1605
+ clearTimeout(timer);
1606
+ ws.off("user:txns:data", onData);
1607
+ resolve(result);
1608
+ };
1609
+ const onData = (data) => {
1610
+ if (!data?.success) {
1611
+ if (data?.txnId === void 0 || String(data.txnId) === String(txnId))
1612
+ finish(null);
1613
+ return;
1614
+ }
1615
+ const item = data.message?.items?.[0];
1616
+ if (!item || String(item.txnId) !== String(txnId)) return;
1617
+ const params = (Array.isArray(item.params) ? item.params : []).map(toTxnDataParam).filter((param) => !!param);
1618
+ finish({ txnId: item.txnId, params });
1619
+ };
1620
+ const timer = setTimeout(() => finish(null), timeoutMs);
1621
+ ws.on("user:txns:data", onData);
1622
+ ws.emit("user:txns:data", { token, txnId });
1623
+ });
1624
+ }
1556
1625
  function reportTxn(args) {
1557
1626
  args.wsc.emit("ext:report", { token: args.token, report: args.report });
1558
1627
  }
@@ -2386,8 +2455,15 @@ function createBlockAuthClient(config3) {
2386
2455
  lifetime: opts.lifetime,
2387
2456
  providerSlug: $ui.get().serviceName ?? "blockauth",
2388
2457
  userParams: opts.userParams,
2458
+ grantedParams: opts.grantedParams,
2459
+ revokedParams: opts.revokedParams,
2389
2460
  sessionId: browserBase.getDeviceSessionId()
2390
2461
  }),
2462
+ dataRequest: (txnId) => requestTxnData({
2463
+ wsc: provider.wsc,
2464
+ token: userToken(),
2465
+ txnId
2466
+ }),
2391
2467
  report: (slug) => reportTxn({
2392
2468
  wsc: provider.wsc,
2393
2469
  token: userToken(),
@@ -2422,6 +2498,392 @@ function createBlockAuthClient(config3) {
2422
2498
  provider
2423
2499
  };
2424
2500
  }
2501
+ var DEFAULT_PHONE_COUNTRY = "ES";
2502
+ var LEGACY_PHONE_PATTERN = /^(\d{1,4})_(\d{4,14})_([a-z]{2})$/i;
2503
+ var NATIONAL_SEPARATORS = /[\s\-().]/g;
2504
+ var SUPPORTED_COUNTRIES = new Set(getCountries());
2505
+ var MAIN_COUNTRY_BY_CALLING_CODE = {
2506
+ "1": "US",
2507
+ "7": "RU",
2508
+ "39": "IT",
2509
+ "44": "GB",
2510
+ "47": "NO",
2511
+ "61": "AU",
2512
+ "212": "MA",
2513
+ "262": "RE",
2514
+ "290": "SH",
2515
+ "358": "FI",
2516
+ "590": "GP",
2517
+ "599": "CW"
2518
+ };
2519
+ var getCallingCodeCountry = (callingCode, fallbackCountry) => getCountryCallingCode(fallbackCountry) === callingCode ? fallbackCountry : MAIN_COUNTRY_BY_CALLING_CODE[callingCode] ?? getCountries().find(
2520
+ (country) => getCountryCallingCode(country) === callingCode
2521
+ ) ?? fallbackCountry;
2522
+ var isPhoneCountry = (value) => !!value && SUPPORTED_COUNTRIES.has(value);
2523
+ var toPhoneCountry = (value) => {
2524
+ const upper = (value ?? "").toUpperCase();
2525
+ return isPhoneCountry(upper) ? upper : null;
2526
+ };
2527
+ function getPhoneCountryFlag(iso2) {
2528
+ const code = iso2.toUpperCase();
2529
+ if (!/^[A-Z]{2}$/.test(code)) return "";
2530
+ return String.fromCodePoint(
2531
+ ...[...code].map((char) => 127462 + char.charCodeAt(0) - 65)
2532
+ );
2533
+ }
2534
+ function getPhoneDialCode(iso2) {
2535
+ return `+${getCountryCallingCode(iso2)}`;
2536
+ }
2537
+ var getRegionNames = (locale) => {
2538
+ try {
2539
+ return typeof Intl !== "undefined" && "DisplayNames" in Intl ? new Intl.DisplayNames([locale], { type: "region" }) : null;
2540
+ } catch {
2541
+ return null;
2542
+ }
2543
+ };
2544
+ function getPhoneCountries(locale = "en") {
2545
+ const names = getRegionNames(locale);
2546
+ return getCountries().map((iso2) => {
2547
+ let name = iso2;
2548
+ try {
2549
+ name = names?.of(iso2) ?? iso2;
2550
+ } catch {
2551
+ name = iso2;
2552
+ }
2553
+ return {
2554
+ iso2,
2555
+ dialCode: getPhoneDialCode(iso2),
2556
+ flag: getPhoneCountryFlag(iso2),
2557
+ name
2558
+ };
2559
+ }).sort((a, b) => a.name.localeCompare(b.name, locale));
2560
+ }
2561
+ var normalizeSearch = (value) => value.normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase().trim();
2562
+ function searchPhoneCountries(countries, query) {
2563
+ const term = normalizeSearch(query);
2564
+ if (!term) return countries;
2565
+ const digits = term.replace(/^\+/, "");
2566
+ return countries.filter(
2567
+ (country) => normalizeSearch(country.name).includes(term) || country.iso2.toLowerCase() === term || /^\d+$/.test(digits) && country.dialCode.slice(1).startsWith(digits)
2568
+ );
2569
+ }
2570
+ var fromLegacy = (raw) => {
2571
+ const legacy = raw.match(LEGACY_PHONE_PATTERN);
2572
+ return legacy ? `+${legacy[1]}${legacy[2]}` : raw;
2573
+ };
2574
+ var parsePhone = (value, country) => {
2575
+ const raw = (value ?? "").trim();
2576
+ if (!raw) return void 0;
2577
+ try {
2578
+ return parsePhoneNumberFromString(fromLegacy(raw), country);
2579
+ } catch {
2580
+ return void 0;
2581
+ }
2582
+ };
2583
+ function isValidPhoneValue(value) {
2584
+ return !!parsePhone(value)?.isValid();
2585
+ }
2586
+ function toPhoneE164(value) {
2587
+ const phone = parsePhone(value);
2588
+ return phone?.isValid() ? phone.number : null;
2589
+ }
2590
+ function formatPhoneForDisplay(value) {
2591
+ const raw = (value ?? "").trim();
2592
+ const phone = parsePhone(raw);
2593
+ return phone?.isValid() ? phone.formatInternational() : raw;
2594
+ }
2595
+ function getDefaultPhoneCountry(languages) {
2596
+ const candidates = languages ?? (typeof navigator !== "undefined" ? [...navigator.languages ?? [], navigator.language] : []);
2597
+ for (const language of candidates) {
2598
+ if (!language) continue;
2599
+ let region;
2600
+ try {
2601
+ region = new Intl.Locale(language).region;
2602
+ } catch {
2603
+ region = language.split(/[-_]/)[1];
2604
+ }
2605
+ const country = toPhoneCountry(region);
2606
+ if (country) return country;
2607
+ }
2608
+ return DEFAULT_PHONE_COUNTRY;
2609
+ }
2610
+ function parsePhoneValue(value, fallbackCountry = getDefaultPhoneCountry()) {
2611
+ const raw = (value ?? "").trim();
2612
+ if (!raw) return { country: fallbackCountry, nationalNumber: "" };
2613
+ const legacy = raw.match(LEGACY_PHONE_PATTERN);
2614
+ const legacyCountry = legacy ? toPhoneCountry(legacy[3]) : null;
2615
+ const phone = parsePhone(raw);
2616
+ if (!phone) {
2617
+ if (!legacy && /^\+\d+$/.test(raw.replace(NATIONAL_SEPARATORS, ""))) {
2618
+ const typer = new AsYouType();
2619
+ typer.input(raw);
2620
+ const callingCode = typer.getCallingCode();
2621
+ if (callingCode) {
2622
+ return {
2623
+ country: typer.getCountry() ?? getCallingCodeCountry(callingCode, fallbackCountry),
2624
+ nationalNumber: raw.replace(/\D/g, "").slice(callingCode.length)
2625
+ };
2626
+ }
2627
+ }
2628
+ return {
2629
+ country: legacyCountry ?? fallbackCountry,
2630
+ nationalNumber: raw
2631
+ };
2632
+ }
2633
+ const country = legacyCountry ?? phone.country ?? getCallingCodeCountry(String(phone.countryCallingCode), fallbackCountry);
2634
+ return {
2635
+ country,
2636
+ nationalNumber: phone.isValid() ? phone.formatNational() : String(phone.nationalNumber)
2637
+ };
2638
+ }
2639
+ function buildPhoneE164(country, nationalNumber) {
2640
+ const raw = nationalNumber.trim();
2641
+ if (!raw) return null;
2642
+ const phone = parsePhone(raw, country);
2643
+ return phone?.isValid() ? phone.number : null;
2644
+ }
2645
+ function buildPhoneValue(country, nationalNumber) {
2646
+ const raw = nationalNumber.trim();
2647
+ if (!raw) return "";
2648
+ const e164 = buildPhoneE164(country, raw);
2649
+ if (e164) return e164;
2650
+ const compact = raw.replace(NATIONAL_SEPARATORS, "");
2651
+ return compact.startsWith("+") ? compact : `${getPhoneDialCode(country)}${compact}`;
2652
+ }
2653
+ function updatePhoneDraft(country, nationalNumber) {
2654
+ const raw = nationalNumber.trim();
2655
+ if (raw.startsWith("+")) {
2656
+ const phone = parsePhone(raw);
2657
+ if (phone?.isValid() && phone.country) {
2658
+ return {
2659
+ country: phone.country,
2660
+ nationalNumber: phone.formatNational(),
2661
+ value: phone.number
2662
+ };
2663
+ }
2664
+ }
2665
+ return {
2666
+ country,
2667
+ nationalNumber,
2668
+ value: buildPhoneValue(country, nationalNumber)
2669
+ };
2670
+ }
2671
+ function resolvePhoneDraft(value, draft, fallbackCountry) {
2672
+ const current = value ?? "";
2673
+ if (draft && draft.value === current) return draft;
2674
+ const country = draft?.country ?? fallbackCountry ?? getDefaultPhoneCountry();
2675
+ const parsed = parsePhoneValue(current, country);
2676
+ const keepCountry = !!draft && getCountryCallingCode(draft.country) === getCountryCallingCode(parsed.country);
2677
+ return {
2678
+ value: current,
2679
+ country: keepCountry ? country : parsed.country,
2680
+ nationalNumber: parsed.nationalNumber
2681
+ };
2682
+ }
2683
+
2684
+ // src/auth/solicitedData.ts
2685
+ var PARAM_LABEL_KEYS = {
2686
+ "users-firstname": "firstName",
2687
+ "users-lastname": "lastName",
2688
+ "users-secondlastname": "secondLastName",
2689
+ "users-email": "email",
2690
+ "users-phone": "phone"
2691
+ };
2692
+ var PARAM_DISPLAY_ORDER = [
2693
+ "users-firstname",
2694
+ "users-lastname",
2695
+ "users-secondlastname",
2696
+ "users-email",
2697
+ "users-phone"
2698
+ ];
2699
+ var PARAM_INPUT_TYPE = {
2700
+ "users-firstname": "text",
2701
+ "users-lastname": "text",
2702
+ "users-secondlastname": "text",
2703
+ "users-email": "email",
2704
+ "users-phone": "tel"
2705
+ };
2706
+ var NAME_PATTERN = /^[A-Za-zÀ-ÖØ-öø-ÿ\s'-]{1,50}$/;
2707
+ var PARAM_VALIDATORS = {
2708
+ "users-firstname": (v) => NAME_PATTERN.test(v.trim()),
2709
+ "users-lastname": (v) => NAME_PATTERN.test(v.trim()),
2710
+ "users-secondlastname": (v) => NAME_PATTERN.test(v.trim()),
2711
+ "users-email": (v) => v.trim().length <= 100 && /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(v.trim()),
2712
+ "users-phone": (v) => isValidPhoneValue(v)
2713
+ };
2714
+ var PARAM_NORMALIZERS = {
2715
+ "users-phone": (v) => toPhoneE164(v) ?? v.trim()
2716
+ };
2717
+ var PARAM_DISPLAY_FORMATTERS = {
2718
+ "users-phone": (v) => formatPhoneForDisplay(v)
2719
+ };
2720
+ var formatParamValue = (slug, value) => {
2721
+ const format = PARAM_DISPLAY_FORMATTERS[slug];
2722
+ return !format ? value : format(value);
2723
+ };
2724
+ var normalizeParamValue = (slug, value) => {
2725
+ const trimmed = value.trim();
2726
+ const normalize = PARAM_NORMALIZERS[slug];
2727
+ return !normalize || !trimmed ? trimmed : normalize(trimmed);
2728
+ };
2729
+ var PARAM_ERROR_KEYS = {
2730
+ "users-firstname": "onlyLettersAllowed",
2731
+ "users-lastname": "onlyLettersAllowed",
2732
+ "users-secondlastname": "onlyLettersAllowed",
2733
+ "users-email": "enterValidEmail",
2734
+ "users-phone": "enterValidPhone"
2735
+ };
2736
+ var EMPTY_SOLICITED_DATA_FORM = {
2737
+ values: {},
2738
+ shared: {},
2739
+ saved: {}
2740
+ };
2741
+ var omitKey = (record, key) => Object.fromEntries(
2742
+ Object.entries(record).filter(([entryKey]) => entryKey !== key)
2743
+ );
2744
+ var isValidParamValue = (slug, value) => {
2745
+ const trimmed = value.trim();
2746
+ if (!trimmed) return false;
2747
+ const validate = PARAM_VALIDATORS[slug];
2748
+ return !validate || validate(trimmed);
2749
+ };
2750
+ function getSolicitedParams({
2751
+ params,
2752
+ requiredParams = [],
2753
+ optionalParams = []
2754
+ }) {
2755
+ const items = params ?? [
2756
+ ...requiredParams.map((slug) => ({
2757
+ slug,
2758
+ mode: "required",
2759
+ status: "missing",
2760
+ value: null
2761
+ })),
2762
+ ...optionalParams.map((slug) => ({
2763
+ slug,
2764
+ mode: "optional",
2765
+ status: "missing",
2766
+ value: null
2767
+ }))
2768
+ ];
2769
+ return PARAM_DISPLAY_ORDER.flatMap((slug) => {
2770
+ const item = items.find((param) => param.slug === slug);
2771
+ return item ? [item] : [];
2772
+ });
2773
+ }
2774
+ function getSolicitedFields(items, form = EMPTY_SOLICITED_DATA_FORM, withConsent = true) {
2775
+ return items.map((item) => {
2776
+ const profileValue = item.value ?? "";
2777
+ const inputValue = form.values[item.slug] ?? profileValue;
2778
+ const trimmed = inputValue.trim();
2779
+ const isEmpty = !trimmed;
2780
+ const isValid = isValidParamValue(item.slug, inputValue);
2781
+ if (!withConsent) {
2782
+ return {
2783
+ ...item,
2784
+ profileValue,
2785
+ inputValue,
2786
+ isEmpty,
2787
+ isShared: !!trimmed,
2788
+ isChanged: !!trimmed,
2789
+ isSaved: !!trimmed,
2790
+ isValid,
2791
+ isComplete: trimmed ? isValid : item.mode !== "required"
2792
+ };
2793
+ }
2794
+ const isChanged = normalizeParamValue(item.slug, trimmed) !== normalizeParamValue(item.slug, profileValue);
2795
+ const savedValue = form.saved[item.slug];
2796
+ const isSaved = isChanged && (isValid || isEmpty) && savedValue === trimmed;
2797
+ const isShared = !isEmpty && (form.shared[item.slug] ?? (item.status === "granted" || item.status === "shared" || isValid && (!profileValue.trim() || savedValue === "")));
2798
+ const isComplete = isShared ? isValid && (!isChanged || isSaved) : item.mode !== "required";
2799
+ return {
2800
+ ...item,
2801
+ profileValue,
2802
+ inputValue,
2803
+ isEmpty,
2804
+ isShared,
2805
+ isChanged,
2806
+ isSaved,
2807
+ isValid,
2808
+ isComplete
2809
+ };
2810
+ });
2811
+ }
2812
+ function getSolicitedHintKey(field, withConsent = true) {
2813
+ if (!withConsent || !field.isChanged) return null;
2814
+ if (!field.isSaved) return "pendingChangeHint";
2815
+ return field.isShared ? "savedToProfileHint" : "notSharedHint";
2816
+ }
2817
+ var isSolicitedHintSuccess = (field) => field.isSaved && field.isShared;
2818
+ var isSolicitedDataComplete = (fields) => fields.every((field) => field.isComplete);
2819
+ function getSolicitedAcceptParams(fields) {
2820
+ const userParams = {};
2821
+ const grantedParams = [];
2822
+ const revokedParams = [];
2823
+ fields.forEach((field) => {
2824
+ if (!field.isShared) {
2825
+ if ((field.status === "granted" || field.status === "shared") && field.mode === "optional")
2826
+ revokedParams.push(field.slug);
2827
+ return;
2828
+ }
2829
+ if (!field.isValid) return;
2830
+ if (field.isChanged) {
2831
+ if (field.isSaved)
2832
+ userParams[field.slug] = normalizeParamValue(
2833
+ field.slug,
2834
+ field.inputValue
2835
+ );
2836
+ return;
2837
+ }
2838
+ if (field.status === "consent" || field.status === "granted")
2839
+ grantedParams.push(field.slug);
2840
+ });
2841
+ return { userParams, grantedParams, revokedParams };
2842
+ }
2843
+ var setSolicitedValue = (form, item, value) => ({
2844
+ ...form,
2845
+ values: { ...form.values, [item.slug]: value }
2846
+ });
2847
+ var setSolicitedShared = (form, slug, shared) => ({
2848
+ ...form,
2849
+ shared: { ...form.shared, [slug]: shared }
2850
+ });
2851
+ var saveSolicitedValue = (form, slug) => {
2852
+ const value = (form.values[slug] ?? "").trim();
2853
+ return {
2854
+ ...form,
2855
+ saved: { ...form.saved, [slug]: value },
2856
+ shared: value ? { ...form.shared, [slug]: true } : form.shared
2857
+ };
2858
+ };
2859
+ var undoSolicitedValue = (form, item) => ({
2860
+ values: omitKey(form.values, item.slug),
2861
+ saved: omitKey(form.saved, item.slug),
2862
+ shared: (item.value ?? "").trim() ? form.shared : omitKey(form.shared, item.slug)
2863
+ });
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
+ }
2425
2887
 
2426
2888
  // src/runtime/authRuntime.ts
2427
2889
  var SIGNIN_TIMEOUT_MS = 12e4;
@@ -2593,6 +3055,45 @@ function createAuthRuntime(client, callbacks = {}) {
2593
3055
  });
2594
3056
  return logoutInFlight;
2595
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
+ };
2596
3097
  const onStorageLogout = (event) => {
2597
3098
  if (event.key !== "blockauth-logged-out" || event.newValue !== "true") {
2598
3099
  return;
@@ -2603,9 +3104,18 @@ function createAuthRuntime(client, callbacks = {}) {
2603
3104
  });
2604
3105
  };
2605
3106
  let sessionBridged = false;
2606
- const onExtensionSessionBridged = () => {
3107
+ const onExtensionSessionBridged = async () => {
2607
3108
  sessionBridged = true;
2608
- 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();
2609
3119
  };
2610
3120
  const deletion = createDeletionService({ provider });
2611
3121
  const handleUserDeleted = (forAddress = null) => {
@@ -2629,7 +3139,7 @@ function createAuthRuntime(client, callbacks = {}) {
2629
3139
  if (service === "blockauth" || prevDid && prevDid.toLowerCase() !== String(did).toLowerCase()) {
2630
3140
  browserBase.clearBrowserState({ keepExtensionInstalled: keepInstalled });
2631
3141
  }
2632
- void browserBase.setSession({
3142
+ sessionBridge = browserBase.setSession({
2633
3143
  ...result,
2634
3144
  serviceName: service,
2635
3145
  apiUrl: client.apiUrl
@@ -2735,7 +3245,12 @@ function createAuthRuntime(client, callbacks = {}) {
2735
3245
  }
2736
3246
  };
2737
3247
  const onProviderSignin = (data) => {
2738
- const { success, message } = data;
3248
+ const { success, message, translationKey } = data;
3249
+ if (!success && translationKey === TXN_DATA_ERROR_KEY) {
3250
+ setIsAcceptingTxn(false);
3251
+ setAcceptTxnError(message);
3252
+ return;
3253
+ }
2739
3254
  if (!success) {
2740
3255
  void _onError();
2741
3256
  return;
@@ -2859,6 +3374,7 @@ function createAuthRuntime(client, callbacks = {}) {
2859
3374
  setToken(_token);
2860
3375
  setIsSigned(success);
2861
3376
  hookState.isSigned = success;
3377
+ if (success) clearSessionExpiredMark();
2862
3378
  if (success && hookState.isUnsignTimeoutSet && message?.signedExpiredAt) {
2863
3379
  rearmUnsignTimeout(message.signedExpiredAt, _did);
2864
3380
  }
@@ -3017,6 +3533,7 @@ function createAuthRuntime(client, callbacks = {}) {
3017
3533
  }
3018
3534
  };
3019
3535
  const start = async () => {
3536
+ stopped = false;
3020
3537
  const s = browserBase.getSession();
3021
3538
  const externalService = browserBase.getExternalService();
3022
3539
  let _token = s.token;
@@ -3077,15 +3594,21 @@ function createAuthRuntime(client, callbacks = {}) {
3077
3594
  wsc().on("sdk:session:invalidated", onSdkSessionInvalidated);
3078
3595
  wsc().on("sdk:user:roles:changed", onSdkUserRolesChanged);
3079
3596
  wsc().on("sdk:restore", onSdkRestore);
3597
+ wsc().ws?.onAny(onAnyServerEvent);
3080
3598
  if (typeof window !== "undefined") {
3081
3599
  window.addEventListener("storage", onStorageLogout);
3082
3600
  }
3083
3601
  const { domain, signinCallbackUrl, config: config3 } = await provider.app();
3084
3602
  setUiConfig({ domain, signinCallbackUrl, config: config3 });
3085
3603
  setReady(true);
3604
+ if (externalService.service === "blockauth" && hasSessionExpiredMark()) {
3605
+ setIsSignedFirstCheck(true);
3606
+ return;
3607
+ }
3086
3608
  await isUserSignedIn();
3087
3609
  };
3088
3610
  const stop = () => {
3611
+ stopped = true;
3089
3612
  if (unsignTimeout) {
3090
3613
  clearTimeout(unsignTimeout);
3091
3614
  unsignTimeout = null;
@@ -3120,6 +3643,7 @@ function createAuthRuntime(client, callbacks = {}) {
3120
3643
  w.off("sdk:session:invalidated", onSdkSessionInvalidated);
3121
3644
  w.off("sdk:user:roles:changed", onSdkUserRolesChanged);
3122
3645
  w.off("sdk:restore", onSdkRestore);
3646
+ w.ws?.offAny(onAnyServerEvent);
3123
3647
  }
3124
3648
  if (typeof window !== "undefined") {
3125
3649
  window.removeEventListener("storage", onStorageLogout);
@@ -3228,17 +3752,46 @@ var TEXTS = {
3228
3752
  es: "Completa los campos requeridos para continuar",
3229
3753
  en: "Fill required fields to continue"
3230
3754
  },
3755
+ completeRequiredData: {
3756
+ es: "Autoriza o completa los datos obligatorios para continuar",
3757
+ en: "Authorize or fill in the required data to continue"
3758
+ },
3759
+ requiredDataError: {
3760
+ es: "No se pudo aceptar: faltan datos obligatorios o no son v\xE1lidos. Rev\xEDsalos e int\xE9ntalo de nuevo.",
3761
+ en: "Could not accept: required data is missing or invalid. Please review it and try again."
3762
+ },
3763
+ shareData: { es: "Ceder", en: "Share" },
3764
+ saveData: { es: "Guardar", en: "Save" },
3765
+ undoChange: { es: "Deshacer", en: "Undo" },
3766
+ savedToProfileHint: {
3767
+ es: "Se guardar\xE1 en tu perfil al aceptar",
3768
+ en: "It will be saved to your profile on accept"
3769
+ },
3770
+ pendingChangeHint: {
3771
+ es: "Guarda o deshaz el cambio",
3772
+ en: "Save or undo the change"
3773
+ },
3774
+ notSharedHint: {
3775
+ es: "Este dato no se ceder\xE1",
3776
+ en: "This data will not be shared"
3777
+ },
3778
+ clearField: { es: "Limpiar campo", en: "Clear field" },
3779
+ acceptData: { es: "Aceptar", en: "Accept" },
3231
3780
  noTransactionsFound: {
3232
3781
  es: "No se encontraron transacciones",
3233
3782
  en: "No transactions found"
3234
3783
  },
3784
+ otpExpiredTitle: {
3785
+ es: "Verificaci\xF3n caducada",
3786
+ en: "Verification expired"
3787
+ },
3235
3788
  otpExpiredExtension: {
3236
- es: "Tu verificaci\xF3n ha caducado. Introduce tu c\xF3digo en la extensi\xF3n de Block-Auth para aprobar este acceso.",
3237
- 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."
3238
3791
  },
3239
3792
  otpExpiredApp: {
3240
- es: "Tu verificaci\xF3n ha caducado. Introduce tu c\xF3digo en la app de Block-Auth para aprobar este acceso.",
3241
- 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."
3242
3795
  },
3243
3796
  openExtension: { es: "Abrir extensi\xF3n", en: "Open extension" },
3244
3797
  noAppKeyFound: {
@@ -3283,6 +3836,12 @@ var TEXTS = {
3283
3836
  es: "Introduce un n\xFAmero de tel\xE9fono v\xE1lido",
3284
3837
  en: "Enter a valid phone number"
3285
3838
  },
3839
+ phoneCountry: { es: "Pa\xEDs", en: "Country" },
3840
+ searchPhoneCountry: { es: "Buscar pa\xEDs o prefijo", en: "Search country or code" },
3841
+ noPhoneCountryResults: {
3842
+ es: "No hay pa\xEDses que coincidan",
3843
+ en: "No matching countries"
3844
+ },
3286
3845
  helpUsReport: {
3287
3846
  es: "Ay\xFAdanos a mejorar y reporta el error aqu\xED",
3288
3847
  en: "Help us get better and report the error here"
@@ -3303,6 +3862,6 @@ function t(key, locale = "en") {
3303
3862
  return entry?.[locale] ?? entry?.en ?? key;
3304
3863
  }
3305
3864
 
3306
- export { $extension, $locale, $openModals, $ui, $user, $wallet, $web3, $ws, BlockAuthProvider, DISCOVERY_TIMEOUT_MS, RpcClient, SDK_PAGE_MARKER, SYNC_TIMEOUT_MS, TEXTS, WsClient, appearsExtensionInstalled, clearExtensionDomMarkers, clearRemainingAuthData, clearSdkPresence, closeAllModals, closeModal, confirmExtensionPresence, createAuthRuntime, createBlockAuthClient, createDeletionService, createEvmWallet, createSolanaWallet, deepLinkFor, discoverExtensionOnce, fetchUserProfile, finalizeAfterRestorationExpired, getExtensionStoreUrl, getUserRoleNames, getUserRoleSlugs, getUserRoles, handleRestorationExpired, handleRestoreFailure, hasAnyRole, hasAnyRoleBySlug, hasRole, hasRoleBySlug, isExtensionPresent, isExtensionStateComplete, isFirefox, isModalOpen, isRestorationExpiredMessage, isSdkPage, isShowSignin, loadUserProfile, makeQrDataUrl, markSdkPresence, oauth_exports as oauth, onExtensionRemoved, onExtensionStatePublished, openExtensionOnTxn, openModal, probeExtensionPresence, reconcileExtensionState, requestExtensionRefresh, requestExtensionStateSync, requestSdkRestore, resetExtension, resetExtensionAbsentState, resetExtensionSyncModuleState, resetUi, resetUser, resetWallet, resetWeb3, resetWs, setApiKey, setBackendMessage, setDeletionAddress, setDid, setExtensionInstalled, setExtensionIsLocked, setExtensionIsUser, setExtensionIsUserActive, setIsAcceptingTxn, setIsAppActive, setIsCheckingAppActive, setIsLoadingUser, setIsOnDeletion, setIsOtpRequired, setIsSdkSignedIn, setIsServiceConnected, setIsSigned, setIsSignedFirstCheck, setIsSigning, setIsSigningLoader, setLocale, setReady, setRequests, setServiceIcon, setServiceName, setSignature, setSignedBy, setToken, setUiConfig, setUser, setWaitingForSuccessLogInSince, startExtensionSync, syncExtensionStateFromStorage, t, utils_exports as utils };
3865
+ 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, 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, isSolicitedHintSuccess, isValidParamValue, isValidPhoneValue, loadUserProfile, makeQrDataUrl, markSdkPresence, normalizeParamValue, oauth_exports as oauth, onExtensionRemoved, onExtensionStatePublished, openExtensionOnTxn, 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, setIsSdkSignedIn, setIsServiceConnected, setIsSigned, setIsSignedFirstCheck, setIsSigning, setIsSigningLoader, setLocale, setReady, setRequests, setServiceIcon, setServiceName, setSignature, setSignedBy, setSolicitedShared, setSolicitedValue, setToken, setUiConfig, setUser, setWaitingForSuccessLogInSince, startExtensionSync, syncExtensionStateFromStorage, t, toPhoneE164, undoSolicitedValue, updatePhoneDraft, utils_exports as utils };
3307
3866
  //# sourceMappingURL=index.js.map
3308
3867
  //# sourceMappingURL=index.js.map