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.esm.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";
@@ -569,7 +589,7 @@ const MASTER_ENCRYPTION_KEY = '9fa9d3f3c77c20d3a50a08e5299644be29f6e6206ef3479fe
569
589
  { type: 'public-key', alg: PublicKeyCredentialAlgorithm.ES256 },
570
590
  ];
571
591
  const isWeb = typeof window !== 'undefined' && typeof document !== 'undefined';
572
- const currentPackageVersion = "3.1.0" ;
592
+ const currentPackageVersion = "3.2.1" ;
573
593
 
574
594
  /**
575
595
  * Storage keys adapter for Storage interface across different platforms.
@@ -5186,6 +5206,19 @@ function userIsMfaVerified(jwt) {
5186
5206
  const jwtDecoded = jwtDecode(jwt);
5187
5207
  return jwtDecoded.mfaVerified;
5188
5208
  }
5209
+ /**
5210
+ * Checks if a given JWT will expire within the given threshold.
5211
+ *
5212
+ * @param jwt - The JWT string to check. If null, the function returns false.
5213
+ * @param thresholdSeconds - Number of seconds before expiry to consider "near expiry".
5214
+ * @returns `true` if the JWT expires within `thresholdSeconds` seconds, otherwise `false`.
5215
+ */
5216
+ function isJwtNearExpiry(jwt, thresholdSeconds) {
5217
+ if (!jwt) {
5218
+ return false;
5219
+ }
5220
+ return millisecondsToJWTTimeout(jwt) <= thresholdSeconds * 1000;
5221
+ }
5189
5222
  /**
5190
5223
  * Calculates the remaining time in milliseconds until a given JWT expires.
5191
5224
  *
@@ -5200,6 +5233,49 @@ function millisecondsToJWTTimeout(jwt) {
5200
5233
  return jwtExpirationTimeMilliseconds - timeNowMilliseconds;
5201
5234
  }
5202
5235
 
5236
+ const AuthRoutes = {
5237
+ signatureMessage: {
5238
+ fullPath: '/auth/signature-message',
5239
+ method: RequestMethod.Post,
5240
+ requiresAccessToken: false,
5241
+ },
5242
+ signIn: {
5243
+ fullPath: '/auth/sign-in',
5244
+ method: RequestMethod.Post,
5245
+ requiresAccessToken: false,
5246
+ },
5247
+ signUp: {
5248
+ fullPath: '/auth/sign-up',
5249
+ method: RequestMethod.Post,
5250
+ requiresAccessToken: false,
5251
+ },
5252
+ refreshAccessToken: {
5253
+ fullPath: '/auth/refresh-access-token',
5254
+ method: RequestMethod.Post,
5255
+ requiresAccessToken: true,
5256
+ },
5257
+ clientAuthPubKey: {
5258
+ fullPath: 'auth/client-auth-pubkey',
5259
+ method: RequestMethod.Put,
5260
+ requiresAccessToken: true,
5261
+ },
5262
+ wallabyAuthPublicKey: {
5263
+ fullPath: '/auth/wallaby-auth-pubkey',
5264
+ method: RequestMethod.Get,
5265
+ requiresAccessToken: true,
5266
+ },
5267
+ getUserSalt: {
5268
+ fullPath: '/users/salt',
5269
+ method: RequestMethod.Get,
5270
+ requiresAccessToken: true,
5271
+ },
5272
+ getPasskeyCredentials: {
5273
+ fullPath: '/auth/passkey-credentials',
5274
+ method: RequestMethod.Get,
5275
+ requiresAccessToken: true,
5276
+ },
5277
+ };
5278
+
5203
5279
  class LockManagerService {
5204
5280
  constructor() {
5205
5281
  this.activeLocks = new Set();
@@ -5243,6 +5319,43 @@ class LockManagerService {
5243
5319
  }
5244
5320
  }
5245
5321
 
5322
+ class DedupeManagerService {
5323
+ constructor() {
5324
+ this.inFlightOperations = new Map();
5325
+ }
5326
+ /**
5327
+ * Executes an operation once per key while returning the same in-flight promise
5328
+ * to all concurrent callers.
5329
+ * @param key - Unique identifier for dedupe scope.
5330
+ * @param operation - The async operation to execute.
5331
+ */
5332
+ withDedupe(key, operation) {
5333
+ const existingOperation = this.inFlightOperations.get(key);
5334
+ if (existingOperation) {
5335
+ return existingOperation;
5336
+ }
5337
+ const operationPromise = Promise.resolve()
5338
+ .then(operation)
5339
+ .finally(() => {
5340
+ this.inFlightOperations.delete(key);
5341
+ });
5342
+ this.inFlightOperations.set(key, operationPromise);
5343
+ return operationPromise;
5344
+ }
5345
+ /**
5346
+ * Check if a specific operation is currently in flight.
5347
+ */
5348
+ isInFlight(key) {
5349
+ return this.inFlightOperations.has(key);
5350
+ }
5351
+ /**
5352
+ * Clear all tracked in-flight operations (primarily for tests/cleanup).
5353
+ */
5354
+ clearAll() {
5355
+ this.inFlightOperations.clear();
5356
+ }
5357
+ }
5358
+
5246
5359
  function isValidInput(input) {
5247
5360
  // Allow alphanumeric characters, hyphens, and underscores.
5248
5361
  const regex = /^[a-zA-Z0-9-_]+$/;
@@ -6681,6 +6794,48 @@ function objectToQueryParams(obj) {
6681
6794
  return params.toString();
6682
6795
  }
6683
6796
 
6797
+ const refreshableAuth401ErrorCodes = new Set([
6798
+ ErrorResponseCodes.auth_api_jwt_invalid,
6799
+ ErrorResponseCodes.auth_api_jwt_not_active,
6800
+ ErrorResponseCodes.auth_api_jwt_not_provided,
6801
+ ErrorResponseCodes.auth_api_jwt_expired,
6802
+ ErrorResponseCodes.auth_api_unauthorized,
6803
+ ]);
6804
+ const clearTokensOnRefreshFailureErrorCodes = new Set([
6805
+ ErrorResponseCodes.auth_refresh_token_not_found,
6806
+ ErrorResponseCodes.auth_refresh_token_expired,
6807
+ ErrorResponseCodes.auth_refresh_token_reuse_detected,
6808
+ ]);
6809
+ function extractErrorStatus(error) {
6810
+ var _a, _b, _c, _d, _e;
6811
+ 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;
6812
+ }
6813
+ function extractErrorCode(error) {
6814
+ var _a, _b, _c, _d;
6815
+ 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;
6816
+ }
6817
+ function shouldAttemptTokenRefresh(error) {
6818
+ const status = extractErrorStatus(error);
6819
+ if (status !== 401) {
6820
+ return false;
6821
+ }
6822
+ const errorCode = extractErrorCode(error);
6823
+ if (!errorCode) {
6824
+ // Backward compatibility: some endpoints may not provide explicit errorCode.
6825
+ return true;
6826
+ }
6827
+ return refreshableAuth401ErrorCodes.has(errorCode);
6828
+ }
6829
+ function shouldClearTokensAfterRefreshFailure(error) {
6830
+ const status = extractErrorStatus(error);
6831
+ const errorCode = extractErrorCode(error);
6832
+ // Any 401 clears tokens (preserves prior behavior). The error-code set additionally
6833
+ // covers refresh-token failures that arrive with a non-401 status (e.g. 400/403).
6834
+ return status === 401 || (!!errorCode && clearTokensOnRefreshFailureErrorCodes.has(errorCode));
6835
+ }
6836
+
6837
+ // Module-level dedupe manager for token refresh to ensure only one refresh request per user/environment/network at a time
6838
+ const refreshDedupeManager = new DedupeManagerService();
6684
6839
  class Base {
6685
6840
  constructor(config) {
6686
6841
  var _a, _b;
@@ -6710,35 +6865,45 @@ class Base {
6710
6865
  });
6711
6866
  /**
6712
6867
  * This intercepts all API responses and transforms errors into WallabyError format.
6868
+ * On a 401, it performs a single token refresh then retries (reactive guard).
6713
6869
  */
6714
6870
  const originalRequest = httpClient.request.bind(httpClient);
6715
6871
  httpClient.request = async (params) => {
6716
- try {
6717
- return await originalRequest(params);
6718
- }
6719
- catch (error) {
6720
- // Transform the generated API error format into WallabyError
6721
- if (error === null || error === void 0 ? void 0 : error.error) {
6722
- const apiError = error.error;
6872
+ const attemptRequest = async (retried) => {
6873
+ try {
6874
+ return await originalRequest(params);
6875
+ }
6876
+ catch (error) {
6877
+ // Reactive 401 handling for the generated client: refresh once and retry
6878
+ if (!retried && shouldAttemptTokenRefresh(error)) {
6879
+ await this._performTokenRefresh();
6880
+ // securityWorker will re-fetch the new access token on retry
6881
+ return attemptRequest(true);
6882
+ }
6883
+ // Transform the generated API error format into WallabyError
6884
+ if (error === null || error === void 0 ? void 0 : error.error) {
6885
+ const apiError = error.error;
6886
+ throw new WallabyError({
6887
+ message: apiError.message || 'API request failed',
6888
+ statusCode: apiError.statusCode || 500,
6889
+ errorCode: apiError.errorCode,
6890
+ data: apiError,
6891
+ });
6892
+ }
6893
+ // Re-throw if already a WallabyError
6894
+ if (error instanceof WallabyError) {
6895
+ throw error;
6896
+ }
6897
+ // Wrap any other errors
6723
6898
  throw new WallabyError({
6724
- message: apiError.message || 'API request failed',
6725
- statusCode: apiError.statusCode || 500,
6726
- errorCode: apiError.errorCode,
6727
- data: apiError,
6899
+ message: error.message || 'Unknown error occurred',
6900
+ statusCode: error.statusCode || 500,
6901
+ errorCode: error.errorCode,
6902
+ data: error,
6728
6903
  });
6729
6904
  }
6730
- // Re-throw if already a WallabyError
6731
- if (error instanceof WallabyError) {
6732
- throw error;
6733
- }
6734
- // Wrap any other errors
6735
- throw new WallabyError({
6736
- message: error.message || 'Unknown error occurred',
6737
- statusCode: error.statusCode || 500,
6738
- errorCode: error.errorCode,
6739
- data: error,
6740
- });
6741
- }
6905
+ };
6906
+ return attemptRequest(false);
6742
6907
  };
6743
6908
  this.api = new Api(httpClient);
6744
6909
  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));
@@ -6819,15 +6984,51 @@ class Base {
6819
6984
  environment: this.settings.environment,
6820
6985
  });
