All files / src/utils helpers.js

8.47% Statements 10/118
0% Branches 0/165
0% Functions 0/14
8.54% Lines 10/117

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                  2x   2x                                                                                                                                   2x                       2x                   2x                                           2x                                                                                                                                                                                                                                                                                           2x                                 2x                                                 2x                               2x                                                                                                                                                                
import CryptoJS from "crypto-js";
import { getCrypto } from "pkijs";
import {
  INTEGRATION_TYPE,
  STATUS_CERTIFICATE,
  VERIFICATION_STATUS,
} from "./constant";
import { ApacuanaAPIError } from "../errors/index";
 
const KEY_HEX = "dRgUkXp2s5v8y/B?";
 
const getCertificateStatus = (
  userData,
  certificateInDevice,
  integrationType
) => {
  if (!userData) {
    throw new ApacuanaAPIError(
      "El parámetro userData es requerido.",
      404,
      "INVALID_USER_DATA"
    );
  }
  if (typeof certificateInDevice !== "boolean") {
    throw new ApacuanaAPIError(
      "El parámetro certificateInDevice es requerido y debe ser un valor booleano.",
      404,
      "INVALID_CERTIFICATE_IN_DEVICE"
    );
  }
 
  if (integrationType === INTEGRATION_TYPE.ONBOARDING) {
    if (userData?.verificationstatus?.id !== VERIFICATION_STATUS.APPROVED)
      return STATUS_CERTIFICATE.request;
    if (
      !userData?.certifiedid &&
      userData?.requestscert?.requests.length === 0 &&
      !userData?.certificatestatus?.cangenerate
    )
      return STATUS_CERTIFICATE.request_cert;
 
    if (
      userData?.certifiedid &&
      !userData?.certificatestatus?.cangenerate &&
      !userData?.requestscert?.pending &&
      !certificateInDevice &&
      userData?.certificatestatus !== STATUS_CERTIFICATE.revoque
    )
      return STATUS_CERTIFICATE.certificate_another_device;
    if (userData?.requestscert?.pending)
      return STATUS_CERTIFICATE.request_revoque;
    if (
      !userData?.certificatestatus?.cangenerate &&
      userData?.certificatestatus === STATUS_CERTIFICATE.revoque
    )
      return STATUS_CERTIFICATE.revoque;
    if (userData?.certificatestatus?.cangenerate)
      return STATUS_CERTIFICATE.generate;
    if (userData?.certifiedid) return STATUS_CERTIFICATE.current;
 
    return STATUS_CERTIFICATE.revoque;
  }
  if (integrationType === INTEGRATION_TYPE.ONPREMISE) {
    throw new ApacuanaAPIError(
      "Getting certificate status is not supported for integration type: ONPREMISE",
      501,
      "NOT_IMPLEMENTED"
    );
  }
  throw new ApacuanaAPIError(
    `Unsupported integration type: ${integrationType}`,
    400,
    "UNSUPPORTED_INTEGRATION_TYPE"
  );
};
 
// Función para convertir ArrayBuffer a Base64
const arrayBufferToBase64 = (buffer) => {
  const binary = String.fromCharCode.apply(null, new Uint8Array(buffer));
  return window.btoa(binary);
};
 
async function exportPrivateKey(key) {
  const crypto = getCrypto();
  const exported = await crypto.exportKey("pkcs8", key);
  const exportablePrivateKey = new Uint8Array(exported);
  return arrayBufferToBase64(exportablePrivateKey);
}
 
const encryptedCsr = (csr, encryptKey = KEY_HEX) => {
  const body = {
    csr: CryptoJS.AES.encrypt(csr, encryptKey, {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7,
    }).toString(),
  };
  return body;
};
 
const createPayloadGetDigest = (signData) => {
  const formData = new FormData();
 
  Object.keys(signData).forEach((key) => {
    const value = signData[key];
    const isRNFile =
      value &&
      typeof value === "object" &&
      value.uri &&
      value.name &&
      value.type;
 
    if (key === "document" && (signData[key] instanceof File || isRNFile)) {
      // Append the file directly
      formData.append(key, signData[key]);
    } else if (key === "cert") {
      formData.append("publickey", signData[key]);
    }
  });
  return formData;
};
 
