All files / src/storage/gaia errors.ts

48.73% Statements 58/119
19.51% Branches 8/41
25% Functions 6/24
48.64% Lines 54/111

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411          4x                                         4x                                             1x 1x 1x 1x 1x             1x     1x   1x 1x                       4x                   4x                       4x                   4x                       4x                                 4x                               4x                       4x                       4x                     4x                     4x                                                           4x     1x   1x       1x 1x                   4x 1x                 4x                   4x                   4x                   4x                                 4x                     4x             4x   1x   1x 1x 1x 1x             1x 1x             4x     5x       5x             1x     1x 1x   1x   1x   1x 1x                                   4x                                      
import type { GaiaHubConfig } from './types';
 
/**
 * @ignore
 */
export const ERROR_CODES = {
  MISSING_PARAMETER: 'missing_parameter',
  REMOTE_SERVICE_ERROR: 'remote_service_error',
  INVALID_STATE: 'invalid_state',
  NO_SESSION_DATA: 'no_session_data',
  DOES_NOT_EXIST: 'does_not_exist',
  FAILED_DECRYPTION_ERROR: 'failed_decryption_error',
  INVALID_DID_ERROR: 'invalid_did_error',
  NOT_ENOUGH_FUNDS_ERROR: 'not_enough_error',
  INVALID_AMOUNT_ERROR: 'invalid_amount_error',
  LOGIN_FAILED_ERROR: 'login_failed',
  SIGNATURE_VERIFICATION_ERROR: 'signature_verification_failure',
  CONFLICT_ERROR: 'conflict_error',
  NOT_ENOUGH_PROOF_ERROR: 'not_enough_proof_error',
  BAD_PATH_ERROR: 'bad_path_error',
  VALIDATION_ERROR: 'validation_error',
  PAYLOAD_TOO_LARGE_ERROR: 'payload_too_large_error',
  PRECONDITION_FAILED_ERROR: 'precondition_failed_error',
  UNKNOWN: 'unknown',
};
 
Object.freeze(ERROR_CODES);
 
/**
 * @ignore
 */
type ErrorData = {
  code: string;
  parameter?: string;
  message: string;
};
 
/**
 * @ignore
 */
export class BlockstackError extends Error {
  message: string;
 
  code: string;
 
  parameter?: string;
 
  constructor(error: ErrorData) {
    super();
    let message = error.message;
    let bugDetails = `Error Code: ${error.code}`;
    let stack = this.stack;
    if (!stack) {
      Itry {
        throw new Error();
      } catch (e) {
        stack = (e as any).stack;
      }
    } else {
      bugDetails += `Stack Trace:\n${stack}`;
    }
    message += `\nIf you believe this exception is caused by a bug in blockstack.js,
      please file a bug report: https://github.com/blockstack/blockstack.js/issues\n\n${bugDetails}`;
    this.message = message;
    this.code = error.code;
    this.parameter = error.parameter ? error.parameter : undefined;
  }
 
  toString() {
    return `${super.toString()}
    code: ${this.code} param: ${this.parameter ? this.parameter : 'n/a'}`;
  }
}
 
/**
 * @ignore
 */
export class InvalidParameterError extends BlockstackError {
  constructor(parameter: string, message = '') {
    super({ code: ERROR_CODES.MISSING_PARAMETER, message, parameter });
    this.name = 'MissingParametersError';
  }
}
 
/**
 * @ignore
 */
export class MissingParameterError extends BlockstackError {
  constructor(parameter: string, message = '') {
    super({ code: ERROR_CODES.MISSING_PARAMETER, message, parameter });
    this.name = 'MissingParametersError';
  }
}
 
/**
 * @ignore
 */
export class RemoteServiceError extends BlockstackError {
  response: Response;
 
  constructor(response: Response, message = '') {
    super({ code: ERROR_CODES.REMOTE_SERVICE_ERROR, message });
    this.response = response;
  }
}
 
/**
 * @ignore
 */
export class InvalidDIDError extends BlockstackError {
  constructor(message = '') {
    super({ code: ERROR_CODES.INVALID_DID_ERROR, message });
    this.name = 'InvalidDIDError';
  }
}
 
/**
 * @ignore
 */
export class NotEnoughFundsError extends BlockstackError {
  leftToFund: number;
 