6821
6986
  }
6987
+ /**
6988
+ * Fetches a new access/refresh token pair using the stored refresh token.
6989
+ * All concurrent callers share the same in-flight promise via the module-level
6990
+ * `refreshDedupeManager` so only one network request is issued per user/environment scope.
6991
+ */
6992
+ async _performTokenRefresh() {
6993
+ const refreshDedupeKey = `refresh:${this.userId}:${this.settings.environment}:${this.settings.network}`;
6994
+ await refreshDedupeManager.withDedupe(refreshDedupeKey, async () => {
6995
+ const refreshToken = await this.localStorageService.fetch(LocalStorageItems.RefreshToken);
6996
+ if (!refreshToken) {
6997
+ return;
6998
+ }
6999
+ try {
7000
+ const response = await this.request(AuthRoutes.refreshAccessToken, {
7001
+ payload: { refreshToken },
7002
+ });
7003
+ await this.localStorageService.save(LocalStorageItems.AccessToken, response.accessToken);
7004
+ await this.localStorageService.save(LocalStorageItems.RefreshToken, response.refreshToken);
7005
+ }
7006
+ catch (error) {
7007
+ if (shouldClearTokensAfterRefreshFailure(error)) {
7008
+ await this.localStorageService.delete(LocalStorageItems.AccessToken);
7009
+ await this.localStorageService.delete(LocalStorageItems.RefreshToken);
7010
+ }
7011
+ throw error;
7012
+ }
7013
+ });
7014
+ }
6822
7015
  /**
6823
7016
  * Main request method for making API calls to the Wallaby API.
6824
7017
  * @param route - Route configuration object containing the endpoint path and HTTP method
6825
7018
  * @param options - Optional request options including payload and query parameters
7019
+ * @param retried - Internal flag; set to true when retrying after a 401 to prevent loops
6826
7020
  * @returns Promise resolving to the typed response data
6827
7021
  * @throws Error if the API returns an error response or network failure occurs
6828
7022
  */