const validateOnBoardingSignerData = (signerData) => {
  // Create a copy of the original object to avoid modifying the function parameter
  const validatedSignerData = { ...signerData };
 
  if (
    !validatedSignerData.name ||
    typeof validatedSignerData.name !== "string"
  ) {
    throw new ApacuanaAPIError(
      'El campo "name" es requerido y debe ser una cadena de texto.',
      400,
      "INVALID_PARAMETER_FORMAT"
    );
  }
 
  if (
    !validatedSignerData.reference ||
    typeof validatedSignerData.reference !== "string" ||
    validatedSignerData.reference.trim() === ""
  ) {
    delete validatedSignerData.reference;
  }
  if (
    typeof File === "undefined" ||
    !validatedSignerData.file ||
    !(validatedSignerData.file instanceof File)
  ) {
    const value = validatedSignerData.file;
    const isRNFile =
      value &&
      typeof value === "object" &&
      value.uri &&
      value.name &&
      value.type;
 
    if (!isRNFile) {
      delete validatedSignerData.file;
    }
  }
 
  // Valida que solo uno de los dos campos exista después de la limpieza.
  if (validatedSignerData.reference && validatedSignerData.file) {
    throw new ApacuanaAPIError(
      "No se pueden proporcionar 'reference' y 'file' simultáneamente.",
      400,
      "INVALID_PARAMETER_FORMAT"
    );
  }
 
  if (!validatedSignerData.reference && !validatedSignerData.file) {
    throw new ApacuanaAPIError(
      "Se debe proporcionar un campo 'reference' o 'file' válido.",
      400,
      "INVALID_PARAMETER_FORMAT"
    );
  }
 
  const validDocTypes = ["V", "P", "E"];
  if (
    !validatedSignerData.typedoc ||
    !validDocTypes.includes(validatedSignerData.typedoc)
  ) {
    throw new ApacuanaAPIError(
      'El campo "typedoc" es requerido y debe ser uno de los siguientes valores: V, P, E.',
      400,
      "INVALID_PARAMETER_FORMAT"
    );
  }
 
  if (!validatedSignerData.doc || typeof validatedSignerData.doc !== "string") {
    throw new ApacuanaAPIError(
      'El campo "doc" es requerido y debe ser una cadena de texto.',
      400,
      "INVALID_PARAMETER_FORMAT"
    );
  }
 
  if (
    !Array.isArray(validatedSignerData.signature) ||
    validatedSignerData.signature.length === 0
  ) {
    throw new ApacuanaAPIError(
      'El campo "signature" es requerido y debe ser un array no vacío.',
      400,
      "INVALID_PARAMETER_FORMAT"
    );
  }
 
  validatedSignerData.signature.forEach((sig, index) => {
    if (!Number.isInteger(sig.page) || sig.page < 1) {
      throw new ApacuanaAPIError(
        `La página de la firma ${
          index + 1
        } debe ser un número entero positivo.`,
        400,
        "INVALID_PARAMETER_FORMAT"
      );
    }
 
    if (typeof sig.x !== "number" || sig.x < 0 || sig.x > 1) {
      throw new ApacuanaAPIError(
        `La coordenada X de la firma ${
          index + 1
        } debe ser un número entre 0 y 1.`,
        400,
        "INVALID_PARAMETER_FORMAT"
      );
    }
 
    if (typeof sig.y !== "number" || sig.y < 0 || sig.y > 1) {
      throw new ApacuanaAPIError(
        `La coordenada Y de la firma ${
          index + 1
        } debe ser un número entre 0 y 1.`,
        400,
        "INVALID_PARAMETER_FORMAT"
      );
    }
  });
 
  const formData = new FormData();
  Object.keys(validatedSignerData).forEach((key) => {
    const value = validatedSignerData[key];
    const isRNFile =
      value &&
      typeof value === "object" &&
      value.uri &&
      value.name &&
      value.type;
 
    if (key === "signature") {
      formData.append(key, JSON.stringify(validatedSignerData[key]));
    } else if (key === "file" || isRNFile) {
      formData.append("document", validatedSignerData[key]);
    } else if (validatedSignerData[key] !== undefined) {
      formData.append(key, validatedSignerData[key]);
    }
  });
 
  return formData;
};
 
