@turnkey/core 1.0.0 → 1.1.2

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 +162 -334
  2. package/dist/__clients__/core.d.ts.map +1 -1
  3. package/dist/__clients__/core.js +418 -275
  4. package/dist/__clients__/core.js.map +1 -1
  5. package/dist/__clients__/core.mjs +369 -226
  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 +36 -6
  10. package/dist/__generated__/sdk-client-base.js.map +1 -1
  11. package/dist/__generated__/sdk-client-base.mjs +31 -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 +3 -3
  43. package/dist/__storage__/mobile/storage.js.map +1 -1
  44. package/dist/__storage__/mobile/storage.mjs +1 -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 +3 -3
  49. package/dist/__storage__/web/storage.js.map +1 -1
  50. package/dist/__storage__/web/storage.mjs +1 -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 +119 -0
  55. package/dist/__types__/auth.d.ts.map +1 -0
  56. package/dist/__types__/auth.js +7 -0
  57. package/dist/__types__/auth.js.map +1 -0
  58. package/dist/__types__/auth.mjs +5 -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__/enums.d.ts +59 -0
  63. package/dist/__types__/enums.d.ts.map +1 -0
  64. package/dist/__types__/{base.js → enums.js} +28 -45
  65. package/dist/__types__/enums.js.map +1 -0
  66. package/dist/__types__/{base.mjs → enums.mjs} +29 -44
  67. package/dist/__types__/enums.mjs.map +1 -0
  68. package/dist/__types__/error.d.ts +13 -0
  69. package/dist/__types__/error.d.ts.map +1 -0
  70. package/dist/__types__/error.js +18 -0
  71. package/dist/__types__/error.js.map +1 -0
  72. package/dist/__types__/error.mjs +16 -0
  73. package/dist/__types__/error.mjs.map +1 -0
  74. package/dist/__types__/export.d.ts +10 -0
  75. package/dist/__types__/export.d.ts.map +1 -0
  76. package/dist/__types__/external-wallets.d.ts +176 -0
  77. package/dist/__types__/external-wallets.d.ts.map +1 -0
  78. package/dist/__types__/index.d.ts +8 -0
  79. package/dist/__types__/index.d.ts.map +1 -0
  80. package/dist/__types__/method-types.d.ts +315 -0
  81. package/dist/__types__/method-types.d.ts.map +1 -0
  82. package/dist/__wallet__/base.d.ts +1 -1
  83. package/dist/__wallet__/base.d.ts.map +1 -1
  84. package/dist/__wallet__/base.js.map +1 -1
  85. package/dist/__wallet__/base.mjs.map +1 -1
  86. package/dist/__wallet__/connector.d.ts +3 -3
  87. package/dist/__wallet__/connector.d.ts.map +1 -1
  88. package/dist/__wallet__/connector.js +4 -4
  89. package/dist/__wallet__/connector.js.map +1 -1
  90. package/dist/__wallet__/connector.mjs +3 -3
  91. package/dist/__wallet__/connector.mjs.map +1 -1
  92. package/dist/__wallet__/mobile/manager.d.ts +1 -1
  93. package/dist/__wallet__/mobile/manager.d.ts.map +1 -1
  94. package/dist/__wallet__/mobile/manager.js +4 -4
  95. package/dist/__wallet__/mobile/manager.js.map +1 -1
  96. package/dist/__wallet__/mobile/manager.mjs +1 -1
  97. package/dist/__wallet__/mobile/manager.mjs.map +1 -1
  98. package/dist/__wallet__/stamper.d.ts +1 -1
  99. package/dist/__wallet__/stamper.d.ts.map +1 -1
  100. package/dist/__wallet__/stamper.js +8 -8
  101. package/dist/__wallet__/stamper.js.map +1 -1
  102. package/dist/__wallet__/stamper.mjs +1 -1
  103. package/dist/__wallet__/stamper.mjs.map +1 -1
  104. package/dist/__wallet__/wallet-connect/base.d.ts +4 -2
  105. package/dist/__wallet__/wallet-connect/base.d.ts.map +1 -1
  106. package/dist/__wallet__/wallet-connect/base.js +68 -26
  107. package/dist/__wallet__/wallet-connect/base.js.map +1 -1
  108. package/dist/__wallet__/wallet-connect/base.mjs +53 -11
  109. package/dist/__wallet__/wallet-connect/base.mjs.map +1 -1
  110. package/dist/__wallet__/wallet-connect/client.d.ts +30 -9
  111. package/dist/__wallet__/wallet-connect/client.d.ts.map +1 -1
  112. package/dist/__wallet__/wallet-connect/client.js +73 -11
  113. package/dist/__wallet__/wallet-connect/client.js.map +1 -1
  114. package/dist/__wallet__/wallet-connect/client.mjs +73 -11
  115. package/dist/__wallet__/wallet-connect/client.mjs.map +1 -1
  116. package/dist/__wallet__/web/manager.d.ts +1 -1
  117. package/dist/__wallet__/web/manager.d.ts.map +1 -1
  118. package/dist/__wallet__/web/manager.js +10 -10
  119. package/dist/__wallet__/web/manager.js.map +1 -1
  120. package/dist/__wallet__/web/manager.mjs +1 -1
  121. package/dist/__wallet__/web/manager.mjs.map +1 -1
  122. package/dist/__wallet__/web/native/ethereum.d.ts +3 -3
  123. package/dist/__wallet__/web/native/ethereum.d.ts.map +1 -1
  124. package/dist/__wallet__/web/native/ethereum.js +10 -10
  125. package/dist/__wallet__/web/native/ethereum.js.map +1 -1
  126. package/dist/__wallet__/web/native/ethereum.mjs +3 -3
  127. package/dist/__wallet__/web/native/ethereum.mjs.map +1 -1
  128. package/dist/__wallet__/web/native/solana.d.ts +3 -3
  129. package/dist/__wallet__/web/native/solana.d.ts.map +1 -1
  130. package/dist/__wallet__/web/native/solana.js +11 -11
  131. package/dist/__wallet__/web/native/solana.js.map +1 -1
  132. package/dist/__wallet__/web/native/solana.mjs +6 -6
  133. package/dist/__wallet__/web/native/solana.mjs.map +1 -1
  134. package/dist/index.d.ts +8 -1
  135. package/dist/index.d.ts.map +1 -1
  136. package/dist/index.js +22 -14
  137. package/dist/index.js.map +1 -1
  138. package/dist/index.mjs +4 -2
  139. package/dist/index.mjs.map +1 -1
  140. package/dist/turnkey-helpers.js.map +1 -1
  141. package/dist/turnkey-helpers.mjs.map +1 -1
  142. package/dist/utils.d.ts +4 -18
  143. package/dist/utils.d.ts.map +1 -1
  144. package/dist/utils.js +95 -32
  145. package/dist/utils.js.map +1 -1
  146. package/dist/utils.mjs +74 -13
  147. package/dist/utils.mjs.map +1 -1
  148. package/package.json +6 -6
  149. package/dist/__types__/base.d.ts +0 -527
  150. package/dist/__types__/base.d.ts.map +0 -1
  151. package/dist/__types__/base.js.map +0 -1
  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 enums = require('../__types__/enums.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 || enums.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
+ }, enums.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 = enums.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 === enums.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 || enums.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
+ }, enums.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 = enums.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 || enums.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
+ }, enums.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 enums.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 enums.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: enums.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: enums.OtpTypeToFilterTypeMap[otpType],
737
749
  filterValue: contact,
738
750
  });
