@account-kit/signer 4.60.1 → 4.61.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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,EACL,UAAU,EACV,gBAAgB,EAChB,kBAAkB,EAClB,MAAM,GAGP,MAAM,MAAM,CAAC;AACd,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;AAoCzD,OAAO,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AACxC,OAAO,EAAE,SAAS,EAAE,MAAM,yBAAyB,CAAC;AACpD,OAAO,EAAE,KAAK,EAAE,MAAM,kBAAkB,CAAC;AAezC,MAAM,WAAW,GAAG;IAClB,GAAG,EAAE,SAAS;IACd,GAAG,EAAE,SAAS;IACd,MAAM,EAAE,aAAa;IACrB,MAAM,EAAE,YAAY;IACpB,IAAI,EAAE,WAAW;CACT,CAAC;AAEX,MAAM,aAAa,GAAG,CAAC,GAAW,EAAE,EAAE,CAAC,KAAK,GAAG,EAAW,CAAC;AAE3D;;GAEG;AACH,MAAM,OAAgB,gBAAgB;IAOpC;;;;OAIG;IACH,YAAY,MAA8B;QAXlC;;;;;WAAwB;QACxB;;;;;WAAmC;Q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AG,MAAM,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;YACtC,aAAa,EAAE,MAAM,CAAC,aAAa;SACpC,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;CA+rCF","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 {\n hexToBytes,\n recoverPublicKey,\n serializeSignature,\n sha256,\n type Address,\n type Hex,\n} 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 JwtParams,\n JwtResponse,\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 SmsAuthParams,\n} from \"./types.js\";\nimport { VERSION } from \"../version.js\";\nimport { secp256k1 } from \"@noble/curves/secp256k1\";\nimport { Point } from \"@noble/secp256k1\";\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\nconst withHexPrefix = (hex: string) => `0x${hex}` 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 if (params.type === \"sms\") {\n this.eventEmitter.emit(\"authenticating\", { type: \"otp\" });\n const { phone } = params;\n const publicKey = await this.initSessionStamper();\n\n const response = await this.request(\"/v1/signup\", {\n phone,\n targetPublicKey: publicKey,\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 solanaAddress: result.solanaAddress,\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 initSmsAuth(\n params: Omit<SmsAuthParams, \"targetPublicKey\">,\n ): Promise<{ orgId: string; otpId?: string }>;\n\n public abstract completeAuthWithBundle(params: {\n bundle: string;\n orgId: string;\n connectedEventName: keyof AlchemySignerClientEvents;\n authenticatingType: AuthenticatingEventMetadata[\"type\"];\n idToken?: string;\n accessToken?: 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 submitJwt(\n args: Omit<JwtParams, \"targetPublicKey\">,\n ): Promise<JwtResponse>;\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 * @param {string} accessToken an access token which if provided will be added to the user\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 accessToken?: 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 if (accessToken) {\n user.accessToken = accessToken;\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 * Looks up information based on a phone number.\n *\n * @param {string} phone the phone number to look up\n * @returns {Promise<any>} the result of the lookup request\n */\n public lookupUserByPhone = async (phone: string) => {\n return this.request(\"/v1/lookup\", { phone });\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 private experimental_createMultiOwnerStamper = () => ({\n stamp: async (\n request: string,\n ): Promise<{\n stampHeaderName: string;\n stampHeaderValue: string;\n }> => {\n if (!this.user) {\n throw new NotAuthenticatedError();\n }\n\n // we need this later to recover the public key from the signature, so we don't let turnkey hash\n // this for us and pass HASH_FUNCTION_NO_OP instead\n const hashed = sha256(new TextEncoder().encode(request));\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_TEXT_UTF8\",\n hashFunction: \"HASH_FUNCTION_SHA256\",\n payload: request,\n signWith: this.user.address,\n },\n });\n\n const { signature } = await this.request(\"/v1/sign-payload\", {\n stampedRequest,\n });\n\n // recover the public key, we can't just use the address\n const recoveredPublicKey = await recoverPublicKey({\n hash: hashed,\n signature,\n });\n\n // compute the stamp over the original payload using this signature\n // the format here is important\n const stamp = {\n publicKey: Point.fromHex(hexToBytes(recoveredPublicKey)).toHex(true),\n scheme: \"SIGNATURE_SCHEME_TK_API_SECP256K1\",\n signature: secp256k1.Signature.fromCompact(\n hexToBytes(signature).slice(0, 64),\n ).toDERHex(),\n };\n\n return {\n stampHeaderName: \"X-Stamp\",\n stampHeaderValue: base64UrlEncode(Buffer.from(JSON.stringify(stamp))),\n };\n },\n });\n\n private experimental_createMultiOwnerTurnkeyClient = () =>\n new TurnkeyClient(\n { baseUrl: \"https://api.turnkey.com\" },\n this.experimental_createMultiOwnerStamper(),\n );\n\n /**\n * This will sign on behalf of the multi-owner org, 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} orgId orgId of the multi-owner org to sign on behalf of\n * @param {string} orgAddress address of the multi-owner org to sign on behalf of\n * @returns {Promise<Hex>} the signature over the raw hex\n */\n public experimental_multiOwnerSignRawMessage = async (\n msg: Hex,\n orgId: string,\n orgAddress: string,\n ) => {\n if (!this.user) {\n throw new NotAuthenticatedError();\n }\n const multiOwnerClient = this.experimental_createMultiOwnerTurnkeyClient();\n\n const { result } = await this.request(\"/v1/multi-owner-sign-raw-payload\", {\n stampedRequest: await multiOwnerClient.stampSignRawPayload({\n organizationId: 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: msg,\n signWith: orgAddress,\n },\n }),\n });\n\n return serializeSignature({\n r: withHexPrefix(result.signRawPayloadResult.r),\n s: withHexPrefix(result.signRawPayloadResult.s),\n yParity: Number(result.signRawPayloadResult.v), // this is not actually a legacy v value, it's the y parity bit\n });\n };\n\n /**\n * This will create a multi-owner account with the current user and additional specified signers\n *\n * @param {Address[]} additionalMembers members to add, aside from the currently authenticated user\n * @returns {Promise<SignerResponse<\"/v1/multi-owner-create\">['result']>} created multi-owner account\n */\n public experimental_createMultiOwner = async (\n additionalMembers: Address[],\n ) => {\n if (!this.user) {\n throw new NotAuthenticatedError();\n }\n\n const response = await this.request(\"/v1/multi-owner-create\", {\n members: [this.user.address, ...additionalMembers].map(\n (evmSignerAddress) => ({ evmSignerAddress }),\n ),\n });\n\n return response.result;\n };\n\n /**\n * This will add additional members to an existing multi-sig account\n *\n * @param {string} orgId orgId of the multi-sig to add members to\n * @param {Address[]} members the addresses of the members to add\n */\n public experimental_addToMultiOwner = async (\n orgId: string,\n members: Address[],\n ) => {\n if (!this.user) {\n throw new NotAuthenticatedError();\n }\n\n const multiOwnerClient = this.experimental_createMultiOwnerTurnkeyClient();\n\n const prepared = await this.request(\"/v1/multi-owner-prepare-add\", {\n organizationId: orgId,\n members: members.map((evmSignerAddress) => ({ evmSignerAddress })),\n });\n\n const stampedRequest = await multiOwnerClient.stampCreateUsers(\n prepared.result,\n );\n\n const {\n result: { updateRootQuorumRequest },\n } = await this.request(\"/v1/multi-owner-add\", {\n stampedRequest,\n });\n\n await this.request(\"/v1/multi-owner-update-root-quorum\", {\n stampedRequest: await multiOwnerClient.stampUpdateRootQuorum(\n updateRootQuorumRequest,\n ),\n });\n };\n\n /**\n * This will remove members from an existing multi-sig account\n *\n * @param {string} orgId orgId of the multi-sig to remove members from\n * @param {Address[]} members the addresses of the members to remove\n */\n public experimental_deleteFromMultiOwner = async (\n orgId: string,\n members: Address[],\n ) => {\n if (!this.user) {\n throw new NotAuthenticatedError();\n }\n\n const multiOwnerClient = this.experimental_createMultiOwnerTurnkeyClient();\n\n const prepared = await this.request(\"/v1/multi-owner-prepare-delete\", {\n organizationId: orgId,\n members: members.map((evmSignerAddress) => ({ evmSignerAddress })),\n });\n\n const stampedRequest = await multiOwnerClient.stampDeleteUsers(\n prepared.result.deleteMembersRequest,\n );\n\n await this.request(\"/v1/multi-owner-update-root-quorum\", {\n stampedRequest: await multiOwnerClient.stampUpdateRootQuorum(\n prepared.result.updateRootQuorumRequest,\n ),\n });\n\n await this.request(\"/v1/multi-owner-delete\", {\n stampedRequest,\n });\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"]}
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,EACL,UAAU,EACV,gBAAgB,EAChB,kBAAkB,EAClB,MAAM,GAGP,MAAM,MAAM,CAAC;AACd,OAAO,EAAE,qBAAqB,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAA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CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,MAAM,CAAC,QAAQ,EAAE,CACjE,CAAC;QAEF,MAAM,MAAM,GAAG,MAAM,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;YACtC,aAAa,EAAE,MAAM,CAAC,aAAa;SACpC,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;CAymCF","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 {\n hexToBytes,\n recoverPublicKey,\n serializeSignature,\n sha256,\n type Address,\n type Hex,\n} 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 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 JwtParams,\n JwtResponse,\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 SmsAuthParams,\n} from \"./types.js\";\nimport { VERSION } from \"../version.js\";\nimport { secp256k1 } from \"@noble/curves/secp256k1\";\nimport { Point } from \"@noble/secp256k1\";\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\nconst withHexPrefix = (hex: string) => `0x${hex}` as const;\n\n/**\n * Base class for all Alchemy Signer clients\n */\nexport abstract class BaseSignerClient<\n TExportWalletParams = unknown,\n TExportWalletOutput = unknown,\n> {\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 * 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 if (params.type === \"sms\") {\n this.eventEmitter.emit(\"authenticating\", { type: \"otp\" });\n const { phone } = params;\n const publicKey = await this.initSessionStamper();\n\n const response = await this.request(\"/v1/signup\", {\n phone,\n targetPublicKey: publicKey,\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 solanaAddress: result.solanaAddress,\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 initSmsAuth(\n params: Omit<SmsAuthParams, \"targetPublicKey\">,\n ): Promise<{ orgId: string; otpId?: string }>;\n\n public abstract completeAuthWithBundle(params: {\n bundle: string;\n orgId: string;\n connectedEventName: keyof AlchemySignerClientEvents;\n authenticatingType: AuthenticatingEventMetadata[\"type\"];\n idToken?: string;\n accessToken?: 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 submitJwt(\n args: Omit<JwtParams, \"targetPublicKey\">,\n ): Promise<JwtResponse>;\n\n public abstract disconnect(): Promise<void>;\n\n public abstract exportWallet(\n params: TExportWalletParams,\n ): Promise<TExportWalletOutput>;\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 * @param {string} accessToken an access token which if provided will be added to the user\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 accessToken?: 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 if (accessToken) {\n user.accessToken = accessToken;\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 * Looks up information based on a phone number.\n *\n * @param {string} phone the phone number to look up\n * @returns {Promise<any>} the result of the lookup request\n */\n public lookupUserByPhone = async (phone: string) => {\n return this.request(\"/v1/lookup\", { phone });\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 private experimental_createMultiOwnerStamper = () => ({\n stamp: async (\n request: string,\n ): Promise<{\n stampHeaderName: string;\n stampHeaderValue: string;\n }> => {\n if (!this.user) {\n throw new NotAuthenticatedError();\n }\n\n // we need this later to recover the public key from the signature, so we don't let turnkey hash\n // this for us and pass HASH_FUNCTION_NO_OP instead\n const hashed = sha256(new TextEncoder().encode(request));\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_TEXT_UTF8\",\n hashFunction: \"HASH_FUNCTION_SHA256\",\n payload: request,\n signWith: this.user.address,\n },\n });\n\n const { signature } = await this.request(\"/v1/sign-payload\", {\n stampedRequest,\n });\n\n // recover the public key, we can't just use the address\n const recoveredPublicKey = await recoverPublicKey({\n hash: hashed,\n signature,\n });\n\n // compute the stamp over the original payload using this signature\n // the format here is important\n const stamp = {\n publicKey: Point.fromHex(hexToBytes(recoveredPublicKey)).toHex(true),\n scheme: \"SIGNATURE_SCHEME_TK_API_SECP256K1\",\n signature: secp256k1.Signature.fromCompact(\n hexToBytes(signature).slice(0, 64),\n ).toDERHex(),\n };\n\n return {\n stampHeaderName: \"X-Stamp\",\n stampHeaderValue: base64UrlEncode(Buffer.from(JSON.stringify(stamp))),\n };\n },\n });\n\n private experimental_createMultiOwnerTurnkeyClient = () =>\n new TurnkeyClient(\n { baseUrl: \"https://api.turnkey.com\" },\n this.experimental_createMultiOwnerStamper(),\n );\n\n /**\n * This will sign on behalf of the multi-owner org, 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} orgId orgId of the multi-owner org to sign on behalf of\n * @param {string} orgAddress address of the multi-owner org to sign on behalf of\n * @returns {Promise<Hex>} the signature over the raw hex\n */\n public experimental_multiOwnerSignRawMessage = async (\n msg: Hex,\n orgId: string,\n orgAddress: string,\n ) => {\n if (!this.user) {\n throw new NotAuthenticatedError();\n }\n const multiOwnerClient = this.experimental_createMultiOwnerTurnkeyClient();\n\n const { result } = await this.request(\"/v1/multi-owner-sign-raw-payload\", {\n stampedRequest: await multiOwnerClient.stampSignRawPayload({\n organizationId: 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: msg,\n signWith: orgAddress,\n },\n }),\n });\n\n return serializeSignature({\n r: withHexPrefix(result.signRawPayloadResult.r),\n s: withHexPrefix(result.signRawPayloadResult.s),\n yParity: Number(result.signRawPayloadResult.v), // this is not actually a legacy v value, it's the y parity bit\n });\n };\n\n /**\n * This will create a multi-owner account with the current user and additional specified signers\n *\n * @param {Address[]} additionalMembers members to add, aside from the currently authenticated user\n * @returns {Promise<SignerResponse<\"/v1/multi-owner-create\">['result']>} created multi-owner account\n */\n public experimental_createMultiOwner = async (\n additionalMembers: Address[],\n ) => {\n if (!this.user) {\n throw new NotAuthenticatedError();\n }\n\n const response = await this.request(\"/v1/multi-owner-create\", {\n members: [this.user.address, ...additionalMembers].map(\n (evmSignerAddress) => ({ evmSignerAddress }),\n ),\n });\n\n return response.result;\n };\n\n /**\n * This will add additional members to an existing multi-sig account\n *\n * @param {string} orgId orgId of the multi-sig to add members to\n * @param {Address[]} members the addresses of the members to add\n */\n public experimental_addToMultiOwner = async (\n orgId: string,\n members: Address[],\n ) => {\n if (!this.user) {\n throw new NotAuthenticatedError();\n }\n\n const multiOwnerClient = this.experimental_createMultiOwnerTurnkeyClient();\n\n const prepared = await this.request(\"/v1/multi-owner-prepare-add\", {\n organizationId: orgId,\n members: members.map((evmSignerAddress) => ({ evmSignerAddress })),\n });\n\n const stampedRequest = await multiOwnerClient.stampCreateUsers(\n prepared.result,\n );\n\n const {\n result: { updateRootQuorumRequest },\n } = await this.request(\"/v1/multi-owner-add\", {\n stampedRequest,\n });\n\n await this.request(\"/v1/multi-owner-update-root-quorum\", {\n stampedRequest: await multiOwnerClient.stampUpdateRootQuorum(\n updateRootQuorumRequest,\n ),\n });\n };\n\n /**\n * This will remove members from an existing multi-sig account\n *\n * @param {string} orgId orgId of the multi-sig to remove members from\n * @param {Address[]} members the addresses of the members to remove\n */\n public experimental_deleteFromMultiOwner = async (\n orgId: string,\n members: Address[],\n ) => {\n if (!this.user) {\n throw new NotAuthenticatedError();\n }\n\n const multiOwnerClient = this.experimental_createMultiOwnerTurnkeyClient();\n\n const prepared = await this.request(\"/v1/multi-owner-prepare-delete\", {\n organizationId: orgId,\n members: members.map((evmSignerAddress) => ({ evmSignerAddress })),\n });\n\n const stampedRequest = await multiOwnerClient.stampDeleteUsers(\n prepared.result.deleteMembersRequest,\n );\n\n await this.request(\"/v1/multi-owner-update-root-quorum\", {\n stampedRequest: await multiOwnerClient.stampUpdateRootQuorum(\n prepared.result.updateRootQuorumRequest,\n ),\n });\n\n await this.request(\"/v1/multi-owner-delete\", {\n stampedRequest,\n });\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\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,8 +1,8 @@
1
1
  import { BaseError } from "@aa-sdk/core";
