wallaby-cash 3.1.0 → 3.2.1

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.
package/dist/index.js CHANGED
@@ -82,6 +82,7 @@ var TransportEnum;
82
82
  */
83
83
  class WallabyError extends Error {
84
84
  constructor(errorPayload) {
85
+ var _a;
85
86
  const { message, statusCode, errorCode, data, cause, onError } = errorPayload;
86
87
  super(message);
87
88
  this.name = 'WallabyError';
@@ -90,7 +91,17 @@ class WallabyError extends Error {
90
91
  this.cause = cause;
91
92
  this.onError = onError;
92
93
  this.data = data;
93
- Error.captureStackTrace(this, WallabyError);
94
+ /**
95
+ * Preserve prototype chain when extending built-ins across transpilation targets.
96
+ * Object.setPrototypeOf(this, WallabyError.prototype) forces the prototype to WallabyError even when a consumer subclasses WallabyError,
97
+ * breaking the prototype chain for derived errors (and potentially instanceof DerivedWallabyError).
98
+ * Use new.target.prototype (and new.target for stack capture) so the fix works for subclasses too.
99
+ *
100
+ * Use optional chaining since Error.captureStackTrace isn't available in all runtimes (e.g., Safari).
101
+ */
102
+ Object.setPrototypeOf(this, new.target.prototype);
103
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
104
+ (_a = Error.captureStackTrace) === null || _a === void 0 ? void 0 : _a.call(Error, this, new.target);
94
105
  }
95
106
  static isWallabyError(error) {
96
107
  return error instanceof WallabyError;
@@ -321,6 +332,12 @@ var ErrorResponseCodes;
321
332
  ErrorResponseCodes["auth_api_jwt_invalid"] = "auth_api_jwt_invalid";
322
333
  ErrorResponseCodes["auth_api_jwt_not_active"] = "auth_api_jwt_not_active";
323
334
  ErrorResponseCodes["auth_api_jwt_not_provided"] = "auth_api_jwt_not_provided";
335
+ ErrorResponseCodes["auth_api_jwt_expired"] = "auth_api_jwt_expired";
336
+ ErrorResponseCodes["auth_api_unauthorized"] = "auth_api_unauthorized";
337
+ // Auth Refresh Token
338
+ ErrorResponseCodes["auth_refresh_token_not_found"] = "auth_refresh_token_not_found";
339
+ ErrorResponseCodes["auth_refresh_token_expired"] = "auth_refresh_token_expired";
340
+ ErrorResponseCodes["auth_refresh_token_reuse_detected"] = "auth_refresh_token_reuse_detected";
324
341
  // Auth Client JWT
325
342
  ErrorResponseCodes["auth_client_jwt_invalid"] = "auth_client_jwt_invalid";
326
343
  ErrorResponseCodes["auth_client_jwt_missing_external_id_payload"] = "auth_client_jwt_missing_external_id_payload";
@@ -328,6 +345,8 @@ var ErrorResponseCodes;
328
345
  ErrorResponseCodes["auth_client_jwt_external_id_not_match"] = "auth_client_jwt_external_id_not_match";
329
346
  ErrorResponseCodes["auth_client_jwt_expired"] = "auth_client_jwt_expired";
330
347
  ErrorResponseCodes["auth_client_jwt_not_provided"] = "auth_client_jwt_not_provided";
348
+ ErrorResponseCodes["auth_client_jwt_invalid_auth_type"] = "auth_client_jwt_invalid_auth_type";
349
+ ErrorResponseCodes["auth_client_jwt_invalid_passkey"] = "auth_client_jwt_invalid_passkey";
331
350
  // Auth Client Transport keys
332
351
  ErrorResponseCodes["auth_client_pub_key_and_message_not_match"] = "auth_client_pub_key_and_message_not_match";
333
352
  ErrorResponseCodes["auth_client_pub_key_and_message_expired"] = "auth_client_pub_key_and_message_expired";
@@ -361,6 +380,7 @@ var ErrorResponseCodes;
361
380
  ErrorResponseCodes["sdk_seed_phrase_not_found"] = "sdk_seed_phrase_not_found";
362
381
  ErrorResponseCodes["sdk_private_key_decryption_failed"] = "sdk_private_key_decryption_failed";
363
382
  ErrorResponseCodes["sdk_private_key_not_found"] = "sdk_private_key_not_found";
383
+ ErrorResponseCodes["sdk_refresh_token_missing"] = "sdk_refresh_token_missing";
364
384
  ErrorResponseCodes["sdk_missing_parameter"] = "sdk_missing_parameter";
365
385
  ErrorResponseCodes["sdk_invalid_parameter"] = "sdk_invalid_parameter";
366
386
  ErrorResponseCodes["sdk_wrong_password"] = "sdk_wrong_password";
@@ -574,7 +594,7 @@ const env = {
574
594
  isNative: false,
575
595
  isWeb,
576
596
  };
577
- const currentPackageVersion = "3.1.0" ;
597
+ const currentPackageVersion = "3.2.1" ;
578
598
 
579
599
  /**
580
600
  * Storage keys adapter for Storage interface across different platforms.
@@ -5191,6 +5211,19 @@ function userIsMfaVerified(jwt) {
5191
5211
  const jwtDecoded = jwtDecode(jwt);
5192
5212
  return jwtDecoded.mfaVerified;
5193
5213
  }
5214
+ /**
5215
+ * Checks if a given JWT will expire within the given threshold.
5216
+ *
5217
+ * @param jwt - The JWT string to check. If null, the function returns false.
5218
+ * @param thresholdSeconds - Number of seconds before expiry to consider "near expiry".
5219
+ * @returns `true` if the JWT expires within `thresholdSeconds` seconds, otherwise `false`.
5220
+ */
5221
+ function isJwtNearExpiry(jwt, thresholdSeconds) {
5222
+ if (!jwt) {
5223
+ return false;
5224
+ }
5225
+ return millisecondsToJWTTimeout(jwt) <= thresholdSeconds * 1000;
5226
+ }
5194
5227
  /**
5195
5228
  * Calculates the remaining time in milliseconds until a given JWT expires.
5196
5229
  *
@@ -5205,6 +5238,49 @@ function millisecondsToJWTTimeout(jwt) {
5205
5238
  return jwtExpirationTimeMilliseconds - timeNowMilliseconds;
5206
5239
  }
5207
5240
 
5241
+ const AuthRoutes = {
5242
+ signatureMessage: {
5243
+ fullPath: '/auth/signature-message',
5244
+ method: RequestMethod.Post,
5245
+ requiresAccessToken: false,
5246
+ },
5247
+ signIn: {
5248
+ fullPath: '/auth/sign-in',
5249
+ method: RequestMethod.Post,
5250
+ requiresAccessToken: false,
5251
+ },
5252
+ signUp: {
5253
+ fullPath: '/auth/sign-up',
5254
+ method: RequestMethod.Post,
5255
+ requiresAccessToken: false,
5256
+ },
5257
+ refreshAccessToken: {
5258
+ fullPath: '/auth/refresh-access-token',
5259
+ method: RequestMethod.Post,
5260
+ requiresAccessToken: true,
5261
+ },
5262
+ clientAuthPubKey: {
5263
+ fullPath: 'auth/client-auth-pubkey',
5264
+ method: RequestMethod.Put,
5265
+ requiresAccessToken: true,
5266
+ },
5267
+ wallabyAuthPublicKey: {
5268
+ fullPath: '/auth/wallaby-auth-pubkey',
5269
+ method: RequestMethod.Get,
5270
+ requiresAccessToken: true,
5271
+ },
5272
+ getUserSalt: {
5273
+ fullPath: '/users/salt',
5274
+ method: RequestMethod.Get,
5275
+ requiresAccessToken: true,
5276
+ },
5277
+ getPasskeyCredentials: {
5278
+ fullPath: '/auth/passkey-credentials',
5279
+ method: RequestMethod.Get,
5280
+ requiresAccessToken: true,
5281
+ },
5282
+ };
5283
+
5208
5284
  class LockManagerService {
5209
5285
  constructor() {
5210
5286
  this.activeLocks = new Set();
@@ -5248,6 +5324,43 @@ class LockManagerService {
5248
5324
  }
5249
5325
  }
5250
5326
 
5327
+ class DedupeManagerService {
5328
+ constructor() {
5329
+ this.inFlightOperations = new Map();
5330
+ }
5331
+ /**
5332
+ * Executes an operation once per key while returning the same in-flight promise
5333
+ * to all concurrent callers.
5334
+ * @param key - Unique identifier for dedupe scope.
5335
+ * @param operation - The async operation to execute.
5336
+ */
5337
+ withDedupe(key, operation) {
5338
+ const existingOperation = this.inFlightOperations.get(key);
5339
+ if (existingOperation) {
5340
+ return existingOperation;
5341
+ }
5342
+ const operationPromise = Promise.resolve()
5343
+ .then(operation)
5344
+ .finally(() => {
5345
+ this.inFlightOperations.delete(key);
5346
+ });
5347
+ this.inFlightOperations.set(key, operationPromise);
5348
+ return operationPromise;
5349
+ }
5350
+ /**
5351
+ * Check if a specific operation is currently in flight.
5352
+ */
5353
+ isInFlight(key) {
5354
+ return this.inFlightOperations.has(key);
5355
+ }
5356
+ /**
5357
+ * Clear all tracked in-flight operations (primarily for tests/cleanup).
5358
+ */
5359
+ clearAll() {
5360
+ this.inFlightOperations.clear();
5361
+ }
5362
+ }
5363
+
5251
5364
  function isValidInput(input) {
5252
5365
  // Allow alphanumeric characters, hyphens, and underscores.
5253
5366
  const regex = /^[a-zA-Z0-9-_]+$/;
@@ -6686,6 +6799,48 @@ function objectToQueryParams(obj) {
6686
6799
  return params.toString();
6687
6800
  }
6688
6801
 
6802
+ const refreshableAuth401ErrorCodes = new Set([
6803
+ ErrorResponseCodes.auth_api_jwt_invalid,
6804
+ ErrorResponseCodes.auth_api_jwt_not_active,
6805
+ ErrorResponseCodes.auth_api_jwt_not_provided,
6806
+ ErrorResponseCodes.auth_api_jwt_expired,
6807
+ ErrorResponseCodes.auth_api_unauthorized,
6808
+ ]);
6809
+ const clearTokensOnRefreshFailureErrorCodes = new Set([
6810
+ ErrorResponseCodes.auth_refresh_token_not_found,
6811
+ ErrorResponseCodes.auth_refresh_token_expired,
6812
+ ErrorResponseCodes.auth_refresh_token_reuse_detected,
6813
+ ]);
6814
+ function extractErrorStatus(error) {
6815
+ var _a, _b, _c, _d, _e;
6816
+ return (_d = (_b = (_a = error === null || error === void 0 ? void 0 : error.status) !== null && _a !== void 0 ? _a : error === null || error === void 0 ? void 0 : error.statusCode) !== null && _b !== void 0 ? _b : (_c = error === null || error === void 0 ? void 0 : error.error) === null || _c === void 0 ? void 0 : _c.statusCode) !== null && _d !== void 0 ? _d : (_e = error === null || error === void 0 ? void 0 : error.data) === null || _e === void 0 ? void 0 : _e.statusCode;
6817
+ }
6818
+ function extractErrorCode(error) {
6819
+ var _a, _b, _c, _d;
6820
+ return (_c = (_a = error === null || error === void 0 ? void 0 : error.errorCode) !== null && _a !== void 0 ? _a : (_b = error === null || error === void 0 ? void 0 : error.error) === null || _b === void 0 ? void 0 : _b.errorCode) !== null && _c !== void 0 ? _c : (_d = error === null || error === void 0 ? void 0 : error.data) === null || _d === void 0 ? void 0 : _d.errorCode;
6821
+ }
6822
+ function shouldAttemptTokenRefresh(error) {
6823
+ const status = extractErrorStatus(error);
6824
+ if (status !== 401) {
6825
+ return false;
6826
+ }
6827
+ const errorCode = extractErrorCode(error);
6828
+ if (!errorCode) {
6829
+ // Backward compatibility: some endpoints may not provide explicit errorCode.
6830
+ return true;
6831
+ }
6832
+ return refreshableAuth401ErrorCodes.has(errorCode);
6833
+ }
6834
+ function shouldClearTokensAfterRefreshFailure(error) {
6835
+ const status = extractErrorStatus(error);
6836
+ const errorCode = extractErrorCode(error);
6837
+ // Any 401 clears tokens (preserves prior behavior). The error-code set additionally
6838
+ // covers refresh-token failures that arrive with a non-401 status (e.g. 400/403).
6839
+ return status === 401 || (!!errorCode && clearTokensOnRefreshFailureErrorCodes.has(errorCode));
6840
+ }
6841
+
6842
+ // Module-level dedupe manager for token refresh to ensure only one refresh request per user/environment/network at a time
6843
+ const refreshDedupeManager = new DedupeManagerService();
6689
6844
  class Base {
6690
6845
  constructor(config) {
6691
6846
  var _a, _b;
@@ -6716,35 +6871,45 @@ class Base {
6716
6871
  });
6717
6872
  /**
6718
6873
  * This intercepts all API responses and transforms errors into WallabyError format.
6874
+ * On a 401, it performs a single token refresh then retries (reactive guard).
6719
6875
  */
6720
6876
  const originalRequest = httpClient.request.bind(httpClient);
6721
6877
  httpClient.request = async (params) => {
6722
- try {
6723
- return await originalRequest(params);
6724
- }
6725
- catch (error) {
6726
- // Transform the generated API error format into WallabyError
6727
- if (error === null || error === void 0 ? void 0 : error.error) {
6728
- const apiError = error.error;
6878
+ const attemptRequest = async (retried) => {
6879
+ try {
6880
+ return await originalRequest(params);
6881
+ }
6882
+ catch (error) {
6883
+ // Reactive 401 handling for the generated client: refresh once and retry
6884
+ if (!retried && shouldAttemptTokenRefresh(error)) {
6885
+ await this._performTokenRefresh();
6886
+ // securityWorker will re-fetch the new access token on retry
6887
+ return attemptRequest(true);
6888
+ }
6889
+ // Transform the generated API error format into WallabyError
6890
+ if (error === null || error === void 0 ? void 0 : error.error) {
6891
+ const apiError = error.error;
6892
+ throw new WallabyError({
6893
+ message: apiError.message || 'API request failed',
6894
+ statusCode: apiError.statusCode || 500,
6895
+ errorCode: apiError.errorCode,
6896
+ data: apiError,
6897
+ });
6898
+ }
6899
+ // Re-throw if already a WallabyError
6900
+ if (error instanceof WallabyError) {
6901
+ throw error;
6902
+ }
6903
+ // Wrap any other errors
6729
6904
  throw new WallabyError({
6730
- message: apiError.message || 'API request failed',
6731
- statusCode: apiError.statusCode || 500,
6732
- errorCode: apiError.errorCode,
6733
- data: apiError,
6905
+ message: error.message || 'Unknown error occurred',
6906
+ statusCode: error.statusCode || 500,
6907
+ errorCode: error.errorCode,
6908
+ data: error,
6734
6909
  });
6735
6910
  }
6736
- // Re-throw if already a WallabyError
6737
- if (error instanceof WallabyError) {
6738
- throw error;
6739
- }
6740
- // Wrap any other errors
6741
- throw new WallabyError({
6742
- message: error.message || 'Unknown error occurred',
6743
- statusCode: error.statusCode || 500,
6744
- errorCode: error.errorCode,
6745
- data: error,
6746
- });
6747
- }
6911
+ };
6912
+ return attemptRequest(false);
6748
6913
  };
6749
6914
  this.api = new Api(httpClient);
6750
6915
  this.api.http.setSecurityData(Object.assign({ 'x-api-key': config.apiKey, 'x-client-jwt': config.clientAuthToken }, (_b = this.options) === null || _b === void 0 ? void 0 : _b.headers));
@@ -6825,15 +6990,51 @@ class Base {
6825
6990
  environment: this.settings.environment,
6826
6991
  });
6827
6992
  }
6993
+ /**
6994
+ * Fetches a new access/refresh token pair using the stored refresh token.
6995
+ * All concurrent callers share the same in-flight promise via the module-level
6996
+ * `refreshDedupeManager` so only one network request is issued per user/environment scope.
6997
+ */
6998
+ async _performTokenRefresh() {
6999
+ const refreshDedupeKey = `refresh:${this.userId}:${this.settings.environment}:${this.settings.network}`;
7000
+ await refreshDedupeManager.withDedupe(refreshDedupeKey, async () => {
7001
+ const refreshToken = await this.localStorageService.fetch(LocalStorageItems.RefreshToken);
7002
+ if (!refreshToken) {
7003
+ return;
7004
+ }
7005
+ try {
7006
+ const response = await this.request(AuthRoutes.refreshAccessToken, {
7007
+ payload: { refreshToken },
7008
+ });
7009
+ await this.localStorageService.save(LocalStorageItems.AccessToken, response.accessToken);
7010
+ await this.localStorageService.save(LocalStorageItems.RefreshToken, response.refreshToken);
7011
+ }
7012
+ catch (error) {
7013
+ if (shouldClearTokensAfterRefreshFailure(error)) {
7014
+ await this.localStorageService.delete(LocalStorageItems.AccessToken);
7015
+ await this.localStorageService.delete(LocalStorageItems.RefreshToken);
7016
+ }
7017
+ throw error;
7018
+ }
7019
+ });
7020
+ }
6828
7021
  /**
6829
7022
  * Main request method for making API calls to the Wallaby API.
6830
7023
  * @param route - Route configuration object containing the endpoint path and HTTP method
6831
7024
  * @param options - Optional request options including payload and query parameters
7025
+ * @param retried - Internal flag; set to true when retrying after a 401 to prevent loops
6832
7026
  * @returns Promise resolving to the typed response data
6833
7027
  * @throws Error if the API returns an error response or network failure occurs
6834
7028
  */
6835
- async request(route, options) {
7029
+ async request(route, options, retried = false) {
6836
7030
  var _a;
7031
+ // Proactive token refresh: if access token is near expiry, refresh before making the request
7032
+ if (route !== AuthRoutes.refreshAccessToken && !retried) {
7033
+ const accessToken = await this.localStorageService.fetch(LocalStorageItems.AccessToken);
7034
+ if (accessToken && isJwtNearExpiry(accessToken, 60)) {
7035
+ await this._performTokenRefresh();
7036
+ }
7037
+ }
6837
7038
  const path = typeof route.fullPath === 'string' ? route.fullPath : route.fullPath(options === null || options === void 0 ? void 0 : options.payload);
6838
7039
  // Add query parameters to the path if provided
6839
7040
  let finalPath = path;
@@ -6887,6 +7088,11 @@ class Base {
6887
7088
  return data;
6888
7089
  }
6889
7090
  catch (error) {
7091
+ // Reactive token refresh: on 401, refresh once and retry the original request
7092
+ if (!retried && route !== AuthRoutes.refreshAccessToken && shouldAttemptTokenRefresh(error)) {
7093
+ await this._performTokenRefresh();
7094
+ return this.request(route, options, true);
7095
+ }
6890
7096
  if (error === null || error === void 0 ? void 0 : error.error) {
6891
7097
  logger.error('SDK::Base::handleApiCall::API Error', { error });
6892
7098
  const apiError = error.error;
@@ -6939,6 +7145,16 @@ class Base {
6939
7145
  return headers;
6940
7146
  }
6941
7147
  async securityWorker(securityData) {
7148
+ // Proactive token refresh before building headers for the generated client
7149
+ try {
7150
+ const accessToken = await this.localStorageService.fetch(LocalStorageItems.AccessToken);
7151
+ if (accessToken && isJwtNearExpiry(accessToken, 60)) {
7152
+ await this._performTokenRefresh();
7153
+ }
7154
+ }
7155
+ catch (_a) {
7156
+ // Best-effort proactive refresh; proceed even if it fails
7157
+ }
6942
7158
  // Start with the security data that contains API key and JWT
6943
7159
  const headers = Object.assign({ 'Content-Type': 'application/json' }, (securityData || {}));
6944
7160
  // Add access token if available
@@ -6948,7 +7164,7 @@ class Base {
6948
7164
  headers.Authorization = `Bearer ${accessToken}`;
6949
7165
  }
6950
7166
  }
6951
- catch (_a) {
7167
+ catch (_b) {
6952
7168
  // Access token is optional, continue without it
6953
7169
  }
6954
7170
  return {
@@ -7075,49 +7291,6 @@ const WalletRoutes = {
7075
7291
  },
7076
7292
  };
7077
7293
 
7078
- const AuthRoutes = {
7079
- signatureMessage: {
7080
- fullPath: '/auth/signature-message',
7081
- method: RequestMethod.Post,
7082
- requiresAccessToken: false,
7083
- },
7084
- signIn: {
7085
- fullPath: '/auth/sign-in',
7086
- method: RequestMethod.Post,
7087
- requiresAccessToken: false,
7088
- },
7089
- signUp: {
7090
- fullPath: '/auth/sign-up',
7091
- method: RequestMethod.Post,
7092
- requiresAccessToken: false,
7093
- },
7094
- refreshAccessToken: {
7095
- fullPath: '/auth/refresh-access-token',
7096
- method: RequestMethod.Post,
7097
- requiresAccessToken: true,
7098
- },
7099
- clientAuthPubKey: {
7100
- fullPath: 'auth/client-auth-pubkey',
7101
- method: RequestMethod.Put,
7102
- requiresAccessToken: true,
7103
- },
7104
- wallabyAuthPublicKey: {
7105
- fullPath: '/auth/wallaby-auth-pubkey',
7106
- method: RequestMethod.Get,
7107
- requiresAccessToken: true,
7108
- },
7109
- getUserSalt: {
7110
- fullPath: '/users/salt',
7111
- method: RequestMethod.Get,
7112
- requiresAccessToken: true,
7113
- },
7114
- getPasskeyCredentials: {
7115
- fullPath: '/auth/passkey-credentials',
7116
- method: RequestMethod.Get,
7117
- requiresAccessToken: true,
7118
- },
7119
- };
7120
-
7121
7294
  const SystemRoutes = {
7122
7295
  getSupportedBlockchains: {
7123
7296
  fullPath: '/chains',
@@ -8007,6 +8180,33 @@ class AuthService extends Base {
8007
8180
  const refreshToken = await this.localStorageService.fetch(LocalStorageItems.RefreshToken);
8008
8181
  return (!!accessToken && !jwtHasExpired(accessToken)) || !!refreshToken;
8009
8182
  }
8183
+ /**
8184
+ * @description Refreshes auth tokens using the stored refresh token.
8185
+ */
8186
+ async refreshAuthTokens() {
8187
+ const refreshToken = await this.localStorageService.fetch(LocalStorageItems.RefreshToken);
8188
+ if (!refreshToken) {
8189
+ throw new WallabyError({
8190
+ message: 'Refresh token is required',
8191
+ statusCode: 401,
8192
+ errorCode: ErrorResponseCodes.sdk_refresh_token_missing,
8193
+ });
8194
+ }
8195
+ await this._performTokenRefresh();
8196
+ const accessToken = await this.localStorageService.fetch(LocalStorageItems.AccessToken);
8197
+ const newRefreshToken = await this.localStorageService.fetch(LocalStorageItems.RefreshToken);
8198
+ if (!accessToken || !newRefreshToken) {
8199
+ throw new WallabyError({
8200
+ message: 'Token refresh failed: tokens not present in storage after refresh',
8201
+ statusCode: 401,
8202
+ errorCode: ErrorResponseCodes.sdk_refresh_token_missing,
8203
+ });
8204
+ }
8205
+ return {
8206
+ accessToken,
8207
+ refreshToken: newRefreshToken,
8208
+ };
8209
+ }
8010
8210
  /**
8011
8211
  * @description Validates the user's password by decrypting the stored private key.
8012
8212
  * @returns { boolean } Returns true if the password is valid, false otherwise.
@@ -10042,6 +10242,7 @@ class WalletService extends Base {
10042
10242
  storeSeedPhrase: false,
10043
10243
  returnWalletOption: ReturnWalletOption.ReturnOnlyEncryptedShares, // always only return the encrypted shares
10044
10244
  walletId: input.walletId,
10245
+ reference: v4(),
10045
10246
  keyShareOptions: {
10046
10247
  threshold: 2,
10047
10248
  numberOfKeyShares: 3,