@turnkey/core 1.0.0 → 1.1.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 (152) hide show
  1. package/dist/__clients__/core.d.ts +161 -334
  2. package/dist/__clients__/core.d.ts.map +1 -1
  3. package/dist/__clients__/core.js +416 -275
  4. package/dist/__clients__/core.js.map +1 -1
  5. package/dist/__clients__/core.mjs +366 -225
  6. package/dist/__clients__/core.mjs.map +1 -1
  7. package/dist/__generated__/sdk-client-base.d.ts +4 -2
  8. package/dist/__generated__/sdk-client-base.d.ts.map +1 -1
  9. package/dist/__generated__/sdk-client-base.js +37 -6
  10. package/dist/__generated__/sdk-client-base.js.map +1 -1
  11. package/dist/__generated__/sdk-client-base.mjs +32 -1
  12. package/dist/__generated__/sdk-client-base.mjs.map +1 -1
  13. package/dist/__generated__/version.d.ts +1 -1
  14. package/dist/__generated__/version.js +1 -1
  15. package/dist/__generated__/version.mjs +1 -1
  16. package/dist/__inputs__/public_api.types.d.ts +49 -0
  17. package/dist/__inputs__/public_api.types.d.ts.map +1 -1
  18. package/dist/__polyfills__/window.js.map +1 -1
  19. package/dist/__polyfills__/window.mjs.map +1 -1
  20. package/dist/__stampers__/api/base.d.ts +1 -1
  21. package/dist/__stampers__/api/base.d.ts.map +1 -1
  22. package/dist/__stampers__/api/base.js.map +1 -1
  23. package/dist/__stampers__/api/base.mjs.map +1 -1
  24. package/dist/__stampers__/api/mobile/stamper.d.ts +1 -1
  25. package/dist/__stampers__/api/mobile/stamper.d.ts.map +1 -1
  26. package/dist/__stampers__/api/mobile/stamper.js.map +1 -1
  27. package/dist/__stampers__/api/mobile/stamper.mjs.map +1 -1
  28. package/dist/__stampers__/api/web/stamper.d.ts +1 -1
  29. package/dist/__stampers__/api/web/stamper.d.ts.map +1 -1
  30. package/dist/__stampers__/api/web/stamper.js.map +1 -1
  31. package/dist/__stampers__/api/web/stamper.mjs.map +1 -1
  32. package/dist/__stampers__/passkey/base.d.ts +1 -1
  33. package/dist/__stampers__/passkey/base.d.ts.map +1 -1
  34. package/dist/__stampers__/passkey/base.js.map +1 -1
  35. package/dist/__stampers__/passkey/base.mjs.map +1 -1
  36. package/dist/__storage__/base.d.ts +1 -1
  37. package/dist/__storage__/base.d.ts.map +1 -1
  38. package/dist/__storage__/base.js.map +1 -1
  39. package/dist/__storage__/base.mjs.map +1 -1
  40. package/dist/__storage__/mobile/storage.d.ts +1 -1
  41. package/dist/__storage__/mobile/storage.d.ts.map +1 -1
  42. package/dist/__storage__/mobile/storage.js +4 -3
  43. package/dist/__storage__/mobile/storage.js.map +1 -1
  44. package/dist/__storage__/mobile/storage.mjs +2 -1
  45. package/dist/__storage__/mobile/storage.mjs.map +1 -1
  46. package/dist/__storage__/web/storage.d.ts +1 -1
  47. package/dist/__storage__/web/storage.d.ts.map +1 -1
  48. package/dist/__storage__/web/storage.js +4 -3
  49. package/dist/__storage__/web/storage.js.map +1 -1
  50. package/dist/__storage__/web/storage.mjs +2 -1
  51. package/dist/__storage__/web/storage.mjs.map +1 -1
  52. package/dist/__typedoc-entry__/index.d.ts +3 -0
  53. package/dist/__typedoc-entry__/index.d.ts.map +1 -0
  54. package/dist/__types__/auth.d.ts +150 -0
  55. package/dist/__types__/auth.d.ts.map +1 -0
  56. package/dist/__types__/auth.js +43 -0
  57. package/dist/__types__/auth.js.map +1 -0
  58. package/dist/__types__/auth.mjs +40 -0
  59. package/dist/__types__/auth.mjs.map +1 -0
  60. package/dist/__types__/config.d.ts +140 -0
  61. package/dist/__types__/config.d.ts.map +1 -0
  62. package/dist/__types__/error.d.ts +13 -0
  63. package/dist/__types__/error.d.ts.map +1 -0
  64. package/dist/__types__/error.js +18 -0
  65. package/dist/__types__/error.js.map +1 -0
  66. package/dist/__types__/error.mjs +16 -0
  67. package/dist/__types__/error.mjs.map +1 -0
  68. package/dist/__types__/export.d.ts +10 -0
  69. package/dist/__types__/export.d.ts.map +1 -0
  70. package/dist/__types__/external-wallets.d.ts +202 -0
  71. package/dist/__types__/external-wallets.d.ts.map +1 -0
  72. package/dist/__types__/external-wallets.js +35 -0
  73. package/dist/__types__/external-wallets.js.map +1 -0
  74. package/dist/__types__/external-wallets.mjs +35 -0
  75. package/dist/__types__/external-wallets.mjs.map +1 -0
  76. package/dist/__types__/index.d.ts +7 -0
  77. package/dist/__types__/index.d.ts.map +1 -0
  78. package/dist/__types__/method-types.d.ts +314 -0
  79. package/dist/__types__/method-types.d.ts.map +1 -0
  80. package/dist/__wallet__/base.d.ts +1 -1
  81. package/dist/__wallet__/base.d.ts.map +1 -1
  82. package/dist/__wallet__/base.js.map +1 -1
  83. package/dist/__wallet__/base.mjs.map +1 -1
  84. package/dist/__wallet__/connector.d.ts +3 -3
  85. package/dist/__wallet__/connector.d.ts.map +1 -1
  86. package/dist/__wallet__/connector.js +5 -4
  87. package/dist/__wallet__/connector.js.map +1 -1
  88. package/dist/__wallet__/connector.mjs +4 -3
  89. package/dist/__wallet__/connector.mjs.map +1 -1
  90. package/dist/__wallet__/mobile/manager.d.ts +1 -1
  91. package/dist/__wallet__/mobile/manager.d.ts.map +1 -1
  92. package/dist/__wallet__/mobile/manager.js +5 -4
  93. package/dist/__wallet__/mobile/manager.js.map +1 -1
  94. package/dist/__wallet__/mobile/manager.mjs +2 -1
  95. package/dist/__wallet__/mobile/manager.mjs.map +1 -1
  96. package/dist/__wallet__/stamper.d.ts +1 -1
  97. package/dist/__wallet__/stamper.d.ts.map +1 -1
  98. package/dist/__wallet__/stamper.js +9 -8
  99. package/dist/__wallet__/stamper.js.map +1 -1
  100. package/dist/__wallet__/stamper.mjs +2 -1
  101. package/dist/__wallet__/stamper.mjs.map +1 -1
  102. package/dist/__wallet__/wallet-connect/base.d.ts +4 -2
  103. package/dist/__wallet__/wallet-connect/base.d.ts.map +1 -1
  104. package/dist/__wallet__/wallet-connect/base.js +69 -26
  105. package/dist/__wallet__/wallet-connect/base.js.map +1 -1
  106. package/dist/__wallet__/wallet-connect/base.mjs +54 -11
  107. package/dist/__wallet__/wallet-connect/base.mjs.map +1 -1
  108. package/dist/__wallet__/wallet-connect/client.d.ts +30 -9
  109. package/dist/__wallet__/wallet-connect/client.d.ts.map +1 -1
  110. package/dist/__wallet__/wallet-connect/client.js +73 -11
  111. package/dist/__wallet__/wallet-connect/client.js.map +1 -1
  112. package/dist/__wallet__/wallet-connect/client.mjs +73 -11
  113. package/dist/__wallet__/wallet-connect/client.mjs.map +1 -1
  114. package/dist/__wallet__/web/manager.d.ts +1 -1
  115. package/dist/__wallet__/web/manager.d.ts.map +1 -1
  116. package/dist/__wallet__/web/manager.js +11 -10
  117. package/dist/__wallet__/web/manager.js.map +1 -1
  118. package/dist/__wallet__/web/manager.mjs +2 -1
  119. package/dist/__wallet__/web/manager.mjs.map +1 -1
  120. package/dist/__wallet__/web/native/ethereum.d.ts +3 -3
  121. package/dist/__wallet__/web/native/ethereum.d.ts.map +1 -1
  122. package/dist/__wallet__/web/native/ethereum.js +11 -10
  123. package/dist/__wallet__/web/native/ethereum.js.map +1 -1
  124. package/dist/__wallet__/web/native/ethereum.mjs +4 -3
  125. package/dist/__wallet__/web/native/ethereum.mjs.map +1 -1
  126. package/dist/__wallet__/web/native/solana.d.ts +3 -3
  127. package/dist/__wallet__/web/native/solana.d.ts.map +1 -1
  128. package/dist/__wallet__/web/native/solana.js +12 -11
  129. package/dist/__wallet__/web/native/solana.js.map +1 -1
  130. package/dist/__wallet__/web/native/solana.mjs +7 -6
  131. package/dist/__wallet__/web/native/solana.mjs.map +1 -1
  132. package/dist/index.d.ts +2 -1
  133. package/dist/index.d.ts.map +1 -1
  134. package/dist/index.js +29 -21
  135. package/dist/index.js.map +1 -1
  136. package/dist/index.mjs +4 -2
  137. package/dist/index.mjs.map +1 -1
  138. package/dist/turnkey-helpers.js.map +1 -1
  139. package/dist/turnkey-helpers.mjs.map +1 -1
  140. package/dist/utils.d.ts +4 -18
  141. package/dist/utils.d.ts.map +1 -1
  142. package/dist/utils.js +96 -32
  143. package/dist/utils.js.map +1 -1
  144. package/dist/utils.mjs +75 -13
  145. package/dist/utils.mjs.map +1 -1
  146. package/package.json +6 -6
  147. package/dist/__types__/base.d.ts +0 -527
  148. package/dist/__types__/base.d.ts.map +0 -1
  149. package/dist/__types__/base.js +0 -89
  150. package/dist/__types__/base.js.map +0 -1
  151. package/dist/__types__/base.mjs +0 -85
  152. package/dist/__types__/base.mjs.map +0 -1
@@ -2,14 +2,15 @@
2
2
 
3
3
  var sdkClientBase = require('../__generated__/sdk-client-base.js');
4
4
  var sdkTypes = require('@turnkey/sdk-types');
5
- var base = require('../__types__/base.js');
5
+ var auth = require('../__types__/auth.js');
6
+ var externalWallets = require('../__types__/external-wallets.js');
6
7
  var utils = require('../utils.js');
7
- var base$1 = require('../__storage__/base.js');
8
- var base$2 = require('../__stampers__/api/base.js');
9
- var base$3 = require('../__stampers__/passkey/base.js');
8
+ var base = require('../__storage__/base.js');
9
+ var base$1 = require('../__stampers__/api/base.js');
10
+ var base$2 = require('../__stampers__/passkey/base.js');
10
11
  var turnkeyHelpers = require('../turnkey-helpers.js');
11
12
  var jwtDecode = require('jwt-decode');
12
- var base$4 = require('../__wallet__/base.js');
13
+ var base$3 = require('../__wallet__/base.js');
13
14
  var ethers = require('ethers');
14
15
 