  constructor(leftToFund: number) {
    const message = `Not enough UTXOs to fund. Left to fund: ${leftToFund}`;
    super({ code: ERROR_CODES.NOT_ENOUGH_FUNDS_ERROR, message });
    this.leftToFund = leftToFund;
    this.name = 'NotEnoughFundsError';
    this.message = message;
  }
}
 
/**
 * @ignore
 */
export class InvalidAmountError extends BlockstackError {
  fees: number;
 
  specifiedAmount: number;
 
  constructor(fees: number, specifiedAmount: number) {
    const message =
      `Not enough coin to fund fees transaction fees. Fees would be ${fees},` +
      ` specified spend is  ${specifiedAmount}`;
    super({ code: ERROR_CODES.INVALID_AMOUNT_ERROR, message });
    this.specifiedAmount = specifiedAmount;
    this.fees = fees;
    this.name = 'InvalidAmountError';
    this.message = message;
  }
}
 
/**
 * @ignore
 */
export class LoginFailedError extends BlockstackError {
  constructor(reason: string) {
    const message = `Failed to login: ${reason}`;
    super({ code: ERROR_CODES.LOGIN_FAILED_ERROR, message });
    this.message = message;
    this.name = 'LoginFailedError';
  }
}
 
/**
 * @ignore
 */
export class SignatureVerificationError extends BlockstackError {
  constructor(reason: string) {
    const message = `Failed to verify signature: ${reason}`;
    super({ code: ERROR_CODES.SIGNATURE_VERIFICATION_ERROR, message });
    this.message = message;
    this.name = 'SignatureVerificationError';
  }
}
 
/**
 * @ignore
 */
export class FailedDecryptionError extends BlockstackError {
  constructor(message = 'Unable to decrypt cipher object.') {
    super({ code: ERROR_CODES.FAILED_DECRYPTION_ERROR, message });
    this.message = message;
    this.name = 'FailedDecryptionError';
  }
}
 
/**
 * @ignore
 */
export class InvalidStateError extends BlockstackError {
  constructor(message: string) {
    super({ code: ERROR_CODES.INVALID_STATE, message });
    this.message = message;
    this.name = 'InvalidStateError';
  }
}
 
/**
 * @ignore
 */
export class NoSessionDataError extends BlockstackError {
  constructor(message: string) {
    super({ code: ERROR_CODES.INVALID_STATE, message });
    this.message = message;
    this.name = 'NoSessionDataError';
  }
}
 
/**
 * @ignore
 */
export interface GaiaHubErrorResponse {
  status: number;
  statusText: string;
  body?: string | any;
}
 
export interface HubErrorDetails {
  message?: string;
  statusCode: number;
  statusText: string;
 
  [prop: string]: any;
}
 
/**
 * @ignore
 */
export class GaiaHubError extends BlockstackError {
  hubError?: HubErrorDetails;
 
  constructor(error: ErrorData, response: GaiaHubErrorResponse) {
    super(error);
    if (response) {
      this.hubError = {
        statusCode: response.status,
        statusText: response.statusText,
      };
      if (typeof response.body === 'string') {
        this.hubError.message = response.body;
      } else if (typeof response.body === 'object') {
        Object.assign(this.hubError, response.body);
      }IE
    }
  }
}
 
/**
 * @ignore
 */
export class DoesNotExist extends GaiaHubError {
  constructor(message: string, response: GaiaHubErrorResponse) {
    super({ message, code: ERROR_CODES.DOES_NOT_EXIST }, response);
    this.name = 'DoesNotExist';
  }
}
 
/**
 * @ignore
 */
export class ConflictError extends GaiaHubError {
  constructor(message: string, response: GaiaHubErrorResponse) {
    super({ message, code: ERROR_CODES.CONFLICT_ERROR }, response);
    this.name = 'ConflictError';
  }
}
 
/**
 * @ignore
 */
export class NotEnoughProofError extends GaiaHubError {
  constructor(message: string, response: GaiaHubErrorResponse) {
    super({ message, code: ERROR_CODES.NOT_ENOUGH_PROOF_ERROR }, response);
    this.name = 'NotEnoughProofError';
  }
}
 
/**
 * @ignore
 */
export class BadPathError extends GaiaHubError {
  constructor(message: string, response: GaiaHubErrorResponse) {
    super({ message, code: ERROR_CODES.BAD_PATH_ERROR }, response);
    this.name = 'BadPathError';
  }
}
 
