@account-kit/signer 4.42.0 → 4.43.1

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.
@@ -10,8 +10,8 @@ export interface BaseSignerClientParams {
10
10
  rpId?: string;
11
11
  }
12
12
  export type ExportWalletStamper = TurnkeyClient["stamper"] & {
13
- injectWalletExportBundle(bundle: string): Promise<boolean>;
14
- injectKeyExportBundle(bundle: string): Promise<boolean>;
13
+ injectWalletExportBundle(bundle: string, orgId: string): Promise<boolean>;
14
+ injectKeyExportBundle(bundle: string, orgId: string): Promise<boolean>;
15
15
  publicKey(): string | null;
16
16
  };
17
17
  /**
@@ -765,7 +765,7 @@ export class BaseSignerClient {
765
765
  },
766
766
  });
767
767
  const { exportBundle } = await this.pollActivityCompletion(activity, this.user.orgId, "exportWalletResult");
768
- const result = await stamper.injectWalletExportBundle(exportBundle);
768
+ const result = await stamper.injectWalletExportBundle(exportBundle, this.user.orgId);
769
769
  if (!result) {
770
770
  throw new Error("Failed to inject wallet export bundle");
771
771
  }
@@ -790,7 +790,7 @@ export class BaseSignerClient {
790
790
  },
791
791
  });
792
792
  const { exportBundle } = await this.pollActivityCompletion(activity, this.user.orgId, "exportWalletAccountResult");
793
- const result = await stamper.injectKeyExportBundle(exportBundle);
793
+ const result = await stamper.injectKeyExportBundle(exportBundle, this.user.orgId);
794
794
  if (!result) {
795
795
  throw new Error("Failed to inject wallet export bundle");
796
796
  }
@@ -1 +1 @@
1
- {"version":3,"file":"base.js","sourceRoot":"","sources":["../../../src/client/base.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAyB,MAAM,cAAc,CAAC;AAC7E,OAAO,EAAE,aAAa,EAAuB,MAAM,eAAe,CAAC;AACnE,OAAO,YAAY,MAAM,eAAe,CAAC;AACzC,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AACvC,OAAO,EAAE,MAAM,EAAY,MAAM,MAAM,CAAC;AACxC,OAAO,EAAE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AM,IAAI,CAAC,OAAO,CAAC,YAAY,EAAE;YAC9C,OAAO,EAAE;gBACP,SAAS,EACP,OAAO,SAAS,KAAK,QAAQ;oBAC3B,CAAC,CAAC,SAAS;oBACX,CAAC,CAAC,eAAe,CAAC,SAAS,CAAC;gBAChC,WAAW;aACZ;YACD,KAAK,EAAE,OAAO,IAAI,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS;SACpD,CAAC,CAAC;QAEH,IAAI,CAAC,IAAI,GAAG;YACV,KAAK,EAAE,MAAM,CAAC,KAAK;YACnB,OAAO,EAAE,MAAM,CAAC,OAAQ;YACxB,MAAM,EAAE,MAAM,CAAC,MAAO;YACtB,YAAY,EAAE,WAAW,CAAC,YAAY;SACvC,CAAC;QACF,IAAI,CAAC,mBAAmB,CAAC,IAAI,CAAC,IAAI,EAAE,MAAM,CAAC,YAAY,CAAC,CAAC;QACzD,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,kBAAkB,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC;QAEtD,OAAO,MAAM,CAAC;IAChB,CAAC;CA29BF","sourcesContent":["import { ConnectionConfigSchema, type ConnectionConfig } from \"@aa-sdk/core\";\nimport { TurnkeyClient, type TSignedRequest } from \"@turnkey/http\";\nimport EventEmitter from \"eventemitter3\";\nimport { jwtDecode } from \"jwt-decode\";\nimport { sha256, type Hex } from \"viem\";\nimport { NotAuthenticatedError, OAuthProvidersError } from \"../errors.js\";\nimport { getDefaultProviderCustomization } from \"../oauth.js\";\nimport type { OauthMode } from \"../signer.js\";\nimport { base64UrlEncode } from \"../utils/base64UrlEncode.js\";\nimport { resolveRelativeUrl } from \"../utils/resolveRelativeUrl.js\";\nimport { assertNever } from \"../utils/typeAssertions.js\";\nimport type {\n AlchemySignerClientEvent,\n AlchemySignerClientEvents,\n AuthenticatingEventMetadata,\n CreateAccountParams,\n RemoveMfaParams,\n EmailAuthParams,\n AddMfaParams,\n AddMfaResult,\n experimental_CreateApiKeyParams,\n GetOauthProviderUrlArgs,\n GetWebAuthnAttestationResult,\n MfaFactor,\n OauthConfig,\n OauthParams,\n OauthState,\n OtpParams,\n SignerBody,\n SignerResponse,\n SignerRoutes,\n SignupResponse,\n User,\n VerifyMfaParams,\n SubmitOtpCodeResponse,\n ValidateMultiFactorsParams,\n AuthLinkingPrompt,\n AddOauthProviderParams,\n CredentialCreationOptionOverrides,\n OauthProviderInfo,\n IdTokenOnly,\n AuthMethods,\n} from \"./types.js\";\nimport { VERSION } from \"../version.js\";\n\nexport interface BaseSignerClientParams {\n stamper: TurnkeyClient[\"stamper\"];\n connection: ConnectionConfig;\n rootOrgId?: string;\n rpId?: string;\n}\n\nexport type ExportWalletStamper = TurnkeyClient[\"stamper\"] & {\n injectWalletExportBundle(bundle: string): Promise<boolean>;\n injectKeyExportBundle(bundle: string): Promise<boolean>;\n publicKey(): string | null;\n};\n\nconst MFA_PAYLOAD = {\n GET: \"get_mfa\",\n ADD: \"add_mfa\",\n DELETE: \"delete_mfas\",\n VERIFY: \"verify_mfa\",\n LIST: \"list_mfas\",\n} as const;\n\n/**\n * Base class for all Alchemy Signer clients\n */\nexport abstract class BaseSignerClient<TExportWalletParams = unknown> {\n private _user: User | undefined;\n private connectionConfig: ConnectionConfig;\n protected turnkeyClient: TurnkeyClient;\n protected rootOrg: string;\n protected eventEmitter: EventEmitter<AlchemySignerClientEvents>;\n protected oauthConfig: OauthConfig | undefined;\n /**\n * Create a new instance of the Alchemy Signer client\n *\n * @param {BaseSignerClientParams} params the parameters required to create the client\n */\n constructor(params: BaseSignerClientParams) {\n const { stamper, connection, rootOrgId } = params;\n this.rootOrg = rootOrgId ?? \"24c1acf5-810f-41e0-a503-d5d13fa8e830\";\n this.eventEmitter = new EventEmitter<AlchemySignerClientEvents>();\n this.connectionConfig = ConnectionConfigSchema.parse(connection);\n this.turnkeyClient = new TurnkeyClient(\n { baseUrl: \"https://api.turnkey.com\" },\n stamper,\n );\n }\n\n /**\n * Asynchronously fetches and sets the OAuth configuration.\n *\n * @returns {Promise<OauthConfig>} A promise that resolves to the OAuth configuration\n */\n public initOauth = async (): Promise<OauthConfig> => {\n this.oauthConfig = await this.getOauthConfig();\n return this.oauthConfig;\n };\n\n protected get user() {\n return this._user;\n }\n\n protected set user(user: User | undefined) {\n const previousUser = this._user;\n this._user = user;\n if (user && !previousUser) {\n this.eventEmitter.emit(\"connected\", user);\n } else if (!user && previousUser) {\n this.eventEmitter.emit(\"disconnected\");\n }\n }\n\n /**\n * Sets the stamper of the TurnkeyClient.\n *\n * @param {TurnkeyClient[\"stamper\"]} stamper the stamper function to set for the TurnkeyClient\n */\n protected setStamper(stamper: TurnkeyClient[\"stamper\"]) {\n this.turnkeyClient.stamper = stamper;\n }\n\n /**\n * Exports wallet credentials based on the specified type, either as a SEED_PHRASE or PRIVATE_KEY.\n *\n * @param {object} params The parameters for exporting the wallet\n * @param {ExportWalletStamper} params.exportStamper The stamper used for exporting the wallet\n * @param {\"SEED_PHRASE\" | \"PRIVATE_KEY\"} params.exportAs Specifies the format for exporting the wallet, either as a SEED_PHRASE or PRIVATE_KEY\n * @returns {Promise<boolean>} A promise that resolves to true if the export is successful\n */\n protected exportWalletInner(params: {\n exportStamper: ExportWalletStamper;\n exportAs: \"SEED_PHRASE\" | \"PRIVATE_KEY\";\n }): Promise<boolean> {\n const { exportAs } = params;\n switch (exportAs) {\n case \"PRIVATE_KEY\":\n return this.exportAsPrivateKey(params.exportStamper);\n case \"SEED_PHRASE\":\n return this.exportAsSeedPhrase(params.exportStamper);\n default:\n assertNever(exportAs, `Unknown export mode: ${exportAs}`);\n }\n }\n\n /**\n * Authenticates the user by either email or passkey account creation flow. Emits events during the process.\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 async createAccount(\n params: CreateAccountParams,\n ): Promise<SignupResponse> {\n if (params.type === \"email\") {\n this.eventEmitter.emit(\"authenticating\", { type: \"otp\" });\n const { email, emailMode, expirationSeconds } = params;\n const publicKey = await this.initSessionStamper();\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:\n typeof challenge === \"string\"\n ? challenge\n : 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, params.creationOpts);\n this.eventEmitter.emit(\"connectedPasskey\", this.user);\n\n return result;\n }\n\n // #region ABSTRACT METHODS\n\n public abstract initEmailAuth(\n params: Omit<EmailAuthParams, \"targetPublicKey\">,\n ): Promise<{ orgId: string; otpId?: string; multiFactors?: MfaFactor[] }>;\n\n public abstract completeAuthWithBundle(params: {\n bundle: string;\n orgId: string;\n connectedEventName: keyof AlchemySignerClientEvents;\n authenticatingType: AuthenticatingEventMetadata[\"type\"];\n idToken?: string;\n }): Promise<User>;\n\n public abstract oauthWithRedirect(\n args: Extract<OauthParams, { mode: \"redirect\" }>,\n ): Promise<User | IdTokenOnly>;\n\n public abstract oauthWithPopup(\n args: Extract<OauthParams, { mode: \"popup\" }>,\n ): Promise<User | AuthLinkingPrompt | IdTokenOnly>;\n\n public abstract submitOtpCode(\n args: Omit<OtpParams, \"targetPublicKey\">,\n ): Promise<SubmitOtpCodeResponse>;\n\n public abstract disconnect(): Promise<void>;\n\n public abstract exportWallet(params: TExportWalletParams): Promise<boolean>;\n\n public abstract targetPublicKey(): Promise<string>;\n\n protected abstract getOauthConfig(): Promise<OauthConfig>;\n\n protected abstract getWebAuthnAttestation(\n options?: CredentialCreationOptionOverrides,\n userDetails?: { username: string },\n ): Promise<GetWebAuthnAttestationResult>;\n\n /**\n * Initializes the session stamper and returns its public key.\n */\n protected abstract initSessionStamper(): Promise<string>;\n\n protected abstract initWebauthnStamper(\n user: User | undefined,\n options: CredentialCreationOptionOverrides | undefined,\n ): Promise<void>;\n\n // #endregion\n\n // #region PUBLIC METHODS\n\n /**\n * Listen to events emitted by the client\n *\n * @param {AlchemySignerClientEvent} event the event you want to listen to\n * @param {AlchemySignerClientEvents[AlchemySignerClientEvent]} listener the callback function to execute when an event is fired\n * @returns {() => void} a function that will remove the listener when called\n */\n public on = <E extends AlchemySignerClientEvent>(\n event: E,\n listener: AlchemySignerClientEvents[E],\n ) => {\n this.eventEmitter.on(event, listener as any);\n\n return () => this.eventEmitter.removeListener(event, listener as any);\n };\n\n /**\n * Sets the email for the authenticated user, allowing them to login with that\n * email.\n *\n * You must contact Alchemy to enable this feature for your team, as there are\n * important security considerations. In particular, you must not call this\n * without first validating that the user owns this email account.\n *\n * @param {string} email The email to set for the user\n * @returns {Promise<void>} A promise that resolves when the email is set\n * @throws {NotAuthenticatedError} If the user is not authenticated\n */\n public setEmail = async (email: string): Promise<void> => {\n if (!email) {\n throw new Error(\n \"Email must not be empty. Use removeEmail() to remove email auth.\",\n );\n }\n await this.updateEmail(email);\n };\n\n /**\n * Removes the email for the authenticated user, disallowing them from login with that email.\n *\n * @returns {Promise<void>} A promise that resolves when the email is removed\n * @throws {NotAuthenticatedError} If the user is not authenticated\n */\n public removeEmail = async (): Promise<void> => {\n // This is a hack to remove the email for the user. Turnkey does not\n // support clearing the email once set, so we set it to a known\n // inaccessible address instead.\n await this.updateEmail(\"not.enabled@example.invalid\");\n };\n\n private updateEmail = async (email: string): Promise<void> => {\n if (!this.user) {\n throw new NotAuthenticatedError();\n }\n const stampedRequest = await this.turnkeyClient.stampUpdateUser({\n type: \"ACTIVITY_TYPE_UPDATE_USER\",\n timestampMs: Date.now().toString(),\n organizationId: this.user.orgId,\n parameters: {\n userId: this.user.userId,\n userEmail: email,\n userTagIds: [],\n },\n });\n await this.request(\"/v1/update-email-auth\", {\n stampedRequest,\n });\n };\n\n /**\n * Handles the creation of authenticators using WebAuthn attestation and the provided options. Requires the user to be authenticated.\n *\n * @param {CredentialCreationOptions} options The options used to create the WebAuthn attestation\n * @returns {Promise<string[]>} A promise that resolves to an array of authenticator IDs\n * @throws {NotAuthenticatedError} If the user is not authenticated\n */\n public addPasskey = async (options: CredentialCreationOptions) => {\n if (!this.user) {\n throw new NotAuthenticatedError();\n }\n const { attestation, challenge } =\n await this.getWebAuthnAttestation(options);\n\n const { activity } = await this.turnkeyClient.createAuthenticators({\n type: \"ACTIVITY_TYPE_CREATE_AUTHENTICATORS_V2\",\n timestampMs: Date.now().toString(),\n organizationId: this.user.orgId,\n parameters: {\n userId: this.user.userId,\n authenticators: [\n {\n attestation,\n authenticatorName: `passkey-${Date.now().toString()}`,\n challenge:\n typeof challenge === \"string\"\n ? challenge\n : base64UrlEncode(challenge),\n },\n ],\n },\n });\n\n const { authenticatorIds } = await this.pollActivityCompletion(\n activity,\n this.user.orgId,\n \"createAuthenticatorsResult\",\n );\n\n return authenticatorIds;\n };\n\n /**\n * Removes a passkey authenticator from the user's account.\n *\n * @param {string} authenticatorId The ID of the authenticator to remove.\n * @returns {Promise<void>} A promise that resolves when the authenticator is removed.\n * @throws {NotAuthenticatedError} If the user is not authenticated.\n */\n public removePasskey = async (authenticatorId: string): Promise<void> => {\n if (!this.user) {\n throw new NotAuthenticatedError();\n }\n await this.turnkeyClient.deleteAuthenticators({\n type: \"ACTIVITY_TYPE_DELETE_AUTHENTICATORS\",\n timestampMs: Date.now().toString(),\n organizationId: this.user.orgId,\n parameters: {\n userId: this.user.userId,\n authenticatorIds: [authenticatorId],\n },\n });\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 * @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 lookupUserWithPasskey = async (user: User | undefined = undefined) => {\n this.eventEmitter.emit(\"authenticating\", { type: \"passkey\" });\n await this.initWebauthnStamper(user, undefined);\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, undefined);\n this.eventEmitter.emit(\"connectedPasskey\", result);\n\n return result;\n };\n\n /**\n * Retrieves the status of the passkey for the current user. Requires the user to be authenticated.\n *\n * @returns {Promise<{ isPasskeyAdded: boolean }>} A promise that resolves to an object containing the passkey status\n * @throws {NotAuthenticatedError} If the user is not authenticated\n */\n public getPasskeyStatus = async () => {\n if (!this.user) {\n throw new NotAuthenticatedError();\n }\n const resp = await this.turnkeyClient.getAuthenticators({\n organizationId: this.user.orgId,\n userId: this.user.userId,\n });\n return {\n isPasskeyAdded: resp.authenticators.some((it) =>\n it.authenticatorName.startsWith(\"passkey-\"),\n ),\n };\n };\n\n /**\n * Adds an OAuth provider for the authenticated user using the provided parameters. Throws an error if the user is not authenticated.\n *\n * @param {AddOauthProviderParams} params The parameters for adding an OAuth provider, including `providerName` and `oidcToken`.\n * @throws {NotAuthenticatedError} Throws if the user is not authenticated.\n * @returns {Promise<void>} A Promise that resolves when the OAuth provider is added.\n */\n public addOauthProvider = async (\n params: AddOauthProviderParams,\n ): Promise<OauthProviderInfo> => {\n if (!this.user) {\n throw new NotAuthenticatedError();\n }\n const { providerName, oidcToken } = params;\n const stampedRequest = await this.turnkeyClient.stampCreateOauthProviders({\n type: \"ACTIVITY_TYPE_CREATE_OAUTH_PROVIDERS\",\n timestampMs: Date.now().toString(),\n organizationId: this.user.orgId,\n parameters: {\n userId: this.user.userId,\n oauthProviders: [{ providerName, oidcToken }],\n },\n });\n const response = await this.request(\"/v1/add-oauth-provider\", {\n stampedRequest,\n });\n return response.oauthProviders[0];\n };\n\n /**\n * Deletes a specified OAuth provider for the authenticated user.\n *\n * @param {string} providerId The ID of the provider to be deleted\n * @throws {NotAuthenticatedError} If the user is not authenticated\n */\n public removeOauthProvider = async (providerId: string) => {\n if (!this.user) {\n throw new NotAuthenticatedError();\n }\n const stampedRequest = await this.turnkeyClient.stampDeleteOauthProviders({\n type: \"ACTIVITY_TYPE_DELETE_OAUTH_PROVIDERS\",\n timestampMs: Date.now().toString(),\n organizationId: this.user.orgId,\n parameters: {\n userId: this.user.userId,\n providerIds: [providerId],\n },\n });\n await this.request(\"/v1/remove-oauth-provider\", { stampedRequest });\n };\n\n /**\n * Retrieves the list of authentication methods for the current user.\n *\n * @returns {Promise<AuthMethods>} A promise that resolves to the list of authentication methods\n * @throws {NotAuthenticatedError} If the user is not authenticated\n */\n public listAuthMethods = async (): Promise<AuthMethods> => {\n if (!this.user) {\n throw new NotAuthenticatedError();\n }\n return await this.request(\"/v1/list-auth-methods\", {\n suborgId: this.user.orgId,\n });\n };\n\n /**\n * Retrieves the current user or fetches the user information if not already available.\n *\n * @param {string} [orgId] optional organization ID, defaults to the user's organization ID\n * @param {string} idToken an OIDC ID token containing additional user information\n * @returns {Promise<User>} A promise that resolves to the user object\n * @throws {Error} if no organization ID is provided when there is no current user\n */\n public whoami = async (\n orgId = this.user?.orgId,\n idToken?: string,\n ): Promise<User> => {\n if (this.user) {\n return this.user;\n }\n\n if (!orgId) {\n throw new Error(\"No orgId provided\");\n }\n\n const stampedRequest = await this.turnkeyClient.stampGetWhoami({\n organizationId: orgId,\n });\n\n const user = await this.request(\"/v1/whoami\", {\n stampedRequest,\n });\n\n if (idToken) {\n const claims: Record<string, unknown> = jwtDecode(idToken);\n user.idToken = idToken;\n user.claims = claims;\n if (typeof claims.email === \"string\") {\n user.email = claims.email;\n }\n }\n\n const credentialId = (() => {\n try {\n return JSON.parse(stampedRequest?.stamp.stampHeaderValue)\n .credentialId as string;\n } catch (e) {\n return undefined;\n }\n })();\n\n this.user = {\n ...user,\n credentialId,\n };\n\n return this.user;\n };\n\n /**\n * Generates a stamped whoami request for the current user. This request can then be used to call /signer/v1/whoami to get the user information.\n * This is useful if you want to get the user information in a different context like a server. You can pass the stamped request to the server\n * and then call our API to get the user information. Using this stamp is the most trusted way to get the user information since a stamp can only\n * belong to the user who created it.\n *\n * @returns {Promise<TSignedRequest>} a promise that resolves to the \"whoami\" information for the logged in user\n * @throws {Error} if no organization ID is provided\n */\n public stampWhoami = async (): Promise<TSignedRequest> => {\n if (!this.user) {\n throw new Error(\"User must be authenticated to stamp a whoami request\");\n }\n\n return await this.turnkeyClient.stampGetWhoami({\n organizationId: this.user.orgId,\n });\n };\n\n /**\n * Generates a stamped getOrganization request for the current user.\n *\n * @returns {Promise<TSignedRequest>} a promise that resolves to the \"getOrganization\" information for the logged in user\n * @throws {Error} if no user is authenticated\n */\n public stampGetOrganization = async (): Promise<TSignedRequest> => {\n if (!this.user) {\n throw new Error(\n \"User must be authenticated to stamp a get organization request\",\n );\n }\n\n return await this.turnkeyClient.stampGetOrganization({\n organizationId: this.user.orgId,\n });\n };\n\n /**\n * Creates an API key that can take any action on behalf of the current user.\n * (Note that this method is currently experimental and is subject to change.)\n *\n * @param {CreateApiKeyParams} params Parameters for creating the API key.\n * @param {string} params.name Name of the API key.\n * @param {string} params.publicKey Public key to be used for the API key.\n * @param {number} params.expirationSec Number of seconds until the API key expires.\n * @throws {Error} If there is no authenticated user or the API key creation fails.\n */\n public experimental_createApiKey = async (\n params: experimental_CreateApiKeyParams,\n ): Promise<void> => {\n if (!this.user) {\n throw new Error(\"User must be authenticated to create api key\");\n }\n const resp = await this.turnkeyClient.createApiKeys({\n type: \"ACTIVITY_TYPE_CREATE_API_KEYS_V2\",\n timestampMs: new Date().getTime().toString(),\n organizationId: this.user.orgId,\n parameters: {\n apiKeys: [\n {\n apiKeyName: params.name,\n publicKey: params.publicKey,\n curveType: \"API_KEY_CURVE_P256\",\n expirationSeconds: params.expirationSec.toString(),\n },\n ],\n userId: this.user.userId,\n },\n });\n if (resp.activity.status !== \"ACTIVITY_STATUS_COMPLETED\") {\n throw new Error(\"Failed to create api key\");\n }\n };\n\n /**\n * Looks up information based on an email address.\n *\n * @param {string} email the email address to look up\n * @returns {Promise<any>} the result of the lookup request\n */\n public lookupUserByEmail = async (email: string) => {\n return this.request(\"/v1/lookup\", { email });\n };\n\n /**\n * This will sign a message with the user's private key, without doing any transformations on the message.\n * For SignMessage or SignTypedData, the caller should hash the message before calling this method and pass\n * that result here.\n *\n * @param {Hex} msg the hex representation of the bytes to sign\n * @param {string} mode specify if signing should happen for solana or ethereum\n * @returns {Promise<Hex>} the signature over the raw hex\n */\n public signRawMessage = async (\n msg: Hex,\n mode: \"SOLANA\" | \"ETHEREUM\" = \"ETHEREUM\",\n ): Promise<Hex> => {\n if (!this.user) {\n throw new NotAuthenticatedError();\n }\n\n if (!this.user.solanaAddress && mode === \"SOLANA\") {\n // TODO: we need to add backwards compatibility for users who signed up before we added Solana support\n throw new Error(\"No Solana address available for the user\");\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:\n mode === \"ETHEREUM\"\n ? \"HASH_FUNCTION_NO_OP\"\n : \"HASH_FUNCTION_NOT_APPLICABLE\",\n payload: msg,\n signWith:\n mode === \"ETHEREUM\" ? this.user.address : this.user.solanaAddress!,\n },\n });\n\n const { signature } = await this.request(\"/v1/sign-payload\", {\n stampedRequest,\n });\n\n return signature;\n };\n\n /**\n * Returns the current user or null if no user is set.\n *\n * @returns {User | null} the current user object or null if no user is available\n */\n public getUser = (): User | null => {\n return this.user ?? null;\n };\n\n /**\n * Sends a POST request to the given signer route with the specified body and returns the response.\n * Not intended to be used directly, use the specific methods instead on the client instead.\n *\n * @param {SignerRoutes} route The route to which the request should be sent\n * @param {SignerBody<R>} body The request body containing the data to be sent\n * @returns {Promise<SignerResponse<R>>} A promise that resolves to the response from the signer\n */\n public request = async <R extends SignerRoutes>(\n route: R,\n body: SignerBody<R>,\n ): Promise<SignerResponse<R>> => {\n const url = this.connectionConfig.rpcUrl ?? \"https://api.g.alchemy.com\";\n\n const basePath = \"/signer\";\n\n const headers = new Headers();\n headers.append(\"Alchemy-AA-Sdk-Version\", VERSION);\n headers.append(\"Content-Type\", \"application/json\");\n if (this.connectionConfig.apiKey) {\n headers.append(\"Authorization\", `Bearer ${this.connectionConfig.apiKey}`);\n } else if (this.connectionConfig.jwt) {\n headers.append(\"Authorization\", `Bearer ${this.connectionConfig.jwt}`);\n }\n\n const response = await fetch(`${url}${basePath}${route}`, {\n method: \"POST\",\n body: JSON.stringify(body),\n headers,\n });\n\n if (!response.ok) {\n throw new Error(await response.text());\n }\n\n const json = await response.json();\n\n return json as SignerResponse<R>;\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 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 {AddMfaParams} params The parameters required to enable a new MFA factor\n * @returns {Promise<AddMfaResult>} 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 addMfa = async (params: AddMfaParams): Promise<AddMfaResult> => {\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 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 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 validateMultiFactors = async (\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 // #endregion\n\n // #region PRIVATE METHODS\n private exportAsSeedPhrase = async (stamper: ExportWalletStamper) => {\n if (!this.user) {\n throw new NotAuthenticatedError();\n }\n\n const { wallets } = await this.turnkeyClient.getWallets({\n organizationId: this.user.orgId,\n });\n\n const walletAccounts = await Promise.all(\n wallets.map(({ walletId }) =>\n this.turnkeyClient.getWalletAccounts({\n organizationId: this.user!.orgId,\n walletId,\n }),\n ),\n ).then((x) => x.flatMap((x) => x.accounts));\n\n const walletAccount = walletAccounts.find(\n (x) => x.address === this.user!.address,\n );\n\n if (!walletAccount) {\n throw new Error(\n `Could not find wallet associated with ${this.user.address}`,\n );\n }\n\n const { activity } = await this.turnkeyClient.exportWallet({\n organizationId: this.user.orgId,\n type: \"ACTIVITY_TYPE_EXPORT_WALLET\",\n timestampMs: Date.now().toString(),\n parameters: {\n walletId: walletAccount!.walletId,\n targetPublicKey: stamper.publicKey()!,\n },\n });\n\n const { exportBundle } = await this.pollActivityCompletion(\n activity,\n this.user.orgId,\n \"exportWalletResult\",\n );\n\n const result = await stamper.injectWalletExportBundle(exportBundle);\n\n if (!result) {\n throw new Error(\"Failed to inject wallet export bundle\");\n }\n\n return result;\n };\n\n private exportAsPrivateKey = async (stamper: ExportWalletStamper) => {\n if (!this.user) {\n throw new NotAuthenticatedError();\n }\n\n const { activity } = await this.turnkeyClient.exportWalletAccount({\n organizationId: this.user.orgId,\n type: \"ACTIVITY_TYPE_EXPORT_WALLET_ACCOUNT\",\n timestampMs: Date.now().toString(),\n parameters: {\n address: this.user.address,\n targetPublicKey: stamper.publicKey()!,\n },\n });\n\n const { exportBundle } = await this.pollActivityCompletion(\n activity,\n this.user.orgId,\n \"exportWalletAccountResult\",\n );\n\n const result = await stamper.injectKeyExportBundle(exportBundle);\n\n if (!result) {\n throw new Error(\"Failed to inject wallet export bundle\");\n }\n\n return result;\n };\n\n /**\n * Returns the authentication url for the selected OAuth Proivder\n *\n * @example\n * ```ts\n *\n * cosnt oauthParams = {\n * authProviderId: \"google\",\n * isCustomProvider: false,\n * auth0Connection: undefined,\n * scope: undefined,\n * claims: undefined,\n * mode: \"redirect\",\n * redirectUrl: \"https://your-url-path/oauth-return\",\n * expirationSeconds: 3000\n * };\n *\n * const turnkeyPublicKey = await this.initIframeStamper();\n * const oauthCallbackUrl = this.oauthCallbackUrl;\n * const oauthConfig = this.getOauthConfig() // Optional value for OauthConfig()\n * const usesRelativeUrl = true // Optional value to determine if we use a relative (or absolute) url for the `redirect_url`\n *\n * const oauthProviderUrl = getOauthProviderUrl({\n * oauthParams,\n * turnkeyPublicKey,\n * oauthCallbackUrl\n * })\n *\n * ```\n * @param {GetOauthProviderUrlArgs} args Required. The Oauth provider's auth parameters\n *\n * @returns {Promise<string>} returns the Oauth provider's url\n */\n protected getOauthProviderUrl = async (\n args: GetOauthProviderUrlArgs,\n ): Promise<string> => {\n const {\n oauthParams,\n turnkeyPublicKey,\n oauthCallbackUrl,\n oauthConfig,\n usesRelativeUrl = true,\n } = args;\n\n const {\n authProviderId,\n isCustomProvider,\n auth0Connection,\n scope: providedScope,\n claims: providedClaims,\n otherParameters: providedOtherParameters,\n mode,\n redirectUrl,\n expirationSeconds,\n } = oauthParams;\n\n const { codeChallenge, requestKey, authProviders } =\n oauthConfig ?? (await this.getOauthConfigForMode(mode));\n\n if (!authProviders) {\n throw new OAuthProvidersError();\n }\n\n const authProvider = authProviders.find(\n (provider) =>\n provider.id === authProviderId &&\n !!provider.isCustomProvider === !!isCustomProvider,\n );\n\n if (!authProvider) {\n throw new Error(`No auth provider found with id ${authProviderId}`);\n }\n\n let scope: string | undefined = providedScope;\n let claims: string | undefined = providedClaims;\n let otherParameters: Record<string, string> | undefined =\n providedOtherParameters;\n\n if (!isCustomProvider) {\n const defaultCustomization =\n getDefaultProviderCustomization(authProviderId);\n scope ??= defaultCustomization?.scope;\n claims ??= defaultCustomization?.claims;\n otherParameters ??= defaultCustomization?.otherParameters;\n }\n if (!scope) {\n throw new Error(`Default scope not known for provider ${authProviderId}`);\n }\n const { authEndpoint, clientId } = authProvider;\n\n const nonce = this.getOauthNonce(turnkeyPublicKey);\n const stateObject: OauthState = {\n authProviderId,\n isCustomProvider,\n requestKey,\n turnkeyPublicKey,\n expirationSeconds,\n redirectUrl:\n mode === \"redirect\"\n ? usesRelativeUrl\n ? resolveRelativeUrl(redirectUrl)\n : redirectUrl\n : undefined,\n openerOrigin: mode === \"popup\" ? window.location.origin : undefined,\n fetchIdTokenOnly: oauthParams.fetchIdTokenOnly,\n };\n const state = base64UrlEncode(\n new TextEncoder().encode(JSON.stringify(stateObject)),\n );\n const authUrl = new URL(authEndpoint);\n const params: Record<string, string> = {\n redirect_uri: oauthCallbackUrl,\n response_type: \"code\",\n scope,\n state,\n code_challenge: codeChallenge,\n code_challenge_method: \"S256\",\n prompt: \"select_account\",\n client_id: clientId,\n nonce,\n ...otherParameters,\n };\n if (claims) {\n params.claims = claims;\n }\n if (auth0Connection) {\n params.connection = auth0Connection;\n }\n\n Object.keys(params).forEach((param) => {\n params[param] && authUrl.searchParams.append(param, params[param]);\n });\n\n const [urlPath, searchParams] = authUrl.href.split(\"?\");\n\n return `${urlPath?.replace(/\\/$/, \"\")}?${searchParams}`;\n };\n\n private getOauthConfigForMode = async (\n mode: OauthMode,\n ): Promise<OauthConfig> => {\n if (this.oauthConfig) {\n return this.oauthConfig;\n } else if (mode === \"redirect\") {\n return this.initOauth();\n } else {\n throw new Error(\n \"enablePopupOauth must be set in configuration or signer.preparePopupOauth must be called before using popup-based OAuth login\",\n );\n }\n };\n\n // eslint-disable-next-line eslint-rules/require-jsdoc-on-reexported-functions\n protected pollActivityCompletion = async <\n T extends keyof Awaited<\n ReturnType<(typeof this.turnkeyClient)[\"getActivity\"]>\n >[\"activity\"][\"result\"],\n >(\n activity: Awaited<\n ReturnType<(typeof this.turnkeyClient)[\"getActivity\"]>\n >[\"activity\"],\n organizationId: string,\n resultKey: T,\n ): Promise<\n NonNullable<\n Awaited<\n ReturnType<(typeof this.turnkeyClient)[\"getActivity\"]>\n >[\"activity\"][\"result\"][T]\n >\n > => {\n if (activity.status === \"ACTIVITY_STATUS_COMPLETED\") {\n return activity.result[resultKey]!;\n }\n\n const {\n activity: { status, id, result },\n } = await this.turnkeyClient.getActivity({\n activityId: activity.id,\n organizationId,\n });\n\n if (status === \"ACTIVITY_STATUS_COMPLETED\") {\n return result[resultKey]!;\n }\n\n if (\n status === \"ACTIVITY_STATUS_FAILED\" ||\n status === \"ACTIVITY_STATUS_REJECTED\" ||\n status === \"ACTIVITY_STATUS_CONSENSUS_NEEDED\"\n ) {\n throw new Error(\n `Failed to get activity with with id ${id} (status: ${status})`,\n );\n }\n\n // TODO: add ability to configure this + add exponential backoff\n await new Promise((resolve) => setTimeout(resolve, 500));\n\n return this.pollActivityCompletion(activity, organizationId, resultKey);\n };\n // #endregion\n\n /**\n * Turnkey requires the nonce in the id token to be in this format.\n *\n * @param {string} turnkeyPublicKey key from a Turnkey iframe\n * @returns {string} nonce to be used in OIDC\n */\n protected getOauthNonce = (turnkeyPublicKey: string): string => {\n return sha256(new TextEncoder().encode(turnkeyPublicKey)).slice(2);\n };\n}\n"]}
1
+ {"version":3,"file":"base.js","sourceRoot":"","sources":["../../../src/client/base.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAyB,MAAM,cAAc,CAAC;AAC7E,OAAO,EAAE,aAAa,EAAuB,MAAM,eAAe,CAAC;AACnE,OAAO,YAAY,MAAM,eAAe,CAAC;AACzC,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AACvC,OAAO,EAAE,MAAM,EAAY,MAAM,MAAM,CAAC;AACxC,OAAO,EAAE,qBAAqB,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC;AAC1E,OAAO,EAAE,+BAA+B,EAAE,MAAM,aAAa,CAAC;AAE9D,OAAO,EAAE,eAAe,EAAE,MAAM,6BAA6B,CAAC;AAC9D,OAAO,EAAE,kBAAkB,EAAE,MAAM,gCAAgC,CAAC;AACpE,OAAO,EAAE,WAAW,EAAE,MAAM,4BAA4B,CAAC;AAiCzD,OAAO,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AAexC,MAAM,WAAW,GAAG;IAClB,GAAG,EAAE,SAAS;IACd,GAAG,EAAE,SAAS;IACd,MAAM,EAAE,aAAa;IACrB,MA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AK,EAAE,MAAM,CAAC,KAAK;YACnB,OAAO,EAAE,MAAM,CAAC,OAAQ;YACxB,MAAM,EAAE,MAAM,CAAC,MAAO;YACtB,YAAY,EAAE,WAAW,CAAC,YAAY;SACvC,CAAC;QACF,IAAI,CAAC,mBAAmB,CAAC,IAAI,CAAC,IAAI,EAAE,MAAM,CAAC,YAAY,CAAC,CAAC;QACzD,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,kBAAkB,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC;QAEtD,OAAO,MAAM,CAAC;IAChB,CAAC;CAi+BF","sourcesContent":["import { ConnectionConfigSchema, type ConnectionConfig } from \"@aa-sdk/core\";\nimport { TurnkeyClient, type TSignedRequest } from \"@turnkey/http\";\nimport EventEmitter from \"eventemitter3\";\nimport { jwtDecode } from \"jwt-decode\";\nimport { sha256, type Hex } from \"viem\";\nimport { NotAuthenticatedError, OAuthProvidersError } from \"../errors.js\";\nimport { getDefaultProviderCustomization } from \"../oauth.js\";\nimport type { OauthMode } from \"../signer.js\";\nimport { base64UrlEncode } from \"../utils/base64UrlEncode.js\";\nimport { resolveRelativeUrl } from \"../utils/resolveRelativeUrl.js\";\nimport { assertNever } from \"../utils/typeAssertions.js\";\nimport type {\n AlchemySignerClientEvent,\n AlchemySignerClientEvents,\n AuthenticatingEventMetadata,\n CreateAccountParams,\n RemoveMfaParams,\n EmailAuthParams,\n AddMfaParams,\n AddMfaResult,\n experimental_CreateApiKeyParams,\n GetOauthProviderUrlArgs,\n GetWebAuthnAttestationResult,\n MfaFactor,\n OauthConfig,\n OauthParams,\n OauthState,\n OtpParams,\n SignerBody,\n SignerResponse,\n SignerRoutes,\n SignupResponse,\n User,\n VerifyMfaParams,\n SubmitOtpCodeResponse,\n ValidateMultiFactorsParams,\n AuthLinkingPrompt,\n AddOauthProviderParams,\n CredentialCreationOptionOverrides,\n OauthProviderInfo,\n IdTokenOnly,\n AuthMethods,\n} from \"./types.js\";\nimport { VERSION } from \"../version.js\";\n\nexport interface BaseSignerClientParams {\n stamper: TurnkeyClient[\"stamper\"];\n connection: ConnectionConfig;\n rootOrgId?: string;\n rpId?: string;\n}\n\nexport type ExportWalletStamper = TurnkeyClient[\"stamper\"] & {\n injectWalletExportBundle(bundle: string, orgId: string): Promise<boolean>;\n injectKeyExportBundle(bundle: string, orgId: string): Promise<boolean>;\n publicKey(): string | null;\n};\n\nconst MFA_PAYLOAD = {\n GET: \"get_mfa\",\n ADD: \"add_mfa\",\n DELETE: \"delete_mfas\",\n VERIFY: \"verify_mfa\",\n LIST: \"list_mfas\",\n} as const;\n\n/**\n * Base class for all Alchemy Signer clients\n */\nexport abstract class BaseSignerClient<TExportWalletParams = unknown> {\n private _user: User | undefined;\n private connectionConfig: ConnectionConfig;\n protected turnkeyClient: TurnkeyClient;\n protected rootOrg: string;\n protected eventEmitter: EventEmitter<AlchemySignerClientEvents>;\n protected oauthConfig: OauthConfig | undefined;\n /**\n * Create a new instance of the Alchemy Signer client\n *\n * @param {BaseSignerClientParams} params the parameters required to create the client\n */\n constructor(params: BaseSignerClientParams) {\n const { stamper, connection, rootOrgId } = params;\n this.rootOrg = rootOrgId ?? \"24c1acf5-810f-41e0-a503-d5d13fa8e830\";\n this.eventEmitter = new EventEmitter<AlchemySignerClientEvents>();\n this.connectionConfig = ConnectionConfigSchema.parse(connection);\n this.turnkeyClient = new TurnkeyClient(\n { baseUrl: \"https://api.turnkey.com\" },\n stamper,\n );\n }\n\n /**\n * Asynchronously fetches and sets the OAuth configuration.\n *\n * @returns {Promise<OauthConfig>} A promise that resolves to the OAuth configuration\n */\n public initOauth = async (): Promise<OauthConfig> => {\n this.oauthConfig = await this.getOauthConfig();\n return this.oauthConfig;\n };\n\n protected get user() {\n return this._user;\n }\n\n protected set user(user: User | undefined) {\n const previousUser = this._user;\n this._user = user;\n if (user && !previousUser) {\n this.eventEmitter.emit(\"connected\", user);\n } else if (!user && previousUser) {\n this.eventEmitter.emit(\"disconnected\");\n }\n }\n\n /**\n * Sets the stamper of the TurnkeyClient.\n *\n * @param {TurnkeyClient[\"stamper\"]} stamper the stamper function to set for the TurnkeyClient\n */\n protected setStamper(stamper: TurnkeyClient[\"stamper\"]) {\n this.turnkeyClient.stamper = stamper;\n }\n\n /**\n * Exports wallet credentials based on the specified type, either as a SEED_PHRASE or PRIVATE_KEY.\n *\n * @param {object} params The parameters for exporting the wallet\n * @param {ExportWalletStamper} params.exportStamper The stamper used for exporting the wallet\n * @param {\"SEED_PHRASE\" | \"PRIVATE_KEY\"} params.exportAs Specifies the format for exporting the wallet, either as a SEED_PHRASE or PRIVATE_KEY\n * @returns {Promise<boolean>} A promise that resolves to true if the export is successful\n */\n protected exportWalletInner(params: {\n exportStamper: ExportWalletStamper;\n exportAs: \"SEED_PHRASE\" | \"PRIVATE_KEY\";\n }): Promise<boolean> {\n const { exportAs } = params;\n switch (exportAs) {\n case \"PRIVATE_KEY\":\n return this.exportAsPrivateKey(params.exportStamper);\n case \"SEED_PHRASE\":\n return this.exportAsSeedPhrase(params.exportStamper);\n default:\n assertNever(exportAs, `Unknown export mode: ${exportAs}`);\n }\n }\n\n /**\n * Authenticates the user by either email or passkey account creation flow. Emits events during the process.\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 async createAccount(\n params: CreateAccountParams,\n ): Promise<SignupResponse> {\n if (params.type === \"email\") {\n this.eventEmitter.emit(\"authenticating\", { type: \"otp\" });\n const { email, emailMode, expirationSeconds } = params;\n const publicKey = await this.initSessionStamper();\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:\n typeof challenge === \"string\"\n ? challenge\n : 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, params.creationOpts);\n this.eventEmitter.emit(\"connectedPasskey\", this.user);\n\n return result;\n }\n\n // #region ABSTRACT METHODS\n\n public abstract initEmailAuth(\n params: Omit<EmailAuthParams, \"targetPublicKey\">,\n ): Promise<{ orgId: string; otpId?: string; multiFactors?: MfaFactor[] }>;\n\n public abstract completeAuthWithBundle(params: {\n bundle: string;\n orgId: string;\n connectedEventName: keyof AlchemySignerClientEvents;\n authenticatingType: AuthenticatingEventMetadata[\"type\"];\n idToken?: string;\n }): Promise<User>;\n\n public abstract oauthWithRedirect(\n args: Extract<OauthParams, { mode: \"redirect\" }>,\n ): Promise<User | IdTokenOnly>;\n\n public abstract oauthWithPopup(\n args: Extract<OauthParams, { mode: \"popup\" }>,\n ): Promise<User | AuthLinkingPrompt | IdTokenOnly>;\n\n public abstract submitOtpCode(\n args: Omit<OtpParams, \"targetPublicKey\">,\n ): Promise<SubmitOtpCodeResponse>;\n\n public abstract disconnect(): Promise<void>;\n\n public abstract exportWallet(params: TExportWalletParams): Promise<boolean>;\n\n public abstract targetPublicKey(): Promise<string>;\n\n protected abstract getOauthConfig(): Promise<OauthConfig>;\n\n protected abstract getWebAuthnAttestation(\n options?: CredentialCreationOptionOverrides,\n userDetails?: { username: string },\n ): Promise<GetWebAuthnAttestationResult>;\n\n /**\n * Initializes the session stamper and returns its public key.\n */\n protected abstract initSessionStamper(): Promise<string>;\n\n protected abstract initWebauthnStamper(\n user: User | undefined,\n options: CredentialCreationOptionOverrides | undefined,\n ): Promise<void>;\n\n // #endregion\n\n // #region PUBLIC METHODS\n\n /**\n * Listen to events emitted by the client\n *\n * @param {AlchemySignerClientEvent} event the event you want to listen to\n * @param {AlchemySignerClientEvents[AlchemySignerClientEvent]} listener the callback function to execute when an event is fired\n * @returns {() => void} a function that will remove the listener when called\n */\n public on = <E extends AlchemySignerClientEvent>(\n event: E,\n listener: AlchemySignerClientEvents[E],\n ) => {\n this.eventEmitter.on(event, listener as any);\n\n return () => this.eventEmitter.removeListener(event, listener as any);\n };\n\n /**\n * Sets the email for the authenticated user, allowing them to login with that\n * email.\n *\n * You must contact Alchemy to enable this feature for your team, as there are\n * important security considerations. In particular, you must not call this\n * without first validating that the user owns this email account.\n *\n * @param {string} email The email to set for the user\n * @returns {Promise<void>} A promise that resolves when the email is set\n * @throws {NotAuthenticatedError} If the user is not authenticated\n */\n public setEmail = async (email: string): Promise<void> => {\n if (!email) {\n throw new Error(\n \"Email must not be empty. Use removeEmail() to remove email auth.\",\n );\n }\n await this.updateEmail(email);\n };\n\n /**\n * Removes the email for the authenticated user, disallowing them from login with that email.\n *\n * @returns {Promise<void>} A promise that resolves when the email is removed\n * @throws {NotAuthenticatedError} If the user is not authenticated\n */\n public removeEmail = async (): Promise<void> => {\n // This is a hack to remove the email for the user. Turnkey does not\n // support clearing the email once set, so we set it to a known\n // inaccessible address instead.\n await this.updateEmail(\"not.enabled@example.invalid\");\n };\n\n private updateEmail = async (email: string): Promise<void> => {\n if (!this.user) {\n throw new NotAuthenticatedError();\n }\n const stampedRequest = await this.turnkeyClient.stampUpdateUser({\n type: \"ACTIVITY_TYPE_UPDATE_USER\",\n timestampMs: Date.now().toString(),\n organizationId: this.user.orgId,\n parameters: {\n userId: this.user.userId,\n userEmail: email,\n userTagIds: [],\n },\n });\n await this.request(\"/v1/update-email-auth\", {\n stampedRequest,\n });\n };\n\n /**\n * Handles the creation of authenticators using WebAuthn attestation and the provided options. Requires the user to be authenticated.\n *\n * @param {CredentialCreationOptions} options The options used to create the WebAuthn attestation\n * @returns {Promise<string[]>} A promise that resolves to an array of authenticator IDs\n * @throws {NotAuthenticatedError} If the user is not authenticated\n */\n public addPasskey = async (options: CredentialCreationOptions) => {\n if (!this.user) {\n throw new NotAuthenticatedError();\n }\n const { attestation, challenge } =\n await this.getWebAuthnAttestation(options);\n\n const { activity } = await this.turnkeyClient.createAuthenticators({\n type: \"ACTIVITY_TYPE_CREATE_AUTHENTICATORS_V2\",\n timestampMs: Date.now().toString(),\n organizationId: this.user.orgId,\n parameters: {\n userId: this.user.userId,\n authenticators: [\n {\n attestation,\n authenticatorName: `passkey-${Date.now().toString()}`,\n challenge:\n typeof challenge === \"string\"\n ? challenge\n : base64UrlEncode(challenge),\n },\n ],\n },\n });\n\n const { authenticatorIds } = await this.pollActivityCompletion(\n activity,\n this.user.orgId,\n \"createAuthenticatorsResult\",\n );\n\n return authenticatorIds;\n };\n\n /**\n * Removes a passkey authenticator from the user's account.\n *\n * @param {string} authenticatorId The ID of the authenticator to remove.\n * @returns {Promise<void>} A promise that resolves when the authenticator is removed.\n * @throws {NotAuthenticatedError} If the user is not authenticated.\n */\n public removePasskey = async (authenticatorId: string): Promise<void> => {\n if (!this.user) {\n throw new NotAuthenticatedError();\n }\n await this.turnkeyClient.deleteAuthenticators({\n type: \"ACTIVITY_TYPE_DELETE_AUTHENTICATORS\",\n timestampMs: Date.now().toString(),\n organizationId: this.user.orgId,\n parameters: {\n userId: this.user.userId,\n authenticatorIds: [authenticatorId],\n },\n });\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 * @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 lookupUserWithPasskey = async (user: User | undefined = undefined) => {\n this.eventEmitter.emit(\"authenticating\", { type: \"passkey\" });\n await this.initWebauthnStamper(user, undefined);\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, undefined);\n this.eventEmitter.emit(\"connectedPasskey\", result);\n\n return result;\n };\n\n /**\n * Retrieves the status of the passkey for the current user. Requires the user to be authenticated.\n *\n * @returns {Promise<{ isPasskeyAdded: boolean }>} A promise that resolves to an object containing the passkey status\n * @throws {NotAuthenticatedError} If the user is not authenticated\n */\n public getPasskeyStatus = async () => {\n if (!this.user) {\n throw new NotAuthenticatedError();\n }\n const resp = await this.turnkeyClient.getAuthenticators({\n organizationId: this.user.orgId,\n userId: this.user.userId,\n });\n return {\n isPasskeyAdded: resp.authenticators.some((it) =>\n it.authenticatorName.startsWith(\"passkey-\"),\n ),\n };\n };\n\n /**\n * Adds an OAuth provider for the authenticated user using the provided parameters. Throws an error if the user is not authenticated.\n *\n * @param {AddOauthProviderParams} params The parameters for adding an OAuth provider, including `providerName` and `oidcToken`.\n * @throws {NotAuthenticatedError} Throws if the user is not authenticated.\n * @returns {Promise<void>} A Promise that resolves when the OAuth provider is added.\n */\n public addOauthProvider = async (\n params: AddOauthProviderParams,\n ): Promise<OauthProviderInfo> => {\n if (!this.user) {\n throw new NotAuthenticatedError();\n }\n const { providerName, oidcToken } = params;\n const stampedRequest = await this.turnkeyClient.stampCreateOauthProviders({\n type: \"ACTIVITY_TYPE_CREATE_OAUTH_PROVIDERS\",\n timestampMs: Date.now().toString(),\n organizationId: this.user.orgId,\n parameters: {\n userId: this.user.userId,\n oauthProviders: [{ providerName, oidcToken }],\n },\n });\n const response = await this.request(\"/v1/add-oauth-provider\", {\n stampedRequest,\n });\n return response.oauthProviders[0];\n };\n\n /**\n * Deletes a specified OAuth provider for the authenticated user.\n *\n * @param {string} providerId The ID of the provider to be deleted\n * @throws {NotAuthenticatedError} If the user is not authenticated\n */\n public removeOauthProvider = async (providerId: string) => {\n if (!this.user) {\n throw new NotAuthenticatedError();\n }\n const stampedRequest = await this.turnkeyClient.stampDeleteOauthProviders({\n type: \"ACTIVITY_TYPE_DELETE_OAUTH_PROVIDERS\",\n timestampMs: Date.now().toString(),\n organizationId: this.user.orgId,\n parameters: {\n userId: this.user.userId,\n providerIds: [providerId],\n },\n });\n await this.request(\"/v1/remove-oauth-provider\", { stampedRequest });\n };\n\n /**\n * Retrieves the list of authentication methods for the current user.\n *\n * @returns {Promise<AuthMethods>} A promise that resolves to the list of authentication methods\n * @throws {NotAuthenticatedError} If the user is not authenticated\n */\n public listAuthMethods = async (): Promise<AuthMethods> => {\n if (!this.user) {\n throw new NotAuthenticatedError();\n }\n return await this.request(\"/v1/list-auth-methods\", {\n suborgId: this.user.orgId,\n });\n };\n\n /**\n * Retrieves the current user or fetches the user information if not already available.\n *\n * @param {string} [orgId] optional organization ID, defaults to the user's organization ID\n * @param {string} idToken an OIDC ID token containing additional user information\n * @returns {Promise<User>} A promise that resolves to the user object\n * @throws {Error} if no organization ID is provided when there is no current user\n */\n public whoami = async (\n orgId = this.user?.orgId,\n idToken?: string,\n ): Promise<User> => {\n if (this.user) {\n return this.user;\n }\n\n if (!orgId) {\n throw new Error(\"No orgId provided\");\n }\n\n const stampedRequest = await this.turnkeyClient.stampGetWhoami({\n organizationId: orgId,\n });\n\n const user = await this.request(\"/v1/whoami\", {\n stampedRequest,\n });\n\n if (idToken) {\n const claims: Record<string, unknown> = jwtDecode(idToken);\n user.idToken = idToken;\n user.claims = claims;\n if (typeof claims.email === \"string\") {\n user.email = claims.email;\n }\n }\n\n const credentialId = (() => {\n try {\n return JSON.parse(stampedRequest?.stamp.stampHeaderValue)\n .credentialId as string;\n } catch (e) {\n return undefined;\n }\n })();\n\n this.user = {\n ...user,\n credentialId,\n };\n\n return this.user;\n };\n\n /**\n * Generates a stamped whoami request for the current user. This request can then be used to call /signer/v1/whoami to get the user information.\n * This is useful if you want to get the user information in a different context like a server. You can pass the stamped request to the server\n * and then call our API to get the user information. Using this stamp is the most trusted way to get the user information since a stamp can only\n * belong to the user who created it.\n *\n * @returns {Promise<TSignedRequest>} a promise that resolves to the \"whoami\" information for the logged in user\n * @throws {Error} if no organization ID is provided\n */\n public stampWhoami = async (): Promise<TSignedRequest> => {\n if (!this.user) {\n throw new Error(\"User must be authenticated to stamp a whoami request\");\n }\n\n return await this.turnkeyClient.stampGetWhoami({\n organizationId: this.user.orgId,\n });\n };\n\n /**\n * Generates a stamped getOrganization request for the current user.\n *\n * @returns {Promise<TSignedRequest>} a promise that resolves to the \"getOrganization\" information for the logged in user\n * @throws {Error} if no user is authenticated\n */\n public stampGetOrganization = async (): Promise<TSignedRequest> => {\n if (!this.user) {\n throw new Error(\n \"User must be authenticated to stamp a get organization request\",\n );\n }\n\n return await this.turnkeyClient.stampGetOrganization({\n organizationId: this.user.orgId,\n });\n };\n\n /**\n * Creates an API key that can take any action on behalf of the current user.\n * (Note that this method is currently experimental and is subject to change.)\n *\n * @param {CreateApiKeyParams} params Parameters for creating the API key.\n * @param {string} params.name Name of the API key.\n * @param {string} params.publicKey Public key to be used for the API key.\n * @param {number} params.expirationSec Number of seconds until the API key expires.\n * @throws {Error} If there is no authenticated user or the API key creation fails.\n */\n public experimental_createApiKey = async (\n params: experimental_CreateApiKeyParams,\n ): Promise<void> => {\n if (!this.user) {\n throw new Error(\"User must be authenticated to create api key\");\n }\n const resp = await this.turnkeyClient.createApiKeys({\n type: \"ACTIVITY_TYPE_CREATE_API_KEYS_V2\",\n timestampMs: new Date().getTime().toString(),\n organizationId: this.user.orgId,\n parameters: {\n apiKeys: [\n {\n apiKeyName: params.name,\n publicKey: params.publicKey,\n curveType: \"API_KEY_CURVE_P256\",\n expirationSeconds: params.expirationSec.toString(),\n },\n ],\n userId: this.user.userId,\n },\n });\n if (resp.activity.status !== \"ACTIVITY_STATUS_COMPLETED\") {\n throw new Error(\"Failed to create api key\");\n }\n };\n\n /**\n * Looks up information based on an email address.\n *\n * @param {string} email the email address to look up\n * @returns {Promise<any>} the result of the lookup request\n */\n public lookupUserByEmail = async (email: string) => {\n return this.request(\"/v1/lookup\", { email });\n };\n\n /**\n * This will sign a message with the user's private key, without doing any transformations on the message.\n * For SignMessage or SignTypedData, the caller should hash the message before calling this method and pass\n * that result here.\n *\n * @param {Hex} msg the hex representation of the bytes to sign\n * @param {string} mode specify if signing should happen for solana or ethereum\n * @returns {Promise<Hex>} the signature over the raw hex\n */\n public signRawMessage = async (\n msg: Hex,\n mode: \"SOLANA\" | \"ETHEREUM\" = \"ETHEREUM\",\n ): Promise<Hex> => {\n if (!this.user) {\n throw new NotAuthenticatedError();\n }\n\n if (!this.user.solanaAddress && mode === \"SOLANA\") {\n // TODO: we need to add backwards compatibility for users who signed up before we added Solana support\n throw new Error(\"No Solana address available for the user\");\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:\n mode === \"ETHEREUM\"\n ? \"HASH_FUNCTION_NO_OP\"\n : \"HASH_FUNCTION_NOT_APPLICABLE\",\n payload: msg,\n signWith:\n mode === \"ETHEREUM\" ? this.user.address : this.user.solanaAddress!,\n },\n });\n\n const { signature } = await this.request(\"/v1/sign-payload\", {\n stampedRequest,\n });\n\n return signature;\n };\n\n /**\n * Returns the current user or null if no user is set.\n *\n * @returns {User | null} the current user object or null if no user is available\n */\n public getUser = (): User | null => {\n return this.user ?? null;\n };\n\n /**\n * Sends a POST request to the given signer route with the specified body and returns the response.\n * Not intended to be used directly, use the specific methods instead on the client instead.\n *\n * @param {SignerRoutes} route The route to which the request should be sent\n * @param {SignerBody<R>} body The request body containing the data to be sent\n * @returns {Promise<SignerResponse<R>>} A promise that resolves to the response from the signer\n */\n public request = async <R extends SignerRoutes>(\n route: R,\n body: SignerBody<R>,\n ): Promise<SignerResponse<R>> => {\n const url = this.connectionConfig.rpcUrl ?? \"https://api.g.alchemy.com\";\n\n const basePath = \"/signer\";\n\n const headers = new Headers();\n headers.append(\"Alchemy-AA-Sdk-Version\", VERSION);\n headers.append(\"Content-Type\", \"application/json\");\n if (this.connectionConfig.apiKey) {\n headers.append(\"Authorization\", `Bearer ${this.connectionConfig.apiKey}`);\n } else if (this.connectionConfig.jwt) {\n headers.append(\"Authorization\", `Bearer ${this.connectionConfig.jwt}`);\n }\n\n const response = await fetch(`${url}${basePath}${route}`, {\n method: \"POST\",\n body: JSON.stringify(body),\n headers,\n });\n\n if (!response.ok) {\n throw new Error(await response.text());\n }\n\n const json = await response.json();\n\n return json as SignerResponse<R>;\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 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 {AddMfaParams} params The parameters required to enable a new MFA factor\n * @returns {Promise<AddMfaResult>} 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 addMfa = async (params: AddMfaParams): Promise<AddMfaResult> => {\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 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 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 validateMultiFactors = async (\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 // #endregion\n\n // #region PRIVATE METHODS\n private exportAsSeedPhrase = async (stamper: ExportWalletStamper) => {\n if (!this.user) {\n throw new NotAuthenticatedError();\n }\n\n const { wallets } = await this.turnkeyClient.getWallets({\n organizationId: this.user.orgId,\n });\n\n const walletAccounts = await Promise.all(\n wallets.map(({ walletId }) =>\n this.turnkeyClient.getWalletAccounts({\n organizationId: this.user!.orgId,\n walletId,\n }),\n ),\n ).then((x) => x.flatMap((x) => x.accounts));\n\n const walletAccount = walletAccounts.find(\n (x) => x.address === this.user!.address,\n );\n\n if (!walletAccount) {\n throw new Error(\n `Could not find wallet associated with ${this.user.address}`,\n );\n }\n\n const { activity } = await this.turnkeyClient.exportWallet({\n organizationId: this.user.orgId,\n type: \"ACTIVITY_TYPE_EXPORT_WALLET\",\n timestampMs: Date.now().toString(),\n parameters: {\n walletId: walletAccount!.walletId,\n targetPublicKey: stamper.publicKey()!,\n },\n });\n\n const { exportBundle } = await this.pollActivityCompletion(\n activity,\n this.user.orgId,\n \"exportWalletResult\",\n );\n\n const result = await stamper.injectWalletExportBundle(\n exportBundle,\n this.user.orgId,\n );\n\n if (!result) {\n throw new Error(\"Failed to inject wallet export bundle\");\n }\n\n return result;\n };\n\n private exportAsPrivateKey = async (stamper: ExportWalletStamper) => {\n if (!this.user) {\n throw new NotAuthenticatedError();\n }\n\n const { activity } = await this.turnkeyClient.exportWalletAccount({\n organizationId: this.user.orgId,\n type: \"ACTIVITY_TYPE_EXPORT_WALLET_ACCOUNT\",\n timestampMs: Date.now().toString(),\n parameters: {\n address: this.user.address,\n targetPublicKey: stamper.publicKey()!,\n },\n });\n\n const { exportBundle } = await this.pollActivityCompletion(\n activity,\n this.user.orgId,\n \"exportWalletAccountResult\",\n );\n\n const result = await stamper.injectKeyExportBundle(\n exportBundle,\n this.user.orgId,\n );\n\n if (!result) {\n throw new Error(\"Failed to inject wallet export bundle\");\n }\n\n return result;\n };\n\n /**\n * Returns the authentication url for the selected OAuth Proivder\n *\n * @example\n * ```ts\n *\n * cosnt oauthParams = {\n * authProviderId: \"google\",\n * isCustomProvider: false,\n * auth0Connection: undefined,\n * scope: undefined,\n * claims: undefined,\n * mode: \"redirect\",\n * redirectUrl: \"https://your-url-path/oauth-return\",\n * expirationSeconds: 3000\n * };\n *\n * const turnkeyPublicKey = await this.initIframeStamper();\n * const oauthCallbackUrl = this.oauthCallbackUrl;\n * const oauthConfig = this.getOauthConfig() // Optional value for OauthConfig()\n * const usesRelativeUrl = true // Optional value to determine if we use a relative (or absolute) url for the `redirect_url`\n *\n * const oauthProviderUrl = getOauthProviderUrl({\n * oauthParams,\n * turnkeyPublicKey,\n * oauthCallbackUrl\n * })\n *\n * ```\n * @param {GetOauthProviderUrlArgs} args Required. The Oauth provider's auth parameters\n *\n * @returns {Promise<string>} returns the Oauth provider's url\n */\n protected getOauthProviderUrl = async (\n args: GetOauthProviderUrlArgs,\n ): Promise<string> => {\n const {\n oauthParams,\n turnkeyPublicKey,\n oauthCallbackUrl,\n oauthConfig,\n usesRelativeUrl = true,\n } = args;\n\n const {\n authProviderId,\n isCustomProvider,\n auth0Connection,\n scope: providedScope,\n claims: providedClaims,\n otherParameters: providedOtherParameters,\n mode,\n redirectUrl,\n expirationSeconds,\n } = oauthParams;\n\n const { codeChallenge, requestKey, authProviders } =\n oauthConfig ?? (await this.getOauthConfigForMode(mode));\n\n if (!authProviders) {\n throw new OAuthProvidersError();\n }\n\n const authProvider = authProviders.find(\n (provider) =>\n provider.id === authProviderId &&\n !!provider.isCustomProvider === !!isCustomProvider,\n );\n\n if (!authProvider) {\n throw new Error(`No auth provider found with id ${authProviderId}`);\n }\n\n let scope: string | undefined = providedScope;\n let claims: string | undefined = providedClaims;\n let otherParameters: Record<string, string> | undefined =\n providedOtherParameters;\n\n if (!isCustomProvider) {\n const defaultCustomization =\n getDefaultProviderCustomization(authProviderId);\n scope ??= defaultCustomization?.scope;\n claims ??= defaultCustomization?.claims;\n otherParameters ??= defaultCustomization?.otherParameters;\n }\n if (!scope) {\n throw new Error(`Default scope not known for provider ${authProviderId}`);\n }\n const { authEndpoint, clientId } = authProvider;\n\n const nonce = this.getOauthNonce(turnkeyPublicKey);\n const stateObject: OauthState = {\n authProviderId,\n isCustomProvider,\n requestKey,\n turnkeyPublicKey,\n expirationSeconds,\n redirectUrl:\n mode === \"redirect\"\n ? usesRelativeUrl\n ? resolveRelativeUrl(redirectUrl)\n : redirectUrl\n : undefined,\n openerOrigin: mode === \"popup\" ? window.location.origin : undefined,\n fetchIdTokenOnly: oauthParams.fetchIdTokenOnly,\n };\n const state = base64UrlEncode(\n new TextEncoder().encode(JSON.stringify(stateObject)),\n );\n const authUrl = new URL(authEndpoint);\n const params: Record<string, string> = {\n redirect_uri: oauthCallbackUrl,\n response_type: \"code\",\n scope,\n state,\n code_challenge: codeChallenge,\n code_challenge_method: \"S256\",\n prompt: \"select_account\",\n client_id: clientId,\n nonce,\n ...otherParameters,\n };\n if (claims) {\n params.claims = claims;\n }\n if (auth0Connection) {\n params.connection = auth0Connection;\n }\n\n Object.keys(params).forEach((param) => {\n params[param] && authUrl.searchParams.append(param, params[param]);\n });\n\n const [urlPath, searchParams] = authUrl.href.split(\"?\");\n\n return `${urlPath?.replace(/\\/$/, \"\")}?${searchParams}`;\n };\n\n private getOauthConfigForMode = async (\n mode: OauthMode,\n ): Promise<OauthConfig> => {\n if (this.oauthConfig) {\n return this.oauthConfig;\n } else if (mode === \"redirect\") {\n return this.initOauth();\n } else {\n throw new Error(\n \"enablePopupOauth must be set in configuration or signer.preparePopupOauth must be called before using popup-based OAuth login\",\n );\n }\n };\n\n // eslint-disable-next-line eslint-rules/require-jsdoc-on-reexported-functions\n protected pollActivityCompletion = async <\n T extends keyof Awaited<\n ReturnType<(typeof this.turnkeyClient)[\"getActivity\"]>\n >[\"activity\"][\"result\"],\n >(\n activity: Awaited<\n ReturnType<(typeof this.turnkeyClient)[\"getActivity\"]>\n >[\"activity\"],\n organizationId: string,\n resultKey: T,\n ): Promise<\n NonNullable<\n Awaited<\n ReturnType<(typeof this.turnkeyClient)[\"getActivity\"]>\n >[\"activity\"][\"result\"][T]\n >\n > => {\n if (activity.status === \"ACTIVITY_STATUS_COMPLETED\") {\n return activity.result[resultKey]!;\n }\n\n const {\n activity: { status, id, result },\n } = await this.turnkeyClient.getActivity({\n activityId: activity.id,\n organizationId,\n });\n\n if (status === \"ACTIVITY_STATUS_COMPLETED\") {\n return result[resultKey]!;\n }\n\n if (\n status === \"ACTIVITY_STATUS_FAILED\" ||\n status === \"ACTIVITY_STATUS_REJECTED\" ||\n status === \"ACTIVITY_STATUS_CONSENSUS_NEEDED\"\n ) {\n throw new Error(\n `Failed to get activity with with id ${id} (status: ${status})`,\n );\n }\n\n // TODO: add ability to configure this + add exponential backoff\n await new Promise((resolve) => setTimeout(resolve, 500));\n\n return this.pollActivityCompletion(activity, organizationId, resultKey);\n };\n // #endregion\n\n /**\n * Turnkey requires the nonce in the id token to be in this format.\n *\n * @param {string} turnkeyPublicKey key from a Turnkey iframe\n * @returns {string} nonce to be used in OIDC\n */\n protected getOauthNonce = (turnkeyPublicKey: string): string => {\n return sha256(new TextEncoder().encode(turnkeyPublicKey)).slice(2);\n };\n}\n"]}
@@ -139,7 +139,10 @@ export declare class AlchemySignerWebClient extends BaseSignerClient<ExportWalle
139
139
  private iframeStamper;
140
140
  private webauthnStamper;
141
141
  oauthCallbackUrl: string;
142
- iframeContainerId: string;
142
+ iframeConfig: {
143
+ iframeElementId: string;
144
+ iframeContainerId: string;
145
+ };
143
146
  /**
144
147
  * Initializes a new instance with the given parameters, setting up the connection, iframe configuration, and WebAuthn stamper.
145
148
  *
@@ -390,6 +393,7 @@ export declare class AlchemySignerWebClient extends BaseSignerClient<ExportWalle
390
393
  username: string;
391
394
  }) => Promise<GetWebAuthnAttestationResult>;
392
395
  protected getOauthConfig: () => Promise<OauthConfig>;
396
+ private initSessionStamperPromise;
393
397
  protected initSessionStamper(): Promise<string>;
394
398
  protected initWebauthnStamper(user?: User | undefined): Promise<void>;
395
399
  }
@@ -83,7 +83,7 @@ export class AlchemySignerWebClient extends BaseSignerClient {
83
83
  writable: true,
84
84
  value: void 0
85
85
  });
86
- Object.defineProperty(this, "iframeContainerId", {
86
+ Object.defineProperty(this, "iframeConfig", {
87
87
  enumerable: true,
88
88
  configurable: true,
89
89
  writable: true,
@@ -262,7 +262,16 @@ export class AlchemySignerWebClient extends BaseSignerClient {
262
262
  value: async () => {
263
263
  this.user = undefined;
264
264
  this.iframeStamper.clear();
265
- await this.iframeStamper.init();
265
+ // In the latest version of the TK iframe stamper, the
266
+ // IframeStamper instance seems to not be usable after
267
+ // clearing it, so we need to create a new instance.
268
+ const stamper = new IframeStamper({
269
+ iframeContainer: document.getElementById(this.iframeConfig.iframeContainerId),
270
+ iframeElementId: this.iframeConfig.iframeElementId,
271
+ iframeUrl: "https://auth.turnkey.com",
272
+ });
273
+ this.iframeStamper = stamper;
274
+ await this.initSessionStamper();
266
275
  }
267
276
  });
268
277
  /**
@@ -510,8 +519,14 @@ export class AlchemySignerWebClient extends BaseSignerClient {
510
519
  return this.request("/v1/prepare-oauth", { nonce });
511
520
  }
512
521
  });
522
+ Object.defineProperty(this, "initSessionStamperPromise", {
523
+ enumerable: true,
524
+ configurable: true,
525
+ writable: true,
526
+ value: null
527
+ });
513
528
  this.iframeStamper = iframeStamper;
514
- this.iframeContainerId = iframeConfig.iframeContainerId;
529
+ this.iframeConfig = iframeConfig;
515
530
  this.webauthnStamper = new WebauthnStamper({
516
531
  rpId: rpId ?? window.location.hostname,
517
532
  });
@@ -570,11 +585,23 @@ export class AlchemySignerWebClient extends BaseSignerClient {
570
585
  throw new Error("Failed to submit OTP code. Server did not return required fields.");
571
586
  }
572
587
  async initSessionStamper() {
573
- if (!this.iframeStamper.publicKey()) {
574
- await this.iframeStamper.init();
588
+ if (this.initSessionStamperPromise) {
589
+ return this.initSessionStamperPromise;
590
+ }
591
+ this.initSessionStamperPromise = (async () => {
592
+ if (!this.iframeStamper.publicKey()) {
593
+ await this.iframeStamper.init();
594
+ }
595
+ this.setStamper(this.iframeStamper);
596
+ return this.iframeStamper.publicKey();
597
+ })();
598
+ try {
599
+ const result = await this.initSessionStamperPromise;
600
+ return result;
601
+ }
602
+ finally {
603
+ this.initSessionStamperPromise = null;
575
604
  }
576
- this.setStamper(this.iframeStamper);
577
- return this.iframeStamper.publicKey();
578
605
  }
579
606
  async initWebauthnStamper(user = this.user) {
580
607
  this.setStamper(this.webauthnStamper);
@@ -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;AACjE,OAAO,EAAE,sBAAsB,EAAE,MAAM,eAAe,CAAC;AACvD,OAAO,EAAE,aAAa,EAAE,MAAM,yBAAy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AC;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 { generateRandomBuffer } from \"../utils/generateRandomBuffer.js\";\nimport { BaseSignerClient } from \"./base.js\";\nimport type {\n AlchemySignerClientEvents,\n AuthenticatingEventMetadata,\n CredentialCreationOptionOverrides,\n EmailAuthParams,\n ExportWalletParams,\n OauthConfig,\n OtpParams,\n User,\n SubmitOtpCodeResponse,\n AuthLinkingPrompt,\n GetWebAuthnAttestationResult,\n IdTokenOnly,\n} from \"./types.js\";\nimport { MfaRequiredError } from \"../errors.js\";\nimport { parseMfaError } from \"../utils/parseMfaError.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 * 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.initSessionStamper();\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.initSessionStamper();\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.initSessionStamper();\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 * 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<User | IdTokenOnly> => {\n const turnkeyPublicKey = await this.initSessionStamper();\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 | AuthLinkingPrompt | IdTokenOnly> => {\n const turnkeyPublicKey = await this.initSessionStamper();\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 alchemyStatus: status,\n alchemyBundle: bundle,\n alchemyOrgId: orgId,\n alchemyIdToken: idToken,\n alchemyIsSignup: isSignup,\n alchemyError,\n alchemyOtpId: otpId,\n alchemyEmail: email,\n alchemyAuthProvider: providerName,\n } = event.data;\n if (alchemyError) {\n cleanup();\n popup?.close();\n reject(new OauthFailedError(alchemyError));\n }\n if (!status) {\n // This message isn't meant for us.\n return;\n }\n cleanup();\n popup?.close();\n switch (status) {\n case \"SUCCESS\":\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 resolve(user);\n }, reject);\n break;\n case \"ACCOUNT_LINKING_CONFIRMATION_REQUIRED\":\n resolve({\n status,\n idToken,\n email,\n providerName,\n otpId,\n orgId,\n } satisfies AuthLinkingPrompt);\n break;\n case \"FETCHED_ID_TOKEN_ONLY\":\n resolve({\n status,\n idToken,\n providerName,\n } satisfies IdTokenOnly);\n break;\n default:\n reject(new Error(`Unknown status: ${status}`));\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.initSessionStamper();\n };\n\n protected override getWebAuthnAttestation = async (\n options?: CredentialCreationOptionOverrides,\n userDetails: { username: string } = {\n username: this.user?.email ?? \"anonymous\",\n },\n ): Promise<GetWebAuthnAttestationResult> => {\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.initSessionStamper();\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 protected override async initSessionStamper(): Promise<string> {\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 protected override async initWebauthnStamper(\n user: User | undefined = this.user,\n ): Promise<void> {\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\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,2BAA2B,CAAC;AAC5D,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EAAE,oBAAoB,EAAE,MAAM,kCAAkC,CAAC;AACxE,OAAO,EAAE,gBAAgB,EAAE,MAAM,WAAW,CAAC;AAe7C,OAAO,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAChD,OAAO,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAE1D,MAAM,oBAAoB,GAAG,GAAG,CAAC;AAEjC,MAAM,CAAC,MAAM,+BAA+B,GAAG,CAAC,CAAC,MAAM,CAAC;IACtD,UAAU,EAAE,sBAAsB;IAClC,YAAY,EAAE,CAAC,CAAC,MAAM,CAAC;QACrB,eAAe,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,OAAO,CAAC,gBAAgB,CAAC;QACrD,iBAAiB,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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 { generateRandomBuffer } from \"../utils/generateRandomBuffer.js\";\nimport { BaseSignerClient } from \"./base.js\";\nimport type {\n AlchemySignerClientEvents,\n AuthenticatingEventMetadata,\n CredentialCreationOptionOverrides,\n EmailAuthParams,\n ExportWalletParams,\n OauthConfig,\n OtpParams,\n User,\n SubmitOtpCodeResponse,\n AuthLinkingPrompt,\n GetWebAuthnAttestationResult,\n IdTokenOnly,\n} from \"./types.js\";\nimport { MfaRequiredError } from \"../errors.js\";\nimport { parseMfaError } from \"../utils/parseMfaError.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 iframeConfig: {\n iframeElementId: string;\n iframeContainerId: string;\n };\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.iframeConfig = iframeConfig;\n\n this.webauthnStamper = new WebauthnStamper({\n rpId: rpId ?? window.location.hostname,\n });\n\n this.oauthCallbackUrl = oauthCallbackUrl;\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.initSessionStamper();\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.initSessionStamper();\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.initSessionStamper();\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 * 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\n // In the latest version of the TK iframe stamper, the\n // IframeStamper instance seems to not be usable after\n // clearing it, so we need to create a new instance.\n const stamper = new IframeStamper({\n iframeContainer: document.getElementById(\n this.iframeConfig.iframeContainerId,\n ),\n iframeElementId: this.iframeConfig.iframeElementId,\n iframeUrl: \"https://auth.turnkey.com\",\n });\n this.iframeStamper = stamper;\n await this.initSessionStamper();\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<User | IdTokenOnly> => {\n const turnkeyPublicKey = await this.initSessionStamper();\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 | AuthLinkingPrompt | IdTokenOnly> => {\n const turnkeyPublicKey = await this.initSessionStamper();\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 alchemyStatus: status,\n alchemyBundle: bundle,\n alchemyOrgId: orgId,\n alchemyIdToken: idToken,\n alchemyIsSignup: isSignup,\n alchemyError,\n alchemyOtpId: otpId,\n alchemyEmail: email,\n alchemyAuthProvider: providerName,\n } = event.data;\n if (alchemyError) {\n cleanup();\n popup?.close();\n reject(new OauthFailedError(alchemyError));\n }\n if (!status) {\n // This message isn't meant for us.\n return;\n }\n cleanup();\n popup?.close();\n switch (status) {\n case \"SUCCESS\":\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 resolve(user);\n }, reject);\n break;\n case \"ACCOUNT_LINKING_CONFIRMATION_REQUIRED\":\n resolve({\n status,\n idToken,\n email,\n providerName,\n otpId,\n orgId,\n } satisfies AuthLinkingPrompt);\n break;\n case \"FETCHED_ID_TOKEN_ONLY\":\n resolve({\n status,\n idToken,\n providerName,\n } satisfies IdTokenOnly);\n break;\n default:\n reject(new Error(`Unknown status: ${status}`));\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.initSessionStamper();\n };\n\n protected override getWebAuthnAttestation = async (\n options?: CredentialCreationOptionOverrides,\n userDetails: { username: string } = {\n username: this.user?.email ?? \"anonymous\",\n },\n ): Promise<GetWebAuthnAttestationResult> => {\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.initSessionStamper();\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 private initSessionStamperPromise: Promise<string> | null = null;\n\n protected override async initSessionStamper(): Promise<string> {\n if (this.initSessionStamperPromise) {\n return this.initSessionStamperPromise;\n }\n\n this.initSessionStamperPromise = (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 try {\n const result = await this.initSessionStamperPromise;\n return result;\n } finally {\n this.initSessionStamperPromise = null;\n }\n }\n\n protected override async initWebauthnStamper(\n user: User | undefined = this.user,\n ): Promise<void> {\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\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 +1 @@
1
- export declare const VERSION = "4.42.0";
1
+ export declare const VERSION = "4.43.1";
@@ -1,4 +1,4 @@
1
1
  // This file is autogenerated by inject-version.ts. Any changes will be
2
2
  // overwritten on commit!
3
- export const VERSION = "4.42.0";
3
+ export const VERSION = "4.43.1";
4
4
  //# sourceMappingURL=version.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":"AAAA,uEAAuE;AACvE,yBAAyB;AACzB,MAAM,CAAC,MAAM,OAAO,GAAG,QAAQ,CAAC","sourcesContent":["// This file is autogenerated by inject-version.ts. Any changes will be\n// overwritten on commit!\nexport const VERSION = \"4.42.0\";\n"]}
1
+ {"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":"AAAA,uEAAuE;AACvE,yBAAyB;AACzB,MAAM,CAAC,MAAM,OAAO,GAAG,QAAQ,CAAC","sourcesContent":["// This file is autogenerated by inject-version.ts. Any changes will be\n// overwritten on commit!\nexport const VERSION = \"4.43.1\";\n"]}
@@ -10,8 +10,8 @@ export interface BaseSignerClientParams {
10
10
  rpId?: string;
11
11
  }
12
12
  export type ExportWalletStamper = TurnkeyClient["stamper"] & {
13
- injectWalletExportBundle(bundle: string): Promise<boolean>;
14
- injectKeyExportBundle(bundle: string): Promise<boolean>;
13
+ injectWalletExportBundle(bundle: string, orgId: string): Promise<boolean>;
14
+ injectKeyExportBundle(bundle: string, orgId: string): Promise<boolean>;
15
15
  publicKey(): string | null;
16
16
  };
17
17
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"base.d.ts","sourceRoot":"","sources":["../../../src/client/base.ts"],"names":[],"mappings":"AAAA,OAAO,EAA0B,KAAK,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAC7E,OAAO,EAAE,aAAa,EAAE,KAAK,cAAc,EAAE,MAAM,eAAe,CAAC;AACnE,OAAO,YAAY,MAAM,eAAe,CAAC;AAEzC,OAAO,EAAU,KAAK,GAAG,EAAE,MAAM,MAAM,CAAC;AAOxC,OAAO,KAAK,EACV,wBAAwB,EACxB,yBAAyB,EACzB,2BAA2B,EAC3B,mBAAmB,EACnB,eAAe,EACf,eAAe,EACf,YAAY,EACZ,YAAY,EACZ,+BAA+B,EAC/B,uBAAuB,EACvB,4BAA4B,EAC5B,SAAS,EACT,WAAW,EACX,WAAW,EAEX,SAAS,EACT,UAAU,EACV,cAAc,EACd,YAAY,EACZ,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,CAAC,aAAa,GAAI,kBAAkB,MAAM,KAAG,MAAM,CAE1D;CACH"}
@@ -139,7 +139,10 @@ export declare class AlchemySignerWebClient extends BaseSignerClient<ExportWalle
139
139
  private iframeStamper;
140
140
  private webauthnStamper;
141
141
  oauthCallbackUrl: string;
142
- iframeContainerId: string;
142
+ iframeConfig: {
143
+ iframeElementId: string;
144
+ iframeContainerId: string;
145
+ };
143
146
  /**
144
147
  * Initializes a new instance with the given parameters, setting up the connection, iframe configuration, and WebAuthn stamper.
145
148
  *
@@ -390,6 +393,7 @@ export declare class AlchemySignerWebClient extends BaseSignerClient<ExportWalle
390
393
  username: string;
391
394
  }) => Promise<GetWebAuthnAttestationResult>;
392
395
  protected getOauthConfig: () => Promise<OauthConfig>;
396
+ private initSessionStamperPromise;
393
397
  protected initSessionStamper(): Promise<string>;
394
398
  protected initWebauthnStamper(user?: User | undefined): Promise<void>;
395
399
  }
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/client/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAA0B,MAAM,cAAc,CAAC;AAIjE,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAE/C,OAAO,EAAE,gBAAgB,EAAE,MAAM,WAAW,CAAC;AAC7C,OAAO,KAAK,EACV,yBAAyB,EACzB,2BAA2B,EAC3B,iCAAiC,EACjC,eAAe,EACf,kBAAkB,EAClB,WAAW,EACX,SAAS,EACT,IAAI,EACJ,qBAAqB,EACrB,iBAAiB,EACjB,4BAA4B,EAC5B,WAAW,EACZ,MAAM,YAAY,CAAC;AAMpB,eAAO,MAAM,+BAA+B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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-1,2 +1,2 @@
1
- export declare const VERSION = "4.42.0";
1
+ export declare const VERSION = "4.43.1";
2
2
  //# sourceMappingURL=version.d.ts.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@account-kit/signer",
3
- "version": "4.42.0",
3
+ "version": "4.43.1",
4
4
  "description": "Core interfaces and clients for interfacing with the Alchemy Signer API",
5
5
  "author": "Alchemy",
6
6
  "license": "MIT",
@@ -48,11 +48,11 @@
48
48
  "typescript-template": "*"
49
49
  },
50
50
  "dependencies": {
51
- "@aa-sdk/core": "^4.42.0",
52
- "@account-kit/logging": "^4.42.0",
51
+ "@aa-sdk/core": "^4.43.1",
52
+ "@account-kit/logging": "^4.43.1",
53
53
  "@solana/web3.js": "^1.98.0",
54
- "@turnkey/http": "^2.22.0",
55
- "@turnkey/iframe-stamper": "^1.0.0",
54
+ "@turnkey/http": "^3.4.2",
55
+ "@turnkey/iframe-stamper": "^2.5.0",
56
56
  "@turnkey/viem": "^0.4.8",
57
57
  "@turnkey/webauthn-stamper": "^0.4.3",
58
58
  "bs58": "^6.0.0",
@@ -75,5 +75,5 @@
75
75
  "url": "https://github.com/alchemyplatform/aa-sdk/issues"
76
76
  },
77
77
  "homepage": "https://github.com/alchemyplatform/aa-sdk#readme",
78
- "gitHead": "924c688a7ac5de77c453cc1b1fce41f6bbf02dce"
78
+ "gitHead": "f11e22e20d988764c0431dbec6a00c921ebaabec"
79
79
  }
@@ -51,8 +51,8 @@ export interface BaseSignerClientParams {
51
51
  }
52
52
 
53
53
  export type ExportWalletStamper = TurnkeyClient["stamper"] & {
54
- injectWalletExportBundle(bundle: string): Promise<boolean>;
55
- injectKeyExportBundle(bundle: string): Promise<boolean>;
54
+ injectWalletExportBundle(bundle: string, orgId: string): Promise<boolean>;
55
+ injectKeyExportBundle(bundle: string, orgId: string): Promise<boolean>;
56
56
  publicKey(): string | null;
57
57
  };
58
58
 
@@ -936,7 +936,10 @@ export abstract class BaseSignerClient<TExportWalletParams = unknown> {
936
936
  "exportWalletResult",
937
937
  );
938
938
 
939
- const result = await stamper.injectWalletExportBundle(exportBundle);
939
+ const result = await stamper.injectWalletExportBundle(
940
+ exportBundle,
941
+ this.user.orgId,
942
+ );
940
943
 
941
944
  if (!result) {
942
945
  throw new Error("Failed to inject wallet export bundle");
@@ -966,7 +969,10 @@ export abstract class BaseSignerClient<TExportWalletParams = unknown> {
966
969
  "exportWalletAccountResult",
967
970
  );
968
971
 
969
- const result = await stamper.injectKeyExportBundle(exportBundle);
972
+ const result = await stamper.injectKeyExportBundle(
973
+ exportBundle,
974
+ this.user.orgId,
975
+ );
970
976
 
971
977
  if (!result) {
972
978
  throw new Error("Failed to inject wallet export bundle");
@@ -55,7 +55,10 @@ export class AlchemySignerWebClient extends BaseSignerClient<ExportWalletParams>
55
55
  private iframeStamper: IframeStamper;
56
56
  private webauthnStamper: WebauthnStamper;
57
57
  oauthCallbackUrl: string;
58
- iframeContainerId: string;
58
+ iframeConfig: {
59
+ iframeElementId: string;
60
+ iframeContainerId: string;
61
+ };
59
62
 
60
63
  /**
61
64
  * Initializes a new instance with the given parameters, setting up the connection, iframe configuration, and WebAuthn stamper.
@@ -97,7 +100,7 @@ export class AlchemySignerWebClient extends BaseSignerClient<ExportWalletParams>
97
100
  });
98
101
 
99
102
  this.iframeStamper = iframeStamper;
100
- this.iframeContainerId = iframeConfig.iframeContainerId;
103
+ this.iframeConfig = iframeConfig;
101
104
 
102
105
  this.webauthnStamper = new WebauthnStamper({
103
106
  rpId: rpId ?? window.location.hostname,
@@ -350,7 +353,19 @@ export class AlchemySignerWebClient extends BaseSignerClient<ExportWalletParams>
350
353
  public override disconnect = async () => {
351
354
  this.user = undefined;
352
355
  this.iframeStamper.clear();
353
- await this.iframeStamper.init();
356
+
357
+ // In the latest version of the TK iframe stamper, the
358
+ // IframeStamper instance seems to not be usable after
359
+ // clearing it, so we need to create a new instance.
360
+ const stamper = new IframeStamper({
361
+ iframeContainer: document.getElementById(
362
+ this.iframeConfig.iframeContainerId,
363
+ ),
364
+ iframeElementId: this.iframeConfig.iframeElementId,
365
+ iframeUrl: "https://auth.turnkey.com",
366
+ });
367
+ this.iframeStamper = stamper;
368
+ await this.initSessionStamper();
354
369
  };
355
370
 
356
371
  /**
@@ -610,14 +625,29 @@ export class AlchemySignerWebClient extends BaseSignerClient<ExportWalletParams>
610
625
  return this.request("/v1/prepare-oauth", { nonce });
611
626
  };
612
627
 
628
+ private initSessionStamperPromise: Promise<string> | null = null;
629
+
613
630
  protected override async initSessionStamper(): Promise<string> {
614
- if (!this.iframeStamper.publicKey()) {
615
- await this.iframeStamper.init();
631
+ if (this.initSessionStamperPromise) {
632
+ return this.initSessionStamperPromise;
616
633
  }
617
634
 
618
- this.setStamper(this.iframeStamper);
635
+ this.initSessionStamperPromise = (async () => {
636
+ if (!this.iframeStamper.publicKey()) {
637
+ await this.iframeStamper.init();
638
+ }
639
+
640
+ this.setStamper(this.iframeStamper);
641
+
642
+ return this.iframeStamper.publicKey()!;
643
+ })();
619
644
 
620
- return this.iframeStamper.publicKey()!;
645
+ try {
646
+ const result = await this.initSessionStamperPromise;
647
+ return result;
648
+ } finally {
649
+ this.initSessionStamperPromise = null;
650
+ }
621
651
  }
622
652
 
623
653
  protected override async initWebauthnStamper(
package/src/version.ts CHANGED
@@ -1,3 +1,3 @@
1
1
  // This file is autogenerated by inject-version.ts. Any changes will be
2
2
  // overwritten on commit!
3
- export const VERSION = "4.42.0";
3
+ export const VERSION = "4.43.1";