@turnkey/sdk-browser 1.16.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/CHANGELOG.md +90 -0
  2. package/dist/__clients__/base-client.d.ts +7 -0
  3. package/dist/__clients__/base-client.d.ts.map +1 -0
  4. package/dist/__clients__/base-client.js +13 -0
  5. package/dist/__clients__/base-client.js.map +1 -0
  6. package/dist/__clients__/base-client.mjs +11 -0
  7. package/dist/__clients__/base-client.mjs.map +1 -0
  8. package/dist/__clients__/browser-clients.d.ts +251 -0
  9. package/dist/__clients__/browser-clients.d.ts.map +1 -0
  10. package/dist/__clients__/browser-clients.js +657 -0
  11. package/dist/__clients__/browser-clients.js.map +1 -0
  12. package/dist/__clients__/browser-clients.mjs +652 -0
  13. package/dist/__clients__/browser-clients.mjs.map +1 -0
  14. package/dist/__generated__/sdk-client-base.d.ts.map +1 -1
  15. package/dist/__generated__/sdk-client-base.js +110 -114
  16. package/dist/__generated__/sdk-client-base.js.map +1 -1
  17. package/dist/__generated__/sdk-client-base.mjs +110 -114
  18. package/dist/__generated__/sdk-client-base.mjs.map +1 -1
  19. package/dist/__generated__/sdk_api_types.d.ts +2 -2
  20. package/dist/__generated__/sdk_api_types.d.ts.map +1 -1
  21. package/dist/__generated__/version.d.ts +1 -1
  22. package/dist/__generated__/version.d.ts.map +1 -1
  23. package/dist/__generated__/version.js +1 -1
  24. package/dist/__generated__/version.mjs +1 -1
  25. package/dist/__inputs__/public_api.types.d.ts +77 -9
  26. package/dist/__inputs__/public_api.types.d.ts.map +1 -1
  27. package/dist/__types__/base.d.ts +93 -0
  28. package/dist/__types__/base.d.ts.map +1 -1
  29. package/dist/__types__/base.js +5 -0
  30. package/dist/__types__/base.js.map +1 -1
  31. package/dist/__types__/base.mjs +6 -1
  32. package/dist/__types__/base.mjs.map +1 -1
  33. package/dist/constants.d.ts +2 -0
  34. package/dist/constants.d.ts.map +1 -0
  35. package/dist/constants.js +6 -0
  36. package/dist/constants.js.map +1 -0
  37. package/dist/constants.mjs +4 -0
  38. package/dist/constants.mjs.map +1 -0
  39. package/dist/index.d.ts +3 -4
  40. package/dist/index.d.ts.map +1 -1
  41. package/dist/index.js +9 -4
  42. package/dist/index.js.map +1 -1
  43. package/dist/index.mjs +3 -2
  44. package/dist/index.mjs.map +1 -1
  45. package/dist/models.d.ts +0 -53
  46. package/dist/models.d.ts.map +1 -1
  47. package/dist/sdk-client.d.ts +13 -186
  48. package/dist/sdk-client.d.ts.map +1 -1
  49. package/dist/sdk-client.js +75 -437
  50. package/dist/sdk-client.js.map +1 -1
  51. package/dist/sdk-client.mjs +69 -431
  52. package/dist/sdk-client.mjs.map +1 -1
  53. package/dist/storage.d.ts +15 -3
  54. package/dist/storage.d.ts.map +1 -1
  55. package/dist/storage.js +19 -0
  56. package/dist/storage.js.map +1 -1
  57. package/dist/storage.mjs +19 -1
  58. package/dist/storage.mjs.map +1 -1
  59. package/package.json +7 -6
