@account-kit/signer 4.0.0-beta.1 → 4.0.0-beta.10
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 +42 -5
- package/dist/esm/base.js +186 -29
- package/dist/esm/base.js.map +1 -1
- package/dist/esm/client/base.d.ts +22 -4
- package/dist/esm/client/base.js +36 -2
- package/dist/esm/client/base.js.map +1 -1
- package/dist/esm/client/index.d.ts +108 -7
- package/dist/esm/client/index.js +282 -14
- package/dist/esm/client/index.js.map +1 -1
- package/dist/esm/client/types.d.ts +31 -1
- package/dist/esm/client/types.js.map +1 -1
- package/dist/esm/index.d.ts +1 -1
- package/dist/esm/index.js +1 -1
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/metrics.d.ts +17 -0
- package/dist/esm/metrics.js +7 -0
- package/dist/esm/metrics.js.map +1 -0
- package/dist/esm/oauth.d.ts +19 -0
- package/dist/esm/oauth.js +26 -0
- package/dist/esm/oauth.js.map +1 -0
- package/dist/esm/session/manager.d.ts +3 -2
- package/dist/esm/session/manager.js +29 -15
- package/dist/esm/session/manager.js.map +1 -1
- package/dist/esm/session/types.d.ts +1 -1
- package/dist/esm/session/types.js.map +1 -1
- package/dist/esm/signer.d.ts +52 -7
- package/dist/esm/signer.js +46 -3
- package/dist/esm/signer.js.map +1 -1
- package/dist/esm/types.d.ts +8 -1
- package/dist/esm/types.js +3 -1
- package/dist/esm/types.js.map +1 -1
- package/dist/esm/utils/typeAssertions.d.ts +1 -0
- package/dist/esm/utils/typeAssertions.js +4 -0
- package/dist/esm/utils/typeAssertions.js.map +1 -0
- 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 +42 -5
- package/dist/types/base.d.ts.map +1 -1
- package/dist/types/client/base.d.ts +22 -4
- package/dist/types/client/base.d.ts.map +1 -1
- package/dist/types/client/index.d.ts +108 -7
- package/dist/types/client/index.d.ts.map +1 -1
- package/dist/types/client/types.d.ts +31 -1
- package/dist/types/client/types.d.ts.map +1 -1
- package/dist/types/index.d.ts +1 -1
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/metrics.d.ts +18 -0
- package/dist/types/metrics.d.ts.map +1 -0
- package/dist/types/oauth.d.ts +20 -0
- package/dist/types/oauth.d.ts.map +1 -0
- package/dist/types/session/manager.d.ts +3 -2
- package/dist/types/session/manager.d.ts.map +1 -1
- package/dist/types/session/types.d.ts +1 -1
- package/dist/types/session/types.d.ts.map +1 -1
- package/dist/types/signer.d.ts +52 -7
- package/dist/types/signer.d.ts.map +1 -1
- package/dist/types/types.d.ts +8 -1
- package/dist/types/types.d.ts.map +1 -1
- package/dist/types/utils/typeAssertions.d.ts +2 -0
- package/dist/types/utils/typeAssertions.d.ts.map +1 -0
- package/dist/types/version.d.ts +1 -1
- package/dist/types/version.d.ts.map +1 -1
- package/package.json +6 -5
- package/src/base.ts +260 -65
- package/src/client/base.ts +49 -4
- package/src/client/index.ts +317 -20
- package/src/client/types.ts +33 -1
- package/src/index.ts +5 -1
- package/src/metrics.ts +23 -0
- package/src/oauth.ts +36 -0
- package/src/session/manager.ts +46 -19
- package/src/session/types.ts +1 -1
- package/src/signer.ts +91 -4
- package/src/types.ts +9 -1
- package/src/utils/typeAssertions.ts +3 -0
- package/src/version.ts +1 -1
package/dist/esm/client/index.js
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
|
-
import { ConnectionConfigSchema } from "@aa-sdk/core";
|
|
1
|
+
import { BaseError, ConnectionConfigSchema } from "@aa-sdk/core";
|
|
2
2
|
import { getWebAuthnAttestation } from "@turnkey/http";
|
|
3
3
|
import { IframeStamper } from "@turnkey/iframe-stamper";
|
|
4
4
|
import { WebauthnStamper } from "@turnkey/webauthn-stamper";
|
|
5
5
|
import { z } from "zod";
|
|
6
|
+
import { getDefaultScopeAndClaims, getOauthNonce } from "../oauth.js";
|
|
6
7
|
import { base64UrlEncode } from "../utils/base64UrlEncode.js";
|
|
7
8
|
import { generateRandomBuffer } from "../utils/generateRandomBuffer.js";
|
|
8
9
|
import { BaseSignerClient } from "./base.js";
|
|
10
|
+
const CHECK_CLOSE_INTERVAL = 500;
|
|
9
11
|
export const AlchemySignerClientParamsSchema = z.object({
|
|
10
12
|
connection: ConnectionConfigSchema,
|
|
11
13
|
iframeConfig: z.object({
|
|
@@ -17,6 +19,11 @@ export const AlchemySignerClientParamsSchema = z.object({
|
|
|
17
19
|
.string()
|
|
18
20
|
.optional()
|
|
19
21
|
.default("24c1acf5-810f-41e0-a503-d5d13fa8e830"),
|
|
22
|
+
oauthCallbackUrl: z
|
|
23
|
+
.string()
|
|
24
|
+
.optional()
|
|
25
|
+
.default("https://signer.alchemy.com/callback"),
|
|
26
|
+
enablePopupOauth: z.boolean().optional().default(false),
|
|
20
27
|
});
|
|
21
28
|
/**
|
|
22
29
|
* A lower level client used by the AlchemySigner used to communicate with
|
|
@@ -47,7 +54,7 @@ export class AlchemySignerWebClient extends BaseSignerClient {
|
|
|
47
54
|
* @param {string} params.rootOrgId The root organization ID
|
|
48
55
|
*/
|
|
49
56
|
constructor(params) {
|
|
50
|
-
const { connection, iframeConfig, rpId, rootOrgId } = AlchemySignerClientParamsSchema.parse(params);
|
|
57
|
+
const { connection, iframeConfig, rpId, rootOrgId, oauthCallbackUrl } = AlchemySignerClientParamsSchema.parse(params);
|
|
51
58
|
const iframeStamper = new IframeStamper({
|
|
52
59
|
iframeElementId: iframeConfig.iframeElementId,
|
|
53
60
|
iframeUrl: "https://auth.turnkey.com",
|
|
@@ -70,6 +77,12 @@ export class AlchemySignerWebClient extends BaseSignerClient {
|
|
|
70
77
|
writable: true,
|
|
71
78
|
value: void 0
|
|
72
79
|
});
|
|
80
|
+
Object.defineProperty(this, "oauthCallbackUrl", {
|
|
81
|
+
enumerable: true,
|
|
82
|
+
configurable: true,
|
|
83
|
+
writable: true,
|
|
84
|
+
value: void 0
|
|
85
|
+
});
|
|
73
86
|
Object.defineProperty(this, "iframeContainerId", {
|
|
74
87
|
enumerable: true,
|
|
75
88
|
configurable: true,
|
|
@@ -103,8 +116,8 @@ export class AlchemySignerWebClient extends BaseSignerClient {
|
|
|
103
116
|
configurable: true,
|
|
104
117
|
writable: true,
|
|
105
118
|
value: async (params) => {
|
|
106
|
-
this.eventEmitter.emit("authenticating");
|
|
107
119
|
if (params.type === "email") {
|
|
120
|
+
this.eventEmitter.emit("authenticating", { type: "email" });
|
|
108
121
|
const { email, expirationSeconds } = params;
|
|
109
122
|
const publicKey = await this.initIframeStamper();
|
|
110
123
|
const response = await this.request("/v1/signup", {
|
|
@@ -115,6 +128,7 @@ export class AlchemySignerWebClient extends BaseSignerClient {
|
|
|
115
128
|
});
|
|
116
129
|
return response;
|
|
117
130
|
}
|
|
131
|
+
this.eventEmitter.emit("authenticating", { type: "passkey" });
|
|
118
132
|
// Passkey account creation flow
|
|
119
133
|
const { attestation, challenge } = await this.getWebAuthnAttestation(params.creationOpts, { username: "email" in params ? params.email : params.username });
|
|
120
134
|
const result = await this.request("/v1/signup", {
|
|
@@ -163,7 +177,7 @@ export class AlchemySignerWebClient extends BaseSignerClient {
|
|
|
163
177
|
configurable: true,
|
|
164
178
|
writable: true,
|
|
165
179
|
value: async (params) => {
|
|
166
|
-
this.eventEmitter.emit("authenticating");
|
|
180
|
+
this.eventEmitter.emit("authenticating", { type: "email" });
|
|
167
181
|
const { email, expirationSeconds } = params;
|
|
168
182
|
const publicKey = await this.initIframeStamper();
|
|
169
183
|
return this.request("/v1/auth", {
|
|
@@ -175,7 +189,9 @@ export class AlchemySignerWebClient extends BaseSignerClient {
|
|
|
175
189
|
}
|
|
176
190
|
});
|
|
177
191
|
/**
|
|
178
|
-
* Completes
|
|
192
|
+
* Completes auth for the user by injecting a credential bundle and retrieving
|
|
193
|
+
* the user information based on the provided organization ID. Emits events
|
|
194
|
+
* during the process.
|
|
179
195
|
*
|
|
180
196
|
* @example
|
|
181
197
|
* ```ts
|
|
@@ -190,25 +206,30 @@ export class AlchemySignerWebClient extends BaseSignerClient {
|
|
|
190
206
|
* },
|
|
191
207
|
* });
|
|
192
208
|
*
|
|
193
|
-
* const account = await client.
|
|
209
|
+
* const account = await client.completeAuthWithBundle({ orgId: "user-org-id", bundle: "bundle-from-email", connectedEventName: "connectedEmail" });
|
|
194
210
|
* ```
|
|
195
211
|
*
|
|
196
|
-
* @param {{ bundle: string; orgId: string
|
|
197
|
-
*
|
|
212
|
+
* @param {{ bundle: string; orgId: string, connectedEventName: keyof AlchemySignerClientEvents, idToken?: string }} config
|
|
213
|
+
* The configuration object for the authentication function containing the
|
|
214
|
+
* credential bundle to inject and the organization id associated with the
|
|
215
|
+
* user, as well as the event to be emitted on success and optionally an OIDC
|
|
216
|
+
* ID token with extra user information
|
|
217
|
+
* @returns {Promise<User>} A promise that resolves to the authenticated user
|
|
218
|
+
* information
|
|
198
219
|
*/
|
|
199
|
-
Object.defineProperty(this, "
|
|
220
|
+
Object.defineProperty(this, "completeAuthWithBundle", {
|
|
200
221
|
enumerable: true,
|
|
201
222
|
configurable: true,
|
|
202
223
|
writable: true,
|
|
203
|
-
value: async ({ bundle, orgId, }) => {
|
|
204
|
-
this.eventEmitter.emit("authenticating");
|
|
224
|
+
value: async ({ bundle, orgId, connectedEventName, idToken, authenticatingType, }) => {
|
|
225
|
+
this.eventEmitter.emit("authenticating", { type: authenticatingType });
|
|
205
226
|
await this.initIframeStamper();
|
|
206
227
|
const result = await this.iframeStamper.injectCredentialBundle(bundle);
|
|
207
228
|
if (!result) {
|
|
208
229
|
throw new Error("Failed to inject credential bundle");
|
|
209
230
|
}
|
|
210
|
-
const user = await this.whoami(orgId);
|
|
211
|
-
this.eventEmitter.emit(
|
|
231
|
+
const user = await this.whoami(orgId, idToken);
|
|
232
|
+
this.eventEmitter.emit(connectedEventName, user, bundle);
|
|
212
233
|
return user;
|
|
213
234
|
}
|
|
214
235
|
});
|
|
@@ -239,7 +260,7 @@ export class AlchemySignerWebClient extends BaseSignerClient {
|
|
|
239
260
|
configurable: true,
|
|
240
261
|
writable: true,
|
|
241
262
|
value: async (user = undefined) => {
|
|
242
|
-
this.eventEmitter.emit("authenticating");
|
|
263
|
+
this.eventEmitter.emit("authenticating", { type: "passkey" });
|
|
243
264
|
await this.initWebauthnStamper(user);
|
|
244
265
|
if (user) {
|
|
245
266
|
this.user = user;
|
|
@@ -327,6 +348,177 @@ export class AlchemySignerWebClient extends BaseSignerClient {
|
|
|
327
348
|
value: async () => {
|
|
328
349
|
this.user = undefined;
|
|
329
350
|
this.iframeStamper.clear();
|
|
351
|
+
await this.iframeStamper.init();
|
|
352
|
+
}
|
|
353
|
+
});
|
|
354
|
+
/**
|
|
355
|
+
* Redirects the user to the OAuth provider URL based on the provided arguments. This function will always reject after 1 second if the redirection does not occur.
|
|
356
|
+
*
|
|
357
|
+
* @example
|
|
358
|
+
* ```ts
|
|
359
|
+
* import { AlchemySignerWebClient } from "@account-kit/signer";
|
|
360
|
+
*
|
|
361
|
+
* const client = new AlchemySignerWebClient({
|
|
362
|
+
* connection: {
|
|
363
|
+
* apiKey: "your-api-key",
|
|
364
|
+
* },
|
|
365
|
+
* iframeConfig: {
|
|
366
|
+
* iframeContainerId: "signer-iframe-container",
|
|
367
|
+
* },
|
|
368
|
+
* });
|
|
369
|
+
*
|
|
370
|
+
* await client.oauthWithRedirect({
|
|
371
|
+
* type: "oauth",
|
|
372
|
+
* authProviderId: "google",
|
|
373
|
+
* mode: "redirect",
|
|
374
|
+
* redirectUrl: "/",
|
|
375
|
+
* });
|
|
376
|
+
* ```
|
|
377
|
+
*
|
|
378
|
+
* @param {Extract<AuthParams, { type: "oauth"; mode: "redirect" }>} args The arguments required to obtain the OAuth provider URL
|
|
379
|
+
* @returns {Promise<never>} A promise that will never resolve, only reject if the redirection fails
|
|
380
|
+
*/
|
|
381
|
+
Object.defineProperty(this, "oauthWithRedirect", {
|
|
382
|
+
enumerable: true,
|
|
383
|
+
configurable: true,
|
|
384
|
+
writable: true,
|
|
385
|
+
value: async (args) => {
|
|
386
|
+
const providerUrl = await this.getOauthProviderUrl(args);
|
|
387
|
+
window.location.href = providerUrl;
|
|
388
|
+
return new Promise((_, reject) => setTimeout(() => reject("Failed to redirect to OAuth provider"), 1000));
|
|
389
|
+
}
|
|
390
|
+
});
|
|
391
|
+
/**
|
|
392
|
+
* Initiates an OAuth authentication flow in a popup window and returns the authenticated user.
|
|
393
|
+
*
|
|
394
|
+
* @example
|
|
395
|
+
* ```ts
|
|
396
|
+
* import { AlchemySignerWebClient } from "@account-kit/signer";
|
|
397
|
+
*
|
|
398
|
+
* const client = new AlchemySignerWebClient({
|
|
399
|
+
* connection: {
|
|
400
|
+
* apiKey: "your-api-key",
|
|
401
|
+
* },
|
|
402
|
+
* iframeConfig: {
|
|
403
|
+
* iframeContainerId: "signer-iframe-container",
|
|
404
|
+
* },
|
|
405
|
+
* });
|
|
406
|
+
*
|
|
407
|
+
* const user = await client.oauthWithPopup({
|
|
408
|
+
* type: "oauth",
|
|
409
|
+
* authProviderId: "google",
|
|
410
|
+
* mode: "popup"
|
|
411
|
+
* });
|
|
412
|
+
* ```
|
|
413
|
+
*
|
|
414
|
+
* @param {Extract<AuthParams, { type: "oauth"; mode: "popup" }>} args The authentication parameters specifying OAuth type and popup mode
|
|
415
|
+
* @returns {Promise<User>} A promise that resolves to a `User` object containing the authenticated user information
|
|
416
|
+
*/
|
|
417
|
+
Object.defineProperty(this, "oauthWithPopup", {
|
|
418
|
+
enumerable: true,
|
|
419
|
+
configurable: true,
|
|
420
|
+
writable: true,
|
|
421
|
+
value: async (args) => {
|
|
422
|
+
const providerUrl = await this.getOauthProviderUrl(args);
|
|
423
|
+
const popup = window.open(providerUrl, "_blank", "popup,width=500,height=600");
|
|
424
|
+
return new Promise((resolve, reject) => {
|
|
425
|
+
const handleMessage = (event) => {
|
|
426
|
+
if (!event.data) {
|
|
427
|
+
return;
|
|
428
|
+
}
|
|
429
|
+
const { alchemyBundle: bundle, alchemyOrgId: orgId, alchemyIdToken: idToken, alchemyError, } = event.data;
|
|
430
|
+
if (bundle && orgId && idToken) {
|
|
431
|
+
cleanup();
|
|
432
|
+
popup?.close();
|
|
433
|
+
this.completeAuthWithBundle({
|
|
434
|
+
bundle,
|
|
435
|
+
orgId,
|
|
436
|
+
connectedEventName: "connectedOauth",
|
|
437
|
+
idToken,
|
|
438
|
+
authenticatingType: "oauth",
|
|
439
|
+
}).then(resolve, reject);
|
|
440
|
+
}
|
|
441
|
+
else if (alchemyError) {
|
|
442
|
+
cleanup();
|
|
443
|
+
popup?.close();
|
|
444
|
+
reject(new OauthFailedError(alchemyError));
|
|
445
|
+
}
|
|
446
|
+
};
|
|
447
|
+
window.addEventListener("message", handleMessage);
|
|
448
|
+
const checkCloseIntervalId = setInterval(() => {
|
|
449
|
+
if (popup?.closed) {
|
|
450
|
+
cleanup();
|
|
451
|
+
reject(new OauthCancelledError());
|
|
452
|
+
}
|
|
453
|
+
}, CHECK_CLOSE_INTERVAL);
|
|
454
|
+
const cleanup = () => {
|
|
455
|
+
window.removeEventListener("message", handleMessage);
|
|
456
|
+
clearInterval(checkCloseIntervalId);
|
|
457
|
+
};
|
|
458
|
+
});
|
|
459
|
+
}
|
|
460
|
+
});
|
|
461
|
+
Object.defineProperty(this, "getOauthProviderUrl", {
|
|
462
|
+
enumerable: true,
|
|
463
|
+
configurable: true,
|
|
464
|
+
writable: true,
|
|
465
|
+
value: async (args) => {
|
|
466
|
+
const { authProviderId, isCustomProvider, auth0Connection, scope: providedScope, claims: providedClaims, mode, redirectUrl, expirationSeconds, } = args;
|
|
467
|
+
const { codeChallenge, requestKey, authProviders } = await this.getOauthConfigForMode(mode);
|
|
468
|
+
const authProvider = authProviders.find((provider) => provider.id === authProviderId &&
|
|
469
|
+
!!provider.isCustomProvider === !!isCustomProvider);
|
|
470
|
+
if (!authProvider) {
|
|
471
|
+
throw new Error(`No auth provider found with id ${authProviderId}`);
|
|
472
|
+
}
|
|
473
|
+
let scope;
|
|
474
|
+
let claims;
|
|
475
|
+
if (providedScope) {
|
|
476
|
+
scope = addOpenIdIfAbsent(providedScope);
|
|
477
|
+
claims = providedClaims;
|
|
478
|
+
}
|
|
479
|
+
else {
|
|
480
|
+
if (isCustomProvider) {
|
|
481
|
+
throw new Error("scope must be provided for a custom provider");
|
|
482
|
+
}
|
|
483
|
+
const scopeAndClaims = getDefaultScopeAndClaims(authProviderId);
|
|
484
|
+
if (!scopeAndClaims) {
|
|
485
|
+
throw new Error(`Default scope not known for provider ${authProviderId}`);
|
|
486
|
+
}
|
|
487
|
+
({ scope, claims } = scopeAndClaims);
|
|
488
|
+
}
|
|
489
|
+
const { authEndpoint, clientId } = authProvider;
|
|
490
|
+
const turnkeyPublicKey = await this.initIframeStamper();
|
|
491
|
+
const nonce = getOauthNonce(turnkeyPublicKey);
|
|
492
|
+
const stateObject = {
|
|
493
|
+
authProviderId,
|
|
494
|
+
isCustomProvider,
|
|
495
|
+
requestKey,
|
|
496
|
+
turnkeyPublicKey,
|
|
497
|
+
expirationSeconds,
|
|
498
|
+
redirectUrl: mode === "redirect" ? resolveRelativeUrl(redirectUrl) : undefined,
|
|
499
|
+
openerOrigin: mode === "popup" ? window.location.origin : undefined,
|
|
500
|
+
};
|
|
501
|
+
const state = base64UrlEncode(new TextEncoder().encode(JSON.stringify(stateObject)));
|
|
502
|
+
const authUrl = new URL(authEndpoint);
|
|
503
|
+
const params = {
|
|
504
|
+
redirect_uri: this.oauthCallbackUrl,
|
|
505
|
+
response_type: "code",
|
|
506
|
+
scope,
|
|
507
|
+
state,
|
|
508
|
+
code_challenge: codeChallenge,
|
|
509
|
+
code_challenge_method: "S256",
|
|
510
|
+
prompt: "select_account",
|
|
511
|
+
client_id: clientId,
|
|
512
|
+
nonce,
|
|
513
|
+
};
|
|
514
|
+
if (claims) {
|
|
515
|
+
params.claims = claims;
|
|
516
|
+
}
|
|
517
|
+
if (auth0Connection) {
|
|
518
|
+
params.connection = auth0Connection;
|
|
519
|
+
}
|
|
520
|
+
authUrl.search = new URLSearchParams(params).toString();
|
|
521
|
+
return authUrl.toString();
|
|
330
522
|
}
|
|
331
523
|
});
|
|
332
524
|
Object.defineProperty(this, "initIframeStamper", {
|
|
@@ -412,11 +604,87 @@ export class AlchemySignerWebClient extends BaseSignerClient {
|
|
|
412
604
|
return { challenge, authenticatorUserId, attestation };
|
|
413
605
|
}
|
|
414
606
|
});
|
|
607
|
+
Object.defineProperty(this, "getOauthConfig", {
|
|
608
|
+
enumerable: true,
|
|
609
|
+
configurable: true,
|
|
610
|
+
writable: true,
|
|
611
|
+
value: async () => {
|
|
612
|
+
const publicKey = await this.initIframeStamper();
|
|
613
|
+
const nonce = getOauthNonce(publicKey);
|
|
614
|
+
return this.request("/v1/prepare-oauth", { nonce });
|
|
615
|
+
}
|
|
616
|
+
});
|
|
617
|
+
Object.defineProperty(this, "getOauthConfigForMode", {
|
|
618
|
+
enumerable: true,
|
|
619
|
+
configurable: true,
|
|
620
|
+
writable: true,
|
|
621
|
+
value: async (mode) => {
|
|
622
|
+
if (this.oauthConfig) {
|
|
623
|
+
return this.oauthConfig;
|
|
624
|
+
}
|
|
625
|
+
else if (mode === "redirect") {
|
|
626
|
+
return this.initOauth();
|
|
627
|
+
}
|
|
628
|
+
else {
|
|
629
|
+
throw new Error("enablePopupOauth must be set in configuration or signer.preparePopupOauth must be called before using popup-based OAuth login");
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
});
|
|
415
633
|
this.iframeStamper = iframeStamper;
|
|
416
634
|
this.iframeContainerId = iframeConfig.iframeContainerId;
|
|
417
635
|
this.webauthnStamper = new WebauthnStamper({
|
|
418
636
|
rpId: rpId ?? window.location.hostname,
|
|
419
637
|
});
|
|
638
|
+
this.oauthCallbackUrl = oauthCallbackUrl;
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
function resolveRelativeUrl(url) {
|
|
642
|
+
// Funny trick.
|
|
643
|
+
const a = document.createElement("a");
|
|
644
|
+
a.href = url;
|
|
645
|
+
return a.href;
|
|
646
|
+
}
|
|
647
|
+
/**
|
|
648
|
+
* "openid" is a required scope in the OIDC protocol. Insert it if the user
|
|
649
|
+
* forgot.
|
|
650
|
+
*
|
|
651
|
+
* @param {string} scope scope param which may be missing "openid"
|
|
652
|
+
* @returns {string} scope which most definitely contains "openid"
|
|
653
|
+
*/
|
|
654
|
+
function addOpenIdIfAbsent(scope) {
|
|
655
|
+
return scope.match(/\bopenid\b/) ? scope : `openid ${scope}`;
|
|
656
|
+
}
|
|
657
|
+
/**
|
|
658
|
+
* This error is thrown when the OAuth flow is cancelled because the auth popup
|
|
659
|
+
* window was closed.
|
|
660
|
+
*/
|
|
661
|
+
export class OauthCancelledError extends BaseError {
|
|
662
|
+
/**
|
|
663
|
+
* Constructor for initializing an error indicating that the OAuth flow was
|
|
664
|
+
* cancelled.
|
|
665
|
+
*/
|
|
666
|
+
constructor() {
|
|
667
|
+
super("OAuth cancelled");
|
|
668
|
+
Object.defineProperty(this, "name", {
|
|
669
|
+
enumerable: true,
|
|
670
|
+
configurable: true,
|
|
671
|
+
writable: true,
|
|
672
|
+
value: "OauthCancelledError"
|
|
673
|
+
});
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
/**
|
|
677
|
+
* This error is thrown when an error occurs during the OAuth login flow.
|
|
678
|
+
*/
|
|
679
|
+
export class OauthFailedError extends BaseError {
|
|
680
|
+
constructor() {
|
|
681
|
+
super(...arguments);
|
|
682
|
+
Object.defineProperty(this, "name", {
|
|
683
|
+
enumerable: true,
|
|
684
|
+
configurable: true,
|
|
685
|
+
writable: true,
|
|
686
|
+
value: "OauthFailedError"
|
|
687
|
+
});
|
|
420
688
|
}
|
|
421
689
|
}
|
|
422
690
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/client/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,MAAM,cAAc,CAAC;AACtD,OAAO,E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jC,CAAC;gBACJ,CAAC;gBAED,OAAO,EAAE,SAAS,EAAE,mBAAmB,EAAE,WAAW,EAAE,CAAC;YACzD,CAAC;WAAC;QAvVA,IAAI,CAAC,aAAa,GAAG,aAAa,CAAC;QACnC,IAAI,CAAC,iBAAiB,GAAG,YAAY,CAAC,iBAAiB,CAAC;QAExD,IAAI,CAAC,eAAe,GAAG,IAAI,eAAe,CAAC;YACzC,IAAI,EAAE,IAAI,IAAI,MAAM,CAAC,QAAQ,CAAC,QAAQ;SACvC,CAAC,CAAC;IACL,CAAC;CAkVF","sourcesContent":["import { ConnectionConfigSchema } from \"@aa-sdk/core\";\nimport { getWebAuthnAttestation } from \"@turnkey/http\";\nimport { IframeStamper } from \"@turnkey/iframe-stamper\";\nimport { WebauthnStamper } from \"@turnkey/webauthn-stamper\";\nimport { z } from \"zod\";\nimport { base64UrlEncode } from \"../utils/base64UrlEncode.js\";\nimport { generateRandomBuffer } from \"../utils/generateRandomBuffer.js\";\nimport { BaseSignerClient } from \"./base.js\";\nimport type {\n CreateAccountParams,\n CredentialCreationOptionOverrides,\n EmailAuthParams,\n ExportWalletParams,\n User,\n} from \"./types.js\";\n\nexport const AlchemySignerClientParamsSchema = z.object({\n connection: ConnectionConfigSchema,\n iframeConfig: z.object({\n iframeElementId: z.string().default(\"turnkey-iframe\"),\n iframeContainerId: z.string(),\n }),\n rpId: z.string().optional(),\n rootOrgId: z\n .string()\n .optional()\n .default(\"24c1acf5-810f-41e0-a503-d5d13fa8e830\"),\n});\n\nexport type AlchemySignerClientParams = z.input<\n typeof AlchemySignerClientParamsSchema\n>;\n\n/**\n * A lower level client used by the AlchemySigner used to communicate with\n * Alchemy's signer service.\n */\nexport class AlchemySignerWebClient extends BaseSignerClient<ExportWalletParams> {\n private iframeStamper: IframeStamper;\n private webauthnStamper: WebauthnStamper;\n iframeContainerId: string;\n\n /**\n * Initializes a new instance with the given parameters, setting up the connection, iframe configuration, and WebAuthn stamper.\n *\n * @example\n * ```ts\n * import { AlchemySignerWebClient } from \"@account-kit/signer\";\n *\n * const client = new AlchemySignerWebClient({\n * connection: {\n * apiKey: \"your-api-key\",\n * },\n * iframeConfig: {\n * iframeContainerId: \"signer-iframe-container\",\n * },\n * });\n * ```\n *\n * @param {AlchemySignerClientParams} params the parameters required to initialize the client\n * @param {ConnectionConfig} params.connection The connection details needed to connect to the service\n * @param {{ iframeElementId?: string; iframeContainerId: string }} params.iframeConfig The configuration details for setting up the iframe stamper\n * @param {string} params.rpId The relying party ID, defaulting to the current hostname if not provided\n * @param {string} params.rootOrgId The root organization ID\n */\n constructor(params: AlchemySignerClientParams) {\n const { connection, iframeConfig, rpId, rootOrgId } =\n AlchemySignerClientParamsSchema.parse(params);\n\n const iframeStamper = new IframeStamper({\n iframeElementId: iframeConfig.iframeElementId,\n iframeUrl: \"https://auth.turnkey.com\",\n iframeContainer: document.getElementById(iframeConfig.iframeContainerId),\n });\n\n super({\n connection,\n rootOrgId,\n stamper: iframeStamper,\n });\n\n this.iframeStamper = iframeStamper;\n this.iframeContainerId = iframeConfig.iframeContainerId;\n\n this.webauthnStamper = new WebauthnStamper({\n rpId: rpId ?? window.location.hostname,\n });\n }\n\n /**\n * Authenticates the user by either email or passkey account creation flow. Emits events during the process.\n *\n * @example\n * ```ts\n * import { AlchemySignerWebClient } from \"@account-kit/signer\";\n *\n * const client = new AlchemySignerWebClient({\n * connection: {\n * apiKey: \"your-api-key\",\n * },\n * iframeConfig: {\n * iframeContainerId: \"signer-iframe-container\",\n * },\n * });\n *\n * const account = await client.createAccount({ type: \"email\", email: \"you@mail.com\" });\n * ```\n *\n * @param {CreateAccountParams} params The parameters for creating an account, including the type (email or passkey) and additional details.\n * @returns {Promise<SignupResponse>} A promise that resolves with the response object containing the account creation result.\n */\n createAccount = async (params: CreateAccountParams) => {\n this.eventEmitter.emit(\"authenticating\");\n if (params.type === \"email\") {\n const { email, expirationSeconds } = params;\n const publicKey = await this.initIframeStamper();\n\n const response = await this.request(\"/v1/signup\", {\n email,\n targetPublicKey: publicKey,\n expirationSeconds,\n redirectParams: params.redirectParams?.toString(),\n });\n\n return response;\n }\n\n // Passkey account creation flow\n const { attestation, challenge } = await this.getWebAuthnAttestation(\n params.creationOpts,\n { username: \"email\" in params ? params.email : params.username }\n );\n\n const result = await this.request(\"/v1/signup\", {\n passkey: {\n challenge: base64UrlEncode(challenge),\n attestation,\n },\n email: \"email\" in params ? params.email : undefined,\n });\n\n this.user = {\n orgId: result.orgId,\n address: result.address!,\n userId: result.userId!,\n credentialId: attestation.credentialId,\n };\n this.initWebauthnStamper(this.user);\n this.eventEmitter.emit(\"connectedPasskey\", this.user);\n\n return result;\n };\n\n /**\n * Begin authenticating a user with their email and an expiration time for the authentication request. Initializes the iframe stamper to get the target public key.\n * This method sends an email to the user to complete their login\n *\n * @example\n * ```ts\n * import { AlchemySignerWebClient } from \"@account-kit/signer\";\n *\n * const client = new AlchemySignerWebClient({\n * connection: {\n * apiKey: \"your-api-key\",\n * },\n * iframeConfig: {\n * iframeContainerId: \"signer-iframe-container\",\n * },\n * });\n *\n * const account = await client.initEmailAuth({ email: \"you@mail.com\" });\n * ```\n *\n * @param {Omit<EmailAuthParams, \"targetPublicKey\">} params The parameters for email authentication, excluding the target public key\n * @returns {Promise<any>} The response from the authentication request\n */\n public initEmailAuth = async (\n params: Omit<EmailAuthParams, \"targetPublicKey\">\n ) => {\n this.eventEmitter.emit(\"authenticating\");\n const { email, expirationSeconds } = params;\n const publicKey = await this.initIframeStamper();\n\n return this.request(\"/v1/auth\", {\n email,\n targetPublicKey: publicKey,\n expirationSeconds,\n redirectParams: params.redirectParams?.toString(),\n });\n };\n\n /**\n * Completes email auth for the user by injecting a credential bundle and retrieving the user information based on the provided organization ID. Emits events during the process.\n *\n * @example\n * ```ts\n * import { AlchemySignerWebClient } from \"@account-kit/signer\";\n *\n * const client = new AlchemySignerWebClient({\n * connection: {\n * apiKey: \"your-api-key\",\n * },\n * iframeConfig: {\n * iframeContainerId: \"signer-iframe-container\",\n * },\n * });\n *\n * const account = await client.completeEmailAuth({ orgId: \"user-org-id\", bundle: \"bundle-from-email\" });\n * ```\n *\n * @param {{ bundle: string; orgId: string }} config The configuration object for the authentication function containing the credential bundle to inject and the organization id associated with the user\n * @returns {Promise<User>} A promise that resolves to the authenticated user information\n */\n public completeEmailAuth = async ({\n bundle,\n orgId,\n }: {\n bundle: string;\n orgId: string;\n }) => {\n this.eventEmitter.emit(\"authenticating\");\n await this.initIframeStamper();\n\n const result = await this.iframeStamper.injectCredentialBundle(bundle);\n\n if (!result) {\n throw new Error(\"Failed to inject credential bundle\");\n }\n\n const user = await this.whoami(orgId);\n this.eventEmitter.emit(\"connectedEmail\", user, bundle);\n\n return user;\n };\n\n /**\n * Asynchronously handles the authentication process using WebAuthn Stamper. If a user is provided, sets the user and returns it. Otherwise, retrieves the current user and initializes the WebAuthn stamper.\n *\n * @example\n * ```ts\n * import { AlchemySignerWebClient } from \"@account-kit/signer\";\n *\n * const client = new AlchemySignerWebClient({\n * connection: {\n * apiKey: \"your-api-key\",\n * },\n * iframeConfig: {\n * iframeContainerId: \"signer-iframe-container\",\n * },\n * });\n *\n * const account = await client.lookupUserWithPasskey();\n * ```\n *\n * @param {User} [user] An optional user object to authenticate\n * @returns {Promise<User>} A promise that resolves to the authenticated user object\n */\n public lookupUserWithPasskey = async (user: User | undefined = undefined) => {\n this.eventEmitter.emit(\"authenticating\");\n await this.initWebauthnStamper(user);\n if (user) {\n this.user = user;\n return user;\n }\n\n const result = await this.whoami(this.rootOrg);\n await this.initWebauthnStamper(result);\n this.eventEmitter.emit(\"connectedPasskey\", result);\n\n return result;\n };\n\n /**\n * Initiates the export of a wallet by creating an iframe stamper and calling the appropriate export function.\n * The export can be based on a seed phrase or a private key.\n *\n * @example\n * ```ts\n * import { AlchemySignerWebClient } from \"@account-kit/signer\";\n *\n * const client = new AlchemySignerWebClient({\n * connection: {\n * apiKey: \"your-api-key\",\n * },\n * iframeConfig: {\n * iframeContainerId: \"signer-iframe-container\",\n * },\n * });\n *\n * const account = await client.exportWallet({\n * iframeContainerId: \"export-iframe-container\",\n * });\n * ```\n *\n * @param {ExportWalletParams} config The parameters for exporting the wallet\n * @param {string} config.iframeContainerId The ID of the container element that will hold the iframe stamper\n * @param {string} [config.iframeElementId] Optional ID for the iframe element\n * @returns {Promise<void>} A promise that resolves when the export process is complete\n */\n public exportWallet = async ({\n iframeContainerId,\n iframeElementId = \"turnkey-export-iframe\",\n }: ExportWalletParams) => {\n const exportWalletIframeStamper = new IframeStamper({\n iframeContainer: document.getElementById(iframeContainerId),\n iframeElementId: iframeElementId,\n iframeUrl: \"https://export.turnkey.com\",\n });\n await exportWalletIframeStamper.init();\n\n if (this.turnkeyClient.stamper === this.iframeStamper) {\n return this.exportWalletInner({\n exportStamper: exportWalletIframeStamper,\n exportAs: \"SEED_PHRASE\",\n });\n }\n\n return this.exportWalletInner({\n exportStamper: exportWalletIframeStamper,\n exportAs: \"PRIVATE_KEY\",\n });\n };\n\n /**\n * Asynchronous function that clears the user and resets the iframe stamper.\n *\n * @example\n * ```ts\n * import { AlchemySignerWebClient } from \"@account-kit/signer\";\n *\n * const client = new AlchemySignerWebClient({\n * connection: {\n * apiKey: \"your-api-key\",\n * },\n * iframeConfig: {\n * iframeContainerId: \"signer-iframe-container\",\n * },\n * });\n *\n * const account = await client.disconnect();\n * ```\n */\n public disconnect = async () => {\n this.user = undefined;\n this.iframeStamper.clear();\n };\n\n private initIframeStamper = async () => {\n if (!this.iframeStamper.publicKey()) {\n await this.iframeStamper.init();\n }\n\n this.setStamper(this.iframeStamper);\n\n return this.iframeStamper.publicKey()!;\n };\n\n private initWebauthnStamper = async (user: User | undefined = this.user) => {\n this.setStamper(this.webauthnStamper);\n if (user && user.credentialId) {\n // The goal here is to allow us to cache the allowed credential, but this doesn't work with hybrid transport :(\n this.webauthnStamper.allowCredentials = [\n {\n id: Buffer.from(user.credentialId, \"base64\"),\n type: \"public-key\",\n transports: [\"internal\", \"hybrid\"],\n },\n ];\n }\n };\n\n protected getWebAuthnAttestation = async (\n options?: CredentialCreationOptionOverrides,\n userDetails: { username: string } = {\n username: this.user?.email ?? \"anonymous\",\n }\n ) => {\n const challenge = generateRandomBuffer();\n const authenticatorUserId = generateRandomBuffer();\n\n const attestation = await getWebAuthnAttestation({\n publicKey: {\n ...options?.publicKey,\n authenticatorSelection: {\n residentKey: \"preferred\",\n requireResidentKey: false,\n userVerification: \"preferred\",\n ...options?.publicKey?.authenticatorSelection,\n },\n challenge,\n rp: {\n id: window.location.hostname,\n name: window.location.hostname,\n ...options?.publicKey?.rp,\n },\n pubKeyCredParams: [\n {\n type: \"public-key\",\n alg: -7,\n },\n {\n type: \"public-key\",\n alg: -257,\n },\n ],\n user: {\n id: authenticatorUserId,\n name: userDetails.username,\n displayName: userDetails.username,\n ...options?.publicKey?.user,\n },\n },\n signal: options?.signal,\n });\n\n // on iOS sometimes this is returned as empty or null, so handling that here\n if (attestation.transports == null || attestation.transports.length === 0) {\n attestation.transports = [\n \"AUTHENTICATOR_TRANSPORT_INTERNAL\",\n \"AUTHENTICATOR_TRANSPORT_HYBRID\",\n ];\n }\n\n return { challenge, authenticatorUserId, attestation };\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/client/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,sBAAsB,EAAE,MAAM,cAAc,CAAC;AACjE,OAAO,EAAE,sBAAsB,EAAE,MAAM,eAAe,CAAC;AACvD,OAAO,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAC;AACxD,OAAO,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAC;AAC5D,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,wBAAwB,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAEtE,OAAO,EAAE,eAAe,EAAE,MAAM,6BAA6B,CAAC;AAC9D,OAAO,EAAE,oBAAoB,EAAE,MAAM,kCAAk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,MAAM,OAAO,mBAAoB,SAAQ,SAAS;IAGhD;;;OAGG;IACH;QACE,KAAK,CAAC,iBAAiB,CAAC,CAAC;QAPlB;;;;mBAAO,qBAAqB;WAAC;IAQtC,CAAC;CACF;AAED;;GAEG;AACH,MAAM,OAAO,gBAAiB,SAAQ,SAAS;IAA/C;;QACW;;;;mBAAO,kBAAkB;WAAC;IACrC,CAAC;CAAA","sourcesContent":["import { BaseError, ConnectionConfigSchema } from \"@aa-sdk/core\";\nimport { getWebAuthnAttestation } from \"@turnkey/http\";\nimport { IframeStamper } from \"@turnkey/iframe-stamper\";\nimport { WebauthnStamper } from \"@turnkey/webauthn-stamper\";\nimport { z } from \"zod\";\nimport { getDefaultScopeAndClaims, getOauthNonce } from \"../oauth.js\";\nimport type { AuthParams, OauthMode } from \"../signer.js\";\nimport { base64UrlEncode } from \"../utils/base64UrlEncode.js\";\nimport { generateRandomBuffer } from \"../utils/generateRandomBuffer.js\";\nimport { BaseSignerClient } from \"./base.js\";\nimport type {\n AlchemySignerClientEvents,\n AuthenticatingEventMetadata,\n CreateAccountParams,\n CredentialCreationOptionOverrides,\n EmailAuthParams,\n ExportWalletParams,\n OauthConfig,\n OauthParams,\n User,\n} from \"./types.js\";\n\nconst CHECK_CLOSE_INTERVAL = 500;\n\nexport const AlchemySignerClientParamsSchema = z.object({\n connection: ConnectionConfigSchema,\n iframeConfig: z.object({\n iframeElementId: z.string().default(\"turnkey-iframe\"),\n iframeContainerId: z.string(),\n }),\n rpId: z.string().optional(),\n rootOrgId: z\n .string()\n .optional()\n .default(\"24c1acf5-810f-41e0-a503-d5d13fa8e830\"),\n oauthCallbackUrl: z\n .string()\n .optional()\n .default(\"https://signer.alchemy.com/callback\"),\n enablePopupOauth: z.boolean().optional().default(false),\n});\n\nexport type AlchemySignerClientParams = z.input<\n typeof AlchemySignerClientParamsSchema\n>;\n\ntype OauthState = {\n authProviderId: string;\n isCustomProvider?: boolean;\n requestKey: string;\n turnkeyPublicKey: string;\n expirationSeconds?: number;\n redirectUrl?: string;\n openerOrigin?: string;\n};\n\n/**\n * A lower level client used by the AlchemySigner used to communicate with\n * Alchemy's signer service.\n */\nexport class AlchemySignerWebClient extends BaseSignerClient<ExportWalletParams> {\n private iframeStamper: IframeStamper;\n private webauthnStamper: WebauthnStamper;\n oauthCallbackUrl: string;\n iframeContainerId: string;\n\n /**\n * Initializes a new instance with the given parameters, setting up the connection, iframe configuration, and WebAuthn stamper.\n *\n * @example\n * ```ts\n * import { AlchemySignerWebClient } from \"@account-kit/signer\";\n *\n * const client = new AlchemySignerWebClient({\n * connection: {\n * apiKey: \"your-api-key\",\n * },\n * iframeConfig: {\n * iframeContainerId: \"signer-iframe-container\",\n * },\n * });\n * ```\n *\n * @param {AlchemySignerClientParams} params the parameters required to initialize the client\n * @param {ConnectionConfig} params.connection The connection details needed to connect to the service\n * @param {{ iframeElementId?: string; iframeContainerId: string }} params.iframeConfig The configuration details for setting up the iframe stamper\n * @param {string} params.rpId The relying party ID, defaulting to the current hostname if not provided\n * @param {string} params.rootOrgId The root organization ID\n */\n constructor(params: AlchemySignerClientParams) {\n const { connection, iframeConfig, rpId, rootOrgId, oauthCallbackUrl } =\n AlchemySignerClientParamsSchema.parse(params);\n\n const iframeStamper = new IframeStamper({\n iframeElementId: iframeConfig.iframeElementId,\n iframeUrl: \"https://auth.turnkey.com\",\n iframeContainer: document.getElementById(iframeConfig.iframeContainerId),\n });\n\n super({\n connection,\n rootOrgId,\n stamper: iframeStamper,\n });\n\n this.iframeStamper = iframeStamper;\n this.iframeContainerId = iframeConfig.iframeContainerId;\n\n this.webauthnStamper = new WebauthnStamper({\n rpId: rpId ?? window.location.hostname,\n });\n\n this.oauthCallbackUrl = oauthCallbackUrl;\n }\n\n /**\n * Authenticates the user by either email or passkey account creation flow. Emits events during the process.\n *\n * @example\n * ```ts\n * import { AlchemySignerWebClient } from \"@account-kit/signer\";\n *\n * const client = new AlchemySignerWebClient({\n * connection: {\n * apiKey: \"your-api-key\",\n * },\n * iframeConfig: {\n * iframeContainerId: \"signer-iframe-container\",\n * },\n * });\n *\n * const account = await client.createAccount({ type: \"email\", email: \"you@mail.com\" });\n * ```\n *\n * @param {CreateAccountParams} params The parameters for creating an account, including the type (email or passkey) and additional details.\n * @returns {Promise<SignupResponse>} A promise that resolves with the response object containing the account creation result.\n */\n public override createAccount = async (params: CreateAccountParams) => {\n if (params.type === \"email\") {\n this.eventEmitter.emit(\"authenticating\", { type: \"email\" });\n const { email, expirationSeconds } = params;\n const publicKey = await this.initIframeStamper();\n\n const response = await this.request(\"/v1/signup\", {\n email,\n targetPublicKey: publicKey,\n expirationSeconds,\n redirectParams: params.redirectParams?.toString(),\n });\n\n return response;\n }\n\n this.eventEmitter.emit(\"authenticating\", { type: \"passkey\" });\n // Passkey account creation flow\n const { attestation, challenge } = await this.getWebAuthnAttestation(\n params.creationOpts,\n { username: \"email\" in params ? params.email : params.username }\n );\n\n const result = await this.request(\"/v1/signup\", {\n passkey: {\n challenge: base64UrlEncode(challenge),\n attestation,\n },\n email: \"email\" in params ? params.email : undefined,\n });\n\n this.user = {\n orgId: result.orgId,\n address: result.address!,\n userId: result.userId!,\n credentialId: attestation.credentialId,\n };\n this.initWebauthnStamper(this.user);\n this.eventEmitter.emit(\"connectedPasskey\", this.user);\n\n return result;\n };\n\n /**\n * Begin authenticating a user with their email and an expiration time for the authentication request. Initializes the iframe stamper to get the target public key.\n * This method sends an email to the user to complete their login\n *\n * @example\n * ```ts\n * import { AlchemySignerWebClient } from \"@account-kit/signer\";\n *\n * const client = new AlchemySignerWebClient({\n * connection: {\n * apiKey: \"your-api-key\",\n * },\n * iframeConfig: {\n * iframeContainerId: \"signer-iframe-container\",\n * },\n * });\n *\n * const account = await client.initEmailAuth({ email: \"you@mail.com\" });\n * ```\n *\n * @param {Omit<EmailAuthParams, \"targetPublicKey\">} params The parameters for email authentication, excluding the target public key\n * @returns {Promise<any>} The response from the authentication request\n */\n public override initEmailAuth = async (\n params: Omit<EmailAuthParams, \"targetPublicKey\">\n ) => {\n this.eventEmitter.emit(\"authenticating\", { type: \"email\" });\n const { email, expirationSeconds } = params;\n const publicKey = await this.initIframeStamper();\n\n return this.request(\"/v1/auth\", {\n email,\n targetPublicKey: publicKey,\n expirationSeconds,\n redirectParams: params.redirectParams?.toString(),\n });\n };\n\n /**\n * Completes auth for the user by injecting a credential bundle and retrieving\n * the user information based on the provided organization ID. Emits events\n * during the process.\n *\n * @example\n * ```ts\n * import { AlchemySignerWebClient } from \"@account-kit/signer\";\n *\n * const client = new AlchemySignerWebClient({\n * connection: {\n * apiKey: \"your-api-key\",\n * },\n * iframeConfig: {\n * iframeContainerId: \"signer-iframe-container\",\n * },\n * });\n *\n * const account = await client.completeAuthWithBundle({ orgId: \"user-org-id\", bundle: \"bundle-from-email\", connectedEventName: \"connectedEmail\" });\n * ```\n *\n * @param {{ bundle: string; orgId: string, connectedEventName: keyof AlchemySignerClientEvents, idToken?: string }} config\n * The configuration object for the authentication function containing the\n * credential bundle to inject and the organization id associated with the\n * user, as well as the event to be emitted on success and optionally an OIDC\n * ID token with extra user information\n * @returns {Promise<User>} A promise that resolves to the authenticated user\n * information\n */\n public override completeAuthWithBundle = async ({\n bundle,\n orgId,\n connectedEventName,\n idToken,\n authenticatingType,\n }: {\n bundle: string;\n orgId: string;\n connectedEventName: keyof AlchemySignerClientEvents;\n authenticatingType: AuthenticatingEventMetadata[\"type\"];\n idToken?: string;\n }): Promise<User> => {\n this.eventEmitter.emit(\"authenticating\", { type: authenticatingType });\n await this.initIframeStamper();\n\n const result = await this.iframeStamper.injectCredentialBundle(bundle);\n\n if (!result) {\n throw new Error(\"Failed to inject credential bundle\");\n }\n\n const user = await this.whoami(orgId, idToken);\n\n this.eventEmitter.emit(connectedEventName, user, bundle);\n\n return user;\n };\n\n /**\n * Asynchronously handles the authentication process using WebAuthn Stamper. If a user is provided, sets the user and returns it. Otherwise, retrieves the current user and initializes the WebAuthn stamper.\n *\n * @example\n * ```ts\n * import { AlchemySignerWebClient } from \"@account-kit/signer\";\n *\n * const client = new AlchemySignerWebClient({\n * connection: {\n * apiKey: \"your-api-key\",\n * },\n * iframeConfig: {\n * iframeContainerId: \"signer-iframe-container\",\n * },\n * });\n *\n * const account = await client.lookupUserWithPasskey();\n * ```\n *\n * @param {User} [user] An optional user object to authenticate\n * @returns {Promise<User>} A promise that resolves to the authenticated user object\n */\n public override lookupUserWithPasskey = async (\n user: User | undefined = undefined\n ) => {\n this.eventEmitter.emit(\"authenticating\", { type: \"passkey\" });\n await this.initWebauthnStamper(user);\n if (user) {\n this.user = user;\n return user;\n }\n\n const result = await this.whoami(this.rootOrg);\n await this.initWebauthnStamper(result);\n this.eventEmitter.emit(\"connectedPasskey\", result);\n\n return result;\n };\n\n /**\n * Initiates the export of a wallet by creating an iframe stamper and calling the appropriate export function.\n * The export can be based on a seed phrase or a private key.\n *\n * @example\n * ```ts\n * import { AlchemySignerWebClient } from \"@account-kit/signer\";\n *\n * const client = new AlchemySignerWebClient({\n * connection: {\n * apiKey: \"your-api-key\",\n * },\n * iframeConfig: {\n * iframeContainerId: \"signer-iframe-container\",\n * },\n * });\n *\n * const account = await client.exportWallet({\n * iframeContainerId: \"export-iframe-container\",\n * });\n * ```\n *\n * @param {ExportWalletParams} config The parameters for exporting the wallet\n * @param {string} config.iframeContainerId The ID of the container element that will hold the iframe stamper\n * @param {string} [config.iframeElementId] Optional ID for the iframe element\n * @returns {Promise<void>} A promise that resolves when the export process is complete\n */\n public override exportWallet = async ({\n iframeContainerId,\n iframeElementId = \"turnkey-export-iframe\",\n }: ExportWalletParams) => {\n const exportWalletIframeStamper = new IframeStamper({\n iframeContainer: document.getElementById(iframeContainerId),\n iframeElementId: iframeElementId,\n iframeUrl: \"https://export.turnkey.com\",\n });\n await exportWalletIframeStamper.init();\n\n if (this.turnkeyClient.stamper === this.iframeStamper) {\n return this.exportWalletInner({\n exportStamper: exportWalletIframeStamper,\n exportAs: \"SEED_PHRASE\",\n });\n }\n\n return this.exportWalletInner({\n exportStamper: exportWalletIframeStamper,\n exportAs: \"PRIVATE_KEY\",\n });\n };\n\n /**\n * Asynchronous function that clears the user and resets the iframe stamper.\n *\n * @example\n * ```ts\n * import { AlchemySignerWebClient } from \"@account-kit/signer\";\n *\n * const client = new AlchemySignerWebClient({\n * connection: {\n * apiKey: \"your-api-key\",\n * },\n * iframeConfig: {\n * iframeContainerId: \"signer-iframe-container\",\n * },\n * });\n *\n * const account = await client.disconnect();\n * ```\n */\n public override disconnect = async () => {\n this.user = undefined;\n this.iframeStamper.clear();\n await this.iframeStamper.init();\n };\n\n /**\n * Redirects the user to the OAuth provider URL based on the provided arguments. This function will always reject after 1 second if the redirection does not occur.\n *\n * @example\n * ```ts\n * import { AlchemySignerWebClient } from \"@account-kit/signer\";\n *\n * const client = new AlchemySignerWebClient({\n * connection: {\n * apiKey: \"your-api-key\",\n * },\n * iframeConfig: {\n * iframeContainerId: \"signer-iframe-container\",\n * },\n * });\n *\n * await client.oauthWithRedirect({\n * type: \"oauth\",\n * authProviderId: \"google\",\n * mode: \"redirect\",\n * redirectUrl: \"/\",\n * });\n * ```\n *\n * @param {Extract<AuthParams, { type: \"oauth\"; mode: \"redirect\" }>} args The arguments required to obtain the OAuth provider URL\n * @returns {Promise<never>} A promise that will never resolve, only reject if the redirection fails\n */\n public override oauthWithRedirect = async (\n args: Extract<AuthParams, { type: \"oauth\"; mode: \"redirect\" }>\n ): Promise<never> => {\n const providerUrl = await this.getOauthProviderUrl(args);\n window.location.href = providerUrl;\n return new Promise((_, reject) =>\n setTimeout(() => reject(\"Failed to redirect to OAuth provider\"), 1000)\n );\n };\n\n /**\n * Initiates an OAuth authentication flow in a popup window and returns the authenticated user.\n *\n * @example\n * ```ts\n * import { AlchemySignerWebClient } from \"@account-kit/signer\";\n *\n * const client = new AlchemySignerWebClient({\n * connection: {\n * apiKey: \"your-api-key\",\n * },\n * iframeConfig: {\n * iframeContainerId: \"signer-iframe-container\",\n * },\n * });\n *\n * const user = await client.oauthWithPopup({\n * type: \"oauth\",\n * authProviderId: \"google\",\n * mode: \"popup\"\n * });\n * ```\n *\n * @param {Extract<AuthParams, { type: \"oauth\"; mode: \"popup\" }>} args The authentication parameters specifying OAuth type and popup mode\n * @returns {Promise<User>} A promise that resolves to a `User` object containing the authenticated user information\n */\n public override oauthWithPopup = async (\n args: Extract<AuthParams, { type: \"oauth\"; mode: \"popup\" }>\n ): Promise<User> => {\n const providerUrl = await this.getOauthProviderUrl(args);\n const popup = window.open(\n providerUrl,\n \"_blank\",\n \"popup,width=500,height=600\"\n );\n return new Promise((resolve, reject) => {\n const handleMessage = (event: MessageEvent) => {\n if (!event.data) {\n return;\n }\n const {\n alchemyBundle: bundle,\n alchemyOrgId: orgId,\n alchemyIdToken: idToken,\n alchemyError,\n } = event.data;\n if (bundle && orgId && idToken) {\n cleanup();\n popup?.close();\n this.completeAuthWithBundle({\n bundle,\n orgId,\n connectedEventName: \"connectedOauth\",\n idToken,\n authenticatingType: \"oauth\",\n }).then(resolve, reject);\n } else if (alchemyError) {\n cleanup();\n popup?.close();\n reject(new OauthFailedError(alchemyError));\n }\n };\n\n window.addEventListener(\"message\", handleMessage);\n\n const checkCloseIntervalId = setInterval(() => {\n if (popup?.closed) {\n cleanup();\n reject(new OauthCancelledError());\n }\n }, CHECK_CLOSE_INTERVAL);\n\n const cleanup = () => {\n window.removeEventListener(\"message\", handleMessage);\n clearInterval(checkCloseIntervalId);\n };\n });\n };\n\n private getOauthProviderUrl = async (args: OauthParams): Promise<string> => {\n const {\n authProviderId,\n isCustomProvider,\n auth0Connection,\n scope: providedScope,\n claims: providedClaims,\n mode,\n redirectUrl,\n expirationSeconds,\n } = args;\n const { codeChallenge, requestKey, authProviders } =\n await this.getOauthConfigForMode(mode);\n const authProvider = authProviders.find(\n (provider) =>\n provider.id === authProviderId &&\n !!provider.isCustomProvider === !!isCustomProvider\n );\n if (!authProvider) {\n throw new Error(`No auth provider found with id ${authProviderId}`);\n }\n let scope: string;\n let claims: string | undefined;\n if (providedScope) {\n scope = addOpenIdIfAbsent(providedScope);\n claims = providedClaims;\n } else {\n if (isCustomProvider) {\n throw new Error(\"scope must be provided for a custom provider\");\n }\n const scopeAndClaims = getDefaultScopeAndClaims(authProviderId);\n if (!scopeAndClaims) {\n throw new Error(\n `Default scope not known for provider ${authProviderId}`\n );\n }\n ({ scope, claims } = scopeAndClaims);\n }\n const { authEndpoint, clientId } = authProvider;\n const turnkeyPublicKey = await this.initIframeStamper();\n const nonce = getOauthNonce(turnkeyPublicKey);\n const stateObject: OauthState = {\n authProviderId,\n isCustomProvider,\n requestKey,\n turnkeyPublicKey,\n expirationSeconds,\n redirectUrl:\n mode === \"redirect\" ? resolveRelativeUrl(redirectUrl) : 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: this.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 };\n if (claims) {\n params.claims = claims;\n }\n if (auth0Connection) {\n params.connection = auth0Connection;\n }\n authUrl.search = new URLSearchParams(params).toString();\n return authUrl.toString();\n };\n\n private initIframeStamper = async () => {\n if (!this.iframeStamper.publicKey()) {\n await this.iframeStamper.init();\n }\n\n this.setStamper(this.iframeStamper);\n\n return this.iframeStamper.publicKey()!;\n };\n\n private initWebauthnStamper = async (user: User | undefined = this.user) => {\n this.setStamper(this.webauthnStamper);\n if (user && user.credentialId) {\n // The goal here is to allow us to cache the allowed credential, but this doesn't work with hybrid transport :(\n this.webauthnStamper.allowCredentials = [\n {\n id: Buffer.from(user.credentialId, \"base64\"),\n type: \"public-key\",\n transports: [\"internal\", \"hybrid\"],\n },\n ];\n }\n };\n\n protected override getWebAuthnAttestation = async (\n options?: CredentialCreationOptionOverrides,\n userDetails: { username: string } = {\n username: this.user?.email ?? \"anonymous\",\n }\n ) => {\n const challenge = generateRandomBuffer();\n const authenticatorUserId = generateRandomBuffer();\n\n const attestation = await getWebAuthnAttestation({\n publicKey: {\n ...options?.publicKey,\n authenticatorSelection: {\n residentKey: \"preferred\",\n requireResidentKey: false,\n userVerification: \"preferred\",\n ...options?.publicKey?.authenticatorSelection,\n },\n challenge,\n rp: {\n id: window.location.hostname,\n name: window.location.hostname,\n ...options?.publicKey?.rp,\n },\n pubKeyCredParams: [\n {\n type: \"public-key\",\n alg: -7,\n },\n {\n type: \"public-key\",\n alg: -257,\n },\n ],\n user: {\n id: authenticatorUserId,\n name: userDetails.username,\n displayName: userDetails.username,\n ...options?.publicKey?.user,\n },\n },\n signal: options?.signal,\n });\n\n // on iOS sometimes this is returned as empty or null, so handling that here\n if (attestation.transports == null || attestation.transports.length === 0) {\n attestation.transports = [\n \"AUTHENTICATOR_TRANSPORT_INTERNAL\",\n \"AUTHENTICATOR_TRANSPORT_HYBRID\",\n ];\n }\n\n return { challenge, authenticatorUserId, attestation };\n };\n\n protected override getOauthConfig = async (): Promise<OauthConfig> => {\n const publicKey = await this.initIframeStamper();\n const nonce = getOauthNonce(publicKey);\n return this.request(\"/v1/prepare-oauth\", { nonce });\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\nfunction resolveRelativeUrl(url: string): string {\n // Funny trick.\n const a = document.createElement(\"a\");\n a.href = url;\n return a.href;\n}\n\n/**\n * \"openid\" is a required scope in the OIDC protocol. Insert it if the user\n * forgot.\n *\n * @param {string} scope scope param which may be missing \"openid\"\n * @returns {string} scope which most definitely contains \"openid\"\n */\nfunction addOpenIdIfAbsent(scope: string): string {\n return scope.match(/\\bopenid\\b/) ? scope : `openid ${scope}`;\n}\n\n/**\n * This error is thrown when the OAuth flow is cancelled because the auth popup\n * window was closed.\n */\nexport class OauthCancelledError extends BaseError {\n override name = \"OauthCancelledError\";\n\n /**\n * Constructor for initializing an error indicating that the OAuth flow was\n * cancelled.\n */\n constructor() {\n super(\"OAuth cancelled\");\n }\n}\n\n/**\n * This error is thrown when an error occurs during the OAuth login flow.\n */\nexport class OauthFailedError extends BaseError {\n override name = \"OauthFailedError\";\n}\n"]}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { Address } from "@aa-sdk/core";
|
|
2
2
|
import type { TSignedRequest, getWebAuthnAttestation } from "@turnkey/http";
|
|
3
3
|
import type { Hex } from "viem";
|
|
4
|
+
import type { AuthParams } from "../signer";
|
|
4
5
|
export type CredentialCreationOptionOverrides = {
|
|
5
6
|
publicKey?: Partial<CredentialCreationOptions["publicKey"]>;
|
|
6
7
|
} & Pick<CredentialCreationOptions, "signal">;
|
|
@@ -10,6 +11,8 @@ export type User = {
|
|
|
10
11
|
userId: string;
|
|
11
12
|
address: Address;
|
|
12
13
|
credentialId?: string;
|
|
14
|
+
idToken?: string;
|
|
15
|
+
claims?: Record<string, unknown>;
|
|
13
16
|
};
|
|
14
17
|
export type ExportWalletParams = {
|
|
15
18
|
iframeContainerId: string;
|
|
@@ -35,11 +38,27 @@ export type EmailAuthParams = {
|
|
|
35
38
|
targetPublicKey: string;
|
|
36
39
|
redirectParams?: URLSearchParams;
|
|
37
40
|
};
|
|
41
|
+
export type OauthParams = Extract<AuthParams, {
|
|
42
|
+
type: "oauth";
|
|
43
|
+
}> & {
|
|
44
|
+
expirationSeconds?: number;
|
|
45
|
+
};
|
|
38
46
|
export type SignupResponse = {
|
|
39
47
|
orgId: string;
|
|
40
48
|
userId?: string;
|
|
41
49
|
address?: Address;
|
|
42
50
|
};
|
|
51
|
+
export type OauthConfig = {
|
|
52
|
+
codeChallenge: string;
|
|
53
|
+
requestKey: string;
|
|
54
|
+
authProviders: AuthProviderConfig[];
|
|
55
|
+
};
|
|
56
|
+
export type AuthProviderConfig = {
|
|
57
|
+
id: string;
|
|
58
|
+
isCustomProvider?: boolean;
|
|
59
|
+
clientId: string;
|
|
60
|
+
authEndpoint: string;
|
|
61
|
+
};
|
|
43
62
|
export type SignerRoutes = SignerEndpoints[number]["Route"];
|
|
44
63
|
export type SignerBody<T extends SignerRoutes> = Extract<SignerEndpoints[number], {
|
|
45
64
|
Route: T;
|
|
@@ -93,13 +112,24 @@ export type SignerEndpoints = [
|
|
|
93
112
|
Response: {
|
|
94
113
|
signature: Hex;
|
|
95
114
|
};
|
|
115
|
+
},
|
|
116
|
+
{
|
|
117
|
+
Route: "/v1/prepare-oauth";
|
|
118
|
+
Body: {
|
|
119
|
+
nonce: string;
|
|
120
|
+
};
|
|
121
|
+
Response: OauthConfig;
|
|
96
122
|
}
|
|
97
123
|
];
|
|
124
|
+
export type AuthenticatingEventMetadata = {
|
|
125
|
+
type: "email" | "passkey" | "oauth";
|
|
126
|
+
};
|
|
98
127
|
export type AlchemySignerClientEvents = {
|
|
99
128
|
connected(user: User): void;
|
|
100
|
-
authenticating(): void;
|
|
129
|
+
authenticating(data: AuthenticatingEventMetadata): void;
|
|
101
130
|
connectedEmail(user: User, bundle: string): void;
|
|
102
131
|
connectedPasskey(user: User): void;
|
|
132
|
+
connectedOauth(user: User, bundle: string): void;
|
|
103
133
|
disconnected(): void;
|
|
104
134
|
};
|
|
105
135
|
export type AlchemySignerClientEvent = keyof AlchemySignerClientEvents;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/client/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { Address } from \"@aa-sdk/core\";\nimport type { TSignedRequest, getWebAuthnAttestation } from \"@turnkey/http\";\nimport type { Hex } from \"viem\";\n\nexport type CredentialCreationOptionOverrides = {\n publicKey?: Partial<CredentialCreationOptions[\"publicKey\"]>;\n} & Pick<CredentialCreationOptions, \"signal\">;\n\n// [!region User]\nexport type User = {\n email?: string;\n orgId: string;\n userId: string;\n address: Address;\n credentialId?: string;\n};\n// [!endregion User]\n\nexport type ExportWalletParams = {\n iframeContainerId: string;\n iframeElementId?: string;\n};\n\nexport type CreateAccountParams =\n | {\n type: \"email\";\n email: string;\n expirationSeconds?: number;\n redirectParams?: URLSearchParams;\n }\n | {\n type: \"passkey\";\n email: string;\n creationOpts?: CredentialCreationOptionOverrides;\n }\n | {\n type: \"passkey\";\n username: string;\n creationOpts?: CredentialCreationOptionOverrides;\n };\n\nexport type EmailAuthParams = {\n email: string;\n expirationSeconds?: number;\n targetPublicKey: string;\n redirectParams?: URLSearchParams;\n};\n\nexport type SignupResponse = {\n orgId: string;\n userId?: string;\n address?: Address;\n};\n\nexport type SignerRoutes = SignerEndpoints[number][\"Route\"];\nexport type SignerBody<T extends SignerRoutes> = Extract<\n SignerEndpoints[number],\n { Route: T }\n>[\"Body\"];\nexport type SignerResponse<T extends SignerRoutes> = Extract<\n SignerEndpoints[number],\n { Route: T }\n>[\"Response\"];\n\nexport type SignerEndpoints = [\n {\n Route: \"/v1/signup\";\n Body:\n | (Omit<EmailAuthParams, \"redirectParams\"> & { redirectParams?: string })\n | {\n passkey: {\n challenge: string;\n attestation: Awaited<ReturnType<typeof getWebAuthnAttestation>>;\n };\n };\n Response: SignupResponse;\n },\n {\n Route: \"/v1/whoami\";\n Body: {\n stampedRequest: TSignedRequest;\n };\n Response: User;\n },\n {\n Route: \"/v1/auth\";\n Body: Omit<EmailAuthParams, \"redirectParams\"> & { redirectParams?: string };\n Response: {\n orgId: string;\n };\n },\n {\n Route: \"/v1/lookup\";\n Body: {\n email: string;\n };\n Response: {\n orgId: string | null;\n };\n },\n {\n Route: \"/v1/sign-payload\";\n Body: {\n stampedRequest: TSignedRequest;\n };\n Response: {\n signature: Hex;\n };\n }\n];\n\nexport type AlchemySignerClientEvents = {\n connected(user: User): void;\n authenticating(): void;\n connectedEmail(user: User, bundle: string): void;\n connectedPasskey(user: User): void;\n disconnected(): void;\n};\n\nexport type AlchemySignerClientEvent = keyof AlchemySignerClientEvents;\n\nexport type GetWebAuthnAttestationResult = {\n attestation: Awaited<ReturnType<typeof getWebAuthnAttestation>>;\n challenge: ArrayBuffer;\n authenticatorUserId: ArrayBuffer;\n};\n"]}
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/client/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { Address } from \"@aa-sdk/core\";\nimport type { TSignedRequest, getWebAuthnAttestation } from \"@turnkey/http\";\nimport type { Hex } from \"viem\";\nimport type { AuthParams } from \"../signer\";\n\nexport type CredentialCreationOptionOverrides = {\n publicKey?: Partial<CredentialCreationOptions[\"publicKey\"]>;\n} & Pick<CredentialCreationOptions, \"signal\">;\n\n// [!region User]\nexport type User = {\n email?: string;\n orgId: string;\n userId: string;\n address: Address;\n credentialId?: string;\n idToken?: string;\n claims?: Record<string, unknown>;\n};\n// [!endregion User]\n\nexport type ExportWalletParams = {\n iframeContainerId: string;\n iframeElementId?: string;\n};\n\nexport type CreateAccountParams =\n | {\n type: \"email\";\n email: string;\n expirationSeconds?: number;\n redirectParams?: URLSearchParams;\n }\n | {\n type: \"passkey\";\n email: string;\n creationOpts?: CredentialCreationOptionOverrides;\n }\n | {\n type: \"passkey\";\n username: string;\n creationOpts?: CredentialCreationOptionOverrides;\n };\n\nexport type EmailAuthParams = {\n email: string;\n expirationSeconds?: number;\n targetPublicKey: string;\n redirectParams?: URLSearchParams;\n};\n\nexport type OauthParams = Extract<AuthParams, { type: \"oauth\" }> & {\n expirationSeconds?: number;\n};\n\nexport type SignupResponse = {\n orgId: string;\n userId?: string;\n address?: Address;\n};\n\nexport type OauthConfig = {\n codeChallenge: string;\n requestKey: string;\n authProviders: AuthProviderConfig[];\n};\n\nexport type AuthProviderConfig = {\n id: string;\n isCustomProvider?: boolean;\n clientId: string;\n authEndpoint: string;\n};\n\nexport type SignerRoutes = SignerEndpoints[number][\"Route\"];\nexport type SignerBody<T extends SignerRoutes> = Extract<\n SignerEndpoints[number],\n { Route: T }\n>[\"Body\"];\nexport type SignerResponse<T extends SignerRoutes> = Extract<\n SignerEndpoints[number],\n { Route: T }\n>[\"Response\"];\n\nexport type SignerEndpoints = [\n {\n Route: \"/v1/signup\";\n Body:\n | (Omit<EmailAuthParams, \"redirectParams\"> & { redirectParams?: string })\n | {\n passkey: {\n challenge: string;\n attestation: Awaited<ReturnType<typeof getWebAuthnAttestation>>;\n };\n };\n Response: SignupResponse;\n },\n {\n Route: \"/v1/whoami\";\n Body: {\n stampedRequest: TSignedRequest;\n };\n Response: User;\n },\n {\n Route: \"/v1/auth\";\n Body: Omit<EmailAuthParams, \"redirectParams\"> & { redirectParams?: string };\n Response: {\n orgId: string;\n };\n },\n {\n Route: \"/v1/lookup\";\n Body: {\n email: string;\n };\n Response: {\n orgId: string | null;\n };\n },\n {\n Route: \"/v1/sign-payload\";\n Body: {\n stampedRequest: TSignedRequest;\n };\n Response: {\n signature: Hex;\n };\n },\n {\n Route: \"/v1/prepare-oauth\";\n Body: {\n nonce: string;\n };\n Response: OauthConfig;\n }\n];\n\nexport type AuthenticatingEventMetadata = {\n type: \"email\" | \"passkey\" | \"oauth\";\n};\n\nexport type AlchemySignerClientEvents = {\n connected(user: User): void;\n authenticating(data: AuthenticatingEventMetadata): void;\n connectedEmail(user: User, bundle: string): void;\n connectedPasskey(user: User): void;\n connectedOauth(user: User, bundle: string): void;\n disconnected(): void;\n};\n\nexport type AlchemySignerClientEvent = keyof AlchemySignerClientEvents;\n\nexport type GetWebAuthnAttestationResult = {\n attestation: Awaited<ReturnType<typeof getWebAuthnAttestation>>;\n challenge: ArrayBuffer;\n authenticatorUserId: ArrayBuffer;\n};\n"]}
|
package/dist/esm/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
export { BaseAlchemySigner } from "./base.js";
|
|
2
2
|
export { BaseSignerClient } from "./client/base.js";
|
|
3
|
-
export { AlchemySignerWebClient } from "./client/index.js";
|
|
3
|
+
export { AlchemySignerWebClient, OauthCancelledError, OauthFailedError, } from "./client/index.js";
|
|
4
4
|
export type * from "./client/types.js";
|
|
5
5
|
export { DEFAULT_SESSION_MS } from "./session/manager.js";
|
|
6
6
|
export type * from "./signer.js";
|
package/dist/esm/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
export { BaseAlchemySigner } from "./base.js";
|
|
2
2
|
export { BaseSignerClient } from "./client/base.js";
|
|
3
|
-
export { AlchemySignerWebClient } from "./client/index.js";
|
|
3
|
+
export { AlchemySignerWebClient, OauthCancelledError, OauthFailedError, } from "./client/index.js";
|
|
4
4
|
export { DEFAULT_SESSION_MS } from "./session/manager.js";
|
|
5
5
|
export { AlchemyWebSigner } from "./signer.js";
|
|
6
6
|
export { AlchemySignerStatus } from "./types.js";
|
package/dist/esm/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,WAAW,CAAC;AAC9C,OAAO,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AACpD,OAAO,
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,WAAW,CAAC;AAC9C,OAAO,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AACpD,OAAO,EACL,sBAAsB,EACtB,mBAAmB,EACnB,gBAAgB,GACjB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAE1D,OAAO,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAE/C,OAAO,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC","sourcesContent":["export { BaseAlchemySigner } from \"./base.js\";\nexport { BaseSignerClient } from \"./client/base.js\";\nexport {\n AlchemySignerWebClient,\n OauthCancelledError,\n OauthFailedError,\n} from \"./client/index.js\";\nexport type * from \"./client/types.js\";\nexport { DEFAULT_SESSION_MS } from \"./session/manager.js\";\nexport type * from \"./signer.js\";\nexport { AlchemyWebSigner } from \"./signer.js\";\nexport type * from \"./types.js\";\nexport { AlchemySignerStatus } from \"./types.js\";\n"]}
|