@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.cjs CHANGED
@@ -8,6 +8,7 @@ var connectors = require('@wagmi/connectors');
8
8
  var chains = require('viem/chains');
9
9
  var msalBrowser = require('@azure/msal-browser');
10
10
  var bs58 = require('bs58');
11
+ var min = require('libphonenumber-js/min');
11
12
  var QRCode = require('qrcode');
12
13
 
13
14
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
@@ -56,21 +57,26 @@ async function clearSessionCookie(apiUrl) {
56
57
  return false;
57
58
  }
58
59
  }
59
- async function fetchWsTicket(apiUrl) {
60
- if (typeof fetch === "undefined") return null;
60
+ async function requestWsTicket(apiUrl) {
61
+ if (typeof fetch === "undefined") return { ticket: null, refused: false };
61
62
  try {
62
63
  const response = await fetch(buildApiUrl("/auth/ws-ticket", apiUrl), {
63
64
  method: "GET",
64
65
  credentials: "include"
65
66
  });
66
- if (!response.ok) return null;
67
+ if (!response.ok) {
68
+ return { ticket: null, refused: response.status === 401 };
69
+ }
67
70
  const data = await response.json();
68
- return data?.ticket || null;
71
+ return { ticket: data?.ticket || null, refused: false };
69
72
  } catch (error) {
70
73
  console.warn("[block-auth] failed to fetch ws ticket", error);
71
- return null;
74
+ return { ticket: null, refused: false };
72
75
  }
73
76
  }
77
+ async function fetchWsTicket(apiUrl) {
78
+ return (await requestWsTicket(apiUrl)).ticket;
79
+ }
74
80
  var DEFAULT_WS_URL = "wss://wss.block-auth.io";
75
81
  function buildWsServerApiUrl(path, wsUrl) {
76
82
  const url = new URL(wsUrl || DEFAULT_WS_URL);
@@ -219,13 +225,17 @@ var WsClient = class {
219
225
  * requestSignin -> user:txns:create -> sign) - this avoids that.
220
226
  * No-op if there is no open connection yet (connect() will pick up a
221
227
  * ticket on its own once one exists).
222
- * @returns Promise<void>
228
+ * @returns 'renewed' when a ticket was sent, 'refused' when the API answered
229
+ * 401 (no session behind the cookie), 'unavailable' otherwise (not
230
+ * connected yet, or a transient failure).
223
231
  */
224
232
  async refreshAuth() {
225
- if (!this.isConnected()) return;
226
- const ticket = await fetchWsTicket(this._apiUrl);
227
- if (!ticket) return;
233
+ if (!this.isConnected()) return "unavailable";
234
+ const { ticket, refused } = await requestWsTicket(this._apiUrl);
235
+ if (refused) return "refused";
236
+ if (!ticket) return "unavailable";
228
237
  this._ws.emit("auth:refresh", ticket);
238
+ return "renewed";
229
239
  }
230
240
  /**
231
241
  * Allow you to subscribe to an event, and
@@ -993,6 +1003,7 @@ var initial2 = {
993
1003
  isSigned: false,
994
1004
  isSigningLoader: false,
995
1005
  isAcceptingTxn: false,
1006
+ acceptTxnError: null,
996
1007
  waitingForSuccessLogInSince: 0,
997
1008
  isOtpRequired: false,
998
1009
  isOnDeletion: false,
@@ -1011,6 +1022,7 @@ var setIsSigning = (v) => $ui.setKey("isSigning", v);
1011
1022
  var setIsSigned = (v) => $ui.setKey("isSigned", v);
1012
1023
  var setIsSigningLoader = (v) => $ui.setKey("isSigningLoader", v);
1013
1024
  var setIsAcceptingTxn = (v) => $ui.setKey("isAcceptingTxn", v);
1025
+ var setAcceptTxnError = (v) => $ui.setKey("acceptTxnError", v);
1014
1026
  var setWaitingForSuccessLogInSince = (v) => $ui.setKey("waitingForSuccessLogInSince", v);
1015
1027
  var setIsOtpRequired = (v) => $ui.setKey("isOtpRequired", v);
1016
1028
  var setIsOnDeletion = (v) => $ui.setKey("isOnDeletion", v);
@@ -1540,6 +1552,26 @@ async function emitOauthSignup(deps) {
1540
1552
  }
1541
1553
 
1542
1554
  // src/auth/txns.ts
1555
+ var TXN_DATA_TIMEOUT_MS = 3e3;
1556
+ var TXN_DATA_ERROR_KEY = "txn_data_required";
1557
+ var TXN_DATA_MODES = ["required", "optional"];
1558
+ var TXN_DATA_STATUSES = [
1559
+ "shared",
1560
+ "granted",
1561
+ "consent",
1562
+ "missing"
1563
+ ];
1564
+ var toTxnDataParam = (raw) => {
1565
+ if (!raw || typeof raw.slug !== "string") return null;
1566
+ if (!TXN_DATA_MODES.includes(raw.mode)) return null;
1567
+ if (!TXN_DATA_STATUSES.includes(raw.status)) return null;
1568
+ return {
1569
+ slug: raw.slug,
1570
+ mode: raw.mode,
1571
+ status: raw.status,
1572
+ value: typeof raw.value === "string" ? raw.value : null
1573
+ };
1574
+ };
1543
1575
  function requestSignin(args) {
1544
1576
  const { wsc, token, url, service, apiKey, sessionId } = args;
1545
1577
  wsc.emit("user:txns:create", { token, url, service, apiKey, sessionId });
@@ -1551,16 +1583,53 @@ function rejectTxn(args) {
1551
1583
  args.wsc.emit("user:txns:update", { token: args.token, state: "cancelled" });
1552
1584
  }
1553
1585
  function acceptTxn(args) {
1554
- const { wsc, token, lifetime, providerSlug, userParams, sessionId } = args;
1586
+ const {
1587
+ wsc,
1588
+ token,
1589
+ lifetime,
1590
+ providerSlug,
1591
+ userParams,
1592
+ grantedParams,
1593
+ revokedParams,
1594
+ sessionId
1595
+ } = args;
1555
1596
  wsc.emit("provider:signin", {
1556
1597
  token,
1557
1598
  lifetime,
1558
1599
  state: "approved",
1559
1600
  providerSlug,
1560
1601
  userParams: userParams ?? {},
1602
+ grantedParams: grantedParams ?? [],
1603
+ revokedParams: revokedParams ?? [],
1561
1604
  sessionId
1562
1605
  });
1563
1606
  }
1607
+ function requestTxnData(args) {
1608
+ const { wsc, token, txnId, timeoutMs = TXN_DATA_TIMEOUT_MS } = args;
1609
+ const ws = wsc?.ws;
1610
+ if (!ws?.connected) return Promise.resolve(null);
1611
+ return new Promise((resolve) => {
1612
+ const finish = (result) => {
1613
+ clearTimeout(timer);
1614
+ ws.off("user:txns:data", onData);
1615
+ resolve(result);
1616
+ };
1617
+ const onData = (data) => {
1618
+ if (!data?.success) {
1619
+ if (data?.txnId === void 0 || String(data.txnId) === String(txnId))
1620
+ finish(null);
1621
+ return;
1622
+ }
1623
+ const item = data.message?.items?.[0];
1624
+ if (!item || String(item.txnId) !== String(txnId)) return;
1625
+ const params = (Array.isArray(item.params) ? item.params : []).map(toTxnDataParam).filter((param) => !!param);
1626
+ finish({ txnId: item.txnId, params });
1627
+ };
1628
+ const timer = setTimeout(() => finish(null), timeoutMs);
1629
+ ws.on("user:txns:data", onData);
1630
+ ws.emit("user:txns:data", { token, txnId });
1631
+ });
1632
+ }
1564
1633
  function reportTxn(args) {
1565
1634
  args.wsc.emit("ext:report", { token: args.token, report: args.report });
1566
1635
  }
@@ -2394,8 +2463,15 @@ function createBlockAuthClient(config3) {
2394
2463
  lifetime: opts.lifetime,
2395
2464
  providerSlug: $ui.get().serviceName ?? "blockauth",
2396
2465
  userParams: opts.userParams,
2466
+ grantedParams: opts.grantedParams,
2467
+ revokedParams: opts.revokedParams,
2397
2468
  sessionId: browserBase.getDeviceSessionId()
2398
2469
  }),
2470
+ dataRequest: (txnId) => requestTxnData({
2471
+ wsc: provider.wsc,
2472
+ token: userToken(),
2473
+ txnId
2474
+ }),
2399
2475
  report: (slug) => reportTxn({
2400
2476
  wsc: provider.wsc,
2401
2477
  token: userToken(),
@@ -2430,6 +2506,392 @@ function createBlockAuthClient(config3) {
2430
2506
  provider
2431
2507
  };
2432
2508
  }
2509
+ var DEFAULT_PHONE_COUNTRY = "ES";
2510
+ var LEGACY_PHONE_PATTERN = /^(\d{1,4})_(\d{4,14})_([a-z]{2})$/i;
2511
+ var NATIONAL_SEPARATORS = /[\s\-().]/g;
2512
+ var SUPPORTED_COUNTRIES = new Set(min.getCountries());
2513
+ var MAIN_COUNTRY_BY_CALLING_CODE = {
2514
+ "1": "US",
2515
+ "7": "RU",
2516
+ "39": "IT",
2517
+ "44": "GB",
2518
+ "47": "NO",
2519
+ "61": "AU",
2520
+ "212": "MA",
2521
+ "262": "RE",
2522
+ "290": "SH",
2523
+ "358": "FI",
2524
+ "590": "GP",
2525
+ "599": "CW"
2526
+ };
2527
+ var getCallingCodeCountry = (callingCode, fallbackCountry) => min.getCountryCallingCode(fallbackCountry) === callingCode ? fallbackCountry : MAIN_COUNTRY_BY_CALLING_CODE[callingCode] ?? min.getCountries().find(
2528
+ (country) => min.getCountryCallingCode(country) === callingCode
2529
+ ) ?? fallbackCountry;
2530
+ var isPhoneCountry = (value) => !!value && SUPPORTED_COUNTRIES.has(value);
2531
+ var toPhoneCountry = (value) => {
2532
+ const upper = (value ?? "").toUpperCase();
2533
+ return isPhoneCountry(upper) ? upper : null;
2534
+ };
2535
+ function getPhoneCountryFlag(iso2) {
2536
+ const code = iso2.toUpperCase();
2537
+ if (!/^[A-Z]{2}$/.test(code)) return "";
2538
+ return String.fromCodePoint(
2539
+ ...[...code].map((char) => 127462 + char.charCodeAt(0) - 65)
2540
+ );
2541
+ }
2542
+ function getPhoneDialCode(iso2) {
2543
+ return `+${min.getCountryCallingCode(iso2)}`;
2544
+ }
2545
+ var getRegionNames = (locale) => {
2546
+ try {
2547
+ return typeof Intl !== "undefined" && "DisplayNames" in Intl ? new Intl.DisplayNames([locale], { type: "region" }) : null;
2548
+ } catch {
2549
+ return null;
2550
+ }
2551
+ };
2552
+ function getPhoneCountries(locale = "en") {
2553
+ const names = getRegionNames(locale);
2554
+ return min.getCountries().map((iso2) => {
2555
+ let name = iso2;
2556
+ try {
2557
+ name = names?.of(iso2) ?? iso2;
2558
+ } catch {
2559
+ name = iso2;
2560
+ }
2561
+ return {
2562
+ iso2,
2563
+ dialCode: getPhoneDialCode(iso2),
2564
+ flag: getPhoneCountryFlag(iso2),
2565
+ name
2566
+ };
2567
+ }).sort((a, b) => a.name.localeCompare(b.name, locale));
2568
+ }
2569
+ var normalizeSearch = (value) => value.normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase().trim();
2570
+ function searchPhoneCountries(countries, query) {
2571
+ const term = normalizeSearch(query);
2572
+ if (!term) return countries;
2573
+ const digits = term.replace(/^\+/, "");
2574
+ return countries.filter(
2575
+ (country) => normalizeSearch(country.name).includes(term) || country.iso2.toLowerCase() === term || /^\d+$/.test(digits) && country.dialCode.slice(1).startsWith(digits)
2576
+ );
2577
+ }
2578
+ var fromLegacy = (raw) => {
2579
+ const legacy = raw.match(LEGACY_PHONE_PATTERN);
2580
+ return legacy ? `+${legacy[1]}${legacy[2]}` : raw;
2581
+ };
2582
+ var parsePhone = (value, country) => {
2583
+ const raw = (value ?? "").trim();
2584
+ if (!raw) return void 0;
2585
+ try {
2586
+ return min.parsePhoneNumberFromString(fromLegacy(raw), country);
2587
+ } catch {
2588
+ return void 0;
2589
+ }
2590
+ };
2591
+ function isValidPhoneValue(value) {
2592
+ return !!parsePhone(value)?.isValid();
2593
+ }
2594
+ function toPhoneE164(value) {
2595
+ const phone = parsePhone(value);
2596
+ return phone?.isValid() ? phone.number : null;
2597
+ }
2598
+ function formatPhoneForDisplay(value) {
2599
+ const raw = (value ?? "").trim();
2600
+ const phone = parsePhone(raw);
2601
+ return phone?.isValid() ? phone.formatInternational() : raw;
2602
+ }
2603
+ function getDefaultPhoneCountry(languages) {
2604
+ const candidates = languages ?? (typeof navigator !== "undefined" ? [...navigator.languages ?? [], navigator.language] : []);
2605
+ for (const language of candidates) {
2606
+ if (!language) continue;
2607
+ let region;
2608
+ try {
2609
+ region = new Intl.Locale(language).region;
2610
+ } catch {
2611
+ region = language.split(/[-_]/)[1];
2612
+ }
2613
+ const country = toPhoneCountry(region);
2614
+ if (country) return country;
2615
+ }
2616
+ return DEFAULT_PHONE_COUNTRY;
2617
+ }
2618
+ function parsePhoneValue(value, fallbackCountry = getDefaultPhoneCountry()) {
2619
+ const raw = (value ?? "").trim();
2620
+ if (!raw) return { country: fallbackCountry, nationalNumber: "" };
2621
+ const legacy = raw.match(LEGACY_PHONE_PATTERN);
2622
+ const legacyCountry = legacy ? toPhoneCountry(legacy[3]) : null;
2623
+ const phone = parsePhone(raw);
2624
+ if (!phone) {
2625
+ if (!legacy && /^\+\d+$/.test(raw.replace(NATIONAL_SEPARATORS, ""))) {
2626
+ const typer = new min.AsYouType();
2627
+ typer.input(raw);
2628
+ const callingCode = typer.getCallingCode();
2629
+ if (callingCode) {
2630
+ return {
2631
+ country: typer.getCountry() ?? getCallingCodeCountry(callingCode, fallbackCountry),
2632
+ nationalNumber: raw.replace(/\D/g, "").slice(callingCode.length)
2633
+ };
2634
+ }
2635
+ }
2636
+ return {
2637
+ country: legacyCountry ?? fallbackCountry,
2638
+ nationalNumber: raw
2639
+ };
2640
+ }
2641
+ const country = legacyCountry ?? phone.country ?? getCallingCodeCountry(String(phone.countryCallingCode), fallbackCountry);
2642
+ return {
2643
+ country,
2644
+ nationalNumber: phone.isValid() ? phone.formatNational() : String(phone.nationalNumber)
2645
+ };
2646
+ }
2647
+ function buildPhoneE164(country, nationalNumber) {
2648
+ const raw = nationalNumber.trim();
2649
+ if (!raw) return null;
2650
+ const phone = parsePhone(raw, country);
2651
+ return phone?.isValid() ? phone.number : null;
2652
+ }
2653
+ function buildPhoneValue(country, nationalNumber) {
2654
+ const raw = nationalNumber.trim();
2655
+ if (!raw) return "";
2656
+ const e164 = buildPhoneE164(country, raw);
2657
+ if (e164) return e164;
2658
+ const compact = raw.replace(NATIONAL_SEPARATORS, "");
2659
+ return compact.startsWith("+") ? compact : `${getPhoneDialCode(country)}${compact}`;
2660
+ }
2661
+ function updatePhoneDraft(country, nationalNumber) {
2662
+ const raw = nationalNumber.trim();
2663
+ if (raw.startsWith("+")) {
2664
+ const phone = parsePhone(raw);
2665
+ if (phone?.isValid() && phone.country) {
2666
+ return {
2667
+ country: phone.country,
2668
+ nationalNumber: phone.formatNational(),
2669
+ value: phone.number
2670
+ };
2671
+ }
2672
+ }
2673
+ return {
2674
+ country,
2675
+ nationalNumber,
2676
+ value: buildPhoneValue(country, nationalNumber)
2677
+ };
2678
+ }
2679
+ function resolvePhoneDraft(value, draft, fallbackCountry) {
2680
+ const current = value ?? "";
2681
+ if (draft && draft.value === current) return draft;
2682
+ const country = draft?.country ?? fallbackCountry ?? getDefaultPhoneCountry();
2683
+ const parsed = parsePhoneValue(current, country);
2684
+ const keepCountry = !!draft && min.getCountryCallingCode(draft.country) === min.getCountryCallingCode(parsed.country);
2685
+ return {
2686
+ value: current,
2687
+ country: keepCountry ? country : parsed.country,
2688
+ nationalNumber: parsed.nationalNumber
2689
+ };
2690
+ }
2691
+
2692
+ // src/auth/solicitedData.ts
2693
+ var PARAM_LABEL_KEYS = {
2694
+ "users-firstname": "firstName",
2695
+ "users-lastname": "lastName",
2696
+ "users-secondlastname": "secondLastName",
2697
+ "users-email": "email",
2698
+ "users-phone": "phone"
2699
+ };
2700
+ var PARAM_DISPLAY_ORDER = [
2701
+ "users-firstname",
2702
+ "users-lastname",
2703
+ "users-secondlastname",
2704
+ "users-email",
2705
+ "users-phone"
2706
+ ];
2707
+ var PARAM_INPUT_TYPE = {
2708
+ "users-firstname": "text",
2709
+ "users-lastname": "text",
2710
+ "users-secondlastname": "text",
2711
+ "users-email": "email",
2712
+ "users-phone": "tel"
2713
+ };
2714
+ var NAME_PATTERN = /^[A-Za-zÀ-ÖØ-öø-ÿ\s'-]{1,50}$/;
2715
+ var PARAM_VALIDATORS = {
2716
+ "users-firstname": (v) => NAME_PATTERN.test(v.trim()),
2717
+ "users-lastname": (v) => NAME_PATTERN.test(v.trim()),
2718
+ "users-secondlastname": (v) => NAME_PATTERN.test(v.trim()),
2719
+ "users-email": (v) => v.trim().length <= 100 && /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(v.trim()),
2720
+ "users-phone": (v) => isValidPhoneValue(v)
2721
+ };
2722
+ var PARAM_NORMALIZERS = {
2723
+ "users-phone": (v) => toPhoneE164(v) ?? v.trim()
2724
+ };
2725
+ var PARAM_DISPLAY_FORMATTERS = {
2726
+ "users-phone": (v) => formatPhoneForDisplay(v)
2727
+ };
2728
+ var formatParamValue = (slug, value) => {
2729
+ const format = PARAM_DISPLAY_FORMATTERS[slug];
2730
+ return !format ? value : format(value);
2731
+ };
2732
+ var normalizeParamValue = (slug, value) => {
2733
+ const trimmed = value.trim();
2734
+ const normalize = PARAM_NORMALIZERS[slug];
2735
+ return !normalize || !trimmed ? trimmed : normalize(trimmed);
2736
+ };
2737
+ var PARAM_ERROR_KEYS = {
2738
+ "users-firstname": "onlyLettersAllowed",
2739
+ "users-lastname": "onlyLettersAllowed",
2740
+ "users-secondlastname": "onlyLettersAllowed",
2741
+ "users-email": "enterValidEmail",
2742
+ "users-phone": "enterValidPhone"
2743
+ };
2744
+ var EMPTY_SOLICITED_DATA_FORM = {
2745
+ values: {},
2746
+ shared: {},
2747
+ saved: {}
2748
+ };
2749
+ var omitKey = (record, key) => Object.fromEntries(
2750
+ Object.entries(record).filter(([entryKey]) => entryKey !== key)
2751
+ );
2752
+ var isValidParamValue = (slug, value) => {
2753
+ const trimmed = value.trim();
2754
+ if (!trimmed) return false;
2755
+ const validate = PARAM_VALIDATORS[slug];
2756
+ return !validate || validate(trimmed);
2757
+ };
2758
+ function getSolicitedParams({
2759
+ params,
2760
+ requiredParams = [],
2761
+ optionalParams = []
2762
+ }) {
2763
+ const items = params ?? [
2764
+ ...requiredParams.map((slug) => ({
2765
+ slug,
2766
+ mode: "required",
2767
+ status: "missing",
2768
+ value: null
2769
+ })),
2770
+ ...optionalParams.map((slug) => ({
2771
+ slug,
2772
+ mode: "optional",
2773
+ status: "missing",
2774
+ value: null
2775
+ }))
2776
+ ];
2777
+ return PARAM_DISPLAY_ORDER.flatMap((slug) => {
2778
+ const item = items.find((param) => param.slug === slug);
2779
+ return item ? [item] : [];
2780
+ });
2781
+ }
2782
+ function getSolicitedFields(items, form = EMPTY_SOLICITED_DATA_FORM, withConsent = true) {
2783
+ return items.map((item) => {
2784
+ const profileValue = item.value ?? "";
2785
+ const inputValue = form.values[item.slug] ?? profileValue;
2786
+ const trimmed = inputValue.trim();
2787
+ const isEmpty = !trimmed;
2788
+ const isValid = isValidParamValue(item.slug, inputValue);
2789
+ if (!withConsent) {
2790
+ return {
2791
+ ...item,
2792
+ profileValue,
2793
+ inputValue,
2794
+ isEmpty,
2795
+ isShared: !!trimmed,
2796
+ isChanged: !!trimmed,
2797
+ isSaved: !!trimmed,
2798
+ isValid,
2799
+ isComplete: trimmed ? isValid : item.mode !== "required"
2800
+ };
2801
+ }
2802
+ const isChanged = normalizeParamValue(item.slug, trimmed) !== normalizeParamValue(item.slug, profileValue);
2803
+ const savedValue = form.saved[item.slug];
2804
+ const isSaved = isChanged && (isValid || isEmpty) && savedValue === trimmed;
2805
+ const isShared = !isEmpty && (form.shared[item.slug] ?? (item.status === "granted" || item.status === "shared" || isValid && (!profileValue.trim() || savedValue === "")));
2806
+ const isComplete = isShared ? isValid && (!isChanged || isSaved) : item.mode !== "required";
2807
+ return {
2808
+ ...item,
2809
+ profileValue,
2810
+ inputValue,
2811
+ isEmpty,
2812
+ isShared,
2813
+ isChanged,
2814
+ isSaved,
2815
+ isValid,
2816
+ isComplete
2817
+ };
2818
+ });
2819
+ }
2820
+ function getSolicitedHintKey(field, withConsent = true) {
2821
+ if (!withConsent || !field.isChanged) return null;
2822
+ if (!field.isSaved) return "pendingChangeHint";
2823
+ return field.isShared ? "savedToProfileHint" : "notSharedHint";
2824
+ }
2825
+ var isSolicitedHintSuccess = (field) => field.isSaved && field.isShared;
2826
+ var isSolicitedDataComplete = (fields) => fields.every((field) => field.isComplete);
2827
+ function getSolicitedAcceptParams(fields) {
2828
+ const userParams = {};
2829
+ const grantedParams = [];
2830
+ const revokedParams = [];
2831
+ fields.forEach((field) => {
2832
+ if (!field.isShared) {
2833
+ if ((field.status === "granted" || field.status === "shared") && field.mode === "optional")
2834
+ revokedParams.push(field.slug);
2835
+ return;
2836
+ }
2837
+ if (!field.isValid) return;
2838
+ if (field.isChanged) {
2839
+ if (field.isSaved)
2840
+ userParams[field.slug] = normalizeParamValue(
2841
+ field.slug,
2842
+ field.inputValue
2843
+ );
2844
+ return;
2845
+ }
2846
+ if (field.status === "consent" || field.status === "granted")
2847
+ grantedParams.push(field.slug);
2848
+ });
2849
+ return { userParams, grantedParams, revokedParams };
2850
+ }
2851
+ var setSolicitedValue = (form, item, value) => ({
2852
+ ...form,
2853
+ values: { ...form.values, [item.slug]: value }
2854
+ });
2855
+ var setSolicitedShared = (form, slug, shared) => ({
2856
+ ...form,
2857
+ shared: { ...form.shared, [slug]: shared }
2858
+ });
2859
+ var saveSolicitedValue = (form, slug) => {
2860
+ const value = (form.values[slug] ?? "").trim();
2861
+ return {
2862
+ ...form,
2863
+ saved: { ...form.saved, [slug]: value },
2864
+ shared: value ? { ...form.shared, [slug]: true } : form.shared
2865
+ };
2866
+ };
2867
+ var undoSolicitedValue = (form, item) => ({
2868
+ values: omitKey(form.values, item.slug),
2869
+ saved: omitKey(form.saved, item.slug),
2870
+ shared: (item.value ?? "").trim() ? form.shared : omitKey(form.shared, item.slug)
2871
+ });
2872
+
2873
+ // src/session/sessionExpired.ts
2874
+ var USER_SESSION_REQUIRED = "USER_SESSION_REQUIRED";
2875
+ var SESSION_EXPIRED_MARK = "blockauth-session-expired";
2876
+ function markSessionExpired() {
2877
+ try {
2878
+ sessionStorage.setItem(SESSION_EXPIRED_MARK, "1");
2879
+ } catch {
2880
+ }
2881
+ }
2882
+ function hasSessionExpiredMark() {
2883
+ try {
2884
+ return sessionStorage.getItem(SESSION_EXPIRED_MARK) === "1";
2885
+ } catch {
2886
+ return false;
2887
+ }
2888
+ }
2889
+ function clearSessionExpiredMark() {
2890
+ try {
2891
+ sessionStorage.removeItem(SESSION_EXPIRED_MARK);
2892
+ } catch {
2893
+ }
2894
+ }
2433
2895
 
2434
2896
  // src/runtime/authRuntime.ts
2435
2897
  var SIGNIN_TIMEOUT_MS = 12e4;
@@ -2601,6 +3063,45 @@ function createAuthRuntime(client, callbacks = {}) {
2601
3063
  });
2602
3064
  return logoutInFlight;
2603
3065
  };
3066
+ const reactToLostSession = (isLoggingIn) => {
3067
+ if (browserBase.getExternalService().service === "blockauth") {
3068
+ if (isLoggingIn) {
3069
+ markSessionExpired();
3070
+ setIsSigningLoader(false);
3071
+ awaitOtpInExtension();
3072
+ } else if (!hasSessionExpiredMark()) {
3073
+ markSessionExpired();
3074
+ void _onError();
3075
+ }
3076
+ return;
3077
+ }
3078
+ void applyLocalLogout().then(() => {
3079
+ if (!isLoggingIn) return;
3080
+ closeModal("signin");
3081
+ openModal("signup");
3082
+ }).catch((err) => {
3083
+ console.error("[sdk] applyLocalLogout failed (session required):", err);
3084
+ });
3085
+ };
3086
+ let stopped = false;
3087
+ let sessionBridge = Promise.resolve();
3088
+ let sessionCheck = null;
3089
+ const canLoseSession = () => !hookState.isLoggingOut && !$ui.get().isOtpRequired && ($ui.get().isServiceConnected || hookState.isSigned);
3090
+ const onAnyServerEvent = (_event, data) => {
3091
+ if (data?.code !== USER_SESSION_REQUIRED || !canLoseSession()) return;
3092
+ if (sessionCheck) return;
3093
+ sessionCheck = (async () => {
3094
+ await sessionBridge.catch(() => {
3095
+ });
3096
+ const result = await wsc().refreshAuth();
3097
+ if (result !== "refused" || stopped || !canLoseSession()) return;
3098
+ reactToLostSession($openModals.get().includes("signin"));
3099
+ })().catch((err) => {
3100
+ console.error("[sdk] session check failed:", err);
3101
+ }).finally(() => {
3102
+ sessionCheck = null;
3103
+ });
3104
+ };
2604
3105
  const onStorageLogout = (event) => {
2605
3106
  if (event.key !== "blockauth-logged-out" || event.newValue !== "true") {
2606
3107
  return;
@@ -2611,9 +3112,18 @@ function createAuthRuntime(client, callbacks = {}) {
2611
3112
  });
2612
3113
  };
2613
3114
  let sessionBridged = false;
2614
- const onExtensionSessionBridged = () => {
3115
+ const onExtensionSessionBridged = async () => {
2615
3116
  sessionBridged = true;
2616
- void wsc().refreshAuth();
3117
+ const result = await wsc().refreshAuth();
3118
+ if (result === "refused" || !hasSessionExpiredMark()) return;
3119
+ clearSessionExpiredMark();
3120
+ const awaitedSession = $ui.get().isOtpRequired && !hookState.isSigning;
3121
+ if (awaitedSession) setIsOtpRequired(false);
3122
+ if (awaitedSession && $openModals.get().includes("signin")) {
3123
+ client.requestSignin();
3124
+ return;
3125
+ }
3126
+ if ($ws.get().ready) void isUserSignedIn();
2617
3127
  };
2618
3128
  const deletion = createDeletionService({ provider });
2619
3129
  const handleUserDeleted = (forAddress = null) => {
@@ -2637,7 +3147,7 @@ function createAuthRuntime(client, callbacks = {}) {
2637
3147
  if (service === "blockauth" || prevDid && prevDid.toLowerCase() !== String(did).toLowerCase()) {
2638
3148
  browserBase.clearBrowserState({ keepExtensionInstalled: keepInstalled });
2639
3149
  }
2640
- void browserBase.setSession({
3150
+ sessionBridge = browserBase.setSession({
2641
3151
  ...result,
2642
3152
  serviceName: service,
2643
3153
  apiUrl: client.apiUrl
@@ -2743,7 +3253,12 @@ function createAuthRuntime(client, callbacks = {}) {
2743
3253
  }
2744
3254
  };
2745
3255
  const onProviderSignin = (data) => {
2746
- const { success, message } = data;
3256
+ const { success, message, translationKey } = data;
3257
+ if (!success && translationKey === TXN_DATA_ERROR_KEY) {
3258
+ setIsAcceptingTxn(false);
3259
+ setAcceptTxnError(message);
3260
+ return;
3261
+ }
2747
3262
  if (!success) {
2748
3263
  void _onError();
2749
3264
  return;
@@ -2867,6 +3382,7 @@ function createAuthRuntime(client, callbacks = {}) {
2867
3382
  setToken(_token);
2868
3383
  setIsSigned(success);
2869
3384
  hookState.isSigned = success;
3385
+ if (success) clearSessionExpiredMark();
2870
3386
  if (success && hookState.isUnsignTimeoutSet && message?.signedExpiredAt) {
2871
3387
  rearmUnsignTimeout(message.signedExpiredAt, _did);
2872
3388
  }
@@ -3025,6 +3541,7 @@ function createAuthRuntime(client, callbacks = {}) {
3025
3541
  }
3026
3542
  };
3027
3543
  const start = async () => {
3544
+ stopped = false;
3028
3545
  const s = browserBase.getSession();
3029
3546
  const externalService = browserBase.getExternalService();
3030
3547
  let _token = s.token;
@@ -3085,15 +3602,21 @@ function createAuthRuntime(client, callbacks = {}) {
3085
3602
  wsc().on("sdk:session:invalidated", onSdkSessionInvalidated);
3086
3603
  wsc().on("sdk:user:roles:changed", onSdkUserRolesChanged);
3087
3604
  wsc().on("sdk:restore", onSdkRestore);
3605
+ wsc().ws?.onAny(onAnyServerEvent);
3088
3606
  if (typeof window !== "undefined") {
3089
3607
  window.addEventListener("storage", onStorageLogout);
3090
3608
  }
3091
3609
  const { domain, signinCallbackUrl, config: config3 } = await provider.app();
3092
3610
  setUiConfig({ domain, signinCallbackUrl, config: config3 });
3093
3611
  setReady(true);
3612
+ if (externalService.service === "blockauth" && hasSessionExpiredMark()) {
3613
+ setIsSignedFirstCheck(true);
3614
+ return;
3615
+ }
3094
3616
  await isUserSignedIn();
3095
3617
  };
3096
3618
  const stop = () => {
3619
+ stopped = true;
3097
3620
  if (unsignTimeout) {
3098
3621
  clearTimeout(unsignTimeout);
3099
3622
  unsignTimeout = null;
@@ -3128,6 +3651,7 @@ function createAuthRuntime(client, callbacks = {}) {
3128
3651
  w.off("sdk:session:invalidated", onSdkSessionInvalidated);
3129
3652
  w.off("sdk:user:roles:changed", onSdkUserRolesChanged);
3130
3653
  w.off("sdk:restore", onSdkRestore);
3654
+ w.ws?.offAny(onAnyServerEvent);
3131
3655
  }
3132
3656
  if (typeof window !== "undefined") {
3133
3657
  window.removeEventListener("storage", onStorageLogout);
@@ -3236,17 +3760,46 @@ var TEXTS = {
3236
3760
  es: "Completa los campos requeridos para continuar",
3237
3761
  en: "Fill required fields to continue"
3238
3762
  },
3763
+ completeRequiredData: {
3764
+ es: "Autoriza o completa los datos obligatorios para continuar",
3765
+ en: "Authorize or fill in the required data to continue"
3766
+ },
3767
+ requiredDataError: {
3768
+ es: "No se pudo aceptar: faltan datos obligatorios o no son v\xE1lidos. Rev\xEDsalos e int\xE9ntalo de nuevo.",
3769
+ en: "Could not accept: required data is missing or invalid. Please review it and try again."
3770
+ },
3771
+ shareData: { es: "Ceder", en: "Share" },
3772
+ saveData: { es: "Guardar", en: "Save" },
3773
+ undoChange: { es: "Deshacer", en: "Undo" },
3774
+ savedToProfileHint: {
3775
+ es: "Se guardar\xE1 en tu perfil al aceptar",
3776
+ en: "It will be saved to your profile on accept"
3777
+ },
3778
+ pendingChangeHint: {
3779
+ es: "Guarda o deshaz el cambio",
3780
+ en: "Save or undo the change"
3781
+ },
3782
+ notSharedHint: {
3783
+ es: "Este dato no se ceder\xE1",
3784
+ en: "This data will not be shared"
3785
+ },
3786
+ clearField: { es: "Limpiar campo", en: "Clear field" },
3787
+ acceptData: { es: "Aceptar", en: "Accept" },
3239
3788
  noTransactionsFound: {
3240
3789
  es: "No se encontraron transacciones",
3241
3790
  en: "No transactions found"
3242
3791
  },
3792
+ otpExpiredTitle: {
3793
+ es: "Verificaci\xF3n caducada",
3794
+ en: "Verification expired"
3795
+ },
3243
3796
  otpExpiredExtension: {
3244
- es: "Tu verificaci\xF3n ha caducado. Introduce tu c\xF3digo en la extensi\xF3n de Block-Auth para aprobar este acceso.",
3245
- en: "Your verification has expired. Enter your code in the Block-Auth extension to approve this access."
3797
+ es: "Introduce tu c\xF3digo en la extensi\xF3n de Block-Auth para aprobar este acceso.",
3798
+ en: "Enter your code in the Block-Auth extension to approve this access."
3246
3799
  },
3247
3800
  otpExpiredApp: {
3248
- es: "Tu verificaci\xF3n ha caducado. Introduce tu c\xF3digo en la app de Block-Auth para aprobar este acceso.",
3249
- en: "Your verification has expired. Enter your code in the Block-Auth app to approve this access."
3801
+ es: "Introduce tu c\xF3digo en la app de Block-Auth para aprobar este acceso.",
3802
+ en: "Enter your code in the Block-Auth app to approve this access."
3250
3803
  },
3251
3804
  openExtension: { es: "Abrir extensi\xF3n", en: "Open extension" },
3252
3805
  noAppKeyFound: {
@@ -3291,6 +3844,12 @@ var TEXTS = {
3291
3844
  es: "Introduce un n\xFAmero de tel\xE9fono v\xE1lido",
3292
3845
  en: "Enter a valid phone number"
3293
3846
  },
3847
+ phoneCountry: { es: "Pa\xEDs", en: "Country" },
3848
+ searchPhoneCountry: { es: "Buscar pa\xEDs o prefijo", en: "Search country or code" },
3849
+ noPhoneCountryResults: {
3850
+ es: "No hay pa\xEDses que coincidan",
3851
+ en: "No matching countries"
3852
+ },
3294
3853
  helpUsReport: {
3295
3854
  es: "Ay\xFAdanos a mejorar y reporta el error aqu\xED",
3296
3855
  en: "Help us get better and report the error here"
@@ -3320,13 +3879,24 @@ exports.$wallet = $wallet;
3320
3879
  exports.$web3 = $web3;
3321
3880
  exports.$ws = $ws;
3322
3881
  exports.BlockAuthProvider = BlockAuthProvider;
3882
+ exports.DEFAULT_PHONE_COUNTRY = DEFAULT_PHONE_COUNTRY;
3323
3883
  exports.DISCOVERY_TIMEOUT_MS = DISCOVERY_TIMEOUT_MS;
3884
+ exports.EMPTY_SOLICITED_DATA_FORM = EMPTY_SOLICITED_DATA_FORM;
3885
+ exports.PARAM_DISPLAY_FORMATTERS = PARAM_DISPLAY_FORMATTERS;
3886
+ exports.PARAM_DISPLAY_ORDER = PARAM_DISPLAY_ORDER;
3887
+ exports.PARAM_ERROR_KEYS = PARAM_ERROR_KEYS;
3888
+ exports.PARAM_INPUT_TYPE = PARAM_INPUT_TYPE;
3889
+ exports.PARAM_LABEL_KEYS = PARAM_LABEL_KEYS;
3890
+ exports.PARAM_NORMALIZERS = PARAM_NORMALIZERS;
3891
+ exports.PARAM_VALIDATORS = PARAM_VALIDATORS;
3324
3892
  exports.RpcClient = RpcClient;
3325
3893
  exports.SDK_PAGE_MARKER = SDK_PAGE_MARKER;
3326
3894
  exports.SYNC_TIMEOUT_MS = SYNC_TIMEOUT_MS;
3327
3895
  exports.TEXTS = TEXTS;
3328
3896
  exports.WsClient = WsClient;
3329
3897
  exports.appearsExtensionInstalled = appearsExtensionInstalled;
3898
+ exports.buildPhoneE164 = buildPhoneE164;
3899
+ exports.buildPhoneValue = buildPhoneValue;
3330
3900
  exports.clearExtensionDomMarkers = clearExtensionDomMarkers;
3331
3901
  exports.clearRemainingAuthData = clearRemainingAuthData;
3332
3902
  exports.clearSdkPresence = clearSdkPresence;
@@ -3342,7 +3912,17 @@ exports.deepLinkFor = deepLinkFor;
3342
3912
  exports.discoverExtensionOnce = discoverExtensionOnce;
3343
3913
  exports.fetchUserProfile = fetchUserProfile;
3344
3914
  exports.finalizeAfterRestorationExpired = finalizeAfterRestorationExpired;
3915
+ exports.formatParamValue = formatParamValue;
3916
+ exports.formatPhoneForDisplay = formatPhoneForDisplay;
3917
+ exports.getDefaultPhoneCountry = getDefaultPhoneCountry;
3345
3918
  exports.getExtensionStoreUrl = getExtensionStoreUrl;
3919
+ exports.getPhoneCountries = getPhoneCountries;
3920
+ exports.getPhoneCountryFlag = getPhoneCountryFlag;
3921
+ exports.getPhoneDialCode = getPhoneDialCode;
3922
+ exports.getSolicitedAcceptParams = getSolicitedAcceptParams;
3923
+ exports.getSolicitedFields = getSolicitedFields;
3924
+ exports.getSolicitedHintKey = getSolicitedHintKey;
3925
+ exports.getSolicitedParams = getSolicitedParams;
3346
3926
  exports.getUserRoleNames = getUserRoleNames;
3347
3927
  exports.getUserRoleSlugs = getUserRoleSlugs;
3348
3928
  exports.getUserRoles = getUserRoles;
@@ -3356,17 +3936,24 @@ exports.isExtensionPresent = isExtensionPresent;
3356
3936
  exports.isExtensionStateComplete = isExtensionStateComplete;
3357
3937
  exports.isFirefox = isFirefox;
3358
3938
  exports.isModalOpen = isModalOpen;
3939
+ exports.isPhoneCountry = isPhoneCountry;
3359
3940
  exports.isRestorationExpiredMessage = isRestorationExpiredMessage;
3360
3941
  exports.isSdkPage = isSdkPage;
3361
3942
  exports.isShowSignin = isShowSignin;
3943
+ exports.isSolicitedDataComplete = isSolicitedDataComplete;
3944
+ exports.isSolicitedHintSuccess = isSolicitedHintSuccess;
3945
+ exports.isValidParamValue = isValidParamValue;
3946
+ exports.isValidPhoneValue = isValidPhoneValue;
3362
3947
  exports.loadUserProfile = loadUserProfile;
3363
3948
  exports.makeQrDataUrl = makeQrDataUrl;
3364
3949
  exports.markSdkPresence = markSdkPresence;
3950
+ exports.normalizeParamValue = normalizeParamValue;
3365
3951
  exports.oauth = oauth_exports;
3366
3952
  exports.onExtensionRemoved = onExtensionRemoved;
3367
3953
  exports.onExtensionStatePublished = onExtensionStatePublished;
3368
3954
  exports.openExtensionOnTxn = openExtensionOnTxn;
3369
3955
  exports.openModal = openModal;
3956
+ exports.parsePhoneValue = parsePhoneValue;
3370
3957
  exports.probeExtensionPresence = probeExtensionPresence;
3371
3958
  exports.reconcileExtensionState = reconcileExtensionState;
3372
3959
  exports.requestExtensionRefresh = requestExtensionRefresh;
@@ -3380,6 +3967,10 @@ exports.resetUser = resetUser;
3380
3967
  exports.resetWallet = resetWallet;
3381
3968
  exports.resetWeb3 = resetWeb3;
3382
3969
  exports.resetWs = resetWs;
3970
+ exports.resolvePhoneDraft = resolvePhoneDraft;
3971
+ exports.saveSolicitedValue = saveSolicitedValue;
3972
+ exports.searchPhoneCountries = searchPhoneCountries;
3973
+ exports.setAcceptTxnError = setAcceptTxnError;
3383
3974
  exports.setApiKey = setApiKey;
3384
3975
  exports.setBackendMessage = setBackendMessage;
3385
3976
  exports.setDeletionAddress = setDeletionAddress;
@@ -3407,6 +3998,8 @@ exports.setServiceIcon = setServiceIcon;
3407
3998
  exports.setServiceName = setServiceName;
3408
3999
  exports.setSignature = setSignature;
3409
4000
  exports.setSignedBy = setSignedBy;
4001
+ exports.setSolicitedShared = setSolicitedShared;
4002
+ exports.setSolicitedValue = setSolicitedValue;
3410
4003
  exports.setToken = setToken;
3411
4004
  exports.setUiConfig = setUiConfig;
3412
4005
  exports.setUser = setUser;
@@ -3414,6 +4007,9 @@ exports.setWaitingForSuccessLogInSince = setWaitingForSuccessLogInSince;
3414
4007
  exports.startExtensionSync = startExtensionSync;
3415
4008
  exports.syncExtensionStateFromStorage = syncExtensionStateFromStorage;
3416
4009
  exports.t = t;
4010
+ exports.toPhoneE164 = toPhoneE164;
4011
+ exports.undoSolicitedValue = undoSolicitedValue;
4012
+ exports.updatePhoneDraft = updatePhoneDraft;
3417
4013
  exports.utils = utils_exports;
3418
4014
  //# sourceMappingURL=index.cjs.map
3419
4015
  //# sourceMappingURL=index.cjs.map