apacuana-sdk-core 0.3.0 → 0.5.0

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.
Files changed (42) hide show
  1. package/coverage/clover.xml +82 -82
  2. package/coverage/coverage-final.json +3 -3
  3. package/coverage/lcov-report/block-navigation.js +1 -1
  4. package/coverage/lcov-report/index.html +1 -1
  5. package/coverage/lcov-report/sorter.js +21 -7
  6. package/coverage/lcov-report/src/api/certs.js.html +2 -2
  7. package/coverage/lcov-report/src/api/index.html +1 -1
  8. package/coverage/lcov-report/src/api/revocations.js.html +12 -15
  9. package/coverage/lcov-report/src/api/signatures.js.html +320 -140
  10. package/coverage/lcov-report/src/api/users.js.html +1 -1
  11. package/coverage/lcov-report/src/config/index.html +1 -1
  12. package/coverage/lcov-report/src/config/index.js.html +1 -1
  13. package/coverage/lcov-report/src/errors/index.html +1 -1
  14. package/coverage/lcov-report/src/errors/index.js.html +1 -1
  15. package/coverage/lcov-report/src/index.html +1 -1
  16. package/coverage/lcov-report/src/index.js.html +6 -3
  17. package/coverage/lcov-report/src/utils/constant.js.html +1 -1
  18. package/coverage/lcov-report/src/utils/helpers.js.html +1 -1
  19. package/coverage/lcov-report/src/utils/httpClient.js.html +1 -1
  20. package/coverage/lcov-report/src/utils/index.html +1 -1
  21. package/coverage/lcov.info +137 -137
  22. package/dist/api/certs.d.ts +8 -0
  23. package/dist/api/revocations.d.ts +7 -0
  24. package/dist/api/signatures.d.ts +107 -0
  25. package/dist/api/users.d.ts +15 -0
  26. package/dist/config/index.d.ts +11 -0
  27. package/dist/errors/index.d.ts +10 -0
  28. package/dist/index.d.ts +25 -0
  29. package/dist/index.js +204 -97
  30. package/dist/index.js.map +1 -1
  31. package/dist/index.mjs +204 -97
  32. package/dist/index.mjs.map +1 -1
  33. package/dist/utils/constant.d.ts +18 -0
  34. package/dist/utils/helpers.d.ts +21 -0
  35. package/dist/utils/httpClient.d.ts +3 -0
  36. package/package.json +9 -4
  37. package/src/api/certs.js +1 -1
  38. package/src/api/revocations.js +10 -11
  39. package/src/api/signatures.js +156 -96
  40. package/src/index.js +2 -1
  41. package/tests/api/signatures.test.js +11 -4
  42. package/tsconfig.json +15 -0