const validateCsr = (encryptedCSR) => {
  if (
    !encryptedCSR ||
    typeof encryptedCSR !== "object" ||
    !encryptedCSR.csr ||
    typeof encryptedCSR.csr !== "string" ||
    encryptedCSR.csr.trim() === ""
  ) {
    throw new ApacuanaAPIError(
      'The "encryptedCSR" parameter is required and must be an object ' +
        'with a non-empty "csr" string property.',
      400, // Bad Request
      "INVALID_PARAMETER_FORMAT"
    );
  }
};
 
const validateGetDocsData = (data) => {
  if (
    !data ||
    typeof data.page === "undefined" ||
    typeof data.size === "undefined"
  ) {
    throw new ApacuanaAPIError(
      "Los parámetros 'page' y 'size' son requeridos.",
      400,
      "INVALID_PARAMETER"
    );
  }
 
  if (
    typeof data.status !== "undefined" &&
    ![-1, 0, 1, 2].includes(data.status)
  ) {
    throw new ApacuanaAPIError(
      "El parámetro 'status' no es válido. Los valores permitidos son: -1, 0, 1, 2.",
      400,
      "INVALID_PARAMETER"
    );
  }
};
 
const validateGetDigestData = (signData) => {
  if (
    !signData ||
    !signData.cert ||
    typeof signData.cert !== "string" ||
    !signData.signatureId ||
    typeof signData.signatureId !== "string"
  ) {
    throw new ApacuanaAPIError(
      "Los parámetros 'cert' y 'signatureId' son requeridos y deben ser cadenas de texto.",
      400,
      "INVALID_PARAMETER"
    );
  }
};
 
const validateOnBoardingSignDocumentData = (signData) => {
  if (!signData || typeof signData !== "object") {
    throw new ApacuanaAPIError(
      "Sign data is required and must be an object.",
      400,
      "INVALID_PARAMETER"
    );
  }
 
  const { signature, cert, signedDigest } = signData;
 
  if (!signature || typeof signature !== "object" || !signature.id) {
    throw new ApacuanaAPIError(
      "Signature object with an 'id' property is required.",
      400,
      "INVALID_PARAMETER"
    );
  }
 
  if (!Array.isArray(signature.positions)) {
    throw new ApacuanaAPIError(
      "Signature 'positions' must be an array.",
      400,
      "INVALID_PARAMETER"
    );
  }
 
  if (!cert || typeof cert !== "string") {
    throw new ApacuanaAPIError(
      "Certificate 'cert' is required and must be a string.",
      400,
      "INVALID_PARAMETER"
    );
  }
 
  if (!signedDigest || typeof signedDigest !== "string") {
    throw new ApacuanaAPIError(
      "Signed digest 'signedDigest' is required and must be a string.",
      400,
      "INVALID_PARAMETER"
    );
  }
 
  const formData = new FormData();
  formData.append(
    "positions",
    JSON.stringify(
      signature.positions.map((p) => ({
        x: p.x,
        y: p.y,
        page: p.page,
        status: 1,
      }))
    )
  );
  formData.append("publickey", cert);
  formData.append("signeddigest", signedDigest);
  const value = signData.document;
  const isRNFile =
    value && typeof value === "object" && value.uri && value.name && value.type;
 
  if (signData.document && (signData.document instanceof File || isRNFile)) {
    formData.append("document", signData.document);
  }
 
  return formData;
};
 
export default {
  getCertificateStatus,
  exportPrivateKey,
  arrayBufferToBase64,
  encryptedCsr,
  validateOnBoardingSignerData,
  validateCsr,
  validateGetDocsData,
  validateGetDigestData,
  validateOnBoardingSignDocumentData,
  createPayloadGetDigest,
};