15
16
  class TurnkeyClient {
@@ -24,29 +25,30 @@ class TurnkeyClient {
24
25
  * - The resulting attestation and challenge can be used to register the passkey with Turnkey.
25
26
  *
26
27
  * @param params.name - display name for the passkey (defaults to a generated name based on the current timestamp).
27
- * @param params.stampWith - parameter to stamp the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
28
28
  * @param params.challenge - challenge string to use for passkey registration. If not provided, a new challenge will be generated.
29
- * @returns A promise that resolves to an object containing:
30
- * - attestation: attestation object returned from the passkey creation process.
31
- * - encodedChallenge: encoded challenge string used for passkey registration.
29
+ * @returns A promise that resolves to {@link CreatePasskeyResult}
32
30
  * @throws {TurnkeyError} If there is an error during passkey creation, or if the platform is unsupported.
33
31
  */
34
32
  this.createPasskey = async (params) => {
33
+ const { name: nameFromParams, challenge } = params || {};
35
34
  return utils.withTurnkeyErrorHandling(async () => {
36
- const name = utils.isValidPasskeyName(params?.name || `passkey-${Date.now()}`);
35
+ if (!this.passkeyStamper) {
36
+ throw new sdkTypes.TurnkeyError("Passkey stamper is not initialized", sdkTypes.TurnkeyErrorCodes.INTERNAL_ERROR);
37
+ }
38
+ const name = utils.isValidPasskeyName(nameFromParams || `passkey-${Date.now()}`);
37
39
  let passkey;
38
40
  if (utils.isWeb()) {
39
- const res = await this.passkeyStamper?.createWebPasskey({
41
+ const res = await this.passkeyStamper.createWebPasskey({
40
42
  publicKey: {
41
43
  user: {
42
44
  name,
43
45
  displayName: name,
44
46
  },
45
- ...(params?.challenge && { challenge: params.challenge }),
47
+ ...(challenge && { challenge }),
46
48
  },
47
49
  });
48
50
  if (!res) {
49
- throw new sdkTypes.TurnkeyError("Failed to create React Native passkey", sdkTypes.TurnkeyErrorCodes.INTERNAL_ERROR);
51
+ throw new sdkTypes.TurnkeyError("Failed to create Web passkey", sdkTypes.TurnkeyErrorCodes.INTERNAL_ERROR);
50
52
  }
51
53
  passkey = {
52
54
  encodedChallenge: res?.encodedChallenge,
@@ -54,7 +56,7 @@ class TurnkeyClient {
54
56
  };
55
57
  }
56
58
  else if (utils.isReactNative()) {
57
- const res = await this.passkeyStamper?.createReactNativePasskey({
59
+ const res = await this.passkeyStamper.createReactNativePasskey({
58
60
  name,
59
61
  displayName: name,
60
62
  });
@@ -127,6 +129,7 @@ class TurnkeyClient {
127
129
  * @param params.publicKey - public key to use for authentication. If not provided, a new key pair will be generated.
128
130
  * @param params.sessionKey - session key to use for session creation (defaults to the default session key).
129
131
  * @param params.expirationSeconds - session expiration time in seconds (defaults to the configured default).
132
+ * @param params.organizationId - organization ID to target (defaults to the session's organization ID or the parent organization ID).
130
133
  * @returns A promise that resolves to a {@link PasskeyAuthResult}, which includes:
131
134
  * - `sessionToken`: the signed JWT session token.
132
135
  * - `credentialId`: an empty string.
@@ -137,16 +140,16 @@ class TurnkeyClient {
137
140
  return await utils.withTurnkeyErrorHandling(async () => {
138
141
  generatedPublicKey =
139
142
  params?.publicKey || (await this.apiKeyStamper?.createKeyPair());
140
- const sessionKey = params?.sessionKey || base.SessionKey.DefaultSessionkey;
141
- const expirationSeconds = params?.expirationSeconds || base.DEFAULT_SESSION_EXPIRATION_IN_SECONDS;
143
+ const sessionKey = params?.sessionKey || auth.SessionKey.DefaultSessionkey;
144
+ const expirationSeconds = params?.expirationSeconds || auth.DEFAULT_SESSION_EXPIRATION_IN_SECONDS;
142
145
  if (!generatedPublicKey) {
143
146
  throw new sdkTypes.TurnkeyError("A publickey could not be found or generated.", sdkTypes.TurnkeyErrorCodes.INTERNAL_ERROR);
144
147
  }
145
148
  const sessionResponse = await this.httpClient.stampLogin({
146
149
  publicKey: generatedPublicKey,
147
- organizationId: this.config.organizationId,
150
+ organizationId: params?.organizationId ?? this.config.organizationId,
148
151
  expirationSeconds,
149
- }, base.StamperType.Passkey);
152
+ }, auth.StamperType.Passkey);
150
153
  await this.storeSession({
151
154
  sessionToken: sessionResponse.session,
152
155
  sessionKey,
@@ -195,13 +198,14 @@ class TurnkeyClient {
195
198
  * @param params.sessionKey - session key to use for storing the session (defaults to the default session key).
196
199
  * @param params.expirationSeconds - session expiration time in seconds (defaults to the configured default).
197
200
  * @param params.challenge - challenge string to use for passkey registration. If not provided, a new challenge will be generated.
201
+ * @param params.organizationId - organization ID to target (defaults to the session's organization ID or the parent organization ID).
198
202
  * @returns A promise that resolves to a {@link PasskeyAuthResult}, which includes:
199
203
  * - `sessionToken`: the signed JWT session token.
200
204
  * - `credentialId`: the credential ID associated with the passkey created.
201
205
  * @throws {TurnkeyError} If there is an error during passkey creation, sub-organization creation, or session storage.
202
206
  */
203
207
  this.signUpWithPasskey = async (params) => {
204
- const { createSubOrgParams, passkeyDisplayName, sessionKey = base.SessionKey.DefaultSessionkey, expirationSeconds = base.DEFAULT_SESSION_EXPIRATION_IN_SECONDS, } = params || {};
208
+ const { createSubOrgParams, passkeyDisplayName, sessionKey = auth.SessionKey.DefaultSessionkey, expirationSeconds = auth.DEFAULT_SESSION_EXPIRATION_IN_SECONDS, organizationId, } = params || {};
205
209
  let generatedPublicKey = undefined;
206
210
  return utils.withTurnkeyErrorHandling(async () => {
207
211
  generatedPublicKey = await this.apiKeyStamper?.createKeyPair();
@@ -244,7 +248,7 @@ class TurnkeyClient {
244
248
  this.apiKeyStamper?.setTemporaryPublicKey(generatedPublicKey);
245
249
  const sessionResponse = await this.httpClient.stampLogin({
246
250
  publicKey: newGeneratedKeyPair,
247
- organizationId: this.config.organizationId,
251
+ organizationId: organizationId ?? this.config.organizationId,
248
252
  expirationSeconds,
249
253
  });
250
254
  await this.apiKeyStamper?.deleteKeyPair(generatedPublicKey);
@@ -301,7 +305,7 @@ class TurnkeyClient {
301
305
  * - Requires the wallet manager and its connector to be initialized.
302
306
  *
303
307
  * @param walletProvider - wallet provider to connect.
304
- * @returns A promise that resolves once the wallet account is connected.
308
+ * @returns A promise that resolves with the connected wallet's address.
305
309
  * @throws {TurnkeyError} If the wallet manager is uninitialized or the connection fails.
306
310
  */
307
311
  this.connectWalletAccount = async (walletProvider) => {
@@ -309,7 +313,7 @@ class TurnkeyClient {
309
313
  if (!this.walletManager?.connector) {
310
314
  throw new sdkTypes.TurnkeyError("Wallet connector is not initialized", sdkTypes.TurnkeyErrorCodes.WALLET_MANAGER_COMPONENT_NOT_INITIALIZED);
311
315
  }
312
- await this.walletManager.connector.connectWalletAccount(walletProvider);
316
+ return await this.walletManager.connector.connectWalletAccount(walletProvider);
313
317
  }, {
314
318
  errorMessage: "Unable to connect wallet account",
315
319
  errorCode: sdkTypes.TurnkeyErrorCodes.CONNECT_WALLET_ACCOUNT_ERROR,
@@ -357,7 +361,7 @@ class TurnkeyClient {
357
361
  if (!this.walletManager?.connector) {
358
362
  throw new sdkTypes.TurnkeyError("Wallet connector is not initialized", sdkTypes.TurnkeyErrorCodes.WALLET_MANAGER_COMPONENT_NOT_INITIALIZED);
359
363
  }
360
- if (walletAccount.source === base.WalletSource.Embedded) {
364
+ if (walletAccount.source === externalWallets.WalletSource.Embedded) {
361
365
  throw new sdkTypes.TurnkeyError("You can only switch chains for connected wallet accounts", sdkTypes.TurnkeyErrorCodes.NOT_FOUND);
362
366
  }
363
367
  const providers = walletProviders ?? (await this.fetchWalletProviders());
@@ -388,6 +392,7 @@ class TurnkeyClient {
388
392
  * @param params.publicKey - optional public key to associate with the session (generated if not provided).
389
393
  * @param params.sessionKey - optional key to store the session under (defaults to the default session key).
390
394
  * @param params.expirationSeconds - optional session expiration time in seconds (defaults to the configured default).
395
+ * @param params.organizationId - organization ID to target (defaults to the session's organization ID or the parent organization ID).
391
396
  * @returns A promise that resolves to a {@link WalletAuthResult}, which includes:
392
397
  * - `sessionToken`: the signed JWT session token.
393
398
  * - `address`: the authenticated wallet address.
@@ -399,18 +404,18 @@ class TurnkeyClient {
399
404
  if (!this.walletManager?.stamper) {
400
405
  throw new sdkTypes.TurnkeyError("Wallet stamper is not initialized", sdkTypes.TurnkeyErrorCodes.WALLET_MANAGER_COMPONENT_NOT_INITIALIZED);
401
406
  }
402
- const sessionKey = params.sessionKey || base.SessionKey.DefaultSessionkey;
407
+ const sessionKey = params.sessionKey || auth.SessionKey.DefaultSessionkey;
403
408
  const walletProvider = params.walletProvider;
404
- const expirationSeconds = params?.expirationSeconds || base.DEFAULT_SESSION_EXPIRATION_IN_SECONDS;
409
+ const expirationSeconds = params?.expirationSeconds || auth.DEFAULT_SESSION_EXPIRATION_IN_SECONDS;
405
410
  if (!publicKey) {
406
411
  throw new sdkTypes.TurnkeyError("A publickey could not be found or generated.", sdkTypes.TurnkeyErrorCodes.INTERNAL_ERROR);
407
412
  }
408
413
  this.walletManager.stamper.setProvider(walletProvider.interfaceType, walletProvider);
409
414
  const sessionResponse = await this.httpClient.stampLogin({
410
415
  publicKey,
411
- organizationId: this.config.organizationId,
416
+ organizationId: params?.organizationId ?? this.config.organizationId,
412
417
  expirationSeconds,
413
- }, base.StamperType.Wallet);
418
+ }, auth.StamperType.Wallet);
414
419
  await this.storeSession({
415
420
  sessionToken: sessionResponse.session,
416
421
  sessionKey,
@@ -452,13 +457,14 @@ class TurnkeyClient {
452
457
  * @param params.createSubOrgParams - parameters for creating a sub-organization (e.g., authenticators, user metadata).
453
458
  * @param params.sessionKey - session key to use for storing the session (defaults to the default session key).
454
459
  * @param params.expirationSeconds - session expiration time in seconds (defaults to the configured default).
460
+ * @param params.organizationId - organization ID to target (defaults to the session's organization ID or the parent organization ID).
455
461
  * @returns A promise that resolves to a {@link WalletAuthResult}, which includes:
456
462
  * - `sessionToken`: the signed JWT session token.
457
463
  * - `address`: the authenticated wallet address.
458
464
  * @throws {TurnkeyError} If there is an error during wallet authentication, sub-organization creation, session storage, or cleanup.
459
465
  */
460
466
  this.signUpWithWallet = async (params) => {
461
- const { walletProvider, createSubOrgParams, sessionKey = base.SessionKey.DefaultSessionkey, expirationSeconds = base.DEFAULT_SESSION_EXPIRATION_IN_SECONDS, } = params;
467
+ const { walletProvider, createSubOrgParams, sessionKey = auth.SessionKey.DefaultSessionkey, expirationSeconds = auth.DEFAULT_SESSION_EXPIRATION_IN_SECONDS, } = params;
462
468
  let generatedPublicKey = undefined;
463
469
  return utils.withTurnkeyErrorHandling(async () => {
464
470
  if (!this.walletManager?.stamper) {
@@ -543,6 +549,7 @@ class TurnkeyClient {
543
549
  * @param params.createSubOrgParams - optional parameters for creating a sub-organization (e.g., authenticators, user metadata).
544
550
  * @param params.sessionKey - session key to use for storing the session (defaults to the default session key).
545
551
  * @param params.expirationSeconds - session expiration time in seconds (defaults to the configured default).
552
+ * @param params.organizationId - organization ID to target (defaults to the session's organization ID or the parent organization ID).
546
553
  * @returns A promise that resolves to an object containing:
547
554
  * - `sessionToken`: the signed JWT session token.
548
555
  * - `address`: the authenticated wallet address.
@@ -551,9 +558,9 @@ class TurnkeyClient {
551
558
  */
552
559
  this.loginOrSignupWithWallet = async (params) => {
553
560
  const createSubOrgParams = params.createSubOrgParams;
554
- const sessionKey = params.sessionKey || base.SessionKey.DefaultSessionkey;
561
+ const sessionKey = params.sessionKey || auth.SessionKey.DefaultSessionkey;
555
562
  const walletProvider = params.walletProvider;
556
- const expirationSeconds = params.expirationSeconds || base.DEFAULT_SESSION_EXPIRATION_IN_SECONDS;
563
+ const expirationSeconds = params.expirationSeconds || auth.DEFAULT_SESSION_EXPIRATION_IN_SECONDS;
557
564
  let generatedPublicKey = undefined;
558
565
  return utils.withTurnkeyErrorHandling(async () => {
559
566
  if (!this.walletManager?.stamper) {
@@ -569,11 +576,15 @@ class TurnkeyClient {
569
576
  publicKey: generatedPublicKey,
570
577
  organizationId: this.config.organizationId,
571
578
  expirationSeconds,
572
- }, base.StamperType.Wallet);
579
+ }, auth.StamperType.Wallet);
573
580
  }, {
574
581
  errorMessage: "Failed to create stamped request for wallet login",
575
582
  errorCode: sdkTypes.TurnkeyErrorCodes.WALLET_LOGIN_OR_SIGNUP_ERROR,
576
583
  customErrorsByMessages: {
584
+ "WalletConnect: The connection request has expired. Please scan the QR code again.": {
585
+ message: "Your WalletConnect session expired. Please scan the QR code again.",
586
+ code: sdkTypes.TurnkeyErrorCodes.WALLET_CONNECT_EXPIRED,
587
+ },
577
588
  "Failed to sign the message": {
578
589
  message: "Wallet auth was cancelled by the user.",
579
590
  code: sdkTypes.TurnkeyErrorCodes.CONNECT_WALLET_CANCELLED,
@@ -585,13 +596,13 @@ class TurnkeyClient {
585
596
  }
586
597
  let publicKey;
587
598
  switch (walletProvider.chainInfo.namespace) {
588
- case base.Chain.Ethereum: {
599
+ case externalWallets.Chain.Ethereum: {
589
600
  // for Ethereum, there is no way to get the public key from the wallet address
590
601
  // so we derive it from the signed request
591
602
  publicKey = utils.getPublicKeyFromStampHeader(signedRequest.stamp.stampHeaderValue);
592
603
  break;
593
604
  }
594
- case base.Chain.Solana: {
605
+ case externalWallets.Chain.Solana: {
595
606
  // for Solana, we can get the public key from the wallet address
596
607
  // since the wallet address is the public key
597
608
  // this doesn't require any action from the user as long as the wallet is connected
@@ -605,7 +616,7 @@ class TurnkeyClient {
605
616
  // here we check if the subOrg exists and create one
606
617
  // then we send off the stamped request to Turnkey
607
618
  const accountRes = await this.httpClient.proxyGetAccount({
608
- filterType: base.FilterType.PublicKey,
619
+ filterType: auth.FilterType.PublicKey,
609
620
  filterValue: publicKey,
610
621
  });
611
622
  if (!accountRes) {
@@ -684,6 +695,7 @@ class TurnkeyClient {
684
695
  *
685
696
  * @param params.otpType - type of OTP to initialize (OtpType.Email or OtpType.Sms).
686
697
  * @param params.contact - contact information for the user (e.g., email address or phone number).
698
+ * @param params.organizationId - optional organization ID to target (defaults to the session's organization ID or the parent organization ID).
687
699
  * @returns A promise that resolves to the OTP ID required for verification.
688
700
  * @throws {TurnkeyError} If there is an error during the OTP initialization process or if the maximum number of OTPs has been reached.
689
701
  */
@@ -733,7 +745,7 @@ class TurnkeyClient {
733
745
  throw new sdkTypes.TurnkeyError(`OTP verification failed`, sdkTypes.TurnkeyErrorCodes.INTERNAL_ERROR);
734
746
  }
735
747
  const accountRes = await this.httpClient.proxyGetAccount({
736
- filterType: base.OtpTypeToFilterTypeMap[otpType],
748
+ filterType: auth.OtpTypeToFilterTypeMap[otpType],
737
749
  filterValue: contact,
738
750
  });
739
751
  if (!accountRes) {
@@ -773,7 +785,7 @@ class TurnkeyClient {
773
785
  * @throws {TurnkeyError} If there is an error during the OTP login process or if key pair cleanup fails.
774
786
  */
775
787
  this.loginWithOtp = async (params) => {
776
- const { verificationToken, invalidateExisting = false, publicKey = await this.apiKeyStamper?.createKeyPair(), sessionKey = base.SessionKey.DefaultSessionkey, } = params;
788
+ const { verificationToken, invalidateExisting = false, publicKey = await this.apiKeyStamper?.createKeyPair(), sessionKey = auth.SessionKey.DefaultSessionkey, } = params;
777
789
  return utils.withTurnkeyErrorHandling(async () => {
778
790
  const res = await this.httpClient.proxyOtpLogin({
779
791
  verificationToken,
@@ -834,7 +846,7 @@ class TurnkeyClient {
834
846
  const signUpBody = utils.buildSignUpBody({
835
847
  createSubOrgParams: {
836
848
  ...createSubOrgParams,
837
- ...(otpType === base.OtpType.Email
849
+ ...(otpType === auth.OtpType.Email
838
850
  ? { userEmail: contact }
839
851
  : { userPhoneNumber: contact }),
840
852
  verificationToken,
@@ -946,7 +958,7 @@ class TurnkeyClient {
946
958
  * @throws {TurnkeyError} If there is an error during the OAuth completion process, such as account lookup, sign-up, or login.
947
959
  */
948
960
  this.completeOauth = async (params) => {
949
- const { oidcToken, publicKey, createSubOrgParams, providerName = "OpenID Connect Provider" + " " + Date.now(), sessionKey = base.SessionKey.DefaultSessionkey, invalidateExisting = false, } = params;
961
+ const { oidcToken, publicKey, createSubOrgParams, providerName = "OpenID Connect Provider" + " " + Date.now(), sessionKey = auth.SessionKey.DefaultSessionkey, invalidateExisting = false, } = params;
950
962
  return utils.withTurnkeyErrorHandling(async () => {
951
963
  const accountRes = await this.httpClient.proxyGetAccount({
952
964
  filterType: "OIDC_TOKEN",
@@ -1005,7 +1017,7 @@ class TurnkeyClient {
1005
1017
  * @throws {TurnkeyError} If there is an error during the OAuth login process or if key pair cleanup fails.
1006
1018
  */
1007
1019
  this.loginWithOauth = async (params) => {
1008
- const { oidcToken, invalidateExisting = false, publicKey, sessionKey = base.SessionKey.DefaultSessionkey, } = params;
1020
+ const { oidcToken, invalidateExisting = false, publicKey, sessionKey = auth.SessionKey.DefaultSessionkey, } = params;
1009
1021
  return utils.withTurnkeyErrorHandling(async () => {
1010
1022
  if (!publicKey) {
1011
1023
  throw new sdkTypes.TurnkeyError("Public key must be provided to log in with OAuth. Please create a key pair first.", sdkTypes.TurnkeyErrorCodes.MISSING_PARAMS);
@@ -1102,36 +1114,61 @@ class TurnkeyClient {
1102
1114
  * - Returns both embedded and connected wallets in a single array, each with their respective accounts populated.
1103
1115
  * - Optionally allows stamping the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
1104
1116
  *
1105
- * @param params.stampWith - parameter to stamp the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
1106
1117
  * @param params.walletProviders - array of wallet providers to use for fetching wallets.
1118
+ * @param params.organizationId - organization ID to target (defaults to the session's organization ID).
1119
+ * @param params.userId - user ID to target (defaults to the session's user ID).
1120
+ * @param params.connectedOnly - if true, fetches only connected wallets; if false or undefined, fetches both embedded and connected wallets.
1121
+ * @param params.stampWith - parameter to stamp the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
1107
1122
  * @returns A promise that resolves to an array of `Wallet` objects.
1108
1123
  * @throws {TurnkeyError} If no active session is found or if there is an error fetching wallets.
1109
1124
  */
1110
1125
  this.fetchWallets = async (params) => {
1111
- const { stampWith, walletProviders } = params || {};
1126
+ const { walletProviders, organizationId: organizationIdFromParams, userId: userIdFromParams, connectedOnly, stampWith, } = params || {};
1112
1127
  const session = await this.storageManager.getActiveSession();
1113
- if (!session) {
1114
- throw new sdkTypes.TurnkeyError("No active session found. Please log in first.", sdkTypes.TurnkeyErrorCodes.NO_SESSION_FOUND);
1128
+ if (!session && !connectedOnly) {
1129
+ throw new sdkTypes.TurnkeyError("No active session found. Fetching embedded wallets requires a valid session. If you only need connected wallets, set the 'connectedOnly' parameter to true.", sdkTypes.TurnkeyErrorCodes.NO_SESSION_FOUND);
1130
+ }
1131
+ // if `connectedOnly` is true, we need to make sure the walletManager is initialized
1132
+ // or else we can't fetch connected wallets, and we throw an error
1133
+ if (connectedOnly && !this.walletManager?.connector) {
1134
+ throw new sdkTypes.TurnkeyError("Wallet connector is not initialized", sdkTypes.TurnkeyErrorCodes.WALLET_MANAGER_COMPONENT_NOT_INITIALIZED);
1115
1135
  }
1116
1136
  return utils.withTurnkeyErrorHandling(async () => {
1117
- const res = await this.httpClient.getWallets({ organizationId: session.organizationId }, stampWith);
1118
- if (!res || !res.wallets) {
1119
- throw new sdkTypes.TurnkeyError("No wallets found in the response", sdkTypes.TurnkeyErrorCodes.BAD_RESPONSE);
1120
- }
1121
- const embedded = await Promise.all(res.wallets.map(async (wallet) => {
1122
- const embeddedWallet = {
1123
- ...wallet,
1124
- source: base.WalletSource.Embedded,
1125
- accounts: [],
1126
- };
1127
- const accounts = await this.fetchWalletAccounts({
1128
- wallet: embeddedWallet,
1129
- ...(stampWith !== undefined && { stampWith }),
1130
- });
1131
- embeddedWallet.accounts = accounts;
1132
- return embeddedWallet;
1133
- }));
1137
+ let embedded = [];
1138
+ // if connectedOnly is true, we skip fetching embedded wallets
1139
+ if (!connectedOnly) {
1140
+ const organizationId = organizationIdFromParams || session?.organizationId;
1141
+ if (!organizationId) {
1142
+ throw new sdkTypes.TurnkeyError("No organization ID provided and no active session found. Please log in first or pass in an organization ID.", sdkTypes.TurnkeyErrorCodes.INVALID_REQUEST);
1143
+ }
1144
+ const userId = userIdFromParams || session?.userId;
1145
+ if (!userId) {
1146
+ throw new sdkTypes.TurnkeyError("No user ID provided and no active session found. Please log in first or pass in a user ID.", sdkTypes.TurnkeyErrorCodes.INVALID_REQUEST);
1147
+ }
1148
+ const res = await this.httpClient.getWalletAccounts({
1149
+ organizationId,
1150
+ includeWalletDetails: true,
1151
+ }, stampWith);
1152
+ const walletsRes = await this.httpClient.getWallets({
1153
+ organizationId,
1154
+ }, stampWith);
1155
+ if (!res || !res.accounts) {
1156
+ throw new sdkTypes.TurnkeyError("No wallet accounts found in the response", sdkTypes.TurnkeyErrorCodes.BAD_RESPONSE);
1157
+ }
1158
+ // create a map of walletId to EmbeddedWallet for easy lookup
1159
+ const walletMap = new Map(walletsRes.wallets.map((wallet) => [
1160
+ wallet.walletId,
1161
+ {
1162
+ ...wallet,
1163
+ source: externalWallets.WalletSource.Embedded,
1164
+ accounts: [],
1165
+ },
1166
+ ]));
1167
+ // map the accounts to their respective wallets
1168
+ embedded = utils.mapAccountsToWallet(res.accounts, walletMap);
1169
+ }
1134
1170
  // if wallet connecting is disabled we return only embedded wallets
1171
+ // this will never be hit if `connectedOnly` is true because of the check above
1135
1172
  if (!this.walletManager?.connector)
1136
1173
  return embedded;
1137
1174
  const providers = walletProviders ?? (await this.fetchWalletProviders());
@@ -1145,10 +1182,14 @@ class TurnkeyClient {
1145
1182
  group.push(provider);
1146
1183
  groupedProviders.set(walletId, group);
1147
1184
  }
1148
- const connected = (await Promise.all(Array.from(groupedProviders.entries()).map(async ([walletId, grouped]) => {
1185
+ // has to be done in a for of loop so we can await each fetchWalletAccounts call individually
1186
+ // otherwise await Promise.all would cause them all to fire at once breaking passkey only set ups
1187
+ // (multiple wallet fetches at once causing "OperationError: A request is already pending.")
1188
+ let connected = [];
1189
+ for (const [walletId, grouped] of groupedProviders.entries()) {
1149
1190
  const timestamp = utils.toExternalTimestamp();
1150
1191
  const wallet = {
1151
- source: base.WalletSource.Connected,
1192
+ source: externalWallets.WalletSource.Connected,
1152
1193
  walletId,
1153
1194
  walletName: grouped[0]?.info?.name ?? "Unknown",
1154
1195
  createdAt: timestamp,
@@ -1161,10 +1202,16 @@ class TurnkeyClient {
1161
1202
  wallet,
1162
1203
  walletProviders: grouped,
1163
1204
  ...(stampWith !== undefined && { stampWith }),
1205
+ ...(organizationIdFromParams !== undefined && {
1206
+ organizationId: organizationIdFromParams,
1207
+ }),
1208
+ ...(userIdFromParams !== undefined && { userId: userIdFromParams }),
1164
1209
  });
1165
1210
  wallet.accounts = accounts;
1166
- return wallet;
1167
- }))).filter((wallet) => wallet.accounts.length > 0);
1211
+ if (wallet.accounts.length > 0) {
1212
+ connected.push(wallet);
1213
+ }
1214
+ }
1168
1215
  return [...embedded, ...connected];
1169
1216
  }, {
1170
1217
  errorMessage: "Failed to fetch wallets",
@@ -1184,22 +1231,30 @@ class TurnkeyClient {
1184
1231
  * @param params.walletProviders - list of wallet providers to filter by (used for connected wallets).
1185
1232
  * @param params.paginationOptions - pagination options for embedded wallets.
1186
1233
  * @param params.stampWith - parameter to stamp the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
1234
+ * @param params.organizationId - organization ID to target (defaults to the session's organization ID).
1235
+ * @param params.userId - user ID to target (defaults to the session's user ID).
1236
+ *
1187
1237
  * @returns A promise that resolves to an array of `v1WalletAccount` objects.
1188
1238
  * @throws {TurnkeyError} If no active session is found or if there is an error fetching wallet accounts.
1189
1239
  */
1190
1240
  this.fetchWalletAccounts = async (params) => {
1191
1241
  const { wallet, stampWith, walletProviders, paginationOptions } = params;
1192
1242
  const session = await this.storageManager.getActiveSession();
1193
- if (!session) {
1194
- throw new sdkTypes.TurnkeyError("No active session found. Please log in first.", sdkTypes.TurnkeyErrorCodes.NO_SESSION_FOUND);
1195
- }
1243
+ const organizationId = params?.organizationId || session?.organizationId;
1244
+ const userId = params?.userId || session?.userId;
1196
1245
  return utils.withTurnkeyErrorHandling(async () => {
1197
1246
  // this is an embedded wallet so we fetch accounts from Turnkey
1198
- if (wallet.source === base.WalletSource.Embedded) {
1247
+ if (wallet.source === externalWallets.WalletSource.Embedded) {
1199
1248
  const embedded = [];
1249
+ if (!organizationId) {
1250
+ throw new sdkTypes.TurnkeyError("No organization ID provided and no active session found. Please log in first or pass in an organization ID.", sdkTypes.TurnkeyErrorCodes.INVALID_REQUEST);
1251
+ }
1252
+ if (!userId) {
1253
+ throw new sdkTypes.TurnkeyError("No user ID provided and no active session found. Please log in first or pass in a user ID.", sdkTypes.TurnkeyErrorCodes.INVALID_REQUEST);
1254
+ }
1200
1255
  const res = await this.httpClient.getWalletAccounts({
1201
1256
  walletId: wallet.walletId,
1202
- organizationId: session.organizationId,
1257
+ organizationId,
1203
1258
  paginationOptions: paginationOptions || { limit: "100" },
1204
1259
  }, stampWith);
1205
1260
  if (!res || !res.accounts) {
@@ -1208,7 +1263,7 @@ class TurnkeyClient {
1208
1263
  for (const account of res.accounts) {
1209
1264
  embedded.push({
1210
1265
  ...account,
1211
- source: base.WalletSource.Embedded,
1266
+ source: externalWallets.WalletSource.Embedded,
1212
1267
  });
1213
1268
  }
1214
1269
  return embedded;
@@ -1230,31 +1285,40 @@ class TurnkeyClient {
1230
1285
  const matching = providers.filter((p) => p.info?.name?.toLowerCase().replace(/\s+/g, "-") ===
1231
1286
  wallet.walletId && p.connectedAddresses.length > 0);
1232
1287
  const sign = this.walletManager.connector.sign.bind(this.walletManager.connector);
1233
- const user = await this.fetchUser({
1234
- stampWith,
1235
- });
1236
- const { ethereum: ethereumAddresses, solana: solanaAddresses } = utils.getAuthenticatorAddresses(user);
1288
+ let ethereumAddresses = [];
1289
+ let solanaAddresses = [];
1290
+ // we only fetch the user if we have to the organizationId and userId
1291
+ // if not that means `isAuthenticator` will always be false
1292
+ if (organizationId && userId) {
1293
+ const user = await this.fetchUser({
1294
+ userId,
1295
+ organizationId,
1296
+ stampWith,
1297
+ });
1298
+ ({ ethereum: ethereumAddresses, solana: solanaAddresses } =
1299
+ utils.getAuthenticatorAddresses(user));
1300
+ }
1237
1301
  for (const provider of matching) {
1238
1302
  const timestamp = utils.toExternalTimestamp();
1239
1303
  for (const address of provider.connectedAddresses) {
1240
1304
  if (utils.isEthereumProvider(provider)) {
1241
1305
  const evmAccount = {
1242
1306
  walletAccountId: `${wallet.walletId}-${provider.interfaceType}-${address}`,
1243
- organizationId: session.organizationId,
1307
+ organizationId: organizationId ?? "",
1244
1308
  walletId: wallet.walletId,
1245
1309
  pathFormat: "PATH_FORMAT_BIP32",
1246
- path: base.WalletSource.Connected,
1247
- source: base.WalletSource.Connected,
1310
+ path: externalWallets.WalletSource.Connected,
1311
+ source: externalWallets.WalletSource.Connected,
1248
1312
  address,
1249
1313
  createdAt: timestamp,
1250
1314
  updatedAt: timestamp,
1251
1315
  // ethereum specific
1252
- curve: base.Curve.SECP256K1,
1316
+ curve: externalWallets.Curve.SECP256K1,
1253
1317
  addressFormat: "ADDRESS_FORMAT_ETHEREUM",
1254
1318
  chainInfo: provider.chainInfo,
1255
1319
  isAuthenticator: ethereumAddresses.includes(address.toLowerCase()),
1256
- signMessage: (msg) => sign(msg, provider, base.SignIntent.SignMessage),
1257
- signAndSendTransaction: (tx) => sign(tx, provider, base.SignIntent.SignAndSendTransaction),
1320
+ signMessage: (msg) => sign(msg, provider, externalWallets.SignIntent.SignMessage),
1321
+ signAndSendTransaction: (tx) => sign(tx, provider, externalWallets.SignIntent.SignAndSendTransaction),
1258
1322
  };
1259
1323
  connected.push(evmAccount);
1260
1324
  continue;
@@ -1262,22 +1326,22 @@ class TurnkeyClient {
1262
1326
  if (utils.isSolanaProvider(provider)) {
1263
1327
  const solAccount = {
1264
1328
  walletAccountId: `${wallet.walletId}-${provider.interfaceType}-${address}`,
1265
- organizationId: session.organizationId,
1329
+ organizationId: organizationId ?? "",
1266
1330
  walletId: wallet.walletId,
1267
1331
  pathFormat: "PATH_FORMAT_BIP32",
1268
- path: base.WalletSource.Connected,
1269
- source: base.WalletSource.Connected,
1332
+ path: externalWallets.WalletSource.Connected,
1333
+ source: externalWallets.WalletSource.Connected,
1270
1334
  address,
1271
1335
  createdAt: timestamp,
1272
1336
  updatedAt: timestamp,
1273
1337
  // solana specific
1274
1338
  publicKey: address,
1275
- curve: base.Curve.ED25519,
1339
+ curve: externalWallets.Curve.ED25519,
1276
1340
  addressFormat: "ADDRESS_FORMAT_SOLANA",
1277
1341
  chainInfo: provider.chainInfo,
1278
1342
  isAuthenticator: solanaAddresses.includes(address),
1279
- signMessage: (msg) => sign(msg, provider, base.SignIntent.SignMessage),
1280
- signTransaction: (tx) => sign(tx, provider, base.SignIntent.SignTransaction),
1343
+ signMessage: (msg) => sign(msg, provider, externalWallets.SignIntent.SignMessage),
1344
+ signTransaction: (tx) => sign(tx, provider, externalWallets.SignIntent.SignTransaction),
1281
1345
  };
1282
1346
  connected.push(solAccount);
1283
1347
  continue;
@@ -1298,17 +1362,19 @@ class TurnkeyClient {
1298
1362
  * - Supports stamping the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
1299
1363
  *
1300
1364
  * @param params.stampWith - parameter to stamp the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
1365
+ * @param params.organizationId - organization ID to target (defaults to the session's organization ID).
1301
1366
  * @returns A promise that resolves to an array of `v1PrivateKey` objects.
1302
1367
  * @throws {TurnkeyError} If no active session is found or if there is an error fetching private keys.
1303
1368
  */
1304
1369
  this.fetchPrivateKeys = async (params) => {
1305
1370
  const { stampWith } = params || {};
1306
- const session = await this.storageManager.getActiveSession();
1307
- if (!session) {
1308
- throw new sdkTypes.TurnkeyError("No active session found. Please log in first.", sdkTypes.TurnkeyErrorCodes.NO_SESSION_FOUND);
1371
+ const session = await utils.getActiveSessionOrThrowIfRequired(stampWith, this.storageManager.getActiveSession);
1372
+ const organizationId = params?.organizationId || session?.organizationId;
1373
+ if (!organizationId) {
1374
+ throw new sdkTypes.TurnkeyError("No organization ID provided and no active session found. Please log in first or pass in an organization ID.", sdkTypes.TurnkeyErrorCodes.INVALID_REQUEST);
1309
1375
  }
1310
1376
  return utils.withTurnkeyErrorHandling(async () => {
1311
- const res = await this.httpClient.getPrivateKeys({ organizationId: session.organizationId }, stampWith);
1377
+ const res = await this.httpClient.getPrivateKeys({ organizationId }, stampWith);
1312
1378
  if (!res) {
1313
1379
  throw new sdkTypes.TurnkeyError("Failed to fetch private keys", sdkTypes.TurnkeyErrorCodes.BAD_RESPONSE);
1314
1380
  }
@@ -1321,61 +1387,77 @@ class TurnkeyClient {
1321
1387
  /**
1322
1388
  * Signs a message using the specified wallet account.
1323
1389
  *
1324
- * - Supports both embedded and connected wallets.
1325
- * - For **connected wallets**:
1390
+ * Behavior differs depending on the wallet type:
1391
+ *
1392
+ * - **Connected wallets**
1326
1393
  * - Delegates signing to the wallet provider’s native signing method.
1327
- * - **Important:** For Ethereum wallets (e.g., MetaMask), signatures follow [EIP-191](https://eips.ethereum.org/EIPS/eip-191).
1328
- * The message is automatically prefixed with `"\x19Ethereum Signed Message:\n" + message length`
1329
- * before signing. As a result, this signature **cannot be used as a raw transaction signature**
1330
- * or broadcast on-chain.
1331
- * - For **embedded wallets**, uses the Turnkey API to sign the message directly.
1332
- * - Automatically handles message encoding and hashing based on the wallet account’s address format,
1394
+ * - *Ethereum*: signatures always follow [EIP-191](https://eips.ethereum.org/EIPS/eip-191).
1395
+ * - The wallet automatically prefixes messages with
1396
+ * `"\x19Ethereum Signed Message:\n" + message length` before signing.
1397
+ * - As a result, these signatures cannot be used as raw transaction signatures or broadcast on-chain.
1398
+ * - If `addEthereumPrefix` is set to `false`, an error is thrown because connected Ethereum wallets always prefix.
1399
+ * - *Other chains*: follows the native connected wallet behavior.
1400
+ *
1401
+ * - **Embedded wallets**
1402
+ * - Uses the Turnkey API to sign the message directly.
1403
+ * - Supports optional `addEthereumPrefix`:
1404
+ * - If `true` (default for Ethereum), the message is prefixed before signing.
1405
+ * - If `false`, the raw message is signed without any prefix.
1406
+ *
1407
+ * Additional details:
1408
+ * - Automatically handles encoding and hashing based on the wallet account’s address format,
1333
1409
  * unless explicitly overridden.
1410
+ * - Optionally allows stamping with a specific stamper
1411
+ * (`StamperType.Passkey`, `StamperType.ApiKey`, or `StamperType.Wallet`).
1334
1412
  *
1335
- * @param params.message - message to sign.
1413
+ * @param params.message - plaintext (UTF-8) message to sign.
1336
1414
  * @param params.walletAccount - wallet account to use for signing.
1337
- * @param params.encoding - override for the payload encoding (defaults to the encoding appropriate for the address type).
1338
- * @param params.hashFunction - override for the hash function (defaults to the hash function appropriate for the address type).
1339
- * @param params.stampWith - stamper to tag the signing request (e.g., Passkey, ApiKey, or Wallet).
1340
- * @param params.addEthereumPrefix - whether to prefix the message with Ethereum's `"\x19Ethereum Signed Message:\n"` string.
1341
- * - If `true` (default for Ethereum), the message is prefixed before signing.
1342
- * - If `false`:
1343
- * - Connected wallets will throw an error because they always prefix automatically.
1344
- * - Embedded wallets will sign the raw message without any prefix.
1345
- *
1346
- * @returns A promise resolving to a `v1SignRawPayloadResult` containing the signature and metadata.
1347
- * @throws {TurnkeyError} If signing fails, if the wallet account does not support signing, or if the response is invalid.
1415
+ * @param params.encoding - override for payload encoding (defaults to the encoding appropriate for the address format).
1416
+ * @param params.hashFunction - override for hash function (defaults to the function appropriate for the address format).
1417
+ * @param params.stampWith - optional stamper for the signing request.
1418
+ * @param params.addEthereumPrefix - whether to prefix the message with Ethereums
1419
+ * `"\x19Ethereum Signed Message:\n"` string (default: `true` for Ethereum).
1420
+ * @param params.organizationId - organization ID to target (defaults to the session's organization ID).
1421
+ *
1422
+ * @returns A promise that resolves to a `v1SignRawPayloadResult` containing the signature and metadata.
1423
+ * @throws {TurnkeyError} If signing fails, the wallet type does not support message signing, or the response is invalid.
1348
1424
  */
1349
1425
  this.signMessage = async (params) => {
1350
- const { message, walletAccount, stampWith, addEthereumPrefix } = params;
1426
+ const { message, walletAccount, stampWith, addEthereumPrefix, organizationId, } = params;
1351
1427
  const hashFunction = params.hashFunction || utils.getHashFunction(walletAccount.addressFormat);
1352
1428
  const payloadEncoding = params.encoding || utils.getEncodingType(walletAccount.addressFormat);
1353
1429
  return utils.withTurnkeyErrorHandling(async () => {
1354
1430
  const isEthereum = walletAccount.addressFormat === "ADDRESS_FORMAT_ETHEREUM";
1355
- if (walletAccount.source === base.WalletSource.Connected) {
1431
+ if (walletAccount.source === externalWallets.WalletSource.Connected) {
1356
1432
  // this is a connected wallet
1357
1433
  if (!addEthereumPrefix && isEthereum) {
1358
1434
  throw new sdkTypes.TurnkeyError("Connected Ethereum wallets automatically prefix messages. Use `addEthereumPrefix: true`.", sdkTypes.TurnkeyErrorCodes.SIGN_MESSAGE_ERROR);
1359
1435
  }
1360
1436
  let encodedMessage = message;
1361
1437
  if (isEthereum) {
1362
- encodedMessage = utils.getEncodedMessage(walletAccount.addressFormat, message);
1438
+ const msgBytes = ethers.toUtf8Bytes(message);
1439
+ encodedMessage = utils.getEncodedMessage(payloadEncoding, msgBytes);
1363
1440
  }
1364
1441
  const sigHex = await walletAccount.signMessage(encodedMessage);
1365
1442
  return utils.splitSignature(sigHex, walletAccount.addressFormat);
1366
1443
  }
1367
1444
  // this is an embedded wallet
1368
- let messageToEncode = message;
1445
+ let msgBytes = ethers.toUtf8Bytes(message);
1369
1446
  if (addEthereumPrefix && isEthereum) {
1370
- const prefix = `\x19Ethereum Signed Message:\n${ethers.toUtf8Bytes(message).length}`;
1371
- messageToEncode = prefix + message;
1372
- }
1373
- const encodedMessage = utils.getEncodedMessage(walletAccount.addressFormat, messageToEncode);
1447
+ const prefix = `\x19Ethereum Signed Message:\n${msgBytes.length}`;
1448
+ const prefixBytes = ethers.toUtf8Bytes(prefix);
1449
+ const combined = new Uint8Array(prefixBytes.length + msgBytes.length);
1450
+ combined.set(prefixBytes, 0);
1451
+ combined.set(msgBytes, prefixBytes.length);
1452
+ msgBytes = combined;
1453
+ }
1454
+ const encodedMessage = utils.getEncodedMessage(payloadEncoding, msgBytes);
1374
1455
  const response = await this.httpClient.signRawPayload({
1375
1456
  signWith: walletAccount.address,
1376
1457
  payload: encodedMessage,
1377
1458
  encoding: payloadEncoding,
1378
1459
  hashFunction,
1460
+ ...(organizationId && { organizationId }),
1379
1461
  }, stampWith);
1380
1462
  if (response.activity.failure) {
1381
1463
  throw new sdkTypes.TurnkeyError("Failed to sign message, no signed payload returned", sdkTypes.TurnkeyErrorCodes.SIGN_MESSAGE_ERROR);
@@ -1390,27 +1472,35 @@ class TurnkeyClient {
1390
1472
  /**
1391
1473
  * Signs a transaction using the specified wallet account.
1392
1474
  *
1393
- * - This function signs a blockchain transaction using the provided wallet address and transaction data.
1394
- * - Supports all Turnkey-supported blockchain networks (e.g., Ethereum, Solana, Tron).
1395
- * - Automatically determines the appropriate signing method based on the transaction type.
1396
- * - Delegates signing to the Turnkey API, which returns the signed transaction and related metadata.
1397
- * - Optionally allows stamping the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
1475
+ * Behavior differs depending on the type of wallet:
1476
+ *
1477
+ * - **Connected wallets**
1478
+ * - Ethereum: does not support raw transaction signing. Calling this function will throw an error instructing you to use `signAndSendTransaction` instead.
1479
+ * - Solana: supports raw transaction signing via the connected wallet provider.
1480
+ * - Other chains: not supported; will throw an error.
1398
1481
  *
1399
- * @param params.walletAccount - wallet account to use for signing the transaction.
1400
- * @param params.unsignedTransaction - unsigned transaction data (serialized as a string) to be signed.
1482
+ * - **Embedded wallets**
1483
+ * - Delegates signing to the Turnkey API, which returns the signed transaction.
1484
+ * - Supports all Turnkey-supported transaction types (e.g., Ethereum, Solana, Tron).
1485
+ * - Optionally allows stamping with a specific stamper (`StamperType.Passkey`, `StamperType.ApiKey`, or `StamperType.Wallet`).
1486
+ *
1487
+ * @param params.walletAccount - wallet account to use for signing.
1488
+ * @param params.unsignedTransaction - unsigned transaction data as a serialized
1489
+ * string in the canonical encoding for the given `transactionType`.
1401
1490
  * @param params.transactionType - type of transaction (e.g., "TRANSACTION_TYPE_ETHEREUM", "TRANSACTION_TYPE_SOLANA", "TRANSACTION_TYPE_TRON").
1402
- * @param params.stampWith - parameter to stamp the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
1403
- * @returns A promise that resolves to a `TSignTransactionResponse` object containing the signed transaction and any additional signing metadata.
1404
- * @throws {TurnkeyError} If there is an error signing the transaction or if the response is invalid.
1491
+ * @param params.stampWith - stamper to use for signing (`StamperType.Passkey`, `StamperType.ApiKey`, or `StamperType.Wallet`).
1492
+ * @param params.organizationId - organization ID to target (defaults to the session's organization ID).
1493
+ * @returns A promise that resolves to the signed transaction string.
1494
+ * @throws {TurnkeyError} If the wallet type is unsupported, signing fails, or the response is invalid.
1405
1495
  */
1406
1496
  this.signTransaction = async (params) => {
1407
- const { walletAccount, unsignedTransaction, transactionType, stampWith } = params;
1497
+ const { walletAccount, unsignedTransaction, transactionType, stampWith, organizationId, } = params;
1408
1498
  return utils.withTurnkeyErrorHandling(async () => {
1409
- if (walletAccount.source === base.WalletSource.Connected) {
1499
+ if (walletAccount.source === externalWallets.WalletSource.Connected) {
1410
1500
  switch (walletAccount.chainInfo.namespace) {
1411
- case base.Chain.Ethereum:
1501
+ case externalWallets.Chain.Ethereum:
1412
1502
  throw new sdkTypes.TurnkeyError("Ethereum connected wallets do not support raw transaction signing. Use signAndSendTransaction instead.", sdkTypes.TurnkeyErrorCodes.INVALID_REQUEST);
1413
- case base.Chain.Solana:
1503
+ case externalWallets.Chain.Solana:
1414
1504
  // not sure why typescript isn't inferring the type here
1415
1505
  // if namespace is Chain.Solana, then it must be a ConnectedSolanaWalletAccount
1416
1506
  return walletAccount.signTransaction(unsignedTransaction);
@@ -1423,6 +1513,7 @@ class TurnkeyClient {
1423
1513
  signWith: walletAccount.address,
1424
1514
  unsignedTransaction,
1425
1515
  type: transactionType,
1516
+ ...(organizationId && { organizationId }),
1426
1517
  }, stampWith);
1427
1518
  return signTransaction.signedTransaction;
1428
1519
  }, {
@@ -1433,34 +1524,41 @@ class TurnkeyClient {
1433
1524
  /**
1434
1525
  * Signs and broadcasts a transaction using the specified wallet account.
1435
1526
  *
1436
- * - For **connected wallets**:
1437
- * - Calls the wallet’s native `signAndSendTransaction` method.
1438
- * - Does **not** require an `rpcUrl`.
1527
+ * Behavior differs depending on the type of wallet:
1528
+ *
1529
+ * - **Connected wallets**
1530
+ * - *Ethereum*: delegates to the wallet’s native `signAndSendTransaction` method.
1531
+ * - Does **not** require an `rpcUrl` (the wallet handles broadcasting).
1532
+ * - *Solana*: signs the transaction locally with the connected wallet, but requires an `rpcUrl` to broadcast it.
1533
+ * - Other chains: not supported; will throw an error.
1439
1534
  *
1440
- * - For **embedded wallets**:
1535
+ * - **Embedded wallets**
1441
1536
  * - Signs the transaction using the Turnkey API.
1442
- * - Requires an `rpcUrl` to broadcast the transaction.
1443
- * - Broadcasts the transaction using a JSON-RPC client.
1444
- *
1445
- * @param params.walletAccount - wallet account to use for signing and sending.
1446
- * @param params.unsignedTransaction - unsigned transaction (serialized string).
1447
- * @param params.transactionType - transaction type (e.g., "TRANSACTION_TYPE_SOLANA").
1448
- * @param params.rpcUrl - required for embedded wallets to broadcast the signed transaction.
1449
- * @param params.stampWith - optional stamper to tag the signing request.
1537
+ * - Requires an `rpcUrl` to broadcast the signed transaction, since Turnkey does not broadcast directly.
1538
+ * - Broadcasts the transaction using a JSON-RPC client and returns the resulting transaction hash/signature.
1539
+ * - Optionally allows stamping with a specific stamper (`StamperType.Passkey`, `StamperType.ApiKey`, or `StamperType.Wallet`).
1540
+ *
1541
+ * @param params.walletAccount - wallet account to use for signing and broadcasting.
1542
+ * @param params.unsignedTransaction - unsigned transaction data as a serialized
1543
+ * string in the canonical encoding for the given `transactionType`.
1544
+ * @param params.transactionType - type of transaction (e.g., `"TRANSACTION_TYPE_SOLANA"`, `"TRANSACTION_TYPE_ETHEREUM"`).
1545
+ * @param params.rpcUrl - JSON-RPC endpoint used for broadcasting (required for Solana connected wallets and all embedded wallets).
1546
+ * @param params.stampWith - optional stamper to use when signing (`StamperType.Passkey`, `StamperType.ApiKey`, or `StamperType.Wallet`).
1547
+ * @param params.organizationId - **Only for Turnkey embedded wallets**: organization ID to target (defaults to the session's organization ID).
1450
1548
  * @returns A promise that resolves to a transaction signature or hash.
1451
- * @throws {TurnkeyError} If signing or broadcasting fails.
1549
+ * @throws {TurnkeyError} If the wallet type is unsupported, or if signing/broadcasting fails.
1452
1550
  */
1453
1551
  this.signAndSendTransaction = async (params) => {
1454
- const { walletAccount, unsignedTransaction, transactionType, rpcUrl, stampWith, } = params;
1552
+ const { walletAccount, unsignedTransaction, transactionType, rpcUrl, stampWith, organizationId, } = params;
1455
1553
  return utils.withTurnkeyErrorHandling(async () => {
1456
- if (walletAccount.source === base.WalletSource.Connected) {
1554
+ if (walletAccount.source === externalWallets.WalletSource.Connected) {
1457
1555
  // this is a connected wallet account
1458
1556
  switch (walletAccount.chainInfo.namespace) {
1459
- case base.Chain.Ethereum:
1557
+ case externalWallets.Chain.Ethereum:
1460
1558
  // not sure why typescript isn't inferring the type here
1461
1559
  // if namespace is Chain.Ethereum, then it must be a ConnectedEthereumWalletAccount
1462
1560
  return await walletAccount.signAndSendTransaction(unsignedTransaction);
1463
- case base.Chain.Solana:
1561
+ case externalWallets.Chain.Solana:
1464
1562
  if (!rpcUrl) {
1465
1563
  throw new sdkTypes.TurnkeyError("Missing rpcUrl: connected Solana wallets require an RPC URL to broadcast transactions.", sdkTypes.TurnkeyErrorCodes.SIGN_AND_SEND_TRANSACTION_ERROR);
1466
1564
  }
@@ -1486,6 +1584,7 @@ class TurnkeyClient {
1486
1584
  signWith: walletAccount.address,
1487
1585
  unsignedTransaction,
1488
1586
  type: transactionType,
1587
+ ...(organizationId && { organizationId }),
1489
1588
  }, stampWith);
1490
1589
  const signedTx = signTransactionResponse.signedTransaction;
1491
1590
  const txHash = await utils.broadcastTransaction({
@@ -1515,16 +1614,16 @@ class TurnkeyClient {
1515
1614
  * @throws {TurnkeyError} If there is no active session, if there is no userId, or if there is an error fetching user details.
1516
1615
  */
1517
1616
  this.fetchUser = async (params) => {
1518
- const { stampWith } = params || {};
1519
- const session = await this.storageManager.getActiveSession();
1520
- if (!session) {
1521
- throw new sdkTypes.TurnkeyError("No active session found. Please log in first.", sdkTypes.TurnkeyErrorCodes.NO_SESSION_FOUND);
1522
- }
1523
- const userId = params?.userId || session.userId;
1617
+ const { organizationId: organizationIdFromParams, userId: userIdFromParams, stampWith, } = params || {};
1618
+ const session = await utils.getActiveSessionOrThrowIfRequired(stampWith, this.storageManager.getActiveSession);
1619
+ const userId = userIdFromParams || session?.userId;
1524
1620
  if (!userId) {
1525
1621
  throw new sdkTypes.TurnkeyError("User ID must be provided to fetch user", sdkTypes.TurnkeyErrorCodes.INVALID_REQUEST);
1526
1622
  }
1527
- const organizationId = params?.organizationId || session.organizationId;
1623
+ const organizationId = organizationIdFromParams || session?.organizationId;
1624
+ if (!organizationId) {
1625
+ throw new sdkTypes.TurnkeyError("Organization ID must be provided to fetch user", sdkTypes.TurnkeyErrorCodes.INVALID_REQUEST);
1626
+ }
1528
1627
  return utils.withTurnkeyErrorHandling(async () => {
1529
1628
  const userResponse = await this.httpClient.getUser({ organizationId, userId }, stampWith);
1530
1629
  if (!userResponse || !userResponse.user) {
@@ -1547,24 +1646,26 @@ class TurnkeyClient {
1547
1646
  * @param params.publicKey - the P-256 public key to use for lookup and creation.
1548
1647
  * @param params.createParams.userName - optional username to assign if creating a new user (defaults to `"Public Key User"`).
1549
1648
  * @param params.createParams.apiKeyName - optional API key name to assign if creating a new API key (defaults to `public-key-user-${publicKey}`).
1649
+ * @param params.organizationId - organization ID to specify the sub-organization (defaults to the current session's organizationId).
1650
+ * @param params.stampWith - parameter to stamp the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
1550
1651
  * @returns A promise that resolves to the existing or newly created {@link v1User}.
1551
1652
  * @throws {TurnkeyError} If there is no active session, if the input is invalid, if user retrieval fails, or if user creation fails.
1552
1653
  */
1553
1654
  this.fetchOrCreateP256ApiKeyUser = async (params) => {
1554
- const { publicKey, createParams } = params;
1655
+ const { publicKey, createParams, stampWith, organizationId: organizationIdFromParams, } = params;
1555
1656
  return utils.withTurnkeyErrorHandling(async () => {
1556
- const session = await this.storageManager.getActiveSession();
1557
- if (!session) {
1558
- throw new sdkTypes.TurnkeyError("No active session found. Please log in first.", sdkTypes.TurnkeyErrorCodes.NO_SESSION_FOUND);
1657
+ const session = await utils.getActiveSessionOrThrowIfRequired(stampWith, this.storageManager.getActiveSession);
1658
+ const organizationId = organizationIdFromParams || session?.organizationId;
1659
+ if (!organizationId) {
1660
+ throw new sdkTypes.TurnkeyError("Organization ID is required to fetch or create P-256 API key user.", sdkTypes.TurnkeyErrorCodes.INVALID_REQUEST);
1559
1661
  }
1560
- const organizationId = session.organizationId;
1561
1662
  // we validate their input
1562
1663
  if (!publicKey?.trim()) {
1563
1664
  throw new sdkTypes.TurnkeyError("'publicKey' is required and cannot be empty.", sdkTypes.TurnkeyErrorCodes.INVALID_REQUEST);
1564
1665
  }
1565
1666
  const usersResponse = await this.httpClient.getUsers({
1566
1667
  organizationId,
1567
- });
1668
+ }, stampWith);
1568
1669
  if (!usersResponse || !usersResponse.users) {
1569
1670
  throw new sdkTypes.TurnkeyError("No users found in the response", sdkTypes.TurnkeyErrorCodes.BAD_RESPONSE);
1570
1671
  }
@@ -1594,7 +1695,7 @@ class TurnkeyClient {
1594
1695
  oauthProviders: [],
1595
1696
  },
1596
1697
  ],
1597
- });
1698
+ }, stampWith);
1598
1699
  if (!createUserResp?.userIds ||
1599
1700
  createUserResp.userIds.length === 0 ||
1600
1701
  !createUserResp.userIds[0]) {
@@ -1604,6 +1705,7 @@ class TurnkeyClient {
1604
1705
  return await this.fetchUser({
1605
1706
  organizationId,
1606
1707
  userId: newUserId,
1708
+ stampWith,
1607
1709
  });
1608
1710
  }, {
1609
1711
  errorMessage: "Failed to get or create P-256 API key user",
@@ -1619,6 +1721,8 @@ class TurnkeyClient {
1619
1721
  * - If it does not exist, it is created and returned with its new `policyId`.
1620
1722
  *
1621
1723
  * @param params.policies - the list of policies to fetch or create.
1724
+ * @param params.stampWith - parameter to stamp the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
1725
+ * @param params.organizationId - organization ID to specify the sub-organization (defaults to the current session's organizationId).
1622
1726
  * @returns A promise that resolves to an array of objects, each containing:
1623
1727
  * - `policyId`: the unique identifier of the policy.
1624
1728
  * - `policyName`: human-readable name of the policy.
@@ -1630,20 +1734,20 @@ class TurnkeyClient {
1630
1734
  * if fetching policies fails, or if creating policies fails.
1631
1735
  */
1632
1736
  this.fetchOrCreatePolicies = async (params) => {
1633
- const { policies } = params;
1737
+ const { policies, stampWith } = params;
1634
1738
  return await utils.withTurnkeyErrorHandling(async () => {
1635
- const session = await this.storageManager.getActiveSession();
1636
- if (!session) {
1637
- throw new sdkTypes.TurnkeyError("No active session found. Please log in first.", sdkTypes.TurnkeyErrorCodes.NO_SESSION_FOUND);
1638
- }
1739
+ const session = await utils.getActiveSessionOrThrowIfRequired(stampWith, this.storageManager.getActiveSession);
1639
1740
  if (!Array.isArray(policies) || policies.length === 0) {
1640
1741
  throw new sdkTypes.TurnkeyError("'policies' must be a non-empty array of policy definitions.", sdkTypes.TurnkeyErrorCodes.INVALID_REQUEST);
1641
1742
  }
1642
- const organizationId = session.organizationId;
1743
+ const organizationId = params?.organizationId ?? session?.organizationId;
1744
+ if (!organizationId) {
1745
+ throw new sdkTypes.TurnkeyError("Organization ID is required to fetch or create policies.", sdkTypes.TurnkeyErrorCodes.INVALID_REQUEST);
1746
+ }
1643
1747
  // we first fetch existing policies
1644
1748
  const existingPoliciesResponse = await this.httpClient.getPolicies({
1645
1749
  organizationId,
1646
- });
1750
+ }, stampWith);
1647
1751
  const existingPolicies = existingPoliciesResponse.policies || [];
1648
1752
  // we create a map of existing policies by their signature
1649
1753
  // where the policySignature maps to its policyId
@@ -1676,10 +1780,10 @@ class TurnkeyClient {
1676
1780
  const createPoliciesResponse = await this.httpClient.createPolicies({
1677
1781
  organizationId,
1678
1782
  policies: missingPolicies,
1679
- });
1783
+ }, stampWith);
1680
1784
  // assign returned IDs back to the missing ones in order
1681
1785
  if (!createPoliciesResponse || !createPoliciesResponse.policyIds) {
1682
- throw new sdkTypes.TurnkeyError("Failed to create missing delegated access policies", sdkTypes.TurnkeyErrorCodes.CREATE_POLICY_ERROR);
1786
+ throw new sdkTypes.TurnkeyError("Failed to create missing policies", sdkTypes.TurnkeyErrorCodes.CREATE_POLICY_ERROR);
1683
1787
  }
1684
1788
  const newlyCreatedPolicies = missingPolicies.map((p, idx) => ({
1685
1789
  ...p,
@@ -1691,7 +1795,7 @@ class TurnkeyClient {
1691
1795
  // which includes each of their respective IDs
1692
1796
  return [...alreadyExistingPolicies, ...newlyCreatedPolicies];
1693
1797
  }, {
1694
- errorMessage: "Failed to get or create delegated access policies",
1798
+ errorMessage: "Failed to get or create policies",
1695
1799
  errorCode: sdkTypes.TurnkeyErrorCodes.CREATE_USERS_ERROR,
1696
1800
  });
1697
1801
  };
@@ -1708,19 +1812,20 @@ class TurnkeyClient {
1708
1812
  * @param params.verificationToken - verification token from OTP email verification (required if verifying the email).
1709
1813
  * @param params.userId - user ID to update a specific user's email (defaults to the current session's userId).
1710
1814
  * @param params.stampWith - parameter to stamp the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
1815
+ * @param params.organizationId - organization ID to specify the sub-organization (defaults to the current session's organizationId).
1711
1816
  * @returns A promise that resolves to the userId of the updated user.
1712
1817
  * @throws {TurnkeyError} If there is no active session, if the userId is missing, or if there is an error updating or verifying the user email.
1713
1818
  */
1714
1819
  this.updateUserEmail = async (params) => {
1715
- const { verificationToken, email, stampWith } = params;
1716
- const session = await this.storageManager.getActiveSession();
1717
- if (!session) {
1718
- throw new sdkTypes.TurnkeyError("No active session found. Please log in first.", sdkTypes.TurnkeyErrorCodes.NO_SESSION_FOUND);
1820
+ const { verificationToken, email, stampWith, organizationId } = params;
1821
+ const session = await utils.getActiveSessionOrThrowIfRequired(stampWith, this.storageManager.getActiveSession);
1822
+ const userId = params?.userId || session?.userId;
1823
+ if (!userId) {
1824
+ throw new sdkTypes.TurnkeyError("User ID must be provided to update user email", sdkTypes.TurnkeyErrorCodes.INVALID_REQUEST);
1719
1825
  }
1720
- const userId = params?.userId || session.userId;
1721
1826
  return utils.withTurnkeyErrorHandling(async () => {
1722
1827
  const existingUser = await this.httpClient.proxyGetAccount({
1723
- filterType: base.FilterType.Email,
1828
+ filterType: auth.FilterType.Email,
1724
1829
  filterValue: email,
1725
1830
  });
1726
1831
  if (existingUser.organizationId) {
@@ -1730,6 +1835,7 @@ class TurnkeyClient {
1730
1835
  userId: userId,
1731
1836
  userEmail: email,
1732
1837
  ...(verificationToken && { verificationToken }),
1838
+ ...(organizationId && { organizationId }),
1733
1839
  }, stampWith);
1734
1840
  if (!res || !res.userId) {
1735
1841
  throw new sdkTypes.TurnkeyError("No user ID found in the update user email response", sdkTypes.TurnkeyErrorCodes.BAD_RESPONSE);
@@ -1750,20 +1856,22 @@ class TurnkeyClient {
1750
1856
  *
1751
1857
  * @param params.userId - user ID to remove a specific user's email address (defaults to the current session's userId).
1752
1858
  * @param params.stampWith - parameter to stamp the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
1859
+ * @param params.organizationId - organization ID to specify the sub-organization (defaults to the current session's organizationId).
1753
1860
  * @returns A promise that resolves to the userId of the user whose email was removed.
1754
1861
  * @throws {TurnkeyError} If there is no active session, if the userId is missing, or if there is an error removing the user email.
1755
1862
  */
1756
1863
  this.removeUserEmail = async (params) => {
1757
- const { stampWith } = params || {};
1758
- const session = await this.storageManager.getActiveSession();
1759
- if (!session) {
1760
- throw new sdkTypes.TurnkeyError("No active session found. Please log in first.", sdkTypes.TurnkeyErrorCodes.NO_SESSION_FOUND);
1761
- }
1864
+ const { stampWith, organizationId } = params || {};
1865
+ const session = await utils.getActiveSessionOrThrowIfRequired(stampWith, this.storageManager.getActiveSession);
1762
1866
  return utils.withTurnkeyErrorHandling(async () => {
1763
- const userId = params?.userId || session.userId;
1867
+ const userId = params?.userId || session?.userId;
1868
+ if (!userId) {
1869
+ throw new sdkTypes.TurnkeyError("User ID must be provided to remove user email", sdkTypes.TurnkeyErrorCodes.INVALID_REQUEST);
1870
+ }
1764
1871
  const res = await this.httpClient.updateUserEmail({
1765
1872
  userId: userId,
1766
1873
  userEmail: "",
1874
+ ...(organizationId && { organizationId }),
1767
1875
  }, stampWith);
1768
1876
  if (!res || !res.userId) {
1769
1877
  throw new sdkTypes.TurnkeyError("No user ID found in the remove user email response", sdkTypes.TurnkeyErrorCodes.BAD_RESPONSE);
@@ -1787,21 +1895,23 @@ class TurnkeyClient {
1787
1895
  * @param params.verificationToken - verification token from OTP phone verification (required if verifying the phone number).
1788
1896
  * @param params.userId - user ID to update a specific user's phone number (defaults to the current session's userId).
1789
1897
  * @param params.stampWith - parameter to stamp the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
1898
+ * @param params.organizationId - organization ID to specify the sub-organization (defaults to the current session's organizationId).
1790
1899
  * @returns A promise that resolves to the userId of the updated user.
1791
1900
  * @throws {TurnkeyError} If there is no active session, if the userId is missing, or if there is an error updating or verifying the user phone number.
1792
1901
  */
1793
1902
  this.updateUserPhoneNumber = async (params) => {
1794
- const { verificationToken, phoneNumber, stampWith } = params;
1795
- const session = await this.storageManager.getActiveSession();
1796
- if (!session) {
1797
- throw new sdkTypes.TurnkeyError("No active session found. Please log in first.", sdkTypes.TurnkeyErrorCodes.NO_SESSION_FOUND);
1903
+ const { verificationToken, phoneNumber, stampWith, organizationId } = params;
1904
+ const session = await utils.getActiveSessionOrThrowIfRequired(stampWith, this.storageManager.getActiveSession);
1905
+ const userId = params?.userId || session?.userId;
1906
+ if (!userId) {
1907
+ throw new sdkTypes.TurnkeyError("User ID must be provided to update user phone number", sdkTypes.TurnkeyErrorCodes.INVALID_REQUEST);
1798
1908
  }
1799
- const userId = params?.userId || session.userId;
1800
1909
  return utils.withTurnkeyErrorHandling(async () => {
1801
1910
  const res = await this.httpClient.updateUserPhoneNumber({
1802
1911
  userId,
1803
1912
  userPhoneNumber: phoneNumber,
1804
1913
  ...(verificationToken && { verificationToken }),
1914
+ ...(organizationId && { organizationId }),
1805
1915
  }, stampWith);
1806
1916
  if (!res || !res.userId) {
1807
1917
  throw new sdkTypes.TurnkeyError("Failed to update user phone number", sdkTypes.TurnkeyErrorCodes.UPDATE_USER_PHONE_NUMBER_ERROR);
@@ -1822,20 +1932,22 @@ class TurnkeyClient {
1822
1932
  *
1823
1933
  * @param params.userId - user ID to remove a specific user's phone number (defaults to the current session's userId).
1824
1934
  * @param params.stampWith - parameter to stamp the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
1935
+ * @param params.organizationId - organization ID to specify the sub-organization (defaults to the current session's organizationId).
1825
1936
  * @returns A promise that resolves to the userId of the user whose phone number was removed.
1826
1937
  * @throws {TurnkeyError} If there is no active session, if the userId is missing, or if there is an error removing the user phone number.
1827
1938
  */
1828
1939
  this.removeUserPhoneNumber = async (params) => {
1829
- const { stampWith } = params || {};
1830
- const session = await this.storageManager.getActiveSession();
1831
- if (!session) {
1832
- throw new sdkTypes.TurnkeyError("No active session found. Please log in first.", sdkTypes.TurnkeyErrorCodes.NO_SESSION_FOUND);
1940
+ const { stampWith, organizationId } = params || {};
1941
+ const session = await utils.getActiveSessionOrThrowIfRequired(stampWith, this.storageManager.getActiveSession);
1942
+ const userId = params?.userId || session?.userId;
1943
+ if (!userId) {
1944
+ throw new sdkTypes.TurnkeyError("User ID must be provided to remove user phone number", sdkTypes.TurnkeyErrorCodes.INVALID_REQUEST);
1833
1945
  }
1834
- const userId = params?.userId || session.userId;
1835
1946
  return utils.withTurnkeyErrorHandling(async () => {
1836
1947
  const res = await this.httpClient.updateUserPhoneNumber({
1837
1948
  userId,
1838
1949
  userPhoneNumber: "",
1950
+ ...(organizationId && { organizationId }),
1839
1951
  }, stampWith);
1840
1952
  if (!res || !res.userId) {
1841
1953
  throw new sdkTypes.TurnkeyError("Failed to remove user phone number", sdkTypes.TurnkeyErrorCodes.UPDATE_USER_PHONE_NUMBER_ERROR);
@@ -1858,20 +1970,22 @@ class TurnkeyClient {
1858
1970
  * @param params.userName - new name to set for the user.
1859
1971
  * @param params.userId - user ID to update a specific user's name (defaults to the current session's userId).
1860
1972
  * @param params.stampWith - parameter to stamp the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
1973
+ * @param params.organizationId - organization ID to specify the sub-organization (defaults to the current session's organizationId).
1861
1974
  * @returns A promise that resolves to the userId of the updated user.
1862
1975
  * @throws {TurnkeyError} If there is no active session, if the userId is missing, or if there is an error updating the user name.
1863
1976
  */
1864
1977
  this.updateUserName = async (params) => {
1865
- const { userName, stampWith } = params;
1866
- const session = await this.storageManager.getActiveSession();
1867
- if (!session) {
1868
- throw new sdkTypes.TurnkeyError("No active session found. Please log in first.", sdkTypes.TurnkeyErrorCodes.NO_SESSION_FOUND);
1978
+ const { userName, stampWith, organizationId } = params;
1979
+ const session = await utils.getActiveSessionOrThrowIfRequired(stampWith, this.storageManager.getActiveSession);
1980
+ const userId = params?.userId || session?.userId;
1981
+ if (!userId) {
1982
+ throw new sdkTypes.TurnkeyError("User ID must be provided to update user name", sdkTypes.TurnkeyErrorCodes.INVALID_REQUEST);
1869
1983
  }
1870
- const userId = params?.userId || session.userId;
1871
1984
  return utils.withTurnkeyErrorHandling(async () => {
1872
1985
  const res = await this.httpClient.updateUserName({
1873
1986
  userId,
1874
1987
  userName,
1988
+ ...(organizationId && { organizationId }),
1875
1989
  }, stampWith);
1876
1990
  if (!res || !res.userId) {
1877
1991
  throw new sdkTypes.TurnkeyError("No user ID found in the update user name response", sdkTypes.TurnkeyErrorCodes.BAD_RESPONSE);
@@ -1894,6 +2008,7 @@ class TurnkeyClient {
1894
2008
  *
1895
2009
  * @param params.providerName - name of the OAuth provider to add (e.g., "Google", "Apple").
1896
2010
  * @param params.oidcToken - OIDC token for the OAuth provider.
2011
+ * @param params.organizationId - organization ID to specify the sub-organization (defaults to the current session's organizationId).
1897
2012
  * @param params.userId - user ID to add the provider for a specific user (defaults to current session's userId).
1898
2013
  * @param params.stampWith - parameter to stamp the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
1899
2014
  * @returns A promise that resolves to an array of provider IDs associated with the user.
@@ -1901,29 +2016,34 @@ class TurnkeyClient {
1901
2016
  */
1902
2017
  this.addOauthProvider = async (params) => {
1903
2018
  const { providerName, oidcToken, stampWith } = params;
1904
- const session = await this.storageManager.getActiveSession();
1905
- if (!session) {
1906
- throw new sdkTypes.TurnkeyError("No active session found. Please log in first.", sdkTypes.TurnkeyErrorCodes.NO_SESSION_FOUND);
1907
- }
2019
+ const session = await utils.getActiveSessionOrThrowIfRequired(stampWith, this.storageManager.getActiveSession);
1908
2020
  return utils.withTurnkeyErrorHandling(async () => {
1909
2021
  const accountRes = await this.httpClient.proxyGetAccount({
1910
2022
  filterType: "OIDC_TOKEN",
1911
2023
  filterValue: oidcToken,
1912
2024
  });
1913
2025
  if (!accountRes) {
1914
- throw new sdkTypes.TurnkeyError(`Account fetch failed}`, sdkTypes.TurnkeyErrorCodes.ACCOUNT_FETCH_ERROR);
2026
+ throw new sdkTypes.TurnkeyError(`Account fetch failed`, sdkTypes.TurnkeyErrorCodes.ACCOUNT_FETCH_ERROR);
1915
2027
  }
1916
2028
  if (accountRes.organizationId) {
1917
2029
  throw new sdkTypes.TurnkeyError("Account already exists with this OIDC token", sdkTypes.TurnkeyErrorCodes.ACCOUNT_ALREADY_EXISTS);
1918
2030
  }
1919
- const userId = params?.userId || session.userId;
1920
- const { email: oidcEmail, iss } = jwtDecode.jwtDecode(oidcToken) || {}; // Parse the oidc token so we can get the email. Pass it in to updateUser then call createOauthProviders. This will be verified by Turnkey.
2031
+ const userId = params?.userId || session?.userId;
2032
+ if (!userId) {
2033
+ throw new sdkTypes.TurnkeyError("User ID must be provided to add OAuth provider", sdkTypes.TurnkeyErrorCodes.INVALID_REQUEST);
2034
+ }
2035
+ const organizationId = params?.organizationId ?? session?.organizationId;
2036
+ if (!organizationId) {
2037
+ throw new sdkTypes.TurnkeyError("Organization ID is required to add OAuth provider", sdkTypes.TurnkeyErrorCodes.INVALID_REQUEST);
2038
+ }
2039
+ // parse the oidc token so we can get the email. Pass it in to updateUser then call createOauthProviders. This will be verified by Turnkey.
2040
+ const { email: oidcEmail, iss } = jwtDecode.jwtDecode(oidcToken) || {};
1921
2041
  if (iss === utils.googleISS) {
1922
2042
  const verifiedSuborg = await this.httpClient.proxyGetAccount({
1923
2043
  filterType: "EMAIL",
1924
2044
  filterValue: oidcEmail,
1925
2045
  });
1926
- const isVerified = verifiedSuborg.organizationId === session.organizationId;
2046
+ const isVerified = verifiedSuborg.organizationId === organizationId;
1927
2047
  const user = await this.fetchUser({
1928
2048
  userId,
1929
2049
  stampWith,
@@ -1966,20 +2086,22 @@ class TurnkeyClient {
1966
2086
  * @param params.providerIds - IDs of the OAuth providers to remove.
1967
2087
  * @param params.userId - user ID to remove the provider for a specific user (defaults to the current session's userId).
1968
2088
  * @param params.stampWith - parameter to stamp the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
2089
+ * @param params.organizationId - organization ID to specify the sub-organization (defaults to the current session's organizationId).
1969
2090
  * @returns A promise that resolves to an array of provider IDs that were removed.
1970
2091
  * @throws {TurnkeyError} If there is no active session, if the userId is missing, or if there is an error removing the OAuth provider.
1971
2092
  */
1972
2093
  this.removeOauthProviders = async (params) => {
1973
- const { providerIds, stampWith } = params;
1974
- const session = await this.storageManager.getActiveSession();
1975
- if (!session) {
1976
- throw new sdkTypes.TurnkeyError("No active session found. Please log in first.", sdkTypes.TurnkeyErrorCodes.NO_SESSION_FOUND);
2094
+ const { providerIds, stampWith, organizationId } = params;
2095
+ const session = await utils.getActiveSessionOrThrowIfRequired(stampWith, this.storageManager.getActiveSession);
2096
+ const userId = params?.userId || session?.userId;
2097
+ if (!userId) {
2098
+ throw new sdkTypes.TurnkeyError("User ID must be provided to remove OAuth provider", sdkTypes.TurnkeyErrorCodes.INVALID_REQUEST);
1977
2099
  }
1978
- const userId = params?.userId || session.userId;
1979
2100
  return utils.withTurnkeyErrorHandling(async () => {
1980
2101
  const res = await this.httpClient.deleteOauthProviders({
1981
2102
  userId,
1982
2103
  providerIds,
2104
+ ...(organizationId && { organizationId }),
1983
2105
  }, stampWith);
1984
2106
  if (!res) {
1985
2107
  throw new sdkTypes.TurnkeyError("Failed to remove OAuth provider", sdkTypes.TurnkeyErrorCodes.REMOVE_OAUTH_PROVIDER_ERROR);
@@ -2003,21 +2125,21 @@ class TurnkeyClient {
2003
2125
  * @param params.displayName - display name of the passkey (defaults to the value of `name`).
2004
2126
  * @param params.userId - user ID to add the passkey for a specific user (defaults to the current session's userId).
2005
2127
  * @param params.stampWith - parameter to stamp the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
2128
+ * @param params.organizationId - organization ID to specify the sub-organization (defaults to the current session's organizationId).
2006
2129
  * @returns A promise that resolves to an array of authenticator IDs for the newly added passkey(s).
2007
2130
  * @throws {TurnkeyError} If there is no active session, if passkey creation fails, or if there is an error adding the passkey.
2008
2131
  */
2009
2132
  this.addPasskey = async (params) => {
2010
- const { stampWith } = params || {};
2133
+ const { stampWith, organizationId } = params || {};
2011
2134
  const name = params?.name || `Turnkey Passkey-${Date.now()}`;
2012
2135
  return utils.withTurnkeyErrorHandling(async () => {
2013
- const session = await this.storageManager.getActiveSession();
2014
- if (!session) {
2015
- throw new sdkTypes.TurnkeyError("No active session found. Please log in first.", sdkTypes.TurnkeyErrorCodes.NO_SESSION_FOUND);
2136
+ const session = await utils.getActiveSessionOrThrowIfRequired(stampWith, this.storageManager.getActiveSession);
2137
+ const userId = params?.userId || session?.userId;
2138
+ if (!userId) {
2139
+ throw new sdkTypes.TurnkeyError("User ID must be provided to add passkey", sdkTypes.TurnkeyErrorCodes.INVALID_REQUEST);
2016
2140
  }
2017
- const userId = params?.userId || session.userId;
2018
2141
  const { encodedChallenge, attestation } = await this.createPasskey({
2019
2142
  name,
2020
- ...(stampWith && { stampWith }),
2021
2143
  });
2022
2144
  if (!attestation || !encodedChallenge) {
2023
2145
  throw new sdkTypes.TurnkeyError("Failed to create passkey challenge and attestation", sdkTypes.TurnkeyErrorCodes.CREATE_PASSKEY_ERROR);
@@ -2031,6 +2153,7 @@ class TurnkeyClient {
2031
2153
  attestation,
2032
2154
  },
2033
2155
  ],
2156
+ ...(organizationId && { organizationId }),
2034
2157
  }, stampWith);
2035
2158
  return res?.authenticatorIds || [];
2036
2159
  }, {
@@ -2050,20 +2173,22 @@ class TurnkeyClient {
2050
2173
  * @param params.authenticatorIds - IDs of the authenticators (passkeys) to remove.
2051
2174
  * @param params.userId - user ID to remove the passkeys for a specific user (defaults to the current session's userId).
2052
2175
  * @param params.stampWith - parameter to stamp the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
2176
+ * @param params.organizationId - organization ID to specify the sub-organization (defaults to the current session's organizationId).
2053
2177
  * @returns A promise that resolves to an array of authenticator IDs that were removed.
2054
2178
  * @throws {TurnkeyError} If there is no active session, if the userId is missing, or if there is an error removing the passkeys.
2055
2179
  */
2056
2180
  this.removePasskeys = async (params) => {
2057
- const { authenticatorIds, stampWith } = params;
2058
- const session = await this.storageManager.getActiveSession();
2059
- if (!session) {
2060
- throw new sdkTypes.TurnkeyError("No active session found. Please log in first.", sdkTypes.TurnkeyErrorCodes.NO_SESSION_FOUND);
2181
+ const { authenticatorIds, stampWith, organizationId } = params;
2182
+ const session = await utils.getActiveSessionOrThrowIfRequired(stampWith, this.storageManager.getActiveSession);
2183
+ const userId = params?.userId || session?.userId;
2184
+ if (!userId) {
2185
+ throw new sdkTypes.TurnkeyError("User ID must be provided to remove passkey", sdkTypes.TurnkeyErrorCodes.INVALID_REQUEST);
2061
2186
  }
2062
- const userId = params?.userId || session.userId;
2063
2187
  return utils.withTurnkeyErrorHandling(async () => {
2064
2188
  const res = await this.httpClient.deleteAuthenticators({
2065
2189
  userId,
2066
2190
  authenticatorIds,
2191
+ ...(organizationId && { organizationId }),
2067
2192
  }, stampWith);
2068
2193
  if (!res) {
2069
2194
  throw new sdkTypes.TurnkeyError("No response found in the remove passkey response", sdkTypes.TurnkeyErrorCodes.REMOVE_PASSKEY_ERROR);
@@ -2094,10 +2219,11 @@ class TurnkeyClient {
2094
2219
  * @throws {TurnkeyError} If there is no active session or if there is an error creating the wallet.
2095
2220
  */
2096
2221
  this.createWallet = async (params) => {
2097
- const { walletName, accounts, organizationId, mnemonicLength, stampWith } = params;
2098
- const session = await this.storageManager.getActiveSession();
2099
- if (!session) {
2100
- throw new sdkTypes.TurnkeyError("No active session found. Please log in first.", sdkTypes.TurnkeyErrorCodes.NO_SESSION_FOUND);
2222
+ const { walletName, accounts, organizationId: organizationIdFromParams, mnemonicLength, stampWith, } = params;
2223
+ const session = await utils.getActiveSessionOrThrowIfRequired(stampWith, this.storageManager.getActiveSession);
2224
+ const organizationId = organizationIdFromParams || session?.organizationId;
2225
+ if (!organizationId) {
2226
+ throw new sdkTypes.TurnkeyError("Organization ID must be provided to create wallet", sdkTypes.TurnkeyErrorCodes.INVALID_REQUEST);
2101
2227
  }
2102
2228
  let walletAccounts = [];
2103
2229
  if (accounts && !utils.isWalletAccountArray(accounts)) {
@@ -2113,7 +2239,7 @@ class TurnkeyClient {
2113
2239
  }
2114
2240
  return utils.withTurnkeyErrorHandling(async () => {
2115
2241
  const res = await this.httpClient.createWallet({
2116
- organizationId: organizationId || session.organizationId,
2242
+ organizationId: organizationId,
2117
2243
  walletName,
2118
2244
  accounts: walletAccounts,
2119
2245
  mnemonicLength: mnemonicLength || 12,
@@ -2145,10 +2271,11 @@ class TurnkeyClient {
2145
2271
  * @throws {TurnkeyError} If there is no active session, if the wallet does not exist, or if there is an error creating the wallet accounts.
2146
2272
  */
2147
2273
  this.createWalletAccounts = async (params) => {
2148
- const { accounts, walletId, organizationId, stampWith } = params;
2149
- const session = await this.storageManager.getActiveSession();
2150
- if (!session) {
2151
- throw new sdkTypes.TurnkeyError("No active session found. Please log in first.", sdkTypes.TurnkeyErrorCodes.NO_SESSION_FOUND);
2274
+ const { accounts, walletId, organizationId: organizationIdFromParams, stampWith, } = params;
2275
+ const session = await utils.getActiveSessionOrThrowIfRequired(stampWith, this.storageManager.getActiveSession);
2276
+ const organizationId = organizationIdFromParams || session?.organizationId;
2277
+ if (!organizationId) {
2278
+ throw new sdkTypes.TurnkeyError("Organization ID must be provided to create wallet accounts", sdkTypes.TurnkeyErrorCodes.INVALID_REQUEST);
2152
2279
  }
2153
2280
  return utils.withTurnkeyErrorHandling(async () => {
2154
2281
  let walletAccounts = [];
@@ -2156,7 +2283,7 @@ class TurnkeyClient {
2156
2283
  // Query existing wallet accounts to avoid duplicates
2157
2284
  const existingWalletAccounts = await this.httpClient.getWalletAccounts({
2158
2285
  walletId,
2159
- organizationId: organizationId || session.organizationId,
2286
+ organizationId: organizationId,
2160
2287
  paginationOptions: { limit: "100" },
2161
2288
  }, stampWith);
2162
2289
  walletAccounts = utils.generateWalletAccountsFromAddressFormat({
@@ -2168,7 +2295,7 @@ class TurnkeyClient {
2168
2295
  walletAccounts = accounts;
2169
2296
  }
2170
2297
  const res = await this.httpClient.createWalletAccounts({
2171
- organizationId: organizationId || session.organizationId,
2298
+ organizationId: organizationId,
2172
2299
  walletId,
2173
2300
  accounts: walletAccounts,
2174
2301
  }, stampWith);
@@ -2199,16 +2326,17 @@ class TurnkeyClient {
2199
2326
  * @throws {TurnkeyError} If there is no active session, if the targetPublicKey is missing, or if there is an error exporting the wallet.
2200
2327
  */
2201
2328
  this.exportWallet = async (params) => {
2202
- const { walletId, targetPublicKey, stampWith, organizationId } = params;
2203
- const session = await this.storageManager.getActiveSession();
2204
- if (!session) {
2205
- throw new sdkTypes.TurnkeyError("No active session found. Please log in first.", sdkTypes.TurnkeyErrorCodes.NO_SESSION_FOUND);
2329
+ const { walletId, targetPublicKey, stampWith, organizationId: organizationIdFromParams, } = params;
2330
+ const session = await utils.getActiveSessionOrThrowIfRequired(stampWith, this.storageManager.getActiveSession);
2331
+ const organizationId = organizationIdFromParams || session?.organizationId;
2332
+ if (!organizationId) {
2333
+ throw new sdkTypes.TurnkeyError("Organization ID must be provided to export wallet", sdkTypes.TurnkeyErrorCodes.INVALID_REQUEST);
2206
2334
  }
2207
2335
  return utils.withTurnkeyErrorHandling(async () => {
2208
2336
  const res = await this.httpClient.exportWallet({
2209
2337
  walletId,
2210
2338
  targetPublicKey,
2211
- organizationId: organizationId || session.organizationId,
2339
+ organizationId: organizationId,
2212
2340
  }, stampWith);
2213
2341
  if (!res.exportBundle) {
2214
2342
  throw new sdkTypes.TurnkeyError("No export bundle found in the response", sdkTypes.TurnkeyErrorCodes.BAD_RESPONSE);
@@ -2236,16 +2364,17 @@ class TurnkeyClient {
2236
2364
  * @throws {TurnkeyError} If there is no active session, if the targetPublicKey is missing, or if there is an error exporting the private key.
2237
2365
  */
2238
2366
  this.exportPrivateKey = async (params) => {
2239
- const { privateKeyId, targetPublicKey, stampWith, organizationId } = params;
2240
- const session = await this.storageManager.getActiveSession();
2241
- if (!session) {
2242
- throw new sdkTypes.TurnkeyError("No active session found. Please log in first.", sdkTypes.TurnkeyErrorCodes.NO_SESSION_FOUND);
2367
+ const { privateKeyId, targetPublicKey, stampWith, organizationId: organizationIdFromParams, } = params;
2368
+ const session = await utils.getActiveSessionOrThrowIfRequired(stampWith, this.storageManager.getActiveSession);
2369
+ const organizationId = organizationIdFromParams || session?.organizationId;
2370
+ if (!organizationId) {
2371
+ throw new sdkTypes.TurnkeyError("Organization ID must be provided to export private key", sdkTypes.TurnkeyErrorCodes.INVALID_REQUEST);
2243
2372
  }
2244
2373
  return utils.withTurnkeyErrorHandling(async () => {
2245
2374
  const res = await this.httpClient.exportPrivateKey({
2246
2375
  privateKeyId,
2247
2376
  targetPublicKey,
2248
- organizationId: organizationId || session.organizationId,
2377
+ organizationId: organizationId,
2249
2378
  }, stampWith);
2250
2379
  if (!res.exportBundle) {
2251
2380
  throw new sdkTypes.TurnkeyError("No export bundle found in the response", sdkTypes.TurnkeyErrorCodes.BAD_RESPONSE);
@@ -2274,16 +2403,17 @@ class TurnkeyClient {
2274
2403
  *
2275
2404
  */
2276
2405
  this.exportWalletAccount = async (params) => {
2277
- const { address, targetPublicKey, stampWith, organizationId } = params;
2278
- const session = await this.storageManager.getActiveSession();
2279
- if (!session) {
2280
- throw new sdkTypes.TurnkeyError("No active session found. Please log in first.", sdkTypes.TurnkeyErrorCodes.NO_SESSION_FOUND);
2406
+ const { address, targetPublicKey, stampWith, organizationId: organizationIdFromParams, } = params;
2407
+ const session = await utils.getActiveSessionOrThrowIfRequired(stampWith, this.storageManager.getActiveSession);
2408
+ const organizationId = organizationIdFromParams || session?.organizationId;
2409
+ if (!organizationId) {
2410
+ throw new sdkTypes.TurnkeyError("Organization ID must be provided to export wallet account", sdkTypes.TurnkeyErrorCodes.INVALID_REQUEST);
2281
2411
  }
2282
2412
  return utils.withTurnkeyErrorHandling(async () => {
2283
2413
  const res = await this.httpClient.exportWalletAccount({
2284
2414
  address,
2285
2415
  targetPublicKey,
2286
- organizationId: organizationId || session.organizationId,
2416
+ organizationId: organizationId,
2287
2417
  }, stampWith);
2288
2418
  if (!res.exportBundle) {
2289
2419
  throw new sdkTypes.TurnkeyError("No export bundle found in the response", sdkTypes.TurnkeyErrorCodes.BAD_RESPONSE);
@@ -2307,21 +2437,27 @@ class TurnkeyClient {
2307
2437
  * @param params.encryptedBundle - encrypted bundle containing the wallet seed phrase and metadata.
2308
2438
  * @param params.walletName - name of the wallet to create upon import.
2309
2439
  * @param params.accounts - array of account parameters to create in the imported wallet (defaults to standard Ethereum and Solana accounts).
2440
+ * @param params.organizationId - organization ID to import the wallet under a specific sub-organization (wallet will be associated with the sub-organization).
2310
2441
  * @param params.userId - user ID to import the wallet for a specific user (defaults to the current session's userId).
2311
2442
  * @param params.stampWith - parameter to stamp the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
2312
2443
  * @returns A promise that resolves to the ID of the imported wallet.
2313
2444
  * @throws {TurnkeyError} If there is no active session, if the encrypted bundle is invalid, or if there is an error importing the wallet.
2314
2445
  */
2315
2446
  this.importWallet = async (params) => {
2316
- const { encryptedBundle, accounts, walletName, userId, stampWith } = params;
2317
- const session = await this.storageManager.getActiveSession();
2318
- if (!session) {
2319
- throw new sdkTypes.TurnkeyError("No active session found. Please log in first.", sdkTypes.TurnkeyErrorCodes.NO_SESSION_FOUND);
2447
+ const { encryptedBundle, accounts, walletName, organizationId: organizationIdFromParams, userId: userIdFromParams, stampWith, } = params;
2448
+ const session = await utils.getActiveSessionOrThrowIfRequired(stampWith, this.storageManager.getActiveSession);
2449
+ const organizationId = organizationIdFromParams || session?.organizationId;
2450
+ if (!organizationId) {
2451
+ throw new sdkTypes.TurnkeyError("Organization ID must be provided to import wallet", sdkTypes.TurnkeyErrorCodes.INVALID_REQUEST);
2452
+ }
2453
+ const userId = userIdFromParams || session?.userId;
2454
+ if (!userId) {
2455
+ throw new sdkTypes.TurnkeyError("User ID must be provided to import wallet", sdkTypes.TurnkeyErrorCodes.INVALID_REQUEST);
2320
2456
  }
2321
2457
  return utils.withTurnkeyErrorHandling(async () => {
2322
2458
  const res = await this.httpClient.importWallet({
2323
- organizationId: session.organizationId,
2324
- userId: userId || session.userId,
2459
+ organizationId: organizationId,
2460
+ userId: userId,
2325
2461
  encryptedBundle,
2326
2462
  walletName,
2327
2463
  accounts: accounts || [
@@ -2359,21 +2495,27 @@ class TurnkeyClient {
2359
2495
  * @param params.privateKeyName - name of the private key to create upon import.
2360
2496
  * @param params.curve - the cryptographic curve used to generate a given private key
2361
2497
  * @param params.addressFormat - address format of the private key to import.
2498
+ * @param params.organizationId - organization ID to import the private key under a specific sub-organization (private key will be associated with the sub-organization).
2362
2499
  * @param params.userId - user ID to import the wallet for a specific user (defaults to the current session's userId).
2363
2500
  * @param params.stampWith - parameter to stamp the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
2364
2501
  * @returns A promise that resolves to the ID of the imported wallet.
2365
2502
  * @throws {TurnkeyError} If there is no active session, if the encrypted bundle is invalid, or if there is an error importing the wallet.
2366
2503
  */
2367
2504
  this.importPrivateKey = async (params) => {
2368
- const { encryptedBundle, privateKeyName, addressFormats, curve, userId, stampWith, } = params;
2369
- const session = await this.storageManager.getActiveSession();
2370
- if (!session) {
2371
- throw new sdkTypes.TurnkeyError("No active session found. Please log in first.", sdkTypes.TurnkeyErrorCodes.NO_SESSION_FOUND);
2505
+ const { encryptedBundle, privateKeyName, addressFormats, curve, organizationId: organizationIdFromParams, userId: userIdFromParams, stampWith, } = params;
2506
+ const session = await utils.getActiveSessionOrThrowIfRequired(stampWith, this.storageManager.getActiveSession);
2507
+ const organizationId = organizationIdFromParams || session?.organizationId;
2508
+ if (!organizationId) {
2509
+ throw new sdkTypes.TurnkeyError("Organization ID must be provided to import private key", sdkTypes.TurnkeyErrorCodes.INVALID_REQUEST);
2510
+ }
2511
+ const userId = userIdFromParams || session?.userId;
2512
+ if (!userId) {
2513
+ throw new sdkTypes.TurnkeyError("User ID must be provided to import private key", sdkTypes.TurnkeyErrorCodes.INVALID_REQUEST);
2372
2514
  }
2373
2515
  return utils.withTurnkeyErrorHandling(async () => {
2374
2516
  const res = await this.httpClient.importPrivateKey({
2375
- organizationId: session.organizationId,
2376
- userId: userId || session.userId,
2517
+ organizationId,
2518
+ userId,
2377
2519
  encryptedBundle,
2378
2520
  privateKeyName,
2379
2521
  curve,
@@ -2404,18 +2546,17 @@ class TurnkeyClient {
2404
2546
  * - Optionally allows stamping the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
2405
2547
  *
2406
2548
  * @param params.deleteWithoutExport - flag to delete the sub-organization without requiring all wallets to be exported first (defaults to false).
2549
+ * @param params.organizationId - organization ID to delete a specific sub-organization (defaults to the current session's organizationId).
2407
2550
  * @param params.stampWith - parameter to stamp the request with a specific stamper.
2408
2551
  * @returns A promise that resolves to a `TDeleteSubOrganizationResponse` object containing the result of the deletion.
2409
2552
  * @throws {TurnkeyError} If there is no active session or if there is an error deleting the sub-organization.
2410
2553
  */
2411
2554
  this.deleteSubOrganization = async (params) => {
2412
- const { deleteWithoutExport = false, stampWith } = params || {};
2413
- const session = await this.storageManager.getActiveSession();
2414
- if (!session) {
2415
- throw new sdkTypes.TurnkeyError("No active session found. Please log in first.", sdkTypes.TurnkeyErrorCodes.NO_SESSION_FOUND);
2416
- }
2555
+ const { deleteWithoutExport = false, organizationId: organizationIdFromParams, stampWith, } = params || {};
2556
+ const session = await utils.getActiveSessionOrThrowIfRequired(stampWith, this.storageManager.getActiveSession);
2557
+ const organizationId = organizationIdFromParams || session?.organizationId;
2417
2558
  return utils.withTurnkeyErrorHandling(async () => {
2418
- return await this.httpClient.deleteSubOrganization({ deleteWithoutExport }, stampWith);
2559
+ return await this.httpClient.deleteSubOrganization({ deleteWithoutExport, ...(organizationId && { organizationId }) }, stampWith);
2419
2560
  }, {
2420
2561
  errorMessage: "Failed to delete sub-organization",
2421
2562
  errorCode: sdkTypes.TurnkeyErrorCodes.DELETE_SUB_ORGANIZATION_ERROR,
@@ -2436,7 +2577,7 @@ class TurnkeyClient {
2436
2577
  * @throws {TurnkeyError} If there is an error storing the session or cleaning up key pairs.
2437
2578
  */
2438
2579
  this.storeSession = async (params) => {
2439
- const { sessionToken, sessionKey = base.SessionKey.DefaultSessionkey } = params;
2580
+ const { sessionToken, sessionKey = auth.SessionKey.DefaultSessionkey } = params;
2440
2581
  if (!sessionToken)
2441
2582
  return;
2442
2583
  utils.withTurnkeyErrorHandling(async () => {
@@ -2461,7 +2602,7 @@ class TurnkeyClient {
2461
2602
  * @throws {TurnkeyError} If the session does not exist or if there is an error clearing the session.
2462
2603
  */
2463
2604
  this.clearSession = async (params) => {
2464
- const { sessionKey = base.SessionKey.DefaultSessionkey } = params || {};
2605
+ const { sessionKey = auth.SessionKey.DefaultSessionkey } = params || {};
2465
2606
  utils.withTurnkeyErrorHandling(async () => {
2466
2607
  const session = await this.storageManager.getSession(sessionKey);
2467
2608
  if (session) {
@@ -2519,7 +2660,7 @@ class TurnkeyClient {
2519
2660
  * @throws {TurnkeyError} If the session key does not exist, if there is no active session, or if there is an error refreshing the session.
2520
2661
  */
2521
2662
  this.refreshSession = async (params) => {
2522
- const { sessionKey = await this.storageManager.getActiveSessionKey(), expirationSeconds = base.DEFAULT_SESSION_EXPIRATION_IN_SECONDS, publicKey, invalidateExisitng = false, } = params || {};
2663
+ const { sessionKey = await this.storageManager.getActiveSessionKey(), expirationSeconds = auth.DEFAULT_SESSION_EXPIRATION_IN_SECONDS, publicKey, invalidateExisitng = false, } = params || {};
2523
2664
  if (!sessionKey) {
2524
2665
  throw new sdkTypes.TurnkeyError("No session key provided or active session to refresh session", sdkTypes.TurnkeyErrorCodes.NO_SESSION_FOUND);
2525
2666
  }
@@ -2750,17 +2891,17 @@ class TurnkeyClient {
2750
2891
  async init() {
2751
2892
  // Initialize storage manager
2752
2893
  // TODO (Amir): StorageManager should be a class that extends StorageBase and has an init method
2753
- this.storageManager = await base$1.createStorageManager();
2894
+ this.storageManager = await base.createStorageManager();
2754
2895
  // Initialize the API key stamper
2755
- this.apiKeyStamper = new base$2.CrossPlatformApiKeyStamper(this.storageManager);
2896
+ this.apiKeyStamper = new base$1.CrossPlatformApiKeyStamper(this.storageManager);
2756
2897
  await this.apiKeyStamper.init();
2757
2898
  if (this.config.passkeyConfig) {
2758
- this.passkeyStamper = new base$3.CrossPlatformPasskeyStamper(this.config.passkeyConfig);
2899
+ this.passkeyStamper = new base$2.CrossPlatformPasskeyStamper(this.config.passkeyConfig);
2759
2900
  await this.passkeyStamper.init();
2760
2901
  }
2761
2902
  if (this.config.walletConfig?.features?.auth ||
2762
2903
  this.config.walletConfig?.features?.connecting) {
2763
- this.walletManager = await base$4.createWalletManager(this.config.walletConfig);
2904
+ this.walletManager = await base$3.createWalletManager(this.config.walletConfig);
2764
2905
  }
2765
2906
  // We can comfortably default to the prod urls here
2766
2907
  const apiBaseUrl = this.config.apiBaseUrl || "https://api.turnkey.com";