All files / src/api certs.js

90% Statements 72/80
81.57% Branches 31/38
100% Functions 13/13
90% Lines 72/80

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                                                2x 1x 1x         1x 1x               1x                   2x 1x                           2x 3x 3x 3x 1x   2x 1x     1x                       2x 1x 1x 1x 1x         1x 1x     2x 1x 1x           1x                 2x 1x                         2x 3x 3x 1x   2x 1x     1x             2x 2x 2x           1x   1x     1x       2x 1x                             2x 7x 3x       4x   4x 4x 2x   2x 1x     1x             2x 3x 3x           1x   2x 1x   1x       2x 1x                           2x 8x         3x         5x 5x 3x   2x 1x     1x                                                                                                                            
/**
 * @typedef {import('../types/users').UserData} UserData
 * @typedef {import('../types/certs').GenerateCertResponse} GenerateCertResponse
 * @typedef {import('../types/certs').GetCertStatusResponse} GetCertStatusResponse
 * @typedef {import('../types/certs').EncryptedCSRObject} EncryptedCSRObject
 * @typedef {import('../types/certs').GetCertTypesResponse} GetCertTypesResponse
 * @typedef {import('../types/certs').GetRequirementsResponse} GetRequirementsResponse
 * @typedef {import('../types/certs').CertificateRequestParams} CertificateRequestParams
 * @typedef {import('../types/certs').RequestCertificateResponse} RequestCertificateResponse
 * @typedef {import('../types/certs').ValidateCertificateResponseData} ValidateCertificateResponseData
 * @typedef {import('../types/certs').ValidateCertificateRequestParams} ValidateCertificateRequestParams
 */
 
import { getConfig } from "../config/index";
import { httpRequest } from "../utils/httpClient";
import helpers from "../utils/helpers";
import { ApacuanaAPIError } from "../errors";
import ApacuanaSuccess from "../success";
import { INTEGRATION_TYPE, PARSE_STATUS } from "../utils/constant";
import { getCustomer } from "./users";
 
/**
 * @param {EncryptedCSRObject} encryptedCSR
 */
const generateCertOnBoarding = async (encryptedCSR) => {
  try {
    const response = await httpRequest(
      "services/api/register/certificate",
      encryptedCSR,
      "POST"
    );
    const { cert, certifiedid } = response;
    Iif (!cert || !certifiedid) {
      throw new ApacuanaAPIError(
        "The API response does not contain the certificate.",
        response.status,
        "INVALID_API_RESPONSE"
      );
    }
 
    return new ApacuanaSuccess({ cert, certifiedid });
  } catch (error) {
    // The captured error is re-thrown, which will already be of type ApacuanaAPIError or a native Error.
    if (error instanceof ApacuanaAPIError) {
      throw error;
    }
    throw new Error(`Certificate generation failed: ${error.message}`);
  }
};
 
const generateCertOnPremise = async () => {
  throw new ApacuanaAPIError(
    "Certificate generation is not supported for integration type: ONPREMISE",
    501,
    "NOT_IMPLEMENTED"
  );
};
 
/**
 * Generates a digital certificate.
 * @param {EncryptedCSRObject} encryptedCSR - Certificate Signing Request (CSR) object.
 * @returns {Promise<GenerateCertResponse>} Object with the generated certificate and a success indicator.
 * @throws {ApacuanaAPIError} If the CSR is invalid, if the API response does not contain the certificate, or if the integration type is not supported.
 * @throws {Error} If certificate generation fails for another reason.
 */
export const generateCert = async (encryptedCSR) => {
  const { integrationType } = getConfig();
  helpers.validateCsr(encryptedCSR);
  if (integrationType === INTEGRATION_TYPE.ONBOARDING) {
    return generateCertOnBoarding(encryptedCSR);
  }
  if (integrationType === INTEGRATION_TYPE.ONPREMISE) {
    return generateCertOnPremise();
  }
 
  throw new ApacuanaAPIError(
    `Unsupported integration type: ${integrationType}`,
    400,
    "UNSUPPORTED_INTEGRATION_TYPE"
  );
};
 
