@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
@@ -1,7 +1,8 @@
1
1
  import { TurnkeySDKClientBase } from '../__generated__/sdk-client-base.mjs';
2
2
  import { TurnkeyErrorCodes, TurnkeyError, TurnkeyNetworkError, AuthAction } from '@turnkey/sdk-types';
3
- import { SessionKey, DEFAULT_SESSION_EXPIRATION_IN_SECONDS, StamperType, WalletSource, Chain, FilterType, OtpTypeToFilterTypeMap, OtpType, Curve, SignIntent } from '../__types__/base.mjs';
4
- import { withTurnkeyErrorHandling, isValidPasskeyName, isWeb, isReactNative, buildSignUpBody, findWalletProviderFromAddress, addressFromPublicKey, getCurveTypeFromProvider, getPublicKeyFromStampHeader, toExternalTimestamp, getAuthenticatorAddresses, isEthereumProvider, isSolanaProvider, getHashFunction, getEncodingType, getEncodedMessage, splitSignature, broadcastTransaction, getPolicySignature, googleISS, isWalletAccountArray, generateWalletAccountsFromAddressFormat } from '../utils.mjs';
3
+ import { DEFAULT_SESSION_EXPIRATION_IN_SECONDS } from '../__types__/auth.mjs';
4
+ import { SessionKey, StamperType, WalletSource, Chain, FilterType, OtpTypeToFilterTypeMap, OtpType, Curve, SignIntent } from '../__types__/enums.mjs';
5
+ import { withTurnkeyErrorHandling, isValidPasskeyName, isWeb, isReactNative, buildSignUpBody, findWalletProviderFromAddress, addressFromPublicKey, getCurveTypeFromProvider, getPublicKeyFromStampHeader, mapAccountsToWallet, toExternalTimestamp, getAuthenticatorAddresses, isEthereumProvider, isSolanaProvider, getActiveSessionOrThrowIfRequired, getHashFunction, getEncodingType, getEncodedMessage, splitSignature, broadcastTransaction, getPolicySignature, googleISS, isWalletAccountArray, generateWalletAccountsFromAddressFormat } from '../utils.mjs';
5
6
  import { createStorageManager } from '../__storage__/base.mjs';
6
7
  import { CrossPlatformApiKeyStamper } from '../__stampers__/api/base.mjs';
7
8
  import { CrossPlatformPasskeyStamper } from '../__stampers__/passkey/base.mjs';
