@account-kit/signer 4.22.0 → 4.23.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 (62) hide show
  1. package/dist/esm/base.d.ts +183 -2
  2. package/dist/esm/base.js +352 -55
  3. package/dist/esm/base.js.map +1 -1
  4. package/dist/esm/client/base.d.ts +46 -5
  5. package/dist/esm/client/base.js.map +1 -1
  6. package/dist/esm/client/index.d.ts +51 -4
  7. package/dist/esm/client/index.js +201 -9
  8. package/dist/esm/client/index.js.map +1 -1
  9. package/dist/esm/client/types.d.ts +102 -1
  10. package/dist/esm/client/types.js.map +1 -1
  11. package/dist/esm/errors.d.ts +6 -0
  12. package/dist/esm/errors.js +18 -0
  13. package/dist/esm/errors.js.map +1 -1
  14. package/dist/esm/index.d.ts +1 -1
  15. package/dist/esm/index.js +1 -1
  16. package/dist/esm/index.js.map +1 -1
  17. package/dist/esm/session/manager.d.ts +2 -0
  18. package/dist/esm/session/manager.js.map +1 -1
  19. package/dist/esm/signer.d.ts +4 -2
  20. package/dist/esm/signer.js.map +1 -1
  21. package/dist/esm/types.d.ts +15 -1
  22. package/dist/esm/types.js +6 -0
  23. package/dist/esm/types.js.map +1 -1
  24. package/dist/esm/utils/parseMfaError.d.ts +2 -0
  25. package/dist/esm/utils/parseMfaError.js +15 -0
  26. package/dist/esm/utils/parseMfaError.js.map +1 -0
  27. package/dist/esm/version.d.ts +1 -1
  28. package/dist/esm/version.js +1 -1
  29. package/dist/esm/version.js.map +1 -1
  30. package/dist/types/base.d.ts +183 -2
  31. package/dist/types/base.d.ts.map +1 -1
  32. package/dist/types/client/base.d.ts +46 -5
  33. package/dist/types/client/base.d.ts.map +1 -1
  34. package/dist/types/client/index.d.ts +51 -4
  35. package/dist/types/client/index.d.ts.map +1 -1
  36. package/dist/types/client/types.d.ts +102 -1
  37. package/dist/types/client/types.d.ts.map +1 -1
  38. package/dist/types/errors.d.ts +6 -0
  39. package/dist/types/errors.d.ts.map +1 -1
  40. package/dist/types/index.d.ts +1 -1
  41. package/dist/types/index.d.ts.map +1 -1
  42. package/dist/types/session/manager.d.ts +2 -0
  43. package/dist/types/session/manager.d.ts.map +1 -1
  44. package/dist/types/signer.d.ts +4 -2
  45. package/dist/types/signer.d.ts.map +1 -1
  46. package/dist/types/types.d.ts +15 -1
  47. package/dist/types/types.d.ts.map +1 -1
  48. package/dist/types/utils/parseMfaError.d.ts +3 -0
  49. package/dist/types/utils/parseMfaError.d.ts.map +1 -0
  50. package/dist/types/version.d.ts +1 -1
  51. package/package.json +4 -4
  52. package/src/base.ts +421 -62
  53. package/src/client/base.ts +56 -2
  54. package/src/client/index.ts +225 -10
  55. package/src/client/types.ts +112 -1
  56. package/src/errors.ts +11 -1
  57. package/src/index.ts +5 -1
  58. package/src/session/manager.ts +6 -1
  59. package/src/signer.ts +6 -1
  60. package/src/types.ts +16 -0
  61. package/src/utils/parseMfaError.ts +15 -0
  62. package/src/version.ts +1 -1
@@ -2,7 +2,7 @@ import { BaseError } from "@aa-sdk/core";
2
2
  import { z } from "zod";
3
3
  import type { AuthParams } from "../signer.js";
4
4
  import { BaseSignerClient } from "./base.js";
