@account-kit/signer 4.40.0 → 4.42.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/esm/base.d.ts +61 -1
- package/dist/esm/base.js +148 -1
- package/dist/esm/base.js.map +1 -1
- package/dist/esm/client/base.d.ts +47 -4
- package/dist/esm/client/base.js +139 -1
- package/dist/esm/client/base.js.map +1 -1
- package/dist/esm/client/index.d.ts +3 -3
- package/dist/esm/client/index.js +7 -0
- package/dist/esm/client/index.js.map +1 -1
- package/dist/esm/client/types.d.ts +44 -0
- package/dist/esm/client/types.js.map +1 -1
- package/dist/esm/version.d.ts +1 -1
- package/dist/esm/version.js +1 -1
- package/dist/esm/version.js.map +1 -1
- package/dist/types/base.d.ts +61 -1
- package/dist/types/base.d.ts.map +1 -1
- package/dist/types/client/base.d.ts +47 -4
- package/dist/types/client/base.d.ts.map +1 -1
- package/dist/types/client/index.d.ts +3 -3
- package/dist/types/client/index.d.ts.map +1 -1
- package/dist/types/client/types.d.ts +44 -0
- package/dist/types/client/types.d.ts.map +1 -1
- package/dist/types/version.d.ts +1 -1
- package/package.json +5 -5
- package/src/base.ts +148 -1
- package/src/client/base.ts +123 -4
- package/src/client/index.ts +10 -2
- package/src/client/types.ts +46 -0
- package/src/version.ts +1 -1
|
@@ -2,7 +2,7 @@ import { type ConnectionConfig } from "@aa-sdk/core";
|
|
|
2
2
|
import { TurnkeyClient, type TSignedRequest } from "@turnkey/http";
|
|
3
3
|
import EventEmitter from "eventemitter3";
|
|
4
4
|
import { type Hex } from "viem";
|
|
5
|
-
import type { AlchemySignerClientEvent, AlchemySignerClientEvents, AuthenticatingEventMetadata, CreateAccountParams, RemoveMfaParams, EmailAuthParams, AddMfaParams, AddMfaResult, experimental_CreateApiKeyParams, GetOauthProviderUrlArgs, GetWebAuthnAttestationResult, MfaFactor, OauthConfig, OauthParams, OtpParams, SignerBody, SignerResponse, SignerRoutes, SignupResponse, User, VerifyMfaParams, SubmitOtpCodeResponse, ValidateMultiFactorsParams, AuthLinkingPrompt, AddOauthProviderParams, CredentialCreationOptionOverrides } from "./types.js";
|
|
5
|
+
import type { AlchemySignerClientEvent, AlchemySignerClientEvents, AuthenticatingEventMetadata, CreateAccountParams, RemoveMfaParams, EmailAuthParams, AddMfaParams, AddMfaResult, experimental_CreateApiKeyParams, GetOauthProviderUrlArgs, GetWebAuthnAttestationResult, MfaFactor, OauthConfig, OauthParams, OtpParams, SignerBody, SignerResponse, SignerRoutes, SignupResponse, User, VerifyMfaParams, SubmitOtpCodeResponse, ValidateMultiFactorsParams, AuthLinkingPrompt, AddOauthProviderParams, CredentialCreationOptionOverrides, OauthProviderInfo, IdTokenOnly, AuthMethods } from "./types.js";
|
|
6
6
|
export interface BaseSignerClientParams {
|
|
7
7
|
stamper: TurnkeyClient["stamper"];
|
|
8
8
|
connection: ConnectionConfig;
|
|
@@ -77,10 +77,10 @@ export declare abstract class BaseSignerClient<TExportWalletParams = unknown> {
|
|
|
77
77
|
}): Promise<User>;
|
|
78
78
|
abstract oauthWithRedirect(args: Extract<OauthParams, {
|
|
79
79
|
mode: "redirect";
|
|
80
|
-
}>): Promise<User>;
|
|
80
|
+
}>): Promise<User | IdTokenOnly>;
|
|
81
81
|
abstract oauthWithPopup(args: Extract<OauthParams, {
|
|
82
82
|
mode: "popup";
|
|
83
|
-
}>): Promise<User | AuthLinkingPrompt>;
|
|
83
|
+
}>): Promise<User | AuthLinkingPrompt | IdTokenOnly>;
|
|
84
84
|
abstract submitOtpCode(args: Omit<OtpParams, "targetPublicKey">): Promise<SubmitOtpCodeResponse>;
|
|
85
85
|
abstract disconnect(): Promise<void>;
|
|
86
86
|
abstract exportWallet(params: TExportWalletParams): Promise<boolean>;
|
|
@@ -102,6 +102,27 @@ export declare abstract class BaseSignerClient<TExportWalletParams = unknown> {
|
|
|
102
102
|
* @returns {() => void} a function that will remove the listener when called
|
|
103
103
|
*/
|
|
104
104
|
on: <E extends AlchemySignerClientEvent>(event: E, listener: AlchemySignerClientEvents[E]) => () => EventEmitter<AlchemySignerClientEvents, any>;
|
|
105
|
+
/**
|
|
106
|
+
* Sets the email for the authenticated user, allowing them to login with that
|
|
107
|
+
* email.
|
|
108
|
+
*
|
|
109
|
+
* You must contact Alchemy to enable this feature for your team, as there are
|
|
110
|
+
* important security considerations. In particular, you must not call this
|
|
111
|
+
* without first validating that the user owns this email account.
|
|
112
|
+
*
|
|
113
|
+
* @param {string} email The email to set for the user
|
|
114
|
+
* @returns {Promise<void>} A promise that resolves when the email is set
|
|
115
|
+
* @throws {NotAuthenticatedError} If the user is not authenticated
|
|
116
|
+
*/
|
|
117
|
+
setEmail: (email: string) => Promise<void>;
|
|
118
|
+
/**
|
|
119
|
+
* Removes the email for the authenticated user, disallowing them from login with that email.
|
|
120
|
+
*
|
|
121
|
+
* @returns {Promise<void>} A promise that resolves when the email is removed
|
|
122
|
+
* @throws {NotAuthenticatedError} If the user is not authenticated
|
|
123
|
+
*/
|
|
124
|
+
removeEmail: () => Promise<void>;
|
|
125
|
+
private updateEmail;
|
|
105
126
|
/**
|
|
106
127
|
* Handles the creation of authenticators using WebAuthn attestation and the provided options. Requires the user to be authenticated.
|
|
107
128
|
*
|
|
@@ -110,6 +131,14 @@ export declare abstract class BaseSignerClient<TExportWalletParams = unknown> {
|
|
|
110
131
|
* @throws {NotAuthenticatedError} If the user is not authenticated
|
|
111
132
|
*/
|
|
112
133
|
addPasskey: (options: CredentialCreationOptions) => Promise<string[]>;
|
|
134
|
+
/**
|
|
135
|
+
* Removes a passkey authenticator from the user's account.
|
|
136
|
+
*
|
|
137
|
+
* @param {string} authenticatorId The ID of the authenticator to remove.
|
|
138
|
+
* @returns {Promise<void>} A promise that resolves when the authenticator is removed.
|
|
139
|
+
* @throws {NotAuthenticatedError} If the user is not authenticated.
|
|
140
|
+
*/
|
|
141
|
+
removePasskey: (authenticatorId: string) => Promise<void>;
|
|
113
142
|
/**
|
|
114
143
|
* 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.
|
|
115
144
|
*
|
|
@@ -133,7 +162,21 @@ export declare abstract class BaseSignerClient<TExportWalletParams = unknown> {
|
|
|
133
162
|
* @throws {NotAuthenticatedError} Throws if the user is not authenticated.
|
|
134
163
|
* @returns {Promise<void>} A Promise that resolves when the OAuth provider is added.
|
|
135
164
|
*/
|
|
136
|
-
addOauthProvider: (params: AddOauthProviderParams) => Promise<
|
|
165
|
+
addOauthProvider: (params: AddOauthProviderParams) => Promise<OauthProviderInfo>;
|
|
166
|
+
/**
|
|
167
|
+
* Deletes a specified OAuth provider for the authenticated user.
|
|
168
|
+
*
|
|
169
|
+
* @param {string} providerId The ID of the provider to be deleted
|
|
170
|
+
* @throws {NotAuthenticatedError} If the user is not authenticated
|
|
171
|
+
*/
|
|
172
|
+
removeOauthProvider: (providerId: string) => Promise<void>;
|
|
173
|
+
/**
|
|
174
|
+
* Retrieves the list of authentication methods for the current user.
|
|
175
|
+
*
|
|
176
|
+
* @returns {Promise<AuthMethods>} A promise that resolves to the list of authentication methods
|
|
177
|
+
* @throws {NotAuthenticatedError} If the user is not authenticated
|
|
178
|
+
*/
|
|
179
|
+
listAuthMethods: () => Promise<AuthMethods>;
|
|
137
180
|
/**
|
|
138
181
|
* Retrieves the current user or fetches the user information if not already available.
|
|
139
182
|
*
|
package/dist/esm/client/base.js
CHANGED
|
@@ -94,6 +94,69 @@ export class BaseSignerClient {
|
|
|
94
94
|
return () => this.eventEmitter.removeListener(event, listener);
|
|
95
95
|
}
|
|
96
96
|
});
|
|
97
|
+
/**
|
|
98
|
+
* Sets the email for the authenticated user, allowing them to login with that
|
|
99
|
+
* email.
|
|
100
|
+
*
|
|
101
|
+
* You must contact Alchemy to enable this feature for your team, as there are
|
|
102
|
+
* important security considerations. In particular, you must not call this
|
|
103
|
+
* without first validating that the user owns this email account.
|
|
104
|
+
*
|
|
105
|
+
* @param {string} email The email to set for the user
|
|
106
|
+
* @returns {Promise<void>} A promise that resolves when the email is set
|
|
107
|
+
* @throws {NotAuthenticatedError} If the user is not authenticated
|
|
108
|
+
*/
|
|
109
|
+
Object.defineProperty(this, "setEmail", {
|
|
110
|
+
enumerable: true,
|
|
111
|
+
configurable: true,
|
|
112
|
+
writable: true,
|
|
113
|
+
value: async (email) => {
|
|
114
|
+
if (!email) {
|
|
115
|
+
throw new Error("Email must not be empty. Use removeEmail() to remove email auth.");
|
|
116
|
+
}
|
|
117
|
+
await this.updateEmail(email);
|
|
118
|
+
}
|
|
119
|
+
});
|
|
120
|
+
/**
|
|
121
|
+
* Removes the email for the authenticated user, disallowing them from login with that email.
|
|
122
|
+
*
|
|
123
|
+
* @returns {Promise<void>} A promise that resolves when the email is removed
|
|
124
|
+
* @throws {NotAuthenticatedError} If the user is not authenticated
|
|
125
|
+
*/
|
|
126
|
+
Object.defineProperty(this, "removeEmail", {
|
|
127
|
+
enumerable: true,
|
|
128
|
+
configurable: true,
|
|
129
|
+
writable: true,
|
|
130
|
+
value: async () => {
|
|
131
|
+
// This is a hack to remove the email for the user. Turnkey does not
|
|
132
|
+
// support clearing the email once set, so we set it to a known
|
|
133
|
+
// inaccessible address instead.
|
|
134
|
+
await this.updateEmail("not.enabled@example.invalid");
|
|
135
|
+
}
|
|
136
|
+
});
|
|
137
|
+
Object.defineProperty(this, "updateEmail", {
|
|
138
|
+
enumerable: true,
|
|
139
|
+
configurable: true,
|
|
140
|
+
writable: true,
|
|
141
|
+
value: async (email) => {
|
|
142
|
+
if (!this.user) {
|
|
143
|
+
throw new NotAuthenticatedError();
|
|
144
|
+
}
|
|
145
|
+
const stampedRequest = await this.turnkeyClient.stampUpdateUser({
|
|
146
|
+
type: "ACTIVITY_TYPE_UPDATE_USER",
|
|
147
|
+
timestampMs: Date.now().toString(),
|
|
148
|
+
organizationId: this.user.orgId,
|
|
149
|
+
parameters: {
|
|
150
|
+
userId: this.user.userId,
|
|
151
|
+
userEmail: email,
|
|
152
|
+
userTagIds: [],
|
|
153
|
+
},
|
|
154
|
+
});
|
|
155
|
+
await this.request("/v1/update-email-auth", {
|
|
156
|
+
stampedRequest,
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
});
|
|
97
160
|
/**
|
|
98
161
|
* Handles the creation of authenticators using WebAuthn attestation and the provided options. Requires the user to be authenticated.
|
|
99
162
|
*
|
|
@@ -131,6 +194,32 @@ export class BaseSignerClient {
|
|
|
131
194
|
return authenticatorIds;
|
|
132
195
|
}
|
|
133
196
|
});
|
|
197
|
+
/**
|
|
198
|
+
* Removes a passkey authenticator from the user's account.
|
|
199
|
+
*
|
|
200
|
+
* @param {string} authenticatorId The ID of the authenticator to remove.
|
|
201
|
+
* @returns {Promise<void>} A promise that resolves when the authenticator is removed.
|
|
202
|
+
* @throws {NotAuthenticatedError} If the user is not authenticated.
|
|
203
|
+
*/
|
|
204
|
+
Object.defineProperty(this, "removePasskey", {
|
|
205
|
+
enumerable: true,
|
|
206
|
+
configurable: true,
|
|
207
|
+
writable: true,
|
|
208
|
+
value: async (authenticatorId) => {
|
|
209
|
+
if (!this.user) {
|
|
210
|
+
throw new NotAuthenticatedError();
|
|
211
|
+
}
|
|
212
|
+
await this.turnkeyClient.deleteAuthenticators({
|
|
213
|
+
type: "ACTIVITY_TYPE_DELETE_AUTHENTICATORS",
|
|
214
|
+
timestampMs: Date.now().toString(),
|
|
215
|
+
organizationId: this.user.orgId,
|
|
216
|
+
parameters: {
|
|
217
|
+
userId: this.user.userId,
|
|
218
|
+
authenticatorIds: [authenticatorId],
|
|
219
|
+
},
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
});
|
|
134
223
|
/**
|
|
135
224
|
* 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.
|
|
136
225
|
*
|
|
@@ -203,7 +292,55 @@ export class BaseSignerClient {
|
|
|
203
292
|
oauthProviders: [{ providerName, oidcToken }],
|
|
204
293
|
},
|
|
205
294
|
});
|
|
206
|
-
await this.request("/v1/add-oauth-provider", {
|
|
295
|
+
const response = await this.request("/v1/add-oauth-provider", {
|
|
296
|
+
stampedRequest,
|
|
297
|
+
});
|
|
298
|
+
return response.oauthProviders[0];
|
|
299
|
+
}
|
|
300
|
+
});
|
|
301
|
+
/**
|
|
302
|
+
* Deletes a specified OAuth provider for the authenticated user.
|
|
303
|
+
*
|
|
304
|
+
* @param {string} providerId The ID of the provider to be deleted
|
|
305
|
+
* @throws {NotAuthenticatedError} If the user is not authenticated
|
|
306
|
+
*/
|
|
307
|
+
Object.defineProperty(this, "removeOauthProvider", {
|
|
308
|
+
enumerable: true,
|
|
309
|
+
configurable: true,
|
|
310
|
+
writable: true,
|
|
311
|
+
value: async (providerId) => {
|
|
312
|
+
if (!this.user) {
|
|
313
|
+
throw new NotAuthenticatedError();
|
|
314
|
+
}
|
|
315
|
+
const stampedRequest = await this.turnkeyClient.stampDeleteOauthProviders({
|
|
316
|
+
type: "ACTIVITY_TYPE_DELETE_OAUTH_PROVIDERS",
|
|
317
|
+
timestampMs: Date.now().toString(),
|
|
318
|
+
organizationId: this.user.orgId,
|
|
319
|
+
parameters: {
|
|
320
|
+
userId: this.user.userId,
|
|
321
|
+
providerIds: [providerId],
|
|
322
|
+
},
|
|
323
|
+
});
|
|
324
|
+
await this.request("/v1/remove-oauth-provider", { stampedRequest });
|
|
325
|
+
}
|
|
326
|
+
});
|
|
327
|
+
/**
|
|
328
|
+
* Retrieves the list of authentication methods for the current user.
|
|
329
|
+
*
|
|
330
|
+
* @returns {Promise<AuthMethods>} A promise that resolves to the list of authentication methods
|
|
331
|
+
* @throws {NotAuthenticatedError} If the user is not authenticated
|
|
332
|
+
*/
|
|
333
|
+
Object.defineProperty(this, "listAuthMethods", {
|
|
334
|
+
enumerable: true,
|
|
335
|
+
configurable: true,
|
|
336
|
+
writable: true,
|
|
337
|
+
value: async () => {
|
|
338
|
+
if (!this.user) {
|
|
339
|
+
throw new NotAuthenticatedError();
|
|
340
|
+
}
|
|
341
|
+
return await this.request("/v1/list-auth-methods", {
|
|
342
|
+
suborgId: this.user.orgId,
|
|
343
|
+
});
|
|
207
344
|
}
|
|
208
345
|
});
|
|
209
346
|
/**
|
|
@@ -735,6 +872,7 @@ export class BaseSignerClient {
|
|
|
735
872
|
: redirectUrl
|
|
736
873
|
: undefined,
|
|
737
874
|
openerOrigin: mode === "popup" ? window.location.origin : undefined,
|
|
875
|
+
fetchIdTokenOnly: oauthParams.fetchIdTokenOnly,
|
|
738
876
|
};
|
|
739
877
|
const state = base64UrlEncode(new TextEncoder().encode(JSON.stringify(stateObject)));
|
|
740
878
|
const authUrl = new URL(authEndpoint);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base.js","sourceRoot":"","sources":["../../../src/client/base.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAyB,MAAM,cAAc,CAAC;AAC7E,OAAO,EAAE,aAAa,EAAuB,MAAM,eAAe,CAAC;AACnE,OAAO,YAAY,MAAM,eAAe,CAAC;AACzC,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AACvC,OAAO,EAAE,MAAM,EAAY,MAAM,MAAM,CAAC;AACxC,OAAO,EAAE,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;AA8BzD,OAAO,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AAexC,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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C,YAAY,CAAC,CAAC;QACzD,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,kBAAkB,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC;QAEtD,OAAO,MAAM,CAAC;IAChB,CAAC;CAu2BF","sourcesContent":["import { ConnectionConfigSchema, type ConnectionConfig } from \"@aa-sdk/core\";\nimport { TurnkeyClient, type TSignedRequest } from \"@turnkey/http\";\nimport EventEmitter from \"eventemitter3\";\nimport { jwtDecode } from \"jwt-decode\";\nimport { sha256, type Hex } from \"viem\";\nimport { NotAuthenticatedError, OAuthProvidersError } from \"../errors.js\";\nimport { getDefaultProviderCustomization } from \"../oauth.js\";\nimport type { OauthMode } from \"../signer.js\";\nimport { base64UrlEncode } from \"../utils/base64UrlEncode.js\";\nimport { resolveRelativeUrl } from \"../utils/resolveRelativeUrl.js\";\nimport { assertNever } from \"../utils/typeAssertions.js\";\nimport type {\n AlchemySignerClientEvent,\n AlchemySignerClientEvents,\n AuthenticatingEventMetadata,\n CreateAccountParams,\n RemoveMfaParams,\n EmailAuthParams,\n AddMfaParams,\n AddMfaResult,\n experimental_CreateApiKeyParams,\n GetOauthProviderUrlArgs,\n GetWebAuthnAttestationResult,\n MfaFactor,\n OauthConfig,\n OauthParams,\n OauthState,\n OtpParams,\n SignerBody,\n SignerResponse,\n SignerRoutes,\n SignupResponse,\n User,\n VerifyMfaParams,\n SubmitOtpCodeResponse,\n ValidateMultiFactorsParams,\n AuthLinkingPrompt,\n AddOauthProviderParams,\n CredentialCreationOptionOverrides,\n} from \"./types.js\";\nimport { VERSION } from \"../version.js\";\n\nexport interface BaseSignerClientParams {\n stamper: TurnkeyClient[\"stamper\"];\n connection: ConnectionConfig;\n rootOrgId?: string;\n rpId?: string;\n}\n\nexport type ExportWalletStamper = TurnkeyClient[\"stamper\"] & {\n injectWalletExportBundle(bundle: string): Promise<boolean>;\n injectKeyExportBundle(bundle: string): Promise<boolean>;\n publicKey(): string | null;\n};\n\nconst MFA_PAYLOAD = {\n GET: \"get_mfa\",\n ADD: \"add_mfa\",\n DELETE: \"delete_mfas\",\n VERIFY: \"verify_mfa\",\n LIST: \"list_mfas\",\n} as const;\n\n/**\n * Base class for all Alchemy Signer clients\n */\nexport abstract class BaseSignerClient<TExportWalletParams = unknown> {\n private _user: User | undefined;\n private connectionConfig: ConnectionConfig;\n protected turnkeyClient: TurnkeyClient;\n protected rootOrg: string;\n protected eventEmitter: EventEmitter<AlchemySignerClientEvents>;\n protected oauthConfig: OauthConfig | undefined;\n /**\n * Create a new instance of the Alchemy Signer client\n *\n * @param {BaseSignerClientParams} params the parameters required to create the client\n */\n constructor(params: BaseSignerClientParams) {\n const { stamper, connection, rootOrgId } = params;\n this.rootOrg = rootOrgId ?? \"24c1acf5-810f-41e0-a503-d5d13fa8e830\";\n this.eventEmitter = new EventEmitter<AlchemySignerClientEvents>();\n this.connectionConfig = ConnectionConfigSchema.parse(connection);\n this.turnkeyClient = new TurnkeyClient(\n { baseUrl: \"https://api.turnkey.com\" },\n stamper,\n );\n }\n\n /**\n * Asynchronously fetches and sets the OAuth configuration.\n *\n * @returns {Promise<OauthConfig>} A promise that resolves to the OAuth configuration\n */\n public initOauth = async (): Promise<OauthConfig> => {\n this.oauthConfig = await this.getOauthConfig();\n return this.oauthConfig;\n };\n\n protected get user() {\n return this._user;\n }\n\n protected set user(user: User | undefined) {\n const previousUser = this._user;\n this._user = user;\n if (user && !previousUser) {\n this.eventEmitter.emit(\"connected\", user);\n } else if (!user && previousUser) {\n this.eventEmitter.emit(\"disconnected\");\n }\n }\n\n /**\n * Sets the stamper of the TurnkeyClient.\n *\n * @param {TurnkeyClient[\"stamper\"]} stamper the stamper function to set for the TurnkeyClient\n */\n protected setStamper(stamper: TurnkeyClient[\"stamper\"]) {\n this.turnkeyClient.stamper = stamper;\n }\n\n /**\n * Exports wallet credentials based on the specified type, either as a SEED_PHRASE or PRIVATE_KEY.\n *\n * @param {object} params The parameters for exporting the wallet\n * @param {ExportWalletStamper} params.exportStamper The stamper used for exporting the wallet\n * @param {\"SEED_PHRASE\" | \"PRIVATE_KEY\"} params.exportAs Specifies the format for exporting the wallet, either as a SEED_PHRASE or PRIVATE_KEY\n * @returns {Promise<boolean>} A promise that resolves to true if the export is successful\n */\n protected exportWalletInner(params: {\n exportStamper: ExportWalletStamper;\n exportAs: \"SEED_PHRASE\" | \"PRIVATE_KEY\";\n }): Promise<boolean> {\n const { exportAs } = params;\n switch (exportAs) {\n case \"PRIVATE_KEY\":\n return this.exportAsPrivateKey(params.exportStamper);\n case \"SEED_PHRASE\":\n return this.exportAsSeedPhrase(params.exportStamper);\n default:\n assertNever(exportAs, `Unknown export mode: ${exportAs}`);\n }\n }\n\n /**\n * Authenticates the user by either email or passkey account creation flow. Emits events during the process.\n *\n * @param {CreateAccountParams} params The parameters for creating an account, including the type (email or passkey) and additional details.\n * @returns {Promise<SignupResponse>} A promise that resolves with the response object containing the account creation result.\n */\n public async createAccount(\n params: CreateAccountParams,\n ): Promise<SignupResponse> {\n if (params.type === \"email\") {\n this.eventEmitter.emit(\"authenticating\", { type: \"otp\" });\n const { email, emailMode, expirationSeconds } = params;\n const publicKey = await this.initSessionStamper();\n\n const response = await this.request(\"/v1/signup\", {\n email,\n emailMode,\n targetPublicKey: publicKey,\n expirationSeconds,\n redirectParams: params.redirectParams?.toString(),\n });\n\n return response;\n }\n\n this.eventEmitter.emit(\"authenticating\", { type: \"passkey\" });\n // Passkey account creation flow\n const { attestation, challenge } = await this.getWebAuthnAttestation(\n params.creationOpts,\n { username: \"email\" in params ? params.email : params.username },\n );\n\n const result = await this.request(\"/v1/signup\", {\n passkey: {\n challenge:\n typeof challenge === \"string\"\n ? challenge\n : base64UrlEncode(challenge),\n attestation,\n },\n email: \"email\" in params ? params.email : undefined,\n });\n\n this.user = {\n orgId: result.orgId,\n address: result.address!,\n userId: result.userId!,\n credentialId: attestation.credentialId,\n };\n this.initWebauthnStamper(this.user, params.creationOpts);\n this.eventEmitter.emit(\"connectedPasskey\", this.user);\n\n return result;\n }\n\n // #region ABSTRACT METHODS\n\n public abstract initEmailAuth(\n params: Omit<EmailAuthParams, \"targetPublicKey\">,\n ): Promise<{ orgId: string; otpId?: string; multiFactors?: MfaFactor[] }>;\n\n public abstract completeAuthWithBundle(params: {\n bundle: string;\n orgId: string;\n connectedEventName: keyof AlchemySignerClientEvents;\n authenticatingType: AuthenticatingEventMetadata[\"type\"];\n idToken?: string;\n }): Promise<User>;\n\n public abstract oauthWithRedirect(\n args: Extract<OauthParams, { mode: \"redirect\" }>,\n ): Promise<User>;\n\n public abstract oauthWithPopup(\n args: Extract<OauthParams, { mode: \"popup\" }>,\n ): Promise<User | AuthLinkingPrompt>;\n\n public abstract submitOtpCode(\n args: Omit<OtpParams, \"targetPublicKey\">,\n ): Promise<SubmitOtpCodeResponse>;\n\n public abstract disconnect(): Promise<void>;\n\n public abstract exportWallet(params: TExportWalletParams): Promise<boolean>;\n\n public abstract targetPublicKey(): Promise<string>;\n\n protected abstract getOauthConfig(): Promise<OauthConfig>;\n\n protected abstract getWebAuthnAttestation(\n options?: CredentialCreationOptionOverrides,\n userDetails?: { username: string },\n ): Promise<GetWebAuthnAttestationResult>;\n\n /**\n * Initializes the session stamper and returns its public key.\n */\n protected abstract initSessionStamper(): Promise<string>;\n\n protected abstract initWebauthnStamper(\n user: User | undefined,\n options: CredentialCreationOptionOverrides | undefined,\n ): Promise<void>;\n\n // #endregion\n\n // #region PUBLIC METHODS\n\n /**\n * Listen to events emitted by the client\n *\n * @param {AlchemySignerClientEvent} event the event you want to listen to\n * @param {AlchemySignerClientEvents[AlchemySignerClientEvent]} listener the callback function to execute when an event is fired\n * @returns {() => void} a function that will remove the listener when called\n */\n public on = <E extends AlchemySignerClientEvent>(\n event: E,\n listener: AlchemySignerClientEvents[E],\n ) => {\n this.eventEmitter.on(event, listener as any);\n\n return () => this.eventEmitter.removeListener(event, listener as any);\n };\n\n /**\n * 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 * 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<void> => {\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 await this.request(\"/v1/add-oauth-provider\", { stampedRequest });\n };\n\n /**\n * Retrieves the current user or fetches the user information if not already available.\n *\n * @param {string} [orgId] optional organization ID, defaults to the user's organization ID\n * @param {string} idToken an OIDC ID token containing additional user information\n * @returns {Promise<User>} A promise that resolves to the user object\n * @throws {Error} if no organization ID is provided when there is no current user\n */\n public whoami = async (\n orgId = this.user?.orgId,\n idToken?: string,\n ): Promise<User> => {\n if (this.user) {\n return this.user;\n }\n\n if (!orgId) {\n throw new Error(\"No orgId provided\");\n }\n\n const stampedRequest = await this.turnkeyClient.stampGetWhoami({\n organizationId: orgId,\n });\n\n const user = await this.request(\"/v1/whoami\", {\n stampedRequest,\n });\n\n if (idToken) {\n const claims: Record<string, unknown> = jwtDecode(idToken);\n user.idToken = idToken;\n user.claims = claims;\n if (typeof claims.email === \"string\") {\n user.email = claims.email;\n }\n }\n\n const credentialId = (() => {\n try {\n return JSON.parse(stampedRequest?.stamp.stampHeaderValue)\n .credentialId as string;\n } catch (e) {\n return undefined;\n }\n })();\n\n this.user = {\n ...user,\n credentialId,\n };\n\n return this.user;\n };\n\n /**\n * Generates a stamped whoami request for the current user. This request can then be used to call /signer/v1/whoami to get the user information.\n * This is useful if you want to get the user information in a different context like a server. You can pass the stamped request to the server\n * and then call our API to get the user information. Using this stamp is the most trusted way to get the user information since a stamp can only\n * belong to the user who created it.\n *\n * @returns {Promise<TSignedRequest>} a promise that resolves to the \"whoami\" information for the logged in user\n * @throws {Error} if no organization ID is provided\n */\n public stampWhoami = async (): Promise<TSignedRequest> => {\n if (!this.user) {\n throw new Error(\"User must be authenticated to stamp a whoami request\");\n }\n\n return await this.turnkeyClient.stampGetWhoami({\n organizationId: this.user.orgId,\n });\n };\n\n /**\n * Generates a stamped getOrganization request for the current user.\n *\n * @returns {Promise<TSignedRequest>} a promise that resolves to the \"getOrganization\" information for the logged in user\n * @throws {Error} if no user is authenticated\n */\n public stampGetOrganization = async (): Promise<TSignedRequest> => {\n if (!this.user) {\n throw new Error(\n \"User must be authenticated to stamp a get organization request\",\n );\n }\n\n return await this.turnkeyClient.stampGetOrganization({\n organizationId: this.user.orgId,\n });\n };\n\n /**\n * Creates an API key that can take any action on behalf of the current user.\n * (Note that this method is currently experimental and is subject to change.)\n *\n * @param {CreateApiKeyParams} params Parameters for creating the API key.\n * @param {string} params.name Name of the API key.\n * @param {string} params.publicKey Public key to be used for the API key.\n * @param {number} params.expirationSec Number of seconds until the API key expires.\n * @throws {Error} If there is no authenticated user or the API key creation fails.\n */\n public experimental_createApiKey = async (\n params: experimental_CreateApiKeyParams,\n ): Promise<void> => {\n if (!this.user) {\n throw new Error(\"User must be authenticated to create api key\");\n }\n const resp = await this.turnkeyClient.createApiKeys({\n type: \"ACTIVITY_TYPE_CREATE_API_KEYS_V2\",\n timestampMs: new Date().getTime().toString(),\n organizationId: this.user.orgId,\n parameters: {\n apiKeys: [\n {\n apiKeyName: params.name,\n publicKey: params.publicKey,\n curveType: \"API_KEY_CURVE_P256\",\n expirationSeconds: params.expirationSec.toString(),\n },\n ],\n userId: this.user.userId,\n },\n });\n if (resp.activity.status !== \"ACTIVITY_STATUS_COMPLETED\") {\n throw new Error(\"Failed to create api key\");\n }\n };\n\n /**\n * Looks up information based on an email address.\n *\n * @param {string} email the email address to look up\n * @returns {Promise<any>} the result of the lookup request\n */\n public lookupUserByEmail = async (email: string) => {\n return this.request(\"/v1/lookup\", { email });\n };\n\n /**\n * This will sign a message with the user's private key, without doing any transformations on the message.\n * For SignMessage or SignTypedData, the caller should hash the message before calling this method and pass\n * that result here.\n *\n * @param {Hex} msg the hex representation of the bytes to sign\n * @param {string} mode specify if signing should happen for solana or ethereum\n * @returns {Promise<Hex>} the signature over the raw hex\n */\n public signRawMessage = async (\n msg: Hex,\n mode: \"SOLANA\" | \"ETHEREUM\" = \"ETHEREUM\",\n ): Promise<Hex> => {\n if (!this.user) {\n throw new NotAuthenticatedError();\n }\n\n if (!this.user.solanaAddress && mode === \"SOLANA\") {\n // TODO: we need to add backwards compatibility for users who signed up before we added Solana support\n throw new Error(\"No Solana address available for the user\");\n }\n\n const stampedRequest = await this.turnkeyClient.stampSignRawPayload({\n organizationId: this.user.orgId,\n type: \"ACTIVITY_TYPE_SIGN_RAW_PAYLOAD_V2\",\n timestampMs: Date.now().toString(),\n parameters: {\n encoding: \"PAYLOAD_ENCODING_HEXADECIMAL\",\n hashFunction:\n mode === \"ETHEREUM\"\n ? \"HASH_FUNCTION_NO_OP\"\n : \"HASH_FUNCTION_NOT_APPLICABLE\",\n payload: msg,\n signWith:\n mode === \"ETHEREUM\" ? this.user.address : this.user.solanaAddress!,\n },\n });\n\n const { signature } = await this.request(\"/v1/sign-payload\", {\n stampedRequest,\n });\n\n return signature;\n };\n\n /**\n * Returns the current user or null if no user is set.\n *\n * @returns {User | null} the current user object or null if no user is available\n */\n public getUser = (): User | null => {\n return this.user ?? null;\n };\n\n /**\n * Sends a POST request to the given signer route with the specified body and returns the response.\n * Not intended to be used directly, use the specific methods instead on the client instead.\n *\n * @param {SignerRoutes} route The route to which the request should be sent\n * @param {SignerBody<R>} body The request body containing the data to be sent\n * @returns {Promise<SignerResponse<R>>} A promise that resolves to the response from the signer\n */\n public request = async <R extends SignerRoutes>(\n route: R,\n body: SignerBody<R>,\n ): Promise<SignerResponse<R>> => {\n const url = this.connectionConfig.rpcUrl ?? \"https://api.g.alchemy.com\";\n\n const basePath = \"/signer\";\n\n const headers = new Headers();\n headers.append(\"Alchemy-AA-Sdk-Version\", VERSION);\n headers.append(\"Content-Type\", \"application/json\");\n if (this.connectionConfig.apiKey) {\n headers.append(\"Authorization\", `Bearer ${this.connectionConfig.apiKey}`);\n } else if (this.connectionConfig.jwt) {\n headers.append(\"Authorization\", `Bearer ${this.connectionConfig.jwt}`);\n }\n\n const response = await fetch(`${url}${basePath}${route}`, {\n method: \"POST\",\n body: JSON.stringify(body),\n headers,\n });\n\n if (!response.ok) {\n throw new Error(await response.text());\n }\n\n const json = await response.json();\n\n return json as SignerResponse<R>;\n };\n\n /**\n * Retrieves the list of MFA factors configured for the current user.\n *\n * @returns {Promise<{ multiFactors: MfaFactor[] }>} A promise that resolves to an array of configured MFA factors\n * @throws {NotAuthenticatedError} If no user is authenticated\n */\n public getMfaFactors = async (): Promise<{\n multiFactors: MfaFactor[];\n }> => {\n if (!this.user) {\n throw new NotAuthenticatedError();\n }\n\n const stampedRequest = await this.turnkeyClient.stampSignRawPayload({\n organizationId: this.user.orgId,\n type: \"ACTIVITY_TYPE_SIGN_RAW_PAYLOAD_V2\",\n timestampMs: Date.now().toString(),\n parameters: {\n encoding: \"PAYLOAD_ENCODING_HEXADECIMAL\",\n hashFunction: \"HASH_FUNCTION_NO_OP\",\n payload: MFA_PAYLOAD.LIST,\n signWith: this.user.address,\n },\n });\n\n return this.request(\"/v1/auth-list-multi-factors\", {\n stampedRequest,\n });\n };\n\n /**\n * Initiates the setup of a new MFA factor for the current user. Mfa will need to be verified before it is active.\n *\n * @param {AddMfaParams} params The parameters required to enable a new MFA factor\n * @returns {Promise<AddMfaResult>} A promise that resolves to the factor setup information\n * @throws {NotAuthenticatedError} If no user is authenticated\n * @throws {Error} If an unsupported factor type is provided\n */\n public addMfa = async (params: AddMfaParams): Promise<AddMfaResult> => {\n if (!this.user) {\n throw new NotAuthenticatedError();\n }\n\n const stampedRequest = await this.turnkeyClient.stampSignRawPayload({\n organizationId: this.user.orgId,\n type: \"ACTIVITY_TYPE_SIGN_RAW_PAYLOAD_V2\",\n timestampMs: Date.now().toString(),\n parameters: {\n encoding: \"PAYLOAD_ENCODING_HEXADECIMAL\",\n hashFunction: \"HASH_FUNCTION_NO_OP\",\n payload: MFA_PAYLOAD.ADD,\n signWith: this.user.address,\n },\n });\n\n switch (params.multiFactorType) {\n case \"totp\":\n return this.request(\"/v1/auth-request-multi-factor\", {\n stampedRequest,\n multiFactorType: params.multiFactorType,\n });\n default:\n throw new Error(\n `Unsupported MFA factor type: ${params.multiFactorType}`,\n );\n }\n };\n\n /**\n * Verifies a newly created MFA factor to complete the setup process.\n *\n * @param {VerifyMfaParams} params The parameters required to verify the MFA factor\n * @returns {Promise<{ multiFactors: MfaFactor[] }>} A promise that resolves to the updated list of MFA factors\n * @throws {NotAuthenticatedError} If no user is authenticated\n */\n public verifyMfa = async (\n params: VerifyMfaParams,\n ): Promise<{ multiFactors: MfaFactor[] }> => {\n if (!this.user) {\n throw new NotAuthenticatedError();\n }\n\n const stampedRequest = await this.turnkeyClient.stampSignRawPayload({\n organizationId: this.user.orgId,\n type: \"ACTIVITY_TYPE_SIGN_RAW_PAYLOAD_V2\",\n timestampMs: Date.now().toString(),\n parameters: {\n encoding: \"PAYLOAD_ENCODING_HEXADECIMAL\",\n hashFunction: \"HASH_FUNCTION_NO_OP\",\n payload: MFA_PAYLOAD.VERIFY,\n signWith: this.user.address,\n },\n });\n\n return this.request(\"/v1/auth-verify-multi-factor\", {\n stampedRequest,\n multiFactorId: params.multiFactorId,\n multiFactorCode: params.multiFactorCode,\n });\n };\n\n /**\n * Removes existing MFA factors by ID.\n *\n * @param {RemoveMfaParams} params The parameters specifying which factors to disable\n * @returns {Promise<{ multiFactors: MfaFactor[] }>} A promise that resolves to the updated list of MFA factors\n * @throws {NotAuthenticatedError} If no user is authenticated\n */\n public removeMfa = async (\n params: RemoveMfaParams,\n ): Promise<{ multiFactors: MfaFactor[] }> => {\n if (!this.user) {\n throw new NotAuthenticatedError();\n }\n\n const stampedRequest = await this.turnkeyClient.stampSignRawPayload({\n organizationId: this.user.orgId,\n type: \"ACTIVITY_TYPE_SIGN_RAW_PAYLOAD_V2\",\n timestampMs: Date.now().toString(),\n parameters: {\n encoding: \"PAYLOAD_ENCODING_HEXADECIMAL\",\n hashFunction: \"HASH_FUNCTION_NO_OP\",\n payload: MFA_PAYLOAD.DELETE,\n signWith: this.user.address,\n },\n });\n\n return this.request(\"/v1/auth-delete-multi-factors\", {\n stampedRequest,\n multiFactorIds: params.multiFactorIds,\n });\n };\n\n /**\n * Validates multiple MFA factors using the provided encrypted payload and MFA codes.\n *\n * @param {ValidateMultiFactorsParams} params The validation parameters\n * @returns {Promise<{ bundle: string }>} A promise that resolves to an object containing the credential bundle\n * @throws {Error} If no credential bundle is returned from the server\n */\n public validateMultiFactors = async (\n params: ValidateMultiFactorsParams,\n ): Promise<{ bundle: string }> => {\n // Send the encryptedPayload plus TOTP codes, etc:\n const response = await this.request(\"/v1/auth-validate-multi-factors\", {\n encryptedPayload: params.encryptedPayload,\n multiFactors: params.multiFactors,\n });\n\n // The server is expected to return the *decrypted* payload in `response.payload.credentialBundle`\n if (!response.payload || !response.payload.credentialBundle) {\n throw new Error(\n \"Request to validateMultiFactors did not return a credential bundle\",\n );\n }\n\n return {\n bundle: response.payload.credentialBundle,\n };\n };\n\n // #endregion\n\n // #region PRIVATE METHODS\n private exportAsSeedPhrase = async (stamper: ExportWalletStamper) => {\n if (!this.user) {\n throw new NotAuthenticatedError();\n }\n\n const { wallets } = await this.turnkeyClient.getWallets({\n organizationId: this.user.orgId,\n });\n\n const walletAccounts = await Promise.all(\n wallets.map(({ walletId }) =>\n this.turnkeyClient.getWalletAccounts({\n organizationId: this.user!.orgId,\n walletId,\n }),\n ),\n ).then((x) => x.flatMap((x) => x.accounts));\n\n const walletAccount = walletAccounts.find(\n (x) => x.address === this.user!.address,\n );\n\n if (!walletAccount) {\n throw new Error(\n `Could not find wallet associated with ${this.user.address}`,\n );\n }\n\n const { activity } = await this.turnkeyClient.exportWallet({\n organizationId: this.user.orgId,\n type: \"ACTIVITY_TYPE_EXPORT_WALLET\",\n timestampMs: Date.now().toString(),\n parameters: {\n walletId: walletAccount!.walletId,\n targetPublicKey: stamper.publicKey()!,\n },\n });\n\n const { exportBundle } = await this.pollActivityCompletion(\n activity,\n this.user.orgId,\n \"exportWalletResult\",\n );\n\n const result = await stamper.injectWalletExportBundle(exportBundle);\n\n if (!result) {\n throw new Error(\"Failed to inject wallet export bundle\");\n }\n\n return result;\n };\n\n private exportAsPrivateKey = async (stamper: ExportWalletStamper) => {\n if (!this.user) {\n throw new NotAuthenticatedError();\n }\n\n const { activity } = await this.turnkeyClient.exportWalletAccount({\n organizationId: this.user.orgId,\n type: \"ACTIVITY_TYPE_EXPORT_WALLET_ACCOUNT\",\n timestampMs: Date.now().toString(),\n parameters: {\n address: this.user.address,\n targetPublicKey: stamper.publicKey()!,\n },\n });\n\n const { exportBundle } = await this.pollActivityCompletion(\n activity,\n this.user.orgId,\n \"exportWalletAccountResult\",\n );\n\n const result = await stamper.injectKeyExportBundle(exportBundle);\n\n if (!result) {\n throw new Error(\"Failed to inject wallet export bundle\");\n }\n\n return result;\n };\n\n /**\n * Returns the authentication url for the selected OAuth Proivder\n *\n * @example\n * ```ts\n *\n * cosnt oauthParams = {\n * authProviderId: \"google\",\n * isCustomProvider: false,\n * auth0Connection: undefined,\n * scope: undefined,\n * claims: undefined,\n * mode: \"redirect\",\n * redirectUrl: \"https://your-url-path/oauth-return\",\n * expirationSeconds: 3000\n * };\n *\n * const turnkeyPublicKey = await this.initIframeStamper();\n * const oauthCallbackUrl = this.oauthCallbackUrl;\n * const oauthConfig = this.getOauthConfig() // Optional value for OauthConfig()\n * const usesRelativeUrl = true // Optional value to determine if we use a relative (or absolute) url for the `redirect_url`\n *\n * const oauthProviderUrl = getOauthProviderUrl({\n * oauthParams,\n * turnkeyPublicKey,\n * oauthCallbackUrl\n * })\n *\n * ```\n * @param {GetOauthProviderUrlArgs} args Required. The Oauth provider's auth parameters\n *\n * @returns {Promise<string>} returns the Oauth provider's url\n */\n protected getOauthProviderUrl = async (\n args: GetOauthProviderUrlArgs,\n ): Promise<string> => {\n const {\n oauthParams,\n turnkeyPublicKey,\n oauthCallbackUrl,\n oauthConfig,\n usesRelativeUrl = true,\n } = args;\n\n const {\n authProviderId,\n isCustomProvider,\n auth0Connection,\n scope: providedScope,\n claims: providedClaims,\n otherParameters: providedOtherParameters,\n mode,\n redirectUrl,\n expirationSeconds,\n } = oauthParams;\n\n const { codeChallenge, requestKey, authProviders } =\n oauthConfig ?? (await this.getOauthConfigForMode(mode));\n\n if (!authProviders) {\n throw new OAuthProvidersError();\n }\n\n const authProvider = authProviders.find(\n (provider) =>\n provider.id === authProviderId &&\n !!provider.isCustomProvider === !!isCustomProvider,\n );\n\n if (!authProvider) {\n throw new Error(`No auth provider found with id ${authProviderId}`);\n }\n\n let scope: string | undefined = providedScope;\n let claims: string | undefined = providedClaims;\n let otherParameters: Record<string, string> | undefined =\n providedOtherParameters;\n\n if (!isCustomProvider) {\n const defaultCustomization =\n getDefaultProviderCustomization(authProviderId);\n scope ??= defaultCustomization?.scope;\n claims ??= defaultCustomization?.claims;\n otherParameters ??= defaultCustomization?.otherParameters;\n }\n if (!scope) {\n throw new Error(`Default scope not known for provider ${authProviderId}`);\n }\n const { authEndpoint, clientId } = authProvider;\n\n const nonce = this.getOauthNonce(turnkeyPublicKey);\n const stateObject: OauthState = {\n authProviderId,\n isCustomProvider,\n requestKey,\n turnkeyPublicKey,\n expirationSeconds,\n redirectUrl:\n mode === \"redirect\"\n ? usesRelativeUrl\n ? resolveRelativeUrl(redirectUrl)\n : redirectUrl\n : undefined,\n openerOrigin: mode === \"popup\" ? window.location.origin : undefined,\n };\n const state = base64UrlEncode(\n new TextEncoder().encode(JSON.stringify(stateObject)),\n );\n const authUrl = new URL(authEndpoint);\n const params: Record<string, string> = {\n redirect_uri: oauthCallbackUrl,\n response_type: \"code\",\n scope,\n state,\n code_challenge: codeChallenge,\n code_challenge_method: \"S256\",\n prompt: \"select_account\",\n client_id: clientId,\n nonce,\n ...otherParameters,\n };\n if (claims) {\n params.claims = claims;\n }\n if (auth0Connection) {\n params.connection = auth0Connection;\n }\n\n Object.keys(params).forEach((param) => {\n params[param] && authUrl.searchParams.append(param, params[param]);\n });\n\n const [urlPath, searchParams] = authUrl.href.split(\"?\");\n\n return `${urlPath?.replace(/\\/$/, \"\")}?${searchParams}`;\n };\n\n private getOauthConfigForMode = async (\n mode: OauthMode,\n ): Promise<OauthConfig> => {\n if (this.oauthConfig) {\n return this.oauthConfig;\n } else if (mode === \"redirect\") {\n return this.initOauth();\n } else {\n throw new Error(\n \"enablePopupOauth must be set in configuration or signer.preparePopupOauth must be called before using popup-based OAuth login\",\n );\n }\n };\n\n // eslint-disable-next-line eslint-rules/require-jsdoc-on-reexported-functions\n protected pollActivityCompletion = async <\n T extends keyof Awaited<\n ReturnType<(typeof this.turnkeyClient)[\"getActivity\"]>\n >[\"activity\"][\"result\"],\n >(\n activity: Awaited<\n ReturnType<(typeof this.turnkeyClient)[\"getActivity\"]>\n >[\"activity\"],\n organizationId: string,\n resultKey: T,\n ): Promise<\n NonNullable<\n Awaited<\n ReturnType<(typeof this.turnkeyClient)[\"getActivity\"]>\n >[\"activity\"][\"result\"][T]\n >\n > => {\n if (activity.status === \"ACTIVITY_STATUS_COMPLETED\") {\n return activity.result[resultKey]!;\n }\n\n const {\n activity: { status, id, result },\n } = await this.turnkeyClient.getActivity({\n activityId: activity.id,\n organizationId,\n });\n\n if (status === \"ACTIVITY_STATUS_COMPLETED\") {\n return result[resultKey]!;\n }\n\n if (\n status === \"ACTIVITY_STATUS_FAILED\" ||\n status === \"ACTIVITY_STATUS_REJECTED\" ||\n status === \"ACTIVITY_STATUS_CONSENSUS_NEEDED\"\n ) {\n throw new Error(\n `Failed to get activity with with id ${id} (status: ${status})`,\n );\n }\n\n // TODO: add ability to configure this + add exponential backoff\n await new Promise((resolve) => setTimeout(resolve, 500));\n\n return this.pollActivityCompletion(activity, organizationId, resultKey);\n };\n // #endregion\n\n /**\n * Turnkey requires the nonce in the id token to be in this format.\n *\n * @param {string} turnkeyPublicKey key from a Turnkey iframe\n * @returns {string} nonce to be used in OIDC\n */\n protected getOauthNonce = (turnkeyPublicKey: string): string => {\n return sha256(new TextEncoder().encode(turnkeyPublicKey)).slice(2);\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"base.js","sourceRoot":"","sources":["../../../src/client/base.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAyB,MAAM,cAAc,CAAC;AAC7E,OAAO,EAAE,aAAa,EAAuB,MAAM,eAAe,CAAC;AACnE,OAAO,YAAY,MAAM,eAAe,CAAC;AACzC,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AACvC,OAAO,EAAE,MAAM,EAAY,MAAM,MAAM,CAAC;AACxC,OAAO,EAAE,qBAAqB,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC;AAC1E,OAAO,EAAE,+BAA+B,EAAE,MAAM,aAAa,CAAC;AAE9D,OAAO,EAAE,eAAe,EAAE,MAAM,6BAA6B,CAAC;AAC9D,OAAO,EAAE,kBAAkB,EAAE,MAAM,gCAAgC,CAAC;AACpE,OAAO,EAAE,WAAW,EAAE,MAAM,4BAA4B,CAAC;AAiCzD,OAAO,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AAexC,MAAM,WAAW,GAAG;IAClB,GAAG,EAAE,SAAS;IACd,GAAG,EAAE,SAAS;IACd,MAAM,EAAE,aAAa;IACrB,MAAM,EAAE,YAAY;IACpB,IAAI,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AO;YACtB,YAAY,EAAE,WAAW,CAAC,YAAY;SACvC,CAAC;QACF,IAAI,CAAC,mBAAmB,CAAC,IAAI,CAAC,IAAI,EAAE,MAAM,CAAC,YAAY,CAAC,CAAC;QACzD,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,kBAAkB,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC;QAEtD,OAAO,MAAM,CAAC;IAChB,CAAC;CA29BF","sourcesContent":["import { ConnectionConfigSchema, type ConnectionConfig } from \"@aa-sdk/core\";\nimport { TurnkeyClient, type TSignedRequest } from \"@turnkey/http\";\nimport EventEmitter from \"eventemitter3\";\nimport { jwtDecode } from \"jwt-decode\";\nimport { sha256, type Hex } from \"viem\";\nimport { NotAuthenticatedError, OAuthProvidersError } from \"../errors.js\";\nimport { getDefaultProviderCustomization } from \"../oauth.js\";\nimport type { OauthMode } from \"../signer.js\";\nimport { base64UrlEncode } from \"../utils/base64UrlEncode.js\";\nimport { resolveRelativeUrl } from \"../utils/resolveRelativeUrl.js\";\nimport { assertNever } from \"../utils/typeAssertions.js\";\nimport type {\n AlchemySignerClientEvent,\n AlchemySignerClientEvents,\n AuthenticatingEventMetadata,\n CreateAccountParams,\n RemoveMfaParams,\n EmailAuthParams,\n AddMfaParams,\n AddMfaResult,\n experimental_CreateApiKeyParams,\n GetOauthProviderUrlArgs,\n GetWebAuthnAttestationResult,\n MfaFactor,\n OauthConfig,\n OauthParams,\n OauthState,\n OtpParams,\n SignerBody,\n SignerResponse,\n SignerRoutes,\n SignupResponse,\n User,\n VerifyMfaParams,\n SubmitOtpCodeResponse,\n ValidateMultiFactorsParams,\n AuthLinkingPrompt,\n AddOauthProviderParams,\n CredentialCreationOptionOverrides,\n OauthProviderInfo,\n IdTokenOnly,\n AuthMethods,\n} from \"./types.js\";\nimport { VERSION } from \"../version.js\";\n\nexport interface BaseSignerClientParams {\n stamper: TurnkeyClient[\"stamper\"];\n connection: ConnectionConfig;\n rootOrgId?: string;\n rpId?: string;\n}\n\nexport type ExportWalletStamper = TurnkeyClient[\"stamper\"] & {\n injectWalletExportBundle(bundle: string): Promise<boolean>;\n injectKeyExportBundle(bundle: string): Promise<boolean>;\n publicKey(): string | null;\n};\n\nconst MFA_PAYLOAD = {\n GET: \"get_mfa\",\n ADD: \"add_mfa\",\n DELETE: \"delete_mfas\",\n VERIFY: \"verify_mfa\",\n LIST: \"list_mfas\",\n} as const;\n\n/**\n * Base class for all Alchemy Signer clients\n */\nexport abstract class BaseSignerClient<TExportWalletParams = unknown> {\n private _user: User | undefined;\n private connectionConfig: ConnectionConfig;\n protected turnkeyClient: TurnkeyClient;\n protected rootOrg: string;\n protected eventEmitter: EventEmitter<AlchemySignerClientEvents>;\n protected oauthConfig: OauthConfig | undefined;\n /**\n * Create a new instance of the Alchemy Signer client\n *\n * @param {BaseSignerClientParams} params the parameters required to create the client\n */\n constructor(params: BaseSignerClientParams) {\n const { stamper, connection, rootOrgId } = params;\n this.rootOrg = rootOrgId ?? \"24c1acf5-810f-41e0-a503-d5d13fa8e830\";\n this.eventEmitter = new EventEmitter<AlchemySignerClientEvents>();\n this.connectionConfig = ConnectionConfigSchema.parse(connection);\n this.turnkeyClient = new TurnkeyClient(\n { baseUrl: \"https://api.turnkey.com\" },\n stamper,\n );\n }\n\n /**\n * Asynchronously fetches and sets the OAuth configuration.\n *\n * @returns {Promise<OauthConfig>} A promise that resolves to the OAuth configuration\n */\n public initOauth = async (): Promise<OauthConfig> => {\n this.oauthConfig = await this.getOauthConfig();\n return this.oauthConfig;\n };\n\n protected get user() {\n return this._user;\n }\n\n protected set user(user: User | undefined) {\n const previousUser = this._user;\n this._user = user;\n if (user && !previousUser) {\n this.eventEmitter.emit(\"connected\", user);\n } else if (!user && previousUser) {\n this.eventEmitter.emit(\"disconnected\");\n }\n }\n\n /**\n * Sets the stamper of the TurnkeyClient.\n *\n * @param {TurnkeyClient[\"stamper\"]} stamper the stamper function to set for the TurnkeyClient\n */\n protected setStamper(stamper: TurnkeyClient[\"stamper\"]) {\n this.turnkeyClient.stamper = stamper;\n }\n\n /**\n * Exports wallet credentials based on the specified type, either as a SEED_PHRASE or PRIVATE_KEY.\n *\n * @param {object} params The parameters for exporting the wallet\n * @param {ExportWalletStamper} params.exportStamper The stamper used for exporting the wallet\n * @param {\"SEED_PHRASE\" | \"PRIVATE_KEY\"} params.exportAs Specifies the format for exporting the wallet, either as a SEED_PHRASE or PRIVATE_KEY\n * @returns {Promise<boolean>} A promise that resolves to true if the export is successful\n */\n protected exportWalletInner(params: {\n exportStamper: ExportWalletStamper;\n exportAs: \"SEED_PHRASE\" | \"PRIVATE_KEY\";\n }): Promise<boolean> {\n const { exportAs } = params;\n switch (exportAs) {\n case \"PRIVATE_KEY\":\n return this.exportAsPrivateKey(params.exportStamper);\n case \"SEED_PHRASE\":\n return this.exportAsSeedPhrase(params.exportStamper);\n default:\n assertNever(exportAs, `Unknown export mode: ${exportAs}`);\n }\n }\n\n /**\n * Authenticates the user by either email or passkey account creation flow. Emits events during the process.\n *\n * @param {CreateAccountParams} params The parameters for creating an account, including the type (email or passkey) and additional details.\n * @returns {Promise<SignupResponse>} A promise that resolves with the response object containing the account creation result.\n */\n public async createAccount(\n params: CreateAccountParams,\n ): Promise<SignupResponse> {\n if (params.type === \"email\") {\n this.eventEmitter.emit(\"authenticating\", { type: \"otp\" });\n const { email, emailMode, expirationSeconds } = params;\n const publicKey = await this.initSessionStamper();\n\n const response = await this.request(\"/v1/signup\", {\n email,\n emailMode,\n targetPublicKey: publicKey,\n expirationSeconds,\n redirectParams: params.redirectParams?.toString(),\n });\n\n return response;\n }\n\n this.eventEmitter.emit(\"authenticating\", { type: \"passkey\" });\n // Passkey account creation flow\n const { attestation, challenge } = await this.getWebAuthnAttestation(\n params.creationOpts,\n { username: \"email\" in params ? params.email : params.username },\n );\n\n const result = await this.request(\"/v1/signup\", {\n passkey: {\n challenge:\n typeof challenge === \"string\"\n ? challenge\n : base64UrlEncode(challenge),\n attestation,\n },\n email: \"email\" in params ? params.email : undefined,\n });\n\n this.user = {\n orgId: result.orgId,\n address: result.address!,\n userId: result.userId!,\n credentialId: attestation.credentialId,\n };\n this.initWebauthnStamper(this.user, params.creationOpts);\n this.eventEmitter.emit(\"connectedPasskey\", this.user);\n\n return result;\n }\n\n // #region ABSTRACT METHODS\n\n public abstract initEmailAuth(\n params: Omit<EmailAuthParams, \"targetPublicKey\">,\n ): Promise<{ orgId: string; otpId?: string; multiFactors?: MfaFactor[] }>;\n\n public abstract completeAuthWithBundle(params: {\n bundle: string;\n orgId: string;\n connectedEventName: keyof AlchemySignerClientEvents;\n authenticatingType: AuthenticatingEventMetadata[\"type\"];\n idToken?: string;\n }): Promise<User>;\n\n public abstract oauthWithRedirect(\n args: Extract<OauthParams, { mode: \"redirect\" }>,\n ): Promise<User | IdTokenOnly>;\n\n public abstract oauthWithPopup(\n args: Extract<OauthParams, { mode: \"popup\" }>,\n ): Promise<User | AuthLinkingPrompt | IdTokenOnly>;\n\n public abstract submitOtpCode(\n args: Omit<OtpParams, \"targetPublicKey\">,\n ): Promise<SubmitOtpCodeResponse>;\n\n public abstract disconnect(): Promise<void>;\n\n public abstract exportWallet(params: TExportWalletParams): Promise<boolean>;\n\n public abstract targetPublicKey(): Promise<string>;\n\n protected abstract getOauthConfig(): Promise<OauthConfig>;\n\n protected abstract getWebAuthnAttestation(\n options?: CredentialCreationOptionOverrides,\n userDetails?: { username: string },\n ): Promise<GetWebAuthnAttestationResult>;\n\n /**\n * Initializes the session stamper and returns its public key.\n */\n protected abstract initSessionStamper(): Promise<string>;\n\n protected abstract initWebauthnStamper(\n user: User | undefined,\n options: CredentialCreationOptionOverrides | undefined,\n ): Promise<void>;\n\n // #endregion\n\n // #region PUBLIC METHODS\n\n /**\n * Listen to events emitted by the client\n *\n * @param {AlchemySignerClientEvent} event the event you want to listen to\n * @param {AlchemySignerClientEvents[AlchemySignerClientEvent]} listener the callback function to execute when an event is fired\n * @returns {() => void} a function that will remove the listener when called\n */\n public on = <E extends AlchemySignerClientEvent>(\n event: E,\n listener: AlchemySignerClientEvents[E],\n ) => {\n this.eventEmitter.on(event, listener as any);\n\n return () => this.eventEmitter.removeListener(event, listener as any);\n };\n\n /**\n * Sets the email for the authenticated user, allowing them to login with that\n * email.\n *\n * You must contact Alchemy to enable this feature for your team, as there are\n * important security considerations. In particular, you must not call this\n * without first validating that the user owns this email account.\n *\n * @param {string} email The email to set for the user\n * @returns {Promise<void>} A promise that resolves when the email is set\n * @throws {NotAuthenticatedError} If the user is not authenticated\n */\n public setEmail = async (email: string): Promise<void> => {\n if (!email) {\n throw new Error(\n \"Email must not be empty. Use removeEmail() to remove email auth.\",\n );\n }\n await this.updateEmail(email);\n };\n\n /**\n * Removes the email for the authenticated user, disallowing them from login with that email.\n *\n * @returns {Promise<void>} A promise that resolves when the email is removed\n * @throws {NotAuthenticatedError} If the user is not authenticated\n */\n public removeEmail = async (): Promise<void> => {\n // This is a hack to remove the email for the user. Turnkey does not\n // support clearing the email once set, so we set it to a known\n // inaccessible address instead.\n await this.updateEmail(\"not.enabled@example.invalid\");\n };\n\n private updateEmail = async (email: string): Promise<void> => {\n if (!this.user) {\n throw new NotAuthenticatedError();\n }\n const stampedRequest = await this.turnkeyClient.stampUpdateUser({\n type: \"ACTIVITY_TYPE_UPDATE_USER\",\n timestampMs: Date.now().toString(),\n organizationId: this.user.orgId,\n parameters: {\n userId: this.user.userId,\n userEmail: email,\n userTagIds: [],\n },\n });\n await this.request(\"/v1/update-email-auth\", {\n stampedRequest,\n });\n };\n\n /**\n * Handles the creation of authenticators using WebAuthn attestation and the provided options. Requires the user to be authenticated.\n *\n * @param {CredentialCreationOptions} options The options used to create the WebAuthn attestation\n * @returns {Promise<string[]>} A promise that resolves to an array of authenticator IDs\n * @throws {NotAuthenticatedError} If the user is not authenticated\n */\n public addPasskey = async (options: CredentialCreationOptions) => {\n if (!this.user) {\n throw new NotAuthenticatedError();\n }\n const { attestation, challenge } =\n await this.getWebAuthnAttestation(options);\n\n const { activity } = await this.turnkeyClient.createAuthenticators({\n type: \"ACTIVITY_TYPE_CREATE_AUTHENTICATORS_V2\",\n timestampMs: Date.now().toString(),\n organizationId: this.user.orgId,\n parameters: {\n userId: this.user.userId,\n authenticators: [\n {\n attestation,\n authenticatorName: `passkey-${Date.now().toString()}`,\n challenge:\n typeof challenge === \"string\"\n ? challenge\n : base64UrlEncode(challenge),\n },\n ],\n },\n });\n\n const { authenticatorIds } = await this.pollActivityCompletion(\n activity,\n this.user.orgId,\n \"createAuthenticatorsResult\",\n );\n\n return authenticatorIds;\n };\n\n /**\n * Removes a passkey authenticator from the user's account.\n *\n * @param {string} authenticatorId The ID of the authenticator to remove.\n * @returns {Promise<void>} A promise that resolves when the authenticator is removed.\n * @throws {NotAuthenticatedError} If the user is not authenticated.\n */\n public removePasskey = async (authenticatorId: string): Promise<void> => {\n if (!this.user) {\n throw new NotAuthenticatedError();\n }\n await this.turnkeyClient.deleteAuthenticators({\n type: \"ACTIVITY_TYPE_DELETE_AUTHENTICATORS\",\n timestampMs: Date.now().toString(),\n organizationId: this.user.orgId,\n parameters: {\n userId: this.user.userId,\n authenticatorIds: [authenticatorId],\n },\n });\n };\n\n /**\n * Asynchronously handles the authentication process using WebAuthn Stamper. If a user is provided, sets the user and returns it. Otherwise, retrieves the current user and initializes the WebAuthn stamper.\n *\n * @param {User} [user] An optional user object to authenticate\n * @returns {Promise<User>} A promise that resolves to the authenticated user object\n */\n public lookupUserWithPasskey = async (user: User | undefined = undefined) => {\n this.eventEmitter.emit(\"authenticating\", { type: \"passkey\" });\n await this.initWebauthnStamper(user, undefined);\n if (user) {\n this.user = user;\n this.eventEmitter.emit(\"connectedPasskey\", user);\n return user;\n }\n\n const result = await this.whoami(this.rootOrg);\n await this.initWebauthnStamper(result, undefined);\n this.eventEmitter.emit(\"connectedPasskey\", result);\n\n return result;\n };\n\n /**\n * Retrieves the status of the passkey for the current user. Requires the user to be authenticated.\n *\n * @returns {Promise<{ isPasskeyAdded: boolean }>} A promise that resolves to an object containing the passkey status\n * @throws {NotAuthenticatedError} If the user is not authenticated\n */\n public getPasskeyStatus = async () => {\n if (!this.user) {\n throw new NotAuthenticatedError();\n }\n const resp = await this.turnkeyClient.getAuthenticators({\n organizationId: this.user.orgId,\n userId: this.user.userId,\n });\n return {\n isPasskeyAdded: resp.authenticators.some((it) =>\n it.authenticatorName.startsWith(\"passkey-\"),\n ),\n };\n };\n\n /**\n * Adds an OAuth provider for the authenticated user using the provided parameters. Throws an error if the user is not authenticated.\n *\n * @param {AddOauthProviderParams} params The parameters for adding an OAuth provider, including `providerName` and `oidcToken`.\n * @throws {NotAuthenticatedError} Throws if the user is not authenticated.\n * @returns {Promise<void>} A Promise that resolves when the OAuth provider is added.\n */\n public addOauthProvider = async (\n params: AddOauthProviderParams,\n ): Promise<OauthProviderInfo> => {\n if (!this.user) {\n throw new NotAuthenticatedError();\n }\n const { providerName, oidcToken } = params;\n const stampedRequest = await this.turnkeyClient.stampCreateOauthProviders({\n type: \"ACTIVITY_TYPE_CREATE_OAUTH_PROVIDERS\",\n timestampMs: Date.now().toString(),\n organizationId: this.user.orgId,\n parameters: {\n userId: this.user.userId,\n oauthProviders: [{ providerName, oidcToken }],\n },\n });\n const response = await this.request(\"/v1/add-oauth-provider\", {\n stampedRequest,\n });\n return response.oauthProviders[0];\n };\n\n /**\n * Deletes a specified OAuth provider for the authenticated user.\n *\n * @param {string} providerId The ID of the provider to be deleted\n * @throws {NotAuthenticatedError} If the user is not authenticated\n */\n public removeOauthProvider = async (providerId: string) => {\n if (!this.user) {\n throw new NotAuthenticatedError();\n }\n const stampedRequest = await this.turnkeyClient.stampDeleteOauthProviders({\n type: \"ACTIVITY_TYPE_DELETE_OAUTH_PROVIDERS\",\n timestampMs: Date.now().toString(),\n organizationId: this.user.orgId,\n parameters: {\n userId: this.user.userId,\n providerIds: [providerId],\n },\n });\n await this.request(\"/v1/remove-oauth-provider\", { stampedRequest });\n };\n\n /**\n * Retrieves the list of authentication methods for the current user.\n *\n * @returns {Promise<AuthMethods>} A promise that resolves to the list of authentication methods\n * @throws {NotAuthenticatedError} If the user is not authenticated\n */\n public listAuthMethods = async (): Promise<AuthMethods> => {\n if (!this.user) {\n throw new NotAuthenticatedError();\n }\n return await this.request(\"/v1/list-auth-methods\", {\n suborgId: this.user.orgId,\n });\n };\n\n /**\n * Retrieves the current user or fetches the user information if not already available.\n *\n * @param {string} [orgId] optional organization ID, defaults to the user's organization ID\n * @param {string} idToken an OIDC ID token containing additional user information\n * @returns {Promise<User>} A promise that resolves to the user object\n * @throws {Error} if no organization ID is provided when there is no current user\n */\n public whoami = async (\n orgId = this.user?.orgId,\n idToken?: string,\n ): Promise<User> => {\n if (this.user) {\n return this.user;\n }\n\n if (!orgId) {\n throw new Error(\"No orgId provided\");\n }\n\n const stampedRequest = await this.turnkeyClient.stampGetWhoami({\n organizationId: orgId,\n });\n\n const user = await this.request(\"/v1/whoami\", {\n stampedRequest,\n });\n\n if (idToken) {\n const claims: Record<string, unknown> = jwtDecode(idToken);\n user.idToken = idToken;\n user.claims = claims;\n if (typeof claims.email === \"string\") {\n user.email = claims.email;\n }\n }\n\n const credentialId = (() => {\n try {\n return JSON.parse(stampedRequest?.stamp.stampHeaderValue)\n .credentialId as string;\n } catch (e) {\n return undefined;\n }\n })();\n\n this.user = {\n ...user,\n credentialId,\n };\n\n return this.user;\n };\n\n /**\n * Generates a stamped whoami request for the current user. This request can then be used to call /signer/v1/whoami to get the user information.\n * This is useful if you want to get the user information in a different context like a server. You can pass the stamped request to the server\n * and then call our API to get the user information. Using this stamp is the most trusted way to get the user information since a stamp can only\n * belong to the user who created it.\n *\n * @returns {Promise<TSignedRequest>} a promise that resolves to the \"whoami\" information for the logged in user\n * @throws {Error} if no organization ID is provided\n */\n public stampWhoami = async (): Promise<TSignedRequest> => {\n if (!this.user) {\n throw new Error(\"User must be authenticated to stamp a whoami request\");\n }\n\n return await this.turnkeyClient.stampGetWhoami({\n organizationId: this.user.orgId,\n });\n };\n\n /**\n * Generates a stamped getOrganization request for the current user.\n *\n * @returns {Promise<TSignedRequest>} a promise that resolves to the \"getOrganization\" information for the logged in user\n * @throws {Error} if no user is authenticated\n */\n public stampGetOrganization = async (): Promise<TSignedRequest> => {\n if (!this.user) {\n throw new Error(\n \"User must be authenticated to stamp a get organization request\",\n );\n }\n\n return await this.turnkeyClient.stampGetOrganization({\n organizationId: this.user.orgId,\n });\n };\n\n /**\n * Creates an API key that can take any action on behalf of the current user.\n * (Note that this method is currently experimental and is subject to change.)\n *\n * @param {CreateApiKeyParams} params Parameters for creating the API key.\n * @param {string} params.name Name of the API key.\n * @param {string} params.publicKey Public key to be used for the API key.\n * @param {number} params.expirationSec Number of seconds until the API key expires.\n * @throws {Error} If there is no authenticated user or the API key creation fails.\n */\n public experimental_createApiKey = async (\n params: experimental_CreateApiKeyParams,\n ): Promise<void> => {\n if (!this.user) {\n throw new Error(\"User must be authenticated to create api key\");\n }\n const resp = await this.turnkeyClient.createApiKeys({\n type: \"ACTIVITY_TYPE_CREATE_API_KEYS_V2\",\n timestampMs: new Date().getTime().toString(),\n organizationId: this.user.orgId,\n parameters: {\n apiKeys: [\n {\n apiKeyName: params.name,\n publicKey: params.publicKey,\n curveType: \"API_KEY_CURVE_P256\",\n expirationSeconds: params.expirationSec.toString(),\n },\n ],\n userId: this.user.userId,\n },\n });\n if (resp.activity.status !== \"ACTIVITY_STATUS_COMPLETED\") {\n throw new Error(\"Failed to create api key\");\n }\n };\n\n /**\n * Looks up information based on an email address.\n *\n * @param {string} email the email address to look up\n * @returns {Promise<any>} the result of the lookup request\n */\n public lookupUserByEmail = async (email: string) => {\n return this.request(\"/v1/lookup\", { email });\n };\n\n /**\n * This will sign a message with the user's private key, without doing any transformations on the message.\n * For SignMessage or SignTypedData, the caller should hash the message before calling this method and pass\n * that result here.\n *\n * @param {Hex} msg the hex representation of the bytes to sign\n * @param {string} mode specify if signing should happen for solana or ethereum\n * @returns {Promise<Hex>} the signature over the raw hex\n */\n public signRawMessage = async (\n msg: Hex,\n mode: \"SOLANA\" | \"ETHEREUM\" = \"ETHEREUM\",\n ): Promise<Hex> => {\n if (!this.user) {\n throw new NotAuthenticatedError();\n }\n\n if (!this.user.solanaAddress && mode === \"SOLANA\") {\n // TODO: we need to add backwards compatibility for users who signed up before we added Solana support\n throw new Error(\"No Solana address available for the user\");\n }\n\n const stampedRequest = await this.turnkeyClient.stampSignRawPayload({\n organizationId: this.user.orgId,\n type: \"ACTIVITY_TYPE_SIGN_RAW_PAYLOAD_V2\",\n timestampMs: Date.now().toString(),\n parameters: {\n encoding: \"PAYLOAD_ENCODING_HEXADECIMAL\",\n hashFunction:\n mode === \"ETHEREUM\"\n ? \"HASH_FUNCTION_NO_OP\"\n : \"HASH_FUNCTION_NOT_APPLICABLE\",\n payload: msg,\n signWith:\n mode === \"ETHEREUM\" ? this.user.address : this.user.solanaAddress!,\n },\n });\n\n const { signature } = await this.request(\"/v1/sign-payload\", {\n stampedRequest,\n });\n\n return signature;\n };\n\n /**\n * Returns the current user or null if no user is set.\n *\n * @returns {User | null} the current user object or null if no user is available\n */\n public getUser = (): User | null => {\n return this.user ?? null;\n };\n\n /**\n * Sends a POST request to the given signer route with the specified body and returns the response.\n * Not intended to be used directly, use the specific methods instead on the client instead.\n *\n * @param {SignerRoutes} route The route to which the request should be sent\n * @param {SignerBody<R>} body The request body containing the data to be sent\n * @returns {Promise<SignerResponse<R>>} A promise that resolves to the response from the signer\n */\n public request = async <R extends SignerRoutes>(\n route: R,\n body: SignerBody<R>,\n ): Promise<SignerResponse<R>> => {\n const url = this.connectionConfig.rpcUrl ?? \"https://api.g.alchemy.com\";\n\n const basePath = \"/signer\";\n\n const headers = new Headers();\n headers.append(\"Alchemy-AA-Sdk-Version\", VERSION);\n headers.append(\"Content-Type\", \"application/json\");\n if (this.connectionConfig.apiKey) {\n headers.append(\"Authorization\", `Bearer ${this.connectionConfig.apiKey}`);\n } else if (this.connectionConfig.jwt) {\n headers.append(\"Authorization\", `Bearer ${this.connectionConfig.jwt}`);\n }\n\n const response = await fetch(`${url}${basePath}${route}`, {\n method: \"POST\",\n body: JSON.stringify(body),\n headers,\n });\n\n if (!response.ok) {\n throw new Error(await response.text());\n }\n\n const json = await response.json();\n\n return json as SignerResponse<R>;\n };\n\n /**\n * Retrieves the list of MFA factors configured for the current user.\n *\n * @returns {Promise<{ multiFactors: MfaFactor[] }>} A promise that resolves to an array of configured MFA factors\n * @throws {NotAuthenticatedError} If no user is authenticated\n */\n public getMfaFactors = async (): Promise<{\n multiFactors: MfaFactor[];\n }> => {\n if (!this.user) {\n throw new NotAuthenticatedError();\n }\n\n const stampedRequest = await this.turnkeyClient.stampSignRawPayload({\n organizationId: this.user.orgId,\n type: \"ACTIVITY_TYPE_SIGN_RAW_PAYLOAD_V2\",\n timestampMs: Date.now().toString(),\n parameters: {\n encoding: \"PAYLOAD_ENCODING_HEXADECIMAL\",\n hashFunction: \"HASH_FUNCTION_NO_OP\",\n payload: MFA_PAYLOAD.LIST,\n signWith: this.user.address,\n },\n });\n\n return this.request(\"/v1/auth-list-multi-factors\", {\n stampedRequest,\n });\n };\n\n /**\n * Initiates the setup of a new MFA factor for the current user. Mfa will need to be verified before it is active.\n *\n * @param {AddMfaParams} params The parameters required to enable a new MFA factor\n * @returns {Promise<AddMfaResult>} A promise that resolves to the factor setup information\n * @throws {NotAuthenticatedError} If no user is authenticated\n * @throws {Error} If an unsupported factor type is provided\n */\n public addMfa = async (params: AddMfaParams): Promise<AddMfaResult> => {\n if (!this.user) {\n throw new NotAuthenticatedError();\n }\n\n const stampedRequest = await this.turnkeyClient.stampSignRawPayload({\n organizationId: this.user.orgId,\n type: \"ACTIVITY_TYPE_SIGN_RAW_PAYLOAD_V2\",\n timestampMs: Date.now().toString(),\n parameters: {\n encoding: \"PAYLOAD_ENCODING_HEXADECIMAL\",\n hashFunction: \"HASH_FUNCTION_NO_OP\",\n payload: MFA_PAYLOAD.ADD,\n signWith: this.user.address,\n },\n });\n\n switch (params.multiFactorType) {\n case \"totp\":\n return this.request(\"/v1/auth-request-multi-factor\", {\n stampedRequest,\n multiFactorType: params.multiFactorType,\n });\n default:\n throw new Error(\n `Unsupported MFA factor type: ${params.multiFactorType}`,\n );\n }\n };\n\n /**\n * Verifies a newly created MFA factor to complete the setup process.\n *\n * @param {VerifyMfaParams} params The parameters required to verify the MFA factor\n * @returns {Promise<{ multiFactors: MfaFactor[] }>} A promise that resolves to the updated list of MFA factors\n * @throws {NotAuthenticatedError} If no user is authenticated\n */\n public verifyMfa = async (\n params: VerifyMfaParams,\n ): Promise<{ multiFactors: MfaFactor[] }> => {\n if (!this.user) {\n throw new NotAuthenticatedError();\n }\n\n const stampedRequest = await this.turnkeyClient.stampSignRawPayload({\n organizationId: this.user.orgId,\n type: \"ACTIVITY_TYPE_SIGN_RAW_PAYLOAD_V2\",\n timestampMs: Date.now().toString(),\n parameters: {\n encoding: \"PAYLOAD_ENCODING_HEXADECIMAL\",\n hashFunction: \"HASH_FUNCTION_NO_OP\",\n payload: MFA_PAYLOAD.VERIFY,\n signWith: this.user.address,\n },\n });\n\n return this.request(\"/v1/auth-verify-multi-factor\", {\n stampedRequest,\n multiFactorId: params.multiFactorId,\n multiFactorCode: params.multiFactorCode,\n });\n };\n\n /**\n * Removes existing MFA factors by ID.\n *\n * @param {RemoveMfaParams} params The parameters specifying which factors to disable\n * @returns {Promise<{ multiFactors: MfaFactor[] }>} A promise that resolves to the updated list of MFA factors\n * @throws {NotAuthenticatedError} If no user is authenticated\n */\n public removeMfa = async (\n params: RemoveMfaParams,\n ): Promise<{ multiFactors: MfaFactor[] }> => {\n if (!this.user) {\n throw new NotAuthenticatedError();\n }\n\n const stampedRequest = await this.turnkeyClient.stampSignRawPayload({\n organizationId: this.user.orgId,\n type: \"ACTIVITY_TYPE_SIGN_RAW_PAYLOAD_V2\",\n timestampMs: Date.now().toString(),\n parameters: {\n encoding: \"PAYLOAD_ENCODING_HEXADECIMAL\",\n hashFunction: \"HASH_FUNCTION_NO_OP\",\n payload: MFA_PAYLOAD.DELETE,\n signWith: this.user.address,\n },\n });\n\n return this.request(\"/v1/auth-delete-multi-factors\", {\n stampedRequest,\n multiFactorIds: params.multiFactorIds,\n });\n };\n\n /**\n * Validates multiple MFA factors using the provided encrypted payload and MFA codes.\n *\n * @param {ValidateMultiFactorsParams} params The validation parameters\n * @returns {Promise<{ bundle: string }>} A promise that resolves to an object containing the credential bundle\n * @throws {Error} If no credential bundle is returned from the server\n */\n public validateMultiFactors = async (\n params: ValidateMultiFactorsParams,\n ): Promise<{ bundle: string }> => {\n // Send the encryptedPayload plus TOTP codes, etc:\n const response = await this.request(\"/v1/auth-validate-multi-factors\", {\n encryptedPayload: params.encryptedPayload,\n multiFactors: params.multiFactors,\n });\n\n // The server is expected to return the *decrypted* payload in `response.payload.credentialBundle`\n if (!response.payload || !response.payload.credentialBundle) {\n throw new Error(\n \"Request to validateMultiFactors did not return a credential bundle\",\n );\n }\n\n return {\n bundle: response.payload.credentialBundle,\n };\n };\n\n // #endregion\n\n // #region PRIVATE METHODS\n private exportAsSeedPhrase = async (stamper: ExportWalletStamper) => {\n if (!this.user) {\n throw new NotAuthenticatedError();\n }\n\n const { wallets } = await this.turnkeyClient.getWallets({\n organizationId: this.user.orgId,\n });\n\n const walletAccounts = await Promise.all(\n wallets.map(({ walletId }) =>\n this.turnkeyClient.getWalletAccounts({\n organizationId: this.user!.orgId,\n walletId,\n }),\n ),\n ).then((x) => x.flatMap((x) => x.accounts));\n\n const walletAccount = walletAccounts.find(\n (x) => x.address === this.user!.address,\n );\n\n if (!walletAccount) {\n throw new Error(\n `Could not find wallet associated with ${this.user.address}`,\n );\n }\n\n const { activity } = await this.turnkeyClient.exportWallet({\n organizationId: this.user.orgId,\n type: \"ACTIVITY_TYPE_EXPORT_WALLET\",\n timestampMs: Date.now().toString(),\n parameters: {\n walletId: walletAccount!.walletId,\n targetPublicKey: stamper.publicKey()!,\n },\n });\n\n const { exportBundle } = await this.pollActivityCompletion(\n activity,\n this.user.orgId,\n \"exportWalletResult\",\n );\n\n const result = await stamper.injectWalletExportBundle(exportBundle);\n\n if (!result) {\n throw new Error(\"Failed to inject wallet export bundle\");\n }\n\n return result;\n };\n\n private exportAsPrivateKey = async (stamper: ExportWalletStamper) => {\n if (!this.user) {\n throw new NotAuthenticatedError();\n }\n\n const { activity } = await this.turnkeyClient.exportWalletAccount({\n organizationId: this.user.orgId,\n type: \"ACTIVITY_TYPE_EXPORT_WALLET_ACCOUNT\",\n timestampMs: Date.now().toString(),\n parameters: {\n address: this.user.address,\n targetPublicKey: stamper.publicKey()!,\n },\n });\n\n const { exportBundle } = await this.pollActivityCompletion(\n activity,\n this.user.orgId,\n \"exportWalletAccountResult\",\n );\n\n const result = await stamper.injectKeyExportBundle(exportBundle);\n\n if (!result) {\n throw new Error(\"Failed to inject wallet export bundle\");\n }\n\n return result;\n };\n\n /**\n * Returns the authentication url for the selected OAuth Proivder\n *\n * @example\n * ```ts\n *\n * cosnt oauthParams = {\n * authProviderId: \"google\",\n * isCustomProvider: false,\n * auth0Connection: undefined,\n * scope: undefined,\n * claims: undefined,\n * mode: \"redirect\",\n * redirectUrl: \"https://your-url-path/oauth-return\",\n * expirationSeconds: 3000\n * };\n *\n * const turnkeyPublicKey = await this.initIframeStamper();\n * const oauthCallbackUrl = this.oauthCallbackUrl;\n * const oauthConfig = this.getOauthConfig() // Optional value for OauthConfig()\n * const usesRelativeUrl = true // Optional value to determine if we use a relative (or absolute) url for the `redirect_url`\n *\n * const oauthProviderUrl = getOauthProviderUrl({\n * oauthParams,\n * turnkeyPublicKey,\n * oauthCallbackUrl\n * })\n *\n * ```\n * @param {GetOauthProviderUrlArgs} args Required. The Oauth provider's auth parameters\n *\n * @returns {Promise<string>} returns the Oauth provider's url\n */\n protected getOauthProviderUrl = async (\n args: GetOauthProviderUrlArgs,\n ): Promise<string> => {\n const {\n oauthParams,\n turnkeyPublicKey,\n oauthCallbackUrl,\n oauthConfig,\n usesRelativeUrl = true,\n } = args;\n\n const {\n authProviderId,\n isCustomProvider,\n auth0Connection,\n scope: providedScope,\n claims: providedClaims,\n otherParameters: providedOtherParameters,\n mode,\n redirectUrl,\n expirationSeconds,\n } = oauthParams;\n\n const { codeChallenge, requestKey, authProviders } =\n oauthConfig ?? (await this.getOauthConfigForMode(mode));\n\n if (!authProviders) {\n throw new OAuthProvidersError();\n }\n\n const authProvider = authProviders.find(\n (provider) =>\n provider.id === authProviderId &&\n !!provider.isCustomProvider === !!isCustomProvider,\n );\n\n if (!authProvider) {\n throw new Error(`No auth provider found with id ${authProviderId}`);\n }\n\n let scope: string | undefined = providedScope;\n let claims: string | undefined = providedClaims;\n let otherParameters: Record<string, string> | undefined =\n providedOtherParameters;\n\n if (!isCustomProvider) {\n const defaultCustomization =\n getDefaultProviderCustomization(authProviderId);\n scope ??= defaultCustomization?.scope;\n claims ??= defaultCustomization?.claims;\n otherParameters ??= defaultCustomization?.otherParameters;\n }\n if (!scope) {\n throw new Error(`Default scope not known for provider ${authProviderId}`);\n }\n const { authEndpoint, clientId } = authProvider;\n\n const nonce = this.getOauthNonce(turnkeyPublicKey);\n const stateObject: OauthState = {\n authProviderId,\n isCustomProvider,\n requestKey,\n turnkeyPublicKey,\n expirationSeconds,\n redirectUrl:\n mode === \"redirect\"\n ? usesRelativeUrl\n ? resolveRelativeUrl(redirectUrl)\n : redirectUrl\n : undefined,\n openerOrigin: mode === \"popup\" ? window.location.origin : undefined,\n fetchIdTokenOnly: oauthParams.fetchIdTokenOnly,\n };\n const state = base64UrlEncode(\n new TextEncoder().encode(JSON.stringify(stateObject)),\n );\n const authUrl = new URL(authEndpoint);\n const params: Record<string, string> = {\n redirect_uri: oauthCallbackUrl,\n response_type: \"code\",\n scope,\n state,\n code_challenge: codeChallenge,\n code_challenge_method: \"S256\",\n prompt: \"select_account\",\n client_id: clientId,\n nonce,\n ...otherParameters,\n };\n if (claims) {\n params.claims = claims;\n }\n if (auth0Connection) {\n params.connection = auth0Connection;\n }\n\n Object.keys(params).forEach((param) => {\n params[param] && authUrl.searchParams.append(param, params[param]);\n });\n\n const [urlPath, searchParams] = authUrl.href.split(\"?\");\n\n return `${urlPath?.replace(/\\/$/, \"\")}?${searchParams}`;\n };\n\n private getOauthConfigForMode = async (\n mode: OauthMode,\n ): Promise<OauthConfig> => {\n if (this.oauthConfig) {\n return this.oauthConfig;\n } else if (mode === \"redirect\") {\n return this.initOauth();\n } else {\n throw new Error(\n \"enablePopupOauth must be set in configuration or signer.preparePopupOauth must be called before using popup-based OAuth login\",\n );\n }\n };\n\n // eslint-disable-next-line eslint-rules/require-jsdoc-on-reexported-functions\n protected pollActivityCompletion = async <\n T extends keyof Awaited<\n ReturnType<(typeof this.turnkeyClient)[\"getActivity\"]>\n >[\"activity\"][\"result\"],\n >(\n activity: Awaited<\n ReturnType<(typeof this.turnkeyClient)[\"getActivity\"]>\n >[\"activity\"],\n organizationId: string,\n resultKey: T,\n ): Promise<\n NonNullable<\n Awaited<\n ReturnType<(typeof this.turnkeyClient)[\"getActivity\"]>\n >[\"activity\"][\"result\"][T]\n >\n > => {\n if (activity.status === \"ACTIVITY_STATUS_COMPLETED\") {\n return activity.result[resultKey]!;\n }\n\n const {\n activity: { status, id, result },\n } = await this.turnkeyClient.getActivity({\n activityId: activity.id,\n organizationId,\n });\n\n if (status === \"ACTIVITY_STATUS_COMPLETED\") {\n return result[resultKey]!;\n }\n\n if (\n status === \"ACTIVITY_STATUS_FAILED\" ||\n status === \"ACTIVITY_STATUS_REJECTED\" ||\n status === \"ACTIVITY_STATUS_CONSENSUS_NEEDED\"\n ) {\n throw new Error(\n `Failed to get activity with with id ${id} (status: ${status})`,\n );\n }\n\n // TODO: add ability to configure this + add exponential backoff\n await new Promise((resolve) => setTimeout(resolve, 500));\n\n return this.pollActivityCompletion(activity, organizationId, resultKey);\n };\n // #endregion\n\n /**\n * Turnkey requires the nonce in the id token to be in this format.\n *\n * @param {string} turnkeyPublicKey key from a Turnkey iframe\n * @returns {string} nonce to be used in OIDC\n */\n protected getOauthNonce = (turnkeyPublicKey: string): string => {\n return sha256(new TextEncoder().encode(turnkeyPublicKey)).slice(2);\n };\n}\n"]}
|
|
@@ -2,7 +2,7 @@ import { BaseError } from "@aa-sdk/core";
|
|
|
2
2
|
import { z } from "zod";
|
|
3
3
|
import type { AuthParams } from "../signer.js";
|
|
4
4
|
import { BaseSignerClient } from "./base.js";
|
|
5
|
-
import type { AlchemySignerClientEvents, AuthenticatingEventMetadata, CredentialCreationOptionOverrides, EmailAuthParams, ExportWalletParams, OauthConfig, OtpParams, User, SubmitOtpCodeResponse, AuthLinkingPrompt, GetWebAuthnAttestationResult } from "./types.js";
|
|
5
|
+
import type { AlchemySignerClientEvents, AuthenticatingEventMetadata, CredentialCreationOptionOverrides, EmailAuthParams, ExportWalletParams, OauthConfig, OtpParams, User, SubmitOtpCodeResponse, AuthLinkingPrompt, GetWebAuthnAttestationResult, IdTokenOnly } 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>;
|
|
@@ -333,7 +333,7 @@ export declare class AlchemySignerWebClient extends BaseSignerClient<ExportWalle
|
|
|
333
333
|
oauthWithRedirect: (args: Extract<AuthParams, {
|
|
334
334
|
type: "oauth";
|
|
335
335
|
mode: "redirect";
|
|
336
|
-
}>) => Promise<
|
|
336
|
+
}>) => Promise<User | IdTokenOnly>;
|
|
337
337
|
/**
|
|
338
338
|
* Initiates an OAuth authentication flow in a popup window and returns the authenticated user.
|
|
339
339
|
*
|
|
@@ -363,7 +363,7 @@ export declare class AlchemySignerWebClient extends BaseSignerClient<ExportWalle
|
|
|
363
363
|
oauthWithPopup: (args: Extract<AuthParams, {
|
|
364
364
|
type: "oauth";
|
|
365
365
|
mode: "popup";
|
|
366
|
-
}>) => Promise<User | AuthLinkingPrompt>;
|
|
366
|
+
}>) => Promise<User | AuthLinkingPrompt | IdTokenOnly>;
|
|
367
367
|
/**
|
|
368
368
|
* Initializes the iframe stamper and returns its public key.
|
|
369
369
|
*
|
package/dist/esm/client/index.js
CHANGED
|
@@ -390,6 +390,13 @@ export class AlchemySignerWebClient extends BaseSignerClient {
|
|
|
390
390
|
orgId,
|
|
391
391
|
});
|
|
392
392
|
break;
|
|
393
|
+
case "FETCHED_ID_TOKEN_ONLY":
|
|
394
|
+
resolve({
|
|
395
|
+
status,
|
|
396
|
+
idToken,
|
|
397
|
+
providerName,
|
|
398
|
+
});
|
|
399
|
+
break;
|
|
393
400
|
default:
|
|
394
401
|
reject(new Error(`Unknown status: ${status}`));
|
|
395
402
|
}
|