@@ -22,29 +23,30 @@ class TurnkeyClient {
22
23
  * - The resulting attestation and challenge can be used to register the passkey with Turnkey.
23
24
  *
24
25
  * @param params.name - display name for the passkey (defaults to a generated name based on the current timestamp).
25
- * @param params.stampWith - parameter to stamp the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
26
26
  * @param params.challenge - challenge string to use for passkey registration. If not provided, a new challenge will be generated.
27
- * @returns A promise that resolves to an object containing:
28
- * - attestation: attestation object returned from the passkey creation process.
29
- * - encodedChallenge: encoded challenge string used for passkey registration.
27
+ * @returns A promise that resolves to {@link CreatePasskeyResult}
30
28
  * @throws {TurnkeyError} If there is an error during passkey creation, or if the platform is unsupported.
31
29
  */
32
30
  this.createPasskey = async (params) => {
31
+ const { name: nameFromParams, challenge } = params || {};
33
32
  return withTurnkeyErrorHandling(async () => {
34
- const name = isValidPasskeyName(params?.name || `passkey-${Date.now()}`);
33
+ if (!this.passkeyStamper) {
34
+ throw new TurnkeyError("Passkey stamper is not initialized", TurnkeyErrorCodes.INTERNAL_ERROR);
35
+ }
36
+ const name = isValidPasskeyName(nameFromParams || `passkey-${Date.now()}`);
35
37
  let passkey;
36
38
  if (isWeb()) {
37
- const res = await this.passkeyStamper?.createWebPasskey({
39
+ const res = await this.passkeyStamper.createWebPasskey({
38
40
  publicKey: {
39
41
  user: {
40
42
  name,
41
43
  displayName: name,
42
44
  },
43
- ...(params?.challenge && { challenge: params.challenge }),
45
+ ...(challenge && { challenge }),
44
46
  },
45
47
  });
46
48
  if (!res) {
47
- throw new TurnkeyError("Failed to create React Native passkey", TurnkeyErrorCodes.INTERNAL_ERROR);
49
+ throw new TurnkeyError("Failed to create Web passkey", TurnkeyErrorCodes.INTERNAL_ERROR);
48
50
  }
49
51
  passkey = {
50
52
  encodedChallenge: res?.encodedChallenge,
@@ -52,7 +54,7 @@ class TurnkeyClient {
52
54
  };
53
55
  }
54
56
  else if (isReactNative()) {
55
- const res = await this.passkeyStamper?.createReactNativePasskey({
57
+ const res = await this.passkeyStamper.createReactNativePasskey({
56
58
  name,
57
59
  displayName: name,
58
60
  });
@@ -125,6 +127,7 @@ class TurnkeyClient {
125
127
  * @param params.publicKey - public key to use for authentication. If not provided, a new key pair will be generated.
126
128
  * @param params.sessionKey - session key to use for session creation (defaults to the default session key).
127
129
  * @param params.expirationSeconds - session expiration time in seconds (defaults to the configured default).
130
+ * @param params.organizationId - organization ID to target (defaults to the session's organization ID or the parent organization ID).
128
131
  * @returns A promise that resolves to a {@link PasskeyAuthResult}, which includes:
129
132
  * - `sessionToken`: the signed JWT session token.
130
133
  * - `credentialId`: an empty string.
@@ -142,7 +145,7 @@ class TurnkeyClient {
142
145
  }
143
146
  const sessionResponse = await this.httpClient.stampLogin({
144
147
  publicKey: generatedPublicKey,
145
- organizationId: this.config.organizationId,
148
+ organizationId: params?.organizationId ?? this.config.organizationId,
146
149
  expirationSeconds,
147
150
  }, StamperType.Passkey);
148
151
  await this.storeSession({
@@ -193,13 +196,14 @@ class TurnkeyClient {
193
196
  * @param params.sessionKey - session key to use for storing the session (defaults to the default session key).
194
197
  * @param params.expirationSeconds - session expiration time in seconds (defaults to the configured default).
195
198
  * @param params.challenge - challenge string to use for passkey registration. If not provided, a new challenge will be generated.
199
+ * @param params.organizationId - organization ID to target (defaults to the session's organization ID or the parent organization ID).
196
200
  * @returns A promise that resolves to a {@link PasskeyAuthResult}, which includes:
197
201
  * - `sessionToken`: the signed JWT session token.
198
202
  * - `credentialId`: the credential ID associated with the passkey created.
199
203
  * @throws {TurnkeyError} If there is an error during passkey creation, sub-organization creation, or session storage.
200
204
  */
201
205
  this.signUpWithPasskey = async (params) => {
202
- const { createSubOrgParams, passkeyDisplayName, sessionKey = SessionKey.DefaultSessionkey, expirationSeconds = DEFAULT_SESSION_EXPIRATION_IN_SECONDS, } = params || {};
206
+ const { createSubOrgParams, passkeyDisplayName, sessionKey = SessionKey.DefaultSessionkey, expirationSeconds = DEFAULT_SESSION_EXPIRATION_IN_SECONDS, organizationId, } = params || {};
203
207
  let generatedPublicKey = undefined;
204
208
  return withTurnkeyErrorHandling(async () => {
205
209
  generatedPublicKey = await this.apiKeyStamper?.createKeyPair();
@@ -242,7 +246,7 @@ class TurnkeyClient {
242
246
  this.apiKeyStamper?.setTemporaryPublicKey(generatedPublicKey);
243
247
  const sessionResponse = await this.httpClient.stampLogin({
244
248
  publicKey: newGeneratedKeyPair,
245
- organizationId: this.config.organizationId,
249
+ organizationId: organizationId ?? this.config.organizationId,
246
250
  expirationSeconds,
247
251
  });
248
252
  await this.apiKeyStamper?.deleteKeyPair(generatedPublicKey);
@@ -299,7 +303,7 @@ class TurnkeyClient {
299
303
  * - Requires the wallet manager and its connector to be initialized.
300
304
  *
301
305
  * @param walletProvider - wallet provider to connect.
302
- * @returns A promise that resolves once the wallet account is connected.
306
+ * @returns A promise that resolves with the connected wallet's address.
303
307
  * @throws {TurnkeyError} If the wallet manager is uninitialized or the connection fails.
304
308
  */
305
309
  this.connectWalletAccount = async (walletProvider) => {
@@ -307,7 +311,7 @@ class TurnkeyClient {
307
311
  if (!this.walletManager?.connector) {
308
312
  throw new TurnkeyError("Wallet connector is not initialized", TurnkeyErrorCodes.WALLET_MANAGER_COMPONENT_NOT_INITIALIZED);
309
313
  }
310
- await this.walletManager.connector.connectWalletAccount(walletProvider);
314
+ return await this.walletManager.connector.connectWalletAccount(walletProvider);
311
315
  }, {
312
316
  errorMessage: "Unable to connect wallet account",
313
317
  errorCode: TurnkeyErrorCodes.CONNECT_WALLET_ACCOUNT_ERROR,
@@ -386,6 +390,7 @@ class TurnkeyClient {
386
390
  * @param params.publicKey - optional public key to associate with the session (generated if not provided).
387
391
  * @param params.sessionKey - optional key to store the session under (defaults to the default session key).
388
392
  * @param params.expirationSeconds - optional session expiration time in seconds (defaults to the configured default).
393
+ * @param params.organizationId - organization ID to target (defaults to the session's organization ID or the parent organization ID).
389
394
  * @returns A promise that resolves to a {@link WalletAuthResult}, which includes:
390
395
  * - `sessionToken`: the signed JWT session token.
391
396
  * - `address`: the authenticated wallet address.
@@ -406,7 +411,7 @@ class TurnkeyClient {
406
411
  this.walletManager.stamper.setProvider(walletProvider.interfaceType, walletProvider);
407
412
  const sessionResponse = await this.httpClient.stampLogin({
408
413
  publicKey,
409
- organizationId: this.config.organizationId,
414
+ organizationId: params?.organizationId ?? this.config.organizationId,
410
415
  expirationSeconds,
411
416
  }, StamperType.Wallet);
412
417
  await this.storeSession({
@@ -450,6 +455,7 @@ class TurnkeyClient {
450
455
  * @param params.createSubOrgParams - parameters for creating a sub-organization (e.g., authenticators, user metadata).
451
456
  * @param params.sessionKey - session key to use for storing the session (defaults to the default session key).
452
457
  * @param params.expirationSeconds - session expiration time in seconds (defaults to the configured default).
458
+ * @param params.organizationId - organization ID to target (defaults to the session's organization ID or the parent organization ID).
453
459
  * @returns A promise that resolves to a {@link WalletAuthResult}, which includes:
454
460
  * - `sessionToken`: the signed JWT session token.
455
461
  * - `address`: the authenticated wallet address.
@@ -541,6 +547,7 @@ class TurnkeyClient {
541
547
  * @param params.createSubOrgParams - optional parameters for creating a sub-organization (e.g., authenticators, user metadata).
542
548
  * @param params.sessionKey - session key to use for storing the session (defaults to the default session key).
543
549
  * @param params.expirationSeconds - session expiration time in seconds (defaults to the configured default).
550
+ * @param params.organizationId - organization ID to target (defaults to the session's organization ID or the parent organization ID).
544
551
  * @returns A promise that resolves to an object containing:
545
552
  * - `sessionToken`: the signed JWT session token.
546
553
  * - `address`: the authenticated wallet address.
@@ -572,6 +579,10 @@ class TurnkeyClient {
572
579
  errorMessage: "Failed to create stamped request for wallet login",
573
580
  errorCode: TurnkeyErrorCodes.WALLET_LOGIN_OR_SIGNUP_ERROR,
574
581
  customErrorsByMessages: {
582
+ "WalletConnect: The connection request has expired. Please scan the QR code again.": {
583
+ message: "Your WalletConnect session expired. Please scan the QR code again.",
584
+ code: TurnkeyErrorCodes.WALLET_CONNECT_EXPIRED,
585
+ },
575
586
  "Failed to sign the message": {
576
587
  message: "Wallet auth was cancelled by the user.",
577
588
  code: TurnkeyErrorCodes.CONNECT_WALLET_CANCELLED,
@@ -682,6 +693,7 @@ class TurnkeyClient {
682
693
  *
683
694
  * @param params.otpType - type of OTP to initialize (OtpType.Email or OtpType.Sms).
684
695
  * @param params.contact - contact information for the user (e.g., email address or phone number).
696
+ * @param params.organizationId - optional organization ID to target (defaults to the session's organization ID or the parent organization ID).
685
697
  * @returns A promise that resolves to the OTP ID required for verification.
686
698
  * @throws {TurnkeyError} If there is an error during the OTP initialization process or if the maximum number of OTPs has been reached.
687
699
  */
@@ -764,6 +776,7 @@ class TurnkeyClient {
764
776
  *
765
777
  * @param params.verificationToken - verification token received after OTP verification.
766
778
  * @param params.publicKey - public key to use for authentication. If not provided, a new key pair will be generated.
779
+ * @param params.organizationId - optional organization ID to target (defaults to the verified subOrg ID linked to the verification token contact).
767
780
  * @param params.invalidateExisting - flag to invalidate existing session for the user.
768
781
  * @param params.sessionKey - session key to use for session creation (defaults to the default session key).
769
782
  * @returns A promise that resolves to a {@link BaseAuthResult}, which includes:
@@ -771,12 +784,13 @@ class TurnkeyClient {
771
784
  * @throws {TurnkeyError} If there is an error during the OTP login process or if key pair cleanup fails.
772
785
  */
773
786
  this.loginWithOtp = async (params) => {
774
- const { verificationToken, invalidateExisting = false, publicKey = await this.apiKeyStamper?.createKeyPair(), sessionKey = SessionKey.DefaultSessionkey, } = params;
787
+ const { verificationToken, invalidateExisting = false, publicKey = await this.apiKeyStamper?.createKeyPair(), organizationId, sessionKey = SessionKey.DefaultSessionkey, } = params;
775
788
  return withTurnkeyErrorHandling(async () => {
776
789
  const res = await this.httpClient.proxyOtpLogin({
777
790
  verificationToken,
778
791
  publicKey: publicKey,
779
792
  invalidateExisting,
793
+ ...(organizationId && { organizationId }),
780
794
  });
781
795
  if (!res) {
782
796
  throw new TurnkeyError(`Auth proxy OTP login failed`, TurnkeyErrorCodes.OTP_LOGIN_ERROR);
@@ -1100,36 +1114,61 @@ class TurnkeyClient {
1100
1114
  * - Returns both embedded and connected wallets in a single array, each with their respective accounts populated.
1101
1115
  * - Optionally allows stamping the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
1102
1116
  *
1103
- * @param params.stampWith - parameter to stamp the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
1104
1117
  * @param params.walletProviders - array of wallet providers to use for fetching wallets.
1118
+ * @param params.organizationId - organization ID to target (defaults to the session's organization ID).
1119
+ * @param params.userId - user ID to target (defaults to the session's user ID).
1120
+ * @param params.connectedOnly - if true, fetches only connected wallets; if false or undefined, fetches both embedded and connected wallets.
1121
+ * @param params.stampWith - parameter to stamp the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
1105
1122
  * @returns A promise that resolves to an array of `Wallet` objects.
1106
1123
  * @throws {TurnkeyError} If no active session is found or if there is an error fetching wallets.
1107
1124
  */
1108
1125
  this.fetchWallets = async (params) => {
1109
- const { stampWith, walletProviders } = params || {};
1126
+ const { walletProviders, organizationId: organizationIdFromParams, userId: userIdFromParams, connectedOnly, stampWith, } = params || {};
1110
1127
  const session = await this.storageManager.getActiveSession();
1111
- if (!session) {
1112
- throw new TurnkeyError("No active session found. Please log in first.", TurnkeyErrorCodes.NO_SESSION_FOUND);
1128
+ if (!session && !connectedOnly) {
1129
+ throw new TurnkeyError("No active session found. Fetching embedded wallets requires a valid session. If you only need connected wallets, set the 'connectedOnly' parameter to true.", TurnkeyErrorCodes.NO_SESSION_FOUND);
1130
+ }
1131
+ // if `connectedOnly` is true, we need to make sure the walletManager is initialized
1132
+ // or else we can't fetch connected wallets, and we throw an error
1133
+ if (connectedOnly && !this.walletManager?.connector) {
1134
+ throw new TurnkeyError("Wallet connector is not initialized", TurnkeyErrorCodes.WALLET_MANAGER_COMPONENT_NOT_INITIALIZED);
1113
1135
  }
1114
1136
  return withTurnkeyErrorHandling(async () => {
1115
- const res = await this.httpClient.getWallets({ organizationId: session.organizationId }, stampWith);
1116
- if (!res || !res.wallets) {
1117
- throw new TurnkeyError("No wallets found in the response", TurnkeyErrorCodes.BAD_RESPONSE);
1118
- }
1119
- const embedded = await Promise.all(res.wallets.map(async (wallet) => {
1120
- const embeddedWallet = {
1121
- ...wallet,
1122
- source: WalletSource.Embedded,
1123
- accounts: [],
1124
- };
1125
- const accounts = await this.fetchWalletAccounts({
1126
- wallet: embeddedWallet,
1127
- ...(stampWith !== undefined && { stampWith }),
1128
- });
1129
- embeddedWallet.accounts = accounts;
1130
- return embeddedWallet;
1131
- }));
1137
+ let embedded = [];
1138
+ // if connectedOnly is true, we skip fetching embedded wallets
1139
+ if (!connectedOnly) {
1140
+ const organizationId = organizationIdFromParams || session?.organizationId;
1141
+ if (!organizationId) {
1142
+ throw new TurnkeyError("No organization ID provided and no active session found. Please log in first or pass in an organization ID.", TurnkeyErrorCodes.INVALID_REQUEST);
1143
+ }
1144
+ const userId = userIdFromParams || session?.userId;
1145
+ if (!userId) {
1146
+ throw new TurnkeyError("No user ID provided and no active session found. Please log in first or pass in a user ID.", TurnkeyErrorCodes.INVALID_REQUEST);
1147
+ }
1148
+ const res = await this.httpClient.getWalletAccounts({
1149
+ organizationId,
1150
+ includeWalletDetails: true,
1151
+ }, stampWith);
1152
+ const walletsRes = await this.httpClient.getWallets({
1153
+ organizationId,
1154
+ }, stampWith);
1155
+ if (!res || !res.accounts) {
1156
+ throw new TurnkeyError("No wallet accounts found in the response", TurnkeyErrorCodes.BAD_RESPONSE);
1157
+ }
1158
+ // create a map of walletId to EmbeddedWallet for easy lookup
1159
+ const walletMap = new Map(walletsRes.wallets.map((wallet) => [
1160
+ wallet.walletId,
1161
+ {
1162
+ ...wallet,
1163
+ source: WalletSource.Embedded,
1164
+ accounts: [],
1165
+ },
1166
+ ]));
1167
+ // map the accounts to their respective wallets
1168
+ embedded = mapAccountsToWallet(res.accounts, walletMap);
1169
+ }
1132
1170
  // if wallet connecting is disabled we return only embedded wallets
1171
+ // this will never be hit if `connectedOnly` is true because of the check above
1133
1172
  if (!this.walletManager?.connector)
1134
1173
  return embedded;
1135
1174
  const providers = walletProviders ?? (await this.fetchWalletProviders());
@@ -1143,7 +1182,11 @@ class TurnkeyClient {
1143
1182
  group.push(provider);
1144
1183
  groupedProviders.set(walletId, group);
1145
1184
  }
1146
- const connected = (await Promise.all(Array.from(groupedProviders.entries()).map(async ([walletId, grouped]) => {
1185
+ // has to be done in a for of loop so we can await each fetchWalletAccounts call individually
1186
+ // otherwise await Promise.all would cause them all to fire at once breaking passkey only set ups
1187
+ // (multiple wallet fetches at once causing "OperationError: A request is already pending.")
1188
+ let connected = [];
1189
+ for (const [walletId, grouped] of groupedProviders.entries()) {
1147
1190
  const timestamp = toExternalTimestamp();
1148
1191
  const wallet = {
1149
1192
  source: WalletSource.Connected,
@@ -1159,10 +1202,16 @@ class TurnkeyClient {
1159
1202
  wallet,
1160
1203
  walletProviders: grouped,
1161
1204
  ...(stampWith !== undefined && { stampWith }),
1205
+ ...(organizationIdFromParams !== undefined && {
1206
+ organizationId: organizationIdFromParams,
1207
+ }),
1208
+ ...(userIdFromParams !== undefined && { userId: userIdFromParams }),
1162
1209
  });
1163
1210
  wallet.accounts = accounts;
1164
- return wallet;
1165
- }))).filter((wallet) => wallet.accounts.length > 0);
1211
+ if (wallet.accounts.length > 0) {
1212
+ connected.push(wallet);
1213
+ }
1214
+ }
1166
1215
  return [...embedded, ...connected];
1167
1216
  }, {
1168
1217
  errorMessage: "Failed to fetch wallets",
@@ -1182,22 +1231,30 @@ class TurnkeyClient {
1182
1231
  * @param params.walletProviders - list of wallet providers to filter by (used for connected wallets).
1183
1232
  * @param params.paginationOptions - pagination options for embedded wallets.
1184
1233
  * @param params.stampWith - parameter to stamp the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
1234
+ * @param params.organizationId - organization ID to target (defaults to the session's organization ID).
1235
+ * @param params.userId - user ID to target (defaults to the session's user ID).
1236
+ *
1185
1237
  * @returns A promise that resolves to an array of `v1WalletAccount` objects.
1186
1238
  * @throws {TurnkeyError} If no active session is found or if there is an error fetching wallet accounts.
1187
1239
  */
1188
1240
  this.fetchWalletAccounts = async (params) => {
1189
1241
  const { wallet, stampWith, walletProviders, paginationOptions } = params;
1190
1242
  const session = await this.storageManager.getActiveSession();
1191
- if (!session) {
1192
- throw new TurnkeyError("No active session found. Please log in first.", TurnkeyErrorCodes.NO_SESSION_FOUND);
1193
- }
1243
+ const organizationId = params?.organizationId || session?.organizationId;
1244
+ const userId = params?.userId || session?.userId;
1194
1245
  return withTurnkeyErrorHandling(async () => {
1195
1246
  // this is an embedded wallet so we fetch accounts from Turnkey
1196
1247
  if (wallet.source === WalletSource.Embedded) {
1197
1248
  const embedded = [];
1249
+ if (!organizationId) {
1250
+ throw new TurnkeyError("No organization ID provided and no active session found. Please log in first or pass in an organization ID.", TurnkeyErrorCodes.INVALID_REQUEST);
1251
+ }
1252
+ if (!userId) {
1253
+ throw new TurnkeyError("No user ID provided and no active session found. Please log in first or pass in a user ID.", TurnkeyErrorCodes.INVALID_REQUEST);
1254
+ }
1198
1255
  const res = await this.httpClient.getWalletAccounts({
1199
1256
  walletId: wallet.walletId,
1200
- organizationId: session.organizationId,
1257
+ organizationId,
1201
1258
  paginationOptions: paginationOptions || { limit: "100" },
1202
1259
  }, stampWith);
1203
1260
  if (!res || !res.accounts) {
@@ -1228,17 +1285,26 @@ class TurnkeyClient {
1228
1285
  const matching = providers.filter((p) => p.info?.name?.toLowerCase().replace(/\s+/g, "-") ===
1229
1286
  wallet.walletId && p.connectedAddresses.length > 0);
1230
1287
  const sign = this.walletManager.connector.sign.bind(this.walletManager.connector);
1231
- const user = await this.fetchUser({
1232
- stampWith,
1233
- });
1234
- const { ethereum: ethereumAddresses, solana: solanaAddresses } = getAuthenticatorAddresses(user);
1288
+ let ethereumAddresses = [];
1289
+ let solanaAddresses = [];
1290
+ // we only fetch the user if we have to the organizationId and userId
1291
+ // if not that means `isAuthenticator` will always be false
1292
+ if (organizationId && userId) {
1293
+ const user = await this.fetchUser({
1294
+ userId,
1295
+ organizationId,
1296
+ stampWith,
1297
+ });
1298
+ ({ ethereum: ethereumAddresses, solana: solanaAddresses } =
1299
+ getAuthenticatorAddresses(user));
1300
+ }
1235
1301
  for (const provider of matching) {
1236
1302
  const timestamp = toExternalTimestamp();
1237
1303
  for (const address of provider.connectedAddresses) {
1238
1304
  if (isEthereumProvider(provider)) {
1239
1305
  const evmAccount = {
1240
1306
  walletAccountId: `${wallet.walletId}-${provider.interfaceType}-${address}`,
1241
- organizationId: session.organizationId,
1307
+ organizationId: organizationId ?? "",
1242
1308
  walletId: wallet.walletId,
1243
1309
  pathFormat: "PATH_FORMAT_BIP32",
1244
1310
  path: WalletSource.Connected,
@@ -1260,7 +1326,7 @@ class TurnkeyClient {
1260
1326
  if (isSolanaProvider(provider)) {
1261
1327
  const solAccount = {
1262
1328
  walletAccountId: `${wallet.walletId}-${provider.interfaceType}-${address}`,
1263
- organizationId: session.organizationId,
1329
+ organizationId: organizationId ?? "",
1264
1330
  walletId: wallet.walletId,
1265
1331
  pathFormat: "PATH_FORMAT_BIP32",
1266
1332
  path: WalletSource.Connected,
@@ -1296,17 +1362,19 @@ class TurnkeyClient {
1296
1362
  * - Supports stamping the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
1297
1363
  *
1298
1364
  * @param params.stampWith - parameter to stamp the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
1365
+ * @param params.organizationId - organization ID to target (defaults to the session's organization ID).
1299
1366
  * @returns A promise that resolves to an array of `v1PrivateKey` objects.
1300
1367
  * @throws {TurnkeyError} If no active session is found or if there is an error fetching private keys.
1301
1368
  */
1302
1369
  this.fetchPrivateKeys = async (params) => {
1303
1370
  const { stampWith } = params || {};
1304
- const session = await this.storageManager.getActiveSession();
1305
- if (!session) {
1306
- throw new TurnkeyError("No active session found. Please log in first.", TurnkeyErrorCodes.NO_SESSION_FOUND);
1371
+ const session = await getActiveSessionOrThrowIfRequired(stampWith, this.storageManager.getActiveSession);
1372
+ const organizationId = params?.organizationId || session?.organizationId;
1373
+ if (!organizationId) {
1374
+ throw new TurnkeyError("No organization ID provided and no active session found. Please log in first or pass in an organization ID.", TurnkeyErrorCodes.INVALID_REQUEST);
1307
1375
  }
1308
1376
  return withTurnkeyErrorHandling(async () => {
1309
- const res = await this.httpClient.getPrivateKeys({ organizationId: session.organizationId }, stampWith);
1377
+ const res = await this.httpClient.getPrivateKeys({ organizationId }, stampWith);
1310
1378
  if (!res) {
1311
1379
  throw new TurnkeyError("Failed to fetch private keys", TurnkeyErrorCodes.BAD_RESPONSE);
1312
1380
  }
@@ -1319,33 +1387,43 @@ class TurnkeyClient {
1319
1387
  /**
1320
1388
  * Signs a message using the specified wallet account.
1321
1389
  *
1322
- * - Supports both embedded and connected wallets.
1323
- * - For **connected wallets**:
1390
+ * Behavior differs depending on the wallet type:
1391
+ *
1392
+ * - **Connected wallets**
1324
1393
  * - Delegates signing to the wallet provider’s native signing method.
1325
- * - **Important:** For Ethereum wallets (e.g., MetaMask), signatures follow [EIP-191](https://eips.ethereum.org/EIPS/eip-191).
1326
- * The message is automatically prefixed with `"\x19Ethereum Signed Message:\n" + message length`
1327
- * before signing. As a result, this signature **cannot be used as a raw transaction signature**
1328
- * or broadcast on-chain.
1329
- * - For **embedded wallets**, uses the Turnkey API to sign the message directly.
1330
- * - Automatically handles message encoding and hashing based on the wallet account’s address format,
1394
+ * - *Ethereum*: signatures always follow [EIP-191](https://eips.ethereum.org/EIPS/eip-191).
1395
+ * - The wallet automatically prefixes messages with
1396
+ * `"\x19Ethereum Signed Message:\n" + message length` before signing.
1397
+ * - As a result, these signatures cannot be used as raw transaction signatures or broadcast on-chain.
1398
+ * - If `addEthereumPrefix` is set to `false`, an error is thrown because connected Ethereum wallets always prefix.
1399
+ * - *Other chains*: follows the native connected wallet behavior.
1400
+ *
1401
+ * - **Embedded wallets**
1402
+ * - Uses the Turnkey API to sign the message directly.
1403
+ * - Supports optional `addEthereumPrefix`:
1404
+ * - If `true` (default for Ethereum), the message is prefixed before signing.
1405
+ * - If `false`, the raw message is signed without any prefix.
1406
+ *
1407
+ * Additional details:
1408
+ * - Automatically handles encoding and hashing based on the wallet account’s address format,
1331
1409
  * unless explicitly overridden.
1410
+ * - Optionally allows stamping with a specific stamper
1411
+ * (`StamperType.Passkey`, `StamperType.ApiKey`, or `StamperType.Wallet`).
1332
1412
  *
1333
- * @param params.message - message to sign.
1413
+ * @param params.message - plaintext (UTF-8) message to sign.
1334
1414
  * @param params.walletAccount - wallet account to use for signing.
1335
- * @param params.encoding - override for the payload encoding (defaults to the encoding appropriate for the address type).
1336
- * @param params.hashFunction - override for the hash function (defaults to the hash function appropriate for the address type).
1337
- * @param params.stampWith - stamper to tag the signing request (e.g., Passkey, ApiKey, or Wallet).
1338
- * @param params.addEthereumPrefix - whether to prefix the message with Ethereum's `"\x19Ethereum Signed Message:\n"` string.
1339
- * - If `true` (default for Ethereum), the message is prefixed before signing.
1340
- * - If `false`:
1341
- * - Connected wallets will throw an error because they always prefix automatically.
1342
- * - Embedded wallets will sign the raw message without any prefix.
1343
- *
1344
- * @returns A promise resolving to a `v1SignRawPayloadResult` containing the signature and metadata.
1345
- * @throws {TurnkeyError} If signing fails, if the wallet account does not support signing, or if the response is invalid.
1415
+ * @param params.encoding - override for payload encoding (defaults to the encoding appropriate for the address format).
1416
+ * @param params.hashFunction - override for hash function (defaults to the function appropriate for the address format).
1417
+ * @param params.stampWith - optional stamper for the signing request.
1418
+ * @param params.addEthereumPrefix - whether to prefix the message with Ethereums
1419
+ * `"\x19Ethereum Signed Message:\n"` string (default: `true` for Ethereum).
1420
+ * @param params.organizationId - organization ID to target (defaults to the session's organization ID).
1421
+ *
1422
+ * @returns A promise that resolves to a `v1SignRawPayloadResult` containing the signature and metadata.
1423
+ * @throws {TurnkeyError} If signing fails, the wallet type does not support message signing, or the response is invalid.
1346
1424
  */
1347
1425
  this.signMessage = async (params) => {
1348
- const { message, walletAccount, stampWith, addEthereumPrefix } = params;
1426
+ const { message, walletAccount, stampWith, addEthereumPrefix, organizationId, } = params;
1349
1427
  const hashFunction = params.hashFunction || getHashFunction(walletAccount.addressFormat);
1350
1428
  const payloadEncoding = params.encoding || getEncodingType(walletAccount.addressFormat);
1351
1429
  return withTurnkeyErrorHandling(async () => {
@@ -1357,23 +1435,29 @@ class TurnkeyClient {
1357
1435
  }
1358
1436
  let encodedMessage = message;
1359
1437
  if (isEthereum) {
1360
- encodedMessage = getEncodedMessage(walletAccount.addressFormat, message);
1438
+ const msgBytes = toUtf8Bytes(message);
1439
+ encodedMessage = getEncodedMessage(payloadEncoding, msgBytes);
1361
1440
  }
1362
1441
  const sigHex = await walletAccount.signMessage(encodedMessage);
1363
1442
  return splitSignature(sigHex, walletAccount.addressFormat);
1364
1443
  }
1365
1444
  // this is an embedded wallet
1366
- let messageToEncode = message;
1445
+ let msgBytes = toUtf8Bytes(message);
1367
1446
  if (addEthereumPrefix && isEthereum) {
1368
- const prefix = `\x19Ethereum Signed Message:\n${toUtf8Bytes(message).length}`;
1369
- messageToEncode = prefix + message;
1370
- }
1371
- const encodedMessage = getEncodedMessage(walletAccount.addressFormat, messageToEncode);
1447
+ const prefix = `\x19Ethereum Signed Message:\n${msgBytes.length}`;
1448
+ const prefixBytes = toUtf8Bytes(prefix);
1449
+ const combined = new Uint8Array(prefixBytes.length + msgBytes.length);
1450
+ combined.set(prefixBytes, 0);
1451
+ combined.set(msgBytes, prefixBytes.length);
1452
+ msgBytes = combined;
1453
+ }
1454
+ const encodedMessage = getEncodedMessage(payloadEncoding, msgBytes);
1372
1455
  const response = await this.httpClient.signRawPayload({
1373
1456
  signWith: walletAccount.address,
1374
1457
  payload: encodedMessage,
1375
1458
  encoding: payloadEncoding,
1376
1459
  hashFunction,
1460
+ ...(organizationId && { organizationId }),
1377
1461
  }, stampWith);
1378
1462
  if (response.activity.failure) {
1379
1463
  throw new TurnkeyError("Failed to sign message, no signed payload returned", TurnkeyErrorCodes.SIGN_MESSAGE_ERROR);
@@ -1388,21 +1472,29 @@ class TurnkeyClient {
1388
1472
  /**
1389
1473
  * Signs a transaction using the specified wallet account.
1390
1474
  *
1391
- * - This function signs a blockchain transaction using the provided wallet address and transaction data.
1392
- * - Supports all Turnkey-supported blockchain networks (e.g., Ethereum, Solana, Tron).
1393
- * - Automatically determines the appropriate signing method based on the transaction type.
1394
- * - Delegates signing to the Turnkey API, which returns the signed transaction and related metadata.
1395
- * - Optionally allows stamping the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
1475
+ * Behavior differs depending on the type of wallet:
1476
+ *
1477
+ * - **Connected wallets**
1478
+ * - Ethereum: does not support raw transaction signing. Calling this function will throw an error instructing you to use `signAndSendTransaction` instead.
1479
+ * - Solana: supports raw transaction signing via the connected wallet provider.
1480
+ * - Other chains: not supported; will throw an error.
1396
1481
  *
1397
- * @param params.walletAccount - wallet account to use for signing the transaction.
1398
- * @param params.unsignedTransaction - unsigned transaction data (serialized as a string) to be signed.
1482
+ * - **Embedded wallets**
1483
+ * - Delegates signing to the Turnkey API, which returns the signed transaction.
1484
+ * - Supports all Turnkey-supported transaction types (e.g., Ethereum, Solana, Tron).
1485
+ * - Optionally allows stamping with a specific stamper (`StamperType.Passkey`, `StamperType.ApiKey`, or `StamperType.Wallet`).
1486
+ *
1487
+ * @param params.walletAccount - wallet account to use for signing.
1488
+ * @param params.unsignedTransaction - unsigned transaction data as a serialized
1489
+ * string in the canonical encoding for the given `transactionType`.
1399
1490
  * @param params.transactionType - type of transaction (e.g., "TRANSACTION_TYPE_ETHEREUM", "TRANSACTION_TYPE_SOLANA", "TRANSACTION_TYPE_TRON").
1400
- * @param params.stampWith - parameter to stamp the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
1401
- * @returns A promise that resolves to a `TSignTransactionResponse` object containing the signed transaction and any additional signing metadata.
1402
- * @throws {TurnkeyError} If there is an error signing the transaction or if the response is invalid.
1491
+ * @param params.stampWith - stamper to use for signing (`StamperType.Passkey`, `StamperType.ApiKey`, or `StamperType.Wallet`).
1492
+ * @param params.organizationId - organization ID to target (defaults to the session's organization ID).
1493
+ * @returns A promise that resolves to the signed transaction string.
1494
+ * @throws {TurnkeyError} If the wallet type is unsupported, signing fails, or the response is invalid.
1403
1495
  */
1404
1496
  this.signTransaction = async (params) => {
1405
- const { walletAccount, unsignedTransaction, transactionType, stampWith } = params;
1497
+ const { walletAccount, unsignedTransaction, transactionType, stampWith, organizationId, } = params;
1406
1498
  return withTurnkeyErrorHandling(async () => {
1407
1499
  if (walletAccount.source === WalletSource.Connected) {
1408
1500
  switch (walletAccount.chainInfo.namespace) {
@@ -1421,6 +1513,7 @@ class TurnkeyClient {
1421
1513
  signWith: walletAccount.address,
1422
1514
  unsignedTransaction,
1423
1515
  type: transactionType,
1516
+ ...(organizationId && { organizationId }),
1424
1517
  }, stampWith);
1425
1518
  return signTransaction.signedTransaction;
1426
1519
  }, {
@@ -1431,25 +1524,32 @@ class TurnkeyClient {
1431
1524
  /**
1432
1525
  * Signs and broadcasts a transaction using the specified wallet account.
1433
1526
  *
1434
- * - For **connected wallets**:
1435
- * - Calls the wallet’s native `signAndSendTransaction` method.
1436
- * - Does **not** require an `rpcUrl`.
1527
+ * Behavior differs depending on the type of wallet:
1528
+ *
1529
+ * - **Connected wallets**
1530
+ * - *Ethereum*: delegates to the wallet’s native `signAndSendTransaction` method.
1531
+ * - Does **not** require an `rpcUrl` (the wallet handles broadcasting).
1532
+ * - *Solana*: signs the transaction locally with the connected wallet, but requires an `rpcUrl` to broadcast it.
1533
+ * - Other chains: not supported; will throw an error.
1437
1534
  *
1438
- * - For **embedded wallets**:
1535
+ * - **Embedded wallets**
1439
1536
  * - Signs the transaction using the Turnkey API.
1440
- * - Requires an `rpcUrl` to broadcast the transaction.
1441
- * - Broadcasts the transaction using a JSON-RPC client.
1442
- *
1443
- * @param params.walletAccount - wallet account to use for signing and sending.
1444
- * @param params.unsignedTransaction - unsigned transaction (serialized string).
1445
- * @param params.transactionType - transaction type (e.g., "TRANSACTION_TYPE_SOLANA").
1446
- * @param params.rpcUrl - required for embedded wallets to broadcast the signed transaction.
1447
- * @param params.stampWith - optional stamper to tag the signing request.
1537
+ * - Requires an `rpcUrl` to broadcast the signed transaction, since Turnkey does not broadcast directly.
1538
+ * - Broadcasts the transaction using a JSON-RPC client and returns the resulting transaction hash/signature.
1539
+ * - Optionally allows stamping with a specific stamper (`StamperType.Passkey`, `StamperType.ApiKey`, or `StamperType.Wallet`).
1540
+ *
1541
+ * @param params.walletAccount - wallet account to use for signing and broadcasting.
1542
+ * @param params.unsignedTransaction - unsigned transaction data as a serialized
1543
+ * string in the canonical encoding for the given `transactionType`.
1544
+ * @param params.transactionType - type of transaction (e.g., `"TRANSACTION_TYPE_SOLANA"`, `"TRANSACTION_TYPE_ETHEREUM"`).
1545
+ * @param params.rpcUrl - JSON-RPC endpoint used for broadcasting (required for Solana connected wallets and all embedded wallets).
1546
+ * @param params.stampWith - optional stamper to use when signing (`StamperType.Passkey`, `StamperType.ApiKey`, or `StamperType.Wallet`).
1547
+ * @param params.organizationId - **Only for Turnkey embedded wallets**: organization ID to target (defaults to the session's organization ID).
1448
1548
  * @returns A promise that resolves to a transaction signature or hash.
1449
- * @throws {TurnkeyError} If signing or broadcasting fails.
1549
+ * @throws {TurnkeyError} If the wallet type is unsupported, or if signing/broadcasting fails.
1450
1550
  */
1451
1551
  this.signAndSendTransaction = async (params) => {
1452
- const { walletAccount, unsignedTransaction, transactionType, rpcUrl, stampWith, } = params;
1552
+ const { walletAccount, unsignedTransaction, transactionType, rpcUrl, stampWith, organizationId, } = params;
1453
1553
  return withTurnkeyErrorHandling(async () => {
1454
1554
  if (walletAccount.source === WalletSource.Connected) {
1455
1555
  // this is a connected wallet account
@@ -1484,6 +1584,7 @@ class TurnkeyClient {
1484
1584
  signWith: walletAccount.address,
1485
1585
  unsignedTransaction,
1486
1586
  type: transactionType,
1587
+ ...(organizationId && { organizationId }),
1487
1588
  }, stampWith);
1488
1589
  const signedTx = signTransactionResponse.signedTransaction;
1489
1590
  const txHash = await broadcastTransaction({
@@ -1513,16 +1614,16 @@ class TurnkeyClient {
1513
1614
  * @throws {TurnkeyError} If there is no active session, if there is no userId, or if there is an error fetching user details.
1514
1615
  */
1515
1616
  this.fetchUser = async (params) => {
1516
- const { stampWith } = params || {};
1517
- const session = await this.storageManager.getActiveSession();
1518
- if (!session) {
1519
- throw new TurnkeyError("No active session found. Please log in first.", TurnkeyErrorCodes.NO_SESSION_FOUND);
1520
- }
1521
- const userId = params?.userId || session.userId;
1617
+ const { organizationId: organizationIdFromParams, userId: userIdFromParams, stampWith, } = params || {};
1618
+ const session = await getActiveSessionOrThrowIfRequired(stampWith, this.storageManager.getActiveSession);
1619
+ const userId = userIdFromParams || session?.userId;
1522
1620
  if (!userId) {
1523
1621
  throw new TurnkeyError("User ID must be provided to fetch user", TurnkeyErrorCodes.INVALID_REQUEST);
1524
1622
  }
1525
- const organizationId = params?.organizationId || session.organizationId;
1623
+ const organizationId = organizationIdFromParams || session?.organizationId;
1624
+ if (!organizationId) {
1625
+ throw new TurnkeyError("Organization ID must be provided to fetch user", TurnkeyErrorCodes.INVALID_REQUEST);
1626
+ }
1526
1627
  return withTurnkeyErrorHandling(async () => {
1527
1628
  const userResponse = await this.httpClient.getUser({ organizationId, userId }, stampWith);
1528
1629
  if (!userResponse || !userResponse.user) {
@@ -1545,24 +1646,26 @@ class TurnkeyClient {
1545
1646
  * @param params.publicKey - the P-256 public key to use for lookup and creation.
1546
1647
  * @param params.createParams.userName - optional username to assign if creating a new user (defaults to `"Public Key User"`).
1547
1648
  * @param params.createParams.apiKeyName - optional API key name to assign if creating a new API key (defaults to `public-key-user-${publicKey}`).
1649
+ * @param params.organizationId - organization ID to specify the sub-organization (defaults to the current session's organizationId).
1650
+ * @param params.stampWith - parameter to stamp the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
1548
1651
  * @returns A promise that resolves to the existing or newly created {@link v1User}.
1549
1652
  * @throws {TurnkeyError} If there is no active session, if the input is invalid, if user retrieval fails, or if user creation fails.
1550
1653
  */
1551
1654
  this.fetchOrCreateP256ApiKeyUser = async (params) => {
1552
- const { publicKey, createParams } = params;
1655
+ const { publicKey, createParams, stampWith, organizationId: organizationIdFromParams, } = params;
1553
1656
  return withTurnkeyErrorHandling(async () => {
1554
- const session = await this.storageManager.getActiveSession();
1555
- if (!session) {
1556
- throw new TurnkeyError("No active session found. Please log in first.", TurnkeyErrorCodes.NO_SESSION_FOUND);
1657
+ const session = await getActiveSessionOrThrowIfRequired(stampWith, this.storageManager.getActiveSession);
1658
+ const organizationId = organizationIdFromParams || session?.organizationId;
1659
+ if (!organizationId) {
1660
+ throw new TurnkeyError("Organization ID is required to fetch or create P-256 API key user.", TurnkeyErrorCodes.INVALID_REQUEST);
1557
1661
  }
1558
- const organizationId = session.organizationId;
1559
1662
  // we validate their input
1560
1663
  if (!publicKey?.trim()) {
1561
1664
  throw new TurnkeyError("'publicKey' is required and cannot be empty.", TurnkeyErrorCodes.INVALID_REQUEST);
1562
1665
  }
1563
1666
  const usersResponse = await this.httpClient.getUsers({
1564
1667
  organizationId,
1565
- });
1668
+ }, stampWith);
1566
1669
  if (!usersResponse || !usersResponse.users) {
1567
1670
  throw new TurnkeyError("No users found in the response", TurnkeyErrorCodes.BAD_RESPONSE);
1568
1671
  }
@@ -1592,7 +1695,7 @@ class TurnkeyClient {
1592
1695
  oauthProviders: [],
1593
1696
  },
1594
1697
  ],
1595
- });
1698
+ }, stampWith);
1596
1699
  if (!createUserResp?.userIds ||
1597
1700
  createUserResp.userIds.length === 0 ||
1598
1701
  !createUserResp.userIds[0]) {
@@ -1602,6 +1705,7 @@ class TurnkeyClient {
1602
1705
  return await this.fetchUser({
1603
1706
  organizationId,
1604
1707
  userId: newUserId,
1708
+ stampWith,
1605
1709
  });
1606
1710
  }, {
1607
1711
  errorMessage: "Failed to get or create P-256 API key user",
@@ -1617,6 +1721,8 @@ class TurnkeyClient {
1617
1721
  * - If it does not exist, it is created and returned with its new `policyId`.
1618
1722
  *
1619
1723
  * @param params.policies - the list of policies to fetch or create.
1724
+ * @param params.stampWith - parameter to stamp the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
1725
+ * @param params.organizationId - organization ID to specify the sub-organization (defaults to the current session's organizationId).
1620
1726
  * @returns A promise that resolves to an array of objects, each containing:
1621
1727
  * - `policyId`: the unique identifier of the policy.
1622
1728
  * - `policyName`: human-readable name of the policy.
@@ -1628,20 +1734,20 @@ class TurnkeyClient {
1628
1734
  * if fetching policies fails, or if creating policies fails.
1629
1735
  */
1630
1736
  this.fetchOrCreatePolicies = async (params) => {
1631
- const { policies } = params;
1737
+ const { policies, stampWith } = params;
1632
1738
  return await withTurnkeyErrorHandling(async () => {
1633
- const session = await this.storageManager.getActiveSession();
1634
- if (!session) {
1635
- throw new TurnkeyError("No active session found. Please log in first.", TurnkeyErrorCodes.NO_SESSION_FOUND);
1636
- }
1739
+ const session = await getActiveSessionOrThrowIfRequired(stampWith, this.storageManager.getActiveSession);
1637
1740
  if (!Array.isArray(policies) || policies.length === 0) {
1638
1741
  throw new TurnkeyError("'policies' must be a non-empty array of policy definitions.", TurnkeyErrorCodes.INVALID_REQUEST);
1639
1742
  }
1640
- const organizationId = session.organizationId;
1743
+ const organizationId = params?.organizationId ?? session?.organizationId;
1744
+ if (!organizationId) {
1745
+ throw new TurnkeyError("Organization ID is required to fetch or create policies.", TurnkeyErrorCodes.INVALID_REQUEST);
1746
+ }
1641
1747
  // we first fetch existing policies
1642
1748
  const existingPoliciesResponse = await this.httpClient.getPolicies({
1643
1749
  organizationId,
1644
- });
1750
+ }, stampWith);
1645
1751
  const existingPolicies = existingPoliciesResponse.policies || [];
1646
1752
  // we create a map of existing policies by their signature
1647
1753
  // where the policySignature maps to its policyId
@@ -1674,10 +1780,10 @@ class TurnkeyClient {
1674
1780
  const createPoliciesResponse = await this.httpClient.createPolicies({
1675
1781
  organizationId,
1676
1782
  policies: missingPolicies,
1677
- });
1783
+ }, stampWith);
1678
1784
  // assign returned IDs back to the missing ones in order
1679
1785
  if (!createPoliciesResponse || !createPoliciesResponse.policyIds) {
1680
- throw new TurnkeyError("Failed to create missing delegated access policies", TurnkeyErrorCodes.CREATE_POLICY_ERROR);
1786
+ throw new TurnkeyError("Failed to create missing policies", TurnkeyErrorCodes.CREATE_POLICY_ERROR);
1681
1787
  }
1682
1788
  const newlyCreatedPolicies = missingPolicies.map((p, idx) => ({
1683
1789
  ...p,
@@ -1689,7 +1795,7 @@ class TurnkeyClient {
1689
1795
  // which includes each of their respective IDs
1690
1796
  return [...alreadyExistingPolicies, ...newlyCreatedPolicies];
1691
1797
  }, {
1692
- errorMessage: "Failed to get or create delegated access policies",
1798
+ errorMessage: "Failed to get or create policies",
1693
1799
  errorCode: TurnkeyErrorCodes.CREATE_USERS_ERROR,
1694
1800
  });
1695
1801
  };
@@ -1706,16 +1812,17 @@ class TurnkeyClient {
1706
1812
  * @param params.verificationToken - verification token from OTP email verification (required if verifying the email).
1707
1813
  * @param params.userId - user ID to update a specific user's email (defaults to the current session's userId).
1708
1814
  * @param params.stampWith - parameter to stamp the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
1815
+ * @param params.organizationId - organization ID to specify the sub-organization (defaults to the current session's organizationId).
1709
1816
  * @returns A promise that resolves to the userId of the updated user.
1710
1817
  * @throws {TurnkeyError} If there is no active session, if the userId is missing, or if there is an error updating or verifying the user email.
1711
1818
  */
1712
1819
  this.updateUserEmail = async (params) => {
1713
- const { verificationToken, email, stampWith } = params;
1714
- const session = await this.storageManager.getActiveSession();
1715
- if (!session) {
1716
- throw new TurnkeyError("No active session found. Please log in first.", TurnkeyErrorCodes.NO_SESSION_FOUND);
1820
+ const { verificationToken, email, stampWith, organizationId } = params;
1821
+ const session = await getActiveSessionOrThrowIfRequired(stampWith, this.storageManager.getActiveSession);
1822
+ const userId = params?.userId || session?.userId;
1823
+ if (!userId) {
1824
+ throw new TurnkeyError("User ID must be provided to update user email", TurnkeyErrorCodes.INVALID_REQUEST);
1717
1825
  }
1718
- const userId = params?.userId || session.userId;
1719
1826
  return withTurnkeyErrorHandling(async () => {
1720
1827
  const existingUser = await this.httpClient.proxyGetAccount({
1721
1828
  filterType: FilterType.Email,
@@ -1728,6 +1835,7 @@ class TurnkeyClient {
1728
1835
  userId: userId,
1729
1836
  userEmail: email,
1730
1837
  ...(verificationToken && { verificationToken }),
1838
+ ...(organizationId && { organizationId }),
1731
1839
  }, stampWith);
1732
1840
  if (!res || !res.userId) {
1733
1841
  throw new TurnkeyError("No user ID found in the update user email response", TurnkeyErrorCodes.BAD_RESPONSE);
@@ -1748,20 +1856,22 @@ class TurnkeyClient {
1748
1856
  *
1749
1857
  * @param params.userId - user ID to remove a specific user's email address (defaults to the current session's userId).
1750
1858
  * @param params.stampWith - parameter to stamp the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
1859
+ * @param params.organizationId - organization ID to specify the sub-organization (defaults to the current session's organizationId).
1751
1860
  * @returns A promise that resolves to the userId of the user whose email was removed.
1752
1861
  * @throws {TurnkeyError} If there is no active session, if the userId is missing, or if there is an error removing the user email.
1753
1862
  */
1754
1863
  this.removeUserEmail = async (params) => {
1755
- const { stampWith } = params || {};
1756
- const session = await this.storageManager.getActiveSession();
1757
- if (!session) {
1758
- throw new TurnkeyError("No active session found. Please log in first.", TurnkeyErrorCodes.NO_SESSION_FOUND);
1759
- }
1864
+ const { stampWith, organizationId } = params || {};
1865
+ const session = await getActiveSessionOrThrowIfRequired(stampWith, this.storageManager.getActiveSession);
1760
1866
  return withTurnkeyErrorHandling(async () => {
1761
- const userId = params?.userId || session.userId;
1867
+ const userId = params?.userId || session?.userId;
1868
+ if (!userId) {
1869
+ throw new TurnkeyError("User ID must be provided to remove user email", TurnkeyErrorCodes.INVALID_REQUEST);
1870
+ }
1762
1871
  const res = await this.httpClient.updateUserEmail({
1763
1872
  userId: userId,
1764
1873
  userEmail: "",
1874
+ ...(organizationId && { organizationId }),
1765
1875
  }, stampWith);
1766
1876
  if (!res || !res.userId) {
1767
1877
  throw new TurnkeyError("No user ID found in the remove user email response", TurnkeyErrorCodes.BAD_RESPONSE);
@@ -1785,21 +1895,23 @@ class TurnkeyClient {
1785
1895
  * @param params.verificationToken - verification token from OTP phone verification (required if verifying the phone number).
1786
1896
  * @param params.userId - user ID to update a specific user's phone number (defaults to the current session's userId).
1787
1897
  * @param params.stampWith - parameter to stamp the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
1898
+ * @param params.organizationId - organization ID to specify the sub-organization (defaults to the current session's organizationId).
1788
1899
  * @returns A promise that resolves to the userId of the updated user.
1789
1900
  * @throws {TurnkeyError} If there is no active session, if the userId is missing, or if there is an error updating or verifying the user phone number.
1790
1901
  */
1791
1902
  this.updateUserPhoneNumber = async (params) => {
1792
- const { verificationToken, phoneNumber, stampWith } = params;
1793
- const session = await this.storageManager.getActiveSession();
1794
- if (!session) {
1795
- throw new TurnkeyError("No active session found. Please log in first.", TurnkeyErrorCodes.NO_SESSION_FOUND);
1903
+ const { verificationToken, phoneNumber, stampWith, organizationId } = params;
1904
+ const session = await getActiveSessionOrThrowIfRequired(stampWith, this.storageManager.getActiveSession);
1905
+ const userId = params?.userId || session?.userId;
1906
+ if (!userId) {
1907
+ throw new TurnkeyError("User ID must be provided to update user phone number", TurnkeyErrorCodes.INVALID_REQUEST);
1796
1908
  }
1797
- const userId = params?.userId || session.userId;
1798
1909
  return withTurnkeyErrorHandling(async () => {
1799
1910
  const res = await this.httpClient.updateUserPhoneNumber({
1800
1911
  userId,
1801
1912
  userPhoneNumber: phoneNumber,
1802
1913
  ...(verificationToken && { verificationToken }),
1914
+ ...(organizationId && { organizationId }),
1803
1915
  }, stampWith);
1804
1916
  if (!res || !res.userId) {
1805
1917
  throw new TurnkeyError("Failed to update user phone number", TurnkeyErrorCodes.UPDATE_USER_PHONE_NUMBER_ERROR);
@@ -1820,20 +1932,22 @@ class TurnkeyClient {
1820
1932
  *
1821
1933
  * @param params.userId - user ID to remove a specific user's phone number (defaults to the current session's userId).
1822
1934
  * @param params.stampWith - parameter to stamp the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
1935
+ * @param params.organizationId - organization ID to specify the sub-organization (defaults to the current session's organizationId).
1823
1936
  * @returns A promise that resolves to the userId of the user whose phone number was removed.
1824
1937
  * @throws {TurnkeyError} If there is no active session, if the userId is missing, or if there is an error removing the user phone number.
1825
1938
  */
1826
1939
  this.removeUserPhoneNumber = async (params) => {
1827
- const { stampWith } = params || {};
1828
- const session = await this.storageManager.getActiveSession();
1829
- if (!session) {
1830
- throw new TurnkeyError("No active session found. Please log in first.", TurnkeyErrorCodes.NO_SESSION_FOUND);
1940
+ const { stampWith, organizationId } = params || {};
1941
+ const session = await getActiveSessionOrThrowIfRequired(stampWith, this.storageManager.getActiveSession);
1942
+ const userId = params?.userId || session?.userId;
1943
+ if (!userId) {
1944
+ throw new TurnkeyError("User ID must be provided to remove user phone number", TurnkeyErrorCodes.INVALID_REQUEST);
1831
1945
  }
1832
- const userId = params?.userId || session.userId;
1833
1946
  return withTurnkeyErrorHandling(async () => {
1834
1947
  const res = await this.httpClient.updateUserPhoneNumber({
1835
1948
  userId,
1836
1949
  userPhoneNumber: "",
1950
+ ...(organizationId && { organizationId }),
1837
1951
  }, stampWith);
1838
1952
  if (!res || !res.userId) {
1839
1953
  throw new TurnkeyError("Failed to remove user phone number", TurnkeyErrorCodes.UPDATE_USER_PHONE_NUMBER_ERROR);
@@ -1856,20 +1970,22 @@ class TurnkeyClient {
1856
1970
  * @param params.userName - new name to set for the user.
1857
1971
  * @param params.userId - user ID to update a specific user's name (defaults to the current session's userId).
1858
1972
  * @param params.stampWith - parameter to stamp the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
1973
+ * @param params.organizationId - organization ID to specify the sub-organization (defaults to the current session's organizationId).
1859
1974
  * @returns A promise that resolves to the userId of the updated user.
1860
1975
  * @throws {TurnkeyError} If there is no active session, if the userId is missing, or if there is an error updating the user name.
1861
1976
  */
1862
1977
  this.updateUserName = async (params) => {
1863
- const { userName, stampWith } = params;
1864
- const session = await this.storageManager.getActiveSession();
1865
- if (!session) {
1866
- throw new TurnkeyError("No active session found. Please log in first.", TurnkeyErrorCodes.NO_SESSION_FOUND);
1978
+ const { userName, stampWith, organizationId } = params;
1979
+ const session = await getActiveSessionOrThrowIfRequired(stampWith, this.storageManager.getActiveSession);
1980
+ const userId = params?.userId || session?.userId;
1981
+ if (!userId) {
1982
+ throw new TurnkeyError("User ID must be provided to update user name", TurnkeyErrorCodes.INVALID_REQUEST);
1867
1983
  }
1868
- const userId = params?.userId || session.userId;
1869
1984
  return withTurnkeyErrorHandling(async () => {
1870
1985
  const res = await this.httpClient.updateUserName({
1871
1986
  userId,
1872
1987
  userName,
1988
+ ...(organizationId && { organizationId }),
1873
1989
  }, stampWith);
1874
1990
  if (!res || !res.userId) {
1875
1991
  throw new TurnkeyError("No user ID found in the update user name response", TurnkeyErrorCodes.BAD_RESPONSE);
@@ -1892,6 +2008,7 @@ class TurnkeyClient {
1892
2008
  *
1893
2009
  * @param params.providerName - name of the OAuth provider to add (e.g., "Google", "Apple").
1894
2010
  * @param params.oidcToken - OIDC token for the OAuth provider.
2011
+ * @param params.organizationId - organization ID to specify the sub-organization (defaults to the current session's organizationId).
1895
2012
  * @param params.userId - user ID to add the provider for a specific user (defaults to current session's userId).
1896
2013
  * @param params.stampWith - parameter to stamp the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
1897
2014
  * @returns A promise that resolves to an array of provider IDs associated with the user.
@@ -1899,29 +2016,34 @@ class TurnkeyClient {
1899
2016
  */
1900
2017
  this.addOauthProvider = async (params) => {
1901
2018
  const { providerName, oidcToken, stampWith } = params;
1902
- const session = await this.storageManager.getActiveSession();
1903
- if (!session) {
1904
- throw new TurnkeyError("No active session found. Please log in first.", TurnkeyErrorCodes.NO_SESSION_FOUND);
1905
- }
2019
+ const session = await getActiveSessionOrThrowIfRequired(stampWith, this.storageManager.getActiveSession);
1906
2020
  return withTurnkeyErrorHandling(async () => {
1907
2021
  const accountRes = await this.httpClient.proxyGetAccount({
1908
2022
  filterType: "OIDC_TOKEN",
1909
2023
  filterValue: oidcToken,
1910
2024
  });
1911
2025
  if (!accountRes) {
1912
- throw new TurnkeyError(`Account fetch failed}`, TurnkeyErrorCodes.ACCOUNT_FETCH_ERROR);
2026
+ throw new TurnkeyError(`Account fetch failed`, TurnkeyErrorCodes.ACCOUNT_FETCH_ERROR);
1913
2027
  }
1914
2028
  if (accountRes.organizationId) {
1915
2029
  throw new TurnkeyError("Account already exists with this OIDC token", TurnkeyErrorCodes.ACCOUNT_ALREADY_EXISTS);
1916
2030
  }
1917
- const userId = params?.userId || session.userId;
1918
- const { email: oidcEmail, iss } = jwtDecode(oidcToken) || {}; // Parse the oidc token so we can get the email. Pass it in to updateUser then call createOauthProviders. This will be verified by Turnkey.
2031
+ const userId = params?.userId || session?.userId;
2032
+ if (!userId) {
2033
+ throw new TurnkeyError("User ID must be provided to add OAuth provider", TurnkeyErrorCodes.INVALID_REQUEST);
2034
+ }
2035
+ const organizationId = params?.organizationId ?? session?.organizationId;
2036
+ if (!organizationId) {
2037
+ throw new TurnkeyError("Organization ID is required to add OAuth provider", TurnkeyErrorCodes.INVALID_REQUEST);
2038
+ }
2039
+ // parse the oidc token so we can get the email. Pass it in to updateUser then call createOauthProviders. This will be verified by Turnkey.
2040
+ const { email: oidcEmail, iss } = jwtDecode(oidcToken) || {};
1919
2041
  if (iss === googleISS) {
1920
2042
  const verifiedSuborg = await this.httpClient.proxyGetAccount({
1921
2043
  filterType: "EMAIL",
1922
2044
  filterValue: oidcEmail,
1923
2045
  });
1924
- const isVerified = verifiedSuborg.organizationId === session.organizationId;
2046
+ const isVerified = verifiedSuborg.organizationId === organizationId;
1925
2047
  const user = await this.fetchUser({
1926
2048
  userId,
1927
2049
  stampWith,
@@ -1964,20 +2086,22 @@ class TurnkeyClient {
1964
2086
  * @param params.providerIds - IDs of the OAuth providers to remove.
1965
2087
  * @param params.userId - user ID to remove the provider for a specific user (defaults to the current session's userId).
1966
2088
  * @param params.stampWith - parameter to stamp the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
2089
+ * @param params.organizationId - organization ID to specify the sub-organization (defaults to the current session's organizationId).
1967
2090
  * @returns A promise that resolves to an array of provider IDs that were removed.
1968
2091
  * @throws {TurnkeyError} If there is no active session, if the userId is missing, or if there is an error removing the OAuth provider.
1969
2092
  */
1970
2093
  this.removeOauthProviders = async (params) => {
1971
- const { providerIds, stampWith } = params;
1972
- const session = await this.storageManager.getActiveSession();
1973
- if (!session) {
1974
- throw new TurnkeyError("No active session found. Please log in first.", TurnkeyErrorCodes.NO_SESSION_FOUND);
2094
+ const { providerIds, stampWith, organizationId } = params;
2095
+ const session = await getActiveSessionOrThrowIfRequired(stampWith, this.storageManager.getActiveSession);
2096
+ const userId = params?.userId || session?.userId;
2097
+ if (!userId) {
2098
+ throw new TurnkeyError("User ID must be provided to remove OAuth provider", TurnkeyErrorCodes.INVALID_REQUEST);
1975
2099
  }
1976
- const userId = params?.userId || session.userId;
1977
2100
  return withTurnkeyErrorHandling(async () => {
1978
2101
  const res = await this.httpClient.deleteOauthProviders({
1979
2102
  userId,
1980
2103
  providerIds,
2104
+ ...(organizationId && { organizationId }),
1981
2105
  }, stampWith);
1982
2106
  if (!res) {
1983
2107
  throw new TurnkeyError("Failed to remove OAuth provider", TurnkeyErrorCodes.REMOVE_OAUTH_PROVIDER_ERROR);
@@ -2001,21 +2125,21 @@ class TurnkeyClient {
2001
2125
  * @param params.displayName - display name of the passkey (defaults to the value of `name`).
2002
2126
  * @param params.userId - user ID to add the passkey for a specific user (defaults to the current session's userId).
2003
2127
  * @param params.stampWith - parameter to stamp the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
2128
+ * @param params.organizationId - organization ID to specify the sub-organization (defaults to the current session's organizationId).
2004
2129
  * @returns A promise that resolves to an array of authenticator IDs for the newly added passkey(s).
2005
2130
  * @throws {TurnkeyError} If there is no active session, if passkey creation fails, or if there is an error adding the passkey.
2006
2131
  */
2007
2132
  this.addPasskey = async (params) => {
2008
- const { stampWith } = params || {};
2133
+ const { stampWith, organizationId } = params || {};
2009
2134
  const name = params?.name || `Turnkey Passkey-${Date.now()}`;
2010
2135
  return withTurnkeyErrorHandling(async () => {
2011
- const session = await this.storageManager.getActiveSession();
2012
- if (!session) {
2013
- throw new TurnkeyError("No active session found. Please log in first.", TurnkeyErrorCodes.NO_SESSION_FOUND);
2136
+ const session = await getActiveSessionOrThrowIfRequired(stampWith, this.storageManager.getActiveSession);
2137
+ const userId = params?.userId || session?.userId;
2138
+ if (!userId) {
2139
+ throw new TurnkeyError("User ID must be provided to add passkey", TurnkeyErrorCodes.INVALID_REQUEST);
2014
2140
  }
2015
- const userId = params?.userId || session.userId;
2016
2141
  const { encodedChallenge, attestation } = await this.createPasskey({
2017
2142
  name,
2018
- ...(stampWith && { stampWith }),
2019
2143
  });
2020
2144
  if (!attestation || !encodedChallenge) {
2021
2145
  throw new TurnkeyError("Failed to create passkey challenge and attestation", TurnkeyErrorCodes.CREATE_PASSKEY_ERROR);
@@ -2029,6 +2153,7 @@ class TurnkeyClient {
2029
2153
  attestation,
2030
2154
  },
2031
2155
  ],
2156
+ ...(organizationId && { organizationId }),
2032
2157
  }, stampWith);
2033
2158
  return res?.authenticatorIds || [];
2034
2159
  }, {
@@ -2048,20 +2173,22 @@ class TurnkeyClient {
2048
2173
  * @param params.authenticatorIds - IDs of the authenticators (passkeys) to remove.
2049
2174
  * @param params.userId - user ID to remove the passkeys for a specific user (defaults to the current session's userId).
2050
2175
  * @param params.stampWith - parameter to stamp the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
2176
+ * @param params.organizationId - organization ID to specify the sub-organization (defaults to the current session's organizationId).
2051
2177
  * @returns A promise that resolves to an array of authenticator IDs that were removed.
2052
2178
  * @throws {TurnkeyError} If there is no active session, if the userId is missing, or if there is an error removing the passkeys.
2053
2179
  */
2054
2180
  this.removePasskeys = async (params) => {
2055
- const { authenticatorIds, stampWith } = params;
2056
- const session = await this.storageManager.getActiveSession();
2057
- if (!session) {
2058
- throw new TurnkeyError("No active session found. Please log in first.", TurnkeyErrorCodes.NO_SESSION_FOUND);
2181
+ const { authenticatorIds, stampWith, organizationId } = params;
2182
+ const session = await getActiveSessionOrThrowIfRequired(stampWith, this.storageManager.getActiveSession);
2183
+ const userId = params?.userId || session?.userId;
2184
+ if (!userId) {
2185
+ throw new TurnkeyError("User ID must be provided to remove passkey", TurnkeyErrorCodes.INVALID_REQUEST);
2059
2186
  }
2060
- const userId = params?.userId || session.userId;
2061
2187
  return withTurnkeyErrorHandling(async () => {
2062
2188
  const res = await this.httpClient.deleteAuthenticators({
2063
2189
  userId,
2064
2190
  authenticatorIds,
2191
+ ...(organizationId && { organizationId }),
2065
2192
  }, stampWith);
2066
2193
  if (!res) {
2067
2194
  throw new TurnkeyError("No response found in the remove passkey response", TurnkeyErrorCodes.REMOVE_PASSKEY_ERROR);
@@ -2092,10 +2219,11 @@ class TurnkeyClient {
2092
2219
  * @throws {TurnkeyError} If there is no active session or if there is an error creating the wallet.
2093
2220
  */
2094
2221
  this.createWallet = async (params) => {
2095
- const { walletName, accounts, organizationId, mnemonicLength, stampWith } = params;
2096
- const session = await this.storageManager.getActiveSession();
2097
- if (!session) {
2098
- throw new TurnkeyError("No active session found. Please log in first.", TurnkeyErrorCodes.NO_SESSION_FOUND);
2222
+ const { walletName, accounts, organizationId: organizationIdFromParams, mnemonicLength, stampWith, } = params;
2223
+ const session = await getActiveSessionOrThrowIfRequired(stampWith, this.storageManager.getActiveSession);
2224
+ const organizationId = organizationIdFromParams || session?.organizationId;
2225
+ if (!organizationId) {
2226
+ throw new TurnkeyError("Organization ID must be provided to create wallet", TurnkeyErrorCodes.INVALID_REQUEST);
2099
2227
  }
2100
2228
  let walletAccounts = [];
2101
2229
  if (accounts && !isWalletAccountArray(accounts)) {
@@ -2111,7 +2239,7 @@ class TurnkeyClient {
2111
2239
  }
2112
2240
  return withTurnkeyErrorHandling(async () => {
2113
2241
  const res = await this.httpClient.createWallet({
2114
- organizationId: organizationId || session.organizationId,
2242
+ organizationId: organizationId,
2115
2243
  walletName,
2116
2244
  accounts: walletAccounts,
2117
2245
  mnemonicLength: mnemonicLength || 12,
@@ -2143,10 +2271,11 @@ class TurnkeyClient {
2143
2271
  * @throws {TurnkeyError} If there is no active session, if the wallet does not exist, or if there is an error creating the wallet accounts.
2144
2272
  */
2145
2273
  this.createWalletAccounts = async (params) => {
2146
- const { accounts, walletId, organizationId, stampWith } = params;
2147
- const session = await this.storageManager.getActiveSession();
2148
- if (!session) {
2149
- throw new TurnkeyError("No active session found. Please log in first.", TurnkeyErrorCodes.NO_SESSION_FOUND);
2274
+ const { accounts, walletId, organizationId: organizationIdFromParams, stampWith, } = params;
2275
+ const session = await getActiveSessionOrThrowIfRequired(stampWith, this.storageManager.getActiveSession);
2276
+ const organizationId = organizationIdFromParams || session?.organizationId;
2277
+ if (!organizationId) {
2278
+ throw new TurnkeyError("Organization ID must be provided to create wallet accounts", TurnkeyErrorCodes.INVALID_REQUEST);
2150
2279
  }
2151
2280
  return withTurnkeyErrorHandling(async () => {
2152
2281
  let walletAccounts = [];
@@ -2154,7 +2283,7 @@ class TurnkeyClient {
2154
2283
  // Query existing wallet accounts to avoid duplicates
2155
2284
  const existingWalletAccounts = await this.httpClient.getWalletAccounts({
2156
2285
  walletId,
2157
- organizationId: organizationId || session.organizationId,
2286
+ organizationId: organizationId,
2158
2287
  paginationOptions: { limit: "100" },
2159
2288
  }, stampWith);
2160
2289
  walletAccounts = generateWalletAccountsFromAddressFormat({
@@ -2166,7 +2295,7 @@ class TurnkeyClient {
2166
2295
  walletAccounts = accounts;
2167
2296
  }
2168
2297
  const res = await this.httpClient.createWalletAccounts({
2169
- organizationId: organizationId || session.organizationId,
2298
+ organizationId: organizationId,
2170
2299
  walletId,
2171
2300
  accounts: walletAccounts,
2172
2301
  }, stampWith);
@@ -2197,16 +2326,17 @@ class TurnkeyClient {
2197
2326
  * @throws {TurnkeyError} If there is no active session, if the targetPublicKey is missing, or if there is an error exporting the wallet.
2198
2327
  */
2199
2328
  this.exportWallet = async (params) => {
2200
- const { walletId, targetPublicKey, stampWith, organizationId } = params;
2201
- const session = await this.storageManager.getActiveSession();
2202
- if (!session) {
2203
- throw new TurnkeyError("No active session found. Please log in first.", TurnkeyErrorCodes.NO_SESSION_FOUND);
2329
+ const { walletId, targetPublicKey, stampWith, organizationId: organizationIdFromParams, } = params;
2330
+ const session = await getActiveSessionOrThrowIfRequired(stampWith, this.storageManager.getActiveSession);
2331
+ const organizationId = organizationIdFromParams || session?.organizationId;
2332
+ if (!organizationId) {
2333
+ throw new TurnkeyError("Organization ID must be provided to export wallet", TurnkeyErrorCodes.INVALID_REQUEST);
2204
2334
  }
2205
2335
  return withTurnkeyErrorHandling(async () => {
2206
2336
  const res = await this.httpClient.exportWallet({
2207
2337
  walletId,
2208
2338
  targetPublicKey,
2209
- organizationId: organizationId || session.organizationId,
2339
+ organizationId: organizationId,
2210
2340
  }, stampWith);
2211
2341
  if (!res.exportBundle) {
2212
2342
  throw new TurnkeyError("No export bundle found in the response", TurnkeyErrorCodes.BAD_RESPONSE);
@@ -2234,16 +2364,17 @@ class TurnkeyClient {
2234
2364
  * @throws {TurnkeyError} If there is no active session, if the targetPublicKey is missing, or if there is an error exporting the private key.
2235
2365
  */
2236
2366
  this.exportPrivateKey = async (params) => {
2237
- const { privateKeyId, targetPublicKey, stampWith, organizationId } = params;
2238
- const session = await this.storageManager.getActiveSession();
2239
- if (!session) {
2240
- throw new TurnkeyError("No active session found. Please log in first.", TurnkeyErrorCodes.NO_SESSION_FOUND);
2367
+ const { privateKeyId, targetPublicKey, stampWith, organizationId: organizationIdFromParams, } = params;
2368
+ const session = await getActiveSessionOrThrowIfRequired(stampWith, this.storageManager.getActiveSession);
2369
+ const organizationId = organizationIdFromParams || session?.organizationId;
2370
+ if (!organizationId) {
2371
+ throw new TurnkeyError("Organization ID must be provided to export private key", TurnkeyErrorCodes.INVALID_REQUEST);
2241
2372
  }
2242
2373
  return withTurnkeyErrorHandling(async () => {
2243
2374
  const res = await this.httpClient.exportPrivateKey({
2244
2375
  privateKeyId,
2245
2376
  targetPublicKey,
2246
- organizationId: organizationId || session.organizationId,
2377
+ organizationId: organizationId,
2247
2378
  }, stampWith);
2248
2379
  if (!res.exportBundle) {
2249
2380
  throw new TurnkeyError("No export bundle found in the response", TurnkeyErrorCodes.BAD_RESPONSE);
@@ -2272,16 +2403,17 @@ class TurnkeyClient {
2272
2403
  *
2273
2404
  */
2274
2405
  this.exportWalletAccount = async (params) => {
2275
- const { address, targetPublicKey, stampWith, organizationId } = params;
2276
- const session = await this.storageManager.getActiveSession();
2277
- if (!session) {
2278
- throw new TurnkeyError("No active session found. Please log in first.", TurnkeyErrorCodes.NO_SESSION_FOUND);
2406
+ const { address, targetPublicKey, stampWith, organizationId: organizationIdFromParams, } = params;
2407
+ const session = await getActiveSessionOrThrowIfRequired(stampWith, this.storageManager.getActiveSession);
2408
+ const organizationId = organizationIdFromParams || session?.organizationId;
2409
+ if (!organizationId) {
2410
+ throw new TurnkeyError("Organization ID must be provided to export wallet account", TurnkeyErrorCodes.INVALID_REQUEST);
2279
2411
  }
2280
2412
  return withTurnkeyErrorHandling(async () => {
2281
2413
  const res = await this.httpClient.exportWalletAccount({
2282
2414
  address,
2283
2415
  targetPublicKey,
2284
- organizationId: organizationId || session.organizationId,
2416
+ organizationId: organizationId,
2285
2417
  }, stampWith);
2286
2418
  if (!res.exportBundle) {
2287
2419
  throw new TurnkeyError("No export bundle found in the response", TurnkeyErrorCodes.BAD_RESPONSE);
@@ -2305,21 +2437,27 @@ class TurnkeyClient {
2305
2437
  * @param params.encryptedBundle - encrypted bundle containing the wallet seed phrase and metadata.
2306
2438
  * @param params.walletName - name of the wallet to create upon import.
2307
2439
  * @param params.accounts - array of account parameters to create in the imported wallet (defaults to standard Ethereum and Solana accounts).
2440
+ * @param params.organizationId - organization ID to import the wallet under a specific sub-organization (wallet will be associated with the sub-organization).
2308
2441
  * @param params.userId - user ID to import the wallet for a specific user (defaults to the current session's userId).
2309
2442
  * @param params.stampWith - parameter to stamp the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
2310
2443
  * @returns A promise that resolves to the ID of the imported wallet.
2311
2444
  * @throws {TurnkeyError} If there is no active session, if the encrypted bundle is invalid, or if there is an error importing the wallet.
2312
2445
  */
2313
2446
  this.importWallet = async (params) => {
2314
- const { encryptedBundle, accounts, walletName, userId, stampWith } = params;
2315
- const session = await this.storageManager.getActiveSession();
2316
- if (!session) {
2317
- throw new TurnkeyError("No active session found. Please log in first.", TurnkeyErrorCodes.NO_SESSION_FOUND);
2447
+ const { encryptedBundle, accounts, walletName, organizationId: organizationIdFromParams, userId: userIdFromParams, stampWith, } = params;
2448
+ const session = await getActiveSessionOrThrowIfRequired(stampWith, this.storageManager.getActiveSession);
2449
+ const organizationId = organizationIdFromParams || session?.organizationId;
2450
+ if (!organizationId) {
2451
+ throw new TurnkeyError("Organization ID must be provided to import wallet", TurnkeyErrorCodes.INVALID_REQUEST);
2452
+ }
2453
+ const userId = userIdFromParams || session?.userId;
2454
+ if (!userId) {
2455
+ throw new TurnkeyError("User ID must be provided to import wallet", TurnkeyErrorCodes.INVALID_REQUEST);
2318
2456
  }
2319
2457
  return withTurnkeyErrorHandling(async () => {
2320
2458
  const res = await this.httpClient.importWallet({
2321
- organizationId: session.organizationId,
2322
- userId: userId || session.userId,
2459
+ organizationId: organizationId,
2460
+ userId: userId,
2323
2461
  encryptedBundle,
2324
2462
  walletName,
2325
2463
  accounts: accounts || [
@@ -2357,21 +2495,27 @@ class TurnkeyClient {
2357
2495
  * @param params.privateKeyName - name of the private key to create upon import.
2358
2496
  * @param params.curve - the cryptographic curve used to generate a given private key
2359
2497
  * @param params.addressFormat - address format of the private key to import.
2498
+ * @param params.organizationId - organization ID to import the private key under a specific sub-organization (private key will be associated with the sub-organization).
2360
2499
  * @param params.userId - user ID to import the wallet for a specific user (defaults to the current session's userId).
2361
2500
  * @param params.stampWith - parameter to stamp the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
2362
2501
  * @returns A promise that resolves to the ID of the imported wallet.
2363
2502
  * @throws {TurnkeyError} If there is no active session, if the encrypted bundle is invalid, or if there is an error importing the wallet.
2364
2503
  */
2365
2504
  this.importPrivateKey = async (params) => {
2366
- const { encryptedBundle, privateKeyName, addressFormats, curve, userId, stampWith, } = params;
2367
- const session = await this.storageManager.getActiveSession();
2368
- if (!session) {
2369
- throw new TurnkeyError("No active session found. Please log in first.", TurnkeyErrorCodes.NO_SESSION_FOUND);
2505
+ const { encryptedBundle, privateKeyName, addressFormats, curve, organizationId: organizationIdFromParams, userId: userIdFromParams, stampWith, } = params;
2506
+ const session = await getActiveSessionOrThrowIfRequired(stampWith, this.storageManager.getActiveSession);
2507
+ const organizationId = organizationIdFromParams || session?.organizationId;
2508
+ if (!organizationId) {
2509
+ throw new TurnkeyError("Organization ID must be provided to import private key", TurnkeyErrorCodes.INVALID_REQUEST);
2510
+ }
2511
+ const userId = userIdFromParams || session?.userId;
2512
+ if (!userId) {
2513
+ throw new TurnkeyError("User ID must be provided to import private key", TurnkeyErrorCodes.INVALID_REQUEST);
2370
2514
  }
2371
2515
  return withTurnkeyErrorHandling(async () => {
2372
2516
  const res = await this.httpClient.importPrivateKey({
2373
- organizationId: session.organizationId,
2374
- userId: userId || session.userId,
2517
+ organizationId,
2518
+ userId,
2375
2519
  encryptedBundle,
2376
2520
  privateKeyName,
2377
2521
  curve,
@@ -2402,18 +2546,17 @@ class TurnkeyClient {
2402
2546
  * - Optionally allows stamping the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
2403
2547
  *
2404
2548
  * @param params.deleteWithoutExport - flag to delete the sub-organization without requiring all wallets to be exported first (defaults to false).
2549
+ * @param params.organizationId - organization ID to delete a specific sub-organization (defaults to the current session's organizationId).
2405
2550
  * @param params.stampWith - parameter to stamp the request with a specific stamper.
2406
2551
  * @returns A promise that resolves to a `TDeleteSubOrganizationResponse` object containing the result of the deletion.
2407
2552
  * @throws {TurnkeyError} If there is no active session or if there is an error deleting the sub-organization.
2408
2553
  */
2409
2554
  this.deleteSubOrganization = async (params) => {
2410
- const { deleteWithoutExport = false, stampWith } = params || {};
2411
- const session = await this.storageManager.getActiveSession();
2412
- if (!session) {
2413
- throw new TurnkeyError("No active session found. Please log in first.", TurnkeyErrorCodes.NO_SESSION_FOUND);
2414
- }
2555
+ const { deleteWithoutExport = false, organizationId: organizationIdFromParams, stampWith, } = params || {};
2556
+ const session = await getActiveSessionOrThrowIfRequired(stampWith, this.storageManager.getActiveSession);
2557
+ const organizationId = organizationIdFromParams || session?.organizationId;
2415
2558
  return withTurnkeyErrorHandling(async () => {
2416
- return await this.httpClient.deleteSubOrganization({ deleteWithoutExport }, stampWith);
2559
+ return await this.httpClient.deleteSubOrganization({ deleteWithoutExport, ...(organizationId && { organizationId }) }, stampWith);
2417
2560
  }, {
2418
2561
  errorMessage: "Failed to delete sub-organization",
2419
2562
  errorCode: TurnkeyErrorCodes.DELETE_SUB_ORGANIZATION_ERROR,