5
- import type { AlchemySignerClientEvents, AuthenticatingEventMetadata, CreateAccountParams, CredentialCreationOptionOverrides, EmailAuthParams, ExportWalletParams, OauthConfig, OtpParams, User } from "./types.js";
5
+ import type { AlchemySignerClientEvents, AuthenticatingEventMetadata, CreateAccountParams, CredentialCreationOptionOverrides, EmailAuthParams, ExportWalletParams, OauthConfig, OtpParams, User, MfaFactor, EnableMfaParams, EnableMfaResult, VerifyMfaParams, RemoveMfaParams, SubmitOtpCodeResponse, ValidateMultiFactorsParams } from "./types.js";
6
6
  export declare const AlchemySignerClientParamsSchema: z.ZodObject<{
7
7
  connection: z.ZodUnion<[z.ZodObject<{
8
8
  rpcUrl: z.ZodOptional<z.ZodNever>;
@@ -203,6 +203,7 @@ export declare class AlchemySignerWebClient extends BaseSignerClient<ExportWalle
203
203
  initEmailAuth: (params: Omit<EmailAuthParams, "targetPublicKey">) => Promise<{
204
204
  orgId: string;
205
205
  otpId?: string | undefined;
206
+ multiFactors?: MfaFactor[] | undefined;
206
207
  }>;
207
208
  /**
208
209
  * Authenticates using an OTP code which was previously received via email.
@@ -230,9 +231,7 @@ export declare class AlchemySignerWebClient extends BaseSignerClient<ExportWalle
230
231
  * @param {Omit<OtpParams, "targetPublicKey">} args The parameters for the OTP request, excluding the target public key.
231
232
  * @returns {Promise<{ bundle: string }>} A promise that resolves to an object containing the credential bundle.
232
233
  */
233
- submitOtpCode(args: Omit<OtpParams, "targetPublicKey">): Promise<{
234
- bundle: string;
235
- }>;
234
+ submitOtpCode(args: Omit<OtpParams, "targetPublicKey">): Promise<SubmitOtpCodeResponse>;
236
235
  /**
237
236
  * Completes auth for the user by injecting a credential bundle and retrieving
238
237
  * the user information based on the provided organization ID. Emits events
@@ -438,6 +437,54 @@ export declare class AlchemySignerWebClient extends BaseSignerClient<ExportWalle
438
437
  };
439
438
  }>;
440
439
  protected getOauthConfig: () => Promise<OauthConfig>;
440
+ /**
441
+ * Retrieves the list of MFA factors configured for the current user.
442
+ *
443
+ * @returns {Promise<{ multiFactors: MfaFactor[] }>} A promise that resolves to an array of configured MFA factors
444
+ * @throws {NotAuthenticatedError} If no user is authenticated
445
+ */
446
+ getMfaFactors: () => Promise<{
447
+ multiFactors: MfaFactor[];
448
+ }>;
449
+ /**
450
+ * Initiates the setup of a new MFA factor for the current user. Mfa will need to be verified before it is active.
451
+ *
452
+ * @param {EnableMfaParams} params The parameters required to enable a new MFA factor
453
+ * @returns {Promise<EnableMfaResult>} A promise that resolves to the factor setup information
454
+ * @throws {NotAuthenticatedError} If no user is authenticated
455
+ * @throws {Error} If an unsupported factor type is provided
456
+ */
457
+ addMfa: (params: EnableMfaParams) => Promise<EnableMfaResult>;
458
+ /**
459
+ * Verifies a newly created MFA factor to complete the setup process.
460
+ *
461
+ * @param {VerifyMfaParams} params The parameters required to verify the MFA factor
462
+ * @returns {Promise<{ multiFactors: MfaFactor[] }>} A promise that resolves to the updated list of MFA factors
463
+ * @throws {NotAuthenticatedError} If no user is authenticated
464
+ */
465
+ verifyMfa: (params: VerifyMfaParams) => Promise<{
466
+ multiFactors: MfaFactor[];
467
+ }>;
468
+ /**
469
+ * Removes existing MFA factors by ID.
470
+ *
471
+ * @param {RemoveMfaParams} params The parameters specifying which factors to disable
472
+ * @returns {Promise<{ multiFactors: MfaFactor[] }>} A promise that resolves to the updated list of MFA factors
473
+ * @throws {NotAuthenticatedError} If no user is authenticated
474
+ */
475
+ removeMfa: (params: RemoveMfaParams) => Promise<{
476
+ multiFactors: MfaFactor[];
477
+ }>;
478
+ /**
479
+ * Validates multiple MFA factors using the provided encrypted payload and MFA codes.
480
+ *
481
+ * @param {ValidateMultiFactorsParams} params The validation parameters
482
+ * @returns {Promise<{ bundle: string }>} A promise that resolves to an object containing the credential bundle
483
+ * @throws {Error} If no credential bundle is returned from the server
484
+ */
485
+ validateMultiFactors(params: ValidateMultiFactorsParams): Promise<{
486
+ bundle: string;
487
+ }>;
441
488
  }
442
489
  /**
443
490
  * This error is thrown when the OAuth flow is cancelled because the auth popup
@@ -6,7 +6,16 @@ import { z } from "zod";
6
6
  import { base64UrlEncode } from "../utils/base64UrlEncode.js";
7
7
  import { generateRandomBuffer } from "../utils/generateRandomBuffer.js";
8
8
  import { BaseSignerClient } from "./base.js";
9
+ import { MfaRequiredError, NotAuthenticatedError } from "../errors.js";
10
+ import { parseMfaError } from "../utils/parseMfaError.js";
9
11
  const CHECK_CLOSE_INTERVAL = 500;
12
+ const MFA_PAYLOAD = {
13
+ GET: "get_mfa",
14
+ ADD: "add_mfa",
15
+ DELETE: "delete_mfas",
16
+ VERIFY: "verify_mfa",
17
+ LIST: "list_mfas",
18
+ };
10
19
  export const AlchemySignerClientParamsSchema = z.object({
11
20
  connection: ConnectionConfigSchema,
12
21
  iframeConfig: z.object({
@@ -180,13 +189,25 @@ export class AlchemySignerWebClient extends BaseSignerClient {
180
189
  this.eventEmitter.emit("authenticating", { type: "otp" });
181
190
  const { email, emailMode, expirationSeconds } = params;
182
191
  const publicKey = await this.initIframeStamper();
183
- return this.request("/v1/auth", {
184
- email,
185
- emailMode,
186
- targetPublicKey: publicKey,
187
- expirationSeconds,
188
- redirectParams: params.redirectParams?.toString(),
189
- });
192
+ try {
193
+ return await this.request("/v1/auth", {
194
+ email,
195
+ emailMode,
196
+ targetPublicKey: publicKey,
197
+ expirationSeconds,
198
+ redirectParams: params.redirectParams?.toString(),
199
+ multiFactors: params.multiFactors,
200
+ });
201
+ }
202
+ catch (error) {
203
+ const multiFactors = parseMfaError(error);
204
+ // If MFA is required, and emailMode is Magic Link, the user must submit mfa with the request or
205
+ // the the server will return an error with the required mfa factors.
206
+ if (multiFactors) {
207
+ throw new MfaRequiredError(multiFactors);
208
+ }
209
+ throw error;
210
+ }
190
211
  }
191
212
  });
192
213
  /**
@@ -603,6 +624,139 @@ export class AlchemySignerWebClient extends BaseSignerClient {
603
624
  return this.request("/v1/prepare-oauth", { nonce });
604
625
  }
605
626
  });
627
+ /**
628
+ * Retrieves the list of MFA factors configured for the current user.
629
+ *
630
+ * @returns {Promise<{ multiFactors: MfaFactor[] }>} A promise that resolves to an array of configured MFA factors
631
+ * @throws {NotAuthenticatedError} If no user is authenticated
632
+ */
633
+ Object.defineProperty(this, "getMfaFactors", {
634
+ enumerable: true,
635
+ configurable: true,
636
+ writable: true,
637
+ value: async () => {
638
+ if (!this.user) {
639
+ throw new NotAuthenticatedError();
640
+ }
641
+ const stampedRequest = await this.turnkeyClient.stampSignRawPayload({
642
+ organizationId: this.user.orgId,
643
+ type: "ACTIVITY_TYPE_SIGN_RAW_PAYLOAD_V2",
644
+ timestampMs: Date.now().toString(),
645
+ parameters: {
646
+ encoding: "PAYLOAD_ENCODING_HEXADECIMAL",
647
+ hashFunction: "HASH_FUNCTION_NO_OP",
648
+ payload: MFA_PAYLOAD.LIST,
649
+ signWith: this.user.address,
650
+ },
651
+ });
652
+ return this.request("/v1/auth-list-multi-factors", {
653
+ stampedRequest,
654
+ });
655
+ }
656
+ });
657
+ /**
658
+ * Initiates the setup of a new MFA factor for the current user. Mfa will need to be verified before it is active.
659
+ *
660
+ * @param {EnableMfaParams} params The parameters required to enable a new MFA factor
661
+ * @returns {Promise<EnableMfaResult>} A promise that resolves to the factor setup information
662
+ * @throws {NotAuthenticatedError} If no user is authenticated
663
+ * @throws {Error} If an unsupported factor type is provided
664
+ */
665
+ Object.defineProperty(this, "addMfa", {
666
+ enumerable: true,
667
+ configurable: true,
668
+ writable: true,
669
+ value: async (params) => {
670
+ if (!this.user) {
671
+ throw new NotAuthenticatedError();
672
+ }
673
+ const stampedRequest = await this.turnkeyClient.stampSignRawPayload({
674
+ organizationId: this.user.orgId,
675
+ type: "ACTIVITY_TYPE_SIGN_RAW_PAYLOAD_V2",
676
+ timestampMs: Date.now().toString(),
677
+ parameters: {
678
+ encoding: "PAYLOAD_ENCODING_HEXADECIMAL",
679
+ hashFunction: "HASH_FUNCTION_NO_OP",
680
+ payload: MFA_PAYLOAD.ADD,
681
+ signWith: this.user.address,
682
+ },
683
+ });
684
+ switch (params.multiFactorType) {
685
+ case "totp":
686
+ return this.request("/v1/auth-request-multi-factor", {
687
+ stampedRequest,
688
+ multiFactorType: params.multiFactorType,
689
+ });
690
+ default:
691
+ throw new Error(`Unsupported MFA factor type: ${params.multiFactorType}`);
692
+ }
693
+ }
694
+ });
695
+ /**
696
+ * Verifies a newly created MFA factor to complete the setup process.
697
+ *
698
+ * @param {VerifyMfaParams} params The parameters required to verify the MFA factor
699
+ * @returns {Promise<{ multiFactors: MfaFactor[] }>} A promise that resolves to the updated list of MFA factors
700
+ * @throws {NotAuthenticatedError} If no user is authenticated
701
+ */
702
+ Object.defineProperty(this, "verifyMfa", {
703
+ enumerable: true,
704
+ configurable: true,
705
+ writable: true,
706
+ value: async (params) => {
707
+ if (!this.user) {
708
+ throw new NotAuthenticatedError();
709
+ }
710
+ const stampedRequest = await this.turnkeyClient.stampSignRawPayload({
711
+ organizationId: this.user.orgId,
712
+ type: "ACTIVITY_TYPE_SIGN_RAW_PAYLOAD_V2",
713
+ timestampMs: Date.now().toString(),
714
+ parameters: {
715
+ encoding: "PAYLOAD_ENCODING_HEXADECIMAL",
716
+ hashFunction: "HASH_FUNCTION_NO_OP",
717
+ payload: MFA_PAYLOAD.VERIFY,
718
+ signWith: this.user.address,
719
+ },
720
+ });
721
+ return this.request("/v1/auth-verify-multi-factor", {
722
+ stampedRequest,
723
+ multiFactorId: params.multiFactorId,
724
+ multiFactorCode: params.multiFactorCode,
725
+ });
726
+ }
727
+ });
728
+ /**
729
+ * Removes existing MFA factors by ID.
730
+ *
731
+ * @param {RemoveMfaParams} params The parameters specifying which factors to disable
732
+ * @returns {Promise<{ multiFactors: MfaFactor[] }>} A promise that resolves to the updated list of MFA factors
733
+ * @throws {NotAuthenticatedError} If no user is authenticated
734
+ */
735
+ Object.defineProperty(this, "removeMfa", {
736
+ enumerable: true,
737
+ configurable: true,
738
+ writable: true,
739
+ value: async (params) => {
740
+ if (!this.user) {
741
+ throw new NotAuthenticatedError();
742
+ }
743
+ const stampedRequest = await this.turnkeyClient.stampSignRawPayload({
744
+ organizationId: this.user.orgId,
745
+ type: "ACTIVITY_TYPE_SIGN_RAW_PAYLOAD_V2",
746
+ timestampMs: Date.now().toString(),
747
+ parameters: {
748
+ encoding: "PAYLOAD_ENCODING_HEXADECIMAL",
749
+ hashFunction: "HASH_FUNCTION_NO_OP",
750
+ payload: MFA_PAYLOAD.DELETE,
751
+ signWith: this.user.address,
752
+ },
753
+ });
754
+ return this.request("/v1/auth-delete-multi-factors", {
755
+ stampedRequest,
756
+ multiFactorIds: params.multiFactorIds,
757
+ });
758
+ }
759
+ });
606
760
  this.iframeStamper = iframeStamper;
607
761
  this.iframeContainerId = iframeConfig.iframeContainerId;
608
762
  this.webauthnStamper = new WebauthnStamper({
@@ -639,11 +793,49 @@ export class AlchemySignerWebClient extends BaseSignerClient {
639
793
  async submitOtpCode(args) {
640
794
  this.eventEmitter.emit("authenticating", { type: "otpVerify" });
641
795
  const targetPublicKey = await this.initIframeStamper();
642
- const { credentialBundle } = await this.request("/v1/otp", {
796
+ const response = await this.request("/v1/otp", {
643
797
  ...args,
644
798
  targetPublicKey,
645
799
  });
646
- return { bundle: credentialBundle };
800
+ if ("credentialBundle" in response && response.credentialBundle) {
801
+ return {
802
+ mfaRequired: false,
803
+ bundle: response.credentialBundle,
804
+ };
805
+ }
806
+ // If the server says "MFA_REQUIRED", pass that data back to the caller:
807
+ if (response.status === "MFA_REQUIRED" &&
808
+ response.encryptedPayload &&
809
+ response.multiFactors) {
810
+ return {
811
+ mfaRequired: true,
812
+ encryptedPayload: response.encryptedPayload,
813
+ multiFactors: response.multiFactors,
814
+ };
815
+ }
816
+ // Otherwise, it's truly an error:
817
+ throw new Error("Failed to submit OTP code. Server did not return required fields.");
818
+ }
819
+ /**
820
+ * Validates multiple MFA factors using the provided encrypted payload and MFA codes.
821
+ *
822
+ * @param {ValidateMultiFactorsParams} params The validation parameters
823
+ * @returns {Promise<{ bundle: string }>} A promise that resolves to an object containing the credential bundle
824
+ * @throws {Error} If no credential bundle is returned from the server
825
+ */
826
+ async validateMultiFactors(params) {
827
+ // Send the encryptedPayload plus TOTP codes, etc:
828
+ const response = await this.request("/v1/auth-validate-multi-factors", {
829
+ encryptedPayload: params.encryptedPayload,
830
+ multiFactors: params.multiFactors,
831
+ });
832
+ // The server is expected to return the *decrypted* payload in `response.payload.credentialBundle`
833
+ if (!response.payload || !response.payload.credentialBundle) {
834
+ throw new Error("Request to validateMultiFactors did not return a credential bundle");
835
+ }
836
+ return {
837
+ bundle: response.payload.credentialBundle,
838
+ };
647
839
  }
648
840
  }
649
841
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/client/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,sBAAsB,EAAE,MAAM,cAAc,CAAC;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mBAAO,kBAAkB;WAAC;IACrC,CAAC;CAAA","sourcesContent":["import { BaseError, ConnectionConfigSchema } from \"@aa-sdk/core\";\nimport { getWebAuthnAttestation } from \"@turnkey/http\";\nimport { IframeStamper } from \"@turnkey/iframe-stamper\";\nimport { WebauthnStamper } from \"@turnkey/webauthn-stamper\";\nimport { z } from \"zod\";\nimport type { AuthParams } from \"../signer.js\";\nimport { base64UrlEncode } from \"../utils/base64UrlEncode.js\";\nimport { generateRandomBuffer } from \"../utils/generateRandomBuffer.js\";\nimport { BaseSignerClient } from \"./base.js\";\nimport type {\n AlchemySignerClientEvents,\n AuthenticatingEventMetadata,\n CreateAccountParams,\n CredentialCreationOptionOverrides,\n EmailAuthParams,\n ExportWalletParams,\n OauthConfig,\n OtpParams,\n User,\n} from \"./types.js\";\n\nconst CHECK_CLOSE_INTERVAL = 500;\n\nexport const AlchemySignerClientParamsSchema = z.object({\n connection: ConnectionConfigSchema,\n iframeConfig: z.object({\n iframeElementId: z.string().default(\"turnkey-iframe\"),\n iframeContainerId: z.string(),\n }),\n rpId: z.string().optional(),\n rootOrgId: z\n .string()\n .optional()\n .default(\"24c1acf5-810f-41e0-a503-d5d13fa8e830\"),\n oauthCallbackUrl: z\n .string()\n .optional()\n .default(\"https://signer.alchemy.com/callback\"),\n enablePopupOauth: z.boolean().optional().default(false),\n});\n\nexport type AlchemySignerClientParams = z.input<\n typeof AlchemySignerClientParamsSchema\n>;\n\n/**\n * A lower level client used by the AlchemySigner used to communicate with\n * Alchemy's signer service.\n */\nexport class AlchemySignerWebClient extends BaseSignerClient<ExportWalletParams> {\n private iframeStamper: IframeStamper;\n private webauthnStamper: WebauthnStamper;\n oauthCallbackUrl: string;\n iframeContainerId: string;\n\n /**\n * Initializes a new instance with the given parameters, setting up the connection, iframe configuration, and WebAuthn stamper.\n *\n * @example\n * ```ts\n * import { AlchemySignerWebClient } from \"@account-kit/signer\";\n *\n * const client = new AlchemySignerWebClient({\n * connection: {\n * apiKey: \"your-api-key\",\n * },\n * iframeConfig: {\n * iframeContainerId: \"signer-iframe-container\",\n * },\n * });\n * ```\n *\n * @param {AlchemySignerClientParams} params the parameters required to initialize the client\n * @param {ConnectionConfig} params.connection The connection details needed to connect to the service\n * @param {{ iframeElementId?: string; iframeContainerId: string }} params.iframeConfig The configuration details for setting up the iframe stamper\n * @param {string} params.rpId The relying party ID, defaulting to the current hostname if not provided\n * @param {string} params.rootOrgId The root organization ID\n */\n constructor(params: AlchemySignerClientParams) {\n const { connection, iframeConfig, rpId, rootOrgId, oauthCallbackUrl } =\n AlchemySignerClientParamsSchema.parse(params);\n\n const iframeStamper = new IframeStamper({\n iframeElementId: iframeConfig.iframeElementId,\n iframeUrl: \"https://auth.turnkey.com\",\n iframeContainer: document.getElementById(iframeConfig.iframeContainerId),\n });\n\n super({\n connection,\n rootOrgId,\n stamper: iframeStamper,\n });\n\n this.iframeStamper = iframeStamper;\n this.iframeContainerId = iframeConfig.iframeContainerId;\n\n this.webauthnStamper = new WebauthnStamper({\n rpId: rpId ?? window.location.hostname,\n });\n\n this.oauthCallbackUrl = oauthCallbackUrl;\n }\n\n /**\n * Authenticates the user by either email or passkey account creation flow. Emits events during the process.\n *\n * @example\n * ```ts\n * import { AlchemySignerWebClient } from \"@account-kit/signer\";\n *\n * const client = new AlchemySignerWebClient({\n * connection: {\n * apiKey: \"your-api-key\",\n * },\n * iframeConfig: {\n * iframeContainerId: \"signer-iframe-container\",\n * },\n * });\n *\n * const account = await client.createAccount({ type: \"email\", email: \"you@mail.com\" });\n * ```\n *\n * @param {CreateAccountParams} params The parameters for creating an account, including the type (email or passkey) and additional details.\n * @returns {Promise<SignupResponse>} A promise that resolves with the response object containing the account creation result.\n */\n public override createAccount = async (params: CreateAccountParams) => {\n if (params.type === \"email\") {\n this.eventEmitter.emit(\"authenticating\", { type: \"otp\" });\n const { email, emailMode, expirationSeconds } = params;\n const publicKey = await this.initIframeStamper();\n\n const response = await this.request(\"/v1/signup\", {\n email,\n emailMode,\n targetPublicKey: publicKey,\n expirationSeconds,\n redirectParams: params.redirectParams?.toString(),\n });\n\n return response;\n }\n\n this.eventEmitter.emit(\"authenticating\", { type: \"passkey\" });\n // Passkey account creation flow\n const { attestation, challenge } = await this.getWebAuthnAttestation(\n params.creationOpts,\n { username: \"email\" in params ? params.email : params.username }\n );\n\n const result = await this.request(\"/v1/signup\", {\n passkey: {\n challenge: base64UrlEncode(challenge),\n attestation,\n },\n email: \"email\" in params ? params.email : undefined,\n });\n\n this.user = {\n orgId: result.orgId,\n address: result.address!,\n userId: result.userId!,\n credentialId: attestation.credentialId,\n };\n this.initWebauthnStamper(this.user);\n this.eventEmitter.emit(\"connectedPasskey\", this.user);\n\n return result;\n };\n\n /**\n * Begin authenticating a user with their email and an expiration time for the authentication request. Initializes the iframe stamper to get the target public key.\n * This method sends an email to the user to complete their login\n *\n * @example\n * ```ts\n * import { AlchemySignerWebClient } from \"@account-kit/signer\";\n *\n * const client = new AlchemySignerWebClient({\n * connection: {\n * apiKey: \"your-api-key\",\n * },\n * iframeConfig: {\n * iframeContainerId: \"signer-iframe-container\",\n * },\n * });\n *\n * const account = await client.initEmailAuth({ email: \"you@mail.com\" });\n * ```\n *\n * @param {Omit<EmailAuthParams, \"targetPublicKey\">} params The parameters for email authentication, excluding the target public key\n * @returns {Promise<any>} The response from the authentication request\n */\n public override initEmailAuth = async (\n params: Omit<EmailAuthParams, \"targetPublicKey\">\n ) => {\n this.eventEmitter.emit(\"authenticating\", { type: \"otp\" });\n const { email, emailMode, expirationSeconds } = params;\n const publicKey = await this.initIframeStamper();\n\n return this.request(\"/v1/auth\", {\n email,\n emailMode,\n targetPublicKey: publicKey,\n expirationSeconds,\n redirectParams: params.redirectParams?.toString(),\n });\n };\n\n /**\n * Authenticates using an OTP code which was previously received via email.\n *\n * @example\n * ```ts\n * import { AlchemySignerWebClient } from \"@account-kit/signer\";\n *\n * const client = new AlchemySignerWebClient({\n * connection: {\n * apiKey: \"your-api-key\",\n * },\n * iframeConfig: {\n * iframeContainerId: \"signer-iframe-container\",\n * },\n * });\n *\n * const account = await client.submitOtpCode({\n * orgId: \"user-org-id\",\n * otpId: \"opt-returned-from-initEmailAuth\",\n * otpCode: \"otp-code-from-email\",\n * });\n * ```\n *\n * @param {Omit<OtpParams, \"targetPublicKey\">} args The parameters for the OTP request, excluding the target public key.\n * @returns {Promise<{ bundle: string }>} A promise that resolves to an object containing the credential bundle.\n */\n public override async submitOtpCode(\n args: Omit<OtpParams, \"targetPublicKey\">\n ): Promise<{ bundle: string }> {\n this.eventEmitter.emit(\"authenticating\", { type: \"otpVerify\" });\n const targetPublicKey = await this.initIframeStamper();\n const { credentialBundle } = await this.request(\"/v1/otp\", {\n ...args,\n targetPublicKey,\n });\n return { bundle: credentialBundle };\n }\n\n /**\n * Completes auth for the user by injecting a credential bundle and retrieving\n * the user information based on the provided organization ID. Emits events\n * during the process.\n *\n * @example\n * ```ts\n * import { AlchemySignerWebClient } from \"@account-kit/signer\";\n *\n * const client = new AlchemySignerWebClient({\n * connection: {\n * apiKey: \"your-api-key\",\n * },\n * iframeConfig: {\n * iframeContainerId: \"signer-iframe-container\",\n * },\n * });\n *\n * const account = await client.completeAuthWithBundle({ orgId: \"user-org-id\", bundle: \"bundle-from-email\", connectedEventName: \"connectedEmail\" });\n * ```\n *\n * @param {{ bundle: string; orgId: string, connectedEventName: keyof AlchemySignerClientEvents, idToken?: string }} config\n * The configuration object for the authentication function containing the\n * credential bundle to inject and the organization id associated with the\n * user, as well as the event to be emitted on success and optionally an OIDC\n * ID token with extra user information\n * @returns {Promise<User>} A promise that resolves to the authenticated user\n * information\n */\n public override completeAuthWithBundle = async ({\n bundle,\n orgId,\n connectedEventName,\n idToken,\n authenticatingType,\n }: {\n bundle: string;\n orgId: string;\n connectedEventName: keyof AlchemySignerClientEvents;\n authenticatingType: AuthenticatingEventMetadata[\"type\"];\n idToken?: string;\n }): Promise<User> => {\n this.eventEmitter.emit(\"authenticating\", { type: authenticatingType });\n await this.initIframeStamper();\n\n const result = await this.iframeStamper.injectCredentialBundle(bundle);\n\n if (!result) {\n throw new Error(\"Failed to inject credential bundle\");\n }\n\n const user = await this.whoami(orgId, idToken);\n\n this.eventEmitter.emit(connectedEventName, user, bundle);\n\n return user;\n };\n\n /**\n * Asynchronously handles the authentication process using WebAuthn Stamper. If a user is provided, sets the user and returns it. Otherwise, retrieves the current user and initializes the WebAuthn stamper.\n *\n * @example\n * ```ts\n * import { AlchemySignerWebClient } from \"@account-kit/signer\";\n *\n * const client = new AlchemySignerWebClient({\n * connection: {\n * apiKey: \"your-api-key\",\n * },\n * iframeConfig: {\n * iframeContainerId: \"signer-iframe-container\",\n * },\n * });\n *\n * const account = await client.lookupUserWithPasskey();\n * ```\n *\n * @param {User} [user] An optional user object to authenticate\n * @returns {Promise<User>} A promise that resolves to the authenticated user object\n */\n public override lookupUserWithPasskey = async (\n user: User | undefined = undefined\n ) => {\n this.eventEmitter.emit(\"authenticating\", { type: \"passkey\" });\n await this.initWebauthnStamper(user);\n if (user) {\n this.user = user;\n this.eventEmitter.emit(\"connectedPasskey\", user);\n return user;\n }\n\n const result = await this.whoami(this.rootOrg);\n await this.initWebauthnStamper(result);\n this.eventEmitter.emit(\"connectedPasskey\", result);\n\n return result;\n };\n\n /**\n * Initiates the export of a wallet by creating an iframe stamper and calling the appropriate export function.\n * The export can be based on a seed phrase or a private key.\n *\n * @example\n * ```ts\n * import { AlchemySignerWebClient } from \"@account-kit/signer\";\n *\n * const client = new AlchemySignerWebClient({\n * connection: {\n * apiKey: \"your-api-key\",\n * },\n * iframeConfig: {\n * iframeContainerId: \"signer-iframe-container\",\n * },\n * });\n *\n * const account = await client.exportWallet({\n * iframeContainerId: \"export-iframe-container\",\n * });\n * ```\n *\n * @param {ExportWalletParams} config The parameters for exporting the wallet\n * @param {string} config.iframeContainerId The ID of the container element that will hold the iframe stamper\n * @param {string} [config.iframeElementId] Optional ID for the iframe element\n * @returns {Promise<void>} A promise that resolves when the export process is complete\n */\n public override exportWallet = async ({\n iframeContainerId,\n iframeElementId = \"turnkey-export-iframe\",\n }: ExportWalletParams) => {\n const exportWalletIframeStamper = new IframeStamper({\n iframeContainer: document.getElementById(iframeContainerId),\n iframeElementId: iframeElementId,\n iframeUrl: \"https://export.turnkey.com\",\n });\n await exportWalletIframeStamper.init();\n\n if (this.turnkeyClient.stamper === this.iframeStamper) {\n return this.exportWalletInner({\n exportStamper: exportWalletIframeStamper,\n exportAs: \"SEED_PHRASE\",\n });\n }\n\n return this.exportWalletInner({\n exportStamper: exportWalletIframeStamper,\n exportAs: \"PRIVATE_KEY\",\n });\n };\n\n /**\n * Asynchronous function that clears the user and resets the iframe stamper.\n *\n * @example\n * ```ts\n * import { AlchemySignerWebClient } from \"@account-kit/signer\";\n *\n * const client = new AlchemySignerWebClient({\n * connection: {\n * apiKey: \"your-api-key\",\n * },\n * iframeConfig: {\n * iframeContainerId: \"signer-iframe-container\",\n * },\n * });\n *\n * const account = await client.disconnect();\n * ```\n */\n public override disconnect = async () => {\n this.user = undefined;\n this.iframeStamper.clear();\n await this.iframeStamper.init();\n };\n\n /**\n * Redirects the user to the OAuth provider URL based on the provided arguments. This function will always reject after 1 second if the redirection does not occur.\n *\n * @example\n * ```ts\n * import { AlchemySignerWebClient } from \"@account-kit/signer\";\n *\n * const client = new AlchemySignerWebClient({\n * connection: {\n * apiKey: \"your-api-key\",\n * },\n * iframeConfig: {\n * iframeContainerId: \"signer-iframe-container\",\n * },\n * });\n *\n * await client.oauthWithRedirect({\n * type: \"oauth\",\n * authProviderId: \"google\",\n * mode: \"redirect\",\n * redirectUrl: \"/\",\n * });\n * ```\n *\n * @param {Extract<AuthParams, { type: \"oauth\"; mode: \"redirect\" }>} args The arguments required to obtain the OAuth provider URL\n * @returns {Promise<never>} A promise that will never resolve, only reject if the redirection fails\n */\n public override oauthWithRedirect = async (\n args: Extract<AuthParams, { type: \"oauth\"; mode: \"redirect\" }>\n ): Promise<never> => {\n const turnkeyPublicKey = await this.initIframeStamper();\n\n const oauthParams = args;\n const providerUrl = await this.getOauthProviderUrl({\n oauthParams,\n turnkeyPublicKey,\n oauthCallbackUrl: this.oauthCallbackUrl,\n });\n\n window.location.href = providerUrl;\n return new Promise((_, reject) =>\n setTimeout(() => reject(\"Failed to redirect to OAuth provider\"), 1000)\n );\n };\n\n /**\n * Initiates an OAuth authentication flow in a popup window and returns the authenticated user.\n *\n * @example\n * ```ts\n * import { AlchemySignerWebClient } from \"@account-kit/signer\";\n *\n * const client = new AlchemySignerWebClient({\n * connection: {\n * apiKey: \"your-api-key\",\n * },\n * iframeConfig: {\n * iframeContainerId: \"signer-iframe-container\",\n * },\n * });\n *\n * const user = await client.oauthWithPopup({\n * type: \"oauth\",\n * authProviderId: \"google\",\n * mode: \"popup\"\n * });\n * ```\n *\n * @param {Extract<AuthParams, { type: \"oauth\"; mode: \"popup\" }>} args The authentication parameters specifying OAuth type and popup mode\n * @returns {Promise<User>} A promise that resolves to a `User` object containing the authenticated user information\n */\n public override oauthWithPopup = async (\n args: Extract<AuthParams, { type: \"oauth\"; mode: \"popup\" }>\n ): Promise<User> => {\n const turnkeyPublicKey = await this.initIframeStamper();\n const oauthParams = args;\n const providerUrl = await this.getOauthProviderUrl({\n oauthParams,\n turnkeyPublicKey,\n oauthCallbackUrl: this.oauthCallbackUrl,\n });\n const popup = window.open(\n providerUrl,\n \"_blank\",\n \"popup,width=500,height=600\"\n );\n const eventEmitter = this.eventEmitter;\n return new Promise((resolve, reject) => {\n const handleMessage = (event: MessageEvent) => {\n if (!event.data) {\n return;\n }\n const {\n alchemyBundle: bundle,\n alchemyOrgId: orgId,\n alchemyIdToken: idToken,\n alchemyIsSignup: isSignup,\n alchemyError,\n } = event.data;\n if (bundle && orgId && idToken) {\n cleanup();\n popup?.close();\n this.completeAuthWithBundle({\n bundle,\n orgId,\n connectedEventName: \"connectedOauth\",\n idToken,\n authenticatingType: \"oauth\",\n }).then((user) => {\n if (isSignup) {\n eventEmitter.emit(\"newUserSignup\");\n }\n\n resolve(user);\n }, reject);\n } else if (alchemyError) {\n cleanup();\n popup?.close();\n reject(new OauthFailedError(alchemyError));\n }\n };\n\n window.addEventListener(\"message\", handleMessage);\n\n const checkCloseIntervalId = setInterval(() => {\n if (popup?.closed) {\n cleanup();\n reject(new OauthCancelledError());\n }\n }, CHECK_CLOSE_INTERVAL);\n\n const cleanup = () => {\n window.removeEventListener(\"message\", handleMessage);\n clearInterval(checkCloseIntervalId);\n };\n });\n };\n\n /**\n * Initializes the iframe stamper and returns its public key.\n *\n * @example\n * ```ts twoslash\n * import { AlchemySignerWebClient } from \"@account-kit/signer\";\n *\n * const client = new AlchemySignerWebClient({\n * connection: {\n * apiKey: \"your-api-key\",\n * },\n * iframeConfig: {\n * iframeContainerId: \"signer-iframe-container\",\n * },\n * });\n *\n * const publicKey = await client.targetPublicKey();\n * ```\n *\n * @returns {Promise<string>} A promise that resolves with the target public key when the iframe stamper is successfully initialized, or throws an error if the target public key is not supported.\n */\n public override targetPublicKey = async (): Promise<string> => {\n return this.initIframeStamper();\n };\n\n private initIframeStamper = async () => {\n if (!this.iframeStamper.publicKey()) {\n await this.iframeStamper.init();\n }\n\n this.setStamper(this.iframeStamper);\n\n return this.iframeStamper.publicKey()!;\n };\n\n private initWebauthnStamper = async (user: User | undefined = this.user) => {\n this.setStamper(this.webauthnStamper);\n if (user && user.credentialId) {\n // The goal here is to allow us to cache the allowed credential, but this doesn't work with hybrid transport :(\n this.webauthnStamper.allowCredentials = [\n {\n id: Buffer.from(user.credentialId, \"base64\"),\n type: \"public-key\",\n transports: [\"internal\", \"hybrid\"],\n },\n ];\n }\n };\n\n protected override getWebAuthnAttestation = async (\n options?: CredentialCreationOptionOverrides,\n userDetails: { username: string } = {\n username: this.user?.email ?? \"anonymous\",\n }\n ) => {\n const challenge = generateRandomBuffer();\n const authenticatorUserId = generateRandomBuffer();\n\n const attestation = await getWebAuthnAttestation({\n publicKey: {\n ...options?.publicKey,\n authenticatorSelection: {\n residentKey: \"preferred\",\n requireResidentKey: false,\n userVerification: \"preferred\",\n ...options?.publicKey?.authenticatorSelection,\n },\n challenge,\n rp: {\n id: window.location.hostname,\n name: window.location.hostname,\n ...options?.publicKey?.rp,\n },\n pubKeyCredParams: [\n {\n type: \"public-key\",\n alg: -7,\n },\n {\n type: \"public-key\",\n alg: -257,\n },\n ],\n user: {\n id: authenticatorUserId,\n name: userDetails.username,\n displayName: userDetails.username,\n ...options?.publicKey?.user,\n },\n },\n signal: options?.signal,\n });\n\n // on iOS sometimes this is returned as empty or null, so handling that here\n if (attestation.transports == null || attestation.transports.length === 0) {\n attestation.transports = [\n \"AUTHENTICATOR_TRANSPORT_INTERNAL\",\n \"AUTHENTICATOR_TRANSPORT_HYBRID\",\n ];\n }\n\n return { challenge, authenticatorUserId, attestation };\n };\n\n protected override getOauthConfig = async (): Promise<OauthConfig> => {\n const currentStamper = this.turnkeyClient.stamper;\n const publicKey = await this.initIframeStamper();\n\n // swap the stamper back in case the user logged in with a different stamper (passkeys)\n this.setStamper(currentStamper);\n const nonce = this.getOauthNonce(publicKey);\n return this.request(\"/v1/prepare-oauth\", { nonce });\n };\n}\n\n/**\n * This error is thrown when the OAuth flow is cancelled because the auth popup\n * window was closed.\n */\nexport class OauthCancelledError extends BaseError {\n override name = \"OauthCancelledError\";\n\n /**\n * Constructor for initializing an error indicating that the OAuth flow was\n * cancelled.\n */\n constructor() {\n super(\"OAuth cancelled\");\n }\n}\n\n/**\n * This error is thrown when an error occurs during the OAuth login flow.\n */\nexport class OauthFailedError extends BaseError {\n override name = \"OauthFailedError\";\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/client/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,sBAAsB,EAAE,MAAM,cAAc,CAAC;AACjE,OAAO,EAAE,sBAAsB,EAAE,MAAM,eAAe,CAAC;AACvD,OAAO,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAC;AACxD,OAAO,EAAE,eAAe,EAAE,MAAM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,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,OAAO,CAAC,iCAAiC,EAAE;YACrE,gBAAgB,EAAE,MAAM,CAAC,gBAAgB;YACzC,YAAY,EAAE,MAAM,CAAC,YAAY;SAClC,CAAC,CAAC;QAEH,kGAAkG;QAClG,IAAI,CAAC,QAAQ,CAAC,OAAO,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,gBAAgB,EAAE,CAAC;YAC5D,MAAM,IAAI,KAAK,CACb,oEAAoE,CACrE,CAAC;QACJ,CAAC;QAED,OAAO;YACL,MAAM,EAAE,QAAQ,CAAC,OAAO,CAAC,gBAAgB;SAC1C,CAAC;IACJ,CAAC;CACF;AAED;;;GAGG;AACH,MAAM,OAAO,mBAAoB,SAAQ,SAAS;IAGhD;;;OAGG;IACH;QACE,KAAK,CAAC,iBAAiB,CAAC,CAAC;QAPlB;;;;mBAAO,qBAAqB;WAAC;IAQtC,CAAC;CACF;AAED;;GAEG;AACH,MAAM,OAAO,gBAAiB,SAAQ,SAAS;IAA/C;;QACW;;;;mBAAO,kBAAkB;WAAC;IACrC,CAAC;CAAA","sourcesContent":["import { BaseError, ConnectionConfigSchema } from \"@aa-sdk/core\";\nimport { getWebAuthnAttestation } from \"@turnkey/http\";\nimport { IframeStamper } from \"@turnkey/iframe-stamper\";\nimport { WebauthnStamper } from \"@turnkey/webauthn-stamper\";\nimport { z } from \"zod\";\nimport type { AuthParams } from \"../signer.js\";\nimport { base64UrlEncode } from \"../utils/base64UrlEncode.js\";\nimport { generateRandomBuffer } from \"../utils/generateRandomBuffer.js\";\nimport { BaseSignerClient } from \"./base.js\";\nimport type {\n AlchemySignerClientEvents,\n AuthenticatingEventMetadata,\n CreateAccountParams,\n CredentialCreationOptionOverrides,\n EmailAuthParams,\n ExportWalletParams,\n OauthConfig,\n OtpParams,\n User,\n MfaFactor,\n EnableMfaParams,\n EnableMfaResult,\n VerifyMfaParams,\n RemoveMfaParams,\n SubmitOtpCodeResponse,\n ValidateMultiFactorsParams,\n} from \"./types.js\";\nimport { MfaRequiredError, NotAuthenticatedError } from \"../errors.js\";\nimport { parseMfaError } from \"../utils/parseMfaError.js\";\n\nconst CHECK_CLOSE_INTERVAL = 500;\nconst MFA_PAYLOAD = {\n GET: \"get_mfa\",\n ADD: \"add_mfa\",\n DELETE: \"delete_mfas\",\n VERIFY: \"verify_mfa\",\n LIST: \"list_mfas\",\n};\n\nexport const AlchemySignerClientParamsSchema = z.object({\n connection: ConnectionConfigSchema,\n iframeConfig: z.object({\n iframeElementId: z.string().default(\"turnkey-iframe\"),\n iframeContainerId: z.string(),\n }),\n rpId: z.string().optional(),\n rootOrgId: z\n .string()\n .optional()\n .default(\"24c1acf5-810f-41e0-a503-d5d13fa8e830\"),\n oauthCallbackUrl: z\n .string()\n .optional()\n .default(\"https://signer.alchemy.com/callback\"),\n enablePopupOauth: z.boolean().optional().default(false),\n});\n\nexport type AlchemySignerClientParams = z.input<\n typeof AlchemySignerClientParamsSchema\n>;\n\n/**\n * A lower level client used by the AlchemySigner used to communicate with\n * Alchemy's signer service.\n */\nexport class AlchemySignerWebClient extends BaseSignerClient<ExportWalletParams> {\n private iframeStamper: IframeStamper;\n private webauthnStamper: WebauthnStamper;\n oauthCallbackUrl: string;\n iframeContainerId: string;\n\n /**\n * Initializes a new instance with the given parameters, setting up the connection, iframe configuration, and WebAuthn stamper.\n *\n * @example\n * ```ts\n * import { AlchemySignerWebClient } from \"@account-kit/signer\";\n *\n * const client = new AlchemySignerWebClient({\n * connection: {\n * apiKey: \"your-api-key\",\n * },\n * iframeConfig: {\n * iframeContainerId: \"signer-iframe-container\",\n * },\n * });\n * ```\n *\n * @param {AlchemySignerClientParams} params the parameters required to initialize the client\n * @param {ConnectionConfig} params.connection The connection details needed to connect to the service\n * @param {{ iframeElementId?: string; iframeContainerId: string }} params.iframeConfig The configuration details for setting up the iframe stamper\n * @param {string} params.rpId The relying party ID, defaulting to the current hostname if not provided\n * @param {string} params.rootOrgId The root organization ID\n */\n constructor(params: AlchemySignerClientParams) {\n const { connection, iframeConfig, rpId, rootOrgId, oauthCallbackUrl } =\n AlchemySignerClientParamsSchema.parse(params);\n\n const iframeStamper = new IframeStamper({\n iframeElementId: iframeConfig.iframeElementId,\n iframeUrl: \"https://auth.turnkey.com\",\n iframeContainer: document.getElementById(iframeConfig.iframeContainerId),\n });\n\n super({\n connection,\n rootOrgId,\n stamper: iframeStamper,\n });\n\n this.iframeStamper = iframeStamper;\n this.iframeContainerId = iframeConfig.iframeContainerId;\n\n this.webauthnStamper = new WebauthnStamper({\n rpId: rpId ?? window.location.hostname,\n });\n\n this.oauthCallbackUrl = oauthCallbackUrl;\n }\n\n /**\n * Authenticates the user by either email or passkey account creation flow. Emits events during the process.\n *\n * @example\n * ```ts\n * import { AlchemySignerWebClient } from \"@account-kit/signer\";\n *\n * const client = new AlchemySignerWebClient({\n * connection: {\n * apiKey: \"your-api-key\",\n * },\n * iframeConfig: {\n * iframeContainerId: \"signer-iframe-container\",\n * },\n * });\n *\n * const account = await client.createAccount({ type: \"email\", email: \"you@mail.com\" });\n * ```\n *\n * @param {CreateAccountParams} params The parameters for creating an account, including the type (email or passkey) and additional details.\n * @returns {Promise<SignupResponse>} A promise that resolves with the response object containing the account creation result.\n */\n public override createAccount = async (params: CreateAccountParams) => {\n if (params.type === \"email\") {\n this.eventEmitter.emit(\"authenticating\", { type: \"otp\" });\n const { email, emailMode, expirationSeconds } = params;\n const publicKey = await this.initIframeStamper();\n\n const response = await this.request(\"/v1/signup\", {\n email,\n emailMode,\n targetPublicKey: publicKey,\n expirationSeconds,\n redirectParams: params.redirectParams?.toString(),\n });\n\n return response;\n }\n\n this.eventEmitter.emit(\"authenticating\", { type: \"passkey\" });\n // Passkey account creation flow\n const { attestation, challenge } = await this.getWebAuthnAttestation(\n params.creationOpts,\n { username: \"email\" in params ? params.email : params.username }\n );\n\n const result = await this.request(\"/v1/signup\", {\n passkey: {\n challenge: base64UrlEncode(challenge),\n attestation,\n },\n email: \"email\" in params ? params.email : undefined,\n });\n\n this.user = {\n orgId: result.orgId,\n address: result.address!,\n userId: result.userId!,\n credentialId: attestation.credentialId,\n };\n this.initWebauthnStamper(this.user);\n this.eventEmitter.emit(\"connectedPasskey\", this.user);\n\n return result;\n };\n\n /**\n * Begin authenticating a user with their email and an expiration time for the authentication request. Initializes the iframe stamper to get the target public key.\n * This method sends an email to the user to complete their login\n *\n * @example\n * ```ts\n * import { AlchemySignerWebClient } from \"@account-kit/signer\";\n *\n * const client = new AlchemySignerWebClient({\n * connection: {\n * apiKey: \"your-api-key\",\n * },\n * iframeConfig: {\n * iframeContainerId: \"signer-iframe-container\",\n * },\n * });\n *\n * const account = await client.initEmailAuth({ email: \"you@mail.com\" });\n * ```\n *\n * @param {Omit<EmailAuthParams, \"targetPublicKey\">} params The parameters for email authentication, excluding the target public key\n * @returns {Promise<any>} The response from the authentication request\n */\n public override initEmailAuth = async (\n params: Omit<EmailAuthParams, \"targetPublicKey\">\n ) => {\n this.eventEmitter.emit(\"authenticating\", { type: \"otp\" });\n const { email, emailMode, expirationSeconds } = params;\n const publicKey = await this.initIframeStamper();\n\n try {\n return await this.request(\"/v1/auth\", {\n email,\n emailMode,\n targetPublicKey: publicKey,\n expirationSeconds,\n redirectParams: params.redirectParams?.toString(),\n multiFactors: params.multiFactors,\n });\n } catch (error) {\n const multiFactors = parseMfaError(error);\n\n // If MFA is required, and emailMode is Magic Link, the user must submit mfa with the request or\n // the the server will return an error with the required mfa factors.\n if (multiFactors) {\n throw new MfaRequiredError(multiFactors);\n }\n throw error;\n }\n };\n\n /**\n * Authenticates using an OTP code which was previously received via email.\n *\n * @example\n * ```ts\n * import { AlchemySignerWebClient } from \"@account-kit/signer\";\n *\n * const client = new AlchemySignerWebClient({\n * connection: {\n * apiKey: \"your-api-key\",\n * },\n * iframeConfig: {\n * iframeContainerId: \"signer-iframe-container\",\n * },\n * });\n *\n * const account = await client.submitOtpCode({\n * orgId: \"user-org-id\",\n * otpId: \"opt-returned-from-initEmailAuth\",\n * otpCode: \"otp-code-from-email\",\n * });\n * ```\n *\n * @param {Omit<OtpParams, \"targetPublicKey\">} args The parameters for the OTP request, excluding the target public key.\n * @returns {Promise<{ bundle: string }>} A promise that resolves to an object containing the credential bundle.\n */\n public override async submitOtpCode(\n args: Omit<OtpParams, \"targetPublicKey\">\n ): Promise<SubmitOtpCodeResponse> {\n this.eventEmitter.emit(\"authenticating\", { type: \"otpVerify\" });\n const targetPublicKey = await this.initIframeStamper();\n const response = await this.request(\"/v1/otp\", {\n ...args,\n targetPublicKey,\n });\n\n if (\"credentialBundle\" in response && response.credentialBundle) {\n return {\n mfaRequired: false,\n bundle: response.credentialBundle,\n };\n }\n\n // If the server says \"MFA_REQUIRED\", pass that data back to the caller:\n if (\n response.status === \"MFA_REQUIRED\" &&\n response.encryptedPayload &&\n response.multiFactors\n ) {\n return {\n mfaRequired: true,\n encryptedPayload: response.encryptedPayload,\n multiFactors: response.multiFactors,\n };\n }\n\n // Otherwise, it's truly an error:\n throw new Error(\n \"Failed to submit OTP code. Server did not return required fields.\"\n );\n }\n\n /**\n * Completes auth for the user by injecting a credential bundle and retrieving\n * the user information based on the provided organization ID. Emits events\n * during the process.\n *\n * @example\n * ```ts\n * import { AlchemySignerWebClient } from \"@account-kit/signer\";\n *\n * const client = new AlchemySignerWebClient({\n * connection: {\n * apiKey: \"your-api-key\",\n * },\n * iframeConfig: {\n * iframeContainerId: \"signer-iframe-container\",\n * },\n * });\n *\n * const account = await client.completeAuthWithBundle({ orgId: \"user-org-id\", bundle: \"bundle-from-email\", connectedEventName: \"connectedEmail\" });\n * ```\n *\n * @param {{ bundle: string; orgId: string, connectedEventName: keyof AlchemySignerClientEvents, idToken?: string }} config\n * The configuration object for the authentication function containing the\n * credential bundle to inject and the organization id associated with the\n * user, as well as the event to be emitted on success and optionally an OIDC\n * ID token with extra user information\n * @returns {Promise<User>} A promise that resolves to the authenticated user\n * information\n */\n public override completeAuthWithBundle = async ({\n bundle,\n orgId,\n connectedEventName,\n idToken,\n authenticatingType,\n }: {\n bundle: string;\n orgId: string;\n connectedEventName: keyof AlchemySignerClientEvents;\n authenticatingType: AuthenticatingEventMetadata[\"type\"];\n idToken?: string;\n }): Promise<User> => {\n this.eventEmitter.emit(\"authenticating\", { type: authenticatingType });\n await this.initIframeStamper();\n\n const result = await this.iframeStamper.injectCredentialBundle(bundle);\n\n if (!result) {\n throw new Error(\"Failed to inject credential bundle\");\n }\n\n const user = await this.whoami(orgId, idToken);\n\n this.eventEmitter.emit(connectedEventName, user, bundle);\n\n return user;\n };\n\n /**\n * Asynchronously handles the authentication process using WebAuthn Stamper. If a user is provided, sets the user and returns it. Otherwise, retrieves the current user and initializes the WebAuthn stamper.\n *\n * @example\n * ```ts\n * import { AlchemySignerWebClient } from \"@account-kit/signer\";\n *\n * const client = new AlchemySignerWebClient({\n * connection: {\n * apiKey: \"your-api-key\",\n * },\n * iframeConfig: {\n * iframeContainerId: \"signer-iframe-container\",\n * },\n * });\n *\n * const account = await client.lookupUserWithPasskey();\n * ```\n *\n * @param {User} [user] An optional user object to authenticate\n * @returns {Promise<User>} A promise that resolves to the authenticated user object\n */\n public override lookupUserWithPasskey = async (\n user: User | undefined = undefined\n ) => {\n this.eventEmitter.emit(\"authenticating\", { type: \"passkey\" });\n await this.initWebauthnStamper(user);\n if (user) {\n this.user = user;\n this.eventEmitter.emit(\"connectedPasskey\", user);\n return user;\n }\n\n const result = await this.whoami(this.rootOrg);\n await this.initWebauthnStamper(result);\n this.eventEmitter.emit(\"connectedPasskey\", result);\n\n return result;\n };\n\n /**\n * Initiates the export of a wallet by creating an iframe stamper and calling the appropriate export function.\n * The export can be based on a seed phrase or a private key.\n *\n * @example\n * ```ts\n * import { AlchemySignerWebClient } from \"@account-kit/signer\";\n *\n * const client = new AlchemySignerWebClient({\n * connection: {\n * apiKey: \"your-api-key\",\n * },\n * iframeConfig: {\n * iframeContainerId: \"signer-iframe-container\",\n * },\n * });\n *\n * const account = await client.exportWallet({\n * iframeContainerId: \"export-iframe-container\",\n * });\n * ```\n *\n * @param {ExportWalletParams} config The parameters for exporting the wallet\n * @param {string} config.iframeContainerId The ID of the container element that will hold the iframe stamper\n * @param {string} [config.iframeElementId] Optional ID for the iframe element\n * @returns {Promise<void>} A promise that resolves when the export process is complete\n */\n public override exportWallet = async ({\n iframeContainerId,\n iframeElementId = \"turnkey-export-iframe\",\n }: ExportWalletParams) => {\n const exportWalletIframeStamper = new IframeStamper({\n iframeContainer: document.getElementById(iframeContainerId),\n iframeElementId: iframeElementId,\n iframeUrl: \"https://export.turnkey.com\",\n });\n await exportWalletIframeStamper.init();\n\n if (this.turnkeyClient.stamper === this.iframeStamper) {\n return this.exportWalletInner({\n exportStamper: exportWalletIframeStamper,\n exportAs: \"SEED_PHRASE\",\n });\n }\n\n return this.exportWalletInner({\n exportStamper: exportWalletIframeStamper,\n exportAs: \"PRIVATE_KEY\",\n });\n };\n\n /**\n * Asynchronous function that clears the user and resets the iframe stamper.\n *\n * @example\n * ```ts\n * import { AlchemySignerWebClient } from \"@account-kit/signer\";\n *\n * const client = new AlchemySignerWebClient({\n * connection: {\n * apiKey: \"your-api-key\",\n * },\n * iframeConfig: {\n * iframeContainerId: \"signer-iframe-container\",\n * },\n * });\n *\n * const account = await client.disconnect();\n * ```\n */\n public override disconnect = async () => {\n this.user = undefined;\n this.iframeStamper.clear();\n await this.iframeStamper.init();\n };\n\n /**\n * Redirects the user to the OAuth provider URL based on the provided arguments. This function will always reject after 1 second if the redirection does not occur.\n *\n * @example\n * ```ts\n * import { AlchemySignerWebClient } from \"@account-kit/signer\";\n *\n * const client = new AlchemySignerWebClient({\n * connection: {\n * apiKey: \"your-api-key\",\n * },\n * iframeConfig: {\n * iframeContainerId: \"signer-iframe-container\",\n * },\n * });\n *\n * await client.oauthWithRedirect({\n * type: \"oauth\",\n * authProviderId: \"google\",\n * mode: \"redirect\",\n * redirectUrl: \"/\",\n * });\n * ```\n *\n * @param {Extract<AuthParams, { type: \"oauth\"; mode: \"redirect\" }>} args The arguments required to obtain the OAuth provider URL\n * @returns {Promise<never>} A promise that will never resolve, only reject if the redirection fails\n */\n public override oauthWithRedirect = async (\n args: Extract<AuthParams, { type: \"oauth\"; mode: \"redirect\" }>\n ): Promise<never> => {\n const turnkeyPublicKey = await this.initIframeStamper();\n\n const oauthParams = args;\n const providerUrl = await this.getOauthProviderUrl({\n oauthParams,\n turnkeyPublicKey,\n oauthCallbackUrl: this.oauthCallbackUrl,\n });\n\n window.location.href = providerUrl;\n return new Promise((_, reject) =>\n setTimeout(() => reject(\"Failed to redirect to OAuth provider\"), 1000)\n );\n };\n\n /**\n * Initiates an OAuth authentication flow in a popup window and returns the authenticated user.\n *\n * @example\n * ```ts\n * import { AlchemySignerWebClient } from \"@account-kit/signer\";\n *\n * const client = new AlchemySignerWebClient({\n * connection: {\n * apiKey: \"your-api-key\",\n * },\n * iframeConfig: {\n * iframeContainerId: \"signer-iframe-container\",\n * },\n * });\n *\n * const user = await client.oauthWithPopup({\n * type: \"oauth\",\n * authProviderId: \"google\",\n * mode: \"popup\"\n * });\n * ```\n *\n * @param {Extract<AuthParams, { type: \"oauth\"; mode: \"popup\" }>} args The authentication parameters specifying OAuth type and popup mode\n * @returns {Promise<User>} A promise that resolves to a `User` object containing the authenticated user information\n */\n public override oauthWithPopup = async (\n args: Extract<AuthParams, { type: \"oauth\"; mode: \"popup\" }>\n ): Promise<User> => {\n const turnkeyPublicKey = await this.initIframeStamper();\n const oauthParams = args;\n const providerUrl = await this.getOauthProviderUrl({\n oauthParams,\n turnkeyPublicKey,\n oauthCallbackUrl: this.oauthCallbackUrl,\n });\n const popup = window.open(\n providerUrl,\n \"_blank\",\n \"popup,width=500,height=600\"\n );\n const eventEmitter = this.eventEmitter;\n return new Promise((resolve, reject) => {\n const handleMessage = (event: MessageEvent) => {\n if (!event.data) {\n return;\n }\n const {\n alchemyBundle: bundle,\n alchemyOrgId: orgId,\n alchemyIdToken: idToken,\n alchemyIsSignup: isSignup,\n alchemyError,\n } = event.data;\n if (bundle && orgId && idToken) {\n cleanup();\n popup?.close();\n this.completeAuthWithBundle({\n bundle,\n orgId,\n connectedEventName: \"connectedOauth\",\n idToken,\n authenticatingType: \"oauth\",\n }).then((user) => {\n if (isSignup) {\n eventEmitter.emit(\"newUserSignup\");\n }\n\n resolve(user);\n }, reject);\n } else if (alchemyError) {\n cleanup();\n popup?.close();\n reject(new OauthFailedError(alchemyError));\n }\n };\n\n window.addEventListener(\"message\", handleMessage);\n\n const checkCloseIntervalId = setInterval(() => {\n if (popup?.closed) {\n cleanup();\n reject(new OauthCancelledError());\n }\n }, CHECK_CLOSE_INTERVAL);\n\n const cleanup = () => {\n window.removeEventListener(\"message\", handleMessage);\n clearInterval(checkCloseIntervalId);\n };\n });\n };\n\n /**\n * Initializes the iframe stamper and returns its public key.\n *\n * @example\n * ```ts twoslash\n * import { AlchemySignerWebClient } from \"@account-kit/signer\";\n *\n * const client = new AlchemySignerWebClient({\n * connection: {\n * apiKey: \"your-api-key\",\n * },\n * iframeConfig: {\n * iframeContainerId: \"signer-iframe-container\",\n * },\n * });\n *\n * const publicKey = await client.targetPublicKey();\n * ```\n *\n * @returns {Promise<string>} A promise that resolves with the target public key when the iframe stamper is successfully initialized, or throws an error if the target public key is not supported.\n */\n public override targetPublicKey = async (): Promise<string> => {\n return this.initIframeStamper();\n };\n\n private initIframeStamper = async () => {\n if (!this.iframeStamper.publicKey()) {\n await this.iframeStamper.init();\n }\n\n this.setStamper(this.iframeStamper);\n\n return this.iframeStamper.publicKey()!;\n };\n\n private initWebauthnStamper = async (user: User | undefined = this.user) => {\n this.setStamper(this.webauthnStamper);\n if (user && user.credentialId) {\n // The goal here is to allow us to cache the allowed credential, but this doesn't work with hybrid transport :(\n this.webauthnStamper.allowCredentials = [\n {\n id: Buffer.from(user.credentialId, \"base64\"),\n type: \"public-key\",\n transports: [\"internal\", \"hybrid\"],\n },\n ];\n }\n };\n\n protected override getWebAuthnAttestation = async (\n options?: CredentialCreationOptionOverrides,\n userDetails: { username: string } = {\n username: this.user?.email ?? \"anonymous\",\n }\n ) => {\n const challenge = generateRandomBuffer();\n const authenticatorUserId = generateRandomBuffer();\n\n const attestation = await getWebAuthnAttestation({\n publicKey: {\n ...options?.publicKey,\n authenticatorSelection: {\n residentKey: \"preferred\",\n requireResidentKey: false,\n userVerification: \"preferred\",\n ...options?.publicKey?.authenticatorSelection,\n },\n challenge,\n rp: {\n id: window.location.hostname,\n name: window.location.hostname,\n ...options?.publicKey?.rp,\n },\n pubKeyCredParams: [\n {\n type: \"public-key\",\n alg: -7,\n },\n {\n type: \"public-key\",\n alg: -257,\n },\n ],\n user: {\n id: authenticatorUserId,\n name: userDetails.username,\n displayName: userDetails.username,\n ...options?.publicKey?.user,\n },\n },\n signal: options?.signal,\n });\n\n // on iOS sometimes this is returned as empty or null, so handling that here\n if (attestation.transports == null || attestation.transports.length === 0) {\n attestation.transports = [\n \"AUTHENTICATOR_TRANSPORT_INTERNAL\",\n \"AUTHENTICATOR_TRANSPORT_HYBRID\",\n ];\n }\n\n return { challenge, authenticatorUserId, attestation };\n };\n\n protected override getOauthConfig = async (): Promise<OauthConfig> => {\n const currentStamper = this.turnkeyClient.stamper;\n const publicKey = await this.initIframeStamper();\n\n // swap the stamper back in case the user logged in with a different stamper (passkeys)\n this.setStamper(currentStamper);\n const nonce = this.getOauthNonce(publicKey);\n return this.request(\"/v1/prepare-oauth\", { nonce });\n };\n\n /**\n * Retrieves the list of MFA factors configured for the current user.\n *\n * @returns {Promise<{ multiFactors: MfaFactor[] }>} A promise that resolves to an array of configured MFA factors\n * @throws {NotAuthenticatedError} If no user is authenticated\n */\n public override getMfaFactors = async (): Promise<{\n multiFactors: MfaFactor[];\n }> => {\n if (!this.user) {\n throw new NotAuthenticatedError();\n }\n\n const stampedRequest = await this.turnkeyClient.stampSignRawPayload({\n organizationId: this.user.orgId,\n type: \"ACTIVITY_TYPE_SIGN_RAW_PAYLOAD_V2\",\n timestampMs: Date.now().toString(),\n parameters: {\n encoding: \"PAYLOAD_ENCODING_HEXADECIMAL\",\n hashFunction: \"HASH_FUNCTION_NO_OP\",\n payload: MFA_PAYLOAD.LIST,\n signWith: this.user.address,\n },\n });\n\n return this.request(\"/v1/auth-list-multi-factors\", {\n stampedRequest,\n });\n };\n\n /**\n * Initiates the setup of a new MFA factor for the current user. Mfa will need to be verified before it is active.\n *\n * @param {EnableMfaParams} params The parameters required to enable a new MFA factor\n * @returns {Promise<EnableMfaResult>} A promise that resolves to the factor setup information\n * @throws {NotAuthenticatedError} If no user is authenticated\n * @throws {Error} If an unsupported factor type is provided\n */\n public override addMfa = async (\n params: EnableMfaParams\n ): Promise<EnableMfaResult> => {\n if (!this.user) {\n throw new NotAuthenticatedError();\n }\n\n const stampedRequest = await this.turnkeyClient.stampSignRawPayload({\n organizationId: this.user.orgId,\n type: \"ACTIVITY_TYPE_SIGN_RAW_PAYLOAD_V2\",\n timestampMs: Date.now().toString(),\n parameters: {\n encoding: \"PAYLOAD_ENCODING_HEXADECIMAL\",\n hashFunction: \"HASH_FUNCTION_NO_OP\",\n payload: MFA_PAYLOAD.ADD,\n signWith: this.user.address,\n },\n });\n\n switch (params.multiFactorType) {\n case \"totp\":\n return this.request(\"/v1/auth-request-multi-factor\", {\n stampedRequest,\n multiFactorType: params.multiFactorType,\n });\n default:\n throw new Error(\n `Unsupported MFA factor type: ${params.multiFactorType}`\n );\n }\n };\n\n /**\n * Verifies a newly created MFA factor to complete the setup process.\n *\n * @param {VerifyMfaParams} params The parameters required to verify the MFA factor\n * @returns {Promise<{ multiFactors: MfaFactor[] }>} A promise that resolves to the updated list of MFA factors\n * @throws {NotAuthenticatedError} If no user is authenticated\n */\n public override verifyMfa = async (\n params: VerifyMfaParams\n ): Promise<{ multiFactors: MfaFactor[] }> => {\n if (!this.user) {\n throw new NotAuthenticatedError();\n }\n\n const stampedRequest = await this.turnkeyClient.stampSignRawPayload({\n organizationId: this.user.orgId,\n type: \"ACTIVITY_TYPE_SIGN_RAW_PAYLOAD_V2\",\n timestampMs: Date.now().toString(),\n parameters: {\n encoding: \"PAYLOAD_ENCODING_HEXADECIMAL\",\n hashFunction: \"HASH_FUNCTION_NO_OP\",\n payload: MFA_PAYLOAD.VERIFY,\n signWith: this.user.address,\n },\n });\n\n return this.request(\"/v1/auth-verify-multi-factor\", {\n stampedRequest,\n multiFactorId: params.multiFactorId,\n multiFactorCode: params.multiFactorCode,\n });\n };\n\n /**\n * Removes existing MFA factors by ID.\n *\n * @param {RemoveMfaParams} params The parameters specifying which factors to disable\n * @returns {Promise<{ multiFactors: MfaFactor[] }>} A promise that resolves to the updated list of MFA factors\n * @throws {NotAuthenticatedError} If no user is authenticated\n */\n public override removeMfa = async (\n params: RemoveMfaParams\n ): Promise<{ multiFactors: MfaFactor[] }> => {\n if (!this.user) {\n throw new NotAuthenticatedError();\n }\n\n const stampedRequest = await this.turnkeyClient.stampSignRawPayload({\n organizationId: this.user.orgId,\n type: \"ACTIVITY_TYPE_SIGN_RAW_PAYLOAD_V2\",\n timestampMs: Date.now().toString(),\n parameters: {\n encoding: \"PAYLOAD_ENCODING_HEXADECIMAL\",\n hashFunction: \"HASH_FUNCTION_NO_OP\",\n payload: MFA_PAYLOAD.DELETE,\n signWith: this.user.address,\n },\n });\n\n return this.request(\"/v1/auth-delete-multi-factors\", {\n stampedRequest,\n multiFactorIds: params.multiFactorIds,\n });\n };\n\n /**\n * Validates multiple MFA factors using the provided encrypted payload and MFA codes.\n *\n * @param {ValidateMultiFactorsParams} params The validation parameters\n * @returns {Promise<{ bundle: string }>} A promise that resolves to an object containing the credential bundle\n * @throws {Error} If no credential bundle is returned from the server\n */\n public override async validateMultiFactors(\n params: ValidateMultiFactorsParams\n ): Promise<{ bundle: string }> {\n // Send the encryptedPayload plus TOTP codes, etc:\n const response = await this.request(\"/v1/auth-validate-multi-factors\", {\n encryptedPayload: params.encryptedPayload,\n multiFactors: params.multiFactors,\n });\n\n // The server is expected to return the *decrypted* payload in `response.payload.credentialBundle`\n if (!response.payload || !response.payload.credentialBundle) {\n throw new Error(\n \"Request to validateMultiFactors did not return a credential bundle\"\n );\n }\n\n return {\n bundle: response.payload.credentialBundle,\n };\n }\n}\n\n/**\n * This error is thrown when the OAuth flow is cancelled because the auth popup\n * window was closed.\n */\nexport class OauthCancelledError extends BaseError {\n override name = \"OauthCancelledError\";\n\n /**\n * Constructor for initializing an error indicating that the OAuth flow was\n * cancelled.\n */\n constructor() {\n super(\"OAuth cancelled\");\n }\n}\n\n/**\n * This error is thrown when an error occurs during the OAuth login flow.\n */\nexport class OauthFailedError extends BaseError {\n override name = \"OauthFailedError\";\n}\n"]}