@dynamic-labs-sdk/client 1.30.2 → 1.31.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (348) hide show
  1. package/dist/{updateAuthFromVerifyResponse-CTvWpZLa.native.esm.js → apiClient-DpzKqY39.native.esm.js} +557 -465
  2. package/dist/apiClient-DpzKqY39.native.esm.js.map +1 -0
  3. package/dist/client/types/DynamicClient.d.ts +1 -1
  4. package/dist/client/types/DynamicClient.d.ts.map +1 -1
  5. package/dist/core.cjs +121 -61
  6. package/dist/core.cjs.map +1 -1
  7. package/dist/core.esm.js +64 -6
  8. package/dist/core.esm.js.map +1 -1
  9. package/dist/core.native.esm.js +64 -6
  10. package/dist/core.native.esm.js.map +1 -1
  11. package/dist/errors/WaasRbacStaleRetryUnsafeError.d.ts +36 -0
  12. package/dist/errors/WaasRbacStaleRetryUnsafeError.d.ts.map +1 -0
  13. package/dist/exports/core.d.ts +6 -0
  14. package/dist/exports/core.d.ts.map +1 -1
  15. package/dist/exports/index.d.ts +16 -4
  16. package/dist/exports/index.d.ts.map +1 -1
  17. package/dist/exports/waas.d.ts +3 -2
  18. package/dist/exports/waas.d.ts.map +1 -1
  19. package/dist/{getNetworkProviderFromNetworkId-CamHn2s3.esm.js → getNetworkProviderFromNetworkId-BN2jUhHm.esm.js} +8 -3
  20. package/dist/getNetworkProviderFromNetworkId-BN2jUhHm.esm.js.map +1 -0
  21. package/dist/{getNetworkProviderFromNetworkId-igDf2OPy.cjs → getNetworkProviderFromNetworkId-BoNAPSjx.cjs} +62 -51
  22. package/dist/getNetworkProviderFromNetworkId-BoNAPSjx.cjs.map +1 -0
  23. package/dist/{getNetworkProviderFromNetworkId--X0cb1ad.native.esm.js → getNetworkProviderFromNetworkId-DUym3Qq0.native.esm.js} +9 -4
  24. package/dist/getNetworkProviderFromNetworkId-DUym3Qq0.native.esm.js.map +1 -0
  25. package/dist/{getSignedSessionId-DGa_pu-i.cjs → getSignedSessionId-9ADIJCl1.cjs} +11 -11
  26. package/dist/{getSignedSessionId-DGa_pu-i.cjs.map → getSignedSessionId-9ADIJCl1.cjs.map} +1 -1
  27. package/dist/{getSignedSessionId--XNTxNFo.native.esm.js → getSignedSessionId-Dr4Ic68X.native.esm.js} +3 -3
  28. package/dist/{getSignedSessionId--XNTxNFo.native.esm.js.map → getSignedSessionId-Dr4Ic68X.native.esm.js.map} +1 -1
  29. package/dist/{getSignedSessionId-DY-ietfO.esm.js → getSignedSessionId-DxpqG4pv.esm.js} +3 -3
  30. package/dist/{getSignedSessionId-DY-ietfO.esm.js.map → getSignedSessionId-DxpqG4pv.esm.js.map} +1 -1
  31. package/dist/{getWalletProviderByKey-DzpmoNlv.cjs → getVerifiedCredentialForWalletAccount-C2o5idph.cjs} +10 -10
  32. package/dist/getVerifiedCredentialForWalletAccount-C2o5idph.cjs.map +1 -0
  33. package/dist/{getWalletProviderByKey-xqyD3ybv.esm.js → getVerifiedCredentialForWalletAccount-Cjwoeej7.esm.js} +10 -10
  34. package/dist/getVerifiedCredentialForWalletAccount-Cjwoeej7.esm.js.map +1 -0
  35. package/dist/index.cjs +677 -672
  36. package/dist/index.cjs.map +1 -1
  37. package/dist/index.esm.js +47 -23
  38. package/dist/index.esm.js.map +1 -1
  39. package/dist/index.native.esm.js +47 -23
  40. package/dist/index.native.esm.js.map +1 -1
  41. package/dist/{isMfaRequiredForAction-CatS60F6.esm.js → isMfaRequiredForAction-BIBmJbV9.esm.js} +2 -2
  42. package/dist/isMfaRequiredForAction-BIBmJbV9.esm.js.map +1 -0
  43. package/dist/{isMfaRequiredForAction-BcJvy7Gw.native.esm.js → isMfaRequiredForAction-DuSU67yq.native.esm.js} +2 -2
  44. package/dist/isMfaRequiredForAction-DuSU67yq.native.esm.js.map +1 -0
  45. package/dist/{isMfaRequiredForAction-DKfoMhEk.cjs → isMfaRequiredForAction-yM84r7l7.cjs} +11 -11
  46. package/dist/isMfaRequiredForAction-yM84r7l7.cjs.map +1 -0
  47. package/dist/{isUserOnboardingComplete-BWVuE4Jg.native.esm.js → isUserOnboardingComplete-B2Ha2dkP.esm.js} +47 -4
  48. package/dist/isUserOnboardingComplete-B2Ha2dkP.esm.js.map +1 -0
  49. package/dist/{isUserOnboardingComplete-jv_idxWY.cjs → isUserOnboardingComplete-BRTOnK8V.cjs} +63 -14
  50. package/dist/isUserOnboardingComplete-BRTOnK8V.cjs.map +1 -0
  51. package/dist/{isUserOnboardingComplete-jkAQQVdP.esm.js → isUserOnboardingComplete-DCIlkCub.native.esm.js} +47 -4
  52. package/dist/isUserOnboardingComplete-DCIlkCub.native.esm.js.map +1 -0
  53. package/dist/{updateAuthFromVerifyResponse-BLgNMqwN.esm.js → logoutWithReason-DV89zJmJ.esm.js} +679 -587
  54. package/dist/logoutWithReason-DV89zJmJ.esm.js.map +1 -0
  55. package/dist/{updateAuthFromVerifyResponse-Dsw-eAro.cjs → logoutWithReason-DlA15deT.cjs} +691 -587
  56. package/dist/logoutWithReason-DlA15deT.cjs.map +1 -0
  57. package/dist/{getWalletProviderByKey-Cl6WDOoD.native.esm.js → logoutWithReason-HqGlUccb.native.esm.js} +19 -19
  58. package/dist/logoutWithReason-HqGlUccb.native.esm.js.map +1 -0
  59. package/dist/migrateFromFireblocks-CiOS4_Nq.esm.js +128 -0
  60. package/dist/migrateFromFireblocks-CiOS4_Nq.esm.js.map +1 -0
  61. package/dist/migrateFromFireblocks-CqIpxGRS.cjs +163 -0
  62. package/dist/migrateFromFireblocks-CqIpxGRS.cjs.map +1 -0
  63. package/dist/migrateFromFireblocks-DnQsGmIW.native.esm.js +128 -0
  64. package/dist/migrateFromFireblocks-DnQsGmIW.native.esm.js.map +1 -0
  65. package/dist/modules/apiClient/apiClient.types.d.ts +1 -1
  66. package/dist/modules/apiClient/apiClient.types.d.ts.map +1 -1
  67. package/dist/modules/apiClient/createApiClient.d.ts.map +1 -1
  68. package/dist/modules/apiClient/utils/rbacStaleMiddleware/createRbacStaleMiddleware.d.ts +10 -0
  69. package/dist/modules/apiClient/utils/rbacStaleMiddleware/createRbacStaleMiddleware.d.ts.map +1 -0
  70. package/dist/modules/auth/auth.types.d.ts +45 -0
  71. package/dist/modules/auth/auth.types.d.ts.map +1 -0
  72. package/dist/modules/auth/checkStepUpAuth/checkStepUpAuth.d.ts +2 -1
  73. package/dist/modules/auth/checkStepUpAuth/checkStepUpAuth.d.ts.map +1 -1
  74. package/dist/modules/auth/consts.d.ts +9 -0
  75. package/dist/modules/auth/consts.d.ts.map +1 -1
  76. package/dist/modules/auth/createVisit/createVisit.d.ts.map +1 -1
  77. package/dist/modules/auth/externalAuth/requestExternalAuthElevatedToken/requestExternalAuthElevatedToken.d.ts +1 -1
  78. package/dist/modules/auth/externalAuth/requestExternalAuthElevatedToken/requestExternalAuthElevatedToken.d.ts.map +1 -1
  79. package/dist/modules/auth/externalAuth/signInWithExternalJwt/signInWithExternalJwt.d.ts +1 -1
  80. package/dist/modules/auth/externalAuth/signInWithExternalJwt/signInWithExternalJwt.d.ts.map +1 -1
  81. package/dist/modules/auth/getActionAuthorizationTokens/getActionAuthorizationTokens.d.ts +2 -1
  82. package/dist/modules/auth/getActionAuthorizationTokens/getActionAuthorizationTokens.d.ts.map +1 -1
  83. package/dist/modules/auth/mergeUserAccounts/mergeUserAccounts.d.ts +4 -3
  84. package/dist/modules/auth/mergeUserAccounts/mergeUserAccounts.d.ts.map +1 -1
  85. package/dist/modules/auth/passkeys/getPasskeys/getPasskeys.d.ts +1 -1
  86. package/dist/modules/auth/passkeys/getPasskeys/getPasskeys.d.ts.map +1 -1
  87. package/dist/modules/auth/passkeys/registerPasskey/registerPasskey.d.ts +2 -1
  88. package/dist/modules/auth/passkeys/registerPasskey/registerPasskey.d.ts.map +1 -1
  89. package/dist/modules/auth/passkeys/serverAuthenticatePasskey/serverAuthenticatePasskey.d.ts +3 -1
  90. package/dist/modules/auth/passkeys/serverAuthenticatePasskey/serverAuthenticatePasskey.d.ts.map +1 -1
  91. package/dist/modules/auth/passkeys/serverRegisterPasskey/serverRegisterPasskey.d.ts +2 -1
  92. package/dist/modules/auth/passkeys/serverRegisterPasskey/serverRegisterPasskey.d.ts.map +1 -1
  93. package/dist/modules/auth/passkeys/signInWithPasskey/signInWithPasskey.d.ts +1 -1
  94. package/dist/modules/auth/passkeys/signInWithPasskey/signInWithPasskey.d.ts.map +1 -1
  95. package/dist/modules/auth/social/oauth/completeSocialAuthentication/completeSocialAuthentication.d.ts +1 -1
  96. package/dist/modules/auth/social/oauth/completeSocialAuthentication/completeSocialAuthentication.d.ts.map +1 -1
  97. package/dist/modules/auth/social/oauth/completeSocialRedirect/completeSocialRedirect.types.d.ts +1 -1
  98. package/dist/modules/auth/social/oauth/completeSocialRedirect/completeSocialRedirect.types.d.ts.map +1 -1
  99. package/dist/modules/auth/social/oauth/processSocialCallback/processSocialCallback.d.ts +1 -1
  100. package/dist/modules/auth/social/oauth/processSocialCallback/processSocialCallback.d.ts.map +1 -1
  101. package/dist/modules/auth/social/oauth/signInWithSocialPopUp/signInWithSocialPopUp.types.d.ts +1 -1
  102. package/dist/modules/auth/social/oauth/signInWithSocialPopUp/signInWithSocialPopUp.types.d.ts.map +1 -1
  103. package/dist/modules/auth/social/oauth/unlinkSocialAccount/unlinkSocialAccount.d.ts +1 -1
  104. package/dist/modules/auth/social/oauth/unlinkSocialAccount/unlinkSocialAccount.d.ts.map +1 -1
  105. package/dist/modules/auth/updateAuthFromVerifyResponse/updateAuthFromVerifyResponse.d.ts +1 -1
  106. package/dist/modules/auth/updateAuthFromVerifyResponse/updateAuthFromVerifyResponse.d.ts.map +1 -1
  107. package/dist/modules/balances/balances.types.d.ts +59 -0
  108. package/dist/modules/balances/balances.types.d.ts.map +1 -0
  109. package/dist/modules/balances/getMultichainTokenBalances/getMultichainTokenBalances.d.ts +1 -1
  110. package/dist/modules/balances/getMultichainTokenBalances/getMultichainTokenBalances.d.ts.map +1 -1
  111. package/dist/modules/balances/getTokenBalances/getTokenBalances.d.ts +1 -1
  112. package/dist/modules/balances/getTokenBalances/getTokenBalances.d.ts.map +1 -1
  113. package/dist/modules/checkout/broadcastCheckoutTransaction/broadcastCheckoutTransaction.d.ts +1 -1
  114. package/dist/modules/checkout/broadcastCheckoutTransaction/broadcastCheckoutTransaction.d.ts.map +1 -1
  115. package/dist/modules/checkout/checkout.types.d.ts +10 -2
  116. package/dist/modules/checkout/checkout.types.d.ts.map +1 -1
  117. package/dist/modules/deviceRegistration/completeDeviceRegistration/completeDeviceRegistration.d.ts +1 -1
  118. package/dist/modules/deviceRegistration/completeDeviceRegistration/completeDeviceRegistration.d.ts.map +1 -1
  119. package/dist/modules/deviceRegistration/deviceRegistration.types.d.ts +9 -0
  120. package/dist/modules/deviceRegistration/deviceRegistration.types.d.ts.map +1 -0
  121. package/dist/modules/deviceRegistration/getRegisteredDevices/getRegisteredDevices.d.ts +1 -1
  122. package/dist/modules/deviceRegistration/getRegisteredDevices/getRegisteredDevices.d.ts.map +1 -1
  123. package/dist/modules/funding/coinbase/coinbase.types.d.ts +2 -40
  124. package/dist/modules/funding/coinbase/coinbase.types.d.ts.map +1 -1
  125. package/dist/modules/funding/coinbase/createCoinbaseExchangeTransfer/createCoinbaseExchangeTransfer.d.ts +1 -1
  126. package/dist/modules/funding/coinbase/createCoinbaseExchangeTransfer/createCoinbaseExchangeTransfer.d.ts.map +1 -1
  127. package/dist/modules/funding/coinbase/utils/validateUserCredentialsForCoinbaseOnrampOrder/validateUserCredentialsForCoinbaseOnrampOrder.d.ts +2 -2
  128. package/dist/modules/funding/coinbase/utils/validateUserCredentialsForCoinbaseOnrampOrder/validateUserCredentialsForCoinbaseOnrampOrder.d.ts.map +1 -1
  129. package/dist/modules/funding/cryptoDotCom/cryptoDotCom.types.d.ts +2 -2
  130. package/dist/modules/funding/cryptoDotCom/cryptoDotCom.types.d.ts.map +1 -1
  131. package/dist/modules/funding/funding.types.d.ts +26 -0
  132. package/dist/modules/funding/funding.types.d.ts.map +1 -0
  133. package/dist/modules/funding/kraken/createKrakenExchangeTransfer/createKrakenExchangeTransfer.d.ts +4 -4
  134. package/dist/modules/funding/kraken/createKrakenExchangeTransfer/createKrakenExchangeTransfer.d.ts.map +1 -1
  135. package/dist/modules/mfa/authenticateMfaRecoveryCode/authenticateMfaRecoveryCode.d.ts +3 -1
  136. package/dist/modules/mfa/authenticateMfaRecoveryCode/authenticateMfaRecoveryCode.d.ts.map +1 -1
  137. package/dist/modules/mfa/authenticatePasskeyMFA/authenticatePasskeyMFA.d.ts +3 -1
  138. package/dist/modules/mfa/authenticatePasskeyMFA/authenticatePasskeyMFA.d.ts.map +1 -1
  139. package/dist/modules/mfa/authenticateTotpMfaDevice/authenticateTotpMfaDevice.d.ts +3 -1
  140. package/dist/modules/mfa/authenticateTotpMfaDevice/authenticateTotpMfaDevice.d.ts.map +1 -1
  141. package/dist/modules/mfa/createNewMfaRecoveryCodes/createNewMfaRecoveryCodes.d.ts +1 -1
  142. package/dist/modules/mfa/createNewMfaRecoveryCodes/createNewMfaRecoveryCodes.d.ts.map +1 -1
  143. package/dist/modules/mfa/getMfaDevices/getMfaDevices.d.ts +1 -1
  144. package/dist/modules/mfa/getMfaDevices/getMfaDevices.d.ts.map +1 -1
  145. package/dist/modules/mfa/getMfaMethods/getMfaMethods.d.ts +1 -1
  146. package/dist/modules/mfa/getMfaMethods/getMfaMethods.d.ts.map +1 -1
  147. package/dist/modules/mfa/getMfaRecoveryCodes/getMfaRecoveryCodes.d.ts +1 -1
  148. package/dist/modules/mfa/getMfaRecoveryCodes/getMfaRecoveryCodes.d.ts.map +1 -1
  149. package/dist/modules/mfa/isMfaRequiredForAction/isMfaRequiredForAction.d.ts +1 -1
  150. package/dist/modules/mfa/isMfaRequiredForAction/isMfaRequiredForAction.d.ts.map +1 -1
  151. package/dist/modules/mfa/mfa.consts.d.ts +10 -0
  152. package/dist/modules/mfa/mfa.consts.d.ts.map +1 -0
  153. package/dist/modules/mfa/mfa.types.d.ts +66 -1
  154. package/dist/modules/mfa/mfa.types.d.ts.map +1 -1
  155. package/dist/modules/mfa/registerTotpMfaDevice/registerTotpMfaDevice.d.ts +1 -1
  156. package/dist/modules/mfa/registerTotpMfaDevice/registerTotpMfaDevice.d.ts.map +1 -1
  157. package/dist/modules/otp/verifyOTP/verifyOTP.d.ts +2 -1
  158. package/dist/modules/otp/verifyOTP/verifyOTP.d.ts.map +1 -1
  159. package/dist/modules/otp/verifyOTP/verifyOTPForUserSignIn/verifyOTPForUserSignIn.d.ts +1 -1
  160. package/dist/modules/otp/verifyOTP/verifyOTPForUserSignIn/verifyOTPForUserSignIn.d.ts.map +1 -1
  161. package/dist/modules/projectSettings/fetchProjectSettings/fetchProjectSettings.d.ts +1 -1
  162. package/dist/modules/projectSettings/fetchProjectSettings/fetchProjectSettings.d.ts.map +1 -1
  163. package/dist/modules/projectSettings/projectSettings.types.d.ts +15 -0
  164. package/dist/modules/projectSettings/projectSettings.types.d.ts.map +1 -0
  165. package/dist/modules/simulation/simulation.types.d.ts +27 -1
  166. package/dist/modules/simulation/simulation.types.d.ts.map +1 -1
  167. package/dist/modules/storageSync/schema.d.ts +2 -2
  168. package/dist/modules/storageSync/schema.d.ts.map +1 -1
  169. package/dist/modules/swap/swap.types.d.ts +15 -2
  170. package/dist/modules/swap/swap.types.d.ts.map +1 -1
  171. package/dist/modules/user/refreshAuth/refreshAuth.d.ts +2 -2
  172. package/dist/modules/user/refreshAuth/refreshAuth.d.ts.map +1 -1
  173. package/dist/modules/user/refreshUser/refreshUser.d.ts +3 -3
  174. package/dist/modules/user/refreshUser/refreshUser.d.ts.map +1 -1
  175. package/dist/modules/user/user.consts.d.ts +19 -0
  176. package/dist/modules/user/user.consts.d.ts.map +1 -0
  177. package/dist/modules/user/user.types.d.ts +22 -2
  178. package/dist/modules/user/user.types.d.ts.map +1 -1
  179. package/dist/modules/waas/businessAccounts/addBusinessAccountSigner/addBusinessAccountSigner.d.ts +4 -2
  180. package/dist/modules/waas/businessAccounts/addBusinessAccountSigner/addBusinessAccountSigner.d.ts.map +1 -1
  181. package/dist/modules/waas/businessAccounts/businessAccounts.types.d.ts +1 -1
  182. package/dist/modules/waas/businessAccounts/businessAccounts.types.d.ts.map +1 -1
  183. package/dist/modules/waas/createWaasProvider/createWaasProvider.d.ts.map +1 -1
  184. package/dist/modules/waas/getWalletAccountShareSets/getWalletAccountShareSets.d.ts +2 -2
  185. package/dist/modules/waas/getWalletAccountShareSets/getWalletAccountShareSets.d.ts.map +1 -1
  186. package/dist/modules/waas/injectWaasVerifiedCredentialFields/injectWaasVerifiedCredentialFields.d.ts +3 -1
  187. package/dist/modules/waas/injectWaasVerifiedCredentialFields/injectWaasVerifiedCredentialFields.d.ts.map +1 -1
  188. package/dist/modules/waas/policies/applyPolicyLayerBatch/applyPolicyLayerBatch.d.ts +2 -1
  189. package/dist/modules/waas/policies/applyPolicyLayerBatch/applyPolicyLayerBatch.d.ts.map +1 -1
  190. package/dist/modules/waas/policies/buildAllowAddressesRule/buildAllowAddressesRule.d.ts +1 -2
  191. package/dist/modules/waas/policies/buildAllowAddressesRule/buildAllowAddressesRule.d.ts.map +1 -1
  192. package/dist/modules/waas/policies/buildAllowPolicyRule/buildAllowPolicyRule.d.ts +1 -2
  193. package/dist/modules/waas/policies/buildAllowPolicyRule/buildAllowPolicyRule.d.ts.map +1 -1
  194. package/dist/modules/waas/policies/buildBlockExportRule/buildBlockExportRule.d.ts +1 -2
  195. package/dist/modules/waas/policies/buildBlockExportRule/buildBlockExportRule.d.ts.map +1 -1
  196. package/dist/modules/waas/policies/buildDenyAddressesRule/buildDenyAddressesRule.d.ts +1 -2
  197. package/dist/modules/waas/policies/buildDenyAddressesRule/buildDenyAddressesRule.d.ts.map +1 -1
  198. package/dist/modules/waas/policies/buildDenyPolicyRule/buildDenyPolicyRule.d.ts +1 -2
  199. package/dist/modules/waas/policies/buildDenyPolicyRule/buildDenyPolicyRule.d.ts.map +1 -1
  200. package/dist/modules/waas/policies/buildMaxAmountPerTransactionRule/buildMaxAmountPerTransactionRule.d.ts +1 -2
  201. package/dist/modules/waas/policies/buildMaxAmountPerTransactionRule/buildMaxAmountPerTransactionRule.d.ts.map +1 -1
  202. package/dist/modules/waas/policies/buildOperationForExistingRule/buildOperationForExistingRule.d.ts +3 -2
  203. package/dist/modules/waas/policies/buildOperationForExistingRule/buildOperationForExistingRule.d.ts.map +1 -1
  204. package/dist/modules/waas/policies/buildOperationsForRule/buildOperationsForRule.d.ts +2 -2
  205. package/dist/modules/waas/policies/buildOperationsForRule/buildOperationsForRule.d.ts.map +1 -1
  206. package/dist/modules/waas/policies/createPolicy/createPolicy.d.ts +2 -1
  207. package/dist/modules/waas/policies/createPolicy/createPolicy.d.ts.map +1 -1
  208. package/dist/modules/waas/policies/desugarPolicyRules/desugarPolicyRules.d.ts +1 -2
  209. package/dist/modules/waas/policies/desugarPolicyRules/desugarPolicyRules.d.ts.map +1 -1
  210. package/dist/modules/waas/policies/expandPolicyRules/expandPolicyRules.d.ts +2 -2
  211. package/dist/modules/waas/policies/expandPolicyRules/expandPolicyRules.d.ts.map +1 -1
  212. package/dist/modules/waas/policies/fillOmittedRuleValues/fillOmittedRuleValues.d.ts +1 -2
  213. package/dist/modules/waas/policies/fillOmittedRuleValues/fillOmittedRuleValues.d.ts.map +1 -1
  214. package/dist/modules/waas/policies/findMatchedRuleKind/findMatchedRuleKind.d.ts +1 -2
  215. package/dist/modules/waas/policies/findMatchedRuleKind/findMatchedRuleKind.d.ts.map +1 -1
  216. package/dist/modules/waas/policies/getAccountPolicyLayer/getAccountPolicyLayer.d.ts +1 -1
  217. package/dist/modules/waas/policies/getAccountPolicyLayer/getAccountPolicyLayer.d.ts.map +1 -1
  218. package/dist/modules/waas/policies/getPolicy/getPolicy.d.ts +2 -2
  219. package/dist/modules/waas/policies/getPolicy/getPolicy.d.ts.map +1 -1
  220. package/dist/modules/waas/policies/getResolvedPolicyLayer/getResolvedPolicyLayer.d.ts +1 -1
  221. package/dist/modules/waas/policies/getResolvedPolicyLayer/getResolvedPolicyLayer.d.ts.map +1 -1
  222. package/dist/modules/waas/policies/getSignerPolicyLayer/getSignerPolicyLayer.d.ts +1 -1
  223. package/dist/modules/waas/policies/getSignerPolicyLayer/getSignerPolicyLayer.d.ts.map +1 -1
  224. package/dist/modules/waas/policies/getWalletPolicyLayer/getWalletPolicyLayer.d.ts +1 -1
  225. package/dist/modules/waas/policies/getWalletPolicyLayer/getWalletPolicyLayer.d.ts.map +1 -1
  226. package/dist/modules/waas/policies/hasAddresses/hasAddresses.d.ts +1 -1
  227. package/dist/modules/waas/policies/hasAddresses/hasAddresses.d.ts.map +1 -1
  228. package/dist/modules/waas/policies/hasUnrecognizedFields/hasUnrecognizedFields.d.ts +1 -1
  229. package/dist/modules/waas/policies/hasUnrecognizedFields/hasUnrecognizedFields.d.ts.map +1 -1
  230. package/dist/modules/waas/policies/isPolicyRuleDeletionMarker/isPolicyRuleDeletionMarker.d.ts +1 -2
  231. package/dist/modules/waas/policies/isPolicyRuleDeletionMarker/isPolicyRuleDeletionMarker.d.ts.map +1 -1
  232. package/dist/modules/waas/policies/matchExistingRules/matchExistingRules.d.ts +1 -1
  233. package/dist/modules/waas/policies/matchExistingRules/matchExistingRules.d.ts.map +1 -1
  234. package/dist/modules/waas/policies/policies.types.d.ts +17 -1
  235. package/dist/modules/waas/policies/policies.types.d.ts.map +1 -1
  236. package/dist/modules/waas/policies/policyRuleKinds.d.ts +1 -2
  237. package/dist/modules/waas/policies/policyRuleKinds.d.ts.map +1 -1
  238. package/dist/modules/waas/policies/readAllowAddressesRule/readAllowAddressesRule.d.ts +1 -2
  239. package/dist/modules/waas/policies/readAllowAddressesRule/readAllowAddressesRule.d.ts.map +1 -1
  240. package/dist/modules/waas/policies/readBlockExportRule/readBlockExportRule.d.ts +1 -2
  241. package/dist/modules/waas/policies/readBlockExportRule/readBlockExportRule.d.ts.map +1 -1
  242. package/dist/modules/waas/policies/readCoveredRule/readCoveredRule.d.ts +1 -2
  243. package/dist/modules/waas/policies/readCoveredRule/readCoveredRule.d.ts.map +1 -1
  244. package/dist/modules/waas/policies/readDenyAddressesRule/readDenyAddressesRule.d.ts +1 -2
  245. package/dist/modules/waas/policies/readDenyAddressesRule/readDenyAddressesRule.d.ts.map +1 -1
  246. package/dist/modules/waas/policies/readMaxAmountPerTransactionRule/readMaxAmountPerTransactionRule.d.ts +1 -2
  247. package/dist/modules/waas/policies/readMaxAmountPerTransactionRule/readMaxAmountPerTransactionRule.d.ts.map +1 -1
  248. package/dist/modules/waas/policies/removeAccountPolicyRule/removeAccountPolicyRule.d.ts +1 -1
  249. package/dist/modules/waas/policies/removeAccountPolicyRule/removeAccountPolicyRule.d.ts.map +1 -1
  250. package/dist/modules/waas/policies/removePolicyRules/removePolicyRules.d.ts +2 -1
  251. package/dist/modules/waas/policies/removePolicyRules/removePolicyRules.d.ts.map +1 -1
  252. package/dist/modules/waas/policies/removeSignerPolicyRule/removeSignerPolicyRule.d.ts +1 -1
  253. package/dist/modules/waas/policies/removeSignerPolicyRule/removeSignerPolicyRule.d.ts.map +1 -1
  254. package/dist/modules/waas/policies/removeWalletPolicyRule/removeWalletPolicyRule.d.ts +1 -1
  255. package/dist/modules/waas/policies/removeWalletPolicyRule/removeWalletPolicyRule.d.ts.map +1 -1
  256. package/dist/modules/waas/policies/resolveRuleName/resolveRuleName.d.ts +1 -2
  257. package/dist/modules/waas/policies/resolveRuleName/resolveRuleName.d.ts.map +1 -1
  258. package/dist/modules/waas/policies/sortRulesByRuleId/sortRulesByRuleId.d.ts +1 -1
  259. package/dist/modules/waas/policies/sortRulesByRuleId/sortRulesByRuleId.d.ts.map +1 -1
  260. package/dist/modules/waas/policies/upsertAccountPolicyRule/upsertAccountPolicyRule.d.ts +2 -1
  261. package/dist/modules/waas/policies/upsertAccountPolicyRule/upsertAccountPolicyRule.d.ts.map +1 -1
  262. package/dist/modules/waas/policies/upsertSignerPolicyRule/upsertSignerPolicyRule.d.ts +2 -1
  263. package/dist/modules/waas/policies/upsertSignerPolicyRule/upsertSignerPolicyRule.d.ts.map +1 -1
  264. package/dist/modules/waas/policies/upsertWalletPolicyRule/upsertWalletPolicyRule.d.ts +2 -1
  265. package/dist/modules/waas/policies/upsertWalletPolicyRule/upsertWalletPolicyRule.d.ts.map +1 -1
  266. package/dist/modules/waas/waas.consts.d.ts +23 -0
  267. package/dist/modules/waas/waas.consts.d.ts.map +1 -0
  268. package/dist/modules/waas/waas.types.d.ts +30 -1
  269. package/dist/modules/waas/waas.types.d.ts.map +1 -1
  270. package/dist/modules/wallets/getWalletAccounts/getWalletAccountsFromState/getWalletAccountsFromState.d.ts +2 -2
  271. package/dist/modules/wallets/getWalletAccounts/getWalletAccountsFromState/getWalletAccountsFromState.d.ts.map +1 -1
  272. package/dist/modules/wallets/networks/getTransactionHistory/getTransactionHistory.d.ts +2 -2
  273. package/dist/modules/wallets/networks/getTransactionHistory/getTransactionHistory.d.ts.map +1 -1
  274. package/dist/modules/wallets/screenTransaction/screenTransaction.d.ts +1 -1
  275. package/dist/modules/wallets/screenTransaction/screenTransaction.d.ts.map +1 -1
  276. package/dist/modules/wallets/userHasEmbeddedWalletForChain/userHasEmbeddedWalletForChain.d.ts +2 -2
  277. package/dist/modules/wallets/userHasEmbeddedWalletForChain/userHasEmbeddedWalletForChain.d.ts.map +1 -1
  278. package/dist/modules/wallets/userHasExternalWallet/userHasExternalWallet.d.ts +2 -2
  279. package/dist/modules/wallets/userHasExternalWallet/userHasExternalWallet.d.ts.map +1 -1
  280. package/dist/modules/wallets/utils/formatWalletProviderKey/formatWalletProviderKey.d.ts +1 -1
  281. package/dist/modules/wallets/utils/formatWalletProviderKey/formatWalletProviderKey.d.ts.map +1 -1
  282. package/dist/modules/wallets/verifyMessageSignatureOwnership/verifyMessageSignatureOwnership.d.ts +5 -3
  283. package/dist/modules/wallets/verifyMessageSignatureOwnership/verifyMessageSignatureOwnership.d.ts.map +1 -1
  284. package/dist/modules/wallets/verifyWalletAccount/verifyWalletAccount.d.ts +1 -1
  285. package/dist/modules/wallets/verifyWalletAccount/verifyWalletAccount.d.ts.map +1 -1
  286. package/dist/modules/wallets/verifyWalletAccountForSignInOrTransfer/verifyWalletAccountForSignInOrTransfer.d.ts +1 -1
  287. package/dist/modules/wallets/verifyWalletAccountForSignInOrTransfer/verifyWalletAccountForSignInOrTransfer.d.ts.map +1 -1
  288. package/dist/modules/wallets/walletProvider/walletProvider.types.d.ts +4 -2
  289. package/dist/modules/wallets/walletProvider/walletProvider.types.d.ts.map +1 -1
  290. package/dist/modules/wallets/wallets.types.d.ts +47 -0
  291. package/dist/modules/wallets/wallets.types.d.ts.map +1 -0
  292. package/dist/modules/yield/yield.types.d.ts +8 -0
  293. package/dist/modules/yield/yield.types.d.ts.map +1 -1
  294. package/dist/services/eventEmitter/createEventEmitter.d.ts +3 -2
  295. package/dist/services/eventEmitter/createEventEmitter.d.ts.map +1 -1
  296. package/dist/services/eventEmitter/index.d.ts +1 -1
  297. package/dist/services/eventEmitter/index.d.ts.map +1 -1
  298. package/dist/tsconfig.lib.tsbuildinfo +1 -1
  299. package/dist/utils/createSequenceQueue/createSequenceQueue.d.ts +52 -0
  300. package/dist/utils/createSequenceQueue/createSequenceQueue.d.ts.map +1 -0
  301. package/dist/utils/createSequenceQueue/index.d.ts +3 -0
  302. package/dist/utils/createSequenceQueue/index.d.ts.map +1 -0
  303. package/dist/waas-BOKafCeH.cjs +2467 -0
  304. package/dist/waas-BOKafCeH.cjs.map +1 -0
  305. package/dist/waas-CUDgU2pl.esm.js +2150 -0
  306. package/dist/waas-CUDgU2pl.esm.js.map +1 -0
  307. package/dist/waas-CkQYVo6U.native.esm.js +2150 -0
  308. package/dist/waas-CkQYVo6U.native.esm.js.map +1 -0
  309. package/dist/waas.cjs +60 -2185
  310. package/dist/waas.esm.js +5 -2126
  311. package/dist/waas.native.esm.js +5 -2126
  312. package/dist/waasCore.cjs +76 -44
  313. package/dist/waasCore.cjs.map +1 -1
  314. package/dist/waasCore.esm.js +56 -24
  315. package/dist/waasCore.esm.js.map +1 -1
  316. package/dist/waasCore.native.esm.js +56 -24
  317. package/dist/waasCore.native.esm.js.map +1 -1
  318. package/package.json +5 -5
  319. package/dist/getNetworkProviderFromNetworkId--X0cb1ad.native.esm.js.map +0 -1
  320. package/dist/getNetworkProviderFromNetworkId-CamHn2s3.esm.js.map +0 -1
  321. package/dist/getNetworkProviderFromNetworkId-igDf2OPy.cjs.map +0 -1
  322. package/dist/getWalletProviderByKey-Cl6WDOoD.native.esm.js.map +0 -1
  323. package/dist/getWalletProviderByKey-DzpmoNlv.cjs.map +0 -1
  324. package/dist/getWalletProviderByKey-xqyD3ybv.esm.js.map +0 -1
  325. package/dist/isDynamicWaasEnabled-CMccs1-6.cjs +0 -136
  326. package/dist/isDynamicWaasEnabled-CMccs1-6.cjs.map +0 -1
  327. package/dist/isDynamicWaasEnabled-DSqgpEcX.native.esm.js +0 -113
  328. package/dist/isDynamicWaasEnabled-DSqgpEcX.native.esm.js.map +0 -1
  329. package/dist/isDynamicWaasEnabled-DYORq7Jc.esm.js +0 -113
  330. package/dist/isDynamicWaasEnabled-DYORq7Jc.esm.js.map +0 -1
  331. package/dist/isMfaRequiredForAction-BcJvy7Gw.native.esm.js.map +0 -1
  332. package/dist/isMfaRequiredForAction-CatS60F6.esm.js.map +0 -1
  333. package/dist/isMfaRequiredForAction-DKfoMhEk.cjs.map +0 -1
  334. package/dist/isUserOnboardingComplete-BWVuE4Jg.native.esm.js.map +0 -1
  335. package/dist/isUserOnboardingComplete-jkAQQVdP.esm.js.map +0 -1
  336. package/dist/isUserOnboardingComplete-jv_idxWY.cjs.map +0 -1
  337. package/dist/migrateFromFireblocks-B-WUs34v.native.esm.js +0 -65
  338. package/dist/migrateFromFireblocks-B-WUs34v.native.esm.js.map +0 -1
  339. package/dist/migrateFromFireblocks-D4E9bT2H.esm.js +0 -65
  340. package/dist/migrateFromFireblocks-D4E9bT2H.esm.js.map +0 -1
  341. package/dist/migrateFromFireblocks-zp5Jbq2J.cjs +0 -82
  342. package/dist/migrateFromFireblocks-zp5Jbq2J.cjs.map +0 -1
  343. package/dist/updateAuthFromVerifyResponse-BLgNMqwN.esm.js.map +0 -1
  344. package/dist/updateAuthFromVerifyResponse-CTvWpZLa.native.esm.js.map +0 -1
  345. package/dist/updateAuthFromVerifyResponse-Dsw-eAro.cjs.map +0 -1
  346. package/dist/waas.cjs.map +0 -1
  347. package/dist/waas.esm.js.map +0 -1
  348. package/dist/waas.native.esm.js.map +0 -1