@@ -0,0 +1,18 @@
1
+ export namespace STATUS_CERTIFICATE {
2
+ let request: string;
3
+ let generate: string;
4
+ let current: string;
5
+ let revoque: string;
6
+ let expire: string;
7
+ let request_revoque: string;
8
+ let certificate_another_device: string;
9
+ let sign_pending: string;
10
+ }
11
+ export namespace VERIFICATION_STATUS {
12
+ let IN_REGISTER: number;
13
+ let APPROVED: number;
14
+ }
15
+ export namespace INTEGRATION_TYPE {
16
+ let ONBOARDING: string;
17
+ let ONPREMISE: string;
18
+ }
@@ -0,0 +1,21 @@
1
+ declare namespace _default {
2
+ export { getCertificateStatus };
3
+ export { exportPrivateKey };
4
+ export { arrayBufferToBase64 };
5
+ export { encryptedCsr };
6
+ export { validateOnBoardingSignerData };
7
+ export { validateCsr };
8
+ export { validateGetDocsData };
9
+ export { validateGetDigestData };
10
+ }
11
+ export default _default;
12
+ declare function getCertificateStatus(userData: any, certificateInDevice: any): string;
13
+ declare function exportPrivateKey(key: any): Promise<string>;
14
+ declare function arrayBufferToBase64(buffer: any): string;
15
+ declare function encryptedCsr(csr: any, encryptKey?: string): {
16
+ csr: any;
17
+ };
18
+ declare function validateOnBoardingSignerData(signerData: any): void;
19
+ declare function validateCsr(csr: any): void;
20
+ declare function validateGetDocsData(data: any): void;
21
+ declare function validateGetDigestData(signData: any): void;
@@ -0,0 +1,3 @@
1
+ export function initHttpClient(): void;
2
+ export function setAuthToken(token: string): void;
3
+ export function httpRequest(path: string, data?: object, method?: string): Promise<object>;
package/package.json CHANGED
@@ -1,15 +1,18 @@
1
1
  {
2
2
  "name": "apacuana-sdk-core",
3
- "version": "0.3.0",
3
+ "version": "0.5.0",
4
4
  "description": "Core SDK para interacciones con las APIs de Apacuana.",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",
7
+ "types": "dist/index.d.ts",
7
8
  "type": "module",
8
9
  "scripts": {
10
+ "clean": "rimraf dist",
11
+ "clean-modules": "rimraf node_modules",
9
12
  "test": "jest",
10
13
  "lint": "eslint src/",
11
- "build": "rollup -c",
12
- "prepublishOnly": "npm test && npm run build",
14
+ "build": "npm run clean && tsc && rollup -c",
15
+ "prepublishOnly": "npm run validate",
13
16
  "validate": "npm run lint && npm test && npm run build"
14
17
  },
15
18
  "keywords": [
@@ -33,7 +36,9 @@
33
36
  "eslint-config-prettier": "^10.1.8",
34
37
  "eslint-plugin-import": "^2.29.1",
35
38
  "jest": "^29.7.0",
36
- "rollup": "^4.18.0"
39
+ "rollup": "^4.18.0",
40
+ "rimraf": "^5.0.7",
41
+ "typescript": "^5.4.5"
37
42
  },
38
43
  "engines": {
39
44
  "node": ">=14.0.0"
package/src/api/certs.js CHANGED
@@ -42,7 +42,7 @@ const generateCertOnPremise = async () => {
42
42
 
43
43
  /**
44
44
  * Generates a digital certificate.
45
- * @param {string} [csr] - Optional Certificate Signing Request (CSR).
45
+ * @param {string} [csr] - Certificate Signing Request (CSR).
46
46
  * @returns {Promise<{cert: string, success: boolean}>} Object with the generated certificate and a success indicator.
47
47
  * @throws {ApacuanaAPIError} If the CSR is invalid, if the API response does not contain the certificate, or if the integration type is not supported.
48
48
  * @throws {Error} If certificate generation fails for another reason.
@@ -1,6 +1,5 @@
1
- // src/api/revocations.js
2
- import { httpRequest } from '../utils/httpClient';
3
- import { ApacuanaAPIError } from '../errors/index';
1
+ import { httpRequest } from "../utils/httpClient";
2
+ import { ApacuanaAPIError } from "../errors/index";
4
3
 
5
4
  /**
6
5
  * Simula la solicitud de revocación de un certificado.
@@ -8,31 +7,31 @@ import { ApacuanaAPIError } from '../errors/index';
8
7
  * @returns {Promise<object>} Objeto con el estado de la solicitud de revocación.
9
8
  */
10
9
  const requestRevocation = async (reasonCode) => {
11
- console.log('-> Función \'requestRevocation\' ejecutada.');
12
- console.log('Parámetros recibidos para solicitud de revocación:', {
10
+ console.log("-> Función 'requestRevocation' ejecutada.");
11
+ console.log("Parámetros recibidos para solicitud de revocación:", {
13
12
  reasonCode,
14
13
  });
15
14
 
16
15
  if (!reasonCode) {
17
16
  throw new Error(
18
- 'ID de certificado y motivo son requeridos para requestRevocation.',
17
+ "ID de certificado y motivo son requeridos para requestRevocation."
19
18
  );
20
19
  }
21
20
 
22
21
  try {
23
22
  const response = await httpRequest(
24
- 'users/api/customers/requestcert',
23
+ "users/api/customers/requestcert",
25
24
  { reason: reasonCode },
26
- 'POST',
25
+ "POST"
27
26
  );
28
- console.log('Respuesta del servidor', response);
27
+ console.log("Respuesta del servidor", response);
29
28
  if (!response.success) {
30
29
  throw new ApacuanaAPIError(
31
- response.message || 'Error desconocido al solicitar revocación.',
30
+ response.message || "Error desconocido al solicitar revocación."
32
31
  );
33
32
  }
34
33
  return {
35
- revocationStatus: response.status || 'pending',
34
+ revocationStatus: response.status || "pending",
36
35
  requestId: response.id,
37
36
  };
38
37
  } catch (error) {
@@ -5,6 +5,66 @@ import { ApacuanaAPIError } from "../errors";
5
5
  import helpers from "../utils/helpers";
6
6
  import { INTEGRATION_TYPE } from "../utils/constant";
7
7
 
8
+ // =================================================================
9
+ // Type Definitions
10
+ // =================================================================
11
+
12
+ /**
13
+ * Define la estructura de un objeto Firmante.
14
+ * @typedef {object} Signer
15
+ * @property {string} name - Nombre completo del firmante.
16
+ * @property {string} email - Correo electrónico del firmante.
17
+ * @property {string} document - Documento de identidad del firmante.
18
+ */
19
+
20
+ /**
21
+ * Define la estructura de datos para añadir un firmante.
22
+ * @typedef {object} SignerData
23
+ * @property {string} docId - Identificador único del documento.
24
+ * @property {Signer} signer - Objeto con la información del firmante.
25
+ */
26
+
27
+ /**
28
+ * Define la estructura de la respuesta al añadir un firmante.
29
+ * @typedef {object} AddSignerResponse
30
+ * @property {string} signer - Identificador de confirmación del firmante añadido.
31
+ * @property {boolean} success - Indica si la operación fue exitosa.
32
+ */
33
+
34
+ /**
35
+ * Define la estructura de datos para obtener el digest de un documento.
36
+ * @typedef {object} GetDigestData
37
+ * @property {string} cert - Certificado del firmante en formato base64.
38
+ * @property {string} signatureId - Identificador único del proceso de firma.
39
+ */
40
+
41
+ /**
42
+ * Define la estructura de la respuesta al obtener el digest.
43
+ * @typedef {object} GetDigestResponse
44
+ * @property {string} digest - El digest del documento que se va a firmar.
45
+ * @property {boolean} success - Indica si la operación fue exitosa.
46
+ */
47
+
48
+ /**
49
+ * Define la estructura de los parámetros para obtener documentos.
50
+ * @typedef {object} GetDocsParams
51
+ * @property {number} page - Número de página para la paginación.
52
+ * @property {number} size - Cantidad de registros por página.
53
+ * @property {string} [status] - (Opcional) Estado para filtrar los documentos.
54
+ */
55
+
56
+ /**
57
+ * Define la estructura de la respuesta al obtener documentos.
58
+ * @typedef {object} GetDocsResponse
59
+ * @property {number} totalRecords - El número total de registros encontrados.
60
+ * @property {Array<object>} records - Un arreglo con los registros de los documentos.
61
+ * @property {boolean} success - Indica si la operación fue exitosa.
62
+ */
63
+
64
+ // =================================================================
65
+ // Internal Functions
66
+ // =================================================================
67
+
8
68
  const signDocumentOnBoarding = async () => {
9
69
  throw new ApacuanaAPIError(
10
70
  "Document signing is not supported for integration type: ONBOARDING",
@@ -21,30 +81,6 @@ const signDocumentOnPremise = async () => {
21
81
  );
22
82
  };
23
83
 
24
- /**
25
- * Signs a PDF document with a digital certificate.
26
- * @param {object} data - Data for the signature. For 'on-boarding', it must contain {documentData, signatureData}. For 'on-premise', it must contain {signature, cert, privateKey}.
27
- * @returns {Promise<{digest: string}>} Object with the document's digest.
28
- * @throws {ApacuanaAPIError} If the integration type is not supported or the function is not implemented for the integration type.
29
- */
30
- export const signDocument = async () => {
31
- const { integrationType } = getConfig();
32
-
33
- if (integrationType === INTEGRATION_TYPE.ONBOARDING) {
34
- return signDocumentOnBoarding();
35
- }
36
-
37
- if (integrationType === INTEGRATION_TYPE.ONPREMISE) {
38
- return signDocumentOnPremise();
39
- }
40
-
41
- throw new ApacuanaAPIError(
42
- `Unsupported integration type: ${integrationType}`,
43
- 400,
44
- "UNSUPPORTED_INTEGRATION_TYPE"
45
- );
46
- };
47
-
48
84
  const getDigestToSignOnBoarding = async (signData) => {
49
85
  try {
50
86
  const response = await httpRequest(
@@ -82,45 +118,16 @@ const getDigestToSignOnPremise = async () => {
82
118
  );
83
119
  };
84
120
 
85
- /**
86
- * Gets the digest of a document to be signed.
87
- * @param {object} signData - Data for the signature. Must contain { cert, signatureId }.
88
- * @returns {Promise<{digest: string, success: boolean}>} Object with the document's digest.
89
- * @throws {ApacuanaAPIError} If the input data is invalid, if the API call fails, or if the integration type is not supported.
90
- */
91
- export const getDigest = async (signData) => {
92
- helpers.validateGetDigestData(signData);
93
-
94
- const { integrationType } = getConfig();
95
-
96
- if (integrationType === INTEGRATION_TYPE.ONBOARDING) {
97
- return getDigestToSignOnBoarding(signData);
98
- }
99
-
100
- if (integrationType === INTEGRATION_TYPE.ONPREMISE) {
101
- return getDigestToSignOnPremise();
102
- }
103
-
104
- throw new ApacuanaAPIError(
105
- `Document retrieval is not supported for an unknown integration type: ${integrationType}`,
106
- 501,
107
- "NOT_IMPLEMENTED"
108
- );
109
- };
110
-
111
121
  const addSignerOnBoarding = async (signerData) => {
112
122
  helpers.validateOnBoardingSignerData(signerData);
113
123
  try {
114
- // Current httpRequest logic is moved here
115
124
  await httpRequest("services/api/documents/signing", signerData, "POST");
116
125
  return { signer: signerData.typedoc + signerData.doc, success: true };
117
126
  } catch (error) {
118
127
  if (error instanceof ApacuanaAPIError) {
119
128
  throw error;
120
129
  }
121
- throw new Error(
122
- `Failed to add signer in On-Boarding: ${error.message}`
123
- );
130
+ throw new Error(`Failed to add signer in On-Boarding: ${error.message}`);
124
131
  }
125
132
  };
126
133
 
@@ -132,45 +139,9 @@ const addSignerOnPremise = async () => {
132
139
  );
133
140
  };
134
141
 
135
- /**
136
- * Adds a signer to a document, handling different integration types.
137
- * @param {object} signerData - Data of the signer to be added.
138
- * @returns {Promise<{signer: string, success: boolean}>} Object with the result of adding the signer.
139
- * @throws {ApacuanaAPIError} If the signer data is invalid, if the API call fails, or if the integration type is not supported.
140
- */
141
- export const addSigner = async (signerData) => {
142
- if (
143
- !signerData ||
144
- typeof signerData !== "object" ||
145
- Object.keys(signerData).length === 0
146
- ) {
147
- throw new ApacuanaAPIError(
148
- "Signer data (signerData) is required and must be a non-empty object.",
149
- 400,
150
- "INVALID_PARAMETER"
151
- );
152
- }
153
-
154
- const { integrationType } = getConfig();
155
-
156
- if (integrationType === INTEGRATION_TYPE.ONBOARDING) {
157
- return addSignerOnBoarding(signerData);
158
- }
159
-
160
- if (integrationType === INTEGRATION_TYPE.ONPREMISE) {
161
- return addSignerOnPremise(signerData);
162
- }
163
-
164
- throw new ApacuanaAPIError(
165
- `Unsupported integration type: ${integrationType}`,
166
- 400,
167
- "UNSUPPORTED_INTEGRATION_TYPE"
168
- );
169
- };
170
-
171
142
  const getDocsOnPremise = async () => {
172
143
  throw new ApacuanaAPIError(
173
- "Document retrieval is not supported for integration type: ONBOARDING",
144
+ "Document retrieval is not supported for integration type: ONPREMISE",
174
145
  501,
175
146
  "NOT_IMPLEMENTED"
176
147
  );
@@ -209,16 +180,105 @@ const getDocsOnBoarding = async (data) => {
209
180
  throw error;
210
181
  }
211
182
  throw new ApacuanaAPIError(
212
- `Failed to get document list (on-premise): ${error.message}`
183
+ `Failed to get document list (on-boarding): ${error.message}`
213
184
  );
214
185
  }
215
186
  };
216
187
 
188
+ // =================================================================
189
+ // Exported Functions
190
+ // =================================================================
191
+
192
+ /**
193
+ * Firma un documento PDF con un certificado digital.
194
+ * NOTA: Esta función no está implementada actualmente para ningún tipo de integración.
195
+ * @returns {Promise<object>}
196
+ * @throws {ApacuanaAPIError} Arroja un error 'NOT_IMPLEMENTED' para cualquier tipo de integración.
197
+ */
198
+ export const signDocument = async () => {
199
+ const { integrationType } = getConfig();
200
+
201
+ if (integrationType === INTEGRATION_TYPE.ONBOARDING) {
202
+ return signDocumentOnBoarding();
203
+ }
204
+
205
+ if (integrationType === INTEGRATION_TYPE.ONPREMISE) {
206
+ return signDocumentOnPremise();
207
+ }
208
+
209
+ throw new ApacuanaAPIError(
210
+ `Unsupported integration type: ${integrationType}`,
211
+ 400,
212
+ "UNSUPPORTED_INTEGRATION_TYPE"
213
+ );
214
+ };
215
+
216
+ /**
217
+ * Obtiene el digest de un documento para ser firmado.
218
+ * @param {GetDigestData} signData - Datos requeridos para obtener el digest.
219
+ * @returns {Promise<GetDigestResponse>} Una promesa que resuelve a un objeto con el digest del documento.
220
+ * @throws {ApacuanaAPIError} Si los datos de entrada son inválidos, la llamada a la API falla, o el tipo de integración no es soportado.
221
+ */
222
+ export const getDigest = async (signData) => {
223
+ helpers.validateGetDigestData(signData);
224
+
225
+ const { integrationType } = getConfig();
226
+
227
+ if (integrationType === INTEGRATION_TYPE.ONBOARDING) {
228
+ return getDigestToSignOnBoarding(signData);
229
+ }
230
+
231
+ if (integrationType === INTEGRATION_TYPE.ONPREMISE) {
232
+ return getDigestToSignOnPremise();
233
+ }
234
+
235
+ throw new ApacuanaAPIError(
236
+ `Document retrieval is not supported for an unknown integration type: ${integrationType}`,
237
+ 501,
238
+ "NOT_IMPLEMENTED"
239
+ );
240
+ };
241
+
242
+ /**
243
+ * Añade un firmante a un documento.
244
+ * @param {SignerData} signerData - Los datos del firmante que se va a añadir.
245
+ * @returns {Promise<AddSignerResponse>} Una promesa que resuelve a un objeto con el resultado de la operación.
246
+ * @throws {ApacuanaAPIError} Si los datos del firmante son inválidos, la llamada a la API falla, o el tipo de integración no es soportado.
247
+ */
248
+ export const addSigner = async (signerData) => {
249
+ if (
250
+ !signerData ||
251
+ typeof signerData !== "object" ||
252
+ Object.keys(signerData).length === 0
253
+ ) {
254
+ throw new ApacuanaAPIError(
255
+ "Signer data (signerData) is required and must be a non-empty object.",
256
+ 400,
257
+ "INVALID_PARAMETER"
258
+ );
259
+ }
260
+ const { integrationType } = getConfig();
261
+
262
+ if (integrationType === INTEGRATION_TYPE.ONBOARDING) {
263
+ return addSignerOnBoarding(signerData);
264
+ }
265
+
266
+ if (integrationType === INTEGRATION_TYPE.ONPREMISE) {
267
+ return addSignerOnPremise();
268
+ }
269
+
270
+ throw new ApacuanaAPIError(
271
+ `Unsupported integration type: ${integrationType}`,
272
+ 400,
273
+ "UNSUPPORTED_INTEGRATION_TYPE"
274
+ );
275
+ };
276
+
217
277
  /**
218
- * Gets a list of documents.
219
- * @param {object} data - Object with pagination parameters. Must contain {page, size}.
220
- * @returns {Promise<{totalRecords: number, records:any[], success: boolean}>} Object with the list of documents.
221
- * @throws {ApacuanaAPIError} If pagination parameters are invalid, if 'customerId' is not configured, if the API call fails, or if the integration type is not supported.
278
+ * Obtiene una lista de documentos basada en los filtros especificados.
279
+ * @param {GetDocsParams} data - Objeto con parámetros de paginación y filtros.
280
+ * @returns {Promise<GetDocsResponse>} Una promesa que resuelve a un objeto con la lista de documentos.
281
+ * @throws {ApacuanaAPIError} Si los parámetros de paginación son inválidos, 'customerId' no está configurado, la llamada a la API falla, o el tipo de integración no es soportado.
222
282
  */
223
283
  export const getDocs = async (data) => {
224
284
  helpers.validateGetDocsData(data);
package/src/index.js CHANGED
@@ -2,7 +2,7 @@ import { setConfig, getConfig } from "./config/index";
2
2
  import { initHttpClient, setAuthToken } from "./utils/httpClient";
3
3
  import getCustomer from "./api/users";
4
4
  import requestRevocation from "./api/revocations";
5
- import { getCertStatus } from "./api/certs";
5
+ import { generateCert, getCertStatus } from "./api/certs";
6
6
  import { addSigner, getDocs } from "./api/signatures";
7
7
 
8
8
  const apacuana = {
@@ -65,6 +65,7 @@ const apacuana = {
65
65
  getCustomer,
66
66
  addSigner,
67
67
  getDocs,
68
+ generateCert,
68
69
  };
69
70
 
70
71
  export default apacuana;
@@ -1,7 +1,12 @@
1
1
  import { getConfig } from "../../src/config";
2
2
  import { httpRequest } from "../../src/utils/httpClient";
3
3
  import { ApacuanaAPIError } from "../../src/errors";
4
- import { addSigner, getDocs, getDigest, signDocument } from "../../src/api/signatures";
4
+ import {
5
+ addSigner,
6
+ getDocs,
7
+ getDigest,
8
+ signDocument,
9
+ } from "../../src/api/signatures";
5
10
  import helpers from "../../src/utils/helpers";
6
11
  import { INTEGRATION_TYPE } from "../../src/utils/constant";
7
12
 
@@ -23,7 +28,9 @@ describe("API - Signatures", () => {
23
28
 
24
29
  describe("addSigner", () => {
25
30
  it("should call addSignerOnBoarding for ONBOARDING integration", async () => {
26
- getConfig.mockReturnValue({ integrationType: INTEGRATION_TYPE.ONBOARDING });
31
+ getConfig.mockReturnValue({
32
+ integrationType: INTEGRATION_TYPE.ONBOARDING,
33
+ });
27
34
  const signerData = { typedoc: "V", doc: "12345678" };
28
35
  httpRequest.mockResolvedValue({ success: true });
29
36
 
@@ -106,7 +113,7 @@ describe("API - Signatures", () => {
106
113
  httpRequest.mockResolvedValue({ docs: [] });
107
114
 
108
115
  await expect(getDocs(paginationData)).rejects.toThrow(
109
- "Document retrieval is not supported for integration type: ONBOARDING"
116
+ "Document retrieval is not supported for integration type: ONPREMISE"
110
117
  );
111
118
  });
112
119
 
@@ -151,4 +158,4 @@ describe("API - Signatures", () => {
151
158
  );
152
159
  });
153
160
  });
154
- });
161
+ });
package/tsconfig.json ADDED
@@ -0,0 +1,15 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "es2020",
4
+ "module": "esnext",
5
+ "allowJs": true,
6
+ "declaration": true,
7
+ "emitDeclarationOnly": true,
8
+ "outDir": "./dist",
9
+ "strict": true,
10
+ "moduleResolution": "node",
11
+ "esModuleInterop": true
12
+ },
13
+ "include": ["src"],
14
+ "exclude": ["node_modules", "dist", "tests"]
15
+ }