eocene-auth-sdk 0.3.0 → 0.5.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
@@ -2600,6 +2600,16 @@ function normalizeErrorCode(body, status) {
2600
2600
  if (raw === "PLAN_USER_LIMIT" || raw === "plan_user_limit") return "plan_user_limit";
2601
2601
  if (raw === "PLAN_PROJECT_LIMIT" || raw === "plan_project_limit") return "plan_project_limit";
2602
2602
  if (raw === "RATE_LIMITED" || raw === "rate_limited") return "rate_limited";
2603
+ if (raw === "reset_cooldown") return "reset_cooldown";
2604
+ if (raw === "reset_code_invalid") return "reset_code_invalid";
2605
+ if (raw === "reset_code_expired") return "reset_code_expired";
2606
+ if (raw === "reset_code_locked") return "reset_code_locked";
2607
+ if (raw === "reset_channel_unavailable") return "reset_channel_unavailable";
2608
+ if (raw === "reset_delivery_failed") return "reset_delivery_failed";
2609
+ if (raw === "password_not_enabled") return "password_not_enabled";
2610
+ if (raw === "recovery_contact_required") return "recovery_contact_required";
2611
+ if (raw === "invalid_recovery_email") return "invalid_recovery_email";
2612
+ if (raw === "password_too_short") return "password_too_short";
2603
2613
  if (raw === "password_locked" || raw.includes("password_locked")) return "password_locked";
2604
2614
  if (raw === "password_invalid") return "password_invalid";
2605
2615
  if (raw.includes("at least 6")) return "password_too_short";
@@ -2814,7 +2824,7 @@ function createWaasEip1193Provider(client, options) {
2814
2824
 
2815
2825
  // ../eocene-worker/packages/sdk/src/index.ts
2816
2826
  async function http(url, init) {
2817
- const res = await fetch(url, init);
2827
+ const res = await fetch(url, { credentials: "include", ...init });
2818
2828
  const body = await res.json().catch(() => ({}));
2819
2829
  if (!res.ok) {
2820
2830
  throw new WaasHttpError(res.status, url, body);
@@ -2887,7 +2897,8 @@ var WaasClient = class {
2887
2897
  walletId: me.wallet?.walletId,
2888
2898
  address: me.wallet?.address,
2889
2899
  epoch: me.wallet?.epoch,
2890
- passwordEnabled: me.wallet?.passwordEnabled ?? false
2900
+ passwordEnabled: me.wallet?.passwordEnabled ?? false,
2901
+ recovery: me.wallet?.recovery
2891
2902
  };
2892
2903
  return this.getState();
2893
2904
  }
@@ -2897,29 +2908,71 @@ var WaasClient = class {
2897
2908
  headers: this.authHeaders()
2898
2909
  });
2899
2910
  }
2900
- async ensureWallet() {
2911
+ async ensureWallet(opts) {
2901
2912
  this.requireSession();
2913
+ const hasInitData = Boolean(opts?.telegramInitData);
2902
2914
  const out = await this.authed(`${this.controlBaseUrl}/wallet/ensure`, {
2903
2915
  method: "POST",
2904
- headers: this.authHeaders()
2916
+ headers: hasInitData ? { ...this.authHeaders(), "content-type": "application/json" } : this.authHeaders(),
2917
+ body: hasInitData ? JSON.stringify({ telegramInitData: opts.telegramInitData }) : void 0
2905
2918
  });
2906
2919
  this.state = {
2907
2920
  ...this.state,
2908
2921
  walletId: out.walletId,
2909
2922
  address: out.address,
2910
2923
  epoch: out.epoch,
2911
- passwordEnabled: out.passwordEnabled
2924
+ passwordEnabled: out.passwordEnabled,
2925
+ recovery: out.recovery ?? this.state?.recovery
2926
+ };
2927
+ return {
2928
+ walletId: out.walletId,
2929
+ address: out.address,
2930
+ passwordEnabled: out.passwordEnabled,
2931
+ recovery: out.recovery
2912
2932
  };
2913
- return { walletId: out.walletId, address: out.address, passwordEnabled: out.passwordEnabled };
2914
2933
  }
2915
- async setPassword(password, currentPassword) {
2934
+ async setPassword(password, currentPassword, recoveryBind) {
2916
2935
  this.requireSession();
2917
- await this.authed(`${this.controlBaseUrl}/wallet/password/set`, {
2936
+ const out = await this.authed(`${this.controlBaseUrl}/wallet/password/set`, {
2918
2937
  method: "POST",
2919
2938
  headers: { ...this.authHeaders(), "content-type": "application/json" },
2920
- body: JSON.stringify({ password, currentPassword })
2939
+ body: JSON.stringify({
2940
+ password,
2941
+ currentPassword,
2942
+ recoveryEmail: recoveryBind?.recoveryEmail,
2943
+ recoveryCode: recoveryBind?.recoveryCode
2944
+ })
2921
2945
  });
2922
- if (this.state) this.state.passwordEnabled = true;
2946
+ if (this.state) {
2947
+ this.state.passwordEnabled = true;
2948
+ if (out.recovery) this.state.recovery = out.recovery;
2949
+ }
2950
+ }
2951
+ async requestRecoveryEmailBind(email) {
2952
+ this.requireSession();
2953
+ return this.authed(
2954
+ `${this.controlBaseUrl}/wallet/recovery/email/request`,
2955
+ {
2956
+ method: "POST",
2957
+ headers: { ...this.authHeaders(), "content-type": "application/json" },
2958
+ body: JSON.stringify({ email })
2959
+ }
2960
+ );
2961
+ }
2962
+ async confirmRecoveryEmailBind(code, email) {
2963
+ this.requireSession();
2964
+ const out = await this.authed(
2965
+ `${this.controlBaseUrl}/wallet/recovery/email/confirm`,
2966
+ {
2967
+ method: "POST",
2968
+ headers: { ...this.authHeaders(), "content-type": "application/json" },
2969
+ body: JSON.stringify({ code, email })
2970
+ }
2971
+ );
2972
+ if (this.state && out.recovery) {
2973
+ this.state.recovery = out.recovery;
2974
+ }
2975
+ return out;
2923
2976
  }
2924
2977
  async clearPassword(password) {
2925
2978
  this.requireSession();
@@ -2930,6 +2983,30 @@ var WaasClient = class {
2930
2983
  });
2931
2984
  if (this.state) this.state.passwordEnabled = false;
2932
2985
  }
2986
+ async requestPasswordReset(channel) {
2987
+ this.requireSession();
2988
+ return this.authed(
2989
+ `${this.controlBaseUrl}/wallet/password/reset/request`,
2990
+ {
2991
+ method: "POST",
2992
+ headers: { ...this.authHeaders(), "content-type": "application/json" },
2993
+ body: JSON.stringify(channel ? { channel } : {})
2994
+ }
2995
+ );
2996
+ }
2997
+ async confirmPasswordReset(code, newPassword) {
2998
+ this.requireSession();
2999
+ const out = await this.authed(
3000
+ `${this.controlBaseUrl}/wallet/password/reset/confirm`,
3001
+ {
3002
+ method: "POST",
3003
+ headers: { ...this.authHeaders(), "content-type": "application/json" },
3004
+ body: JSON.stringify({ code, newPassword })
3005
+ }
3006
+ );
3007
+ if (this.state) this.state.passwordEnabled = out.passwordEnabled;
3008
+ return out;
3009
+ }
2933
3010
  async signMessage(message, opts) {
2934
3011
  const digest = hashPersonalMessage(message);
2935
3012
  return this.signDigestHex(digestToHex(digest), opts);
@@ -3042,6 +3119,24 @@ function getTelegramInitData() {
3042
3119
 
3043
3120
  // src/client/AuthClient.ts
3044
3121
  var SOCIAL_METHODS = ["google", "twitter", "github", "apple", "telegram"];
3122
+ var RESTORE_EXPIRY_BUFFER_MS = 6e4;
3123
+ var RESTORE_REFRESH_WITHIN_MS = 15 * 60 * 1e3;
3124
+ function sessionTokenExpMs(sessionToken) {
3125
+ try {
3126
+ const encoded = sessionToken.split(".")[1];
3127
+ if (!encoded) return null;
3128
+ const base64 = encoded.replace(/-/g, "+").replace(/_/g, "/");
3129
+ const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, "=");
3130
+ const payload = JSON.parse(atob(padded));
3131
+ return typeof payload.exp === "number" && Number.isFinite(payload.exp) ? payload.exp * 1e3 : null;
3132
+ } catch {
3133
+ return null;
3134
+ }
3135
+ }
3136
+ function hasUsableSessionToken(sessionToken) {
3137
+ const expMs = sessionTokenExpMs(sessionToken);
3138
+ return expMs != null && expMs > Date.now() + RESTORE_EXPIRY_BUFFER_MS;
3139
+ }
3045
3140
  var AuthClient = class {
3046
3141
  config;
3047
3142
  storageKey;
@@ -3050,6 +3145,7 @@ var AuthClient = class {
3050
3145
  provider = null;
3051
3146
  chainId;
3052
3147
  active = false;
3148
+ restorePromise = null;
3053
3149
  requestApproval;
3054
3150
  onSessionExpired;
3055
3151
  constructor(options) {
@@ -3073,7 +3169,7 @@ var AuthClient = class {
3073
3169
  const saved = loadPersistedState(this.storageKey);
3074
3170
  if (saved?.sessionToken) {
3075
3171
  this.client.hydrate(saved);
3076
- if (saved.address) this.active = true;
3172
+ this.active = Boolean(saved.address && hasUsableSessionToken(saved.sessionToken));
3077
3173
  }
3078
3174
  }
3079
3175
  setRequestApproval(fn) {
@@ -3094,7 +3190,8 @@ var AuthClient = class {
3094
3190
  email: s.email,
3095
3191
  address: s.address,
3096
3192
  walletId: s.walletId,
3097
- passwordEnabled: s.passwordEnabled
3193
+ passwordEnabled: s.passwordEnabled,
3194
+ recovery: s.recovery
3098
3195
  };
3099
3196
  }
3100
3197
  /** Current EIP-1193 chain. Changes via wallet_switchEthereumChain. */
@@ -3207,7 +3304,9 @@ var AuthClient = class {
3207
3304
  }
3208
3305
  }
3209
3306
  }
3210
- const wallet = await this.client.ensureWallet();
3307
+ const wallet = await this.client.ensureWallet({
3308
+ telegramInitData: getTelegramInitData() ?? void 0
3309
+ });
3211
3310
  this.persist();
3212
3311
  this.active = true;
3213
3312
  this.provider = null;
@@ -3238,7 +3337,7 @@ var AuthClient = class {
3238
3337
  throw new Error(body.error ?? `telegram miniapp login HTTP ${res.status}`);
3239
3338
  }
3240
3339
  await this.client.loginWithSessionToken(body.sessionToken);
3241
- const wallet = await this.client.ensureWallet();
3340
+ const wallet = await this.client.ensureWallet({ telegramInitData: data });
3242
3341
  this.persist();
3243
3342
  this.active = true;
3244
3343
  this.provider = null;
@@ -3253,7 +3352,9 @@ var AuthClient = class {
3253
3352
  if (!sessionToken) throw new Error("missing waas_session in callback");
3254
3353
  const provider = params.get("waas_provider") ?? void 0;
3255
3354
  await this.client.loginWithSessionToken(decodeURIComponent(sessionToken));
3256
- const wallet = await this.client.ensureWallet();
3355
+ const wallet = await this.client.ensureWallet({
3356
+ telegramInitData: getTelegramInitData() ?? void 0
3357
+ });
3257
3358
  this.persist();
3258
3359
  this.active = true;
3259
3360
  this.provider = null;
@@ -3286,25 +3387,113 @@ var AuthClient = class {
3286
3387
  this.persist();
3287
3388
  }
3288
3389
  }
3289
- restoreIfNeeded() {
3290
- const saved = loadPersistedState(this.storageKey);
3291
- if (!saved?.sessionToken || !saved.address) return false;
3390
+ restoreLocalSession() {
3391
+ const saved = loadPersistedState(this.storageKey) ?? this.client.getState();
3392
+ if (!saved?.sessionToken || !saved.address || !hasUsableSessionToken(saved.sessionToken)) return false;
3292
3393
  this.client.hydrate(saved);
3293
3394
  this.active = true;
3294
3395
  this.provider = null;
3295
3396
  return true;
3296
3397
  }
3398
+ localSessionNeedsRefresh() {
3399
+ const token = loadPersistedState(this.storageKey)?.sessionToken ?? this.client.getState()?.sessionToken;
3400
+ const expMs = token ? sessionTokenExpMs(token) : null;
3401
+ return expMs == null || expMs <= Date.now() + RESTORE_REFRESH_WITHIN_MS;
3402
+ }
3403
+ restoreIfNeeded() {
3404
+ return this.restoreLocalSession();
3405
+ }
3406
+ restoreSession() {
3407
+ if (this.restorePromise) return this.restorePromise;
3408
+ this.restorePromise = this.performRestoreSession().finally(() => {
3409
+ this.restorePromise = null;
3410
+ });
3411
+ return this.restorePromise;
3412
+ }
3413
+ async performRestoreSession() {
3414
+ const restoreLocalIfCurrent = () => this.restoreLocalSession() && !this.localSessionNeedsRefresh();
3415
+ if (restoreLocalIfCurrent()) return true;
3416
+ const restore = async () => {
3417
+ if (restoreLocalIfCurrent()) return true;
3418
+ try {
3419
+ const base = resolveControlAbsoluteUrl(this.config.controlBaseUrl);
3420
+ const url = `${base}/auth/session/refresh`;
3421
+ const body = JSON.stringify({ projectId: this.config.projectId });
3422
+ let res = await fetch(url, {
3423
+ method: "POST",
3424
+ credentials: "include",
3425
+ headers: { "content-type": "application/json" },
3426
+ body
3427
+ });
3428
+ const legacyToken = loadPersistedState(this.storageKey)?.sessionToken;
3429
+ const legacyExpMs = legacyToken ? sessionTokenExpMs(legacyToken) : null;
3430
+ if (res.status === 401 && legacyToken && legacyExpMs != null && legacyExpMs > Date.now()) {
3431
+ res = await fetch(url, {
3432
+ method: "POST",
3433
+ credentials: "include",
3434
+ headers: { "content-type": "application/json", authorization: `Bearer ${legacyToken}` },
3435
+ body
3436
+ });
3437
+ }
3438
+ const result = await res.json().catch(() => ({}));
3439
+ if (!res.ok || !result.sessionToken) throw new Error(`session refresh HTTP ${res.status}`);
3440
+ await this.client.loginWithSessionToken(result.sessionToken);
3441
+ await this.client.ensureWallet({
3442
+ telegramInitData: getTelegramInitData() ?? void 0
3443
+ });
3444
+ this.persist();
3445
+ this.active = true;
3446
+ this.provider = null;
3447
+ return true;
3448
+ } catch {
3449
+ if (!this.restoreLocalSession()) this.markActive(false);
3450
+ return false;
3451
+ }
3452
+ };
3453
+ if (typeof navigator !== "undefined" && navigator.locks) {
3454
+ return navigator.locks.request(`eocene:restore:${this.storageKey}`, restore);
3455
+ }
3456
+ return restore();
3457
+ }
3297
3458
  logout() {
3298
- this.markActive(false);
3459
+ const base = resolveControlAbsoluteUrl(this.config.controlBaseUrl);
3460
+ try {
3461
+ void fetch(`${base}/auth/session/logout`, {
3462
+ method: "POST",
3463
+ credentials: "include",
3464
+ keepalive: true,
3465
+ headers: { "content-type": "application/json" },
3466
+ body: JSON.stringify({ projectId: this.config.projectId })
3467
+ }).catch(() => {
3468
+ });
3469
+ } finally {
3470
+ this.markActive(false);
3471
+ }
3299
3472
  }
3300
- async setPassword(password, currentPassword) {
3301
- await this.client.setPassword(password, currentPassword);
3473
+ async setPassword(password, currentPassword, recoveryBind) {
3474
+ await this.client.setPassword(password, currentPassword, recoveryBind);
3302
3475
  this.persist();
3303
3476
  }
3304
3477
  async clearPassword(password) {
3305
3478
  await this.client.clearPassword(password);
3306
3479
  this.persist();
3307
3480
  }
3481
+ async requestRecoveryEmailBind(email) {
3482
+ return this.client.requestRecoveryEmailBind(email);
3483
+ }
3484
+ async confirmRecoveryEmailBind(code, email) {
3485
+ const out = await this.client.confirmRecoveryEmailBind(code, email);
3486
+ this.persist();
3487
+ return out;
3488
+ }
3489
+ async requestPasswordReset(channel) {
3490
+ return this.client.requestPasswordReset(channel);
3491
+ }
3492
+ async confirmPasswordReset(code, newPassword) {
3493
+ const out = await this.client.confirmPasswordReset(code, newPassword);
3494
+ this.persist();
3495
+ return out;
3496
+ }
3308
3497
  };
3309
3498
 
3310
3499
  // src/provider/createProvider.ts
@@ -3323,6 +3512,27 @@ function formatAuthError(e, labels) {
3323
3512
  if (e.code === "plan_project_limit") {
3324
3513
  return "Project limit reached on this Eocene account.";
3325
3514
  }
3515
+ if (e.code === "reset_code_invalid") return labels.passwordSettingsResetCodeInvalid;
3516
+ if (e.code === "reset_code_expired") return labels.passwordSettingsResetCodeExpired;
3517
+ if (e.code === "reset_code_locked") return labels.passwordSettingsResetCodeLocked;
3518
+ if (e.code === "reset_cooldown") {
3519
+ return labels.passwordSettingsResetCooldown.replace(
3520
+ "{seconds}",
3521
+ String(e.retryAfterSec ?? 60)
3522
+ );
3523
+ }
3524
+ if (e.code === "reset_channel_unavailable") {
3525
+ return labels.passwordSettingsResetChannelUnavailable;
3526
+ }
3527
+ if (e.code === "reset_delivery_failed") {
3528
+ return e.message || labels.passwordSettingsResetDeliveryFailed;
3529
+ }
3530
+ if (e.code === "recovery_contact_required") {
3531
+ return labels.passwordSettingsRecoveryRequired;
3532
+ }
3533
+ if (e.code === "invalid_recovery_email") {
3534
+ return labels.passwordSettingsInvalidRecoveryEmail;
3535
+ }
3326
3536
  return formatSignAuthError(
3327
3537
  {
3328
3538
  code: e.code,
@@ -3584,28 +3794,96 @@ function AuthLoginPanel({
3584
3794
  function SetPasswordModal({
3585
3795
  open,
3586
3796
  passwordEnabled,
3797
+ initialMode,
3798
+ recovery,
3587
3799
  labels,
3588
3800
  busy,
3801
+ sendingResetCode = false,
3802
+ resetSent = null,
3803
+ sendingRecoveryBindCode = false,
3804
+ recoveryBindSent = null,
3589
3805
  error,
3590
3806
  onSubmitSet,
3591
3807
  onSubmitClear,
3808
+ onRequestResetCode,
3809
+ onSubmitReset,
3810
+ onRequestRecoveryEmailBind,
3592
3811
  onClose
3593
3812
  }) {
3594
3813
  const [password, setPassword] = useState("");
3595
3814
  const [confirm, setConfirm] = useState("");
3596
3815
  const [current, setCurrent] = useState("");
3816
+ const [code, setCode] = useState("");
3817
+ const [recoveryEmail, setRecoveryEmail] = useState("");
3818
+ const [recoveryCode, setRecoveryCode] = useState("");
3819
+ const [selectedChannel, setSelectedChannel] = useState(
3820
+ void 0
3821
+ );
3597
3822
  const [mode, setMode] = useState("set");
3823
+ const [cooldownLeft, setCooldownLeft] = useState(0);
3824
+ const [bindCooldownLeft, setBindCooldownLeft] = useState(0);
3598
3825
  useEffect(() => {
3599
3826
  if (!open) return;
3600
3827
  setPassword("");
3601
3828
  setConfirm("");
3602
3829
  setCurrent("");
3603
- setMode(passwordEnabled ? "set" : "set");
3604
- }, [open, passwordEnabled]);
3830
+ setCode("");
3831
+ setRecoveryEmail("");
3832
+ setRecoveryCode("");
3833
+ setSelectedChannel(recovery?.defaultChannel ?? void 0);
3834
+ setMode(passwordEnabled && initialMode ? initialMode : "set");
3835
+ }, [open, passwordEnabled, initialMode, recovery?.defaultChannel]);
3836
+ useEffect(() => {
3837
+ if (!open || !resetSent) {
3838
+ setCooldownLeft(0);
3839
+ return;
3840
+ }
3841
+ const update = () => {
3842
+ const rem = Math.max(
3843
+ 0,
3844
+ Math.ceil((resetSent.sentAt + resetSent.cooldownSec * 1e3 - Date.now()) / 1e3)
3845
+ );
3846
+ setCooldownLeft(rem);
3847
+ };
3848
+ update();
3849
+ const timer = window.setInterval(update, 1e3);
3850
+ return () => window.clearInterval(timer);
3851
+ }, [open, resetSent]);
3852
+ useEffect(() => {
3853
+ if (!open || !recoveryBindSent) {
3854
+ setBindCooldownLeft(0);
3855
+ return;
3856
+ }
3857
+ const update = () => {
3858
+ const rem = Math.max(
3859
+ 0,
3860
+ Math.ceil(
3861
+ (recoveryBindSent.sentAt + recoveryBindSent.cooldownSec * 1e3 - Date.now()) / 1e3
3862
+ )
3863
+ );
3864
+ setBindCooldownLeft(rem);
3865
+ };
3866
+ update();
3867
+ const timer = window.setInterval(update, 1e3);
3868
+ return () => window.clearInterval(timer);
3869
+ }, [open, recoveryBindSent]);
3605
3870
  if (!open) return null;
3871
+ const needsRecoveryBind = Boolean(
3872
+ mode === "set" && recovery && !recovery.hasRecovery && onRequestRecoveryEmailBind
3873
+ );
3606
3874
  const mismatch = password.length > 0 && confirm.length > 0 && password !== confirm;
3607
- const canSet = password.length >= 6 && password === confirm && (!passwordEnabled || current.length > 0) && !busy;
3875
+ const normalizedCode = code.trim();
3876
+ const validCode = /^\d{6}$/.test(normalizedCode);
3877
+ const normalizedBindCode = recoveryCode.trim();
3878
+ const validBindCode = /^\d{6}$/.test(normalizedBindCode);
3879
+ const validRecoveryEmail = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(recoveryEmail.trim());
3880
+ const canSet = password.length >= 6 && password === confirm && (!passwordEnabled || current.length > 0) && (!needsRecoveryBind || validRecoveryEmail && validBindCode) && !busy;
3608
3881
  const canClear = passwordEnabled && current.length > 0 && !busy;
3882
+ const canResetSet = passwordEnabled && validCode && password.length >= 6 && password === confirm && !busy;
3883
+ const canResetClear = passwordEnabled && validCode && !busy;
3884
+ const resetHintText = mode === "reset" && resetSent ? (resetSent.channel === "telegram" ? labels.passwordSettingsCodeSentTelegram : labels.passwordSettingsCodeSentEmail).replace("{target}", resetSent.maskedTarget) : mode === "reset" ? labels.passwordSettingsResetHint : needsRecoveryBind ? recoveryBindSent ? labels.passwordSettingsCodeSentEmail.replace("{target}", recoveryBindSent.maskedTarget) : labels.passwordSettingsBindEmailHint : passwordEnabled ? labels.passwordSettingsEnabledHint : labels.passwordSettingsDisabledHint;
3885
+ const dualChannels = Boolean(recovery?.channels && recovery.channels.length > 1);
3886
+ const effectiveResetChannel = selectedChannel ?? recovery?.defaultChannel ?? void 0;
3609
3887
  return /* @__PURE__ */ jsxs("div", { className: "auth-sdk-root", role: "presentation", children: [
3610
3888
  /* @__PURE__ */ jsx("div", { className: "auth-sdk-backdrop", onClick: busy ? void 0 : onClose, "aria-hidden": true }),
3611
3889
  /* @__PURE__ */ jsxs(
@@ -3623,7 +3901,7 @@ function SetPasswordModal({
3623
3901
  /* @__PURE__ */ jsx("h2", { id: "auth-sdk-password-title", className: "auth-sdk-sign-title", children: labels.passwordSettingsTitle })
3624
3902
  ] })
3625
3903
  ] }),
3626
- /* @__PURE__ */ jsx("p", { className: "auth-sdk-sign-subtitle", children: passwordEnabled ? labels.passwordSettingsEnabledHint : labels.passwordSettingsDisabledHint }),
3904
+ /* @__PURE__ */ jsx("p", { className: "auth-sdk-sign-subtitle", children: resetHintText }),
3627
3905
  passwordEnabled ? /* @__PURE__ */ jsxs("div", { className: "auth-sdk-mode-tabs", role: "tablist", children: [
3628
3906
  /* @__PURE__ */ jsx(
3629
3907
  "button",
@@ -3648,14 +3926,87 @@ function SetPasswordModal({
3648
3926
  disabled: busy,
3649
3927
  children: labels.passwordSettingsClear
3650
3928
  }
3651
- )
3929
+ ),
3930
+ onRequestResetCode && onSubmitReset ? /* @__PURE__ */ jsx(
3931
+ "button",
3932
+ {
3933
+ type: "button",
3934
+ role: "tab",
3935
+ className: `auth-sdk-mode-tab${mode === "reset" ? " is-active" : ""}`,
3936
+ "aria-selected": mode === "reset",
3937
+ onClick: () => setMode("reset"),
3938
+ disabled: busy,
3939
+ children: labels.passwordSettingsReset
3940
+ }
3941
+ ) : null
3652
3942
  ] }) : null,
3653
3943
  mode === "set" ? /* @__PURE__ */ jsxs(Fragment, { children: [
3654
- passwordEnabled ? /* @__PURE__ */ jsxs("label", { className: "auth-sdk-password", children: [
3655
- /* @__PURE__ */ jsx("span", { children: labels.passwordSettingsCurrentLabel }),
3944
+ needsRecoveryBind ? /* @__PURE__ */ jsxs(Fragment, { children: [
3945
+ /* @__PURE__ */ jsxs("div", { className: "auth-sdk-password", children: [
3946
+ /* @__PURE__ */ jsx("span", { children: labels.passwordSettingsBindEmailLabel }),
3947
+ /* @__PURE__ */ jsxs("div", { className: "auth-sdk-code-row", children: [
3948
+ /* @__PURE__ */ jsx(
3949
+ "input",
3950
+ {
3951
+ type: "email",
3952
+ autoComplete: "email",
3953
+ placeholder: labels.passwordSettingsBindEmailPlaceholder,
3954
+ value: recoveryEmail,
3955
+ onChange: (e) => setRecoveryEmail(e.target.value),
3956
+ disabled: busy,
3957
+ autoFocus: !passwordEnabled
3958
+ }
3959
+ ),
3960
+ /* @__PURE__ */ jsx(
3961
+ "button",
3962
+ {
3963
+ type: "button",
3964
+ className: "auth-sdk-code-send-btn",
3965
+ disabled: busy || sendingRecoveryBindCode || bindCooldownLeft > 0 || !validRecoveryEmail,
3966
+ onClick: () => void onRequestRecoveryEmailBind?.(recoveryEmail.trim()),
3967
+ children: sendingRecoveryBindCode ? labels.passwordSettingsSendingCode : bindCooldownLeft > 0 ? labels.passwordSettingsResendCooldown.replace(
3968
+ "{seconds}",
3969
+ String(bindCooldownLeft)
3970
+ ) : recoveryBindSent ? labels.passwordSettingsResendCode : labels.passwordSettingsSendCode
3971
+ }
3972
+ )
3973
+ ] })
3974
+ ] }),
3975
+ /* @__PURE__ */ jsxs("label", { className: "auth-sdk-password", children: [
3976
+ /* @__PURE__ */ jsx("span", { children: labels.passwordSettingsCodeLabel }),
3977
+ /* @__PURE__ */ jsx(
3978
+ "input",
3979
+ {
3980
+ type: "text",
3981
+ inputMode: "numeric",
3982
+ maxLength: 6,
3983
+ autoComplete: "one-time-code",
3984
+ placeholder: labels.passwordSettingsCodePlaceholder,
3985
+ value: recoveryCode,
3986
+ onChange: (e) => setRecoveryCode(e.target.value.replace(/\D+/g, "").slice(0, 6)),
3987
+ disabled: busy
3988
+ }
3989
+ )
3990
+ ] })
3991
+ ] }) : null,
3992
+ passwordEnabled ? /* @__PURE__ */ jsxs("div", { className: "auth-sdk-password", children: [
3993
+ /* @__PURE__ */ jsxs("div", { className: "auth-sdk-password-label-row", children: [
3994
+ /* @__PURE__ */ jsx("label", { htmlFor: "auth-sdk-pw-current", children: labels.passwordSettingsCurrentLabel }),
3995
+ onRequestResetCode && onSubmitReset ? /* @__PURE__ */ jsx(
3996
+ "button",
3997
+ {
3998
+ type: "button",
3999
+ className: "auth-sdk-forgot-btn",
4000
+ onClick: () => setMode("reset"),
4001
+ disabled: busy,
4002
+ children: labels.signForgotPassword
4003
+ }
4004
+ ) : null
4005
+ ] }),
3656
4006
  /* @__PURE__ */ jsx(
3657
4007
  "input",
3658
4008
  {
4009
+ id: "auth-sdk-pw-current",
3659
4010
  type: "password",
3660
4011
  autoComplete: "current-password",
3661
4012
  placeholder: labels.passwordSettingsCurrentPlaceholder,
@@ -3677,7 +4028,7 @@ function SetPasswordModal({
3677
4028
  value: password,
3678
4029
  onChange: (e) => setPassword(e.target.value),
3679
4030
  disabled: busy,
3680
- autoFocus: !passwordEnabled
4031
+ autoFocus: !passwordEnabled && !needsRecoveryBind
3681
4032
  }
3682
4033
  )
3683
4034
  ] }),
@@ -3696,11 +4047,24 @@ function SetPasswordModal({
3696
4047
  )
3697
4048
  ] }),
3698
4049
  mismatch ? /* @__PURE__ */ jsx("p", { className: "auth-sdk-sign-error", children: labels.passwordSettingsMismatch }) : null
3699
- ] }) : /* @__PURE__ */ jsxs("label", { className: "auth-sdk-password", children: [
3700
- /* @__PURE__ */ jsx("span", { children: labels.passwordSettingsCurrentLabel }),
4050
+ ] }) : mode === "clear" ? /* @__PURE__ */ jsxs("div", { className: "auth-sdk-password", children: [
4051
+ /* @__PURE__ */ jsxs("div", { className: "auth-sdk-password-label-row", children: [
4052
+ /* @__PURE__ */ jsx("label", { htmlFor: "auth-sdk-pw-clear-current", children: labels.passwordSettingsCurrentLabel }),
4053
+ onRequestResetCode && onSubmitReset ? /* @__PURE__ */ jsx(
4054
+ "button",
4055
+ {
4056
+ type: "button",
4057
+ className: "auth-sdk-forgot-btn",
4058
+ onClick: () => setMode("reset"),
4059
+ disabled: busy,
4060
+ children: labels.signForgotPassword
4061
+ }
4062
+ ) : null
4063
+ ] }),
3701
4064
  /* @__PURE__ */ jsx(
3702
4065
  "input",
3703
4066
  {
4067
+ id: "auth-sdk-pw-clear-current",
3704
4068
  type: "password",
3705
4069
  autoComplete: "current-password",
3706
4070
  placeholder: labels.passwordSettingsCurrentPlaceholder,
@@ -3710,6 +4074,103 @@ function SetPasswordModal({
3710
4074
  autoFocus: true
3711
4075
  }
3712
4076
  )
4077
+ ] }) : /* @__PURE__ */ jsxs(Fragment, { children: [
4078
+ dualChannels ? /* @__PURE__ */ jsxs("div", { className: "auth-sdk-mode-tabs", role: "radiogroup", children: [
4079
+ /* @__PURE__ */ jsxs(
4080
+ "button",
4081
+ {
4082
+ type: "button",
4083
+ className: `auth-sdk-mode-tab${effectiveResetChannel === "email" ? " is-active" : ""}`,
4084
+ onClick: () => setSelectedChannel("email"),
4085
+ disabled: busy || sendingResetCode,
4086
+ children: [
4087
+ "Email",
4088
+ recovery?.maskedEmail ? ` (${recovery.maskedEmail})` : ""
4089
+ ]
4090
+ }
4091
+ ),
4092
+ /* @__PURE__ */ jsx(
4093
+ "button",
4094
+ {
4095
+ type: "button",
4096
+ className: `auth-sdk-mode-tab${effectiveResetChannel === "telegram" ? " is-active" : ""}`,
4097
+ onClick: () => setSelectedChannel("telegram"),
4098
+ disabled: busy || sendingResetCode,
4099
+ children: recovery?.maskedTelegram ?? "Telegram"
4100
+ }
4101
+ )
4102
+ ] }) : null,
4103
+ /* @__PURE__ */ jsxs("div", { className: "auth-sdk-password", children: [
4104
+ /* @__PURE__ */ jsx("span", { children: labels.passwordSettingsCodeLabel }),
4105
+ /* @__PURE__ */ jsxs("div", { className: "auth-sdk-code-row", children: [
4106
+ /* @__PURE__ */ jsx(
4107
+ "input",
4108
+ {
4109
+ type: "text",
4110
+ inputMode: "numeric",
4111
+ maxLength: 6,
4112
+ autoComplete: "one-time-code",
4113
+ placeholder: labels.passwordSettingsCodePlaceholder,
4114
+ value: code,
4115
+ onChange: (e) => setCode(e.target.value.replace(/\D+/g, "").slice(0, 6)),
4116
+ disabled: busy,
4117
+ autoFocus: true
4118
+ }
4119
+ ),
4120
+ /* @__PURE__ */ jsx(
4121
+ "button",
4122
+ {
4123
+ type: "button",
4124
+ className: "auth-sdk-code-send-btn",
4125
+ disabled: busy || sendingResetCode || cooldownLeft > 0,
4126
+ onClick: () => void onRequestResetCode?.(effectiveResetChannel),
4127
+ children: sendingResetCode ? labels.passwordSettingsSendingCode : cooldownLeft > 0 ? labels.passwordSettingsResendCooldown.replace(
4128
+ "{seconds}",
4129
+ String(cooldownLeft)
4130
+ ) : resetSent ? labels.passwordSettingsResendCode : labels.passwordSettingsSendCode
4131
+ }
4132
+ )
4133
+ ] })
4134
+ ] }),
4135
+ /* @__PURE__ */ jsxs("label", { className: "auth-sdk-password", children: [
4136
+ /* @__PURE__ */ jsx("span", { children: labels.passwordSettingsNewLabel }),
4137
+ /* @__PURE__ */ jsx(
4138
+ "input",
4139
+ {
4140
+ type: "password",
4141
+ autoComplete: "new-password",
4142
+ placeholder: labels.passwordSettingsNewPlaceholder,
4143
+ value: password,
4144
+ onChange: (e) => setPassword(e.target.value),
4145
+ disabled: busy
4146
+ }
4147
+ )
4148
+ ] }),
4149
+ /* @__PURE__ */ jsxs("label", { className: "auth-sdk-password", children: [
4150
+ /* @__PURE__ */ jsx("span", { children: labels.passwordSettingsConfirmLabel }),
4151
+ /* @__PURE__ */ jsx(
4152
+ "input",
4153
+ {
4154
+ type: "password",
4155
+ autoComplete: "new-password",
4156
+ placeholder: labels.passwordSettingsConfirmPlaceholder,
4157
+ value: confirm,
4158
+ onChange: (e) => setConfirm(e.target.value),
4159
+ disabled: busy
4160
+ }
4161
+ )
4162
+ ] }),
4163
+ mismatch ? /* @__PURE__ */ jsx("p", { className: "auth-sdk-sign-error", children: labels.passwordSettingsMismatch }) : null,
4164
+ validCode && password.length === 0 ? /* @__PURE__ */ jsx("div", { className: "auth-sdk-reset-clear-row", children: /* @__PURE__ */ jsx(
4165
+ "button",
4166
+ {
4167
+ type: "button",
4168
+ className: "auth-sdk-forgot-btn",
4169
+ disabled: !canResetClear,
4170
+ onClick: () => void onSubmitReset?.(normalizedCode, null),
4171
+ children: labels.passwordSettingsResetClearConfirm
4172
+ }
4173
+ ) }) : null
3713
4174
  ] }),
3714
4175
  error ? /* @__PURE__ */ jsx("p", { className: "auth-sdk-sign-error", children: error }) : null,
3715
4176
  /* @__PURE__ */ jsxs("div", { className: "auth-sdk-actions", children: [
@@ -3729,10 +4190,14 @@ function SetPasswordModal({
3729
4190
  type: "button",
3730
4191
  className: "auth-sdk-btn auth-sdk-btn-primary",
3731
4192
  disabled: !canSet,
3732
- onClick: () => void onSubmitSet(password, passwordEnabled ? current : void 0),
4193
+ onClick: () => void onSubmitSet(
4194
+ password,
4195
+ passwordEnabled ? current : void 0,
4196
+ needsRecoveryBind ? { recoveryEmail: recoveryEmail.trim(), recoveryCode: normalizedBindCode } : void 0
4197
+ ),
3733
4198
  children: busy ? labels.passwordSettingsSaving : labels.passwordSettingsSave
3734
4199
  }
3735
- ) : /* @__PURE__ */ jsx(
4200
+ ) : mode === "clear" ? /* @__PURE__ */ jsx(
3736
4201
  "button",
3737
4202
  {
3738
4203
  type: "button",
@@ -3741,6 +4206,15 @@ function SetPasswordModal({
3741
4206
  onClick: () => void onSubmitClear(current),
3742
4207
  children: busy ? labels.passwordSettingsSaving : labels.passwordSettingsClearConfirm
3743
4208
  }
4209
+ ) : /* @__PURE__ */ jsx(
4210
+ "button",
4211
+ {
4212
+ type: "button",
4213
+ className: "auth-sdk-btn auth-sdk-btn-primary",
4214
+ disabled: !canResetSet,
4215
+ onClick: () => void onSubmitReset?.(normalizedCode, password),
4216
+ children: busy ? labels.passwordSettingsSaving : labels.passwordSettingsResetConfirm
4217
+ }
3744
4218
  )
3745
4219
  ] })
3746
4220
  ]
@@ -3774,7 +4248,8 @@ function SignConfirmModal({
3774
4248
  onPasswordChange,
3775
4249
  onApprove,
3776
4250
  onReject,
3777
- onOpenSetPassword
4251
+ onOpenSetPassword,
4252
+ onOpenResetPassword
3778
4253
  }) {
3779
4254
  if (!open || !request) return null;
3780
4255
  const isTyped = request.method === "eth_signTypedData_v4";
@@ -3783,6 +4258,7 @@ function SignConfirmModal({
3783
4258
  const payloadLabel = isTyped ? labels.signPayloadLabelTyped : isTx ? labels.signPayloadLabelTx : labels.signPayloadLabel;
3784
4259
  const needsPassword = request.passwordEnabled;
3785
4260
  const canApprove = !locked && (needsPassword ? password.length > 0 && !busy : !busy);
4261
+ const handleForgotPassword = onOpenResetPassword ?? onOpenSetPassword;
3786
4262
  return /* @__PURE__ */ jsxs("div", { className: "auth-sdk-root", role: "presentation", children: [
3787
4263
  /* @__PURE__ */ jsx("div", { className: "auth-sdk-backdrop", onClick: busy ? void 0 : onReject, "aria-hidden": true }),
3788
4264
  /* @__PURE__ */ jsxs(
@@ -3815,11 +4291,24 @@ function SignConfirmModal({
3815
4291
  /* @__PURE__ */ jsx("span", { className: "auth-sdk-sign-msg-label", children: payloadLabel }),
3816
4292
  /* @__PURE__ */ jsx("pre", { className: "auth-sdk-sign-body", children: truncateMessage(request.message) })
3817
4293
  ] }),
3818
- needsPassword ? /* @__PURE__ */ jsxs("label", { className: "auth-sdk-password", children: [
3819
- /* @__PURE__ */ jsx("span", { children: labels.signPasswordLabel }),
4294
+ needsPassword ? /* @__PURE__ */ jsxs("div", { className: "auth-sdk-password", children: [
4295
+ /* @__PURE__ */ jsxs("div", { className: "auth-sdk-password-label-row", children: [
4296
+ /* @__PURE__ */ jsx("label", { htmlFor: "auth-sdk-sign-password-input", children: labels.signPasswordLabel }),
4297
+ handleForgotPassword ? /* @__PURE__ */ jsx(
4298
+ "button",
4299
+ {
4300
+ type: "button",
4301
+ className: "auth-sdk-forgot-btn",
4302
+ onClick: handleForgotPassword,
4303
+ disabled: busy,
4304
+ children: labels.signForgotPassword
4305
+ }
4306
+ ) : null
4307
+ ] }),
3820
4308
  /* @__PURE__ */ jsx(
3821
4309
  "input",
3822
4310
  {
4311
+ id: "auth-sdk-sign-password-input",
3823
4312
  type: "password",
3824
4313
  autoComplete: "current-password",
3825
4314
  placeholder: labels.signPasswordPlaceholder,
@@ -3891,6 +4380,7 @@ var DEFAULT_LABELS = {
3891
4380
  signReject: "Reject",
3892
4381
  signPasswordLabel: "Wallet password",
3893
4382
  signPasswordPlaceholder: "Enter password",
4383
+ signForgotPassword: "Forgot password?",
3894
4384
  signSetPasswordOptional: "Optional \u2014 protect future signatures with a password.",
3895
4385
  signSetPasswordButton: "Set password",
3896
4386
  signPasswordIncorrect: "Incorrect password",
@@ -3921,6 +4411,29 @@ var DEFAULT_LABELS = {
3921
4411
  passwordSettingsDisabledHint: "Optional. When set, signing will ask for this password.",
3922
4412
  passwordSettingsChange: "Change",
3923
4413
  passwordSettingsClear: "Remove",
4414
+ passwordSettingsReset: "Reset",
4415
+ passwordSettingsResetHint: "Receive a 6-digit verification code via your bound email or Telegram to reset your wallet password.",
4416
+ passwordSettingsSendCode: "Send code",
4417
+ passwordSettingsSendingCode: "Sending\u2026",
4418
+ passwordSettingsResendCode: "Resend",
4419
+ passwordSettingsResendCooldown: "Resend ({seconds}s)",
4420
+ passwordSettingsCodeSentEmail: "Verification code sent to {target}",
4421
+ passwordSettingsCodeSentTelegram: "Verification code sent via {target}",
4422
+ passwordSettingsCodeLabel: "Verification code",
4423
+ passwordSettingsCodePlaceholder: "6-digit code",
4424
+ passwordSettingsResetConfirm: "Reset password",
4425
+ passwordSettingsResetClearConfirm: "Verify & remove password",
4426
+ passwordSettingsResetCodeInvalid: "Incorrect verification code",
4427
+ passwordSettingsResetCodeExpired: "Verification code expired. Please request a new code.",
4428
+ passwordSettingsResetCodeLocked: "Too many incorrect attempts. Please request a new code.",
4429
+ passwordSettingsResetCooldown: "Please wait {seconds}s before requesting another code.",
4430
+ passwordSettingsResetChannelUnavailable: "No verified email or Telegram account is linked to this wallet.",
4431
+ passwordSettingsResetDeliveryFailed: "Failed to send verification code. Please try again.",
4432
+ passwordSettingsBindEmailLabel: "Recovery email",
4433
+ passwordSettingsBindEmailPlaceholder: "Enter email for password recovery",
4434
+ passwordSettingsBindEmailHint: "Your login method has no email or Telegram linked. Verify a recovery email to enable wallet password.",
4435
+ passwordSettingsRecoveryRequired: "Please verify a recovery email first",
4436
+ passwordSettingsInvalidRecoveryEmail: "Please enter a valid email address",
3924
4437
  passwordSettingsCurrentLabel: "Current password",
3925
4438
  passwordSettingsCurrentPlaceholder: "Current password",
3926
4439
  passwordSettingsNewLabel: "New password",
@@ -3953,8 +4466,14 @@ function AuthProvider({
3953
4466
  const [signBusy, setSignBusy] = useState(false);
3954
4467
  const [signError, setSignError] = useState(null);
3955
4468
  const [passwordSettingsOpen, setPasswordSettingsOpen] = useState(false);
4469
+ const [passwordInitialMode, setPasswordInitialMode] = useState("set");
3956
4470
  const [passwordBusy, setPasswordBusy] = useState(false);
4471
+ const [sendingResetCode, setSendingResetCode] = useState(false);
4472
+ const [resetSent, setResetSent] = useState(null);
4473
+ const [sendingRecoveryBindCode, setSendingRecoveryBindCode] = useState(false);
4474
+ const [recoveryBindSent, setRecoveryBindSent] = useState(null);
3957
4475
  const [passwordError, setPasswordError] = useState(null);
4476
+ const [passwordVersion, setPasswordVersion] = useState(0);
3958
4477
  const pendingSignRef = useRef(null);
3959
4478
  const defaultModalApproval = useCallback((req) => {
3960
4479
  return new Promise((resolve) => {
@@ -3979,13 +4498,16 @@ function AuthProvider({
3979
4498
  );
3980
4499
  const [tick, setTick] = useState(0);
3981
4500
  const [ready, setReady] = useState(false);
4501
+ const mountedRef = useRef(false);
3982
4502
  const sessionExpiredRef = useRef(void 0);
3983
4503
  sessionExpiredRef.current = onSessionExpired;
3984
4504
  const handleSessionExpired = useCallback(() => {
3985
4505
  pendingSignRef.current?.resolve(false);
3986
4506
  pendingSignRef.current = null;
3987
- setPendingSign(null);
3988
- setTick((n) => n + 1);
4507
+ if (mountedRef.current) {
4508
+ setPendingSign(null);
4509
+ setTick((n) => n + 1);
4510
+ }
3989
4511
  sessionExpiredRef.current?.();
3990
4512
  }, []);
3991
4513
  const clientRef = useRef(null);
@@ -3997,26 +4519,52 @@ function AuthProvider({
3997
4519
  onSessionExpired: handleSessionExpired
3998
4520
  });
3999
4521
  }
4522
+ useEffect(() => {
4523
+ mountedRef.current = true;
4524
+ return () => {
4525
+ mountedRef.current = false;
4526
+ };
4527
+ }, []);
4000
4528
  useEffect(() => {
4001
4529
  clientRef.current?.setRequestApproval(approvalFn);
4002
4530
  }, [approvalFn]);
4003
4531
  useEffect(() => {
4004
4532
  const c = clientRef.current;
4005
4533
  if (!c) return;
4006
- if (c.config.controlBaseUrl !== config.controlBaseUrl || c.config.oauthReturnTo !== config.oauthReturnTo) {
4534
+ if (c.config.controlBaseUrl !== config.controlBaseUrl || c.config.oauthReturnTo !== config.oauthReturnTo || c.config.projectId !== config.projectId || c.config.chainId !== config.chainId || c.config.asDeveloper !== config.asDeveloper || c.config.storageKey !== config.storageKey || c.config.oauthPendingKey !== config.oauthPendingKey || c.config.allowDevLoginFallback !== config.allowDevLoginFallback) {
4007
4535
  clientRef.current = new AuthClient({
4008
4536
  config,
4537
+ chainId: config.chainId,
4009
4538
  requestApproval: approvalFn,
4010
4539
  onSessionExpired: handleSessionExpired
4011
4540
  });
4541
+ setReady(false);
4012
4542
  setTick((n) => n + 1);
4013
4543
  }
4014
4544
  }, [config, approvalFn, handleSessionExpired]);
4015
4545
  useEffect(() => {
4016
- clientRef.current?.restoreIfNeeded();
4017
- setReady(true);
4018
- setTick((n) => n + 1);
4019
- }, []);
4546
+ let alive = true;
4547
+ const c = clientRef.current;
4548
+ if (!c) return;
4549
+ setReady(false);
4550
+ void c.restoreSession().then(() => {
4551
+ if (!alive || clientRef.current !== c) return;
4552
+ setTick((n) => n + 1);
4553
+ setReady(true);
4554
+ });
4555
+ return () => {
4556
+ alive = false;
4557
+ };
4558
+ }, [
4559
+ config.controlBaseUrl,
4560
+ config.oauthReturnTo,
4561
+ config.projectId,
4562
+ config.chainId,
4563
+ config.asDeveloper,
4564
+ config.storageKey,
4565
+ config.oauthPendingKey,
4566
+ config.allowDevLoginFallback
4567
+ ]);
4020
4568
  const [availableMethods, setAvailableMethods] = useState(null);
4021
4569
  useEffect(() => {
4022
4570
  let alive = true;
@@ -4030,7 +4578,9 @@ function AuthProvider({
4030
4578
  alive = false;
4031
4579
  };
4032
4580
  }, [config.controlBaseUrl, config.projectId]);
4033
- const bump = useCallback(() => setTick((n) => n + 1), []);
4581
+ const bump = useCallback(() => {
4582
+ if (mountedRef.current) setTick((n) => n + 1);
4583
+ }, []);
4034
4584
  const login = useCallback(
4035
4585
  async (args) => {
4036
4586
  const result = await clientRef.current.login(args.method);
@@ -4060,6 +4610,12 @@ function AuthProvider({
4060
4610
  bump();
4061
4611
  return ok;
4062
4612
  }, [bump]);
4613
+ const restoreSession = useCallback(async () => {
4614
+ const c = clientRef.current;
4615
+ const ok = await c.restoreSession();
4616
+ if (clientRef.current === c) bump();
4617
+ return ok;
4618
+ }, [bump]);
4063
4619
  const completeOAuthFromHash = useCallback(
4064
4620
  async (hashOrSearch) => {
4065
4621
  const result = await clientRef.current.completeOAuthFromHash(hashOrSearch);
@@ -4072,8 +4628,9 @@ function AuthProvider({
4072
4628
  const getProvider = useCallback(() => clientRef.current.getProvider(), []);
4073
4629
  const getConnectorShim = useCallback(() => clientRef.current.getConnectorShim(), []);
4074
4630
  const setPassword = useCallback(
4075
- async (pw, currentPassword) => {
4076
- await clientRef.current.setPassword(pw, currentPassword);
4631
+ async (pw, currentPassword, recoveryBind) => {
4632
+ await clientRef.current.setPassword(pw, currentPassword, recoveryBind);
4633
+ setPasswordVersion((v) => v + 1);
4077
4634
  bump();
4078
4635
  },
4079
4636
  [bump]
@@ -4081,19 +4638,47 @@ function AuthProvider({
4081
4638
  const clearPassword = useCallback(
4082
4639
  async (pw) => {
4083
4640
  await clientRef.current.clearPassword(pw);
4641
+ setPasswordVersion((v) => v + 1);
4642
+ bump();
4643
+ },
4644
+ [bump]
4645
+ );
4646
+ const requestPasswordReset = useCallback(
4647
+ async (channel) => {
4648
+ return clientRef.current.requestPasswordReset(channel);
4649
+ },
4650
+ []
4651
+ );
4652
+ const confirmPasswordReset = useCallback(
4653
+ async (code, newPassword) => {
4654
+ const out = await clientRef.current.confirmPasswordReset(code, newPassword);
4655
+ setPasswordVersion((v) => v + 1);
4084
4656
  bump();
4657
+ return out;
4085
4658
  },
4086
4659
  [bump]
4087
4660
  );
4088
- const openPasswordSettings = useCallback(() => {
4661
+ const requestRecoveryEmailBind = useCallback(async (email) => {
4662
+ return clientRef.current.requestRecoveryEmailBind(email);
4663
+ }, []);
4664
+ const confirmRecoveryEmailBind = useCallback(
4665
+ async (code, email) => {
4666
+ const out = await clientRef.current.confirmRecoveryEmailBind(code, email);
4667
+ bump();
4668
+ return out;
4669
+ },
4670
+ [bump]
4671
+ );
4672
+ const openPasswordSettings = useCallback((initialMode) => {
4089
4673
  setPasswordError(null);
4674
+ setPasswordInitialMode(initialMode ?? "set");
4090
4675
  setPasswordSettingsOpen(true);
4091
4676
  }, []);
4092
4677
  const closePasswordSettings = useCallback(() => {
4093
- if (passwordBusy) return;
4678
+ if (passwordBusy || sendingResetCode || sendingRecoveryBindCode) return;
4094
4679
  setPasswordSettingsOpen(false);
4095
4680
  setPasswordError(null);
4096
- }, [passwordBusy]);
4681
+ }, [passwordBusy, sendingResetCode, sendingRecoveryBindCode]);
4097
4682
  const client = clientRef.current;
4098
4683
  const authenticated = client.isAuthenticated();
4099
4684
  const user = client.getUser();
@@ -4122,12 +4707,12 @@ function AuthProvider({
4122
4707
  }
4123
4708
  resolvePending({ approved: true });
4124
4709
  }, [signBusy, password, resolvePending]);
4125
- const markPendingSignNeedsPassword = useCallback(() => {
4710
+ const markPendingSignPasswordState = useCallback((enabled) => {
4126
4711
  const entry = pendingSignRef.current;
4127
4712
  if (!entry) return;
4128
4713
  const next = {
4129
4714
  ...entry,
4130
- request: { ...entry.request, passwordEnabled: true }
4715
+ request: { ...entry.request, passwordEnabled: enabled, authError: void 0 }
4131
4716
  };
4132
4717
  pendingSignRef.current = next;
4133
4718
  setPendingSign(next);
@@ -4149,23 +4734,45 @@ function AuthProvider({
4149
4734
  if (signBusy) return;
4150
4735
  resolvePending(false);
4151
4736
  },
4152
- onOpenSetPassword: openPasswordSettings
4737
+ onOpenSetPassword: () => openPasswordSettings("set"),
4738
+ onOpenResetPassword: () => openPasswordSettings("reset")
4153
4739
  };
4154
4740
  const onSubmitSet = useCallback(
4155
- async (pw, currentPassword) => {
4741
+ async (pw, currentPassword, recoveryBind) => {
4156
4742
  setPasswordBusy(true);
4157
4743
  setPasswordError(null);
4158
4744
  try {
4159
- await setPassword(pw, currentPassword);
4745
+ await setPassword(pw, currentPassword, recoveryBind);
4746
+ setRecoveryBindSent(null);
4160
4747
  setPasswordSettingsOpen(false);
4161
- if (pendingSignRef.current) markPendingSignNeedsPassword();
4748
+ if (pendingSignRef.current) markPendingSignPasswordState(true);
4162
4749
  } catch (e) {
4163
4750
  setPasswordError(formatAuthError(e, labels));
4164
4751
  } finally {
4165
4752
  setPasswordBusy(false);
4166
4753
  }
4167
4754
  },
4168
- [setPassword, markPendingSignNeedsPassword, labels]
4755
+ [setPassword, markPendingSignPasswordState, labels]
4756
+ );
4757
+ const onRequestRecoveryEmailBind = useCallback(
4758
+ async (email) => {
4759
+ setSendingRecoveryBindCode(true);
4760
+ setPasswordError(null);
4761
+ try {
4762
+ const out = await requestRecoveryEmailBind(email);
4763
+ setRecoveryBindSent({
4764
+ channel: "email",
4765
+ maskedTarget: out.maskedTarget,
4766
+ cooldownSec: out.cooldownSec,
4767
+ sentAt: Date.now()
4768
+ });
4769
+ } catch (e) {
4770
+ setPasswordError(formatAuthError(e, labels));
4771
+ } finally {
4772
+ setSendingRecoveryBindCode(false);
4773
+ }
4774
+ },
4775
+ [requestRecoveryEmailBind, labels]
4169
4776
  );
4170
4777
  const onSubmitClear = useCallback(
4171
4778
  async (pw) => {
@@ -4174,22 +4781,69 @@ function AuthProvider({
4174
4781
  try {
4175
4782
  await clearPassword(pw);
4176
4783
  setPasswordSettingsOpen(false);
4784
+ if (pendingSignRef.current) markPendingSignPasswordState(false);
4785
+ } catch (e) {
4786
+ setPasswordError(formatAuthError(e, labels));
4787
+ } finally {
4788
+ setPasswordBusy(false);
4789
+ }
4790
+ },
4791
+ [clearPassword, markPendingSignPasswordState, labels]
4792
+ );
4793
+ const onRequestResetCode = useCallback(
4794
+ async (channel) => {
4795
+ setSendingResetCode(true);
4796
+ setPasswordError(null);
4797
+ try {
4798
+ const out = await requestPasswordReset(channel);
4799
+ setResetSent({
4800
+ channel: out.channel,
4801
+ maskedTarget: out.maskedTarget,
4802
+ cooldownSec: out.cooldownSec,
4803
+ sentAt: Date.now()
4804
+ });
4805
+ } catch (e) {
4806
+ setPasswordError(formatAuthError(e, labels));
4807
+ } finally {
4808
+ setSendingResetCode(false);
4809
+ }
4810
+ },
4811
+ [requestPasswordReset, labels]
4812
+ );
4813
+ const onSubmitReset = useCallback(
4814
+ async (code, newPassword) => {
4815
+ setPasswordBusy(true);
4816
+ setPasswordError(null);
4817
+ try {
4818
+ const out = await confirmPasswordReset(code, newPassword);
4819
+ setResetSent(null);
4820
+ setPasswordSettingsOpen(false);
4821
+ if (pendingSignRef.current) markPendingSignPasswordState(out.passwordEnabled);
4177
4822
  } catch (e) {
4178
4823
  setPasswordError(formatAuthError(e, labels));
4179
4824
  } finally {
4180
4825
  setPasswordBusy(false);
4181
4826
  }
4182
4827
  },
4183
- [clearPassword, labels]
4828
+ [confirmPasswordReset, markPendingSignPasswordState, labels]
4184
4829
  );
4185
4830
  const passwordProps = {
4186
4831
  open: passwordSettingsOpen,
4187
4832
  passwordEnabled,
4833
+ initialMode: passwordInitialMode,
4834
+ recovery: user?.recovery ?? null,
4188
4835
  labels,
4189
4836
  busy: passwordBusy,
4837
+ sendingResetCode,
4838
+ resetSent,
4839
+ sendingRecoveryBindCode,
4840
+ recoveryBindSent,
4190
4841
  error: passwordError,
4191
4842
  onSubmitSet,
4192
4843
  onSubmitClear,
4844
+ onRequestResetCode,
4845
+ onSubmitReset,
4846
+ onRequestRecoveryEmailBind,
4193
4847
  onClose: closePasswordSettings
4194
4848
  };
4195
4849
  const value = useMemo(
@@ -4199,17 +4853,23 @@ function AuthProvider({
4199
4853
  address,
4200
4854
  user,
4201
4855
  passwordEnabled,
4856
+ passwordVersion,
4202
4857
  login,
4203
4858
  loginTelegramMiniApp,
4204
4859
  logout,
4205
4860
  markActive,
4206
4861
  restoreIfNeeded,
4862
+ restoreSession,
4207
4863
  completeOAuthFromHash,
4208
4864
  takeOAuthReturnPath,
4209
4865
  getProvider,
4210
4866
  getConnectorShim,
4211
4867
  setPassword,
4212
4868
  clearPassword,
4869
+ requestPasswordReset,
4870
+ confirmPasswordReset,
4871
+ requestRecoveryEmailBind,
4872
+ confirmRecoveryEmailBind,
4213
4873
  openPasswordSettings,
4214
4874
  closePasswordSettings,
4215
4875
  client,
@@ -4223,17 +4883,23 @@ function AuthProvider({
4223
4883
  address,
4224
4884
  user,
4225
4885
  passwordEnabled,
4886
+ passwordVersion,
4226
4887
  login,
4227
4888
  loginTelegramMiniApp,
4228
4889
  logout,
4229
4890
  markActive,
4230
4891
  restoreIfNeeded,
4892
+ restoreSession,
4231
4893
  completeOAuthFromHash,
4232
4894
  takeOAuthReturnPath,
4233
4895
  getProvider,
4234
4896
  getConnectorShim,
4235
4897
  setPassword,
4236
4898
  clearPassword,
4899
+ requestPasswordReset,
4900
+ confirmPasswordReset,
4901
+ requestRecoveryEmailBind,
4902
+ confirmRecoveryEmailBind,
4237
4903
  openPasswordSettings,
4238
4904
  closePasswordSettings,
4239
4905
  client,