@@ -31,14 +31,18 @@ zod_mini = __toESM(zod_mini);
31
31
 
32
32
  //#region package.json
33
33
  var name = "@dynamic-labs-sdk/client";
34
- var version = "1.30.2";
34
+ var version = "1.31.0";
35
35
 
36
36
  //#endregion
37
- //#region src/client/core/getCore/getCore.ts
38
- /** @notInstrumented */
39
- const getCore = (client) => {
40
- return client.__core;
41
- };
37
+ //#region src/modules/auth/consts.ts
38
+ const DYNAMIC_AUTH_COOKIE_NAME = "DYNAMIC_JWT_TOKEN";
39
+ /**
40
+ * Lists the scopes accepted by authentication and step-up APIs.
41
+ *
42
+ * @see authenticateTotpMfaDevice
43
+ * @see checkStepUpAuth
44
+ */
45
+ const TokenScope = _dynamic_labs_sdk_api_core.TokenScope;
42
46
 
43
47
  //#endregion
44
48
  //#region src/errors/base/BaseError.ts
@@ -103,6 +107,13 @@ var BaseError = class BaseError extends Error {
103
107
  }
104
108
  };
105
109
 
110
+ //#endregion
111
+ //#region src/client/core/getCore/getCore.ts
112
+ /** @notInstrumented */
113
+ const getCore = (client) => {
114
+ return client.__core;
115
+ };
116
+
106
117
  //#endregion
