@seams/wallet 0.11.0 → 0.12.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.
Files changed (56) hide show
  1. package/README.md +3 -3
  2. package/dist/.build-inputs.sha256 +1 -1
  3. package/dist/esm/SeamsWeb/walletIframe/host/ui/auth-menu/AuthMenuSurface.js +130 -47
  4. package/dist/esm/sdk/{host-Bqmmy8Ts.js → host-CHQwi-Nm.js} +1 -1
  5. package/dist/{public/sdk/pendingWalletRecoveryCodeBackup-CMCOUuA-.js → esm/sdk/pendingWalletRecoveryCodeBackup-DMg5U0Fk.js} +1 -1
  6. package/dist/{public/sdk/recovery-entrypoint-QxTiyx-o.js → esm/sdk/recovery-entrypoint-EHY_b7Z-.js} +1 -1
  7. package/dist/{public/sdk/registration-eyzHqLHi.js → esm/sdk/registration-CQxxUt5s.js} +1 -1
  8. package/dist/esm/sdk/runtime-auth-DtpRz88X.js +1 -0
  9. package/dist/esm/sdk/{runtime-device-link-CHsqrEQ9.js → runtime-device-link-DXjabXJb.js} +1 -1
  10. package/dist/esm/sdk/{runtime-ecdsa-tempo-MgmnU9g-.js → runtime-ecdsa-tempo-DlKMIbyP.js} +1 -1
  11. package/dist/esm/sdk/{runtime-email-otp-Cj96n102.js → runtime-email-otp-BBPghU2G.js} +1 -1
  12. package/dist/esm/sdk/{runtime-export-mcwZRxKk.js → runtime-export-pw-xJL8o.js} +1 -1
  13. package/dist/esm/sdk/{runtime-near-BMdTtu7D.js → runtime-near-B-vYxGjl.js} +1 -1
  14. package/dist/esm/sdk/{runtime-preferences-CBlhE8bX.js → runtime-preferences-D-hY0RfC.js} +1 -1
  15. package/dist/esm/sdk/{runtime-recovery-mJp3MLeG.js → runtime-recovery-Vg1ND2nl.js} +1 -1
  16. package/dist/esm/sdk/{runtime-recovery-codes-B1gixZsp.js → runtime-recovery-codes-rLR4Guy4.js} +1 -1
  17. package/dist/esm/sdk/{shared-8Qe7Nxgg.js → shared-6bpRPbcM.js} +1 -1
  18. package/dist/esm/sdk/wallet-iframe-host-ecdsa.js +1 -1
  19. package/dist/esm/sdk/wallet-iframe-host-full.js +1 -1
  20. package/dist/esm/sdk/wallet-iframe-host-near.js +1 -1
  21. package/dist/esm/sdk/wallet-iframe-host-runtime.js +1 -1
  22. package/dist/esm/sdk/{wallet-recovery-D7ywcIHw.js → wallet-recovery-LMtGiEL3.js} +1 -1
  23. package/dist/esm/sdk/wallet-ui.css +1 -1
  24. package/dist/esm/sdk/{walletCustodyEcdsaContinuity-_IKoCUBO.js → walletCustodyEcdsaContinuity-D-gYxv6e.js} +1 -1
  25. package/dist/esm/sdk/{walletRecoveryCommit-DDPa1rAJ.js → walletRecoveryCommit-BYRC_2li.js} +1 -1
  26. package/dist/public/headers.manifest.json +1 -1
  27. package/dist/public/sdk/{host-Bqmmy8Ts.js → host-CHQwi-Nm.js} +1 -1
  28. package/dist/{esm/sdk/pendingWalletRecoveryCodeBackup-CMCOUuA-.js → public/sdk/pendingWalletRecoveryCodeBackup-DMg5U0Fk.js} +1 -1
  29. package/dist/{esm/sdk/recovery-entrypoint-QxTiyx-o.js → public/sdk/recovery-entrypoint-EHY_b7Z-.js} +1 -1
  30. package/dist/{esm/sdk/registration-eyzHqLHi.js → public/sdk/registration-CQxxUt5s.js} +1 -1
  31. package/dist/public/sdk/runtime-auth-DtpRz88X.js +1 -0
  32. package/dist/public/sdk/{runtime-device-link-CHsqrEQ9.js → runtime-device-link-DXjabXJb.js} +1 -1
  33. package/dist/public/sdk/{runtime-ecdsa-tempo-MgmnU9g-.js → runtime-ecdsa-tempo-DlKMIbyP.js} +1 -1
  34. package/dist/public/sdk/{runtime-email-otp-Cj96n102.js → runtime-email-otp-BBPghU2G.js} +1 -1
  35. package/dist/public/sdk/{runtime-export-mcwZRxKk.js → runtime-export-pw-xJL8o.js} +1 -1
  36. package/dist/public/sdk/{runtime-near-BMdTtu7D.js → runtime-near-B-vYxGjl.js} +1 -1
  37. package/dist/public/sdk/{runtime-preferences-CBlhE8bX.js → runtime-preferences-D-hY0RfC.js} +1 -1
  38. package/dist/public/sdk/{runtime-recovery-mJp3MLeG.js → runtime-recovery-Vg1ND2nl.js} +1 -1
  39. package/dist/public/sdk/{runtime-recovery-codes-B1gixZsp.js → runtime-recovery-codes-rLR4Guy4.js} +1 -1
  40. package/dist/public/sdk/{shared-8Qe7Nxgg.js → shared-6bpRPbcM.js} +1 -1
  41. package/dist/public/sdk/wallet-iframe-host-ecdsa.js +1 -1
  42. package/dist/public/sdk/wallet-iframe-host-full.js +1 -1
  43. package/dist/public/sdk/wallet-iframe-host-near.js +1 -1
  44. package/dist/public/sdk/wallet-iframe-host-runtime.js +1 -1
  45. package/dist/public/sdk/{wallet-recovery-D7ywcIHw.js → wallet-recovery-LMtGiEL3.js} +1 -1
  46. package/dist/public/sdk/wallet-ui.css +1 -1
  47. package/dist/public/sdk/{walletCustodyEcdsaContinuity-_IKoCUBO.js → walletCustodyEcdsaContinuity-D-gYxv6e.js} +1 -1
  48. package/dist/public/sdk/{walletRecoveryCommit-DDPa1rAJ.js → walletRecoveryCommit-BYRC_2li.js} +1 -1
  49. package/dist/public/wallet-assets.manifest.json +38 -38
  50. package/dist/public/wallet-service/index.html +4 -4
  51. package/dist/types/wallet/src/SeamsWeb/walletIframe/host/auth-menu/domain.d.ts +7 -3
  52. package/dist/types/wallet/src/SeamsWeb/walletIframe/host/auth-menu/session.d.ts +3 -1
  53. package/dist/types/wallet/src/SeamsWeb/walletIframe/host/ui/auth-menu/AuthMenuSurface.d.ts +8 -5
  54. package/package.json +1 -3
  55. package/dist/esm/sdk/runtime-auth-CbveTM2_.js +0 -1
  56. package/dist/public/sdk/runtime-auth-CbveTM2_.js +0 -1
package/README.md CHANGED
@@ -1,18 +1,18 @@
1
1
  # Seams Wallet SDK
2
2
 
3
- `@seams/wallet` **0.11.0** provides browser wallet lifecycle, NEAR and EVM-family
3
+ `@seams/wallet` **0.12.0** provides browser wallet lifecycle, NEAR and EVM-family
4
4
  threshold signing, React components, and hosted wallet runtime assets.
5
5
 
6
6
  ## Install
7
7
 
8
8
  ```sh
9
- pnpm add @seams/wallet@0.11.0
9
+ pnpm add @seams/wallet@0.12.0
10
10
  ```
11
11
 
12
12
  React integrations support React 18 and 19. Import the provider and UI from
13
13
  `@seams/wallet/react` and its stylesheet from `@seams/wallet/react/styles`.
14
14
  Keep the application package, wallet-origin assets, and
15
- `@seams/wallet-server@0.11.0` on the matching release.
15
+ `@seams/wallet-server@0.12.0` on the matching release.
16
16
 
17
17
  ## Next release migration (unreleased)
18
18
 
@@ -1 +1 @@
1
- 6d2e6b22efe3f00372c471ea3e8fa79ef5f85a847e71a1b1fffffb303b5d669f
1
+ cac337f5d60ac07e7f5ca7219b430e7f4a2cf19050cd38956b352906687b6759
@@ -1,4 +1,5 @@
1
1
  import { isLinkedDeviceTargetEmailAddressV1 } from "../../../../../core/types/linkDevice.js";
2
+ import { EMAIL_OTP_RECOVERY_KEY_ALPHABET } from "../../../../../shared-ts/src/utils/emailOtpRecoveryKey.js";
2
3
  import "../../../../../shared-ts/src/wallet-recovery/recoveryCodes.js";
3
4
  import { demoEmailOtpCodeFromDelivery } from "../../../../../core/signingEngine/session/emailOtp/challengeDelivery.js";
4
5
  import { isAuthMenuActionReady, isAuthMenuGoogleActionReady, isAuthMenuLoadingStatus, isAuthMenuReady, resolveAuthMenuLoginAccount } from "../../auth-menu/domain.js";
@@ -23,20 +24,38 @@ const AUTH_MENU_ACCOUNT_LIST_ID = "seams-auth-menu-account-list";
23
24
  function otpCodeDigits(code, length = 6) {
24
25
  return code.padEnd(length, " ").slice(0, length).split("");
25
26
  }
27
+ const RECOVERY_CODE_CHARACTERS = new Set(EMAIL_OTP_RECOVERY_KEY_ALPHABET);
26
28
  function recoveryInputCharacters(code) {
27
- return code.replace(/[\s\-\u2010-\u2015\u2212]/g, "").toUpperCase();
29
+ let characters = "";
30
+ for (const character of code.toUpperCase()) {
31
+ const read = character === "O" ? "0" : character === "I" || character === "L" ? "1" : character;
32
+ if (RECOVERY_CODE_CHARACTERS.has(read)) characters += read;
33
+ }
34
+ return characters;
28
35
  }