2
2
  import { z } from "zod";
3
3
  import type { AuthParams } from "../signer.js";
4
- import { BaseSignerClient } from "./base.js";
5
- import type { AlchemySignerClientEvents, AuthenticatingEventMetadata, CredentialCreationOptionOverrides, EmailAuthParams, ExportWalletParams, OauthConfig, OtpParams, JwtParams, JwtResponse, User, SubmitOtpCodeResponse, AuthLinkingPrompt, GetWebAuthnAttestationResult, IdTokenOnly, SmsAuthParams } from "./types.js";
4
+ import { BaseSignerClient, type ExportWalletStamper } from "./base.js";
5
+ import type { AlchemySignerClientEvents, AuthenticatingEventMetadata, CredentialCreationOptionOverrides, EmailAuthParams, ExportWalletParams, OauthConfig, OtpParams, JwtParams, JwtResponse, User, SubmitOtpCodeResponse, AuthLinkingPrompt, GetWebAuthnAttestationResult, IdTokenOnly, SmsAuthParams, ExportWalletOutput } from "./types.js";
6
6
  export declare const AlchemySignerClientParamsSchema: z.ZodObject<{
7
7
  connection: z.ZodIntersection<z.ZodUnion<[z.ZodObject<{
8
8
  rpcUrl: z.ZodOptional<z.ZodNever>;
@@ -135,7 +135,7 @@ export type AlchemySignerClientParams = z.input<typeof AlchemySignerClientParams
135
135
  * A lower level client used by the AlchemySigner used to communicate with
136
136
  * Alchemy's signer service.
137
137
  */
138
- export declare class AlchemySignerWebClient extends BaseSignerClient<ExportWalletParams> {
138
+ export declare class AlchemySignerWebClient extends BaseSignerClient<ExportWalletParams, ExportWalletOutput> {
139
139
  private iframeStamper;
140
140
  private webauthnStamper;
141
141
  oauthCallbackUrl: string;
@@ -340,7 +340,19 @@ export declare class AlchemySignerWebClient extends BaseSignerClient<ExportWalle
340
340
  * @param {string} [config.iframeElementId] Optional ID for the iframe element
341
341
  * @returns {Promise<void>} A promise that resolves when the export process is complete
342
342
  */
343
- exportWallet: ({ iframeContainerId, iframeElementId, }: ExportWalletParams) => Promise<boolean>;
343
+ exportWallet: ({ iframeContainerId, iframeElementId, }: ExportWalletParams) => Promise<ExportWalletOutput>;
344
+ /**
345
+ * Exports wallet credentials based on the specified type, either as a SEED_PHRASE or PRIVATE_KEY.
346
+ *
347
+ * @param {object} params The parameters for exporting the wallet
348
+ * @param {ExportWalletStamper} params.exportStamper The stamper used for exporting the wallet
349
+ * @param {"SEED_PHRASE" | "PRIVATE_KEY"} params.exportAs Specifies the format for exporting the wallet, either as a SEED_PHRASE or PRIVATE_KEY
350
+ * @returns {Promise<boolean>} A promise that resolves to true if the export is successful
351
+ */
352
+ protected exportWalletInner(params: {
353
+ exportStamper: ExportWalletStamper;
354
+ exportAs: "SEED_PHRASE" | "PRIVATE_KEY";
355
+ }): Promise<ExportWalletOutput>;
344
356
  /**
345
357
  * Asynchronous function that clears the user and resets the iframe stamper.
346
358
  *
@@ -451,6 +463,8 @@ export declare class AlchemySignerWebClient extends BaseSignerClient<ExportWalle
451
463
  private initSessionStamperPromise;
452
464
  protected initSessionStamper(): Promise<string>;
453
465
  protected initWebauthnStamper(user?: User | undefined): Promise<void>;
466
+ private exportAsSeedPhrase;
467
+ private exportAsPrivateKey;
454
468
  }
455
469
  /**
456
470
  * This error is thrown when the OAuth flow is cancelled because the auth popup
@@ -4,7 +4,9 @@ import { IframeStamper } from "@turnkey/iframe-stamper";
4
4
  import { WebauthnStamper } from "@turnkey/webauthn-stamper";
5
5
  import { z } from "zod";
6
6
  import { generateRandomBuffer } from "../utils/generateRandomBuffer.js";
7
+ import { assertNever } from "../utils/typeAssertions.js";
7
8
  import { BaseSignerClient } from "./base.js";
9
+ import { NotAuthenticatedError } from "../errors.js";
8
10
  import { MfaRequiredError } from "../errors.js";
9
11
  import { parseMfaError } from "../utils/parseMfaError.js";
10
12
  const CHECK_CLOSE_INTERVAL = 500;
@@ -565,6 +567,68 @@ export class AlchemySignerWebClient extends BaseSignerClient {
565
567
  writable: true,
566
568
  value: null
567
569
  });
570
+ Object.defineProperty(this, "exportAsSeedPhrase", {
571
+ enumerable: true,
572
+ configurable: true,
573
+ writable: true,
574
+ value: async (stamper) => {
575
+ if (!this.user) {
576
+ throw new NotAuthenticatedError();
577
+ }
578
+ const { wallets } = await this.turnkeyClient.getWallets({
579
+ organizationId: this.user.orgId,
580
+ });
581
+ const walletAccountResponses = await Promise.all(wallets.map(({ walletId }) => this.turnkeyClient.getWalletAccounts({
582
+ organizationId: this.user.orgId,
583
+ walletId,
584
+ })));
585
+ const walletAccounts = walletAccountResponses.flatMap((x) => x.accounts);
586
+ const walletAccount = walletAccounts.find((x) => x.address.toLowerCase() === this.user.address.toLowerCase());
587
+ if (!walletAccount) {
588
+ throw new Error(`Could not find wallet associated with ${this.user.address}`);
589
+ }
590
+ const { activity } = await this.turnkeyClient.exportWallet({
591
+ organizationId: this.user.orgId,
592
+ type: "ACTIVITY_TYPE_EXPORT_WALLET",
593
+ timestampMs: Date.now().toString(),
594
+ parameters: {
595
+ walletId: walletAccount.walletId,
596
+ targetPublicKey: stamper.publicKey(),
597
+ },
598
+ });
599
+ const { exportBundle } = await this.pollActivityCompletion(activity, this.user.orgId, "exportWalletResult");
600
+ const result = await stamper.injectWalletExportBundle(exportBundle, this.user.orgId);
601
+ if (!result) {
602
+ throw new Error("Failed to inject wallet export bundle");
603
+ }
604
+ return result;
605
+ }
606
+ });
607
+ Object.defineProperty(this, "exportAsPrivateKey", {
608
+ enumerable: true,
609
+ configurable: true,
610
+ writable: true,
611
+ value: async (stamper) => {
612
+ if (!this.user) {
613
+ throw new NotAuthenticatedError();
614
+ }
615
+ const { activity } = await this.turnkeyClient.exportWalletAccount({
616
+ organizationId: this.user.orgId,
617
+ type: "ACTIVITY_TYPE_EXPORT_WALLET_ACCOUNT",
618
+ timestampMs: Date.now().toString(),
619
+ parameters: {
620
+ address: this.user.address,
621
+ targetPublicKey: stamper.publicKey(),
622
+ },
623
+ });
624
+ const { exportBundle } = await this.pollActivityCompletion(activity, this.user.orgId, "exportWalletAccountResult");
625
+ const result = await stamper.injectKeyExportBundle(exportBundle, this.user.orgId);
626
+ if (!result) {
627
+ throw new Error("Failed to inject wallet export bundle");
628
+ }
629
+ return result;
630
+ }
631
+ });
568
632
  this.iframeStamper = iframeStamper;
569
633
  this.iframeConfig = iframeConfig;
570
634
  this.webauthnStamper = new WebauthnStamper({
@@ -659,6 +723,25 @@ export class AlchemySignerWebClient extends BaseSignerClient {
659
723
  expirationSeconds: args.expirationSeconds,
660
724
  });
661
725
  }
726
+ /**
727
+ * Exports wallet credentials based on the specified type, either as a SEED_PHRASE or PRIVATE_KEY.
728
+ *
729
+ * @param {object} params The parameters for exporting the wallet
730
+ * @param {ExportWalletStamper} params.exportStamper The stamper used for exporting the wallet
731
+ * @param {"SEED_PHRASE" | "PRIVATE_KEY"} params.exportAs Specifies the format for exporting the wallet, either as a SEED_PHRASE or PRIVATE_KEY
732
+ * @returns {Promise<boolean>} A promise that resolves to true if the export is successful
733
+ */
734
+ exportWalletInner(params) {
735
+ const { exportAs } = params;
736
+ switch (exportAs) {
737
+ case "PRIVATE_KEY":
738
+ return this.exportAsPrivateKey(params.exportStamper);
739
+ case "SEED_PHRASE":
740
+ return this.exportAsSeedPhrase(params.exportStamper);
741
+ default:
742
+ assertNever(exportAs, `Unknown export mode: ${exportAs}`);
743
+ }
744
+ }
662
745
  async initSessionStamper() {
663
746
  if (this.initSessionStamperPromise) {
664
747
  return this.initSessionStamperPromise;