@@ -0,0 +1,657 @@
1
+ 'use strict';
2
+
3
+ var http = require('@turnkey/http');
4
+ var baseClient = require('./base-client.js');
5
+ var base = require('../__types__/base.js');
6
+ var utils = require('../utils.js');
7
+ var storage = require('../storage.js');
8
+ var constants = require('../constants.js');
9
+
10
+ class TurnkeyBrowserClient extends baseClient.TurnkeyBaseClient {
11
+ constructor(config, authClient) {
12
+ super(config, authClient);
13
+ this.login = async (config) => {
14
+ const readOnlySessionResult = await this.createReadOnlySession(config || {});
15
+ const session = {
16
+ sessionType: base.SessionType.READ_ONLY,
17
+ userId: readOnlySessionResult.userId,
18
+ organizationId: readOnlySessionResult.organizationId,
19
+ expiry: Number(readOnlySessionResult.sessionExpiry),
20
+ token: readOnlySessionResult.session,
21
+ };
22
+ await storage.storeSession(session, this.authClient);
23
+ return readOnlySessionResult;
24
+ };
25
+ /**
26
+ * Attempts to refresh an existing Session. This method infers the current user's organization ID and target userId.
27
+ * This will use a passkeyStamper for `READ_ONLY` sessions or an `iframeStamper` for `READ_WRITE` sessions.
28
+ *
29
+ * @param RefreshSessionParams
30
+ * @param params.sessionType - The type of session that is being refreshed
31
+ * @param params.targetPublicKey - The public key of the target client
32
+ * @param params.expirationSeconds - Specify how long to extend the session. Defaults to 900 seconds or 15 minutes.
33
+ * @returns {Promise<void>}
34
+ */
35
+ this.refreshSession = async (params) => {
36
+ const { sessionType = base.SessionType.READ_WRITE, targetPublicKey, expirationSeconds = constants.DEFAULT_SESSION_EXPIRATION_IN_SECONDS, } = params;
37
+ try {
38
+ if (sessionType === base.SessionType.READ_ONLY) {
39
+ if (this instanceof TurnkeyPasskeyClient) {
40
+ throw new Error("You must use a passkey client to refresh a read session"); // TODO: support wallet client
41
+ }
42
+ const readOnlySessionResult = await this.createReadOnlySession({});
43
+ const session = {
44
+ sessionType: base.SessionType.READ_ONLY,
45
+ userId: readOnlySessionResult.userId,
46
+ organizationId: readOnlySessionResult.organizationId,
47
+ expiry: Number(readOnlySessionResult.sessionExpiry),
48
+ token: readOnlySessionResult.session,
49
+ };
50
+ await storage.storeSession(session, base.AuthClient.Passkey);
51
+ }
52
+ else if (sessionType === base.SessionType.READ_WRITE) {
53
+ if (!targetPublicKey) {
54
+ throw new Error("You must provide a targetPublicKey to refresh a read-write session.");
55
+ }
56
+ const readWriteSessionResult = await this.createReadWriteSession({
57
+ targetPublicKey,
58
+ expirationSeconds,
59
+ invalidateExisting: true,
60
+ });
61
+ const session = {
62
+ sessionType: base.SessionType.READ_WRITE,
63
+ userId: readWriteSessionResult.userId,
64
+ organizationId: readWriteSessionResult.organizationId,
65
+ expiry: Date.now() + Number(expirationSeconds) * 1000,
66
+ token: readWriteSessionResult.credentialBundle,
67
+ };
68
+ if (this instanceof TurnkeyIframeClient) {
69
+ await this.injectCredentialBundle(session.token);
70
+ }
71
+ else {
72
+ // Throw an error if the client is not an iframe client
73
+ throw new Error("You must use an iframe client to refresh a read-write session");
74
+ }
75
+ await storage.storeSession(session, base.AuthClient.Iframe);
76
+ }
77
+ else {
78
+ throw new Error(`Invalid session type passed: ${sessionType}`);
79
+ }
80
+ }
81
+ catch (error) {
82
+ throw new Error(`Unable to refresh session: ${error}`);
83
+ }
84
+ };
85
+ /**
86
+ * Log in with a bundle. This method uses a bundle sent to the end user email
87
+ * To be used in conjunction with an `iframeStamper`.
88
+ *
89
+ * @param LoginWithBundleParams
90
+ * @param params.bundle - Credential bundle to log in with
91
+ * @param params.expirationSeconds - Expiration time for the session in seconds. Defaults to 900 seconds or 15 minutes.
92
+ * @returns {Promise<void>}
93
+ */
94
+ this.loginWithBundle = async (params) => {
95
+ const { bundle, expirationSeconds = constants.DEFAULT_SESSION_EXPIRATION_IN_SECONDS, } = params;
96
+ if (this instanceof TurnkeyIframeClient) {
97
+ await this.injectCredentialBundle(bundle);
98
+ }
99
+ else {
100
+ // Throw an error if the client is not an iframe client
101
+ throw new Error("You must use an iframe client to log in with a session."); //should we default to a "localStorage" client?
102
+ }
103
+ const whoAmI = await this.getWhoami();
104
+ const session = {
105
+ sessionType: base.SessionType.READ_WRITE,
106
+ userId: whoAmI.userId,
107
+ organizationId: whoAmI.organizationId,
108
+ expiry: Date.now() + Number(expirationSeconds) * 1000,
109
+ token: bundle,
110
+ };
111
+ await storage.storeSession(session, base.AuthClient.Iframe);
112
+ };
113
+ /**
114
+ * Log in with a session object. This method uses a session object from server actions and stores it and the active client in local storage
115
+ * To be used in conjunction with an `iframeStamper`.
116
+ *
117
+ * @param session
118
+ * @returns {Promise<void>}
119
+ */
120
+ this.loginWithSession = async (session) => {
121
+ if (this instanceof TurnkeyIframeClient) {
122
+ await this.injectCredentialBundle(session.token);
123
+ }
124
+ else {
125
+ // Throw an error if the client is not an iframe client
126
+ throw new Error("You must use an iframe client to log in with a session."); //should we default to a "localStorage" client?
127
+ }
128
+ await storage.storeSession(session, base.AuthClient.Iframe);
129
+ };
130
+ /**
131
+ * Log in with a passkey.
132
+ * To be used in conjunction with a `passkeyStamper`
133
+ *
134
+ * @param LoginWithPasskeyParams
135
+ * @param params.sessionType - The type of session to create
136
+ * @param params.iframeClient - The iframe client to use to inject the credential bundle
137
+ * @param params.targetPublicKey - The public key of the target client
138
+ * @param params.expirationSeconds - Expiration time for the session in seconds. Defaults to 900 seconds or 15 minutes.
139
+ * @returns {Promise<void>}
140
+ */
141
+ this.loginWithPasskey = async (params) => {
142
+ try {
143
+ const { sessionType = base.SessionType.READ_WRITE, iframeClient, targetPublicKey, expirationSeconds = constants.DEFAULT_SESSION_EXPIRATION_IN_SECONDS, } = params;
144
+ // Create a read-only session
145
+ if (sessionType === base.SessionType.READ_ONLY) {
146
+ const readOnlySessionResult = await this.createReadOnlySession({});
147
+ const session = {
148
+ sessionType: base.SessionType.READ_ONLY,
149
+ userId: readOnlySessionResult.userId,
150
+ organizationId: readOnlySessionResult.organizationId,
151
+ expiry: Number(readOnlySessionResult.sessionExpiry),
152
+ token: readOnlySessionResult.session,
153
+ };
154
+ await storage.storeSession(session, base.AuthClient.Passkey);
155
+ // Create a read-write session
156
+ }
157
+ else if (sessionType === base.SessionType.READ_WRITE) {
158
+ if (!targetPublicKey) {
159
+ throw new Error("You must provide a targetPublicKey to create a read-write session.");
160
+ }
161
+ const readWriteSessionResult = await this.createReadWriteSession({
162
+ targetPublicKey,
163
+ expirationSeconds,
164
+ });
165
+ const session = {
166
+ sessionType: base.SessionType.READ_WRITE,
167
+ userId: readWriteSessionResult.userId,
168
+ organizationId: readWriteSessionResult.organizationId,
169
+ expiry: Date.now() + Number(expirationSeconds) * 1000,
170
+ token: readWriteSessionResult.credentialBundle,
171
+ };
172
+ if (!iframeClient) {
173
+ throw new Error("You must provide an iframe client to log in with a passkey.");
174
+ }
175
+ await iframeClient.injectCredentialBundle(session.token);
176
+ await storage.storeSession(session, base.AuthClient.Iframe);
177
+ }
178
+ else {
179
+ throw new Error(`Invalid session type passed: ${sessionType}`);
180
+ }
181
+ }
182
+ catch (error) {
183
+ throw new Error(`Unable to log in with the provided passkey: ${error}`);
184
+ }
185
+ };
186
+ /**
187
+ * Log in with a browser wallet.
188
+ *
189
+ * @param LoginWithWalletParams
190
+ * @param params.sessionType - The type of session to create
191
+ * @param params.iframeClient - The iframe client to use to inject the credential bundle
192
+ * @param params.targetPublicKey - The public key of the target iframe
193
+ * @param params.expirationSeconds - The expiration time for the session in seconds
194
+ * @returns {Promise<void>}
195
+ */
196
+ this.loginWithWallet = async (params) => {
197
+ try {
198
+ const { sessionType = base.SessionType.READ_WRITE, iframeClient, targetPublicKey, expirationSeconds = constants.DEFAULT_SESSION_EXPIRATION_IN_SECONDS, } = params;
199
+ // Create a read-only session
200
+ if (sessionType === base.SessionType.READ_ONLY) {
201
+ const readOnlySessionResult = await this.createReadOnlySession({});
202
+ const session = {
203
+ sessionType: base.SessionType.READ_ONLY,
204
+ userId: readOnlySessionResult.userId,
205
+ organizationId: readOnlySessionResult.organizationId,
206
+ expiry: Number(readOnlySessionResult.sessionExpiry),
207
+ token: readOnlySessionResult.session,
208
+ };
209
+ await storage.storeSession(session, base.AuthClient.Wallet);
210
+ // Create a read-write session
211
+ }
212
+ else if (sessionType === base.SessionType.READ_WRITE) {
213
+ if (!targetPublicKey) {
214
+ throw new Error("You must provide a targetPublicKey to create a read-write session.");
215
+ }
216
+ const readWriteSessionResult = await this.createReadWriteSession({
217
+ targetPublicKey,
218
+ expirationSeconds,
219
+ });
220
+ const session = {
221
+ sessionType: base.SessionType.READ_WRITE,
222
+ userId: readWriteSessionResult.userId,
223
+ organizationId: readWriteSessionResult.organizationId,
224
+ expiry: Date.now() + Number(expirationSeconds) * 1000,
225
+ token: readWriteSessionResult.credentialBundle,
226
+ };
227
+ if (!iframeClient) {
228
+ throw new Error("You must provide an iframe client to log in with a wallet.");
229
+ }
230
+ await iframeClient.injectCredentialBundle(session.token);
231
+ await storage.storeSession(session, base.AuthClient.Iframe);
232
+ }
233
+ else {
234
+ throw new Error(`Invalid session type passed: ${sessionType}`);
235
+ }
236
+ }
237
+ catch (error) {
238
+ throw new Error(`Unable to log in with the provided wallet: ${error}`);
239
+ }
240
+ };
241
+ /**
242
+ * Creates a read-write session. This method infers the current user's organization ID and target userId.
243
+ * To be used in conjunction with an `iframeStamper`: the resulting session's credential bundle can be
244
+ * injected into an iframeStamper to create a session that enables both read and write requests.
245
+ *
246
+ * @param targetEmbeddedKey
247
+ * @param expirationSeconds
248
+ * @param userId
249
+ * @returns {Promise<SdkApiTypes.TCreateReadWriteSessionResponse>}
250
+ */
251
+ this.loginWithReadWriteSession = async (targetEmbeddedKey, expirationSeconds = constants.DEFAULT_SESSION_EXPIRATION_IN_SECONDS, userId) => {
252
+ try {
253
+ const readWriteSessionResult = await this.createReadWriteSession({
254
+ targetPublicKey: targetEmbeddedKey,
255
+ expirationSeconds,
256
+ userId: userId,
257
+ });
258
+ // Ensure session and sessionExpiry are included in the object
259
+ const readWriteSessionResultWithSession = {
260
+ ...readWriteSessionResult,
261
+ credentialBundle: readWriteSessionResult.credentialBundle,
262
+ sessionExpiry: Date.now() + Number(expirationSeconds) * 1000,
263
+ };
264
+ // store auth bundle in local storage
265
+ await storage.saveSession(readWriteSessionResultWithSession, this.authClient);
266
+ return readWriteSessionResultWithSession;
267
+ }
268
+ catch (error) {
269
+ throw new Error(`Unable to log in with the provided read-write session: ${error}`);
270
+ }
271
+ };
272
+ /**
273
+ * Logs in with an existing auth bundle. this bundle enables both read and write requests.
274
+ *
275
+ * @param credentialBundle
276
+ * @param expirationSeconds
277
+ * @returns {Promise<boolean>}
278
+ */
279
+ this.loginWithAuthBundle = async (credentialBundle, expirationSeconds = constants.DEFAULT_SESSION_EXPIRATION_IN_SECONDS) => {
280
+ try {
281
+ const whoAmIResult = await this.getWhoami();
282
+ const readWriteSessionResultWithSession = {
283
+ ...whoAmIResult,
284
+ credentialBundle: credentialBundle,
285
+ sessionExpiry: Date.now() + Number(expirationSeconds) * 1000,
286
+ };
287
+ await storage.saveSession(readWriteSessionResultWithSession, this.authClient);
288
+ return true;
289
+ }
290
+ catch (error) {
291
+ throw new Error(`Unable to log in with the provided auth bundle: ${error}`);
292
+ }
293
+ };
294
+ /**
295
+ * Removes authentication factors from an end user.
296
+ *
297
+ * This function allows selectively removing:
298
+ * - Phone number
299
+ * - Email
300
+ * - Authenticators (by ID)
301
+ * - OAuth providers (by ID)
302
+ * - API keys (by ID)
303
+ *
304
+ * All removal operations are executed in parallel if multiple
305
+ * parameters are provided.
306
+ *
307
+ * @param params - A structured object containing all the removal parameters
308
+ * @param params.userId - Unique identifier of the user
309
+ * @param params.phoneNumber - true to remove the phone number
310
+ * @param params.email - true to remove the email
311
+ * @param params.authenticatorIds - Array of authenticator IDs to remove
312
+ * @param params.oauthProviderIds - Array of OAuth provider IDs to remove
313
+ * @param params.apiKeyIds - Array of API key IDs to remove
314
+ * @returns A promise that resolves to an array of results from each removal operation
315
+ */
316
+ this.deleteUserAuth = async (params) => {
317
+ try {
318
+ const { userId, phoneNumber, email, authenticatorIds, oauthProviderIds, apiKeyIds, } = params;
319
+ const promises = [];
320
+ if (phoneNumber) {
321
+ promises.push(this.updateUser({ userId, userPhoneNumber: "", userTagIds: [] }));
322
+ }
323
+ if (email) {
324
+ promises.push(this.updateUser({ userId, userEmail: "", userTagIds: [] }));
325
+ }
326
+ if (authenticatorIds && authenticatorIds.length > 0) {
327
+ promises.push(this.deleteAuthenticators({ userId, authenticatorIds }));
328
+ }
329
+ if (oauthProviderIds && oauthProviderIds.length > 0) {
330
+ promises.push(this.deleteOauthProviders({ userId, providerIds: oauthProviderIds }));
331
+ }
332
+ if (apiKeyIds && apiKeyIds.length > 0) {
333
+ promises.push(this.deleteApiKeys({ userId, apiKeyIds }));
334
+ }
335
+ // Execute all removal operations in parallel
336
+ return await Promise.all(promises);
337
+ }
338
+ catch (error) {
339
+ // Surface error
340
+ throw error;
341
+ }
342
+ };
343
+ /**
344
+ * Adds or updates authentication factors for an end user.
345
+ *
346
+ * This function allows selectively adding:
347
+ * - Phone number
348
+ * - Email
349
+ * - Authenticators
350
+ * - OAuth providers
351
+ * - API keys
352
+ *
353
+ * All additions/updates are executed in parallel if multiple
354
+ * parameters are provided.
355
+ *
356
+ * @param params - A structured object containing all the addition/update parameters
357
+ * @param params.userId - Unique identifier of the user
358
+ * @param params.phoneNumber - New phone number for the user
359
+ * @param params.email - New email address for the user
360
+ * @param params.authenticators - Array of authenticator objects to create
361
+ * @param params.oauthProviders - Array of OAuth provider objects to create
362
+ * @param params.apiKeys - Array of API key objects to create
363
+ * @returns A promise that resolves to an array of results from each addition or update
364
+ */
365
+ this.addUserAuth = async (params) => {
366
+ try {
367
+ const { userId, phoneNumber, email, authenticators, oauthProviders, apiKeys, } = params;
368
+ const promises = [];
369
+ if (phoneNumber) {
370
+ promises.push(this.updateUser({
371
+ userId,
372
+ userPhoneNumber: phoneNumber,
373
+ userTagIds: [],
374
+ }));
375
+ }
376
+ if (email) {
377
+ promises.push(this.updateUser({ userId, userEmail: email, userTagIds: [] }));
378
+ }
379
+ if (authenticators && authenticators.length > 0) {
380
+ promises.push(this.createAuthenticators({ userId, authenticators }));
381
+ }
382
+ if (oauthProviders && oauthProviders.length > 0) {
383
+ promises.push(this.createOauthProviders({ userId, oauthProviders }));
384
+ }
385
+ if (apiKeys && apiKeys.length > 0) {
386
+ promises.push(this.createApiKeys({ userId, apiKeys }));
387
+ }
388
+ // Execute all additions/updates operations in parallel
389
+ return await Promise.all(promises);
390
+ }
391
+ catch (error) {
392
+ // Surface error
393
+ throw error;
394
+ }
395
+ };
396
+ }
397
+ /**
398
+ * Comprehensive authentication update for an end user.
399
+ * Combines add/update and delete operations into a single call.
400
+ *
401
+ * The behavior is driven by whether values are set to:
402
+ * - A string/array (to create or update)
403
+ * - `null` or an array of IDs (to remove)
404
+ *
405
+ * All operations are executed in parallel where applicable.
406
+ *
407
+ * @param params - A structured object containing all the update parameters
408
+ * @param params.userId - Unique identifier of the user
409
+ * @param params.phoneNumber - String to set (new phone) or `null` to remove
410
+ * @param params.email - String to set (new email) or `null` to remove
411
+ * @param params.authenticators - Object describing authenticators to add or remove
412
+ * @param params.oauthProviders - Object describing OAuth providers to add or remove
413
+ * @param params.apiKeys - Object describing API keys to add or remove
414
+ *
415
+ * @returns A promise that resolves to a boolean indicating overall success
416
+ */
417
+ async updateUserAuth(params) {
418
+ try {
419
+ const { userId, phoneNumber, email, authenticators, oauthProviders, apiKeys, } = params;
420
+ const promises = [];
421
+ // Handle phone/email in a single updateUser call if both are changing,
422
+ // or separate calls if only one is changing.
423
+ const userUpdates = {};
424
+ if (phoneNumber !== undefined) {
425
+ userUpdates.userPhoneNumber = phoneNumber === null ? "" : phoneNumber;
426
+ }
427
+ if (email !== undefined) {
428
+ userUpdates.userEmail = email === null ? "" : email;
429
+ }
430
+ if (Object.keys(userUpdates).length > 0) {
431
+ promises.push(this.updateUser({ userId, ...userUpdates, userTagIds: [] }));
432
+ }
433
+ // Handle authenticators
434
+ if (authenticators) {
435
+ if (authenticators.add?.length) {
436
+ promises.push(this.createAuthenticators({
437
+ userId,
438
+ authenticators: authenticators.add,
439
+ }));
440
+ }
441
+ if (authenticators.deleteIds?.length) {
442
+ promises.push(this.deleteAuthenticators({
443
+ userId,
444
+ authenticatorIds: authenticators.deleteIds,
445
+ }));
446
+ }
447
+ }
448
+ // Handle OAuth providers
449
+ if (oauthProviders) {
450
+ if (oauthProviders.add?.length) {
451
+ promises.push(this.createOauthProviders({
452
+ userId,
453
+ oauthProviders: oauthProviders.add,
454
+ }));
455
+ }
456
+ if (oauthProviders.deleteIds?.length) {
457
+ promises.push(this.deleteOauthProviders({
458
+ userId,
459
+ providerIds: oauthProviders.deleteIds,
460
+ }));
461
+ }
462
+ }
463
+ // Handle API keys
464
+ if (apiKeys) {
465
+ if (apiKeys.add?.length) {
466
+ promises.push(this.createApiKeys({
467
+ userId,
468
+ apiKeys: apiKeys.add,
469
+ }));
470
+ }
471
+ if (apiKeys.deleteIds?.length) {
472
+ promises.push(this.deleteApiKeys({
473
+ userId,
474
+ apiKeyIds: apiKeys.deleteIds,
475
+ }));
476
+ }
477
+ }
478
+ // Execute all requested operations in parallel
479
+ await Promise.all(promises);
480
+ return true;
481
+ }
482
+ catch (error) {
483
+ // Surface error
484
+ throw error;
485
+ }
486
+ }
487
+ }
488
+ class TurnkeyPasskeyClient extends TurnkeyBrowserClient {
489
+ constructor(config) {
490
+ super(config, base.AuthClient.Passkey);
491
+ /**
492
+ * Create a passkey for an end-user, taking care of various lower-level details.
493
+ *
494
+ * @returns {Promise<Passkey>}
495
+ */
496
+ this.createUserPasskey = async (config = {}) => {
497
+ const challenge = utils.generateRandomBuffer();
498
+ const encodedChallenge = utils.base64UrlEncode(challenge);
499
+ const authenticatorUserId = utils.generateRandomBuffer();
500
+ // WebAuthn credential options options can be found here:
501
+ // https://www.w3.org/TR/webauthn-2/#sctn-sample-registration
502
+ //
503
+ // All pubkey algorithms can be found here: https://www.iana.org/assignments/cose/cose.xhtml#algorithms
504
+ // Turnkey only supports ES256 (-7) and RS256 (-257)
505
+ //
506
+ // The pubkey type only supports one value, "public-key"
507
+ // See https://www.w3.org/TR/webauthn-2/#enumdef-publickeycredentialtype for more details
508
+ // TODO: consider un-nesting these config params
509
+ const webauthnConfig = {
510
+ publicKey: {
511
+ rp: {
512
+ id: config.publicKey?.rp?.id ?? this.rpId,
513
+ name: config.publicKey?.rp?.name ?? "",
514
+ },
515
+ challenge: config.publicKey?.challenge ?? challenge,
516
+ pubKeyCredParams: config.publicKey?.pubKeyCredParams ?? [
517
+ {
518
+ type: "public-key",
519
+ alg: -7,
520
+ },
521
+ {
522
+ type: "public-key",
523
+ alg: -257,
524
+ },
525
+ ],
526
+ user: {
527
+ id: config.publicKey?.user?.id ?? authenticatorUserId,
528
+ name: config.publicKey?.user?.name ?? "Default User",
529
+ displayName: config.publicKey?.user?.displayName ?? "Default User",
530
+ },
531
+ authenticatorSelection: {
532
+ authenticatorAttachment: config.publicKey?.authenticatorSelection?.authenticatorAttachment ??
533
+ undefined,
534
+ requireResidentKey: config.publicKey?.authenticatorSelection?.requireResidentKey ??
535
+ true,
536
+ residentKey: config.publicKey?.authenticatorSelection?.residentKey ?? "required",
537
+ userVerification: config.publicKey?.authenticatorSelection?.userVerification ??
538
+ "preferred",
539
+ },
540
+ },
541
+ };
542
+ const attestation = await http.getWebAuthnAttestation(webauthnConfig);
543
+ return {
544
+ encodedChallenge: config.publicKey?.challenge
545
+ ? utils.base64UrlEncode(config.publicKey?.challenge)
546
+ : encodedChallenge,
547
+ attestation,
548
+ };
549
+ };
550
+ /**
551
+ * Uses passkey authentication to create a read-write session, via an embedded API key,
552
+ * and stores + returns the resulting auth bundle that contains the encrypted API key.
553
+ * This auth bundle (also referred to as a credential bundle) can be injected into an `iframeStamper`,
554
+ * resulting in a touch-free authenticator. Unlike `loginWithReadWriteSession`, this method
555
+ * assumes the end-user's organization ID (i.e. the sub-organization ID) is already known.
556
+ *
557
+ * @param userId
558
+ * @param targetEmbeddedKey
559
+ * @param expirationSeconds
560
+ * @param curveType
561
+ * @returns {Promise<ReadWriteSession>}
562
+ */
563
+ this.createPasskeySession = async (userId, targetEmbeddedKey, expirationSeconds = constants.DEFAULT_SESSION_EXPIRATION_IN_SECONDS, organizationId) => {
564
+ try {
565
+ const session = await storage.getStorageValue(storage.StorageKeys.Session);
566
+ organizationId = organizationId ?? session?.organizationId;
567
+ userId = userId ?? session?.userId;
568
+ if (!organizationId) {
569
+ throw new Error("Error creating passkey session: Organization ID is required");
570
+ }
571
+ if (!userId) {
572
+ throw new Error("Error creating passkey session: User ID is required");
573
+ }
574
+ const { authBundle: credentialBundle, publicKey } = await utils.createEmbeddedAPIKey(targetEmbeddedKey);
575
+ // add API key to Turnkey User
576
+ await this.createApiKeys({
577
+ organizationId,
578
+ userId,
579
+ apiKeys: [
580
+ {
581
+ apiKeyName: `Session Key ${String(Date.now())}`,
582
+ publicKey,
583
+ expirationSeconds,
584
+ curveType: "API_KEY_CURVE_P256",
585
+ },
586
+ ],
587
+ });
588
+ const whoAmI = await this.getWhoami();
589
+ const expiry = Date.now() + Number(expirationSeconds) * 1000;
590
+ await storage.saveSession({
591
+ organizationId,
592
+ organizationName: whoAmI?.organizationName ?? "",
593
+ userId,
594
+ username: whoAmI?.username ?? "",
595
+ credentialBundle,
596
+ sessionExpiry: expiry,
597
+ }, this.authClient);
598
+ return {
599
+ credentialBundle,
600
+ expiry,
601
+ };
602
+ }
603
+ catch (error) {
604
+ throw new Error("Unable to create passkey session.");
605
+ }
606
+ };
607
+ this.rpId = this.stamper.rpId;
608
+ }
609
+ }
610
+ /**
611
+ * TurnkeyIframeClient is a client that uses an iframe to interact with the Turnkey API.
612
+ * It is used to create read-write sessions, and to inject credential bundles into the iframe.
613
+ * It is also used to extract encrypted credential bundles from the iframe.
614
+ * @extends TurnkeyBrowserClient
615
+ */
616
+ class TurnkeyIframeClient extends TurnkeyBrowserClient {
617
+ constructor(config) {
618
+ super(config, base.AuthClient.Iframe);
619
+ this.injectCredentialBundle = async (credentialBundle) => {
620
+ return await this.stamper.injectCredentialBundle(credentialBundle);
621
+ };
622
+ this.injectWalletExportBundle = async (credentialBundle, organizationId) => {
623
+ return await this.stamper.injectWalletExportBundle(credentialBundle, organizationId);
624
+ };
625
+ this.injectKeyExportBundle = async (credentialBundle, organizationId, keyFormat) => {
626
+ return await this.stamper.injectKeyExportBundle(credentialBundle, organizationId, keyFormat);
627
+ };
628
+ this.injectImportBundle = async (bundle, organizationId, userId) => {
629
+ return await this.stamper.injectImportBundle(bundle, organizationId, userId);
630
+ };
631
+ this.extractWalletEncryptedBundle = async () => {
632
+ return await this.stamper.extractWalletEncryptedBundle();
633
+ };
634
+ this.extractKeyEncryptedBundle = async () => {
635
+ return await this.stamper.extractKeyEncryptedBundle();
636
+ };
637
+ this.iframePublicKey = this.stamper.iframePublicKey;
638
+ }
639
+ }
640
+ class TurnkeyWalletClient extends TurnkeyBrowserClient {
641
+ constructor(config) {
642
+ super(config, base.AuthClient.Wallet);
643
+ this.wallet = config.wallet;
644
+ }
645
+ async getPublicKey() {
646
+ return this.wallet.getPublicKey();
647
+ }
648
+ getWalletInterface() {
649
+ return this.wallet;
650
+ }
651
+ }
652
+
653
+ exports.TurnkeyBrowserClient = TurnkeyBrowserClient;
654
+ exports.TurnkeyIframeClient = TurnkeyIframeClient;
655
+ exports.TurnkeyPasskeyClient = TurnkeyPasskeyClient;
656
+ exports.TurnkeyWalletClient = TurnkeyWalletClient;
657
+ //# sourceMappingURL=browser-clients.js.map