29
- function recoveryCodeGroups(digits) {
36
+ function renderRecoveryCodeGroups(code, caret) {
30
37
  const groups = [];
31
- for (let index = 0; index < digits.length; index += 4) groups.push(digits.slice(index, index + 4));
38
+ for (let start = 0; start < 32; start += 4) {
39
+ const end = start + 4;
40
+ const slots = [];
41
+ for (let index = start; index < end; index += 1) {
42
+ const character = code[index] ?? "";
43
+ const classes = ["seams-otp-slot"];
44
+ if (character) classes.push("is-filled");
45
+ if (index === caret) classes.push("is-caret");
46
+ slots.push(/* @__PURE__ */ jsx("span", {
47
+ class: classes.join(" "),
48
+ children: character
49
+ }, index));
50
+ }
51
+ const active = caret !== null && caret >= start && caret < end;
52
+ groups.push(/* @__PURE__ */ jsx("div", {
53
+ class: `seams-recovery-code-group ${active ? "is-active" : ""}`,
54
+ children: slots
55
+ }, start));
56
+ }
32
57
  return groups;
33
58
  }
34
- function renderRecoveryCodeGroup(digits, index) {
35
- return /* @__PURE__ */ jsx("div", {
36
- class: "seams-recovery-code-group",
37
- children: digits.map(renderOtpCodeDigit)
38
- }, index);
39
- }
40
59
  function renderOtpCodeDigit(digit) {
41
60
  return /* @__PURE__ */ jsx(Fragment$1, { children: /* @__PURE__ */ jsx("span", {
42
61
  class: `seams-otp-slot ${digit.trim() ? "is-filled" : ""}`,
@@ -54,6 +73,10 @@ function recoveryAnnouncement(viewModel) {
54
73
  if (viewModel.stage === "sign_in_ready") return "Wallet recovered. Unlock it to continue.";
55
74
  return "";
56
75
  }
76
+ function recoveryBackLabel(viewModel) {
77
+ if (viewModel.kind !== "recovery") return "Back";
78
+ return viewModel.stage === "choose_method" ? "Back to recovery code" : "Back to unlock wallet";
79
+ }
57
80
  function recoveryNavigationLocked(viewModel) {
58
81
  return viewModel.kind === "recovery" && viewModel.stage === "finalizing";
59
82
  }
@@ -194,7 +217,10 @@ const ACCOUNT_MENU_EXIT_MS = 160;
194
217
  var AuthMenuSurface = class extends Component {
195
218
  constructor(..._args) {
196
219
  super(..._args);
197
- this.state = { accountMenu: "closed" };
220
+ this.state = {
221
+ accountMenu: "closed",
222
+ recoveryCaret: null
223
+ };
198
224
  this.accountMenuExitTimer = null;
199
225
  this.accountMenuChoice = null;
200
226
  this.previouslyFocusedElement = null;
@@ -367,24 +393,30 @@ var AuthMenuSurface = class extends Component {
367
393
  };
368
394
  this.onRecoveryCodeInput = (event) => {
369
395
  if (!(event.currentTarget instanceof HTMLInputElement)) return;
370
- const viewModel = this.viewModel;
371
- if (viewModel.kind !== "recovery") return;
396
+ if (this.viewModel.kind !== "recovery") return;
372
397
  const input = event.currentTarget;
373
- const length = viewModel.recoveryCodeSlotCount ?? 32;
374
398
  const raw = input.value;
375
399
  const caret = recoveryInputCharacters(raw.slice(0, input.selectionStart ?? raw.length)).length;
376
- const code = recoveryInputCharacters(raw).slice(0, length);
400
+ const code = recoveryInputCharacters(raw).slice(0, 32);
377
401
  if (input.value !== code) {
378
402
  input.value = code;
379
403
  input.setSelectionRange(Math.min(caret, code.length), Math.min(caret, code.length));
380
404
  }
405
+ this.syncRecoveryCaret(input);
381
406
  this.emitIntent({
382
407
  kind: "recovery_code_changed",
383
408
  recoveryCode: code
384
409
  });
385
410
  };
411
+ this.onRecoveryCaretMove = (event) => {
412
+ if (event.currentTarget instanceof HTMLInputElement) this.syncRecoveryCaret(event.currentTarget);
413
+ };
414
+ this.onRecoveryCodeBlur = () => {
415
+ this.setState({ recoveryCaret: null });
416
+ };
386
417
  this.onRecoverySubmit = (event) => {
387
418
  event.preventDefault();
419
+ this.emitIntent({ kind: "recovery_code_submit" });
388
420
  };
389
421
  this.onRecoveryPasskeySelected = () => {
390
422
  this.emitIntent({ kind: "recovery_passkey_selected" });
@@ -524,6 +556,10 @@ var AuthMenuSurface = class extends Component {
524
556
  if (previous?.kind !== "recovery" || previous.stage !== "enter_code") this.props.element.querySelector("[data-recovery-code]")?.focus();
525
557
  return;
526
558
  }
559
+ if (current.stage === "choose_method") {
560
+ if (stageChanged) this.props.element.querySelector("[data-recovery-target]")?.focus();
561
+ return;
562
+ }
527
563
  const becameRecoverable = current.status.kind === "recoverable" && previous?.kind === "recovery" && previous.status.kind !== "recoverable";
528
564
  if ((stageChanged || becameRecoverable) && (current.stage === "passkey_ready" || current.stage === "finalizing" || current.stage === "sign_in_ready")) this.props.element.querySelector("[data-auth-menu-primary]")?.focus();
529
565
  }
@@ -557,6 +593,11 @@ var AuthMenuSurface = class extends Component {
557
593
  focusableElements() {
558
594
  return Array.from(this.props.element.querySelectorAll("button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), a[href], [tabindex]:not([tabindex=\"-1\"])"));
559
595
  }
596
+ syncRecoveryCaret(input) {
597
+ const caret = Math.min(input.selectionStart ?? input.value.length, 31);
598
+ const recoveryCaret = input.value.length < 32 ? caret : null;
599
+ if (recoveryCaret !== this.state.recoveryCaret) this.setState({ recoveryCaret });
600
+ }
560
601
  emitIntent(intent) {
561
602
  this.props.onIntent(intent);
562
603
  }
@@ -595,7 +636,7 @@ var AuthMenuSurface = class extends Component {
595
636
  /* @__PURE__ */ jsx("button", {
596
637
  class: `seams-back-button ${loading || linkDevice || otpPrompt || registrationPrompt || recovery ? "is-visible" : ""}`,
597
638
  type: "button",
598
- "aria-label": recovery ? "Back to unlock wallet" : "Back",
639
+ "aria-label": recoveryBackLabel(viewModel),
599
640
  "data-auth-menu-close": true,
600
641
  disabled: recoveryNavigationLocked(viewModel),
601
642
  onClick: this.onBackClick,
@@ -856,9 +897,8 @@ var AuthMenuSurface = class extends Component {
856
897
  }
857
898
  renderRecovery(viewModel) {
858
899
  if (viewModel.stage === "enter_code") {
859
- const codeLength = viewModel.recoveryCodeSlotCount ?? 32;
860
- const code = recoveryInputCharacters(viewModel.recoveryCode).slice(0, codeLength);
861
- const digits = otpCodeDigits(code, codeLength);
900
+ const code = recoveryInputCharacters(viewModel.recoveryCode).slice(0, 32);
901
+ const complete = code.length === 32;
862
902
  const statusMessage = viewModel.status.kind === "recoverable" ? viewModel.status.message : "";
863
903
  const feedbackMessage = viewModel.recoveryCodeError ?? statusMessage;
864
904
  const feedbackIsError = feedbackMessage.length > 0;
@@ -877,10 +917,21 @@ var AuthMenuSurface = class extends Component {
877
917
  onSubmit: this.onRecoverySubmit,
878
918
  children: [/* @__PURE__ */ jsxs("div", {
879
919
  class: "seams-recovery-field",
880
- children: [/* @__PURE__ */ jsx("label", {
881
- class: "seams-field-label",
882
- for: "seams-recovery-code",
883
- children: "Recovery code"
920
+ children: [/* @__PURE__ */ jsxs("div", {
921
+ class: "seams-recovery-field-header",
922
+ children: [/* @__PURE__ */ jsx("label", {
923
+ class: "seams-field-label",
924
+ for: "seams-recovery-code",
925
+ children: "Recovery code"
926
+ }), /* @__PURE__ */ jsxs("span", {
927
+ id: "seams-recovery-code-count",
928
+ class: "seams-recovery-code-count",
929
+ children: [
930
+ code.length,
931
+ "/",
932
+ 32
933
+ ]
934
+ })]
884
935
  }), /* @__PURE__ */ jsxs("div", {
885
936
  class: "seams-otp-code-field seams-recovery-code-field",
886
937
  children: [/* @__PURE__ */ jsx("input", {
@@ -889,46 +940,78 @@ var AuthMenuSurface = class extends Component {
889
940
  "data-recovery-code": true,
890
941
  name: "recoveryCode",
891
942
  type: "text",
892
- inputmode: codeLength === 16 ? "numeric" : "text",
943
+ inputmode: "text",
893
944
  autocomplete: "off",
894
945
  autocapitalize: "characters",
895
946
  autocorrect: "off",
896
947
  spellcheck: false,
897
948
  "aria-invalid": viewModel.recoveryCodeError ? "true" : "false",
898
- "aria-describedby": viewModel.recoveryCodeError ? "seams-recovery-code-feedback" : void 0,
949
+ "aria-describedby": viewModel.recoveryCodeError ? "seams-recovery-code-feedback seams-recovery-code-count" : "seams-recovery-code-count",
899
950
  value: code,
900
- onInput: this.onRecoveryCodeInput
951
+ onInput: this.onRecoveryCodeInput,
952
+ onFocus: this.onRecoveryCaretMove,
953
+ onKeyUp: this.onRecoveryCaretMove,
954
+ onClick: this.onRecoveryCaretMove,
955
+ onBlur: this.onRecoveryCodeBlur
901
956
  }), /* @__PURE__ */ jsx("div", {
902
957
  class: "seams-otp-slots seams-recovery-code-slots",
903
958
  "aria-hidden": "true",
904
- children: recoveryCodeGroups(digits).map(renderRecoveryCodeGroup)
959
+ children: renderRecoveryCodeGroups(code, this.state.recoveryCaret)
905
960
  })]
906
961
  })]
907
- }), /* @__PURE__ */ jsxs("div", {
908
- class: "seams-secondary-actions",
909
- children: [/* @__PURE__ */ jsxs("button", {
910
- class: "seams-link-device-btn seams-auth-method-choice-btn",
911
- type: "button",
912
- "data-recovery-target": "passkey",
913
- onClick: this.onRecoveryPasskeySelected,
914
- children: [/* @__PURE__ */ jsx("span", {
915
- class: "seams-auth-method-choice-icon",
916
- children: fingerprintIcon()
917
- }), /* @__PURE__ */ jsx("span", { children: "Recover with Passkey" })]
918
- }), /* @__PURE__ */ jsxs("button", {
919
- class: "seams-link-device-btn seams-auth-method-choice-btn",
920
- type: "button",
921
- "data-recovery-target": "google_email_otp",
922
- onClick: this.onRecoveryGoogleSelected,
923
- children: [/* @__PURE__ */ jsx("span", {
924
- class: "seams-auth-method-choice-icon",
925
- children: googleIcon()
926
- }), /* @__PURE__ */ jsx("span", { children: "Recover with Google" })]
927
- })]
962
+ }), /* @__PURE__ */ jsx("button", {
963
+ class: "seams-auth-method-btn seams-auth-method-btn-primary",
964
+ type: "submit",
965
+ "data-auth-menu-primary": true,
966
+ "data-recovery-continue": true,
967
+ disabled: !complete,
968
+ children: "Continue"
928
969
  })]
929
970
  })
930
971
  ] });
931
972
  }
973
+ if (viewModel.stage === "choose_method" || viewModel.stage === "preparing") {
974
+ const busyTarget = viewModel.stage === "preparing" ? viewModel.target.kind : null;
975
+ const statusMessage = viewModel.status.kind === "recoverable" ? viewModel.status.message : viewModel.status.kind === "busy" ? viewModel.status.headline : "";
976
+ const googleEnabled = viewModel.enabledExternalProviders?.includes("google") ?? false;
977
+ return /* @__PURE__ */ jsxs(Fragment$1, { children: [
978
+ this.renderHeader(viewModel),
979
+ /* @__PURE__ */ jsx("p", {
980
+ class: `seams-recovery-status ${viewModel.status.kind === "recoverable" ? "seams-recovery-error" : ""}`,
981
+ "aria-hidden": "true",
982
+ children: statusMessage
983
+ }),
984
+ /* @__PURE__ */ jsxs("div", {
985
+ class: "seams-auth-methods seams-recovery-methods",
986
+ children: [/* @__PURE__ */ jsxs("button", {
987
+ class: "seams-auth-method-btn seams-auth-method-btn-primary",
988
+ type: "button",
989
+ "data-auth-menu-primary": true,
990
+ "data-recovery-target": "passkey",
991
+ disabled: busyTarget !== null,
992
+ onClick: this.onRecoveryPasskeySelected,
993
+ children: [busyTarget === "passkey" ? /* @__PURE__ */ jsx("span", {
994
+ class: "seams-spinner",
995
+ "aria-hidden": "true"
996
+ }) : fingerprintIcon(), /* @__PURE__ */ jsx("span", { children: "Create a passkey" })]
997
+ }), googleEnabled ? /* @__PURE__ */ jsxs("button", {
998
+ class: "seams-auth-method-btn",
999
+ type: "button",
1000
+ "data-recovery-target": "google_email_otp",
1001
+ disabled: busyTarget !== null,
1002
+ onClick: this.onRecoveryGoogleSelected,
1003
+ children: [busyTarget === "google_email_otp" ? /* @__PURE__ */ jsx("span", {
1004
+ class: "seams-spinner",
1005
+ "aria-hidden": "true"
1006
+ }) : googleIcon(), /* @__PURE__ */ jsx("span", { children: "Continue with Google" })]
1007
+ }) : null]
1008
+ }),
1009
+ /* @__PURE__ */ jsx("p", {
1010
+ class: "seams-recovery-method-note",
1011
+ children: "This adds a new sign-in method to your wallet."
1012
+ })
1013
+ ] });
1014
+ }
932
1015
  if (viewModel.stage === "email_code_required") {
933
1016
  const digits = otpCodeDigits(viewModel.otpCode);
934
1017
  const canSubmit = /^\d{6}$/.test(viewModel.otpCode) && viewModel.status.kind !== "busy";
@@ -1 +1 @@
1
- import{C as e,S as t}from"./chains-C_X_fNuS.js";import{n}from"./walletRegistrationSetupPrewarm-B9kpnrbK.js";import{_ as r,c as i,f as a,g as o,h as s,l as c,m as l,n as u,o as d,t as f,v as p}from"./messages-DgJlG9NU.js";import{a as m,c as h,i as g,l as _,n as v,o as y,s as b,t as x,u as S}from"./transactionReviewAdmission-CIvR4W5_.js";import{t as C}from"./events-1dzC4Ocx.js";import{t as w}from"./walletIframeIdentity-Cz82I_Uh.js";import{t as T}from"./errors-DIWY1KR9.js";function E(){let e=globalThis;e.global===void 0&&(e.global=globalThis),!e.process||typeof e.process!=`object`?e.process={env:{}}:(!e.process.env||typeof e.process.env!=`object`)&&(e.process.env={})}function D(){E(),window.location.origin===`null`&&(window.parent?.postMessage({type:`SERVICE_HOST_DEBUG_ORIGIN`,origin:window.location.origin,href:window.location.href},`*`),console.warn(`[WalletHost] iframe is running with opaque (null) origin. Check COEP/CORP headers and ensure navigation succeeded.`)),O(),window.parent?.postMessage({type:`SERVICE_HOST_BOOTED`},`*`),window.parent?.postMessage({type:`SERVICE_HOST_DEBUG_ORIGIN`,origin:window.location.origin,href:window.location.href},`*`);let e=new URL(import.meta.url),t=e.searchParams.get(`v`);t&&l(t);let n=new URL(`.`,e).toString(),r=n.endsWith(`/`)?n:n+`/`;a()||s(r)}function O(){let e=()=>{let e=document;e.documentElement.classList.add(`seams-transparent`),e.body?.classList.add(`seams-transparent`),e.documentElement.classList.remove(`dark`),e.body?.classList.remove(`dark`)};document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,()=>e(),{once:!0}):e(),window.addEventListener(`load`,()=>e(),{once:!0})}const k={};let A=null,j=null;function M(e){return e.type===`PM_ACKNOWLEDGE_WALLET_RECOVERY_CODE_BACKUP`?(A??=import(`./runtime-recovery-codes-B1gixZsp.js`),A):(k[e.kind]??=P(e.kind),k[e.kind])}async function N(){A??=import(`./runtime-recovery-codes-B1gixZsp.js`),j??=Promise.all([A,import(`./mountRecoveryCodeBackupSurface-D1G-iCPI.js`)]).then(()=>void 0),await j}function P(e){switch(e){case`auth`:return import(`./runtime-auth-CbveTM2_.js`);case`near`:return import(`./runtime-near-BMdTtu7D.js`);case`ecdsa`:return import(`./runtime-ecdsa-tempo-MgmnU9g-.js`);case`email_otp`:return import(`./runtime-email-otp-Cj96n102.js`);case`recovery`:return import(`./runtime-recovery-mJp3MLeG.js`);case`export`:return import(`./runtime-export-mcwZRxKk.js`);case`device_link`:return import(`./runtime-device-link-CHsqrEQ9.js`);case`preferences`:return import(`./runtime-preferences-CBlhE8bX.js`)}return F(e)}function F(e){throw Error(`Unhandled wallet host runtime route: ${String(e)}`)}function I(e){throw Error(`Unhandled wallet host route: ${String(e)}`)}function L(e,t){if(e===null)throw Error(`Invalid ${t} payload`);return e}function R(e){try{return w(e)}catch{throw Error(`Hosted auth-menu request requires a non-empty requestId`)}}function z(e){switch(e.type){case`PM_ACTIVATE_TRANSACTION_REVIEW`:case`PING`:case`PM_SET_CONFIG`:case`PM_CANCEL`:case`PM_SET_TRANSACTION_VIEW`:case`PM_TRANSACTION_BROADCAST_STARTED`:return{kind:`boot`,type:e.type,request:e};case`PM_REGISTER_WALLET`:case`PM_ADD_WALLET_SIGNER`:case`PM_ADD_PASSKEY`:case`PM_ADD_EMAIL_OTP`:case`PM_REVOKE_AUTH_METHOD`:case`PM_GET_NEAR_PROVISIONING_STATE`:case`PM_SIGN_TX_WITH_ACTIONS`:case`PM_SIGN_AND_SEND_TX`:case`PM_SEND_TRANSACTION`:case`PM_SIGN_DELEGATE_ACTION`:case`PM_SIGN_NEP413`:return{kind:`near`,type:e.type,request:e};case`PM_OPEN_AUTH_MENU`:{let t=R(e.requestId);return{kind:`auth`,type:e.type,request:{...e,requestId:t,payload:L(c(e.payload),`hosted auth-menu open`)}}}case`PM_CANCEL_AUTH_MENU`:{let t=R(e.requestId);return{kind:`auth`,type:e.type,request:{...e,requestId:t,payload:L(d(e.payload),`hosted auth-menu cancellation`)}}}case`PM_RESOLVE_AUTH_MENU_EXTERNAL_AUTH`:{let t=R(e.requestId);return{kind:`auth`,type:e.type,request:{...e,requestId:t,payload:L(i(e.payload),`hosted auth-menu external-auth resolution`)}}}case`PM_UNLOCK`:case`PM_LOCK`:case`PM_LOCK_EXACT_WALLET_SESSION`:case`PM_GET_LAST_WALLET_MOVE_REQUEST`:case`PM_MOVE_WALLET`:case`PM_GET_WALLET_MOVE`:case`PM_GET_WALLET_PLACEMENT`:case`PM_GET_WALLET_SESSION`:case`PM_GET_EXACT_WALLET_SESSION_STATE`:case`PM_GET_RECENT_UNLOCKS`:return{kind:`auth`,type:e.type,request:e};case`PM_SIGN_TEMPO`:case`PM_REPORT_TEMPO_BROADCAST_ACCEPTED`:case`PM_REPORT_TEMPO_BROADCAST_REJECTED`:case`PM_REPORT_TEMPO_FINALIZED`:case`PM_REPORT_TEMPO_DROPPED_OR_REPLACED`:case`PM_RECONCILE_TEMPO_NONCE_LANE`:return{kind:`ecdsa`,type:e.type,request:e};case`PM_REDEEM_HOSTED_WALLET_SEAMS_SESSION`:case`PM_REQUEST_EMAIL_OTP_CHALLENGE`:case`PM_BEGIN_GOOGLE_EMAIL_OTP_WALLET_AUTH`:case`PM_GOOGLE_EMAIL_OTP_WALLET_AUTH_RESEND`:case`PM_GOOGLE_EMAIL_OTP_WALLET_AUTH_REROLL_WALLET_ID`:case`PM_GOOGLE_EMAIL_OTP_WALLET_AUTH_SUBMIT`:case`PM_GOOGLE_EMAIL_OTP_WALLET_AUTH_COMPLETE_REGISTRATION`:case`PM_GOOGLE_EMAIL_OTP_WALLET_AUTH_CANCEL`:case`PM_GET_WALLET_RECOVERY_CODE_STATUS`:case`PM_ACKNOWLEDGE_WALLET_RECOVERY_CODE_BACKUP`:case`PM_ROTATE_WALLET_RECOVERY_CODES`:case`PM_REQUEST_WALLET_CUSTODY_EMAIL_OTP_CHALLENGE`:return{kind:`email_otp`,type:e.type,request:e};case`PM_SYNC_ACCOUNT_FLOW`:return{kind:`recovery`,type:e.type,request:e};case`PM_RESOLVE_EXACT_KEY_EXPORT_LANE`:case`PM_EXPORT_KEYPAIR_UI`:return{kind:`export`,type:e.type,request:e};case`PM_HAS_PASSKEY`:case`PM_LIST_LINKED_DEVICES`:case`PM_REVOKE_LINKED_DEVICE`:case`PM_SCAN_AND_LINK_DEVICE`:case`PM_START_DEVICE2_LINKING_FLOW`:case`PM_DEVICE_LINK_TARGET_FACTOR_ACTION`:case`PM_DEVICE_LINK_EMAIL_OTP_BASE_FACTOR_ACTION`:case`PM_CANCEL_DEVICE_LINKING`:return{kind:`device_link`,type:e.type,request:e};case`PM_SET_CONFIRM_BEHAVIOR`:case`PM_SET_CONFIRMATION_CONFIG`:case`PM_GET_CONFIRMATION_CONFIG`:return{kind:`preferences`,type:e.type,request:e}}return I(e)}function B(e){return e.kind!==`boot`}let V=!1;const H=[{selector:`.seams-auth-menu-surface`,cancellationKind:`native_cancel`},{selector:`.seams-confirmation-surface`,cancellationKind:`native_cancel`},{selector:`.seams-export-surface`,cancellationKind:`wallet_iframe_cancel`},{selector:`[data-seams-wallet-recovery-backup-dialog]`,cancellationKind:`native_cancel`}];function U(e,t){let n=new Set(t),r=Object.keys(e);return r.length===t.length&&r.every(e=>n.has(e))}function W(t){return!e(t)||!U(t,[`type`,`payload`])||t.type!==`CONNECT`||!e(t.payload)||!U(t.payload,[`protocolVersion`])?null:typeof t.payload.protocolVersion==`string`?{type:`CONNECT`,payload:{protocolVersion:t.payload.protocolVersion}}:null}function G(e){if(e===`null`)return!0;try{let t=new URL(e);return(t.protocol===`https:`||t.protocol===`http:`)&&t.origin===e}catch{return!1}}function K(e){try{e.close()}catch{}}function q(e,t){if(t===`15.0.0`)return!1;let n={expectedProtocolVersion:u,receivedProtocolVersion:t};try{e.postMessage({type:`ERROR`,payload:{code:f,message:`Wallet iframe protocol version mismatch: expected ${u}, received ${t??`missing`}`,details:n}})}catch{}return K(e),!0}function J(e,t){return!t||t.has(e.kind)}function Y(e,t,n,r){e.executionGeneration===t&&n(r)}function X(e,t,n,r){return e.executionGeneration!==t||n(r)}function Z(e={}){if(V)return;V=!0,D(),(!e.supportedRuntimeRouteKinds||e.supportedRuntimeRouteKinds.has(`email_otp`))&&N().catch(()=>void 0);let i=new Set,a=new Set,s={parentOrigin:null,port:null,configuration:{kind:`unconfigured`},executionGeneration:0,onConfigurationChanged:null},c=e=>{try{s.port?.postMessage(e)}catch{}},l=e=>{e&&i.add(e)},d=e=>!!e&&(i.has(e)||g(e)?.cancelled===!0),f=e=>{e&&i.delete(e)},w=e=>{e&&c({type:`ERROR`,requestId:e,payload:{code:`cancelled`,message:`Request cancelled`}})},E=e=>!e||!d(e)?!1:g(e)?.cancelled?!0:(w(e),f(e),!0),O=()=>{for(let e of H){let t=document.querySelectorAll(e.selector);for(let n of t)try{e.cancellationKind===`native_cancel`?n.dispatchEvent(new Event(`cancel`,{cancelable:!0})):n.dispatchEvent(new CustomEvent(C.TX_CONFIRMER_CANCEL,{bubbles:!0,composed:!0}))}catch{}}},k=async i=>{let u=i.data;if(!u||!t(u))return;let C=u.requestId,D=s.executionGeneration,k=Y.bind(null,s,D,c),A=null;try{if(`transactionReview`in u){if(u.type!==`PM_SIGN_AND_SEND_TX`&&u.type!==`PM_SIGN_TEMPO`)throw new m(`review_invalid_input`,`Review is unsupported for this request`);let e=h(u.transactionReview);if(e.requestId!==C)throw new m(`review_invalid_input`,`Review request identity mismatch`);let t=u.payload?.options?.confirmationConfig;if(t?.uiMode!==`modal`||t.behavior!==`requireClick`)throw new m(`review_unsupported_mode`,`Review requires modal presentation and explicit approval`);A=new x(e,u.type===`PM_SIGN_TEMPO`&&u.payload?.request.senderSignatureAlgorithm!==`secp256k1`?`credential`:`mpc`,e=>k({type:`TRANSACTION_REVIEW_STATE`,requestId:C,payload:e}),e=>k({type:`ERROR`,requestId:C,payload:{code:e instanceof m?e.code:`cancelled`,message:e.message}}))}(u.type===`PM_LOCK`||u.type===`PM_LOCK_EXACT_WALLET_SESSION`)&&v(new m(`review_identity_changed`,`The wallet session changed`));let t=z(u);if(!B(t))switch(t.type){case`PING`:c({type:`PONG`,requestId:C});return;case`PM_SET_CONFIG`:{let e=o(s.configuration,r(t.request.payload)),i=p(s.configuration.kind===`configured`?s.configuration.config:null)!==p(e.config);if(s.configuration=e,i){s.executionGeneration+=1;let t=e.config;t.registration.publishableKey&&t.registration.projectEnvironmentId&&n(t.network.relayer.url);for(let e of a)c({type:`ERROR`,requestId:e,payload:{code:`wallet_configuration_changed`,message:`Wallet configuration changed during request`}});a.clear()}s.onConfigurationChanged?.(),i&&(v(new m(`review_identity_changed`,`Wallet execution configuration changed`)),O()),c({type:`PONG`,requestId:C});return}case`PM_ACTIVATE_TRANSACTION_REVIEW`:{let e=b(t.request.payload);e&&g(e.requestId)?.activate(e);return}case`PM_CANCEL`:{let e=t.request.payload?.requestId,n=t.request.payload,r=n&&typeof n==`object`?Reflect.get(n,`transactionReview`):void 0;if(r!==void 0){let t=h(r),i=g(t.requestId);if(t.requestId===e&&i&&_(t,i.metadata)){let e=new m(S(n&&typeof n==`object`?Reflect.get(n,`reviewErrorCode`):void 0),`Reviewed request cancelled`);try{y(i.metadata.validity)}catch(t){t instanceof Error&&(e=t)}i.cancel(e)}c({type:`PONG`,requestId:C});return}let i=e?g(e):void 0;if(i){i.cancel(new m(`cancelled`,`Request cancelled`)),c({type:`PONG`,requestId:C});return}l(e),O(),e&&w(e),c({type:`PONG`,requestId:C});return}case`PM_SET_TRANSACTION_VIEW`:{let e=t.request.payload,n=e&&typeof e==`object`?Reflect.get(e,`requestId`):null,r=e&&typeof e==`object`?Reflect.get(e,`view`):null;typeof n==`string`&&(r===`toast`||r===`closed`)&&(await import(`./transaction-activity-xfeHKJoq.js`).then(e=>e.o)).setTransactionActivityView(n,r);return}case`PM_TRANSACTION_BROADCAST_STARTED`:{let e=t.request.payload,n=e&&typeof e==`object`?Reflect.get(e,`signedTransaction`):null;typeof n==`string`&&(await import(`./transaction-activity-xfeHKJoq.js`).then(e=>e.o)).transactionBroadcastStarted(n);return}}if(!J(t,e.supportedRuntimeRouteKinds)){c({type:`ERROR`,requestId:C,payload:{code:`unsupported_request`,message:`Unsupported wallet iframe request type: ${t.type}`}});return}C&&a.add(C);let i=await M(t);if(D!==s.executionGeneration)return;await i.handleWalletHostRuntimeRequest({transactionReview:A,state:s,executionGeneration:D,req:t.request,post:Y.bind(null,s,D,c),isCancelled:X.bind(null,s,D,d),respondIfCancelled:X.bind(null,s,D,E)})}catch(e){if(D!==s.executionGeneration&&u.type!==`PM_SET_CONFIG`||A?.cancelled)return;let t=await import(`./canonicalSignerErrorCode-Cz48v4oy.js`);if(D!==s.executionGeneration&&u.type!==`PM_SET_CONFIG`)return;let n=e&&typeof e==`object`&&`code`in e?e.code:void 0,r=T(e),i=t.resolveWalletBoundaryErrorCode({requestType:u.type,rawCode:n,message:r,defaultCode:`HOST_ERROR`}),a=t.resolveWalletBoundaryErrorMessage({requestType:u.type,rawCode:n,code:i,message:r}),o=t.resolveWalletBoundarySignerKind(u.type);c({type:`ERROR`,requestId:C,payload:{code:i,message:a,...t.isWalletSignerBoundaryRequestType(u.type)&&t.isCanonicalSignerSessionBoundaryCode(i)&&o?{signerKind:o}:{}}})}finally{C&&(a.delete(C),f(C)),A?.finish()}};window.addEventListener(`message`,e=>{let t=W(e.data),n=e.ports[0];if(!(!t||!n||s.port)){if(e.source!==window.parent||!G(e.origin)){K(n);return}if(!q(n,t.payload.protocolVersion)){typeof e.origin==`string`&&e.origin.length&&e.origin!==`null`&&(s.parentOrigin=e.origin),s.port=n;try{s.port.onmessage=k,s.port.start?.()}catch{}c({type:`READY`,payload:{protocolVersion:u}})}}})}try{Z()}catch(e){console.error(`[WalletHost] init failed`,e)}export{Z as t};
1
+ import{C as e,S as t}from"./chains-C_X_fNuS.js";import{n}from"./walletRegistrationSetupPrewarm-B9kpnrbK.js";import{_ as r,c as i,f as a,g as o,h as s,l as c,m as l,n as u,o as d,t as f,v as p}from"./messages-DgJlG9NU.js";import{a as m,c as h,i as g,l as _,n as v,o as y,s as b,t as x,u as S}from"./transactionReviewAdmission-CIvR4W5_.js";import{t as C}from"./events-1dzC4Ocx.js";import{t as w}from"./walletIframeIdentity-Cz82I_Uh.js";import{t as T}from"./errors-DIWY1KR9.js";function E(){let e=globalThis;e.global===void 0&&(e.global=globalThis),!e.process||typeof e.process!=`object`?e.process={env:{}}:(!e.process.env||typeof e.process.env!=`object`)&&(e.process.env={})}function D(){E(),window.location.origin===`null`&&(window.parent?.postMessage({type:`SERVICE_HOST_DEBUG_ORIGIN`,origin:window.location.origin,href:window.location.href},`*`),console.warn(`[WalletHost] iframe is running with opaque (null) origin. Check COEP/CORP headers and ensure navigation succeeded.`)),O(),window.parent?.postMessage({type:`SERVICE_HOST_BOOTED`},`*`),window.parent?.postMessage({type:`SERVICE_HOST_DEBUG_ORIGIN`,origin:window.location.origin,href:window.location.href},`*`);let e=new URL(import.meta.url),t=e.searchParams.get(`v`);t&&l(t);let n=new URL(`.`,e).toString(),r=n.endsWith(`/`)?n:n+`/`;a()||s(r)}function O(){let e=()=>{let e=document;e.documentElement.classList.add(`seams-transparent`),e.body?.classList.add(`seams-transparent`),e.documentElement.classList.remove(`dark`),e.body?.classList.remove(`dark`)};document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,()=>e(),{once:!0}):e(),window.addEventListener(`load`,()=>e(),{once:!0})}const k={};let A=null,j=null;function M(e){return e.type===`PM_ACKNOWLEDGE_WALLET_RECOVERY_CODE_BACKUP`?(A??=import(`./runtime-recovery-codes-rLR4Guy4.js`),A):(k[e.kind]??=P(e.kind),k[e.kind])}async function N(){A??=import(`./runtime-recovery-codes-rLR4Guy4.js`),j??=Promise.all([A,import(`./mountRecoveryCodeBackupSurface-D1G-iCPI.js`)]).then(()=>void 0),await j}function P(e){switch(e){case`auth`:return import(`./runtime-auth-DtpRz88X.js`);case`near`:return import(`./runtime-near-B-vYxGjl.js`);case`ecdsa`:return import(`./runtime-ecdsa-tempo-DlKMIbyP.js`);case`email_otp`:return import(`./runtime-email-otp-BBPghU2G.js`);case`recovery`:return import(`./runtime-recovery-Vg1ND2nl.js`);case`export`:return import(`./runtime-export-pw-xJL8o.js`);case`device_link`:return import(`./runtime-device-link-DXjabXJb.js`);case`preferences`:return import(`./runtime-preferences-D-hY0RfC.js`)}return F(e)}function F(e){throw Error(`Unhandled wallet host runtime route: ${String(e)}`)}function I(e){throw Error(`Unhandled wallet host route: ${String(e)}`)}function L(e,t){if(e===null)throw Error(`Invalid ${t} payload`);return e}function R(e){try{return w(e)}catch{throw Error(`Hosted auth-menu request requires a non-empty requestId`)}}function z(e){switch(e.type){case`PM_ACTIVATE_TRANSACTION_REVIEW`:case`PING`:case`PM_SET_CONFIG`:case`PM_CANCEL`:case`PM_SET_TRANSACTION_VIEW`:case`PM_TRANSACTION_BROADCAST_STARTED`:return{kind:`boot`,type:e.type,request:e};case`PM_REGISTER_WALLET`:case`PM_ADD_WALLET_SIGNER`:case`PM_ADD_PASSKEY`:case`PM_ADD_EMAIL_OTP`:case`PM_REVOKE_AUTH_METHOD`:case`PM_GET_NEAR_PROVISIONING_STATE`:case`PM_SIGN_TX_WITH_ACTIONS`:case`PM_SIGN_AND_SEND_TX`:case`PM_SEND_TRANSACTION`:case`PM_SIGN_DELEGATE_ACTION`:case`PM_SIGN_NEP413`:return{kind:`near`,type:e.type,request:e};case`PM_OPEN_AUTH_MENU`:{let t=R(e.requestId);return{kind:`auth`,type:e.type,request:{...e,requestId:t,payload:L(c(e.payload),`hosted auth-menu open`)}}}case`PM_CANCEL_AUTH_MENU`:{let t=R(e.requestId);return{kind:`auth`,type:e.type,request:{...e,requestId:t,payload:L(d(e.payload),`hosted auth-menu cancellation`)}}}case`PM_RESOLVE_AUTH_MENU_EXTERNAL_AUTH`:{let t=R(e.requestId);return{kind:`auth`,type:e.type,request:{...e,requestId:t,payload:L(i(e.payload),`hosted auth-menu external-auth resolution`)}}}case`PM_UNLOCK`:case`PM_LOCK`:case`PM_LOCK_EXACT_WALLET_SESSION`:case`PM_GET_LAST_WALLET_MOVE_REQUEST`:case`PM_MOVE_WALLET`:case`PM_GET_WALLET_MOVE`:case`PM_GET_WALLET_PLACEMENT`:case`PM_GET_WALLET_SESSION`:case`PM_GET_EXACT_WALLET_SESSION_STATE`:case`PM_GET_RECENT_UNLOCKS`:return{kind:`auth`,type:e.type,request:e};case`PM_SIGN_TEMPO`:case`PM_REPORT_TEMPO_BROADCAST_ACCEPTED`:case`PM_REPORT_TEMPO_BROADCAST_REJECTED`:case`PM_REPORT_TEMPO_FINALIZED`:case`PM_REPORT_TEMPO_DROPPED_OR_REPLACED`:case`PM_RECONCILE_TEMPO_NONCE_LANE`:return{kind:`ecdsa`,type:e.type,request:e};case`PM_REDEEM_HOSTED_WALLET_SEAMS_SESSION`:case`PM_REQUEST_EMAIL_OTP_CHALLENGE`:case`PM_BEGIN_GOOGLE_EMAIL_OTP_WALLET_AUTH`:case`PM_GOOGLE_EMAIL_OTP_WALLET_AUTH_RESEND`:case`PM_GOOGLE_EMAIL_OTP_WALLET_AUTH_REROLL_WALLET_ID`:case`PM_GOOGLE_EMAIL_OTP_WALLET_AUTH_SUBMIT`:case`PM_GOOGLE_EMAIL_OTP_WALLET_AUTH_COMPLETE_REGISTRATION`:case`PM_GOOGLE_EMAIL_OTP_WALLET_AUTH_CANCEL`:case`PM_GET_WALLET_RECOVERY_CODE_STATUS`:case`PM_ACKNOWLEDGE_WALLET_RECOVERY_CODE_BACKUP`:case`PM_ROTATE_WALLET_RECOVERY_CODES`:case`PM_REQUEST_WALLET_CUSTODY_EMAIL_OTP_CHALLENGE`:return{kind:`email_otp`,type:e.type,request:e};case`PM_SYNC_ACCOUNT_FLOW`:return{kind:`recovery`,type:e.type,request:e};case`PM_RESOLVE_EXACT_KEY_EXPORT_LANE`:case`PM_EXPORT_KEYPAIR_UI`:return{kind:`export`,type:e.type,request:e};case`PM_HAS_PASSKEY`:case`PM_LIST_LINKED_DEVICES`:case`PM_REVOKE_LINKED_DEVICE`:case`PM_SCAN_AND_LINK_DEVICE`:case`PM_START_DEVICE2_LINKING_FLOW`:case`PM_DEVICE_LINK_TARGET_FACTOR_ACTION`:case`PM_DEVICE_LINK_EMAIL_OTP_BASE_FACTOR_ACTION`:case`PM_CANCEL_DEVICE_LINKING`:return{kind:`device_link`,type:e.type,request:e};case`PM_SET_CONFIRM_BEHAVIOR`:case`PM_SET_CONFIRMATION_CONFIG`:case`PM_GET_CONFIRMATION_CONFIG`:return{kind:`preferences`,type:e.type,request:e}}return I(e)}function B(e){return e.kind!==`boot`}let V=!1;const H=[{selector:`.seams-auth-menu-surface`,cancellationKind:`native_cancel`},{selector:`.seams-confirmation-surface`,cancellationKind:`native_cancel`},{selector:`.seams-export-surface`,cancellationKind:`wallet_iframe_cancel`},{selector:`[data-seams-wallet-recovery-backup-dialog]`,cancellationKind:`native_cancel`}];function U(e,t){let n=new Set(t),r=Object.keys(e);return r.length===t.length&&r.every(e=>n.has(e))}function W(t){return!e(t)||!U(t,[`type`,`payload`])||t.type!==`CONNECT`||!e(t.payload)||!U(t.payload,[`protocolVersion`])?null:typeof t.payload.protocolVersion==`string`?{type:`CONNECT`,payload:{protocolVersion:t.payload.protocolVersion}}:null}function G(e){if(e===`null`)return!0;try{let t=new URL(e);return(t.protocol===`https:`||t.protocol===`http:`)&&t.origin===e}catch{return!1}}function K(e){try{e.close()}catch{}}function q(e,t){if(t===`15.0.0`)return!1;let n={expectedProtocolVersion:u,receivedProtocolVersion:t};try{e.postMessage({type:`ERROR`,payload:{code:f,message:`Wallet iframe protocol version mismatch: expected ${u}, received ${t??`missing`}`,details:n}})}catch{}return K(e),!0}function J(e,t){return!t||t.has(e.kind)}function Y(e,t,n,r){e.executionGeneration===t&&n(r)}function X(e,t,n,r){return e.executionGeneration!==t||n(r)}function Z(e={}){if(V)return;V=!0,D(),(!e.supportedRuntimeRouteKinds||e.supportedRuntimeRouteKinds.has(`email_otp`))&&N().catch(()=>void 0);let i=new Set,a=new Set,s={parentOrigin:null,port:null,configuration:{kind:`unconfigured`},executionGeneration:0,onConfigurationChanged:null},c=e=>{try{s.port?.postMessage(e)}catch{}},l=e=>{e&&i.add(e)},d=e=>!!e&&(i.has(e)||g(e)?.cancelled===!0),f=e=>{e&&i.delete(e)},w=e=>{e&&c({type:`ERROR`,requestId:e,payload:{code:`cancelled`,message:`Request cancelled`}})},E=e=>!e||!d(e)?!1:g(e)?.cancelled?!0:(w(e),f(e),!0),O=()=>{for(let e of H){let t=document.querySelectorAll(e.selector);for(let n of t)try{e.cancellationKind===`native_cancel`?n.dispatchEvent(new Event(`cancel`,{cancelable:!0})):n.dispatchEvent(new CustomEvent(C.TX_CONFIRMER_CANCEL,{bubbles:!0,composed:!0}))}catch{}}},k=async i=>{let u=i.data;if(!u||!t(u))return;let C=u.requestId,D=s.executionGeneration,k=Y.bind(null,s,D,c),A=null;try{if(`transactionReview`in u){if(u.type!==`PM_SIGN_AND_SEND_TX`&&u.type!==`PM_SIGN_TEMPO`)throw new m(`review_invalid_input`,`Review is unsupported for this request`);let e=h(u.transactionReview);if(e.requestId!==C)throw new m(`review_invalid_input`,`Review request identity mismatch`);let t=u.payload?.options?.confirmationConfig;if(t?.uiMode!==`modal`||t.behavior!==`requireClick`)throw new m(`review_unsupported_mode`,`Review requires modal presentation and explicit approval`);A=new x(e,u.type===`PM_SIGN_TEMPO`&&u.payload?.request.senderSignatureAlgorithm!==`secp256k1`?`credential`:`mpc`,e=>k({type:`TRANSACTION_REVIEW_STATE`,requestId:C,payload:e}),e=>k({type:`ERROR`,requestId:C,payload:{code:e instanceof m?e.code:`cancelled`,message:e.message}}))}(u.type===`PM_LOCK`||u.type===`PM_LOCK_EXACT_WALLET_SESSION`)&&v(new m(`review_identity_changed`,`The wallet session changed`));let t=z(u);if(!B(t))switch(t.type){case`PING`:c({type:`PONG`,requestId:C});return;case`PM_SET_CONFIG`:{let e=o(s.configuration,r(t.request.payload)),i=p(s.configuration.kind===`configured`?s.configuration.config:null)!==p(e.config);if(s.configuration=e,i){s.executionGeneration+=1;let t=e.config;t.registration.publishableKey&&t.registration.projectEnvironmentId&&n(t.network.relayer.url);for(let e of a)c({type:`ERROR`,requestId:e,payload:{code:`wallet_configuration_changed`,message:`Wallet configuration changed during request`}});a.clear()}s.onConfigurationChanged?.(),i&&(v(new m(`review_identity_changed`,`Wallet execution configuration changed`)),O()),c({type:`PONG`,requestId:C});return}case`PM_ACTIVATE_TRANSACTION_REVIEW`:{let e=b(t.request.payload);e&&g(e.requestId)?.activate(e);return}case`PM_CANCEL`:{let e=t.request.payload?.requestId,n=t.request.payload,r=n&&typeof n==`object`?Reflect.get(n,`transactionReview`):void 0;if(r!==void 0){let t=h(r),i=g(t.requestId);if(t.requestId===e&&i&&_(t,i.metadata)){let e=new m(S(n&&typeof n==`object`?Reflect.get(n,`reviewErrorCode`):void 0),`Reviewed request cancelled`);try{y(i.metadata.validity)}catch(t){t instanceof Error&&(e=t)}i.cancel(e)}c({type:`PONG`,requestId:C});return}let i=e?g(e):void 0;if(i){i.cancel(new m(`cancelled`,`Request cancelled`)),c({type:`PONG`,requestId:C});return}l(e),O(),e&&w(e),c({type:`PONG`,requestId:C});return}case`PM_SET_TRANSACTION_VIEW`:{let e=t.request.payload,n=e&&typeof e==`object`?Reflect.get(e,`requestId`):null,r=e&&typeof e==`object`?Reflect.get(e,`view`):null;typeof n==`string`&&(r===`toast`||r===`closed`)&&(await import(`./transaction-activity-xfeHKJoq.js`).then(e=>e.o)).setTransactionActivityView(n,r);return}case`PM_TRANSACTION_BROADCAST_STARTED`:{let e=t.request.payload,n=e&&typeof e==`object`?Reflect.get(e,`signedTransaction`):null;typeof n==`string`&&(await import(`./transaction-activity-xfeHKJoq.js`).then(e=>e.o)).transactionBroadcastStarted(n);return}}if(!J(t,e.supportedRuntimeRouteKinds)){c({type:`ERROR`,requestId:C,payload:{code:`unsupported_request`,message:`Unsupported wallet iframe request type: ${t.type}`}});return}C&&a.add(C);let i=await M(t);if(D!==s.executionGeneration)return;await i.handleWalletHostRuntimeRequest({transactionReview:A,state:s,executionGeneration:D,req:t.request,post:Y.bind(null,s,D,c),isCancelled:X.bind(null,s,D,d),respondIfCancelled:X.bind(null,s,D,E)})}catch(e){if(D!==s.executionGeneration&&u.type!==`PM_SET_CONFIG`||A?.cancelled)return;let t=await import(`./canonicalSignerErrorCode-Cz48v4oy.js`);if(D!==s.executionGeneration&&u.type!==`PM_SET_CONFIG`)return;let n=e&&typeof e==`object`&&`code`in e?e.code:void 0,r=T(e),i=t.resolveWalletBoundaryErrorCode({requestType:u.type,rawCode:n,message:r,defaultCode:`HOST_ERROR`}),a=t.resolveWalletBoundaryErrorMessage({requestType:u.type,rawCode:n,code:i,message:r}),o=t.resolveWalletBoundarySignerKind(u.type);c({type:`ERROR`,requestId:C,payload:{code:i,message:a,...t.isWalletSignerBoundaryRequestType(u.type)&&t.isCanonicalSignerSessionBoundaryCode(i)&&o?{signerKind:o}:{}}})}finally{C&&(a.delete(C),f(C)),A?.finish()}};window.addEventListener(`message`,e=>{let t=W(e.data),n=e.ports[0];if(!(!t||!n||s.port)){if(e.source!==window.parent||!G(e.origin)){K(n);return}if(!q(n,t.payload.protocolVersion)){typeof e.origin==`string`&&e.origin.length&&e.origin!==`null`&&(s.parentOrigin=e.origin),s.port=n;try{s.port.onmessage=k,s.port.start?.()}catch{}c({type:`READY`,payload:{protocolVersion:u}})}}})}try{Z()}catch(e){console.error(`[WalletHost] init failed`,e)}export{Z as t};
@@ -1 +1 @@
1
- import{a as e,t}from"./singletons-8UH3gOnZ.js";import{p as n}from"./wallet-recovery-D7ywcIHw.js";import{t as r}from"./surface-measurement-reporter-DvVHPu_O.js";const i=`Recovery-code backup was cancelled before acknowledgement`;async function a(e,t={kind:`disabled`},n={}){if(typeof document>`u`)throw Error(`Wallet recovery-code backup requires a browser or a backup handler`);let a=document.activeElement instanceof HTMLElement?document.activeElement:null;if(n.shouldCancel?.())throw Error(i);let o=await import(`./mountRecoveryCodeBackupSurface-D1G-iCPI.js`);if(n.shouldCancel?.())throw Error(i);let s=null,l=null,u=!1;return await new Promise((d,f)=>{let p=()=>{s?.disconnect(),s=null,l?.dispose(),l=null,a?.focus()},m=e=>{u||(u=!0,p(),e instanceof Error?f(e):d(e))},h=t=>{switch(t.kind){case`dismissed`:m(Error(i));return;case`recovery_codes`:if(t.acknowledged){m({kind:`wallet_recovery_codes_backed_up_v1`});return}if(e.kind===`direct_backup`&&e.request.continuation===`registration_may_defer`){m({kind:`wallet_recovery_code_backup_deferred_v1`});return}m(Error(i));return}};try{l=o.mountRecoveryCodeBackupSurface({parent:document.body,appearance:n.appearance,experience:e,surface:t.kind===`wallet_iframe`?`wallet-iframe`:`standalone`,onClose:h,onCancel:()=>m(Error(i)),onShown:e=>{u||t.kind!==`wallet_iframe`||(s=r({kind:`request_scroll_surface`,requestId:t.requestId,element:e,postMeasurement:c.bind(null,e,t.postMeasurement)}))}})}catch(e){m(e instanceof Error?e:Error(String(e)))}})}async function o(e,t={kind:`disabled`}){return await a({kind:`direct_backup`,request:e},t)}async function s(e,t={kind:`disabled`},n={}){return await a({kind:`account_menu`,...e},t,n)}function c(e,t,n){if(n.kind!==`measured_v1`)throw Error(`Recovery codes require a request surface measurement`);t({kind:`measured_v1`,requestId:n.requestId,sequence:n.sequence,widthCssPx:e.dataset.seamsRecoveryStage===`recovery_codes`?688:480,heightCssPx:n.heightCssPx})}const l=`wallet_recovery_codes_v1`,u=[`record_version`,`wallet_id`,`enrollment_id`,`recovery_codes_issued_at_ms`,`status`,`key`,`iv`,`ciphertext`];function d(e){return typeof CryptoKey<`u`&&e instanceof CryptoKey&&e.type===`secret`&&!e.extractable&&e.algorithm.name===`AES-GCM`&&e.usages.includes(`encrypt`)&&e.usages.includes(`decrypt`)}function f(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;let t=new Map(Object.entries(e)),n=new Set(u);return t.size!==n.size||[...t.keys()].some(e=>!n.has(e))?null:{record_version:t.get(`record_version`),wallet_id:t.get(`wallet_id`),enrollment_id:t.get(`enrollment_id`),recovery_codes_issued_at_ms:t.get(`recovery_codes_issued_at_ms`),status:t.get(`status`),key:t.get(`key`),iv:t.get(`iv`),ciphertext:t.get(`ciphertext`)}}function p(e,t){let n=f(e);if(!n)return null;let r=Number(n.recovery_codes_issued_at_ms);return n.record_version!==1||n.wallet_id!==t||n.enrollment_id!==l||n.status!==`pending`||!Number.isSafeInteger(r)||r<=0||!d(n.key)||!(n.iv instanceof Uint8Array)||n.iv.byteLength!==12||!(n.ciphertext instanceof Uint8Array)||n.ciphertext.byteLength===0?null:{record_version:1,wallet_id:t,enrollment_id:l,recovery_codes_issued_at_ms:r,status:`pending`,key:n.key,iv:n.iv,ciphertext:n.ciphertext}}function m(e,t){return new TextEncoder().encode(JSON.stringify({kind:l,walletId:e,issuedAtMs:t}))}function h(e){return[e,l]}const g=new class{async write(r){let i=r.walletId.trim();if(!i)throw Error(`Pending recovery-code backup requires a wallet`);let a=n(r.recoveryCodes.map(String)),o=r.issuedAtMs??Date.now();if(!Number.isSafeInteger(o)||o<=0)throw Error(`Pending recovery-code backup issue time is invalid`);let s=await crypto.subtle.generateKey({name:`AES-GCM`,length:256},!1,[`encrypt`,`decrypt`]),c=crypto.getRandomValues(new Uint8Array(12)),u=m(i,o),d=new TextEncoder().encode(JSON.stringify(a)),f=null;try{f=new Uint8Array(await crypto.subtle.encrypt({name:`AES-GCM`,iv:c,additionalData:u},s,d)),await t.runTransaction([e.pendingWalletRecoveryCodeBackups],`readwrite`,async t=>{await t.store(e.pendingWalletRecoveryCodeBackups).put({record_version:1,wallet_id:i,enrollment_id:l,recovery_codes_issued_at_ms:o,status:`pending`,key:s,iv:c,ciphertext:f})})}finally{u.fill(0),d.fill(0),f?.fill(0)}}async read(r){let i=r.trim();if(!i)return null;let a=p(await(await t.getDB()).get(e.pendingWalletRecoveryCodeBackups,h(i)),i);if(!a)return null;let o=m(i,a.recovery_codes_issued_at_ms),s=null;try{s=new Uint8Array(await crypto.subtle.decrypt({name:`AES-GCM`,iv:a.iv,additionalData:o},a.key,a.ciphertext));let e=JSON.parse(new TextDecoder().decode(s));if(!Array.isArray(e))throw Error(`Pending recovery-code backup is invalid`);return{walletId:i,recoveryCodes:n(e.map(String))}}finally{o.fill(0),s?.fill(0)}}async has(n){let r=n.trim();return r?p(await(await t.getDB()).get(e.pendingWalletRecoveryCodeBackups,h(r)),r)!==null:!1}async delete(n){let r=n.trim();r&&await t.runTransaction([e.pendingWalletRecoveryCodeBackups],`readwrite`,async t=>{await t.store(e.pendingWalletRecoveryCodeBackups).delete(h(r))})}};export{o as n,s as r,g as t};
1
+ import{a as e,t}from"./singletons-8UH3gOnZ.js";import{m as n}from"./wallet-recovery-LMtGiEL3.js";import{t as r}from"./surface-measurement-reporter-DvVHPu_O.js";const i=`Recovery-code backup was cancelled before acknowledgement`;async function a(e,t={kind:`disabled`},n={}){if(typeof document>`u`)throw Error(`Wallet recovery-code backup requires a browser or a backup handler`);let a=document.activeElement instanceof HTMLElement?document.activeElement:null;if(n.shouldCancel?.())throw Error(i);let o=await import(`./mountRecoveryCodeBackupSurface-D1G-iCPI.js`);if(n.shouldCancel?.())throw Error(i);let s=null,l=null,u=!1;return await new Promise((d,f)=>{let p=()=>{s?.disconnect(),s=null,l?.dispose(),l=null,a?.focus()},m=e=>{u||(u=!0,p(),e instanceof Error?f(e):d(e))},h=t=>{switch(t.kind){case`dismissed`:m(Error(i));return;case`recovery_codes`:if(t.acknowledged){m({kind:`wallet_recovery_codes_backed_up_v1`});return}if(e.kind===`direct_backup`&&e.request.continuation===`registration_may_defer`){m({kind:`wallet_recovery_code_backup_deferred_v1`});return}m(Error(i));return}};try{l=o.mountRecoveryCodeBackupSurface({parent:document.body,appearance:n.appearance,experience:e,surface:t.kind===`wallet_iframe`?`wallet-iframe`:`standalone`,onClose:h,onCancel:()=>m(Error(i)),onShown:e=>{u||t.kind!==`wallet_iframe`||(s=r({kind:`request_scroll_surface`,requestId:t.requestId,element:e,postMeasurement:c.bind(null,e,t.postMeasurement)}))}})}catch(e){m(e instanceof Error?e:Error(String(e)))}})}async function o(e,t={kind:`disabled`}){return await a({kind:`direct_backup`,request:e},t)}async function s(e,t={kind:`disabled`},n={}){return await a({kind:`account_menu`,...e},t,n)}function c(e,t,n){if(n.kind!==`measured_v1`)throw Error(`Recovery codes require a request surface measurement`);t({kind:`measured_v1`,requestId:n.requestId,sequence:n.sequence,widthCssPx:e.dataset.seamsRecoveryStage===`recovery_codes`?688:480,heightCssPx:n.heightCssPx})}const l=`wallet_recovery_codes_v1`,u=[`record_version`,`wallet_id`,`enrollment_id`,`recovery_codes_issued_at_ms`,`status`,`key`,`iv`,`ciphertext`];function d(e){return typeof CryptoKey<`u`&&e instanceof CryptoKey&&e.type===`secret`&&!e.extractable&&e.algorithm.name===`AES-GCM`&&e.usages.includes(`encrypt`)&&e.usages.includes(`decrypt`)}function f(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;let t=new Map(Object.entries(e)),n=new Set(u);return t.size!==n.size||[...t.keys()].some(e=>!n.has(e))?null:{record_version:t.get(`record_version`),wallet_id:t.get(`wallet_id`),enrollment_id:t.get(`enrollment_id`),recovery_codes_issued_at_ms:t.get(`recovery_codes_issued_at_ms`),status:t.get(`status`),key:t.get(`key`),iv:t.get(`iv`),ciphertext:t.get(`ciphertext`)}}function p(e,t){let n=f(e);if(!n)return null;let r=Number(n.recovery_codes_issued_at_ms);return n.record_version!==1||n.wallet_id!==t||n.enrollment_id!==l||n.status!==`pending`||!Number.isSafeInteger(r)||r<=0||!d(n.key)||!(n.iv instanceof Uint8Array)||n.iv.byteLength!==12||!(n.ciphertext instanceof Uint8Array)||n.ciphertext.byteLength===0?null:{record_version:1,wallet_id:t,enrollment_id:l,recovery_codes_issued_at_ms:r,status:`pending`,key:n.key,iv:n.iv,ciphertext:n.ciphertext}}function m(e,t){return new TextEncoder().encode(JSON.stringify({kind:l,walletId:e,issuedAtMs:t}))}function h(e){return[e,l]}const g=new class{async write(r){let i=r.walletId.trim();if(!i)throw Error(`Pending recovery-code backup requires a wallet`);let a=n(r.recoveryCodes.map(String)),o=r.issuedAtMs??Date.now();if(!Number.isSafeInteger(o)||o<=0)throw Error(`Pending recovery-code backup issue time is invalid`);let s=await crypto.subtle.generateKey({name:`AES-GCM`,length:256},!1,[`encrypt`,`decrypt`]),c=crypto.getRandomValues(new Uint8Array(12)),u=m(i,o),d=new TextEncoder().encode(JSON.stringify(a)),f=null;try{f=new Uint8Array(await crypto.subtle.encrypt({name:`AES-GCM`,iv:c,additionalData:u},s,d)),await t.runTransaction([e.pendingWalletRecoveryCodeBackups],`readwrite`,async t=>{await t.store(e.pendingWalletRecoveryCodeBackups).put({record_version:1,wallet_id:i,enrollment_id:l,recovery_codes_issued_at_ms:o,status:`pending`,key:s,iv:c,ciphertext:f})})}finally{u.fill(0),d.fill(0),f?.fill(0)}}async read(r){let i=r.trim();if(!i)return null;let a=p(await(await t.getDB()).get(e.pendingWalletRecoveryCodeBackups,h(i)),i);if(!a)return null;let o=m(i,a.recovery_codes_issued_at_ms),s=null;try{s=new Uint8Array(await crypto.subtle.decrypt({name:`AES-GCM`,iv:a.iv,additionalData:o},a.key,a.ciphertext));let e=JSON.parse(new TextDecoder().decode(s));if(!Array.isArray(e))throw Error(`Pending recovery-code backup is invalid`);return{walletId:i,recoveryCodes:n(e.map(String))}}finally{o.fill(0),s?.fill(0)}}async has(n){let r=n.trim();return r?p(await(await t.getDB()).get(e.pendingWalletRecoveryCodeBackups,h(r)),r)!==null:!1}async delete(n){let r=n.trim();r&&await t.runTransaction([e.pendingWalletRecoveryCodeBackups],`readwrite`,async t=>{await t.store(e.pendingWalletRecoveryCodeBackups).delete(h(r))})}};export{o as n,s as r,g as t};
@@ -1 +1 @@
1
- import{M as e,o as t}from"./domainIds-BzkGsRqO.js";import{d as n,l as r}from"./chains-C_X_fNuS.js";import"./primitives-CqrjmIAH.js";import{i}from"./base64-DW79QA0h.js";import{r as a}from"./secureRandomId-LwBFx84B.js";import"./sessionPolicy-CBTZQe1n.js";import"./signingSessionSeal-DX41aXUL.js";import"./activeWalletSession-WdZkhtBB.js";import"./capabilityKinds-N8xo_IEh.js";import"./errors-DIWY1KR9.js";import"./accountIds-BzZs7YoX.js";import"./registrationSignerPlan-dY9Rp0m_.js";import"./signerDomain-DqLCvI-D.js";import"./registrationIntent-BHU5k2Q-.js";import"./singletons-8UH3gOnZ.js";import"./walletAuthority-BWvfaKIX.js";import"./emailOtpEcdsaDerivationIdentity-p0C1CQva.js";import"./challengeDelivery-5lIu9spR.js";import"./digestEncoding-CkUc5vtR.js";import"./registrationIds-ByuReLUc.js";import{a as o,c as s}from"./passkey-custody-Cd_yyoRa.js";import{u as c}from"./walletCustodyEcdsaContinuity-_IKoCUBO.js";import"./keccak-BArcwgbj.js";import{f as l,m as u}from"./wallet-recovery-D7ywcIHw.js";import{a as d,c as f,d as p,l as m,n as h,o as g,r as _,s as v,t as y,u as b}from"./walletRecoveryCommit-DDPa1rAJ.js";function x(e){throw Error(`Unhandled wallet recovery branch: ${String(e)}`)}function S(e){return e.target.kind===`google_email_otp`}function C(e,t){if(!e||e.stage===`prepared`||e.stage===`google_verified`||e.walletId!==t.walletId||e.target.kind!==t.target.kind)return null;switch(e.target.kind){case`passkey`:return t.kind===`credential_created`&&t.target.kind===`passkey`&&e.target.rpId===t.target.rpId?e:null;case`google_email_otp`:return t.kind===`email_otp_verified`&&t.target.kind===`google_email_otp`&&e.target.googleProvider===t.target.googleProvider?e:null}}function w(){return l(a(`wallet-recovery-reservation`,32,`wallet recovery operation reservations`))}function T(e){return e}const E=`seams:recovery:consumed-code-digests`;function D(){try{let e=JSON.parse(sessionStorage.getItem(E)??`[]`);return Array.isArray(e)?new Set(e.filter(e=>typeof e==`string`)):new Set}catch{return new Set}}function O(e,t){e.add(t);try{sessionStorage.setItem(E,JSON.stringify([...e].slice(-32)))}catch{}}function k(e){e&&e.byteLength>0&&new Uint8Array(e).fill(0)}function A(e){switch(e.recoveryCodeBytes.fill(0),e.stage){case`prepared`:case`google_verified`:return;case`credential_created`:k(e.replacement.factorSecret);return;case`email_otp_verified`:case`manifest_recovered`:k(e.replacement.kind===`passkey`?e.replacement.factorSecret:e.replacement.factor.factorSecret);return}}function j(){return{kind:`refused`}}function M(e){if(typeof e!=`object`||!e)return!1;let t=Reflect.get(e,`name`);return t===`NotAllowedError`||t===`AbortError`}function N(e,t){if(e.target.kind!==`passkey`||!e.prepared.registration)throw Error(`passkey recovery registration is unavailable`);return{stage:`credential_created`,recoveryOperationId:e.recoveryOperationId,walletId:e.walletId,relayUrl:e.relayUrl,target:e.target,prepared:e.prepared,custodyJson:e.custodyJson,recoveryCodeBytes:e.recoveryCodeBytes,replacement:{kind:`passkey`,registration:t.registration,credentialIdB64u:t.credentialIdB64u,factorSecret:t.factorSecret}}}function P(e,t){return{stage:`email_otp_verified`,recoveryOperationId:e.recoveryOperationId,walletId:e.walletId,relayUrl:e.relayUrl,target:e.target,prepared:e.prepared,custodyJson:e.custodyJson,recoveryCodeBytes:e.recoveryCodeBytes,replacement:t}}function F(e){let t=e.prepared.registration;if(!t)throw Error(`passkey recovery registration is unavailable`);return{replacementId:t.replacementId,walletAuthMethodId:t.walletAuthMethodId,factor:s({rpId:t.rpId,credentialIdB64u:e.replacement.credentialIdB64u}),factorSecret:e.replacement.factorSecret}}function I(e){let t=e.prepared.registration;if(!t)throw Error(`passkey recovery registration is unavailable`);return t.challengeId}function L(e,t){return{stage:`manifest_recovered`,recoveryOperationId:e.recoveryOperationId,walletId:e.walletId,relayUrl:e.relayUrl,target:e.target,prepared:e.prepared,custodyJson:e.custodyJson,recoveryCodeBytes:e.recoveryCodeBytes,replacement:e.replacement,recovered:t}}function R(e,t){return{stage:`manifest_recovered`,recoveryOperationId:e.recoveryOperationId,walletId:e.walletId,relayUrl:e.relayUrl,target:e.target,prepared:e.prepared,custodyJson:e.custodyJson,recoveryCodeBytes:e.recoveryCodeBytes,replacement:e.replacement,recovered:t}}function z(e,t){switch(e.stage){case`credential_created`:return L(e,t);case`email_otp_verified`:return R(e,t);default:return x(e)}}function B(e){return e.authMethod.kind===`passkey`}function V(e){return e.target.kind===`passkey`&&e.replacement.kind===`passkey`}function H(e){return e.target.kind===`google_email_otp`&&e.replacement.kind===`email_otp`}async function U(e){return await e.context.signingEngine.getSignerWorkerContext().requestWorkerOperation({kind:`emailOtp`,request:{type:`releaseWalletRecoveryEmailOtpFactor`,payload:{relayUrl:e.relayUrl,walletId:String(e.walletId),recoveryOperationId:e.recoveryOperationId,reservationId:e.reservationId}}})}async function W(e){let t=e.prepared.registration;if(!t)throw Error(`passkey recovery registration is unavailable`);return await m({relayUrl:e.relayUrl,walletId:e.walletId,reservationId:e.prepared.reservationId,recoveryOperationId:e.prepared.recoveryOperationId,targetDeviceId:e.prepared.targetDeviceId,targetAuthorityId:e.prepared.targetAuthorityId,targetWalletAuthMethodId:e.prepared.targetWalletAuthMethodId,challengeId:t.challengeId,replacementId:t.replacementId,webauthnRegistration:e.replacement.registration,replacementEnvelope:e.recovered.replacementEnvelope,ecdsaMaterialPossessionProofs:e.recovered.ecdsaKeySets.map(e=>({keySetId:e.entry.keySetId,proof:e.activation.possessionProof}))})}var G=class{constructor(e=null){this.rpc=e}#e=new Map;#t=new Map;#n=new Map;#r=new Map;#i=new Map;#a=D();async prepareWithCode(t){if(this.#c(),t.signal.aborted)return j();if(t.target.kind===`passkey`){let n=e(t.context.signingEngine.getRpId());if(!n.ok||n.value!==t.target.rpId)return j()}let n=null;try{n=u(t.recoveryCode);let e=i(await r(n));if(this.#a.has(e))return{kind:`consumed`};let o=T(e),s=this.#r.get(o),c=s?.expiresAtMs&&s.expiresAtMs>Date.now()?s.reservationId:w(),l=await p({relayUrl:t.relayUrl,target:t.target,recoveryCodeB64u:i(n),reservationId:c});if(l.kind!==`prepared`)return l.kind===`retryable_conflict`||l.kind===`transport_uncertain`?this.#r.set(o,{reservationId:c,expiresAtMs:Date.now()+3e5}):this.#r.delete(o),l;if(this.#r.delete(o),t.signal.aborted)return this.#r.set(o,{reservationId:l.reservationId,expiresAtMs:l.reservationExpiresAtMs}),j();let d=a(`wallet-recovery-operation`,24,`wallet recovery client operation handles`);return this.#e.set(d,{stage:`prepared`,recoveryOperationId:d,walletId:l.walletId,relayUrl:t.relayUrl,target:t.target,prepared:l,custodyJson:b({walletId:l.walletId,prepared:l}),recoveryCodeBytes:n}),this.#i.set(d,o),n=null,{kind:`prepared`,recoveryOperationId:d,walletId:l.walletId,target:t.target}}catch{return j()}finally{n?.fill(0)}}createPasskey(e){this.#c();let t=this.#e.get(e.operation.recoveryOperationId);if(!t||t.stage!==`prepared`||t.walletId!==e.operation.walletId||t.target.kind!==`passkey`||e.operation.target.kind!==`passkey`||t.target.rpId!==e.operation.target.rpId||this.#n.has(t.recoveryOperationId)||!t.prepared.registration)return Promise.resolve({kind:`refused`});let n=new AbortController;this.#n.set(t.recoveryOperationId,n);let r;try{r=e.context.signingEngine.createWalletRecoveryReplacementCredential({walletId:t.walletId,registration:t.prepared.registration,cancellation:{kind:`abort_signal`,signal:n.signal}})}catch{return this.cancel(t.recoveryOperationId),Promise.resolve({kind:`refused`})}return this.#s({current:t,credentialPromise:r,promptController:n})}async verifyGoogle(e){this.#c();let t=this.#e.get(e.operation.recoveryOperationId);if(!this.rpc||!t||t.stage!==`prepared`||t.target.kind!==`google_email_otp`||e.operation.target.kind!==`google_email_otp`||t.walletId!==e.operation.walletId||t.target.googleProvider!==e.operation.target.googleProvider||t.relayUrl!==e.relayUrl)return j();let n=t.prepared;if(!S(n))return j();try{let r=await this.rpc.verifyGoogle({relayUrl:t.relayUrl,recoveryOperationId:n.recoveryOperationId,reservationId:n.reservationId,idToken:e.idToken});if(r.kind!==`verified`)return r;if(r.recoveryOperationId!==n.recoveryOperationId)return{kind:`transport_uncertain`};let i={kind:`google_verified`,recoveryOperationId:t.recoveryOperationId,walletId:t.walletId,target:t.target,challengeId:r.challengeId,delivery:r.delivery,expiresAtMs:r.expiresAtMs},a={stage:`google_verified`,recoveryOperationId:t.recoveryOperationId,walletId:t.walletId,relayUrl:t.relayUrl,target:t.target,prepared:n,custodyJson:t.custodyJson,recoveryCodeBytes:t.recoveryCodeBytes,verification:i};return this.#e.set(a.recoveryOperationId,a),i}catch{return{kind:`transport_uncertain`}}}async verifyEmailOtp(e){this.#c();let n=this.#e.get(e.operation.recoveryOperationId);if(!this.rpc||!n||n.stage!==`google_verified`||n.walletId!==e.operation.walletId||n.target.kind!==`google_email_otp`||e.operation.target.kind!==`google_email_otp`||n.verification.challengeId!==e.operation.challengeId||e.challengeId!==e.operation.challengeId)return j();let r=t(e.challengeId);if(!r.ok)return j();try{let t=await this.rpc.verifyEmailOtp({relayUrl:n.relayUrl,recoveryOperationId:n.prepared.recoveryOperationId,reservationId:n.prepared.reservationId,challengeId:r.value,otpCode:e.otpCode});if(t.kind!==`verified`)return t;if(t.recoveryOperationId!==n.prepared.recoveryOperationId||t.challengeId!==e.challengeId)return{kind:`transport_uncertain`};let i=await U({context:e.context,relayUrl:n.relayUrl,walletId:n.walletId,recoveryOperationId:n.prepared.recoveryOperationId,reservationId:String(n.prepared.reservationId)});if(i.kind===`existing`){if(i.recoveryOperationId!==String(n.prepared.recoveryOperationId)||i.reservationId!==String(n.prepared.reservationId)||i.factorSecret32.byteLength!==32)return k(i.factorSecret32),{kind:`transport_uncertain`};let t=P(n,{kind:`email_otp`,factor:{replacementId:String(n.prepared.recoveryOperationId),walletAuthMethodId:n.prepared.targetWalletAuthMethodId,factor:o({enrollmentId:i.enrollmentId,enrollmentSealKeyVersion:i.enrollmentSealKeyVersion}),factorSecret:i.factorSecret32},enrollment:{kind:`existing`,enrollmentId:i.enrollmentId,enrollmentSealKeyVersion:i.enrollmentSealKeyVersion},providerSubject:i.providerSubject,verifiedEmail:i.verifiedEmail,registrationAuthorityId:e.challengeId});return this.#e.set(t.recoveryOperationId,t),{kind:`email_otp_verified`,recoveryOperationId:t.recoveryOperationId,walletId:t.walletId,target:t.target,challengeId:e.challengeId}}if(i.kind!==`create`)return i;if(i.recoveryOperationId!==String(n.prepared.recoveryOperationId)||i.reservationId!==String(n.prepared.reservationId))return{kind:`transport_uncertain`};let a=crypto.getRandomValues(new Uint8Array(32)),s=null;try{let t=await e.context.signingEngine.prepareEmailOtpRegistrationEnrollmentMaterialInternal({relayUrl:n.relayUrl,walletId:n.walletId,userId:i.providerSubject,clientSecret32:a});s=a.slice().buffer;let r=P(n,{kind:`email_otp`,factor:{replacementId:String(n.prepared.recoveryOperationId),walletAuthMethodId:n.prepared.targetWalletAuthMethodId,factor:o({enrollmentId:t.enrollmentId,enrollmentSealKeyVersion:t.enrollmentSealKeyVersion}),factorSecret:s},enrollment:{kind:`create`,enrollmentId:t.enrollmentId,providerSubject:i.providerSubject,verifiedEmail:i.verifiedEmail,material:t.emailOtpEnrollment},providerSubject:i.providerSubject,verifiedEmail:i.verifiedEmail,registrationAuthorityId:e.challengeId});return this.#e.set(r.recoveryOperationId,r),s=null,{kind:`email_otp_verified`,recoveryOperationId:r.recoveryOperationId,walletId:r.walletId,target:r.target,challengeId:e.challengeId}}finally{a.fill(0),s&&k(s)}}catch{return{kind:`refused`}}}async finalize(e){let t=String(e.operation.recoveryOperationId),n=this.#t.get(t);if(n)return n;let r=this.#o(e).finally(()=>{this.#t.delete(t)});return this.#t.set(t,r),r}async#o(e){this.#c();let t=C(this.#e.get(e.operation.recoveryOperationId),e.operation);if(!t)return j();try{if(t.stage===`credential_created`||t.stage===`email_otp_verified`){let n=t.stage===`credential_created`?F(t):t.replacement.factor,r=await e.context.signingEngine.recoverWalletCustodyManifest({walletId:t.walletId,prepared:t.prepared,custodyJson:t.custodyJson,recoveryCodeBytes:t.recoveryCodeBytes,replacementFactor:n,recoveryChallengeId:t.stage===`credential_created`?I(t):String(t.prepared.recoveryOperationId),relayUrl:t.relayUrl});if(this.#e.get(t.recoveryOperationId)!==t)return A(t),j();if(t.prepared.reservationExpiresAtMs<=Date.now())return this.cancel(t.recoveryOperationId),j();t.recoveryCodeBytes.fill(0),k(t.stage===`credential_created`?t.replacement.factorSecret:t.replacement.factor.factorSecret),t=z(t,r),this.#e.set(t.recoveryOperationId,t)}if(t.stage===`manifest_recovered`){if(!V(t)&&!H(t))return{kind:`transport_uncertain`};if(t.target.kind===`google_email_otp`&&!this.rpc)return{kind:`refused`};let e=await y({operation:t});if(this.#e.get(t.recoveryOperationId)!==t)return{kind:`transport_uncertain`};await c.putPendingWalletRecoveryCommit(e.pending);let r=V(t)?await W(t):this.rpc?await this.rpc.finalizeEmailOtp({relayUrl:t.relayUrl,walletId:t.walletId,recoveryOperationId:t.prepared.recoveryOperationId,reservationId:t.prepared.reservationId,targetDeviceId:t.prepared.targetDeviceId,targetAuthorityId:t.prepared.targetAuthorityId,targetWalletAuthMethodId:t.prepared.targetWalletAuthMethodId,expectedProviderSubject:t.replacement.providerSubject,expectedEmailHashHex:await n(t.replacement.verifiedEmail),expectedRegistrationAuthorityId:t.replacement.registrationAuthorityId,replacementEnvelope:t.recovered.replacementEnvelope,ecdsaMaterialPossessionProofs:t.recovered.ecdsaKeySets.map(e=>({keySetId:e.entry.keySetId,proof:e.activation.possessionProof})),emailOtpEnrollment:t.replacement.enrollment.kind===`create`?{kind:`create`,material:t.replacement.enrollment.material}:null}):{kind:`refused`};if(r.kind===`refused`)return await c.deletePendingWalletRecoveryCommit(t.prepared.recoveryOperationId),this.#e.get(t.recoveryOperationId)===t&&this.cancel(t.recoveryOperationId),r;if(this.#e.get(t.recoveryOperationId)!==t)return r.kind===`promoted`?{kind:`transport_uncertain`}:r;if(r.kind!==`promoted`)return r;if(t.replacement.kind===`passkey`&&r.authMethod.credentialIdB64u!==t.replacement.credentialIdB64u)return{kind:`transport_uncertain`};let i;if(f(e.payload)){if(!B(r))return{kind:`transport_uncertain`};i={kind:`passkey`,payload:e.payload,promotion:r}}else{if(B(r))return{kind:`transport_uncertain`};i={kind:`google_email_otp`,payload:e.payload,promotion:r}}await _({pending:await h({awaiting:e.pending,promotion:i}),payload:i.payload})}let r=this.#i.get(t.recoveryOperationId);return r&&O(this.#a,r),this.#e.delete(t.recoveryOperationId),this.#i.delete(t.recoveryOperationId),A(t),{kind:`ready_for_sign_in`,walletId:t.walletId}}catch{return{kind:`transport_uncertain`}}}async#s(e){try{let t=await e.credentialPromise;if(this.#e.get(e.current.recoveryOperationId)!==e.current||e.promptController.signal.aborted)return k(t.factorSecret),{kind:`dismissed`};if(e.current.prepared.reservationExpiresAtMs<=Date.now())return k(t.factorSecret),this.cancel(e.current.recoveryOperationId),{kind:`refused`};let n=N(e.current,t);return this.#e.set(n.recoveryOperationId,n),{kind:`credential_created`,recoveryOperationId:n.recoveryOperationId,walletId:n.walletId,target:n.target}}catch(t){return e.promptController.signal.aborted||M(t)?{kind:`dismissed`}:{kind:`transport_uncertain`}}finally{this.#n.get(e.current.recoveryOperationId)===e.promptController&&this.#n.delete(e.current.recoveryOperationId)}}cancel(e){this.#n.get(e)?.abort(),this.#n.delete(e);let t=this.#e.get(e);if(!t)return;let n=this.#i.get(e);this.#i.delete(e),n&&t.prepared.reservationExpiresAtMs>Date.now()&&this.#r.set(n,{reservationId:t.prepared.reservationId,expiresAtMs:t.prepared.reservationExpiresAtMs}),this.#e.delete(e),A(t)}#c(){let e=Date.now();for(let[t,n]of this.#r)n.expiresAtMs<=e&&this.#r.delete(t);for(let[t,n]of this.#e)n.prepared.reservationExpiresAtMs>e||(this.#n.get(t)?.abort(),this.#n.delete(t),this.#e.delete(t),this.#i.delete(t),A(n))}},K=class{#e=new G({verifyGoogle:v,verifyEmailOtp:g,finalizeEmailOtp:d});constructor(t,n){this.context=t,this.relayUrl=n;let r=e(t.signingEngine.getRpId());if(!r.ok)throw Error(`wallet recovery RP ID ${r.error.message}`);this.#t=r.value}#t;targetFor(e){switch(e){case`passkey`:return{kind:e,rpId:this.#t};case`google_email_otp`:return{kind:e,googleProvider:`google`}}}async prepare(e){let t=await this.#e.prepareWithCode({context:this.context,relayUrl:this.relayUrl,recoveryCode:e.recoveryCode,target:e.target,signal:e.signal});return t.kind===`prepared`?(t.target.kind,{kind:`hosted_recovery_prepared`,recoveryOperationId:t.recoveryOperationId,walletId:t.walletId,target:t.target}):t}createPasskey(e){return this.#n({kind:`prepared`,recoveryOperationId:e.recoveryOperationId,walletId:e.walletId,target:e.target})}async verifyGoogle(e,t){let n=await this.#e.verifyGoogle({relayUrl:this.relayUrl,operation:{kind:`prepared`,recoveryOperationId:e.recoveryOperationId,walletId:e.walletId,target:e.target},idToken:t});return n.kind===`google_verified`?{kind:`hosted_recovery_google_verified`,recoveryOperationId:n.recoveryOperationId,walletId:n.walletId,target:n.target,challengeId:n.challengeId,delivery:n.delivery,expiresAtMs:n.expiresAtMs}:n}async verifyEmailOtp(e,t){let n=await this.#e.verifyEmailOtp({context:this.context,operation:{kind:`google_verified`,recoveryOperationId:e.recoveryOperationId,walletId:e.walletId,target:e.target,challengeId:e.challengeId,delivery:e.delivery,expiresAtMs:e.expiresAtMs},challengeId:t.challengeId,otpCode:t.otpCode});return n.kind===`email_otp_verified`?{kind:`hosted_recovery_email_otp_verified`,recoveryOperationId:n.recoveryOperationId,walletId:n.walletId,target:n.target,challengeId:n.challengeId}:n}async finalize(e){return e.kind===`hosted_recovery_credential_created`?await this.#e.finalize({context:this.context,operation:{kind:`credential_created`,recoveryOperationId:e.recoveryOperationId,walletId:e.walletId,target:e.target}}):await this.#e.finalize({context:this.context,operation:{kind:`email_otp_verified`,recoveryOperationId:e.recoveryOperationId,walletId:e.walletId,target:e.target,challengeId:e.challengeId}})}async cancel(e){this.#e.cancel(e.recoveryOperationId)}async#n(e){let t=await this.#e.createPasskey({context:this.context,operation:e});return t.kind===`credential_created`?this.#r(t):t}#r(e){return{kind:`hosted_recovery_credential_created`,recoveryOperationId:e.recoveryOperationId,walletId:e.walletId,target:e.target}}};function q(e){return new K(e.context,e.relayUrl)}export{q as createHostedRecoveryPort};
1
+ import{M as e,o as t}from"./domainIds-BzkGsRqO.js";import{d as n,l as r}from"./chains-C_X_fNuS.js";import"./primitives-CqrjmIAH.js";import{i}from"./base64-DW79QA0h.js";import{r as a}from"./secureRandomId-LwBFx84B.js";import"./sessionPolicy-CBTZQe1n.js";import"./signingSessionSeal-DX41aXUL.js";import"./activeWalletSession-WdZkhtBB.js";import"./capabilityKinds-N8xo_IEh.js";import"./errors-DIWY1KR9.js";import"./accountIds-BzZs7YoX.js";import"./registrationSignerPlan-dY9Rp0m_.js";import"./signerDomain-DqLCvI-D.js";import"./registrationIntent-BHU5k2Q-.js";import"./singletons-8UH3gOnZ.js";import"./walletAuthority-BWvfaKIX.js";import"./emailOtpEcdsaDerivationIdentity-p0C1CQva.js";import"./challengeDelivery-5lIu9spR.js";import"./digestEncoding-CkUc5vtR.js";import"./registrationIds-ByuReLUc.js";import{a as o,c as s}from"./passkey-custody-Cd_yyoRa.js";import{u as c}from"./walletCustodyEcdsaContinuity-D-gYxv6e.js";import"./keccak-BArcwgbj.js";import{f as l,h as u}from"./wallet-recovery-LMtGiEL3.js";import{a as d,c as f,d as p,l as m,n as h,o as g,r as _,s as v,t as y,u as b}from"./walletRecoveryCommit-BYRC_2li.js";function x(e){throw Error(`Unhandled wallet recovery branch: ${String(e)}`)}function S(e){return e.target.kind===`google_email_otp`}function C(e,t){if(!e||e.stage===`prepared`||e.stage===`google_verified`||e.walletId!==t.walletId||e.target.kind!==t.target.kind)return null;switch(e.target.kind){case`passkey`:return t.kind===`credential_created`&&t.target.kind===`passkey`&&e.target.rpId===t.target.rpId?e:null;case`google_email_otp`:return t.kind===`email_otp_verified`&&t.target.kind===`google_email_otp`&&e.target.googleProvider===t.target.googleProvider?e:null}}function w(){return l(a(`wallet-recovery-reservation`,32,`wallet recovery operation reservations`))}function T(e){return e}const E=`seams:recovery:consumed-code-digests`;function D(){try{let e=JSON.parse(sessionStorage.getItem(E)??`[]`);return Array.isArray(e)?new Set(e.filter(e=>typeof e==`string`)):new Set}catch{return new Set}}function O(e,t){e.add(t);try{sessionStorage.setItem(E,JSON.stringify([...e].slice(-32)))}catch{}}function k(e){e&&e.byteLength>0&&new Uint8Array(e).fill(0)}function A(e){switch(e.recoveryCodeBytes.fill(0),e.stage){case`prepared`:case`google_verified`:return;case`credential_created`:k(e.replacement.factorSecret);return;case`email_otp_verified`:case`manifest_recovered`:k(e.replacement.kind===`passkey`?e.replacement.factorSecret:e.replacement.factor.factorSecret);return}}function j(){return{kind:`refused`}}function M(e){if(typeof e!=`object`||!e)return!1;let t=Reflect.get(e,`name`);return t===`NotAllowedError`||t===`AbortError`}function N(e,t){if(e.target.kind!==`passkey`||!e.prepared.registration)throw Error(`passkey recovery registration is unavailable`);return{stage:`credential_created`,recoveryOperationId:e.recoveryOperationId,walletId:e.walletId,relayUrl:e.relayUrl,target:e.target,prepared:e.prepared,custodyJson:e.custodyJson,recoveryCodeBytes:e.recoveryCodeBytes,replacement:{kind:`passkey`,registration:t.registration,credentialIdB64u:t.credentialIdB64u,factorSecret:t.factorSecret}}}function P(e,t){return{stage:`email_otp_verified`,recoveryOperationId:e.recoveryOperationId,walletId:e.walletId,relayUrl:e.relayUrl,target:e.target,prepared:e.prepared,custodyJson:e.custodyJson,recoveryCodeBytes:e.recoveryCodeBytes,replacement:t}}function F(e){let t=e.prepared.registration;if(!t)throw Error(`passkey recovery registration is unavailable`);return{replacementId:t.replacementId,walletAuthMethodId:t.walletAuthMethodId,factor:s({rpId:t.rpId,credentialIdB64u:e.replacement.credentialIdB64u}),factorSecret:e.replacement.factorSecret}}function I(e){let t=e.prepared.registration;if(!t)throw Error(`passkey recovery registration is unavailable`);return t.challengeId}function L(e,t){return{stage:`manifest_recovered`,recoveryOperationId:e.recoveryOperationId,walletId:e.walletId,relayUrl:e.relayUrl,target:e.target,prepared:e.prepared,custodyJson:e.custodyJson,recoveryCodeBytes:e.recoveryCodeBytes,replacement:e.replacement,recovered:t}}function R(e,t){return{stage:`manifest_recovered`,recoveryOperationId:e.recoveryOperationId,walletId:e.walletId,relayUrl:e.relayUrl,target:e.target,prepared:e.prepared,custodyJson:e.custodyJson,recoveryCodeBytes:e.recoveryCodeBytes,replacement:e.replacement,recovered:t}}function z(e,t){switch(e.stage){case`credential_created`:return L(e,t);case`email_otp_verified`:return R(e,t);default:return x(e)}}function B(e){return e.authMethod.kind===`passkey`}function V(e){return e.target.kind===`passkey`&&e.replacement.kind===`passkey`}function H(e){return e.target.kind===`google_email_otp`&&e.replacement.kind===`email_otp`}async function U(e){return await e.context.signingEngine.getSignerWorkerContext().requestWorkerOperation({kind:`emailOtp`,request:{type:`releaseWalletRecoveryEmailOtpFactor`,payload:{relayUrl:e.relayUrl,walletId:String(e.walletId),recoveryOperationId:e.recoveryOperationId,reservationId:e.reservationId}}})}async function W(e){let t=e.prepared.registration;if(!t)throw Error(`passkey recovery registration is unavailable`);return await m({relayUrl:e.relayUrl,walletId:e.walletId,reservationId:e.prepared.reservationId,recoveryOperationId:e.prepared.recoveryOperationId,targetDeviceId:e.prepared.targetDeviceId,targetAuthorityId:e.prepared.targetAuthorityId,targetWalletAuthMethodId:e.prepared.targetWalletAuthMethodId,challengeId:t.challengeId,replacementId:t.replacementId,webauthnRegistration:e.replacement.registration,replacementEnvelope:e.recovered.replacementEnvelope,ecdsaMaterialPossessionProofs:e.recovered.ecdsaKeySets.map(e=>({keySetId:e.entry.keySetId,proof:e.activation.possessionProof}))})}var G=class{constructor(e=null){this.rpc=e}#e=new Map;#t=new Map;#n=new Map;#r=new Map;#i=new Map;#a=D();async prepareWithCode(t){if(this.#c(),t.signal.aborted)return j();if(t.target.kind===`passkey`){let n=e(t.context.signingEngine.getRpId());if(!n.ok||n.value!==t.target.rpId)return j()}let n=null;try{n=u(t.recoveryCode);let e=i(await r(n));if(this.#a.has(e))return{kind:`consumed`};let o=T(e),s=this.#r.get(o),c=s?.expiresAtMs&&s.expiresAtMs>Date.now()?s.reservationId:w(),l=await p({relayUrl:t.relayUrl,target:t.target,recoveryCodeB64u:i(n),reservationId:c});if(l.kind!==`prepared`)return l.kind===`retryable_conflict`||l.kind===`transport_uncertain`?this.#r.set(o,{reservationId:c,expiresAtMs:Date.now()+3e5}):this.#r.delete(o),l;if(this.#r.delete(o),t.signal.aborted)return this.#r.set(o,{reservationId:l.reservationId,expiresAtMs:l.reservationExpiresAtMs}),j();let d=a(`wallet-recovery-operation`,24,`wallet recovery client operation handles`);return this.#e.set(d,{stage:`prepared`,recoveryOperationId:d,walletId:l.walletId,relayUrl:t.relayUrl,target:t.target,prepared:l,custodyJson:b({walletId:l.walletId,prepared:l}),recoveryCodeBytes:n}),this.#i.set(d,o),n=null,{kind:`prepared`,recoveryOperationId:d,walletId:l.walletId,target:t.target}}catch{return j()}finally{n?.fill(0)}}createPasskey(e){this.#c();let t=this.#e.get(e.operation.recoveryOperationId);if(!t||t.stage!==`prepared`||t.walletId!==e.operation.walletId||t.target.kind!==`passkey`||e.operation.target.kind!==`passkey`||t.target.rpId!==e.operation.target.rpId||this.#n.has(t.recoveryOperationId)||!t.prepared.registration)return Promise.resolve({kind:`refused`});let n=new AbortController;this.#n.set(t.recoveryOperationId,n);let r;try{r=e.context.signingEngine.createWalletRecoveryReplacementCredential({walletId:t.walletId,registration:t.prepared.registration,cancellation:{kind:`abort_signal`,signal:n.signal}})}catch{return this.cancel(t.recoveryOperationId),Promise.resolve({kind:`refused`})}return this.#s({current:t,credentialPromise:r,promptController:n})}async verifyGoogle(e){this.#c();let t=this.#e.get(e.operation.recoveryOperationId);if(!this.rpc||!t||t.stage!==`prepared`||t.target.kind!==`google_email_otp`||e.operation.target.kind!==`google_email_otp`||t.walletId!==e.operation.walletId||t.target.googleProvider!==e.operation.target.googleProvider||t.relayUrl!==e.relayUrl)return j();let n=t.prepared;if(!S(n))return j();try{let r=await this.rpc.verifyGoogle({relayUrl:t.relayUrl,recoveryOperationId:n.recoveryOperationId,reservationId:n.reservationId,idToken:e.idToken});if(r.kind!==`verified`)return r;if(r.recoveryOperationId!==n.recoveryOperationId)return{kind:`transport_uncertain`};let i={kind:`google_verified`,recoveryOperationId:t.recoveryOperationId,walletId:t.walletId,target:t.target,challengeId:r.challengeId,delivery:r.delivery,expiresAtMs:r.expiresAtMs},a={stage:`google_verified`,recoveryOperationId:t.recoveryOperationId,walletId:t.walletId,relayUrl:t.relayUrl,target:t.target,prepared:n,custodyJson:t.custodyJson,recoveryCodeBytes:t.recoveryCodeBytes,verification:i};return this.#e.set(a.recoveryOperationId,a),i}catch{return{kind:`transport_uncertain`}}}async verifyEmailOtp(e){this.#c();let n=this.#e.get(e.operation.recoveryOperationId);if(!this.rpc||!n||n.stage!==`google_verified`||n.walletId!==e.operation.walletId||n.target.kind!==`google_email_otp`||e.operation.target.kind!==`google_email_otp`||n.verification.challengeId!==e.operation.challengeId||e.challengeId!==e.operation.challengeId)return j();let r=t(e.challengeId);if(!r.ok)return j();try{let t=await this.rpc.verifyEmailOtp({relayUrl:n.relayUrl,recoveryOperationId:n.prepared.recoveryOperationId,reservationId:n.prepared.reservationId,challengeId:r.value,otpCode:e.otpCode});if(t.kind!==`verified`)return t;if(t.recoveryOperationId!==n.prepared.recoveryOperationId||t.challengeId!==e.challengeId)return{kind:`transport_uncertain`};let i=await U({context:e.context,relayUrl:n.relayUrl,walletId:n.walletId,recoveryOperationId:n.prepared.recoveryOperationId,reservationId:String(n.prepared.reservationId)});if(i.kind===`existing`){if(i.recoveryOperationId!==String(n.prepared.recoveryOperationId)||i.reservationId!==String(n.prepared.reservationId)||i.factorSecret32.byteLength!==32)return k(i.factorSecret32),{kind:`transport_uncertain`};let t=P(n,{kind:`email_otp`,factor:{replacementId:String(n.prepared.recoveryOperationId),walletAuthMethodId:n.prepared.targetWalletAuthMethodId,factor:o({enrollmentId:i.enrollmentId,enrollmentSealKeyVersion:i.enrollmentSealKeyVersion}),factorSecret:i.factorSecret32},enrollment:{kind:`existing`,enrollmentId:i.enrollmentId,enrollmentSealKeyVersion:i.enrollmentSealKeyVersion},providerSubject:i.providerSubject,verifiedEmail:i.verifiedEmail,registrationAuthorityId:e.challengeId});return this.#e.set(t.recoveryOperationId,t),{kind:`email_otp_verified`,recoveryOperationId:t.recoveryOperationId,walletId:t.walletId,target:t.target,challengeId:e.challengeId}}if(i.kind!==`create`)return i;if(i.recoveryOperationId!==String(n.prepared.recoveryOperationId)||i.reservationId!==String(n.prepared.reservationId))return{kind:`transport_uncertain`};let a=crypto.getRandomValues(new Uint8Array(32)),s=null;try{let t=await e.context.signingEngine.prepareEmailOtpRegistrationEnrollmentMaterialInternal({relayUrl:n.relayUrl,walletId:n.walletId,userId:i.providerSubject,clientSecret32:a});s=a.slice().buffer;let r=P(n,{kind:`email_otp`,factor:{replacementId:String(n.prepared.recoveryOperationId),walletAuthMethodId:n.prepared.targetWalletAuthMethodId,factor:o({enrollmentId:t.enrollmentId,enrollmentSealKeyVersion:t.enrollmentSealKeyVersion}),factorSecret:s},enrollment:{kind:`create`,enrollmentId:t.enrollmentId,providerSubject:i.providerSubject,verifiedEmail:i.verifiedEmail,material:t.emailOtpEnrollment},providerSubject:i.providerSubject,verifiedEmail:i.verifiedEmail,registrationAuthorityId:e.challengeId});return this.#e.set(r.recoveryOperationId,r),s=null,{kind:`email_otp_verified`,recoveryOperationId:r.recoveryOperationId,walletId:r.walletId,target:r.target,challengeId:e.challengeId}}finally{a.fill(0),s&&k(s)}}catch{return{kind:`refused`}}}async finalize(e){let t=String(e.operation.recoveryOperationId),n=this.#t.get(t);if(n)return n;let r=this.#o(e).finally(()=>{this.#t.delete(t)});return this.#t.set(t,r),r}async#o(e){this.#c();let t=C(this.#e.get(e.operation.recoveryOperationId),e.operation);if(!t)return j();try{if(t.stage===`credential_created`||t.stage===`email_otp_verified`){let n=t.stage===`credential_created`?F(t):t.replacement.factor,r=await e.context.signingEngine.recoverWalletCustodyManifest({walletId:t.walletId,prepared:t.prepared,custodyJson:t.custodyJson,recoveryCodeBytes:t.recoveryCodeBytes,replacementFactor:n,recoveryChallengeId:t.stage===`credential_created`?I(t):String(t.prepared.recoveryOperationId),relayUrl:t.relayUrl});if(this.#e.get(t.recoveryOperationId)!==t)return A(t),j();if(t.prepared.reservationExpiresAtMs<=Date.now())return this.cancel(t.recoveryOperationId),j();t.recoveryCodeBytes.fill(0),k(t.stage===`credential_created`?t.replacement.factorSecret:t.replacement.factor.factorSecret),t=z(t,r),this.#e.set(t.recoveryOperationId,t)}if(t.stage===`manifest_recovered`){if(!V(t)&&!H(t))return{kind:`transport_uncertain`};if(t.target.kind===`google_email_otp`&&!this.rpc)return{kind:`refused`};let e=await y({operation:t});if(this.#e.get(t.recoveryOperationId)!==t)return{kind:`transport_uncertain`};await c.putPendingWalletRecoveryCommit(e.pending);let r=V(t)?await W(t):this.rpc?await this.rpc.finalizeEmailOtp({relayUrl:t.relayUrl,walletId:t.walletId,recoveryOperationId:t.prepared.recoveryOperationId,reservationId:t.prepared.reservationId,targetDeviceId:t.prepared.targetDeviceId,targetAuthorityId:t.prepared.targetAuthorityId,targetWalletAuthMethodId:t.prepared.targetWalletAuthMethodId,expectedProviderSubject:t.replacement.providerSubject,expectedEmailHashHex:await n(t.replacement.verifiedEmail),expectedRegistrationAuthorityId:t.replacement.registrationAuthorityId,replacementEnvelope:t.recovered.replacementEnvelope,ecdsaMaterialPossessionProofs:t.recovered.ecdsaKeySets.map(e=>({keySetId:e.entry.keySetId,proof:e.activation.possessionProof})),emailOtpEnrollment:t.replacement.enrollment.kind===`create`?{kind:`create`,material:t.replacement.enrollment.material}:null}):{kind:`refused`};if(r.kind===`refused`)return await c.deletePendingWalletRecoveryCommit(t.prepared.recoveryOperationId),this.#e.get(t.recoveryOperationId)===t&&this.cancel(t.recoveryOperationId),r;if(this.#e.get(t.recoveryOperationId)!==t)return r.kind===`promoted`?{kind:`transport_uncertain`}:r;if(r.kind!==`promoted`)return r;if(t.replacement.kind===`passkey`&&r.authMethod.credentialIdB64u!==t.replacement.credentialIdB64u)return{kind:`transport_uncertain`};let i;if(f(e.payload)){if(!B(r))return{kind:`transport_uncertain`};i={kind:`passkey`,payload:e.payload,promotion:r}}else{if(B(r))return{kind:`transport_uncertain`};i={kind:`google_email_otp`,payload:e.payload,promotion:r}}await _({pending:await h({awaiting:e.pending,promotion:i}),payload:i.payload})}let r=this.#i.get(t.recoveryOperationId);return r&&O(this.#a,r),this.#e.delete(t.recoveryOperationId),this.#i.delete(t.recoveryOperationId),A(t),{kind:`ready_for_sign_in`,walletId:t.walletId}}catch{return{kind:`transport_uncertain`}}}async#s(e){try{let t=await e.credentialPromise;if(this.#e.get(e.current.recoveryOperationId)!==e.current||e.promptController.signal.aborted)return k(t.factorSecret),{kind:`dismissed`};if(e.current.prepared.reservationExpiresAtMs<=Date.now())return k(t.factorSecret),this.cancel(e.current.recoveryOperationId),{kind:`refused`};let n=N(e.current,t);return this.#e.set(n.recoveryOperationId,n),{kind:`credential_created`,recoveryOperationId:n.recoveryOperationId,walletId:n.walletId,target:n.target}}catch(t){return e.promptController.signal.aborted||M(t)?{kind:`dismissed`}:{kind:`transport_uncertain`}}finally{this.#n.get(e.current.recoveryOperationId)===e.promptController&&this.#n.delete(e.current.recoveryOperationId)}}cancel(e){this.#n.get(e)?.abort(),this.#n.delete(e);let t=this.#e.get(e);if(!t)return;let n=this.#i.get(e);this.#i.delete(e),n&&t.prepared.reservationExpiresAtMs>Date.now()&&this.#r.set(n,{reservationId:t.prepared.reservationId,expiresAtMs:t.prepared.reservationExpiresAtMs}),this.#e.delete(e),A(t)}#c(){let e=Date.now();for(let[t,n]of this.#r)n.expiresAtMs<=e&&this.#r.delete(t);for(let[t,n]of this.#e)n.prepared.reservationExpiresAtMs>e||(this.#n.get(t)?.abort(),this.#n.delete(t),this.#e.delete(t),this.#i.delete(t),A(n))}},K=class{#e=new G({verifyGoogle:v,verifyEmailOtp:g,finalizeEmailOtp:d});constructor(t,n){this.context=t,this.relayUrl=n;let r=e(t.signingEngine.getRpId());if(!r.ok)throw Error(`wallet recovery RP ID ${r.error.message}`);this.#t=r.value}#t;targetFor(e){switch(e){case`passkey`:return{kind:e,rpId:this.#t};case`google_email_otp`:return{kind:e,googleProvider:`google`}}}async prepare(e){let t=await this.#e.prepareWithCode({context:this.context,relayUrl:this.relayUrl,recoveryCode:e.recoveryCode,target:e.target,signal:e.signal});return t.kind===`prepared`?(t.target.kind,{kind:`hosted_recovery_prepared`,recoveryOperationId:t.recoveryOperationId,walletId:t.walletId,target:t.target}):t}createPasskey(e){return this.#n({kind:`prepared`,recoveryOperationId:e.recoveryOperationId,walletId:e.walletId,target:e.target})}async verifyGoogle(e,t){let n=await this.#e.verifyGoogle({relayUrl:this.relayUrl,operation:{kind:`prepared`,recoveryOperationId:e.recoveryOperationId,walletId:e.walletId,target:e.target},idToken:t});return n.kind===`google_verified`?{kind:`hosted_recovery_google_verified`,recoveryOperationId:n.recoveryOperationId,walletId:n.walletId,target:n.target,challengeId:n.challengeId,delivery:n.delivery,expiresAtMs:n.expiresAtMs}:n}async verifyEmailOtp(e,t){let n=await this.#e.verifyEmailOtp({context:this.context,operation:{kind:`google_verified`,recoveryOperationId:e.recoveryOperationId,walletId:e.walletId,target:e.target,challengeId:e.challengeId,delivery:e.delivery,expiresAtMs:e.expiresAtMs},challengeId:t.challengeId,otpCode:t.otpCode});return n.kind===`email_otp_verified`?{kind:`hosted_recovery_email_otp_verified`,recoveryOperationId:n.recoveryOperationId,walletId:n.walletId,target:n.target,challengeId:n.challengeId}:n}async finalize(e){return e.kind===`hosted_recovery_credential_created`?await this.#e.finalize({context:this.context,operation:{kind:`credential_created`,recoveryOperationId:e.recoveryOperationId,walletId:e.walletId,target:e.target}}):await this.#e.finalize({context:this.context,operation:{kind:`email_otp_verified`,recoveryOperationId:e.recoveryOperationId,walletId:e.walletId,target:e.target,challengeId:e.challengeId}})}async cancel(e){this.#e.cancel(e.recoveryOperationId)}async#n(e){let t=await this.#e.createPasskey({context:this.context,operation:e});return t.kind===`credential_created`?this.#r(t):t}#r(e){return{kind:`hosted_recovery_credential_created`,recoveryOperationId:e.recoveryOperationId,walletId:e.walletId,target:e.target}}};function q(e){return new K(e.context,e.relayUrl)}export{q as createHostedRecoveryPort};