739
751
  if (!accountRes) {
@@ -766,6 +778,7 @@ class TurnkeyClient {
766
778
  *
767
779
  * @param params.verificationToken - verification token received after OTP verification.
768
780
  * @param params.publicKey - public key to use for authentication. If not provided, a new key pair will be generated.
781
+ * @param params.organizationId - optional organization ID to target (defaults to the verified subOrg ID linked to the verification token contact).
769
782
  * @param params.invalidateExisting - flag to invalidate existing session for the user.
770
783
  * @param params.sessionKey - session key to use for session creation (defaults to the default session key).
771
784
  * @returns A promise that resolves to a {@link BaseAuthResult}, which includes:
@@ -773,12 +786,13 @@ class TurnkeyClient {
773
786
  * @throws {TurnkeyError} If there is an error during the OTP login process or if key pair cleanup fails.
774
787
  */
775
788
  this.loginWithOtp = async (params) => {
776
- const { verificationToken, invalidateExisting = false, publicKey = await this.apiKeyStamper?.createKeyPair(), sessionKey = base.SessionKey.DefaultSessionkey, } = params;
789
+ const { verificationToken, invalidateExisting = false, publicKey = await this.apiKeyStamper?.createKeyPair(), organizationId, sessionKey = enums.SessionKey.DefaultSessionkey, } = params;
777
790
  return utils.withTurnkeyErrorHandling(async () => {
778
791
  const res = await this.httpClient.proxyOtpLogin({
779
792
  verificationToken,
780
793
  publicKey: publicKey,
781
794
  invalidateExisting,
795
+ ...(organizationId && { organizationId }),
782
796
  });
783
797
  if (!res) {
784
798
  throw new sdkTypes.TurnkeyError(`Auth proxy OTP login failed`, sdkTypes.TurnkeyErrorCodes.OTP_LOGIN_ERROR);
@@ -834,7 +848,7 @@ class TurnkeyClient {
834
848
  const signUpBody = utils.buildSignUpBody({
835
849
  createSubOrgParams: {
836
850
  ...createSubOrgParams,
837
- ...(otpType === base.OtpType.Email
851
+ ...(otpType === enums.OtpType.Email
838
852
  ? { userEmail: contact }
839
853
  : { userPhoneNumber: contact }),
840
854
  verificationToken,
@@ -946,7 +960,7 @@ class TurnkeyClient {
946
960
  * @throws {TurnkeyError} If there is an error during the OAuth completion process, such as account lookup, sign-up, or login.
947
961
  */
948
962
  this.completeOauth = async (params) => {
949
- const { oidcToken, publicKey, createSubOrgParams, providerName = "OpenID Connect Provider" + " " + Date.now(), sessionKey = base.SessionKey.DefaultSessionkey, invalidateExisting = false, } = params;
963
+ const { oidcToken, publicKey, createSubOrgParams, providerName = "OpenID Connect Provider" + " " + Date.now(), sessionKey = enums.SessionKey.DefaultSessionkey, invalidateExisting = false, } = params;
950
964
  return utils.withTurnkeyErrorHandling(async () => {
951
965
  const accountRes = await this.httpClient.proxyGetAccount({
952
966
  filterType: "OIDC_TOKEN",
@@ -1005,7 +1019,7 @@ class TurnkeyClient {
1005
1019
  * @throws {TurnkeyError} If there is an error during the OAuth login process or if key pair cleanup fails.
1006
1020
  */
1007
1021
  this.loginWithOauth = async (params) => {
1008
- const { oidcToken, invalidateExisting = false, publicKey, sessionKey = base.SessionKey.DefaultSessionkey, } = params;
1022
+ const { oidcToken, invalidateExisting = false, publicKey, sessionKey = enums.SessionKey.DefaultSessionkey, } = params;
1009
1023
  return utils.withTurnkeyErrorHandling(async () => {
1010
1024
  if (!publicKey) {
1011
1025
  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 +1116,61 @@ class TurnkeyClient {
1102
1116
  * - Returns both embedded and connected wallets in a single array, each with their respective accounts populated.
1103
1117
  * - Optionally allows stamping the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
1104
1118
  *
1105
- * @param params.stampWith - parameter to stamp the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
1106
1119
  * @param params.walletProviders - array of wallet providers to use for fetching wallets.
1120
+ * @param params.organizationId - organization ID to target (defaults to the session's organization ID).
1121
+ * @param params.userId - user ID to target (defaults to the session's user ID).
1122
+ * @param params.connectedOnly - if true, fetches only connected wallets; if false or undefined, fetches both embedded and connected wallets.
1123
+ * @param params.stampWith - parameter to stamp the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
1107
1124
  * @returns A promise that resolves to an array of `Wallet` objects.
1108
1125
  * @throws {TurnkeyError} If no active session is found or if there is an error fetching wallets.
1109
1126
  */
1110
1127
  this.fetchWallets = async (params) => {
1111
- const { stampWith, walletProviders } = params || {};
1128
+ const { walletProviders, organizationId: organizationIdFromParams, userId: userIdFromParams, connectedOnly, stampWith, } = params || {};
1112
1129
  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);
1130
+ if (!session && !connectedOnly) {
1131
+ 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);
1132
+ }
1133
+ // if `connectedOnly` is true, we need to make sure the walletManager is initialized
1134
+ // or else we can't fetch connected wallets, and we throw an error
1135
+ if (connectedOnly && !this.walletManager?.connector) {
1136
+ throw new sdkTypes.TurnkeyError("Wallet connector is not initialized", sdkTypes.TurnkeyErrorCodes.WALLET_MANAGER_COMPONENT_NOT_INITIALIZED);
1115
1137
  }
1116
1138
  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
- }));
1139
+ let embedded = [];
1140
+ // if connectedOnly is true, we skip fetching embedded wallets
1141
+ if (!connectedOnly) {
1142
+ const organizationId = organizationIdFromParams || session?.organizationId;
1143
+ if (!organizationId) {
1144
+ 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);
1145
+ }
1146
+ const userId = userIdFromParams || session?.userId;
1147
+ if (!userId) {
1148
+ 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);
1149
+ }
1150
+ const res = await this.httpClient.getWalletAccounts({
1151
+ organizationId,
1152
+ includeWalletDetails: true,
1153
+ }, stampWith);
1154
+ const walletsRes = await this.httpClient.getWallets({
1155
+ organizationId,
1156
+ }, stampWith);
1157
+ if (!res || !res.accounts) {
1158
+ throw new sdkTypes.TurnkeyError("No wallet accounts found in the response", sdkTypes.TurnkeyErrorCodes.BAD_RESPONSE);
1159
+ }
1160
+ // create a map of walletId to EmbeddedWallet for easy lookup
1161
+ const walletMap = new Map(walletsRes.wallets.map((wallet) => [
1162
+ wallet.walletId,
1163
+ {
1164
+ ...wallet,
1165
+ source: enums.WalletSource.Embedded,
1166
+ accounts: [],
1167
+ },
1168
+ ]));
1169
+ // map the accounts to their respective wallets
1170
+ embedded = utils.mapAccountsToWallet(res.accounts, walletMap);
1171
+ }
1134
1172
  // if wallet connecting is disabled we return only embedded wallets
1173
+ // this will never be hit if `connectedOnly` is true because of the check above
1135
1174
  if (!this.walletManager?.connector)
1136
1175
  return embedded;
1137
1176
  const providers = walletProviders ?? (await this.fetchWalletProviders());
@@ -1145,10 +1184,14 @@ class TurnkeyClient {
1145
1184
  group.push(provider);
1146
1185
  groupedProviders.set(walletId, group);
1147
1186
  }
1148
- const connected = (await Promise.all(Array.from(groupedProviders.entries()).map(async ([walletId, grouped]) => {
1187
+ // has to be done in a for of loop so we can await each fetchWalletAccounts call individually
1188
+ // otherwise await Promise.all would cause them all to fire at once breaking passkey only set ups
1189
+ // (multiple wallet fetches at once causing "OperationError: A request is already pending.")
1190
+ let connected = [];
1191
+ for (const [walletId, grouped] of groupedProviders.entries()) {
1149
1192
  const timestamp = utils.toExternalTimestamp();
1150
1193
  const wallet = {
1151
- source: base.WalletSource.Connected,
1194
+ source: enums.WalletSource.Connected,
1152
1195
  walletId,
1153
1196
  walletName: grouped[0]?.info?.name ?? "Unknown",
1154
1197
  createdAt: timestamp,
@@ -1161,10 +1204,16 @@ class TurnkeyClient {
1161
1204
  wallet,
1162
1205
  walletProviders: grouped,
1163
1206
  ...(stampWith !== undefined && { stampWith }),
1207
+ ...(organizationIdFromParams !== undefined && {
1208
+ organizationId: organizationIdFromParams,
1209
+ }),
1210
+ ...(userIdFromParams !== undefined && { userId: userIdFromParams }),
1164
1211
  });
1165
1212
  wallet.accounts = accounts;
1166
- return wallet;
1167
- }))).filter((wallet) => wallet.accounts.length > 0);
1213
+ if (wallet.accounts.length > 0) {
1214
+ connected.push(wallet);
1215
+ }
1216
+ }
1168
1217
  return [...embedded, ...connected];
1169
1218
  }, {
1170
1219
  errorMessage: "Failed to fetch wallets",
@@ -1184,22 +1233,30 @@ class TurnkeyClient {
1184
1233
  * @param params.walletProviders - list of wallet providers to filter by (used for connected wallets).
1185
1234
  * @param params.paginationOptions - pagination options for embedded wallets.
1186
1235
  * @param params.stampWith - parameter to stamp the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
1236
+ * @param params.organizationId - organization ID to target (defaults to the session's organization ID).
1237
+ * @param params.userId - user ID to target (defaults to the session's user ID).
1238
+ *
1187
1239
  * @returns A promise that resolves to an array of `v1WalletAccount` objects.
1188
1240
  * @throws {TurnkeyError} If no active session is found or if there is an error fetching wallet accounts.
1189
1241
  */
1190
1242
  this.fetchWalletAccounts = async (params) => {
1191
1243
  const { wallet, stampWith, walletProviders, paginationOptions } = params;
1192
1244
  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
- }
1245
+ const organizationId = params?.organizationId || session?.organizationId;
1246
+ const userId = params?.userId || session?.userId;
1196
1247
  return utils.withTurnkeyErrorHandling(async () => {
1197
1248
  // this is an embedded wallet so we fetch accounts from Turnkey
1198
- if (wallet.source === base.WalletSource.Embedded) {
1249
+ if (wallet.source === enums.WalletSource.Embedded) {
1199
1250
  const embedded = [];
1251
+ if (!organizationId) {
1252
+ 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);
1253
+ }
1254
+ if (!userId) {
1255
+ 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);
1256
+ }
1200
1257
  const res = await this.httpClient.getWalletAccounts({
1201
1258
  walletId: wallet.walletId,
1202
- organizationId: session.organizationId,
1259
+ organizationId,
1203
1260
  paginationOptions: paginationOptions || { limit: "100" },
1204
1261
  }, stampWith);
1205
1262
  if (!res || !res.accounts) {
@@ -1208,7 +1265,7 @@ class TurnkeyClient {
1208
1265
  for (const account of res.accounts) {
1209
1266
  embedded.push({
1210
1267
  ...account,
1211
- source: base.WalletSource.Embedded,
1268
+ source: enums.WalletSource.Embedded,
1212
1269
  });
1213
1270
  }
1214
1271
  return embedded;
@@ -1230,31 +1287,40 @@ class TurnkeyClient {
1230
1287
  const matching = providers.filter((p) => p.info?.name?.toLowerCase().replace(/\s+/g, "-") ===
1231
1288
  wallet.walletId && p.connectedAddresses.length > 0);
1232
1289
  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);
1290
+ let ethereumAddresses = [];
1291
+ let solanaAddresses = [];
1292
+ // we only fetch the user if we have to the organizationId and userId
1293
+ // if not that means `isAuthenticator` will always be false
1294
+ if (organizationId && userId) {
1295
+ const user = await this.fetchUser({
1296
+ userId,
1297
+ organizationId,
1298
+ stampWith,
1299
+ });
1300
+ ({ ethereum: ethereumAddresses, solana: solanaAddresses } =
1301
+ utils.getAuthenticatorAddresses(user));
1302
+ }
1237
1303
  for (const provider of matching) {
1238
1304
  const timestamp = utils.toExternalTimestamp();
1239
1305
  for (const address of provider.connectedAddresses) {
1240
1306
  if (utils.isEthereumProvider(provider)) {
1241
1307
  const evmAccount = {
1242
1308
  walletAccountId: `${wallet.walletId}-${provider.interfaceType}-${address}`,
1243
- organizationId: session.organizationId,
1309
+ organizationId: organizationId ?? "",
1244
1310
  walletId: wallet.walletId,
1245
1311
  pathFormat: "PATH_FORMAT_BIP32",
1246
- path: base.WalletSource.Connected,
1247
- source: base.WalletSource.Connected,
1312
+ path: enums.WalletSource.Connected,
1313
+ source: enums.WalletSource.Connected,
1248
1314
  address,
1249
1315
  createdAt: timestamp,
1250
1316
  updatedAt: timestamp,
1251
1317
  // ethereum specific
1252
- curve: base.Curve.SECP256K1,
1318
+ curve: enums.Curve.SECP256K1,
1253
1319
  addressFormat: "ADDRESS_FORMAT_ETHEREUM",
1254
1320
  chainInfo: provider.chainInfo,
1255
1321
  isAuthenticator: ethereumAddresses.includes(address.toLowerCase()),
1256
- signMessage: (msg) => sign(msg, provider, base.SignIntent.SignMessage),
1257
- signAndSendTransaction: (tx) => sign(tx, provider, base.SignIntent.SignAndSendTransaction),
1322
+ signMessage: (msg) => sign(msg, provider, enums.SignIntent.SignMessage),
1323
+ signAndSendTransaction: (tx) => sign(tx, provider, enums.SignIntent.SignAndSendTransaction),
1258
1324
  };
1259
1325
  connected.push(evmAccount);
1260
1326
  continue;
@@ -1262,22 +1328,22 @@ class TurnkeyClient {
1262
1328
  if (utils.isSolanaProvider(provider)) {
1263
1329
  const solAccount = {
1264
1330
  walletAccountId: `${wallet.walletId}-${provider.interfaceType}-${address}`,
1265
- organizationId: session.organizationId,
1331
+ organizationId: organizationId ?? "",
1266
1332
  walletId: wallet.walletId,
1267
1333
  pathFormat: "PATH_FORMAT_BIP32",
1268
- path: base.WalletSource.Connected,
1269
- source: base.WalletSource.Connected,
1334
+ path: enums.WalletSource.Connected,
1335
+ source: enums.WalletSource.Connected,
1270
1336
  address,
1271
1337
  createdAt: timestamp,
1272
1338
  updatedAt: timestamp,
1273
1339
  // solana specific
1274
1340
  publicKey: address,
1275
- curve: base.Curve.ED25519,
1341
+ curve: enums.Curve.ED25519,
1276
1342
  addressFormat: "ADDRESS_FORMAT_SOLANA",
1277
1343
  chainInfo: provider.chainInfo,
1278
1344
  isAuthenticator: solanaAddresses.includes(address),
1279
- signMessage: (msg) => sign(msg, provider, base.SignIntent.SignMessage),
1280
- signTransaction: (tx) => sign(tx, provider, base.SignIntent.SignTransaction),
1345
+ signMessage: (msg) => sign(msg, provider, enums.SignIntent.SignMessage),
1346
+ signTransaction: (tx) => sign(tx, provider, enums.SignIntent.SignTransaction),
1281
1347
  };
1282
1348
  connected.push(solAccount);
1283
1349
  continue;
@@ -1298,17 +1364,19 @@ class TurnkeyClient {
1298
1364
  * - Supports stamping the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
1299
1365
  *
1300
1366
  * @param params.stampWith - parameter to stamp the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
1367
+ * @param params.organizationId - organization ID to target (defaults to the session's organization ID).
1301
1368
  * @returns A promise that resolves to an array of `v1PrivateKey` objects.
1302
1369
  * @throws {TurnkeyError} If no active session is found or if there is an error fetching private keys.
1303
1370
  */
1304
1371
  this.fetchPrivateKeys = async (params) => {
1305
1372
  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);
1373
+ const session = await utils.getActiveSessionOrThrowIfRequired(stampWith, this.storageManager.getActiveSession);
1374
+ const organizationId = params?.organizationId || session?.organizationId;
1375
+ if (!organizationId) {
1376
+ 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
1377
  }
1310
1378
  return utils.withTurnkeyErrorHandling(async () => {
1311
- const res = await this.httpClient.getPrivateKeys({ organizationId: session.organizationId }, stampWith);
1379
+ const res = await this.httpClient.getPrivateKeys({ organizationId }, stampWith);
1312
1380
  if (!res) {
1313
1381
  throw new sdkTypes.TurnkeyError("Failed to fetch private keys", sdkTypes.TurnkeyErrorCodes.BAD_RESPONSE);
1314
1382
  }
@@ -1321,61 +1389,77 @@ class TurnkeyClient {
1321
1389
  /**
1322
1390
  * Signs a message using the specified wallet account.
1323
1391
  *
1324
- * - Supports both embedded and connected wallets.
1325
- * - For **connected wallets**:
1392
+ * Behavior differs depending on the wallet type:
1393
+ *
1394
+ * - **Connected wallets**
1326
1395
  * - 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,
1396
+ * - *Ethereum*: signatures always follow [EIP-191](https://eips.ethereum.org/EIPS/eip-191).
1397
+ * - The wallet automatically prefixes messages with
1398
+ * `"\x19Ethereum Signed Message:\n" + message length` before signing.
1399
+ * - As a result, these signatures cannot be used as raw transaction signatures or broadcast on-chain.
1400
+ * - If `addEthereumPrefix` is set to `false`, an error is thrown because connected Ethereum wallets always prefix.
1401
+ * - *Other chains*: follows the native connected wallet behavior.
1402
+ *
1403
+ * - **Embedded wallets**
1404
+ * - Uses the Turnkey API to sign the message directly.
1405
+ * - Supports optional `addEthereumPrefix`:
1406
+ * - If `true` (default for Ethereum), the message is prefixed before signing.
1407
+ * - If `false`, the raw message is signed without any prefix.
1408
+ *
1409
+ * Additional details:
1410
+ * - Automatically handles encoding and hashing based on the wallet account’s address format,
1333
1411
  * unless explicitly overridden.
1412
+ * - Optionally allows stamping with a specific stamper
1413
+ * (`StamperType.Passkey`, `StamperType.ApiKey`, or `StamperType.Wallet`).
1334
1414
  *
1335
- * @param params.message - message to sign.
1415
+ * @param params.message - plaintext (UTF-8) message to sign.
1336
1416
  * @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.
1417
+ * @param params.encoding - override for payload encoding (defaults to the encoding appropriate for the address format).
1418
+ * @param params.hashFunction - override for hash function (defaults to the function appropriate for the address format).
1419
+ * @param params.stampWith - optional stamper for the signing request.
1420
+ * @param params.addEthereumPrefix - whether to prefix the message with Ethereums
1421
+ * `"\x19Ethereum Signed Message:\n"` string (default: `true` for Ethereum).
1422
+ * @param params.organizationId - organization ID to target (defaults to the session's organization ID).
1423
+ *
1424
+ * @returns A promise that resolves to a `v1SignRawPayloadResult` containing the signature and metadata.
1425
+ * @throws {TurnkeyError} If signing fails, the wallet type does not support message signing, or the response is invalid.
1348
1426
  */
1349
1427
  this.signMessage = async (params) => {
1350
- const { message, walletAccount, stampWith, addEthereumPrefix } = params;
1428
+ const { message, walletAccount, stampWith, addEthereumPrefix, organizationId, } = params;
1351
1429
  const hashFunction = params.hashFunction || utils.getHashFunction(walletAccount.addressFormat);
1352
1430
  const payloadEncoding = params.encoding || utils.getEncodingType(walletAccount.addressFormat);
1353
1431
  return utils.withTurnkeyErrorHandling(async () => {
1354
1432
  const isEthereum = walletAccount.addressFormat === "ADDRESS_FORMAT_ETHEREUM";
1355
- if (walletAccount.source === base.WalletSource.Connected) {
1433
+ if (walletAccount.source === enums.WalletSource.Connected) {
1356
1434
  // this is a connected wallet
1357
1435
  if (!addEthereumPrefix && isEthereum) {
1358
1436
  throw new sdkTypes.TurnkeyError("Connected Ethereum wallets automatically prefix messages. Use `addEthereumPrefix: true`.", sdkTypes.TurnkeyErrorCodes.SIGN_MESSAGE_ERROR);
1359
1437
  }
1360
1438
  let encodedMessage = message;
1361
1439
  if (isEthereum) {
1362
- encodedMessage = utils.getEncodedMessage(walletAccount.addressFormat, message);
1440
+ const msgBytes = ethers.toUtf8Bytes(message);
1441
+ encodedMessage = utils.getEncodedMessage(payloadEncoding, msgBytes);
1363
1442
  }
1364
1443
  const sigHex = await walletAccount.signMessage(encodedMessage);
1365
1444
  return utils.splitSignature(sigHex, walletAccount.addressFormat);
1366
1445
  }
1367
1446
  // this is an embedded wallet
1368
- let messageToEncode = message;
1447
+ let msgBytes = ethers.toUtf8Bytes(message);
1369
1448
  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);
1449
+ const prefix = `\x19Ethereum Signed Message:\n${msgBytes.length}`;
1450
+ const prefixBytes = ethers.toUtf8Bytes(prefix);
1451
+ const combined = new Uint8Array(prefixBytes.length + msgBytes.length);
1452
+ combined.set(prefixBytes, 0);
1453
+ combined.set(msgBytes, prefixBytes.length);
1454
+ msgBytes = combined;
1455
+ }
1456
+ const encodedMessage = utils.getEncodedMessage(payloadEncoding, msgBytes);
1374
1457
  const response = await this.httpClient.signRawPayload({
1375
1458
  signWith: walletAccount.address,
1376
1459
  payload: encodedMessage,
1377
1460
  encoding: payloadEncoding,
1378
1461
  hashFunction,
1462
+ ...(organizationId && { organizationId }),
1379
1463
  }, stampWith);
1380
1464
  if (response.activity.failure) {
1381
1465
  throw new sdkTypes.TurnkeyError("Failed to sign message, no signed payload returned", sdkTypes.TurnkeyErrorCodes.SIGN_MESSAGE_ERROR);
@@ -1390,27 +1474,35 @@ class TurnkeyClient {
1390
1474
  /**
1391
1475
  * Signs a transaction using the specified wallet account.
1392
1476
  *
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).
1477
+ * Behavior differs depending on the type of wallet:
1478
+ *
1479
+ * - **Connected wallets**
1480
+ * - Ethereum: does not support raw transaction signing. Calling this function will throw an error instructing you to use `signAndSendTransaction` instead.
1481
+ * - Solana: supports raw transaction signing via the connected wallet provider.
1482
+ * - Other chains: not supported; will throw an error.
1398
1483
  *
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.
1484
+ * - **Embedded wallets**
1485
+ * - Delegates signing to the Turnkey API, which returns the signed transaction.
1486
+ * - Supports all Turnkey-supported transaction types (e.g., Ethereum, Solana, Tron).
1487
+ * - Optionally allows stamping with a specific stamper (`StamperType.Passkey`, `StamperType.ApiKey`, or `StamperType.Wallet`).
1488
+ *
1489
+ * @param params.walletAccount - wallet account to use for signing.
1490
+ * @param params.unsignedTransaction - unsigned transaction data as a serialized
1491
+ * string in the canonical encoding for the given `transactionType`.
1401
1492
  * @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.
1493
+ * @param params.stampWith - stamper to use for signing (`StamperType.Passkey`, `StamperType.ApiKey`, or `StamperType.Wallet`).
1494
+ * @param params.organizationId - organization ID to target (defaults to the session's organization ID).
1495
+ * @returns A promise that resolves to the signed transaction string.
1496
+ * @throws {TurnkeyError} If the wallet type is unsupported, signing fails, or the response is invalid.
1405
1497
  */
1406
1498
  this.signTransaction = async (params) => {
1407
- const { walletAccount, unsignedTransaction, transactionType, stampWith } = params;
1499
+ const { walletAccount, unsignedTransaction, transactionType, stampWith, organizationId, } = params;
1408
1500
  return utils.withTurnkeyErrorHandling(async () => {
1409
- if (walletAccount.source === base.WalletSource.Connected) {
1501
+ if (walletAccount.source === enums.WalletSource.Connected) {
1410
1502
  switch (walletAccount.chainInfo.namespace) {
1411
- case base.Chain.Ethereum:
1503
+ case enums.Chain.Ethereum:
1412
1504
  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:
1505
+ case enums.Chain.Solana:
1414
1506
  // not sure why typescript isn't inferring the type here
1415
1507
  // if namespace is Chain.Solana, then it must be a ConnectedSolanaWalletAccount
1416
1508
  return walletAccount.signTransaction(unsignedTransaction);
@@ -1423,6 +1515,7 @@ class TurnkeyClient {
1423
1515
  signWith: walletAccount.address,
1424
1516
  unsignedTransaction,
1425
1517
  type: transactionType,
1518
+ ...(organizationId && { organizationId }),
1426
1519
  }, stampWith);
1427
1520
  return signTransaction.signedTransaction;
1428
1521
  }, {
@@ -1433,34 +1526,41 @@ class TurnkeyClient {
1433
1526
  /**
1434
1527
  * Signs and broadcasts a transaction using the specified wallet account.
1435
1528
  *
1436
- * - For **connected wallets**:
1437
- * - Calls the wallet’s native `signAndSendTransaction` method.
1438
- * - Does **not** require an `rpcUrl`.
1529
+ * Behavior differs depending on the type of wallet:
1530
+ *
1531
+ * - **Connected wallets**
1532
+ * - *Ethereum*: delegates to the wallet’s native `signAndSendTransaction` method.
1533
+ * - Does **not** require an `rpcUrl` (the wallet handles broadcasting).
1534
+ * - *Solana*: signs the transaction locally with the connected wallet, but requires an `rpcUrl` to broadcast it.
1535
+ * - Other chains: not supported; will throw an error.
1439
1536
  *
1440
- * - For **embedded wallets**:
1537
+ * - **Embedded wallets**
1441
1538
  * - 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.
1539
+ * - Requires an `rpcUrl` to broadcast the signed transaction, since Turnkey does not broadcast directly.
1540
+ * - Broadcasts the transaction using a JSON-RPC client and returns the resulting transaction hash/signature.
1541
+ * - Optionally allows stamping with a specific stamper (`StamperType.Passkey`, `StamperType.ApiKey`, or `StamperType.Wallet`).
1542
+ *
1543
+ * @param params.walletAccount - wallet account to use for signing and broadcasting.
1544
+ * @param params.unsignedTransaction - unsigned transaction data as a serialized
1545
+ * string in the canonical encoding for the given `transactionType`.
1546
+ * @param params.transactionType - type of transaction (e.g., `"TRANSACTION_TYPE_SOLANA"`, `"TRANSACTION_TYPE_ETHEREUM"`).
1547
+ * @param params.rpcUrl - JSON-RPC endpoint used for broadcasting (required for Solana connected wallets and all embedded wallets).
1548
+ * @param params.stampWith - optional stamper to use when signing (`StamperType.Passkey`, `StamperType.ApiKey`, or `StamperType.Wallet`).
1549
+ * @param params.organizationId - **Only for Turnkey embedded wallets**: organization ID to target (defaults to the session's organization ID).
1450
1550
  * @returns A promise that resolves to a transaction signature or hash.
1451
- * @throws {TurnkeyError} If signing or broadcasting fails.
1551
+ * @throws {TurnkeyError} If the wallet type is unsupported, or if signing/broadcasting fails.
1452
1552
  */
1453
1553
  this.signAndSendTransaction = async (params) => {
1454
- const { walletAccount, unsignedTransaction, transactionType, rpcUrl, stampWith, } = params;
1554
+ const { walletAccount, unsignedTransaction, transactionType, rpcUrl, stampWith, organizationId, } = params;
1455
1555
  return utils.withTurnkeyErrorHandling(async () => {
1456
- if (walletAccount.source === base.WalletSource.Connected) {
1556
+ if (walletAccount.source === enums.WalletSource.Connected) {
1457
1557
  // this is a connected wallet account
1458
1558
  switch (walletAccount.chainInfo.namespace) {
1459
- case base.Chain.Ethereum:
1559
+ case enums.Chain.Ethereum:
1460
1560
  // not sure why typescript isn't inferring the type here
1461
1561
  // if namespace is Chain.Ethereum, then it must be a ConnectedEthereumWalletAccount
1462
1562
  return await walletAccount.signAndSendTransaction(unsignedTransaction);
1463
- case base.Chain.Solana:
1563
+ case enums.Chain.Solana:
1464
1564
  if (!rpcUrl) {
1465
1565
  throw new sdkTypes.TurnkeyError("Missing rpcUrl: connected Solana wallets require an RPC URL to broadcast transactions.", sdkTypes.TurnkeyErrorCodes.SIGN_AND_SEND_TRANSACTION_ERROR);
1466
1566
  }
@@ -1486,6 +1586,7 @@ class TurnkeyClient {
1486
1586
  signWith: walletAccount.address,
1487
1587
  unsignedTransaction,
1488
1588
  type: transactionType,
1589
+ ...(organizationId && { organizationId }),
1489
1590
  }, stampWith);
1490
1591
  const signedTx = signTransactionResponse.signedTransaction;
1491
1592
  const txHash = await utils.broadcastTransaction({
@@ -1515,16 +1616,16 @@ class TurnkeyClient {
1515
1616
  * @throws {TurnkeyError} If there is no active session, if there is no userId, or if there is an error fetching user details.
1516
1617
  */
1517
1618
  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;
1619
+ const { organizationId: organizationIdFromParams, userId: userIdFromParams, stampWith, } = params || {};
1620
+ const session = await utils.getActiveSessionOrThrowIfRequired(stampWith, this.storageManager.getActiveSession);
1621
+ const userId = userIdFromParams || session?.userId;
1524
1622
  if (!userId) {
1525
1623
  throw new sdkTypes.TurnkeyError("User ID must be provided to fetch user", sdkTypes.TurnkeyErrorCodes.INVALID_REQUEST);
1526
1624
  }
1527
- const organizationId = params?.organizationId || session.organizationId;
1625
+ const organizationId = organizationIdFromParams || session?.organizationId;
1626
+ if (!organizationId) {
1627
+ throw new sdkTypes.TurnkeyError("Organization ID must be provided to fetch user", sdkTypes.TurnkeyErrorCodes.INVALID_REQUEST);
1628
+ }
1528
1629
  return utils.withTurnkeyErrorHandling(async () => {
1529
1630
  const userResponse = await this.httpClient.getUser({ organizationId, userId }, stampWith);
1530
1631
  if (!userResponse || !userResponse.user) {
@@ -1547,24 +1648,26 @@ class TurnkeyClient {
1547
1648
  * @param params.publicKey - the P-256 public key to use for lookup and creation.
1548
1649
  * @param params.createParams.userName - optional username to assign if creating a new user (defaults to `"Public Key User"`).
1549
1650
  * @param params.createParams.apiKeyName - optional API key name to assign if creating a new API key (defaults to `public-key-user-${publicKey}`).
1651
+ * @param params.organizationId - organization ID to specify the sub-organization (defaults to the current session's organizationId).
1652
+ * @param params.stampWith - parameter to stamp the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
1550
1653
  * @returns A promise that resolves to the existing or newly created {@link v1User}.
1551
1654
  * @throws {TurnkeyError} If there is no active session, if the input is invalid, if user retrieval fails, or if user creation fails.
1552
1655
  */
1553
1656
  this.fetchOrCreateP256ApiKeyUser = async (params) => {
1554
- const { publicKey, createParams } = params;
1657
+ const { publicKey, createParams, stampWith, organizationId: organizationIdFromParams, } = params;
1555
1658
  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);
1659
+ const session = await utils.getActiveSessionOrThrowIfRequired(stampWith, this.storageManager.getActiveSession);
1660
+ const organizationId = organizationIdFromParams || session?.organizationId;
1661
+ if (!organizationId) {
1662
+ throw new sdkTypes.TurnkeyError("Organization ID is required to fetch or create P-256 API key user.", sdkTypes.TurnkeyErrorCodes.INVALID_REQUEST);
1559
1663
  }
1560
- const organizationId = session.organizationId;
1561
1664
  // we validate their input
1562
1665
  if (!publicKey?.trim()) {
1563
1666
  throw new sdkTypes.TurnkeyError("'publicKey' is required and cannot be empty.", sdkTypes.TurnkeyErrorCodes.INVALID_REQUEST);
1564
1667
  }
1565
1668
  const usersResponse = await this.httpClient.getUsers({
1566
1669
  organizationId,
1567
- });
1670
+ }, stampWith);
1568
1671
  if (!usersResponse || !usersResponse.users) {
1569
1672
  throw new sdkTypes.TurnkeyError("No users found in the response", sdkTypes.TurnkeyErrorCodes.BAD_RESPONSE);
1570
1673
  }
@@ -1594,7 +1697,7 @@ class TurnkeyClient {
1594
1697
  oauthProviders: [],
1595
1698
  },
1596
1699
  ],
1597
- });
1700
+ }, stampWith);
1598
1701
  if (!createUserResp?.userIds ||
1599
1702
  createUserResp.userIds.length === 0 ||
1600
1703
  !createUserResp.userIds[0]) {
@@ -1604,6 +1707,7 @@ class TurnkeyClient {
1604
1707
  return await this.fetchUser({
1605
1708
  organizationId,
1606
1709
  userId: newUserId,
1710
+ stampWith,
1607
1711
  });
1608
1712
  }, {
1609
1713
  errorMessage: "Failed to get or create P-256 API key user",
@@ -1619,6 +1723,8 @@ class TurnkeyClient {
1619
1723
  * - If it does not exist, it is created and returned with its new `policyId`.
1620
1724
  *
1621
1725
  * @param params.policies - the list of policies to fetch or create.
1726
+ * @param params.stampWith - parameter to stamp the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
1727
+ * @param params.organizationId - organization ID to specify the sub-organization (defaults to the current session's organizationId).
1622
1728
  * @returns A promise that resolves to an array of objects, each containing:
1623
1729
  * - `policyId`: the unique identifier of the policy.
1624
1730
  * - `policyName`: human-readable name of the policy.
@@ -1630,20 +1736,20 @@ class TurnkeyClient {
1630
1736
  * if fetching policies fails, or if creating policies fails.
1631
1737
  */
1632
1738
  this.fetchOrCreatePolicies = async (params) => {
1633
- const { policies } = params;
1739
+ const { policies, stampWith } = params;
1634
1740
  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
- }
1741
+ const session = await utils.getActiveSessionOrThrowIfRequired(stampWith, this.storageManager.getActiveSession);
1639
1742
  if (!Array.isArray(policies) || policies.length === 0) {
1640
1743
  throw new sdkTypes.TurnkeyError("'policies' must be a non-empty array of policy definitions.", sdkTypes.TurnkeyErrorCodes.INVALID_REQUEST);
1641
1744
  }
1642
- const organizationId = session.organizationId;
1745
+ const organizationId = params?.organizationId ?? session?.organizationId;
1746
+ if (!organizationId) {
1747
+ throw new sdkTypes.TurnkeyError("Organization ID is required to fetch or create policies.", sdkTypes.TurnkeyErrorCodes.INVALID_REQUEST);
1748
+ }
1643
1749
  // we first fetch existing policies
1644
1750
  const existingPoliciesResponse = await this.httpClient.getPolicies({
1645
1751
  organizationId,
1646
- });
1752
+ }, stampWith);
1647
1753
  const existingPolicies = existingPoliciesResponse.policies || [];
1648
1754
  // we create a map of existing policies by their signature
1649
1755
  // where the policySignature maps to its policyId
@@ -1676,10 +1782,10 @@ class TurnkeyClient {
1676
1782
  const createPoliciesResponse = await this.httpClient.createPolicies({
1677
1783
  organizationId,
1678
1784
  policies: missingPolicies,
1679
- });
1785
+ }, stampWith);
1680
1786
  // assign returned IDs back to the missing ones in order
1681
1787
  if (!createPoliciesResponse || !createPoliciesResponse.policyIds) {
1682
- throw new sdkTypes.TurnkeyError("Failed to create missing delegated access policies", sdkTypes.TurnkeyErrorCodes.CREATE_POLICY_ERROR);
1788
+ throw new sdkTypes.TurnkeyError("Failed to create missing policies", sdkTypes.TurnkeyErrorCodes.CREATE_POLICY_ERROR);
1683
1789
  }
1684
1790
  const newlyCreatedPolicies = missingPolicies.map((p, idx) => ({
1685
1791
  ...p,
@@ -1691,7 +1797,7 @@ class TurnkeyClient {
1691
1797
  // which includes each of their respective IDs
1692
1798
  return [...alreadyExistingPolicies, ...newlyCreatedPolicies];
1693
1799
  }, {
1694
- errorMessage: "Failed to get or create delegated access policies",
1800
+ errorMessage: "Failed to get or create policies",
1695
1801
  errorCode: sdkTypes.TurnkeyErrorCodes.CREATE_USERS_ERROR,
1696
1802
  });
1697
1803
  };
@@ -1708,19 +1814,20 @@ class TurnkeyClient {
1708
1814
  * @param params.verificationToken - verification token from OTP email verification (required if verifying the email).
1709
1815
  * @param params.userId - user ID to update a specific user's email (defaults to the current session's userId).
1710
1816
  * @param params.stampWith - parameter to stamp the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
1817
+ * @param params.organizationId - organization ID to specify the sub-organization (defaults to the current session's organizationId).
1711
1818
  * @returns A promise that resolves to the userId of the updated user.
1712
1819
  * @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
1820
  */
1714
1821
  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);
1822
+ const { verificationToken, email, stampWith, organizationId } = params;
1823
+ const session = await utils.getActiveSessionOrThrowIfRequired(stampWith, this.storageManager.getActiveSession);
1824
+ const userId = params?.userId || session?.userId;
1825
+ if (!userId) {
1826
+ throw new sdkTypes.TurnkeyError("User ID must be provided to update user email", sdkTypes.TurnkeyErrorCodes.INVALID_REQUEST);
1719
1827
  }
1720
- const userId = params?.userId || session.userId;
1721
1828
  return utils.withTurnkeyErrorHandling(async () => {
1722
1829
  const existingUser = await this.httpClient.proxyGetAccount({
1723
- filterType: base.FilterType.Email,
1830
+ filterType: enums.FilterType.Email,
1724
1831
  filterValue: email,
1725
1832
  });
1726
1833
  if (existingUser.organizationId) {
@@ -1730,6 +1837,7 @@ class TurnkeyClient {
1730
1837
  userId: userId,
1731
1838
  userEmail: email,
1732
1839
  ...(verificationToken && { verificationToken }),
1840
+ ...(organizationId && { organizationId }),
1733
1841
  }, stampWith);
1734
1842
  if (!res || !res.userId) {
1735
1843
  throw new sdkTypes.TurnkeyError("No user ID found in the update user email response", sdkTypes.TurnkeyErrorCodes.BAD_RESPONSE);
@@ -1750,20 +1858,22 @@ class TurnkeyClient {
1750
1858
  *
1751
1859
  * @param params.userId - user ID to remove a specific user's email address (defaults to the current session's userId).
1752
1860
  * @param params.stampWith - parameter to stamp the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
1861
+ * @param params.organizationId - organization ID to specify the sub-organization (defaults to the current session's organizationId).
1753
1862
  * @returns A promise that resolves to the userId of the user whose email was removed.
1754
1863
  * @throws {TurnkeyError} If there is no active session, if the userId is missing, or if there is an error removing the user email.
1755
1864
  */
1756
1865
  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
- }
1866
+ const { stampWith, organizationId } = params || {};
1867
+ const session = await utils.getActiveSessionOrThrowIfRequired(stampWith, this.storageManager.getActiveSession);
1762
1868
  return utils.withTurnkeyErrorHandling(async () => {
1763
- const userId = params?.userId || session.userId;
1869
+ const userId = params?.userId || session?.userId;
1870
+ if (!userId) {
1871
+ throw new sdkTypes.TurnkeyError("User ID must be provided to remove user email", sdkTypes.TurnkeyErrorCodes.INVALID_REQUEST);
1872
+ }
1764
1873
  const res = await this.httpClient.updateUserEmail({
1765
1874
  userId: userId,
1766
1875
  userEmail: "",
1876
+ ...(organizationId && { organizationId }),
1767
1877
  }, stampWith);
1768
1878
  if (!res || !res.userId) {
1769
1879
  throw new sdkTypes.TurnkeyError("No user ID found in the remove user email response", sdkTypes.TurnkeyErrorCodes.BAD_RESPONSE);
@@ -1787,21 +1897,23 @@ class TurnkeyClient {
1787
1897
  * @param params.verificationToken - verification token from OTP phone verification (required if verifying the phone number).
1788
1898
  * @param params.userId - user ID to update a specific user's phone number (defaults to the current session's userId).
1789
1899
  * @param params.stampWith - parameter to stamp the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
1900
+ * @param params.organizationId - organization ID to specify the sub-organization (defaults to the current session's organizationId).
1790
1901
  * @returns A promise that resolves to the userId of the updated user.
1791
1902
  * @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
1903
  */
1793
1904
  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);
1905
+ const { verificationToken, phoneNumber, stampWith, organizationId } = params;
1906
+ const session = await utils.getActiveSessionOrThrowIfRequired(stampWith, this.storageManager.getActiveSession);
1907
+ const userId = params?.userId || session?.userId;
1908
+ if (!userId) {
1909
+ throw new sdkTypes.TurnkeyError("User ID must be provided to update user phone number", sdkTypes.TurnkeyErrorCodes.INVALID_REQUEST);
1798
1910
  }
1799
- const userId = params?.userId || session.userId;
1800
1911
  return utils.withTurnkeyErrorHandling(async () => {
1801
1912
  const res = await this.httpClient.updateUserPhoneNumber({
1802
1913
  userId,
1803
1914
  userPhoneNumber: phoneNumber,
1804
1915
  ...(verificationToken && { verificationToken }),
1916
+ ...(organizationId && { organizationId }),
1805
1917
  }, stampWith);
1806
1918
  if (!res || !res.userId) {
1807
1919
  throw new sdkTypes.TurnkeyError("Failed to update user phone number", sdkTypes.TurnkeyErrorCodes.UPDATE_USER_PHONE_NUMBER_ERROR);
@@ -1822,20 +1934,22 @@ class TurnkeyClient {
1822
1934
  *
1823
1935
  * @param params.userId - user ID to remove a specific user's phone number (defaults to the current session's userId).
1824
1936
  * @param params.stampWith - parameter to stamp the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
1937
+ * @param params.organizationId - organization ID to specify the sub-organization (defaults to the current session's organizationId).
1825
1938
  * @returns A promise that resolves to the userId of the user whose phone number was removed.
1826
1939
  * @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
1940
  */
1828
1941
  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);
1942
+ const { stampWith, organizationId } = params || {};
1943
+ const session = await utils.getActiveSessionOrThrowIfRequired(stampWith, this.storageManager.getActiveSession);
1944
+ const userId = params?.userId || session?.userId;
1945
+ if (!userId) {
1946
+ throw new sdkTypes.TurnkeyError("User ID must be provided to remove user phone number", sdkTypes.TurnkeyErrorCodes.INVALID_REQUEST);
1833
1947
  }
1834
- const userId = params?.userId || session.userId;
1835
1948
  return utils.withTurnkeyErrorHandling(async () => {
1836
1949
  const res = await this.httpClient.updateUserPhoneNumber({
1837
1950
  userId,
1838
1951
  userPhoneNumber: "",
1952
+ ...(organizationId && { organizationId }),
1839
1953
  }, stampWith);
1840
1954
  if (!res || !res.userId) {
1841
1955
  throw new sdkTypes.TurnkeyError("Failed to remove user phone number", sdkTypes.TurnkeyErrorCodes.UPDATE_USER_PHONE_NUMBER_ERROR);
@@ -1858,20 +1972,22 @@ class TurnkeyClient {
1858
1972
  * @param params.userName - new name to set for the user.
1859
1973
  * @param params.userId - user ID to update a specific user's name (defaults to the current session's userId).
1860
1974
  * @param params.stampWith - parameter to stamp the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
1975
+ * @param params.organizationId - organization ID to specify the sub-organization (defaults to the current session's organizationId).
1861
1976
  * @returns A promise that resolves to the userId of the updated user.
1862
1977
  * @throws {TurnkeyError} If there is no active session, if the userId is missing, or if there is an error updating the user name.
1863
1978
  */
1864
1979
  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);
1980
+ const { userName, stampWith, organizationId } = params;
1981
+ const session = await utils.getActiveSessionOrThrowIfRequired(stampWith, this.storageManager.getActiveSession);
1982
+ const userId = params?.userId || session?.userId;
1983
+ if (!userId) {
1984
+ throw new sdkTypes.TurnkeyError("User ID must be provided to update user name", sdkTypes.TurnkeyErrorCodes.INVALID_REQUEST);
1869
1985
  }
1870
- const userId = params?.userId || session.userId;
1871
1986
  return utils.withTurnkeyErrorHandling(async () => {
1872
1987
  const res = await this.httpClient.updateUserName({
1873
1988
  userId,
1874
1989
  userName,
1990
+ ...(organizationId && { organizationId }),
1875
1991
  }, stampWith);
1876
1992
  if (!res || !res.userId) {
1877
1993
  throw new sdkTypes.TurnkeyError("No user ID found in the update user name response", sdkTypes.TurnkeyErrorCodes.BAD_RESPONSE);
@@ -1894,6 +2010,7 @@ class TurnkeyClient {
1894
2010
  *
1895
2011
  * @param params.providerName - name of the OAuth provider to add (e.g., "Google", "Apple").
1896
2012
  * @param params.oidcToken - OIDC token for the OAuth provider.
2013
+ * @param params.organizationId - organization ID to specify the sub-organization (defaults to the current session's organizationId).
1897
2014
  * @param params.userId - user ID to add the provider for a specific user (defaults to current session's userId).
1898
2015
  * @param params.stampWith - parameter to stamp the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
1899
2016
  * @returns A promise that resolves to an array of provider IDs associated with the user.
@@ -1901,29 +2018,34 @@ class TurnkeyClient {
1901
2018
  */
1902
2019
  this.addOauthProvider = async (params) => {
1903
2020
  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
- }
2021
+ const session = await utils.getActiveSessionOrThrowIfRequired(stampWith, this.storageManager.getActiveSession);
1908
2022
  return utils.withTurnkeyErrorHandling(async () => {
1909
2023
  const accountRes = await this.httpClient.proxyGetAccount({
1910
2024
  filterType: "OIDC_TOKEN",
1911
2025
  filterValue: oidcToken,
1912
2026
  });
1913
2027
  if (!accountRes) {
1914
- throw new sdkTypes.TurnkeyError(`Account fetch failed}`, sdkTypes.TurnkeyErrorCodes.ACCOUNT_FETCH_ERROR);
2028
+ throw new sdkTypes.TurnkeyError(`Account fetch failed`, sdkTypes.TurnkeyErrorCodes.ACCOUNT_FETCH_ERROR);
1915
2029
  }
1916
2030
  if (accountRes.organizationId) {
1917
2031
  throw new sdkTypes.TurnkeyError("Account already exists with this OIDC token", sdkTypes.TurnkeyErrorCodes.ACCOUNT_ALREADY_EXISTS);
1918
2032
  }
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.
2033
+ const userId = params?.userId || session?.userId;
2034
+ if (!userId) {
2035
+ throw new sdkTypes.TurnkeyError("User ID must be provided to add OAuth provider", sdkTypes.TurnkeyErrorCodes.INVALID_REQUEST);
2036
+ }
2037
+ const organizationId = params?.organizationId ?? session?.organizationId;
2038
+ if (!organizationId) {
2039
+ throw new sdkTypes.TurnkeyError("Organization ID is required to add OAuth provider", sdkTypes.TurnkeyErrorCodes.INVALID_REQUEST);
2040
+ }
2041
+ // parse the oidc token so we can get the email. Pass it in to updateUser then call createOauthProviders. This will be verified by Turnkey.
2042
+ const { email: oidcEmail, iss } = jwtDecode.jwtDecode(oidcToken) || {};
1921
2043
  if (iss === utils.googleISS) {
1922
2044
  const verifiedSuborg = await this.httpClient.proxyGetAccount({
1923
2045
  filterType: "EMAIL",
1924
2046
  filterValue: oidcEmail,
1925
2047
  });
1926
- const isVerified = verifiedSuborg.organizationId === session.organizationId;
2048
+ const isVerified = verifiedSuborg.organizationId === organizationId;
1927
2049
  const user = await this.fetchUser({
1928
2050
  userId,
1929
2051
  stampWith,
@@ -1966,20 +2088,22 @@ class TurnkeyClient {
1966
2088
  * @param params.providerIds - IDs of the OAuth providers to remove.
1967
2089
  * @param params.userId - user ID to remove the provider for a specific user (defaults to the current session's userId).
1968
2090
  * @param params.stampWith - parameter to stamp the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
2091
+ * @param params.organizationId - organization ID to specify the sub-organization (defaults to the current session's organizationId).
1969
2092
  * @returns A promise that resolves to an array of provider IDs that were removed.
1970
2093
  * @throws {TurnkeyError} If there is no active session, if the userId is missing, or if there is an error removing the OAuth provider.
1971
2094
  */
1972
2095
  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);
2096
+ const { providerIds, stampWith, organizationId } = params;
2097
+ const session = await utils.getActiveSessionOrThrowIfRequired(stampWith, this.storageManager.getActiveSession);
2098
+ const userId = params?.userId || session?.userId;
2099
+ if (!userId) {
2100
+ throw new sdkTypes.TurnkeyError("User ID must be provided to remove OAuth provider", sdkTypes.TurnkeyErrorCodes.INVALID_REQUEST);
1977
2101
  }
1978
- const userId = params?.userId || session.userId;
1979
2102
  return utils.withTurnkeyErrorHandling(async () => {
1980
2103
  const res = await this.httpClient.deleteOauthProviders({
1981
2104
  userId,
1982
2105
  providerIds,
2106
+ ...(organizationId && { organizationId }),
1983
2107
  }, stampWith);
1984
2108
  if (!res) {
1985
2109
  throw new sdkTypes.TurnkeyError("Failed to remove OAuth provider", sdkTypes.TurnkeyErrorCodes.REMOVE_OAUTH_PROVIDER_ERROR);
@@ -2003,21 +2127,21 @@ class TurnkeyClient {
2003
2127
  * @param params.displayName - display name of the passkey (defaults to the value of `name`).
2004
2128
  * @param params.userId - user ID to add the passkey for a specific user (defaults to the current session's userId).
2005
2129
  * @param params.stampWith - parameter to stamp the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
2130
+ * @param params.organizationId - organization ID to specify the sub-organization (defaults to the current session's organizationId).
2006
2131
  * @returns A promise that resolves to an array of authenticator IDs for the newly added passkey(s).
2007
2132
  * @throws {TurnkeyError} If there is no active session, if passkey creation fails, or if there is an error adding the passkey.
2008
2133
  */
2009
2134
  this.addPasskey = async (params) => {
2010
- const { stampWith } = params || {};
2135
+ const { stampWith, organizationId } = params || {};
2011
2136
  const name = params?.name || `Turnkey Passkey-${Date.now()}`;
2012
2137
  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);
2138
+ const session = await utils.getActiveSessionOrThrowIfRequired(stampWith, this.storageManager.getActiveSession);
2139
+ const userId = params?.userId || session?.userId;
2140
+ if (!userId) {
2141
+ throw new sdkTypes.TurnkeyError("User ID must be provided to add passkey", sdkTypes.TurnkeyErrorCodes.INVALID_REQUEST);
2016
2142
  }
2017
- const userId = params?.userId || session.userId;
2018
2143
  const { encodedChallenge, attestation } = await this.createPasskey({
2019
2144
  name,
2020
- ...(stampWith && { stampWith }),
2021
2145
  });
2022
2146
  if (!attestation || !encodedChallenge) {
2023
2147
  throw new sdkTypes.TurnkeyError("Failed to create passkey challenge and attestation", sdkTypes.TurnkeyErrorCodes.CREATE_PASSKEY_ERROR);
@@ -2031,6 +2155,7 @@ class TurnkeyClient {
2031
2155
  attestation,
2032
2156
  },
2033
2157
  ],
2158
+ ...(organizationId && { organizationId }),
2034
2159
  }, stampWith);
2035
2160
  return res?.authenticatorIds || [];
2036
2161
  }, {
@@ -2050,20 +2175,22 @@ class TurnkeyClient {
2050
2175
  * @param params.authenticatorIds - IDs of the authenticators (passkeys) to remove.
2051
2176
  * @param params.userId - user ID to remove the passkeys for a specific user (defaults to the current session's userId).
2052
2177
  * @param params.stampWith - parameter to stamp the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
2178
+ * @param params.organizationId - organization ID to specify the sub-organization (defaults to the current session's organizationId).
2053
2179
  * @returns A promise that resolves to an array of authenticator IDs that were removed.
2054
2180
  * @throws {TurnkeyError} If there is no active session, if the userId is missing, or if there is an error removing the passkeys.
2055
2181
  */
2056
2182
  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);
2183
+ const { authenticatorIds, stampWith, organizationId } = params;
2184
+ const session = await utils.getActiveSessionOrThrowIfRequired(stampWith, this.storageManager.getActiveSession);
2185
+ const userId = params?.userId || session?.userId;
2186
+ if (!userId) {
2187
+ throw new sdkTypes.TurnkeyError("User ID must be provided to remove passkey", sdkTypes.TurnkeyErrorCodes.INVALID_REQUEST);
2061
2188
  }
2062
- const userId = params?.userId || session.userId;
2063
2189
  return utils.withTurnkeyErrorHandling(async () => {
2064
2190
  const res = await this.httpClient.deleteAuthenticators({
2065
2191
  userId,
2066
2192
  authenticatorIds,
2193
+ ...(organizationId && { organizationId }),
2067
2194
  }, stampWith);
2068
2195
  if (!res) {
2069
2196
  throw new sdkTypes.TurnkeyError("No response found in the remove passkey response", sdkTypes.TurnkeyErrorCodes.REMOVE_PASSKEY_ERROR);
@@ -2094,10 +2221,11 @@ class TurnkeyClient {
2094
2221
  * @throws {TurnkeyError} If there is no active session or if there is an error creating the wallet.
2095
2222
  */
2096
2223
  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);
2224
+ const { walletName, accounts, organizationId: organizationIdFromParams, mnemonicLength, stampWith, } = params;
2225
+ const session = await utils.getActiveSessionOrThrowIfRequired(stampWith, this.storageManager.getActiveSession);
2226
+ const organizationId = organizationIdFromParams || session?.organizationId;
2227
+ if (!organizationId) {
2228
+ throw new sdkTypes.TurnkeyError("Organization ID must be provided to create wallet", sdkTypes.TurnkeyErrorCodes.INVALID_REQUEST);
2101
2229
  }
2102
2230
  let walletAccounts = [];
2103
2231
  if (accounts && !utils.isWalletAccountArray(accounts)) {
@@ -2113,7 +2241,7 @@ class TurnkeyClient {
2113
2241
  }
2114
2242
  return utils.withTurnkeyErrorHandling(async () => {
2115
2243
  const res = await this.httpClient.createWallet({
2116
- organizationId: organizationId || session.organizationId,
2244
+ organizationId: organizationId,
2117
2245
  walletName,
2118
2246
  accounts: walletAccounts,
2119
2247
  mnemonicLength: mnemonicLength || 12,
@@ -2145,10 +2273,11 @@ class TurnkeyClient {
2145
2273
  * @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
2274
  */
2147
2275
  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);
2276
+ const { accounts, walletId, organizationId: organizationIdFromParams, stampWith, } = params;
2277
+ const session = await utils.getActiveSessionOrThrowIfRequired(stampWith, this.storageManager.getActiveSession);
2278
+ const organizationId = organizationIdFromParams || session?.organizationId;
2279
+ if (!organizationId) {
2280
+ throw new sdkTypes.TurnkeyError("Organization ID must be provided to create wallet accounts", sdkTypes.TurnkeyErrorCodes.INVALID_REQUEST);
2152
2281
  }
2153
2282
  return utils.withTurnkeyErrorHandling(async () => {
2154
2283
  let walletAccounts = [];
@@ -2156,7 +2285,7 @@ class TurnkeyClient {
2156
2285
  // Query existing wallet accounts to avoid duplicates
2157
2286
  const existingWalletAccounts = await this.httpClient.getWalletAccounts({
2158
2287
  walletId,
2159
- organizationId: organizationId || session.organizationId,
2288
+ organizationId: organizationId,
2160
2289
  paginationOptions: { limit: "100" },
2161
2290
  }, stampWith);
2162
2291
  walletAccounts = utils.generateWalletAccountsFromAddressFormat({
@@ -2168,7 +2297,7 @@ class TurnkeyClient {
2168
2297
  walletAccounts = accounts;
2169
2298
  }
2170
2299
  const res = await this.httpClient.createWalletAccounts({
2171
- organizationId: organizationId || session.organizationId,
2300
+ organizationId: organizationId,
2172
2301
  walletId,
2173
2302
  accounts: walletAccounts,
2174
2303
  }, stampWith);
@@ -2199,16 +2328,17 @@ class TurnkeyClient {
2199
2328
  * @throws {TurnkeyError} If there is no active session, if the targetPublicKey is missing, or if there is an error exporting the wallet.
2200
2329
  */
2201
2330
  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);
2331
+ const { walletId, targetPublicKey, stampWith, organizationId: organizationIdFromParams, } = params;
2332
+ const session = await utils.getActiveSessionOrThrowIfRequired(stampWith, this.storageManager.getActiveSession);
2333
+ const organizationId = organizationIdFromParams || session?.organizationId;
2334
+ if (!organizationId) {
2335
+ throw new sdkTypes.TurnkeyError("Organization ID must be provided to export wallet", sdkTypes.TurnkeyErrorCodes.INVALID_REQUEST);
2206
2336
  }
2207
2337
  return utils.withTurnkeyErrorHandling(async () => {
2208
2338
  const res = await this.httpClient.exportWallet({
2209
2339
  walletId,
2210
2340
  targetPublicKey,
2211
- organizationId: organizationId || session.organizationId,
2341
+ organizationId: organizationId,
2212
2342
  }, stampWith);
2213
2343
  if (!res.exportBundle) {
2214
2344
  throw new sdkTypes.TurnkeyError("No export bundle found in the response", sdkTypes.TurnkeyErrorCodes.BAD_RESPONSE);
@@ -2236,16 +2366,17 @@ class TurnkeyClient {
2236
2366
  * @throws {TurnkeyError} If there is no active session, if the targetPublicKey is missing, or if there is an error exporting the private key.
2237
2367
  */
2238
2368
  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);
2369
+ const { privateKeyId, targetPublicKey, stampWith, organizationId: organizationIdFromParams, } = params;
2370
+ const session = await utils.getActiveSessionOrThrowIfRequired(stampWith, this.storageManager.getActiveSession);
2371
+ const organizationId = organizationIdFromParams || session?.organizationId;
2372
+ if (!organizationId) {
2373
+ throw new sdkTypes.TurnkeyError("Organization ID must be provided to export private key", sdkTypes.TurnkeyErrorCodes.INVALID_REQUEST);
2243
2374
  }
2244
2375
  return utils.withTurnkeyErrorHandling(async () => {
2245
2376
  const res = await this.httpClient.exportPrivateKey({
2246
2377
  privateKeyId,
2247
2378
  targetPublicKey,
2248
- organizationId: organizationId || session.organizationId,
2379
+ organizationId: organizationId,
2249
2380
  }, stampWith);
2250
2381
  if (!res.exportBundle) {
2251
2382
  throw new sdkTypes.TurnkeyError("No export bundle found in the response", sdkTypes.TurnkeyErrorCodes.BAD_RESPONSE);
@@ -2274,16 +2405,17 @@ class TurnkeyClient {
2274
2405
  *
2275
2406
  */
2276
2407
  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);
2408
+ const { address, targetPublicKey, stampWith, organizationId: organizationIdFromParams, } = params;
2409
+ const session = await utils.getActiveSessionOrThrowIfRequired(stampWith, this.storageManager.getActiveSession);
2410
+ const organizationId = organizationIdFromParams || session?.organizationId;
2411
+ if (!organizationId) {
2412
+ throw new sdkTypes.TurnkeyError("Organization ID must be provided to export wallet account", sdkTypes.TurnkeyErrorCodes.INVALID_REQUEST);
2281
2413
  }
2282
2414
  return utils.withTurnkeyErrorHandling(async () => {
2283
2415
  const res = await this.httpClient.exportWalletAccount({
2284
2416
  address,
2285
2417
  targetPublicKey,
2286
- organizationId: organizationId || session.organizationId,
2418
+ organizationId: organizationId,
2287
2419
  }, stampWith);
2288
2420
  if (!res.exportBundle) {
2289
2421
  throw new sdkTypes.TurnkeyError("No export bundle found in the response", sdkTypes.TurnkeyErrorCodes.BAD_RESPONSE);
@@ -2307,21 +2439,27 @@ class TurnkeyClient {
2307
2439
  * @param params.encryptedBundle - encrypted bundle containing the wallet seed phrase and metadata.
2308
2440
  * @param params.walletName - name of the wallet to create upon import.
2309
2441
  * @param params.accounts - array of account parameters to create in the imported wallet (defaults to standard Ethereum and Solana accounts).
2442
+ * @param params.organizationId - organization ID to import the wallet under a specific sub-organization (wallet will be associated with the sub-organization).
2310
2443
  * @param params.userId - user ID to import the wallet for a specific user (defaults to the current session's userId).
2311
2444
  * @param params.stampWith - parameter to stamp the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
2312
2445
  * @returns A promise that resolves to the ID of the imported wallet.
2313
2446
  * @throws {TurnkeyError} If there is no active session, if the encrypted bundle is invalid, or if there is an error importing the wallet.
2314
2447
  */
2315
2448
  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);
2449
+ const { encryptedBundle, accounts, walletName, organizationId: organizationIdFromParams, userId: userIdFromParams, stampWith, } = params;
2450
+ const session = await utils.getActiveSessionOrThrowIfRequired(stampWith, this.storageManager.getActiveSession);
2451
+ const organizationId = organizationIdFromParams || session?.organizationId;
2452
+ if (!organizationId) {
2453
+ throw new sdkTypes.TurnkeyError("Organization ID must be provided to import wallet", sdkTypes.TurnkeyErrorCodes.INVALID_REQUEST);
2454
+ }
2455
+ const userId = userIdFromParams || session?.userId;
2456
+ if (!userId) {
2457
+ throw new sdkTypes.TurnkeyError("User ID must be provided to import wallet", sdkTypes.TurnkeyErrorCodes.INVALID_REQUEST);
2320
2458
  }
2321
2459
  return utils.withTurnkeyErrorHandling(async () => {
2322
2460
  const res = await this.httpClient.importWallet({
2323
- organizationId: session.organizationId,
2324
- userId: userId || session.userId,
2461
+ organizationId: organizationId,
2462
+ userId: userId,
2325
2463
  encryptedBundle,
2326
2464
  walletName,
2327
2465
  accounts: accounts || [
@@ -2359,21 +2497,27 @@ class TurnkeyClient {
2359
2497
  * @param params.privateKeyName - name of the private key to create upon import.
2360
2498
  * @param params.curve - the cryptographic curve used to generate a given private key
2361
2499
  * @param params.addressFormat - address format of the private key to import.
2500
+ * @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
2501
  * @param params.userId - user ID to import the wallet for a specific user (defaults to the current session's userId).
2363
2502
  * @param params.stampWith - parameter to stamp the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
2364
2503
  * @returns A promise that resolves to the ID of the imported wallet.
2365
2504
  * @throws {TurnkeyError} If there is no active session, if the encrypted bundle is invalid, or if there is an error importing the wallet.
2366
2505
  */
2367
2506
  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);
2507
+ const { encryptedBundle, privateKeyName, addressFormats, curve, organizationId: organizationIdFromParams, userId: userIdFromParams, stampWith, } = params;
2508
+ const session = await utils.getActiveSessionOrThrowIfRequired(stampWith, this.storageManager.getActiveSession);
2509
+ const organizationId = organizationIdFromParams || session?.organizationId;
2510
+ if (!organizationId) {
2511
+ throw new sdkTypes.TurnkeyError("Organization ID must be provided to import private key", sdkTypes.TurnkeyErrorCodes.INVALID_REQUEST);
2512
+ }
2513
+ const userId = userIdFromParams || session?.userId;
2514
+ if (!userId) {
2515
+ throw new sdkTypes.TurnkeyError("User ID must be provided to import private key", sdkTypes.TurnkeyErrorCodes.INVALID_REQUEST);
2372
2516
  }
2373
2517
  return utils.withTurnkeyErrorHandling(async () => {
2374
2518
  const res = await this.httpClient.importPrivateKey({
2375
- organizationId: session.organizationId,
2376
- userId: userId || session.userId,
2519
+ organizationId,
2520
+ userId,
2377
2521
  encryptedBundle,
2378
2522
  privateKeyName,
2379
2523
  curve,
@@ -2404,18 +2548,17 @@ class TurnkeyClient {
2404
2548
  * - Optionally allows stamping the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
2405
2549
  *
2406
2550
  * @param params.deleteWithoutExport - flag to delete the sub-organization without requiring all wallets to be exported first (defaults to false).
2551
+ * @param params.organizationId - organization ID to delete a specific sub-organization (defaults to the current session's organizationId).
2407
2552
  * @param params.stampWith - parameter to stamp the request with a specific stamper.
2408
2553
  * @returns A promise that resolves to a `TDeleteSubOrganizationResponse` object containing the result of the deletion.
2409
2554
  * @throws {TurnkeyError} If there is no active session or if there is an error deleting the sub-organization.
2410
2555
  */
2411
2556
  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
- }
2557
+ const { deleteWithoutExport = false, organizationId: organizationIdFromParams, stampWith, } = params || {};
2558
+ const session = await utils.getActiveSessionOrThrowIfRequired(stampWith, this.storageManager.getActiveSession);
2559
+ const organizationId = organizationIdFromParams || session?.organizationId;
2417
2560
  return utils.withTurnkeyErrorHandling(async () => {
2418
- return await this.httpClient.deleteSubOrganization({ deleteWithoutExport }, stampWith);
2561
+ return await this.httpClient.deleteSubOrganization({ deleteWithoutExport, ...(organizationId && { organizationId }) }, stampWith);
2419
2562
  }, {
2420
2563
  errorMessage: "Failed to delete sub-organization",
2421
2564
  errorCode: sdkTypes.TurnkeyErrorCodes.DELETE_SUB_ORGANIZATION_ERROR,
@@ -2436,7 +2579,7 @@ class TurnkeyClient {
2436
2579
  * @throws {TurnkeyError} If there is an error storing the session or cleaning up key pairs.
2437
2580
  */
2438
2581
  this.storeSession = async (params) => {
2439
- const { sessionToken, sessionKey = base.SessionKey.DefaultSessionkey } = params;
2582
+ const { sessionToken, sessionKey = enums.SessionKey.DefaultSessionkey } = params;
2440
2583
  if (!sessionToken)
2441
2584
  return;
2442
2585
  utils.withTurnkeyErrorHandling(async () => {
@@ -2461,7 +2604,7 @@ class TurnkeyClient {
2461
2604
  * @throws {TurnkeyError} If the session does not exist or if there is an error clearing the session.
2462
2605
  */
2463
2606
  this.clearSession = async (params) => {
2464
- const { sessionKey = base.SessionKey.DefaultSessionkey } = params || {};
2607
+ const { sessionKey = enums.SessionKey.DefaultSessionkey } = params || {};
2465
2608
  utils.withTurnkeyErrorHandling(async () => {
2466
2609
  const session = await this.storageManager.getSession(sessionKey);
2467
2610
  if (session) {
@@ -2519,7 +2662,7 @@ class TurnkeyClient {
2519
2662
  * @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
2663
  */
2521
2664
  this.refreshSession = async (params) => {
2522
- const { sessionKey = await this.storageManager.getActiveSessionKey(), expirationSeconds = base.DEFAULT_SESSION_EXPIRATION_IN_SECONDS, publicKey, invalidateExisitng = false, } = params || {};
2665
+ const { sessionKey = await this.storageManager.getActiveSessionKey(), expirationSeconds = auth.DEFAULT_SESSION_EXPIRATION_IN_SECONDS, publicKey, invalidateExisitng = false, } = params || {};
2523
2666
  if (!sessionKey) {
2524
2667
  throw new sdkTypes.TurnkeyError("No session key provided or active session to refresh session", sdkTypes.TurnkeyErrorCodes.NO_SESSION_FOUND);
2525
2668
  }
@@ -2750,17 +2893,17 @@ class TurnkeyClient {
2750
2893
  async init() {
2751
2894
  // Initialize storage manager
2752
2895
  // TODO (Amir): StorageManager should be a class that extends StorageBase and has an init method
2753
- this.storageManager = await base$1.createStorageManager();
2896
+ this.storageManager = await base.createStorageManager();
2754
2897
  // Initialize the API key stamper
2755
- this.apiKeyStamper = new base$2.CrossPlatformApiKeyStamper(this.storageManager);
2898
+ this.apiKeyStamper = new base$1.CrossPlatformApiKeyStamper(this.storageManager);
2756
2899
  await this.apiKeyStamper.init();
2757
2900
  if (this.config.passkeyConfig) {
2758
- this.passkeyStamper = new base$3.CrossPlatformPasskeyStamper(this.config.passkeyConfig);
2901
+ this.passkeyStamper = new base$2.CrossPlatformPasskeyStamper(this.config.passkeyConfig);
2759
2902
  await this.passkeyStamper.init();
2760
2903
  }
2761
2904
  if (this.config.walletConfig?.features?.auth ||
2762
2905
  this.config.walletConfig?.features?.connecting) {
2763
- this.walletManager = await base$4.createWalletManager(this.config.walletConfig);
2906
+ this.walletManager = await base$3.createWalletManager(this.config.walletConfig);
2764
2907
  }
2765
2908
  // We can comfortably default to the prod urls here
2766
2909
  const apiBaseUrl = this.config.apiBaseUrl || "https://api.turnkey.com";