@devly-cl/sii-client 0.4.3 → 0.4.4

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/README.md CHANGED
@@ -102,7 +102,7 @@ Para recibidas, llamar `getXmlFacturaRecibida({ issuerRut: proveedorRut, documen
102
102
 
103
103
  Admite `DTE`, `SetDTE` y `EnvioDTE`, con exactamente un documento 33/34, namespaces SII y codificación UTF-8 o ISO-8859-1. Límite 1 MiB, 10.000 nodos y 32 niveles. Rechaza DTD, entidades externas, documentos múltiples, identidad distinta, valores inválidos y XML mal formado. No consulta URLs incluidas en el documento.
104
104
 
105
- La descarga usa HTTP del facturador gratuito; no scrapea filas ni usa un navegador. Comprueba la empresa seleccionada en la sesión antes de descargar y vuelve a comprobar el emisor dentro del XML. Si SII requiere selección interactiva de empresa o CAPTCHA, devuelve error explícito. El RCV también contiene facturas emitidas por otros sistemas; no garantiza que sus XML estén disponibles en este servicio. Prueba real del SDK 0.3.0: 01-10-2026, login personal nuevo y descarga de 5.938 bytes ISO-8859-1, raíz `SetDTE`, una línea con cantidad/precio. La evidencia está en `docs/QA.md` del repositorio.
105
+ La descarga usa HTTP del facturador gratuito; no scrapea filas ni usa un navegador. Desde 0.4.4, si SII presenta el formulario de selección de empresas, envía un único POST a `mipeSelEmpresa.cgi` con `RUT_EMP` igual a `empresaRut` y el destino observado `DESDE_DONDE_URL=OPCION=2&TIPO=4`. No toma la primera empresa ni ejecuta JavaScript; valida el formulario HTML con un parser inerte, acotado a 1 MiB, y rechaza destinos distintos, empresas ausentes/deshabilitadas y selecciones ambiguas. El POST no se reintenta. Comprueba las cookies de empresa antes de descargar y los participantes dentro del XML. CAPTCHA o una selección no confirmada siguen produciendo un error explícito. El RCV también contiene facturas emitidas por otros sistemas; no garantiza que sus XML estén disponibles en este servicio. Prueba real del SDK 0.3.0: 01-10-2026, login personal nuevo y descarga de 5.938 bytes ISO-8859-1, raíz `SetDTE`, una línea con cantidad/precio. La evidencia está en `docs/QA.md` del repositorio.
106
106
 
107
107
  El consumidor debe cotejar además receptor, fecha y total con su referencia autorizada antes de guardar; almacenar el original, hash y fecha de obtención; y reutilizar lo guardado ante reintentos. No iniciar descargas desde SSR ni desde usuarios con permiso sólo de lectura.
108
108
 
@@ -141,7 +141,7 @@ try {
141
141
  - `SII_INVALID_RESPONSE`: identidad, fecha, monto, tipo, límite o cantidad de factura inválida; también conflicto de valores para una misma identidad.
142
142
  - `CAPTCHA_INTERACTION_REQUIRED`: SII solicita intervención de CAPTCHA (código 98); resolver interacción fuera del SDK.
143
143
  - `SII_XML_UNAVAILABLE`: el servicio no entregó un XML para esa factura.
144
- - `SII_XML_COMPANY_SELECTION_REQUIRED`: la empresa seleccionada en el facturador no coincide con la empresa de la instancia.
144
+ - `SII_XML_COMPANY_SELECTION_REQUIRED`: selección del facturador no confirmada. `diagnostics.reason` distingue empresa ausente/no autorizada (`COMPANY_NOT_AUTHORIZED`), formulario inválido (`INVALID_RESPONSE`) o falta de confirmación/cookies incorrectas (`COMPANY_SELECTION_REQUIRED`).
145
145
  - `SII_XML_INVALID` / `SII_XML_IDENTITY_MISMATCH`: XML inseguro/incorrecto o identidad distinta; no guardar.
146
146
 
147
147
  Timeout por solicitud: 15 segundos por defecto, rango 1 a 30 segundos. Login nunca se reintenta automáticamente. Lecturas conocidas admiten 0 a 2 reintentos por transporte o HTTP 429/502/503/504; por defecto, uno. TLS conserva validación normal. Sólo la selección del facturador sigue redirecciones HTTPS entre sus dos rutas conocidas en `www1.sii.cl`, hasta cinco solicitudes; otras redirecciones se rechazan.
@@ -4,6 +4,7 @@ exports.SiiClient = exports.SiiError = void 0;
4
4
  const node_crypto_1 = require("node:crypto");
5
5
  const promises_1 = require("node:timers/promises");
6
6
  const tough_cookie_1 = require("tough-cookie");
7
+ const parse5_1 = require("parse5");
7
8
  const rut_1 = require("../domain/rut");
8
9
  const sii_error_1 = require("../domain/sii-error");
9
10
  var sii_error_2 = require("../domain/sii-error");
@@ -19,6 +20,7 @@ const NAMESPACE = 'cl.sii.sdi.lob.diii.consdcv.data.api.interfaces.FacadeService
19
20
  const RETRYABLE = new Set([429, 502, 503, 504]);
20
21
  const STATES = new Set(['REGISTRO', 'PENDIENTE', 'NO_INCLUIR', 'RECLAMADO']);
21
22
  const FACTURADOR = 'https://www1.sii.cl/cgi-bin/Portal001/';
23
+ const FACTURADOR_DESTINATION = 'OPCION=2&TIPO=4';
22
24
  const ENDPOINT_STAGES = {
23
25
  'CAutInicio.cgi': 'AUTHENTICATION', 'aaSessionService/load': 'SESSION_CHECK', getDcvEmpresasAutorizadas: 'COMPANY_AUTHORIZATION',
24
26
  getDatosInicio: 'RCV_INITIALIZATION', getResumen: 'RCV_SUMMARY', getDetalleCompra: 'RCV_DETAIL', getDetalleVenta: 'RCV_DETAIL',
@@ -53,6 +55,52 @@ function assertPeriod(periodo) {
53
55
  if (typeof periodo !== 'string' || !/^\d{4}(0[1-9]|1[0-2])$/.test(periodo) || Number(periodo.slice(0, 4)) < 2017)
54
56
  throw new TypeError('Periodo inválido: YYYYMM');
55
57
  }
58
+ function htmlElements(root) {
59
+ const pending = [root];
60
+ const elements = [];
61
+ for (let node = pending.pop(); node; node = pending.pop()) {
62
+ if ('tagName' in node && node.namespaceURI === 'http://www.w3.org/1999/xhtml')
63
+ elements.push(node);
64
+ if ('childNodes' in node)
65
+ for (const child of node.childNodes)
66
+ pending.push(child);
67
+ }
68
+ return elements;
69
+ }
70
+ /** Read the observed selector inertly; never execute scripts or forward arbitrary form fields. */
71
+ function companySelection(page, company) {
72
+ const attr = (element, name) => element.attrs.find(a => a.name === name)?.value;
73
+ const forms = htmlElements((0, parse5_1.parse)(page)).filter(e => e.tagName === 'form' && attr(e, 'name') === 'fPrmEmpPOP');
74
+ const form = forms[0];
75
+ if (!form)
76
+ return undefined;
77
+ if (forms.length !== 1 || attr(form, 'method')?.toLowerCase() !== 'post')
78
+ return 'INVALID_RESPONSE';
79
+ try {
80
+ if (new URL(attr(form, 'action') ?? '', FACTURADOR).href !== `${FACTURADOR}mipeSelEmpresa.cgi`)
81
+ return 'INVALID_RESPONSE';
82
+ }
83
+ catch {
84
+ return 'INVALID_RESPONSE';
85
+ }
86
+ const controls = htmlElements(form);
87
+ const selects = controls.filter(e => e.tagName === 'select' && attr(e, 'name') === 'RUT_EMP');
88
+ const destinations = controls.filter(e => e.tagName === 'input' && attr(e, 'name') === 'DESDE_DONDE_URL');
89
+ const select = selects[0], destination = destinations[0];
90
+ if (selects.length !== 1 || destinations.length !== 1 || !select || !destination
91
+ || attr(select, 'disabled') !== undefined || attr(select, 'multiple') !== undefined || attr(select, 'form') !== undefined
92
+ || attr(destination, 'type')?.toLowerCase() !== 'hidden' || attr(destination, 'disabled') !== undefined || attr(destination, 'form') !== undefined
93
+ || attr(destination, 'value') !== FACTURADOR_DESTINATION)
94
+ return 'INVALID_RESPONSE';
95
+ const options = htmlElements(select).filter(e => e.tagName === 'option' && attr(e, 'value')?.replace(/\./g, '').toUpperCase() === company);
96
+ if (options.length > 1)
97
+ return 'INVALID_RESPONSE';
98
+ const option = options[0];
99
+ if (!option || attr(option, 'disabled') !== undefined
100
+ || (option.parentNode && 'tagName' in option.parentNode && option.parentNode.tagName === 'optgroup' && attr(option.parentNode, 'disabled') !== undefined))
101
+ return 'COMPANY_NOT_AUTHORIZED';
102
+ return new URLSearchParams({ DESDE_DONDE_URL: FACTURADOR_DESTINATION, RUT_EMP: company });
103
+ }
56
104
  /** Una instancia = una empresa y una sesión personal. Nunca comparte cookies. */
57
105
  class SiiClient {
58
106
  #jar = new tough_cookie_1.CookieJar();
@@ -216,17 +264,33 @@ class SiiClient {
216
264
  throw new TypeError('Identidad de factura inválida');
217
265
  if (!this.#facturadorReady) {
218
266
  let url = `${FACTURADOR}mipeSelEmpresa.cgi?DESDE_DONDE_URL=OPCION%3D2%26TIPO%3D4`;
267
+ let options = {}, submitted = false;
219
268
  for (let hop = 0;; hop++) {
220
- const response = await this.#request(url, {}, true, true);
269
+ const response = await this.#request(url, options, options.method !== 'POST', true);
221
270
  const location = response.headers.get('location');
222
- await response.body?.cancel();
223
271
  if (response.status >= 300 && response.status < 400) {
272
+ await response.body?.cancel();
224
273
  if (!location || hop >= 4)
225
274
  throw this.#failure('SII_XML_COMPANY_SELECTION_REQUIRED', endpointFor(url), 'COMPANY_SELECTION_REQUIRED', response);
226
275
  const next = new URL(location, url);
227
276
  if (next.origin !== 'https://www1.sii.cl' || !['mipeSelEmpresa.cgi', 'mipeLaunchPage.cgi'].some(path => next.pathname === `/cgi-bin/Portal001/${path}`))
228
277
  throw this.#failure('SESSION_OR_INTERACTIVE_AUTH_REQUIRED', endpointFor(url), 'SESSION_REQUIRED', response);
229
278
  url = next.href;
279
+ options = {};
280
+ continue;
281
+ }
282
+ const page = response.body ? Buffer.from(await this.#readBounded(response, endpointFor(url))).toString('latin1') : '';
283
+ if (/recaptcha-response|g-recaptcha|captcha/i.test(page))
284
+ throw this.#failure('CAPTCHA_INTERACTION_REQUIRED', endpointFor(url), 'CAPTCHA_REQUIRED', response);
285
+ const selection = companySelection(page, this.#company.formatted);
286
+ if (typeof selection === 'string')
287
+ throw this.#failure('SII_XML_COMPANY_SELECTION_REQUIRED', endpointFor(url), selection, response);
288
+ if (selection) {
289
+ if (submitted || hop >= 4)
290
+ throw this.#failure('SII_XML_COMPANY_SELECTION_REQUIRED', endpointFor(url), 'COMPANY_SELECTION_REQUIRED', response);
291
+ submitted = true;
292
+ url = `${FACTURADOR}mipeSelEmpresa.cgi`;
293
+ options = { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: selection.toString() };
230
294
  continue;
231
295
  }
232
296
  break;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@devly-cl/sii-client",
3
- "version": "0.4.3",
3
+ "version": "0.4.4",
4
4
  "description": "Cliente HTTP del SII para acceso personal, resúmenes RCV y facturas emitidas y recibidas, independiente de framework.",
5
5
  "license": "UNLICENSED",
6
6
  "type": "commonjs",
@@ -34,6 +34,7 @@
34
34
  "prepack": "npm run check"
35
35
  },
36
36
  "dependencies": {
37
+ "parse5": "7.3.0",
37
38
  "saxes": "^6.0.0",
38
39
  "tough-cookie": "6.0.2"
39
40
  },