/**
 * Gets the user's certificate status.
 * @param {boolean} [isCertificateInDevice=false] - Indicates if the certificate is already on the device.
 * @returns {GetCertStatusResponse} Object with the certificate status and a success indicator.
 */
export const getCertStatus = async (isCertificateInDevice = false) => {
  const config = getConfig();
  const customer = await getCustomer();
  const { userData } = customer.data;
  const status = helpers.getCertificateStatus(
    userData,
    isCertificateInDevice,
    config.integrationType
  );
  const parseStatus = PARSE_STATUS[status];
  return new ApacuanaSuccess({ status: parseStatus });
};
 
const getCertTypesOnBoarding = async () => {
  try {
    const response = await httpRequest(
      "services/api/customer/typeusers",
      {},
      "GET"
    );
 
    return new ApacuanaSuccess(response);
  } catch (error) {
    if (error instanceof ApacuanaAPIError) {
      throw error;
    }
    throw new Error(`Failed to get certificate types: ${error.message}`);
  }
};
 
const getCertTypesOnPremise = async () => {
  throw new ApacuanaAPIError(
    "Getting certificate types is not supported for integration type: ONPREMISE",
    501,
    "NOT_IMPLEMENTED"
  );
};
 
/**
 * Gets the available certificate types.
 * @returns {Promise<GetCertTypesResponse>} Object with the list of certificate types and a success indicator.
 * @throws {ApacuanaAPIError} If the API response is invalid or the integration type is not supported.
 * @throws {Error} If the request fails for another reason.
 */
export const getCertTypes = async () => {
  const { integrationType } = getConfig();
  if (integrationType === INTEGRATION_TYPE.ONBOARDING) {
    return getCertTypesOnBoarding();
  }
  if (integrationType === INTEGRATION_TYPE.ONPREMISE) {
    return getCertTypesOnPremise();
  }
 
  throw new ApacuanaAPIError(
    `Unsupported integration type: ${integrationType}`,
    400,
    "UNSUPPORTED_INTEGRATION_TYPE"
  );
};
 
const getRequerimentsByTypeUserOnBoarding = async (type) => {
  try {
    const response = await httpRequest(
      `services/api/customer/documentspref?typeuser=${type}`,
      {},
      "GET"
    );
 
    return new ApacuanaSuccess(response);
  } catch (error) {
    Iif (error instanceof ApacuanaAPIError) {
      throw error;
    }
    throw new Error(`Failed to get requirements: ${error.message}`);
  }
};
 
const getRequerimentsByTypeUserOnPremise = async () => {
  throw new ApacuanaAPIError(
    "Getting requirements by user type is not supported for integration type: ONPREMISE",
    501,
    "NOT_IMPLEMENTED"
  );
};
 
/**
 * Gets the requirements for a given user type.
 * @param {object} params - The parameters.
 * @param {number} params.type - The user type to get requirements for.
 * @returns {Promise<GetRequirementsResponse>} Object with the list of requirements and a success indicator.
 * @throws {ApacuanaAPIError} If the API response is invalid or the integration type is not supported.
 * @throws {Error} If the request fails for another reason or the type is invalid.
 */
export const getRequerimentsByTypeUser = async (params) => {
  if (!params || typeof params.type !== "number") {
    throw new Error(
      'The "params" object with a numeric "type" property is required.'
    );
  }
  const { type } = params;
 
  const { integrationType } = getConfig();
  if (integrationType === INTEGRATION_TYPE.ONBOARDING) {
    return getRequerimentsByTypeUserOnBoarding(type);
  }
  if (integrationType === INTEGRATION_TYPE.ONPREMISE) {
    return getRequerimentsByTypeUserOnPremise();
  }
 
  throw new ApacuanaAPIError(
    `Unsupported integration type: ${integrationType}`,
    400,
    "UNSUPPORTED_INTEGRATION_TYPE"
  );
};
 