107
118
  //#region src/errors/ClientNotFoundError.ts
108
119
  var ClientNotFoundError = class extends BaseError {
@@ -150,11 +161,6 @@ const setDefaultClient = (client) => {
150
161
  numOfInitializedClients++;
151
162
  };
152
163
 
153
- //#endregion
154
- //#region src/utils/getNonce/constants.ts
155
- const NONCE_POOL_EXPIRATION_TIME = 6e4 * 60 * 24;
156
- const NONCE_POOL_SIZE = 5;
157
-
158
164
  //#endregion
159
165
  //#region src/utils/getPlatform/getPlatform.ts
160
166
  /**
@@ -283,7 +289,7 @@ const getSessionKeys = (client) => {
283
289
 
284
290
  //#endregion
285
291
  //#region src/generated/dependencyCatalog.ts
286
- const dependencyCatalog = { "@dynamic-labs/sdk-api-core": "0.12.0" };
292
+ const dependencyCatalog = { "@dynamic-labs/sdk-api-core": "0.25.0" };
287
293
 
288
294
  //#endregion
289
295
  //#region src/constants.ts
@@ -562,6 +568,11 @@ const createBaseApiClient = ({ middleware = [], options = {} }, client) => {
562
568
  }));
563
569
  };
564
570
 
571
+ //#endregion
572
+ //#region src/utils/getNonce/constants.ts
573
+ const NONCE_POOL_EXPIRATION_TIME = 6e4 * 60 * 24;
574
+ const NONCE_POOL_SIZE = 5;
575
+
565
576
  //#endregion
566
577
  //#region src/services/storage/createStorageKeySchema/createStorageKeySchema.ts
567
578
  /** @notInstrumented */
@@ -659,38 +670,6 @@ const fetchAndStoreNonces = async (client) => {
659
670
  return fetchPromise;
660
671
  };
661
672
 
662
- //#endregion
663
- //#region src/utils/getSecureCookieAttribute/getSecureCookieAttribute.ts
664
- /**
665
- * Returns the cookie `Secure` attribute suffix (`'; Secure'`) when the current
666
- * document is running in a secure context, or an empty string otherwise.
667
- *
668
- * The `Secure` attribute prevents the browser from ever transmitting the cookie
669
- * over an unencrypted `http://` connection, which mitigates cleartext token
670
- * capture (CWE-614). It is intentionally omitted on insecure/localhost dev,
671
- * because browsers reject `Secure` cookies set over `http://` and that would
672
- * silently break local testing.
673
- *
674
- * Used when building the Dynamic auth JWT cookie string so the attribute is
675
- * applied consistently on both the write (sign-in/refresh) and clear (logout)
676
- * paths.
677
- *
678
- * @notInstrumented
679
- */
680
- const getSecureCookieAttribute = () => {
681
- return Boolean(globalThis.window?.isSecureContext) || globalThis.location?.protocol === "https:" ? "; Secure" : "";
682
- };
683
-
684
- //#endregion
685
- //#region src/utils/setCookie/setCookie.ts
686
- /**
687
- * Sefelly sets the cookie in the browser.
688
- * @notInstrumented
689
- */
690
- const setCookie = (cookie) => {
691
- document.cookie = cookie;
692
- };
693
-
694
673
  //#endregion
695
674
  //#region src/utils/getNonce/getNonce.ts
696
675
  /**
@@ -794,160 +773,54 @@ const createDeviceSignatureHeadersMiddleware = (client) => {
794
773
  };
795
774
 
796
775
  //#endregion
797
- //#region src/modules/apiClient/createApiClient.ts
798
- /**
799
- * Returns a new instance of the SDK API client.
800
- *
801
- * This is not meant for storing, as it is very light we can create it whenever needed.
802
- * @notInstrumented
803
- */
804
- const createApiClient = (options = {}, client) => {
805
- return createBaseApiClient({
806
- middleware: [createDeviceSignatureHeadersMiddleware(client)],
807
- options
808
- }, client);
809
- };
810
-
811
- //#endregion
812
- //#region src/modules/clientEvents/clientEvents.ts
776
+ //#region src/utils/getSecureCookieAttribute/getSecureCookieAttribute.ts
813
777
  /**
814
- * Adds an event listener for Dynamic client events.
815
- *
816
- * This function allows you to listen for various events emitted by the Dynamic client,
817
- * such as authentication state changes, wallet connections, and more.
778
+ * Returns the cookie `Secure` attribute suffix (`'; Secure'`) when the current
779
+ * document is running in a secure context, or an empty string otherwise.
818
780
  *
819
- * @example
820
- * ```ts
821
- * const unsubscribe = onEvent({
822
- * event: 'walletAdded',
823
- * listener: ({ walletAccount }) => {
824
- * console.log('Wallet added:', walletAccount.address);
825
- * },
826
- * });
781
+ * The `Secure` attribute prevents the browser from ever transmitting the cookie
782
+ * over an unencrypted `http://` connection, which mitigates cleartext token
783
+ * capture (CWE-614). It is intentionally omitted on insecure/localhost dev,
784
+ * because browsers reject `Secure` cookies set over `http://` and that would
785
+ * silently break local testing.
827
786
  *
828
- * // Later: clean up
829
- * unsubscribe();
830
- * ```
787
+ * Used when building the Dynamic auth JWT cookie string so the attribute is
788
+ * applied consistently on both the write (sign-in/refresh) and clear (logout)
789
+ * paths.
831
790
  *
832
- * @param params.event - The event name to listen for.
833
- * @param params.listener - The callback function to execute when the event is fired.
834
- * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.
835
- * @returns A function that can be called to remove the listener.
836
- * @see offEvent
837
- * @see onceEvent
838
791
  * @notInstrumented
839
- * @hook Event listeners are error-prone to wire up by hand with useEffect.
840
792
  */
841
- const onEvent = ({ event, listener }, client = getDefaultClient()) => {
842
- const { eventEmitter } = getCore(client);
843
- eventEmitter.on(event, listener);
844
- return () => {
845
- eventEmitter.off(event, listener);
846
- };
793
+ const getSecureCookieAttribute = () => {
794
+ return Boolean(globalThis.window?.isSecureContext) || globalThis.location?.protocol === "https:" ? "; Secure" : "";
847
795
  };
796
+
797
+ //#endregion
798
+ //#region src/utils/setCookie/setCookie.ts
848
799
  /**
849
- * Removes an event listener from Dynamic client events.
850
- *
851
- * This function unsubscribes a previously registered event listener
852
- * from the specified Dynamic client event.
853
- *
854
- * @example
855
- * ```ts
856
- * offEvent({ event: 'walletAdded', listener: myListener });
857
- * ```
858
- *
859
- * @param params.event - The event name to remove the listener from.
860
- * @param params.listener - The callback function to remove.
861
- * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.
862
- * @see onEvent
863
- * @see onceEvent
800
+ * Sefelly sets the cookie in the browser.
864
801
  * @notInstrumented
865
802
  */
866
- const offEvent = ({ event, listener }, client = getDefaultClient()) => {
867
- const { eventEmitter } = getCore(client);
868
- eventEmitter.off(event, listener);
803
+ const setCookie = (cookie) => {
804
+ document.cookie = cookie;
869
805
  };
806
+
807
+ //#endregion
808
+ //#region src/modules/mfa/isUserMissingMfaAuth/isUserMissingMfaAuth.ts
870
809
  /**
871
- * Adds a one-time event listener for Dynamic client events.
872
- *
873
- * This function listens for an event that will automatically remove itself
874
- * after being triggered once.
810
+ * Checks if the user requires additional MFA authentication.
875
811
  *
876
- * @example
877
- * ```ts
878
- * onceEvent({
879
- * event: 'logout',
880
- * listener: () => {
881
- * console.log('User logged out');
882
- * },
883
- * });
884
- * ```
812
+ * This function determines if the current user session requires
813
+ * additional multi-factor authentication to access certain features.
885
814
  *
886
- * @param params.event - The event name to listen for.
887
- * @param params.listener - The callback function to execute when the event is fired.
888
815
  * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.
889
- * @returns A function that can be called to remove the listener before it fires.
890
- * @see onEvent
891
- * @see offEvent
892
- * @notInstrumented
893
- * @hook Event listeners are error-prone to wire up by hand with useEffect.
894
- */
895
- const onceEvent = ({ event, listener }, client = getDefaultClient()) => {
896
- const { eventEmitter } = getCore(client);
897
- eventEmitter.once(event, listener);
898
- return () => {
899
- eventEmitter.off(event, listener);
900
- };
901
- };
902
- /**
903
- * Emits a Dynamic client event.
904
- *
905
- * This function triggers an event that will be received by all registered
906
- * listeners for the specified event type.
907
- *
908
- * @param params.event - The event name to emit.
909
- * @param params.args - The arguments to pass to event listeners.
910
- * @param client - The Dynamic client instance.
816
+ * @returns True if the user needs additional MFA authentication, false otherwise.
911
817
  * @notInstrumented
818
+ * @hook Exposed as a hook so consumers reactively know when MFA is still required, updated when the user changes.
912
819
  */
913
- const emitEvent = ({ event, args }, client) => {
914
- const { eventEmitter } = getCore(client);
915
- eventEmitter.emit(event, args);
916
- };
917
-
918
- //#endregion
919
- //#region src/utils/retryOnFail/InvalidRetryOnFailCallError.ts
920
- /**
921
- * This error is thrown when the `retryOnFail` function is called with an invalid
922
- * number of retries (i.e. less than 0).
923
- */
924
- var InvalidRetryOnFailCallError = class extends BaseError {
925
- constructor(maxRetries) {
926
- super({
927
- cause: null,
928
- code: "invalid_retry_on_fail_call_error",
929
- docsUrl: null,
930
- name: "InvalidRetryOnFailCallError",
931
- shortMessage: `Invalid retries parameter for retryOnFail call: ${maxRetries}`
932
- });
933
- }
934
- };
935
-
936
- //#endregion
937
- //#region src/utils/retryOnFail/retryOnFail.ts
938
- /** @notInstrumented */
939
- const retryOnFail = async ({ delay = 0, fn, maxRetries }) => {
940
- for (let retry = 0; retry <= maxRetries; retry++) try {
941
- return await fn();
942
- } catch (error) {
943
- if (retry >= maxRetries) throw error;
944
- if (delay > 0) await new Promise((resolve) => setTimeout(resolve, delay));
945
- }
946
- /**
947
- * Reaching this point should never happen and this
948
- * error is thrown to help us debug the issue.
949
- */
950
- throw new InvalidRetryOnFailCallError(maxRetries);
820
+ const isUserMissingMfaAuth = (client = getDefaultClient()) => {
821
+ const user = client.user;
822
+ assertDefined(user, "User not logged in");
823
+ return Boolean(user.scope?.includes("requiresAdditionalAuth"));
951
824
  };
952
825
 
953
826
  //#endregion
@@ -1293,147 +1166,131 @@ const getWalletAccounts = (client = getDefaultClient()) => {
1293
1166
  };
1294
1167
 
1295
1168
  //#endregion
1296
- //#region src/modules/auth/isSignedIn/isSignedIn.ts
1169
+ //#region src/services/runtimeServices/createRuntimeServiceAccessKey/createRuntimeServiceAccessKey.ts
1297
1170
  /**
1298
- * Checks if the user is currently signed in to the Dynamic client.
1171
+ * Creates a service accessor function that manages service instantiation and caching.
1172
+ * The returned function will either retrieve an existing service from the registry or
1173
+ * create a new one using the provided builder function.
1299
1174
  *
1300
- * The client is considered to be in a signed in state if a user has
1301
- * authenticated or if the client has at least one wallet connected.
1175
+ * @template - The type of service to be created/accessed
1176
+ * @param key - Unique identifier for the service in the registry
1177
+ * @param builder - Function that creates the service instance when called with a DynamicClient
1178
+ * @notInstrumented
1179
+ */
1180
+ const createRuntimeServiceAccessKey = (key, builder) => (client) => {
1181
+ const { runtimeServices } = getCore(client);
1182
+ const currentService = runtimeServices.getByKey(key);
1183
+ if (currentService) return currentService;
1184
+ const service = builder(client);
1185
+ runtimeServices.register(key, service);
1186
+ return service;
1187
+ };
1188
+
1189
+ //#endregion
1190
+ //#region src/modules/clientEvents/clientEvents.ts
1191
+ /**
1192
+ * Adds an event listener for Dynamic client events.
1302
1193
  *
1303
- * @deprecated What counts as "signed in" is your app's business logic, not the
1304
- * SDK's. This helper bakes in one opinion (a user OR any connected wallet),
1305
- * which rarely matches every app and forces a dependency on us for every
1306
- * variation. Compose your own check from the underlying primitives instead —
1307
- * e.g. `Boolean(client.user) || isAnyWalletAccountConnected(client)` — and
1308
- * layer in whatever your app requires (device registration, completed
1309
- * onboarding, satisfied MFA, a required embedded wallet, …). See the
1310
- * "Check if signed in" guide:
1311
- * https://www.dynamic.xyz/docs/javascript/user-session-management
1194
+ * This function allows you to listen for various events emitted by the Dynamic client,
1195
+ * such as authentication state changes, wallet connections, and more.
1312
1196
  *
1313
1197
  * @example
1314
1198
  * ```ts
1315
- * if (isSignedIn()) {
1316
- * console.log('User is authenticated or has a wallet connected');
1317
- * }
1199
+ * const unsubscribe = onEvent({
1200
+ * event: 'walletAdded',
1201
+ * listener: ({ walletAccount }) => {
1202
+ * console.log('Wallet added:', walletAccount.address);
1203
+ * },
1204
+ * });
1205
+ *
1206
+ * // Later: clean up
1207
+ * unsubscribe();
1318
1208
  * ```
1319
1209
  *
1210
+ * @param params.event - The event name to listen for.
1211
+ * @param params.listener - The callback function to execute when the event is fired.
1320
1212
  * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.
1321
- * @returns True if the user is signed in, false otherwise.
1322
- * @see logout
1323
- * @see isAnyWalletAccountConnected
1213
+ * @returns A function that can be called to remove the listener.
1214
+ * @see offEvent
1215
+ * @see onceEvent
1324
1216
  * @notInstrumented
1217
+ * @hook Event listeners are error-prone to wire up by hand with useEffect.
1325
1218
  */
1326
- const isSignedIn = (client = getDefaultClient()) => Boolean(client.user || getWalletAccounts(client).length > 0);
1327
-
1328
- //#endregion
1329
- //#region src/modules/projectSettings/fetchProjectSettings/projectSettingsExpirationScheme.ts
1330
- /**
1331
- * The schema to track the expiration time of the project settings.
1332
- */
1333
- const projectSettingsExpirationStorageKeySchema = createStorageKeySchema({
1334
- key: "projectSettingsExpiration",
1335
- schema: zod_mini.number()
1336
- });
1337
-
1338
- //#endregion
1339
- //#region src/modules/projectSettings/fetchProjectSettings/fetchProjectSettings.ts
1219
+ const onEvent = ({ event, listener }, client = getDefaultClient()) => {
1220
+ const { eventEmitter } = getCore(client);
1221
+ eventEmitter.on(event, listener);
1222
+ return () => {
1223
+ eventEmitter.off(event, listener);
1224
+ };
1225
+ };
1340
1226
  /**
1341
- * Expiration time of the project settings in milliseconds.
1227
+ * Removes an event listener from Dynamic client events.
1228
+ *
1229
+ * This function unsubscribes a previously registered event listener
1230
+ * from the specified Dynamic client event.
1231
+ *
1232
+ * @example
1233
+ * ```ts
1234
+ * offEvent({ event: 'walletAdded', listener: myListener });
1235
+ * ```
1236
+ *
1237
+ * @param params.event - The event name to remove the listener from.
1238
+ * @param params.listener - The callback function to remove.
1239
+ * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.
1240
+ * @see onEvent
1241
+ * @see onceEvent
1242
+ * @notInstrumented
1342
1243
  */
1343
- const PROJECT_SETTINGS_EXPIRATION_TIME = 1e3 * 60 * 5;
1244
+ const offEvent = ({ event, listener }, client = getDefaultClient()) => {
1245
+ const { eventEmitter } = getCore(client);
1246
+ eventEmitter.off(event, listener);
1247
+ };
1344
1248
  /**
1345
- * Fetches and updates the project settings from the API.
1249
+ * Adds a one-time event listener for Dynamic client events.
1346
1250
  *
1347
- * This function retrieves the latest project configuration settings
1348
- * from Dynamic's servers, including authentication options, enabled chains,
1349
- * and security configurations. The settings are cached for performance.
1251
+ * This function listens for an event that will automatically remove itself
1252
+ * after being triggered once.
1350
1253
  *
1351
1254
  * @example
1352
1255
  * ```ts
1353
- * const settings = await fetchProjectSettings();
1354
- * console.log('Enabled chains:', settings.chains);
1256
+ * onceEvent({
1257
+ * event: 'logout',
1258
+ * listener: () => {
1259
+ * console.log('User logged out');
1260
+ * },
1261
+ * });
1355
1262
  * ```
1356
1263
  *
1264
+ * @param params.event - The event name to listen for.
1265
+ * @param params.listener - The callback function to execute when the event is fired.
1357
1266
  * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.
1358
- * @returns A promise that resolves to the updated project settings.
1359
- * @see createDynamicClient
1360
- * @see initializeClient
1267
+ * @returns A function that can be called to remove the listener before it fires.
1268
+ * @see onEvent
1269
+ * @see offEvent
1361
1270
  * @notInstrumented
1362
- * @noHook Internal settings fetch that is not part of the public hook surface.
1271
+ * @hook Event listeners are error-prone to wire up by hand with useEffect.
1363
1272
  */
1364
- const fetchProjectSettings = async (client = getDefaultClient()) => {
1365
- const core = getCore(client);
1366
- const currentExpiration = await core.storage.getItem(projectSettingsExpirationStorageKeySchema);
1367
- if (Boolean(client.projectSettings) && !(currentExpiration && currentExpiration < Date.now()) && isSignedIn(client)) return client.projectSettings;
1368
- const apiClient = createApiClient({}, client);
1369
- core.logger.debug("[fetchProjectSettings] Fetching project settings...");
1370
- const doFetch = async () => apiClient.getEnvironmentSettings({
1371
- environmentId: core.environmentId,
1372
- sdkVersion: `${CLIENT_SDK_NAME}/${core.version}`
1373
- }, { credentials: "omit" });
1374
- const projectSettings = await retryOnFail({
1375
- fn: doFetch,
1376
- maxRetries: 2
1377
- });
1378
- core.state.set({ projectSettings: projectSettings ?? null });
1379
- await core.storage.setItem(projectSettingsExpirationStorageKeySchema, Date.now() + PROJECT_SETTINGS_EXPIRATION_TIME);
1380
- return projectSettings;
1381
- };
1382
-
1383
- //#endregion
1384
- //#region src/modules/sessionKeys/generateSessionKeys/generateSessionKeys.ts
1385
- /** @notInstrumented */
1386
- const generateSessionKeys = async (client) => {
1387
- const core = getCore(client);
1388
- const currentState = core.state.get();
1389
- const isRotation = Boolean(currentState.sessionKeys);
1390
- const logContext = {
1391
- environmentId: core.environmentId,
1392
- operation: isRotation ? "rotate" : "create",
1393
- userId: currentState.user?.id ?? null
1273
+ const onceEvent = ({ event, listener }, client = getDefaultClient()) => {
1274
+ const { eventEmitter } = getCore(client);
1275
+ eventEmitter.once(event, listener);
1276
+ return () => {
1277
+ eventEmitter.off(event, listener);
1394
1278
  };
1395
- core.logger.info(isRotation ? "[generateSessionKeys] Rotating session key..." : "[generateSessionKeys] Creating session key...", logContext);
1396
- await core.keychain.removeKey("session");
1397
- const publicKey = await core.keychain.generateKey("session");
1398
- assertDefined(publicKey, "Public key not found");
1399
- core.state.set({ sessionKeys: publicKey });
1400
- core.logger.info(isRotation ? "[generateSessionKeys] Session key rotated" : "[generateSessionKeys] Session key created", logContext);
1401
- return { publicKey };
1402
- };
1403
-
1404
- //#endregion
1405
- //#region src/errors/NoWalletProviderFoundError.ts
1406
- var NoWalletProviderFoundError = class extends BaseError {
1407
- constructor({ walletProviderKey }) {
1408
- super({
1409
- cause: null,
1410
- code: "no_wallet_provider_found_error",
1411
- docsUrl: null,
1412
- name: "NoWalletProviderFoundError",
1413
- shortMessage: `No wallet provider found with key: ${walletProviderKey}`
1414
- });
1415
- }
1416
1279
  };
1417
-
1418
- //#endregion
1419
- //#region src/services/runtimeServices/createRuntimeServiceAccessKey/createRuntimeServiceAccessKey.ts
1420
1280
  /**
1421
- * Creates a service accessor function that manages service instantiation and caching.
1422
- * The returned function will either retrieve an existing service from the registry or
1423
- * create a new one using the provided builder function.
1281
+ * Emits a Dynamic client event.
1424
1282
  *
1425
- * @template - The type of service to be created/accessed
1426
- * @param key - Unique identifier for the service in the registry
1427
- * @param builder - Function that creates the service instance when called with a DynamicClient
1283
+ * This function triggers an event that will be received by all registered
1284
+ * listeners for the specified event type.
1285
+ *
1286
+ * @param params.event - The event name to emit.
1287
+ * @param params.args - The arguments to pass to event listeners.
1288
+ * @param client - The Dynamic client instance.
1428
1289
  * @notInstrumented
1429
1290
  */
1430
- const createRuntimeServiceAccessKey = (key, builder) => (client) => {
1431
- const { runtimeServices } = getCore(client);
1432
- const currentService = runtimeServices.getByKey(key);
1433
- if (currentService) return currentService;
1434
- const service = builder(client);
1435
- runtimeServices.register(key, service);
1436
- return service;
1291
+ const emitEvent = ({ event, args }, client) => {
1292
+ const { eventEmitter } = getCore(client);
1293
+ eventEmitter.emit(event, args);
1437
1294
  };
1438
1295
 
1439
1296
  //#endregion
@@ -1542,62 +1399,93 @@ const WalletProviderPriority = {
1542
1399
  };
1543
1400
 
1544
1401
  //#endregion
1545
- //#region src/modules/wallets/utils/getWalletProviderFromWalletAccount/getWalletProviderFromWalletAccount.ts
1402
+ //#region src/modules/wallets/getWalletProviders/getWalletProviders.ts
1403
+ /**
1404
+ * Get all available wallet providers to interact with internally.
1405
+ * @notInstrumented
1406
+ */
1407
+ const getWalletProviders = (client) => {
1408
+ return getWalletProviderRegistry(client).listProviders();
1409
+ };
1410
+
1411
+ //#endregion
1412
+ //#region src/modules/waas/constants.ts
1413
+ const DEFAULT_WAAS_BASE_API_URL = "https://app.dynamicauth.com";
1414
+ const DEFAULT_WAAS_BASE_MPC_RELAY_API_URL = "https://relay.dynamicauth.com";
1415
+ const DYNAMIC_WAAS_METADATA = {
1416
+ displayName: "Dynamic WaaS",
1417
+ icon: `${DYNAMIC_ICONIC_SPRITE_URL}#dynamicwaas`,
1418
+ normalizedWalletName: "dynamicwaas"
1419
+ };
1420
+
1421
+ //#endregion
1422
+ //#region src/modules/waas/isWaasWalletProvider/isWaasWalletProvider.ts
1546
1423
  /** @notInstrumented */
1547
- const getWalletProviderFromWalletAccount = ({ walletAccount }, client) => {
1548
- const walletProvider = getWalletProviderRegistry(client).getByKey(walletAccount.walletProviderKey);
1549
- if (!walletProvider) throw new NoWalletProviderFoundError({ walletProviderKey: walletAccount.walletProviderKey });
1550
- return walletProvider;
1424
+ const isWaasWalletProvider = (walletProvider) => {
1425
+ return walletProvider.key.includes(DYNAMIC_WAAS_METADATA.normalizedWalletName);
1551
1426
  };
1552
1427
 
1553
1428
  //#endregion
1554
- //#region src/modules/wallets/utils/getAvailableWalletProvidersFromWalletAccounts/getAvailableWalletProvidersFromWalletAccounts.ts
1429
+ //#region src/modules/waas/findWaasWalletProviderByChain/findWaasWalletProviderByChain.ts
1555
1430
  /** @notInstrumented */
1556
- const getAvailableWalletProvidersFromWalletAccounts = (client) => {
1557
- const core = getCore(client);
1558
- const walletProvidersMap = /* @__PURE__ */ new Map();
1559
- getWalletAccounts(client).forEach((walletAccount) => {
1560
- if (walletProvidersMap.has(walletAccount.walletProviderKey)) return;
1561
- try {
1562
- const walletProvider = getWalletProviderFromWalletAccount({ walletAccount }, client);
1563
- walletProvidersMap.set(walletAccount.walletProviderKey, walletProvider);
1564
- } catch (error) {
1565
- core.logger.debug("Wallet provider not found for wallet account", {
1566
- error,
1567
- walletAccount: walletAccount.address
1568
- });
1569
- }
1431
+ const findWaasWalletProviderByChain = ({ chain }, client) => {
1432
+ const providers = getWalletProviders(client);
1433
+ const waasProviderKey = formatWalletProviderKey({
1434
+ chain,
1435
+ displayName: DYNAMIC_WAAS_METADATA.displayName,
1436
+ walletProviderType: _dynamic_labs_sdk_api_core.WalletProviderEnum.EmbeddedWallet
1570
1437
  });
1571
- return Array.from(walletProvidersMap.values());
1438
+ const waasProvider = providers.find((provider) => provider.key === waasProviderKey && provider.chain === chain);
1439
+ if (!waasProvider || !isWaasWalletProvider(waasProvider)) return null;
1440
+ return waasProvider;
1572
1441
  };
1573
1442
 
1574
1443
  //#endregion
1575
- //#region src/modules/wallets/destroyWalletProviders/destroyWalletProviders.ts
1444
+ //#region src/modules/waas/isWaasWalletAccount/isWaasWalletAccount.ts
1576
1445
  /**
1577
- * Tear down every wallet provider on the client.
1578
- *
1579
- * Each provider's `destroy` is responsible for its own local + remote
1580
- * cleanup. We swallow errors so a failing destroy on one provider does not
1581
- * block teardown of the others (e.g. during logout).
1446
+ * This function determines whether the provided wallet account is a Dynamic
1447
+ * WaaS wallet account.
1582
1448
  *
1449
+ * @param params.walletAccount - The wallet account to check.
1450
+ * @returns True if the wallet account is a WaaS wallet account, false otherwise.
1583
1451
  * @notInstrumented
1584
1452
  */
1585
- const destroyWalletProviders = async ({ reason }, client) => {
1586
- const core = getCore(client);
1587
- const walletProviders = getAvailableWalletProvidersFromWalletAccounts(client);
1588
- await Promise.all(walletProviders.map(async (walletProvider) => {
1589
- if (!walletProvider.destroy) return;
1590
- try {
1591
- await walletProvider.destroy({ reason });
1592
- } catch (err) {
1593
- core.logger.error(`Error destroying wallet provider ${walletProvider.key}`, err);
1594
- }
1595
- }));
1453
+ const isWaasWalletAccount = ({ walletAccount }) => {
1454
+ return walletAccount.walletProviderKey.includes(DYNAMIC_WAAS_METADATA.normalizedWalletName);
1596
1455
  };
1597
1456
 
1598
1457
  //#endregion
1599
- //#region src/modules/auth/consts.ts
1600
- const DYNAMIC_AUTH_COOKIE_NAME = "DYNAMIC_JWT_TOKEN";
1458
+ //#region src/modules/waas/initializeWaasClientsForEagerRecovery/initializeWaasClientsForEagerRecovery.ts
1459
+ /**
1460
+ * On login, boots the WaaS client once per chain so the SDK eagerly recovers
1461
+ * key shares itself (the `eagerlyRecoverKeyShares` capability) instead of the
1462
+ * host looping per wallet. Booting calls `initialize()`, which sends the auth
1463
+ * token the iframe needs to self-recover.
1464
+ *
1465
+ * @notInstrumented
1466
+ */
1467
+ const initializeWaasClientsForEagerRecovery = async (client) => {
1468
+ /**
1469
+ * Booting triggers recovery, which fails if the user is missing the MFA auth.
1470
+ * This early return avoids attempting a call we know will fail and just adds
1471
+ * noise to the logs.
1472
+ */
1473
+ if (isUserMissingMfaAuth(client)) return;
1474
+ const waasChains = new Set(getWalletAccounts(client).filter((walletAccount) => isWaasWalletAccount({ walletAccount })).map((walletAccount) => walletAccount.chain));
1475
+ await Promise.all([...waasChains].map(async (chain) => {
1476
+ const provider = findWaasWalletProviderByChain({ chain }, client);
1477
+ /**
1478
+ * The environment might not have the embedded wallet extensions installed.
1479
+ * In that case there is no provider for the chain and nothing to boot.
1480
+ */
1481
+ if (!provider) return;
1482
+ try {
1483
+ await provider.getWaasClient();
1484
+ } catch (error) {
1485
+ getCore(client).logger.warn("[initializeWaasClientsForEagerRecovery] failed to boot waas client", error);
1486
+ }
1487
+ }));
1488
+ };
1601
1489
 
1602
1490
  //#endregion
1603
1491
  //#region src/modules/wallets/emitWalletAccountsChangedEvent/emitWalletAccountsChangedEvent.ts
@@ -1621,6 +1509,160 @@ const checkAndRaiseWalletAccountsChangedEvent = ({ previousState }, client) => {
1621
1509
  };
1622
1510
  const getWalletAccountsHash = (state, client) => getWalletAccountsFromState(state, client).map((walletAccount) => JSON.stringify(walletAccount)).sort().join("-");
1623
1511
 
1512
+ //#endregion
1513
+ //#region src/errors/InvalidParamError.ts
1514
+ var InvalidParamError = class extends BaseError {
1515
+ constructor(message) {
1516
+ super({
1517
+ cause: null,
1518
+ code: "invalid_param_error",
1519
+ docsUrl: null,
1520
+ name: "InvalidParamError",
1521
+ shortMessage: message
1522
+ });
1523
+ }
1524
+ };
1525
+
1526
+ //#endregion
1527
+ //#region src/modules/auth/decodeJwt/decodeJwt.ts
1528
+ /**
1529
+ * Decodes a JWT token and returns the full payload.
1530
+ *
1531
+ * This function extracts and returns the complete JWT payload including scopes,
1532
+ * expiration time, and other claims.
1533
+ *
1534
+ * @param jwt - The JWT token string.
1535
+ * @returns The decoded JWT payload object.
1536
+ * @throws InvalidParamError if the token is invalid or cannot be decoded.
1537
+ *
1538
+ * @example
1539
+ * ```typescript
1540
+ * const payload = decodeJwt(jwt);
1541
+ * // Returns: { scopes: ['wallet:export'], exp: 1234567890, ... }
1542
+ * ```
1543
+ * @notInstrumented
1544
+ */
1545
+ const decodeJwt = (jwt) => {
1546
+ try {
1547
+ const parts = jwt.split(".");
1548
+ if (parts.length !== 3) throw new InvalidParamError("Invalid JWT format");
1549
+ const base64Payload = parts[1].replaceAll("-", "+").replaceAll("_", "/");
1550
+ const paddedPayload = base64Payload + "=".repeat((4 - base64Payload.length % 4) % 4);
1551
+ const decodedPayload = atob(paddedPayload);
1552
+ return JSON.parse(decodedPayload);
1553
+ } catch (error) {
1554
+ if (error instanceof InvalidParamError) throw error;
1555
+ throw new InvalidParamError(`Failed to decode JWT: ${error instanceof Error ? error.message : String(error)}`);
1556
+ }
1557
+ };
1558
+
1559
+ //#endregion
1560
+ //#region src/modules/auth/updateAuthFromVerifyResponse/elevatedAccessTokens/normalizeScopes/normalizeScopes.ts
1561
+ /**
1562
+ * Normalizes scopes by deduplicating and sorting them.
1563
+ * This creates a canonical representation for comparison.
1564
+ *
1565
+ * @param scopes - Array of scope strings (may contain duplicates)
1566
+ * @returns Normalized, sorted array of unique scopes
1567
+ * @notInstrumented
1568
+ */
1569
+ const normalizeScopes = (scopes) => {
1570
+ return [...new Set(scopes)].sort((a, b) => a.localeCompare(b));
1571
+ };
1572
+
1573
+ //#endregion
1574
+ //#region src/modules/auth/updateAuthFromVerifyResponse/elevatedAccessTokens/parseElevatedAccessToken/parseElevatedAccessToken.ts
1575
+ /**
1576
+ * Validates and parses an elevated access token from a JWT string.
1577
+ * Extracts scopes, expiration, and validates the token structure.
1578
+ *
1579
+ * Policy decisions:
1580
+ * - Tokens without scopes are rejected (returns null)
1581
+ * - Tokens with empty scopes array are rejected (returns null)
1582
+ * - Tokens without exp field are rejected (returns null)
1583
+ * - Expired tokens are rejected (returns null)
1584
+ *
1585
+ * @returns Parsed token data or null if token is invalid/expired
1586
+ * @notInstrumented
1587
+ */
1588
+ const parseElevatedAccessToken = ({ token }) => {
1589
+ const payload = decodeJwt(token);
1590
+ const filteredScopes = ((payload?.scope)?.split(" ") ?? []).filter((s) => s.length > 0);
1591
+ const singleUse = payload.singleUse ?? false;
1592
+ if (!filteredScopes || filteredScopes.length === 0) return null;
1593
+ if (!payload.exp) return null;
1594
+ const expiresAt = /* @__PURE__ */ new Date(payload.exp * 1e3);
1595
+ if (expiresAt <= /* @__PURE__ */ new Date()) return null;
1596
+ return {
1597
+ expiresAt,
1598
+ normalizedScopes: normalizeScopes(filteredScopes),
1599
+ scopes: filteredScopes,
1600
+ singleUse,
1601
+ token
1602
+ };
1603
+ };
1604
+
1605
+ //#endregion
1606
+ //#region src/modules/auth/updateAuthFromVerifyResponse/elevatedAccessTokens/upsertElevatedAccessToken/upsertElevatedAccessToken.ts
1607
+ /**
1608
+ * Upserts an elevated access token into the current tokens array.
1609
+ *
1610
+ * Policy: Only one token per normalized scope-set is allowed.
1611
+ * If a token with the same normalized scopes exists, it is replaced.
1612
+ * This ensures we don't accumulate multiple tokens for the same scope combination.
1613
+ *
1614
+ * @param currentTokens - Current array of elevated access tokens
1615
+ * @param newToken - New token to upsert
1616
+ * @returns Updated array of tokens with the new token upserted
1617
+ * @notInstrumented
1618
+ */
1619
+ const upsertElevatedAccessToken = ({ currentTokens, newToken }) => {
1620
+ const newScopeKey = normalizeScopes(newToken.scopes).join(" ");
1621
+ return [...currentTokens.filter((existingToken) => {
1622
+ return normalizeScopes(existingToken.scopes).join(" ") !== newScopeKey;
1623
+ }), {
1624
+ expiresAt: newToken.expiresAt,
1625
+ scopes: newToken.scopes,
1626
+ singleUse: newToken.singleUse,
1627
+ token: newToken.token
1628
+ }];
1629
+ };
1630
+
1631
+ //#endregion
1632
+ //#region src/modules/auth/updateAuthFromVerifyResponse/updateAuthFromVerifyResponse.ts
1633
+ /** @notInstrumented */
1634
+ const updateAuthFromVerifyResponse = ({ response }, client) => {
1635
+ const core = getCore(client);
1636
+ const previousState = { ...core.state.get() };
1637
+ const { user, minifiedJwt, jwt, expiresAt, mfaToken, elevatedAccessToken } = response;
1638
+ const sessionExpiresAt = /* @__PURE__ */ new Date(expiresAt * 1e3);
1639
+ const newState = {
1640
+ legacyToken: jwt ?? null,
1641
+ sessionExpiresAt,
1642
+ token: minifiedJwt ?? null,
1643
+ user
1644
+ };
1645
+ if (mfaToken) newState.mfaToken = mfaToken;
1646
+ const currentTokens = core.state.get().elevatedAccessTokens || [];
1647
+ newState.elevatedAccessTokens = currentTokens;
1648
+ if (elevatedAccessToken) {
1649
+ const parsedToken = parseElevatedAccessToken({ token: elevatedAccessToken });
1650
+ if (parsedToken) newState.elevatedAccessTokens = upsertElevatedAccessToken({
1651
+ currentTokens,
1652
+ newToken: parsedToken
1653
+ });
1654
+ }
1655
+ core.state.set(newState);
1656
+ /**
1657
+ * For customers using a sandbox environment with cookies enabled, we need to set the cookie
1658
+ * programmatically because Redcoast won't set the cookie via headers. We set the cookie programmatically
1659
+ * so customers can access the cookie from document.cookie consistently between sandbox and live environments.
1660
+ */
1661
+ if (minifiedJwt && isCookieEnabled(client)) setCookie(`${DYNAMIC_AUTH_COOKIE_NAME}=${minifiedJwt}; expires=${sessionExpiresAt.toUTCString()}; path=/; SameSite=Lax${getSecureCookieAttribute()}`);
1662
+ checkAndRaiseWalletAccountsChangedEvent({ previousState }, client);
1663
+ if (!previousState.user && Boolean(newState.user)) initializeWaasClientsForEagerRecovery(client);
1664
+ };
1665
+
1624
1666
  //#endregion
1625
1667
  //#region src/modules/auth/extractSessionId/extractSessionId.ts
1626
1668
  /**
@@ -2030,67 +2072,41 @@ const instrumentFunction = ({ fn, functionName, getCore: getCore$1, selectors })
2030
2072
  };
2031
2073
 
2032
2074
  //#endregion
2033
- //#region src/modules/auth/logoutWithReason/logoutWithReason.ts
2075
+ //#region src/modules/user/refreshAuth/refreshAuth.ts
2034
2076
  /**
2035
- * Logs the user out with an explicit reason.
2077
+ * Refreshes the current session's authentication from the server.
2036
2078
  *
2037
- * Revokes the session, clears auth state, terminates wallet providers, and
2038
- * emits the `logout` client event with the given reason. The reason is also
2039
- * captured as an argument on the function-instrumentation event, which is
2040
- * how Datadog distinguishes between different logout causes.
2079
+ * This rotates the auth token via a full verify call and updates both the
2080
+ * token and the user state from the response, returning the raw
2081
+ * `VerifyResponse` (which includes the new token). Reach for this when you
2082
+ * need a fresh JWT e.g. before a call that requires a non-expired token.
2041
2083
  *
2042
- * Use this instead of the public `logout` when triggering a logout from
2043
- * internal or extension code the caller owns the reason string, so the
2044
- * telemetry correctly attributes *why* the logout happened.
2084
+ * Prefer `refreshUser` when you only need the latest user profile and do not
2085
+ * care about rotating the token: it hits the authenticated-user endpoint,
2086
+ * touches only the user state, and returns the `User` directly.
2045
2087
  *
2046
- * @param params - The logout params.
2047
- * @param params.reason - Why the logout is being triggered. Extension authors
2048
- * needing a reason outside the SDK catalog can cast with `as LogoutReason`.
2049
- * @param client - The Dynamic client instance.
2088
+ * @example
2089
+ * ```ts
2090
+ * const response = await refreshAuth();
2091
+ * console.log('Token refreshed:', response.token);
2092
+ * ```
2093
+ *
2094
+ * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.
2095
+ * @returns A promise that resolves to the verify response.
2096
+ * @see logout
2097
+ * @see refreshUser
2050
2098
  * @instrumented
2051
2099
  */
2052
- const logoutWithReason = async ({ reason }, client) => {
2100
+ const refreshAuth = async (client = getDefaultClient()) => {
2053
2101
  const core = getCore(client);
2054
- core.logger.debug("[logoutWithReason] Logging out...", { reason });
2055
- await destroyWalletProviders({ reason }, client);
2056
- if (client.user !== null) {
2057
- const apiClient = createApiClient({ headers: { [DYNAMIC_LOGOUT_REASON_HEADER]: reason } }, client);
2058
- try {
2059
- await apiClient.revokeSession({ environmentId: core.environmentId });
2060
- } catch (error) {
2061
- core.logger.error("Failed to revoke session", error);
2062
- }
2063
- /**
2064
- * This deletes the auth cookie if it exists.
2065
- * If the cookie doesn't exist, this sets a new cookie that expires immediately.
2066
- */
2067
- if (isCookieEnabled(client)) setCookie(`${DYNAMIC_AUTH_COOKIE_NAME}=; Max-Age=-99999999; path=/; SameSite=Lax${getSecureCookieAttribute()}`);
2068
- }
2069
- await core.keychain.removeKey("session");
2070
- const previousState = core.state.get();
2071
- core.state.set({
2072
- captchaToken: null,
2073
- elevatedAccessTokens: [],
2074
- legacyToken: null,
2075
- mfaToken: null,
2076
- sessionExpiresAt: null,
2077
- sessionKeys: null,
2078
- token: null,
2079
- unverifiedWalletAccounts: [],
2080
- user: null
2081
- });
2082
- emitEvent({
2083
- args: { reason },
2084
- event: "logout"
2085
- }, client);
2086
- checkAndRaiseWalletAccountsChangedEvent({ previousState }, client);
2087
- fetchProjectSettings(client);
2088
- generateSessionKeys(client);
2089
- };
2090
- const __logoutWithReason_impl = logoutWithReason;
2091
- const __logoutWithReason_wrapped = instrumentFunction({
2092
- fn: __logoutWithReason_impl,
2093
- functionName: "logoutWithReason",
2102
+ const response = await createBaseApiClient({ middleware: [createDeviceSignatureHeadersMiddleware(client)] }, client).refreshAuth({ environmentId: core.environmentId });
2103
+ updateAuthFromVerifyResponse({ response }, client);
2104
+ return response;
2105
+ };
2106
+ const __refreshAuth_impl = refreshAuth;
2107
+ const __refreshAuth_wrapped = instrumentFunction({
2108
+ fn: __refreshAuth_impl,
2109
+ functionName: "refreshAuth",
2094
2110
  getCore: () => {
2095
2111
  try {
2096
2112
  return getCore(getDefaultClient());
@@ -2101,266 +2117,342 @@ const __logoutWithReason_wrapped = instrumentFunction({
2101
2117
  });
2102
2118
 
2103
2119
  //#endregion
2104
- //#region src/modules/mfa/isUserMissingMfaAuth/isUserMissingMfaAuth.ts
2120
+ //#region src/modules/apiClient/utils/rbacStaleMiddleware/createRbacStaleMiddleware.ts
2121
+ const RBAC_STALE_CODE = "rbac_stale";
2122
+ const RBAC_STALE_RETRY_HEADER = "x-dyn-rbac-retry";
2105
2123
  /**
2106
- * Checks if the user requires additional MFA authentication.
2107
- *
2108
- * This function determines if the current user session requires
2109
- * additional multi-factor authentication to access certain features.
2110
- *
2111
- * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.
2112
- * @returns True if the user needs additional MFA authentication, false otherwise.
2124
+ * Detects 403 { code: 'rbac_stale' } responses, refreshes the auth token, and
2125
+ * retries the request once with the new token. This lets business account role
2126
+ * changes take effect without revoking the user's session.
2113
2127
  * @notInstrumented
2114
- * @hook Exposed as a hook so consumers reactively know when MFA is still required, updated when the user changes.
2115
2128
  */
2116
- const isUserMissingMfaAuth = (client = getDefaultClient()) => {
2117
- const user = client.user;
2118
- assertDefined(user, "User not logged in");
2119
- return Boolean(user.scope?.includes("requiresAdditionalAuth"));
2120
- };
2129
+ const createRbacStaleMiddleware = (client) => ({ post: async (context) => {
2130
+ if (context.response.status !== 403) return context.response;
2131
+ if (context.init.headers && typeof context.init.headers === "object" && RBAC_STALE_RETRY_HEADER in context.init.headers) return context.response;
2132
+ let errorBody;
2133
+ try {
2134
+ errorBody = await context.response.clone().json();
2135
+ } catch {
2136
+ return context.response;
2137
+ }
2138
+ if (!(typeof errorBody === "object" && errorBody !== null && "code" in errorBody && errorBody.code === RBAC_STALE_CODE)) return context.response;
2139
+ try {
2140
+ await __refreshAuth_wrapped(client);
2141
+ } catch {
2142
+ return context.response;
2143
+ }
2144
+ if (!client.token) return context.response;
2145
+ const headers = { ...context.init.headers };
2146
+ delete headers[RBAC_STALE_RETRY_HEADER];
2147
+ delete headers[MFA_TOKEN_HEADER];
2148
+ delete headers[ELEVATED_ACCESS_TOKEN_HEADER];
2149
+ headers.Authorization = `Bearer ${client.token}`;
2150
+ return context.fetch(context.url, {
2151
+ ...context.init,
2152
+ headers: {
2153
+ ...headers,
2154
+ [RBAC_STALE_RETRY_HEADER]: "1"
2155
+ }
2156
+ });
2157
+ } });
2121
2158
 
2122
2159
  //#endregion
2123
- //#region src/modules/wallets/getWalletProviders/getWalletProviders.ts
2160
+ //#region src/modules/apiClient/createApiClient.ts
2124
2161
  /**
2125
- * Get all available wallet providers to interact with internally.
2162
+ * Returns a new instance of the SDK API client.
2163
+ *
2164
+ * This is not meant for storing, as it is very light we can create it whenever needed.
2126
2165
  * @notInstrumented
2127
2166
  */
2128
- const getWalletProviders = (client) => {
2129
- return getWalletProviderRegistry(client).listProviders();
2130
- };
2131
-
2132
- //#endregion
2133
- //#region src/modules/waas/constants.ts
2134
- const DEFAULT_WAAS_BASE_API_URL = "https://app.dynamicauth.com";
2135
- const DEFAULT_WAAS_BASE_MPC_RELAY_API_URL = "https://relay.dynamicauth.com";
2136
- const DYNAMIC_WAAS_METADATA = {
2137
- displayName: "Dynamic WaaS",
2138
- icon: `${DYNAMIC_ICONIC_SPRITE_URL}#dynamicwaas`,
2139
- normalizedWalletName: "dynamicwaas"
2167
+ const createApiClient = (options = {}, client) => {
2168
+ return createBaseApiClient({
2169
+ middleware: [createDeviceSignatureHeadersMiddleware(client), createRbacStaleMiddleware(client)],
2170
+ options
2171
+ }, client);
2140
2172
  };
2141
2173
 
2142
2174
  //#endregion
2143
- //#region src/modules/waas/isWaasWalletProvider/isWaasWalletProvider.ts
2144
- /** @notInstrumented */
2145
- const isWaasWalletProvider = (walletProvider) => {
2146
- return walletProvider.key.includes(DYNAMIC_WAAS_METADATA.normalizedWalletName);
2175
+ //#region src/errors/NoWalletProviderFoundError.ts
2176
+ var NoWalletProviderFoundError = class extends BaseError {
2177
+ constructor({ walletProviderKey }) {
2178
+ super({
2179
+ cause: null,
2180
+ code: "no_wallet_provider_found_error",
2181
+ docsUrl: null,
2182
+ name: "NoWalletProviderFoundError",
2183
+ shortMessage: `No wallet provider found with key: ${walletProviderKey}`
2184
+ });
2185
+ }
2147
2186
  };
2148
2187
 
2149
2188
  //#endregion
2150
- //#region src/modules/waas/findWaasWalletProviderByChain/findWaasWalletProviderByChain.ts
2189
+ //#region src/modules/wallets/utils/getWalletProviderFromWalletAccount/getWalletProviderFromWalletAccount.ts
2151
2190
  /** @notInstrumented */
2152
- const findWaasWalletProviderByChain = ({ chain }, client) => {
2153
- const providers = getWalletProviders(client);
2154
- const waasProviderKey = formatWalletProviderKey({
2155
- chain,
2156
- displayName: DYNAMIC_WAAS_METADATA.displayName,
2157
- walletProviderType: _dynamic_labs_sdk_api_core.WalletProviderEnum.EmbeddedWallet
2158
- });
2159
- const waasProvider = providers.find((provider) => provider.key === waasProviderKey && provider.chain === chain);
2160
- if (!waasProvider || !isWaasWalletProvider(waasProvider)) return null;
2161
- return waasProvider;
2162
- };
2163
-
2164
- //#endregion
2165
- //#region src/modules/waas/isWaasWalletAccount/isWaasWalletAccount.ts
2166
- /**
2167
- * This function determines whether the provided wallet account is a Dynamic
2168
- * WaaS wallet account.
2169
- *
2170
- * @param params.walletAccount - The wallet account to check.
2171
- * @returns True if the wallet account is a WaaS wallet account, false otherwise.
2172
- * @notInstrumented
2173
- */
2174
- const isWaasWalletAccount = ({ walletAccount }) => {
2175
- return walletAccount.walletProviderKey.includes(DYNAMIC_WAAS_METADATA.normalizedWalletName);
2191
+ const getWalletProviderFromWalletAccount = ({ walletAccount }, client) => {
2192
+ const walletProvider = getWalletProviderRegistry(client).getByKey(walletAccount.walletProviderKey);
2193
+ if (!walletProvider) throw new NoWalletProviderFoundError({ walletProviderKey: walletAccount.walletProviderKey });
2194
+ return walletProvider;
2176
2195
  };
2177
2196
 
2178
2197
  //#endregion
2179
- //#region src/modules/waas/initializeWaasClientsForEagerRecovery/initializeWaasClientsForEagerRecovery.ts
2198
+ //#region src/utils/retryOnFail/InvalidRetryOnFailCallError.ts
2180
2199
  /**
2181
- * On login, boots the WaaS client once per chain so the SDK eagerly recovers
2182
- * key shares itself (the `eagerlyRecoverKeyShares` capability) instead of the
2183
- * host looping per wallet. Booting calls `initialize()`, which sends the auth
2184
- * token the iframe needs to self-recover.
2185
- *
2186
- * @notInstrumented
2200
+ * This error is thrown when the `retryOnFail` function is called with an invalid
2201
+ * number of retries (i.e. less than 0).
2187
2202
  */
2188
- const initializeWaasClientsForEagerRecovery = async (client) => {
2189
- /**
2190
- * Booting triggers recovery, which fails if the user is missing the MFA auth.
2191
- * This early return avoids attempting a call we know will fail and just adds
2192
- * noise to the logs.
2193
- */
2194
- if (isUserMissingMfaAuth(client)) return;
2195
- const waasChains = new Set(getWalletAccounts(client).filter((walletAccount) => isWaasWalletAccount({ walletAccount })).map((walletAccount) => walletAccount.chain));
2196
- await Promise.all([...waasChains].map(async (chain) => {
2197
- const provider = findWaasWalletProviderByChain({ chain }, client);
2198
- /**
2199
- * The environment might not have the embedded wallet extensions installed.
2200
- * In that case there is no provider for the chain and nothing to boot.
2201
- */
2202
- if (!provider) return;
2203
- try {
2204
- await provider.getWaasClient();
2205
- } catch (error) {
2206
- getCore(client).logger.warn("[initializeWaasClientsForEagerRecovery] failed to boot waas client", error);
2207
- }
2208
- }));
2209
- };
2210
-
2211
- //#endregion
2212
- //#region src/errors/InvalidParamError.ts
2213
- var InvalidParamError = class extends BaseError {
2214
- constructor(message) {
2203
+ var InvalidRetryOnFailCallError = class extends BaseError {
2204
+ constructor(maxRetries) {
2215
2205
  super({
2216
2206
  cause: null,
2217
- code: "invalid_param_error",
2207
+ code: "invalid_retry_on_fail_call_error",
2218
2208
  docsUrl: null,
2219
- name: "InvalidParamError",
2220
- shortMessage: message
2209
+ name: "InvalidRetryOnFailCallError",
2210
+ shortMessage: `Invalid retries parameter for retryOnFail call: ${maxRetries}`
2221
2211
  });
2222
2212
  }
2223
2213
  };
2224
2214
 
2225
2215
  //#endregion
2226
- //#region src/modules/auth/decodeJwt/decodeJwt.ts
2216
+ //#region src/utils/retryOnFail/retryOnFail.ts
2217
+ /** @notInstrumented */
2218
+ const retryOnFail = async ({ delay = 0, fn, maxRetries }) => {
2219
+ for (let retry = 0; retry <= maxRetries; retry++) try {
2220
+ return await fn();
2221
+ } catch (error) {
2222
+ if (retry >= maxRetries) throw error;
2223
+ if (delay > 0) await new Promise((resolve) => setTimeout(resolve, delay));
2224
+ }
2225
+ /**
2226
+ * Reaching this point should never happen and this
2227
+ * error is thrown to help us debug the issue.
2228
+ */
2229
+ throw new InvalidRetryOnFailCallError(maxRetries);
2230
+ };
2231
+
2232
+ //#endregion
2233
+ //#region src/modules/auth/isSignedIn/isSignedIn.ts
2227
2234
  /**
2228
- * Decodes a JWT token and returns the full payload.
2235
+ * Checks if the user is currently signed in to the Dynamic client.
2229
2236
  *
2230
- * This function extracts and returns the complete JWT payload including scopes,
2231
- * expiration time, and other claims.
2237
+ * The client is considered to be in a signed in state if a user has
2238
+ * authenticated or if the client has at least one wallet connected.
2232
2239
  *
2233
- * @param jwt - The JWT token string.
2234
- * @returns The decoded JWT payload object.
2235
- * @throws InvalidParamError if the token is invalid or cannot be decoded.
2240
+ * @deprecated What counts as "signed in" is your app's business logic, not the
2241
+ * SDK's. This helper bakes in one opinion (a user OR any connected wallet),
2242
+ * which rarely matches every app and forces a dependency on us for every
2243
+ * variation. Compose your own check from the underlying primitives instead —
2244
+ * e.g. `Boolean(client.user) || isAnyWalletAccountConnected(client)` — and
2245
+ * layer in whatever your app requires (device registration, completed
2246
+ * onboarding, satisfied MFA, a required embedded wallet, …). See the
2247
+ * "Check if signed in" guide:
2248
+ * https://www.dynamic.xyz/docs/javascript/user-session-management
2236
2249
  *
2237
2250
  * @example
2238
- * ```typescript
2239
- * const payload = decodeJwt(jwt);
2240
- * // Returns: { scopes: ['wallet:export'], exp: 1234567890, ... }
2251
+ * ```ts
2252
+ * if (isSignedIn()) {
2253
+ * console.log('User is authenticated or has a wallet connected');
2254
+ * }
2241
2255
  * ```
2242
- * @notInstrumented
2243
- */
2244
- const decodeJwt = (jwt) => {
2245
- try {
2246
- const parts = jwt.split(".");
2247
- if (parts.length !== 3) throw new InvalidParamError("Invalid JWT format");
2248
- const base64Payload = parts[1].replaceAll("-", "+").replaceAll("_", "/");
2249
- const paddedPayload = base64Payload + "=".repeat((4 - base64Payload.length % 4) % 4);
2250
- const decodedPayload = atob(paddedPayload);
2251
- return JSON.parse(decodedPayload);
2252
- } catch (error) {
2253
- if (error instanceof InvalidParamError) throw error;
2254
- throw new InvalidParamError(`Failed to decode JWT: ${error instanceof Error ? error.message : String(error)}`);
2255
- }
2256
- };
2256
+ *
2257
+ * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.
2258
+ * @returns True if the user is signed in, false otherwise.
2259
+ * @see logout
2260
+ * @see isAnyWalletAccountConnected
2261
+ * @notInstrumented
2262
+ */
2263
+ const isSignedIn = (client = getDefaultClient()) => Boolean(client.user || getWalletAccounts(client).length > 0);
2257
2264
 
2258
2265
  //#endregion
2259
- //#region src/modules/auth/updateAuthFromVerifyResponse/elevatedAccessTokens/normalizeScopes/normalizeScopes.ts
2266
+ //#region src/modules/projectSettings/fetchProjectSettings/projectSettingsExpirationScheme.ts
2260
2267
  /**
2261
- * Normalizes scopes by deduplicating and sorting them.
2262
- * This creates a canonical representation for comparison.
2263
- *
2264
- * @param scopes - Array of scope strings (may contain duplicates)
2265
- * @returns Normalized, sorted array of unique scopes
2266
- * @notInstrumented
2268
+ * The schema to track the expiration time of the project settings.
2267
2269
  */
2268
- const normalizeScopes = (scopes) => {
2269
- return [...new Set(scopes)].sort((a, b) => a.localeCompare(b));
2270
- };
2270
+ const projectSettingsExpirationStorageKeySchema = createStorageKeySchema({
2271
+ key: "projectSettingsExpiration",
2272
+ schema: zod_mini.number()
2273
+ });
2271
2274
 
2272
2275
  //#endregion
2273
- //#region src/modules/auth/updateAuthFromVerifyResponse/elevatedAccessTokens/parseElevatedAccessToken/parseElevatedAccessToken.ts
2276
+ //#region src/modules/projectSettings/fetchProjectSettings/fetchProjectSettings.ts
2274
2277
  /**
2275
- * Validates and parses an elevated access token from a JWT string.
2276
- * Extracts scopes, expiration, and validates the token structure.
2278
+ * Expiration time of the project settings in milliseconds.
2279
+ */
2280
+ const PROJECT_SETTINGS_EXPIRATION_TIME = 1e3 * 60 * 5;
2281
+ /**
2282
+ * Fetches and updates the project settings from the API.
2277
2283
  *
2278
- * Policy decisions:
2279
- * - Tokens without scopes are rejected (returns null)
2280
- * - Tokens with empty scopes array are rejected (returns null)
2281
- * - Tokens without exp field are rejected (returns null)
2282
- * - Expired tokens are rejected (returns null)
2284
+ * This function retrieves the latest project configuration settings
2285
+ * from Dynamic's servers, including authentication options, enabled chains,
2286
+ * and security configurations. The settings are cached for performance.
2283
2287
  *
2284
- * @returns Parsed token data or null if token is invalid/expired
2288
+ * @example
2289
+ * ```ts
2290
+ * const settings = await fetchProjectSettings();
2291
+ * console.log('Enabled chains:', settings.chains);
2292
+ * ```
2293
+ *
2294
+ * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.
2295
+ * @returns A promise that resolves to the updated project settings.
2296
+ * @see createDynamicClient
2297
+ * @see initializeClient
2285
2298
  * @notInstrumented
2299
+ * @noHook Internal settings fetch that is not part of the public hook surface.
2286
2300
  */
2287
- const parseElevatedAccessToken = ({ token }) => {
2288
- const payload = decodeJwt(token);
2289
- const filteredScopes = ((payload?.scope)?.split(" ") ?? []).filter((s) => s.length > 0);
2290
- const singleUse = payload.singleUse ?? false;
2291
- if (!filteredScopes || filteredScopes.length === 0) return null;
2292
- if (!payload.exp) return null;
2293
- const expiresAt = /* @__PURE__ */ new Date(payload.exp * 1e3);
2294
- if (expiresAt <= /* @__PURE__ */ new Date()) return null;
2295
- return {
2296
- expiresAt,
2297
- normalizedScopes: normalizeScopes(filteredScopes),
2298
- scopes: filteredScopes,
2299
- singleUse,
2300
- token
2301
+ const fetchProjectSettings = async (client = getDefaultClient()) => {
2302
+ const core = getCore(client);
2303
+ const currentExpiration = await core.storage.getItem(projectSettingsExpirationStorageKeySchema);
2304
+ if (Boolean(client.projectSettings) && !(currentExpiration && currentExpiration < Date.now()) && isSignedIn(client)) return client.projectSettings;
2305
+ const apiClient = createApiClient({}, client);
2306
+ core.logger.debug("[fetchProjectSettings] Fetching project settings...");
2307
+ const doFetch = async () => apiClient.getEnvironmentSettings({
2308
+ environmentId: core.environmentId,
2309
+ sdkVersion: `${CLIENT_SDK_NAME}/${core.version}`
2310
+ }, { credentials: "omit" });
2311
+ const projectSettings = await retryOnFail({
2312
+ fn: doFetch,
2313
+ maxRetries: 2
2314
+ });
2315
+ core.state.set({ projectSettings: projectSettings ?? null });
2316
+ await core.storage.setItem(projectSettingsExpirationStorageKeySchema, Date.now() + PROJECT_SETTINGS_EXPIRATION_TIME);
2317
+ return projectSettings;
2318
+ };
2319
+
2320
+ //#endregion
2321
+ //#region src/modules/sessionKeys/generateSessionKeys/generateSessionKeys.ts
2322
+ /** @notInstrumented */
2323
+ const generateSessionKeys = async (client) => {
2324
+ const core = getCore(client);
2325
+ const currentState = core.state.get();
2326
+ const isRotation = Boolean(currentState.sessionKeys);
2327
+ const logContext = {
2328
+ environmentId: core.environmentId,
2329
+ operation: isRotation ? "rotate" : "create",
2330
+ userId: currentState.user?.id ?? null
2301
2331
  };
2332
+ core.logger.info(isRotation ? "[generateSessionKeys] Rotating session key..." : "[generateSessionKeys] Creating session key...", logContext);
2333
+ await core.keychain.removeKey("session");
2334
+ const publicKey = await core.keychain.generateKey("session");
2335
+ assertDefined(publicKey, "Public key not found");
2336
+ core.state.set({ sessionKeys: publicKey });
2337
+ core.logger.info(isRotation ? "[generateSessionKeys] Session key rotated" : "[generateSessionKeys] Session key created", logContext);
2338
+ return { publicKey };
2302
2339
  };
2303
2340
 
2304
2341
  //#endregion
2305
- //#region src/modules/auth/updateAuthFromVerifyResponse/elevatedAccessTokens/upsertElevatedAccessToken/upsertElevatedAccessToken.ts
2342
+ //#region src/modules/wallets/utils/getAvailableWalletProvidersFromWalletAccounts/getAvailableWalletProvidersFromWalletAccounts.ts
2343
+ /** @notInstrumented */
2344
+ const getAvailableWalletProvidersFromWalletAccounts = (client) => {
2345
+ const core = getCore(client);
2346
+ const walletProvidersMap = /* @__PURE__ */ new Map();
2347
+ getWalletAccounts(client).forEach((walletAccount) => {
2348
+ if (walletProvidersMap.has(walletAccount.walletProviderKey)) return;
2349
+ try {
2350
+ const walletProvider = getWalletProviderFromWalletAccount({ walletAccount }, client);
2351
+ walletProvidersMap.set(walletAccount.walletProviderKey, walletProvider);
2352
+ } catch (error) {
2353
+ core.logger.debug("Wallet provider not found for wallet account", {
2354
+ error,
2355
+ walletAccount: walletAccount.address
2356
+ });
2357
+ }
2358
+ });
2359
+ return Array.from(walletProvidersMap.values());
2360
+ };
2361
+
2362
+ //#endregion
2363
+ //#region src/modules/wallets/destroyWalletProviders/destroyWalletProviders.ts
2306
2364
  /**
2307
- * Upserts an elevated access token into the current tokens array.
2365
+ * Tear down every wallet provider on the client.
2308
2366
  *
2309
- * Policy: Only one token per normalized scope-set is allowed.
2310
- * If a token with the same normalized scopes exists, it is replaced.
2311
- * This ensures we don't accumulate multiple tokens for the same scope combination.
2367
+ * Each provider's `destroy` is responsible for its own local + remote
2368
+ * cleanup. We swallow errors so a failing destroy on one provider does not
2369
+ * block teardown of the others (e.g. during logout).
2312
2370
  *
2313
- * @param currentTokens - Current array of elevated access tokens
2314
- * @param newToken - New token to upsert
2315
- * @returns Updated array of tokens with the new token upserted
2316
2371
  * @notInstrumented
2317
2372
  */
2318
- const upsertElevatedAccessToken = ({ currentTokens, newToken }) => {
2319
- const newScopeKey = normalizeScopes(newToken.scopes).join(" ");
2320
- return [...currentTokens.filter((existingToken) => {
2321
- return normalizeScopes(existingToken.scopes).join(" ") !== newScopeKey;
2322
- }), {
2323
- expiresAt: newToken.expiresAt,
2324
- scopes: newToken.scopes,
2325
- singleUse: newToken.singleUse,
2326
- token: newToken.token
2327
- }];
2373
+ const destroyWalletProviders = async ({ reason }, client) => {
2374
+ const core = getCore(client);
2375
+ const walletProviders = getAvailableWalletProvidersFromWalletAccounts(client);
2376
+ await Promise.all(walletProviders.map(async (walletProvider) => {
2377
+ if (!walletProvider.destroy) return;
2378
+ try {
2379
+ await walletProvider.destroy({ reason });
2380
+ } catch (err) {
2381
+ core.logger.error(`Error destroying wallet provider ${walletProvider.key}`, err);
2382
+ }
2383
+ }));
2328
2384
  };
2329
2385
 
2330
2386
  //#endregion
2331
- //#region src/modules/auth/updateAuthFromVerifyResponse/updateAuthFromVerifyResponse.ts
2332
- /** @notInstrumented */
2333
- const updateAuthFromVerifyResponse = ({ response }, client) => {
2387
+ //#region src/modules/auth/logoutWithReason/logoutWithReason.ts
2388
+ /**
2389
+ * Logs the user out with an explicit reason.
2390
+ *
2391
+ * Revokes the session, clears auth state, terminates wallet providers, and
2392
+ * emits the `logout` client event with the given reason. The reason is also
2393
+ * captured as an argument on the function-instrumentation event, which is
2394
+ * how Datadog distinguishes between different logout causes.
2395
+ *
2396
+ * Use this instead of the public `logout` when triggering a logout from
2397
+ * internal or extension code — the caller owns the reason string, so the
2398
+ * telemetry correctly attributes *why* the logout happened.
2399
+ *
2400
+ * @param params - The logout params.
2401
+ * @param params.reason - Why the logout is being triggered. Extension authors
2402
+ * needing a reason outside the SDK catalog can cast with `as LogoutReason`.
2403
+ * @param client - The Dynamic client instance.
2404
+ * @instrumented
2405
+ */
2406
+ const logoutWithReason = async ({ reason }, client) => {
2334
2407
  const core = getCore(client);
2335
- const previousState = { ...core.state.get() };
2336
- const { user, minifiedJwt, jwt, expiresAt, mfaToken, elevatedAccessToken } = response;
2337
- const sessionExpiresAt = /* @__PURE__ */ new Date(expiresAt * 1e3);
2338
- const newState = {
2339
- legacyToken: jwt ?? null,
2340
- sessionExpiresAt,
2341
- token: minifiedJwt ?? null,
2342
- user
2343
- };
2344
- if (mfaToken) newState.mfaToken = mfaToken;
2345
- const currentTokens = core.state.get().elevatedAccessTokens || [];
2346
- newState.elevatedAccessTokens = currentTokens;
2347
- if (elevatedAccessToken) {
2348
- const parsedToken = parseElevatedAccessToken({ token: elevatedAccessToken });
2349
- if (parsedToken) newState.elevatedAccessTokens = upsertElevatedAccessToken({
2350
- currentTokens,
2351
- newToken: parsedToken
2352
- });
2408
+ core.logger.debug("[logoutWithReason] Logging out...", { reason });
2409
+ await destroyWalletProviders({ reason }, client);
2410
+ if (client.user !== null) {
2411
+ const apiClient = createApiClient({ headers: { [DYNAMIC_LOGOUT_REASON_HEADER]: reason } }, client);
2412
+ try {
2413
+ await apiClient.revokeSession({ environmentId: core.environmentId });
2414
+ } catch (error) {
2415
+ core.logger.error("Failed to revoke session", error);
2416
+ }
2417
+ /**
2418
+ * This deletes the auth cookie if it exists.
2419
+ * If the cookie doesn't exist, this sets a new cookie that expires immediately.
2420
+ */
2421
+ if (isCookieEnabled(client)) setCookie(`${DYNAMIC_AUTH_COOKIE_NAME}=; Max-Age=-99999999; path=/; SameSite=Lax${getSecureCookieAttribute()}`);
2353
2422
  }
2354
- core.state.set(newState);
2355
- /**
2356
- * For customers using a sandbox environment with cookies enabled, we need to set the cookie
2357
- * programmatically because Redcoast won't set the cookie via headers. We set the cookie programmatically
2358
- * so customers can access the cookie from document.cookie consistently between sandbox and live environments.
2359
- */
2360
- if (minifiedJwt && isCookieEnabled(client)) setCookie(`${DYNAMIC_AUTH_COOKIE_NAME}=${minifiedJwt}; expires=${sessionExpiresAt.toUTCString()}; path=/; SameSite=Lax${getSecureCookieAttribute()}`);
2423
+ await core.keychain.removeKey("session");
2424
+ const previousState = core.state.get();
2425
+ core.state.set({
2426
+ captchaToken: null,
2427
+ elevatedAccessTokens: [],
2428
+ legacyToken: null,
2429
+ mfaToken: null,
2430
+ sessionExpiresAt: null,
2431
+ sessionKeys: null,
2432
+ token: null,
2433
+ unverifiedWalletAccounts: [],
2434
+ user: null
2435
+ });
2436
+ emitEvent({
2437
+ args: { reason },
2438
+ event: "logout"
2439
+ }, client);
2361
2440
  checkAndRaiseWalletAccountsChangedEvent({ previousState }, client);
2362
- if (!previousState.user && Boolean(newState.user)) initializeWaasClientsForEagerRecovery(client);
2441
+ fetchProjectSettings(client);
2442
+ generateSessionKeys(client);
2363
2443
  };
2444
+ const __logoutWithReason_impl = logoutWithReason;
2445
+ const __logoutWithReason_wrapped = instrumentFunction({
2446
+ fn: __logoutWithReason_impl,
2447
+ functionName: "logoutWithReason",
2448
+ getCore: () => {
2449
+ try {
2450
+ return getCore(getDefaultClient());
2451
+ } catch {
2452
+ return;
2453
+ }
2454
+ }
2455
+ });
2364
2456
 
2365
2457
  //#endregion
2366
2458
  Object.defineProperty(exports, 'APIError', {
@@ -2483,6 +2575,12 @@ Object.defineProperty(exports, 'SandboxMaximumThresholdReachedError', {
2483
2575
  return SandboxMaximumThresholdReachedError;
2484
2576
  }
2485
2577
  });
2578
+ Object.defineProperty(exports, 'TokenScope', {
2579
+ enumerable: true,
2580
+ get: function () {
2581
+ return TokenScope;
2582
+ }
2583
+ });
2486
2584
  Object.defineProperty(exports, 'UnauthorizedError', {
2487
2585
  enumerable: true,
2488
2586
  get: function () {
@@ -2507,6 +2605,12 @@ Object.defineProperty(exports, '__logoutWithReason_wrapped', {
2507
2605
  return __logoutWithReason_wrapped;
2508
2606
  }
2509
2607
  });
2608
+ Object.defineProperty(exports, '__refreshAuth_wrapped', {
2609
+ enumerable: true,
2610
+ get: function () {
2611
+ return __refreshAuth_wrapped;
2612
+ }
2613
+ });
2510
2614
  Object.defineProperty(exports, '__toESM', {
2511
2615
  enumerable: true,
2512
2616
  get: function () {
@@ -2837,4 +2941,4 @@ Object.defineProperty(exports, 'version', {
2837
2941
  return version;
2838
2942
  }
2839
2943
  });
2840
- //# sourceMappingURL=updateAuthFromVerifyResponse-Dsw-eAro.cjs.map
2944
+ //# sourceMappingURL=logoutWithReason-DlA15deT.cjs.map