/**
 * @ignore
 */
export class ValidationError extends GaiaHubError {
  constructor(message: string, response: GaiaHubErrorResponse) {
    super({ message, code: ERROR_CODES.VALIDATION_ERROR }, response);
    this.name = 'ValidationError';
  }
}
 
/**
 * @ignore
 */
export class PayloadTooLargeError extends GaiaHubError {
  /** Can be `null` when an oversized payload is detected client-side. */
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  // @ts-ignore TODO: fix
  hubError?: HubErrorDetails;
 
  maxUploadByteSize: number;
 
  constructor(message: string, response: GaiaHubErrorResponse | null, maxUploadByteSize: number) {
    super({ message, code: ERROR_CODES.PAYLOAD_TOO_LARGE_ERROR }, response!);
    this.name = 'PayloadTooLargeError';
    this.maxUploadByteSize = maxUploadByteSize;
  }
}
 
/**
 * @ignore
 */
export class PreconditionFailedError extends GaiaHubError {
  constructor(message: string, response: GaiaHubErrorResponse) {
    super({ message, code: ERROR_CODES.PRECONDITION_FAILED_ERROR }, response);
    this.name = 'PreconditionFailedError';
  }
}
 
async function getGaiaErrorResponse(response: Response): Promise<GaiaHubErrorResponse> {
  let responseMsg = '';
  let responseJson: any | undefined;
  try {
    responseMsg = await response.text();
    try {
      responseJson = JSON.parse(responseMsg);
    } catch (error) {
      // Use text instead
    }
  } catch (error) {
    console.debug(`Error getting bad http response text: ${error}`);
  }
  const status = response.status;
  const statusText = response.statusText;
  const body = responseJson || responseMsg;
  return { status, statusText, body };
}
 
/**
 * Converts megabytes to bytes. Returns 0 if the input is not a finite number.
 * @ignore
 */
export function megabytesToBytes(megabytes: number): number {
  if (!Number.isFinite(megabytes)) {
    return 0;
  I}
  return Math.floor(megabytes * 1024 * 1024);
}
 
export async function getBlockstackErrorFromResponse(
  response: Response,
  errorMsg: string,
  hubConfig: GaiaHubConfig | null
): Promise<Error> {
  if (response.ok) {
    throw new Error('Cannot get a Stacks from a valid response.');
  I}
  const gaiaResponse = await getGaiaErrorResponse(response);
  if (gaiaResponse.status === 401) {
    throw new ValidationError(errorMsg, gaiaResponse);
  I} else if (gaiaResponse.status === 402) {
    throw new NotEnoughProofError(errorMsg, gaiaResponse);
  } else Iif (gaiaResponse.status === 403) {
    throw new BadPathError(errorMsg, gaiaResponse);
  } else Iif (gaiaResponse.status === 404) {
    throw new DoesNotExist(errorMsg, gaiaResponse);
  } else if (gaiaResponse.status === 409) {
    throw new ConflictError(errorMsg, gaiaResponse);
  } else Eif (gaiaResponse.status === 412) {
    throw new PreconditionFailedError(errorMsg, gaiaResponse);
  } else if (gaiaResponse.status === 413) {
    const maxBytes =
      hubConfig && hubConfig.max_file_upload_size_megabytes
        ? megabytesToBytes(hubConfig.max_file_upload_size_megabytes)
        : 0;
    throw new PayloadTooLargeError(errorMsg, gaiaResponse, maxBytes);
  } else {
    throw new Error(errorMsg);
  }
}
 
/**
 * Determines if a gaia error response is possible to recover from
 * by refreshing the gaiaHubConfig, and retrying the request.
 */
export function isRecoverableGaiaError(error: GaiaHubError): boolean {
  if (!error || !error.hubError || !error.hubError.statusCode) {
    return false;
  I}
  const statusCode = error.hubError.statusCode;
  // 401 Unauthorized: possible expired, but renewable auth token.
  if (statusCode === 401) {
    return true;
  I}
  // 409 Conflict: possible concurrent writes to a file.
  if (statusCode === 409) {
    return true;
  I}
  // 500s: possible server-side transient error
  if (statusCode >= 500 && statusCode <= 599) {
    return true;
  I}
  return false;
}