const requestCertificateOnBoarding = async (params) => {
  try {
    const response = await httpRequest(
      "services/api/customer/request-certificate",
      params,
      "POST"
    );
 
    return new ApacuanaSuccess(response);
  } catch (error) {
    if (error instanceof ApacuanaAPIError) {
      throw error;
    }
    throw new Error(`Failed to request certificate: ${error.message}`);
  }
};
 
const requestCertificateOnPremise = async () => {
  throw new ApacuanaAPIError(
    "Requesting a certificate is not supported for integration type: ONPREMISE",
    501,
    "NOT_IMPLEMENTED"
  );
};
 
/**
 * Requests a certificate for the user.
 * @param {CertificateRequestParams} params - The parameters for the certificate request.
 * @returns {Promise<RequestCertificateResponse>} Object with a confirmation message and a success indicator.
 * @throws {ApacuanaAPIError} If the API response is invalid or the integration type is not supported.
 * @throws {Error} If the request fails for another reason or the params are invalid.
 */
export const requestCertificate = async (params) => {
  if (
    !params ||
    typeof params.type !== "number" ||
    !Array.isArray(params.documents)
  ) {
    throw new Error(
      'The "params" object with a numeric "type" property and a "documents" array is required.'
    );
  }
 
  const { integrationType } = getConfig();
  if (integrationType === INTEGRATION_TYPE.ONBOARDING) {
    return requestCertificateOnBoarding(params);
  }
  if (integrationType === INTEGRATION_TYPE.ONPREMISE) {
    return requestCertificateOnPremise();
  }
 
  throw new ApacuanaAPIError(
    `Unsupported integration type: ${integrationType}`,
    400,
    "UNSUPPORTED_INTEGRATION_TYPE"
  );
};
 
// const validateCertificateOnBoarding = async (params) => {
//   throw new ApacuanaAPIError(
//     "Requesting a certificate is not supported for integration type: ONBOARDING",
//     501,
//     "NOT_IMPLEMENTED"
//   );
//   // try {
//   //   const response = await httpRequest(
//   //     "services/api/customer/request-certificate",
//   //     params,
//   //     "POST"
//   //   );
//   //   return new ApacuanaSuccess(response);
//   // } catch (error) {
//   //   if (error instanceof ApacuanaAPIError) {
//   //     throw error;
//   //   }
//   //   throw new Error(`Failed to request certificate: ${error.message}`);
//   // }
// };
 
// const validateCertificateOnPremise = async () => {
//   throw new ApacuanaAPIError(
//     "Requesting a certificate is not supported for integration type: ONPREMISE",
//     501,
//     "NOT_IMPLEMENTED"
//   );
// };
 
// /**
//  * Requests a certificate for the user.
//  * @param {ValidateCertificateRequestParams} params - The parameters for the certificate request.
//  * @returns {Promise<ValidateCertificateResponseData>} Object with a confirmation message and a success indicator.
//  * @throws {ApacuanaAPIError} If the API response is invalid or the integration type is not supported.
//  * @throws {Error} If the request fails for another reason or the params are invalid.
//  */
// export const validateCertificate = async (params) => {
//   if (!params || typeof params.challenge !== "string") {
//     throw new Error("Invalid params.");
//   }
 
//   const { integrationType } = getConfig();
//   if (integrationType === INTEGRATION_TYPE.ONBOARDING) {
//     return requestCertificateOnBoarding(params);
//   }
//   if (integrationType === INTEGRATION_TYPE.ONPREMISE) {
//     return requestCertificateOnPremise();
//   }
 
//   throw new ApacuanaAPIError(
//     `Unsupported integration type: ${integrationType}`,
//     400,
//     "UNSUPPORTED_INTEGRATION_TYPE"
//   );
// };