6829
- async request(route, options) {
7023
+ async request(route, options, retried = false) {
6830
7024
  var _a;
7025
+ // Proactive token refresh: if access token is near expiry, refresh before making the request
7026
+ if (route !== AuthRoutes.refreshAccessToken && !retried) {
7027
+ const accessToken = await this.localStorageService.fetch(LocalStorageItems.AccessToken);
7028
+ if (accessToken && isJwtNearExpiry(accessToken, 60)) {
7029
+ await this._performTokenRefresh();
7030
+ }
7031
+ }
6831
7032
  const path = typeof route.fullPath === 'string' ? route.fullPath : route.fullPath(options === null || options === void 0 ? void 0 : options.payload);
6832
7033
  // Add query parameters to the path if provided
6833
7034
  let finalPath = path;
@@ -6881,6 +7082,11 @@ class Base {
6881
7082
  return data;
6882
7083
  }
6883
7084
  catch (error) {
7085
+ // Reactive token refresh: on 401, refresh once and retry the original request
7086
+ if (!retried && route !== AuthRoutes.refreshAccessToken && shouldAttemptTokenRefresh(error)) {
7087
+ await this._performTokenRefresh();
7088
+ return this.request(route, options, true);
7089
+ }
6884
7090
  if (error === null || error === void 0 ? void 0 : error.error) {
6885
7091
  logger.error('SDK::Base::handleApiCall::API Error', { error });
6886
7092
  const apiError = error.error;
@@ -6933,6 +7139,16 @@ class Base {
6933
7139
  return headers;
6934
7140
  }
6935
7141
  async securityWorker(securityData) {
7142
+ // Proactive token refresh before building headers for the generated client
7143
+ try {
7144
+ const accessToken = await this.localStorageService.fetch(LocalStorageItems.AccessToken);
7145
+ if (accessToken && isJwtNearExpiry(accessToken, 60)) {
7146
+ await this._performTokenRefresh();
7147
+ }
7148
+ }
7149
+ catch (_a) {
7150
+ // Best-effort proactive refresh; proceed even if it fails
7151
+ }
6936
7152
  // Start with the security data that contains API key and JWT
6937
7153
  const headers = Object.assign({ 'Content-Type': 'application/json' }, (securityData || {}));
6938
7154
  // Add access token if available
@@ -6942,7 +7158,7 @@ class Base {
6942
7158
  headers.Authorization = `Bearer ${accessToken}`;
6943
7159
  }
6944
7160
  }
6945
- catch (_a) {
7161
+ catch (_b) {
6946
7162
  // Access token is optional, continue without it
6947
7163
  }
6948
7164
  return {
@@ -7069,49 +7285,6 @@ const WalletRoutes = {
7069
7285
  },
7070
7286
  };
7071
7287
 
7072
- const AuthRoutes = {
7073
- signatureMessage: {
7074
- fullPath: '/auth/signature-message',
7075
- method: RequestMethod.Post,
7076
- requiresAccessToken: false,
7077
- },
7078
- signIn: {
7079
- fullPath: '/auth/sign-in',
7080
- method: RequestMethod.Post,
7081
- requiresAccessToken: false,
7082
- },
7083
- signUp: {
7084
- fullPath: '/auth/sign-up',
7085
- method: RequestMethod.Post,
7086
- requiresAccessToken: false,
7087
- },
7088
- refreshAccessToken: {
7089
- fullPath: '/auth/refresh-access-token',
7090
- method: RequestMethod.Post,
7091
- requiresAccessToken: true,
7092
- },
7093
- clientAuthPubKey: {
7094
- fullPath: 'auth/client-auth-pubkey',
7095
- method: RequestMethod.Put,
7096
- requiresAccessToken: true,
7097
- },
7098
- wallabyAuthPublicKey: {
7099
- fullPath: '/auth/wallaby-auth-pubkey',
7100
- method: RequestMethod.Get,
7101
- requiresAccessToken: true,
7102
- },
7103
- getUserSalt: {
7104
- fullPath: '/users/salt',
7105
- method: RequestMethod.Get,
7106
- requiresAccessToken: true,
7107
- },
7108
- getPasskeyCredentials: {
7109
- fullPath: '/auth/passkey-credentials',
7110
- method: RequestMethod.Get,
7111
- requiresAccessToken: true,
7112
- },
7113
- };
7114
-
7115
7288
  const SystemRoutes = {
7116
7289
  getSupportedBlockchains: {
7117
7290
  fullPath: '/chains',
@@ -7893,6 +8066,33 @@ class AuthService extends Base {
7893
8066
  const refreshToken = await this.localStorageService.fetch(LocalStorageItems.RefreshToken);
7894
8067
  return (!!accessToken && !jwtHasExpired(accessToken)) || !!refreshToken;
7895
8068
  }
8069
+ /**
8070
+ * @description Refreshes auth tokens using the stored refresh token.
8071
+ */
8072
+ async refreshAuthTokens() {
8073
+ const refreshToken = await this.localStorageService.fetch(LocalStorageItems.RefreshToken);
8074
+ if (!refreshToken) {
8075
+ throw new WallabyError({
8076
+ message: 'Refresh token is required',
8077
+ statusCode: 401,
8078
+ errorCode: ErrorResponseCodes.sdk_refresh_token_missing,
8079
+ });
8080
+ }
8081
+ await this._performTokenRefresh();
8082
+ const accessToken = await this.localStorageService.fetch(LocalStorageItems.AccessToken);
8083
+ const newRefreshToken = await this.localStorageService.fetch(LocalStorageItems.RefreshToken);
8084
+ if (!accessToken || !newRefreshToken) {
8085
+ throw new WallabyError({
8086
+ message: 'Token refresh failed: tokens not present in storage after refresh',
8087
+ statusCode: 401,
8088
+ errorCode: ErrorResponseCodes.sdk_refresh_token_missing,
8089
+ });
8090
+ }
8091
+ return {
8092
+ accessToken,
8093
+ refreshToken: newRefreshToken,
8094
+ };
8095
+ }
7896
8096
  /**
7897
8097
  * @description Validates the user's password by decrypting the stored private key.
7898
8098
  * @returns { boolean } Returns true if the password is valid, false otherwise.
@@ -9928,6 +10128,7 @@ class WalletService extends Base {
9928
10128
  storeSeedPhrase: false,
9929
10129
  returnWalletOption: ReturnWalletOption.ReturnOnlyEncryptedShares, // always only return the encrypted shares
9930
10130
  walletId: input.walletId,
10131
+ reference: v4(),
9931
10132
  keyShareOptions: {
9932
10133
  threshold: 2,
9933
10134
  numberOfKeyShares: 3,