fintecia 0.0.0-stage → 1.0.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 (74) hide show
  1. package/README.md +134 -2
  2. package/dist/auth/firebaseConfig.d.ts +40 -0
  3. package/dist/auth/firebaseConfig.js +54 -0
  4. package/dist/auth/firebaseConfig.js.map +1 -0
  5. package/dist/auth/session.d.ts +20 -0
  6. package/dist/auth/session.js +25 -0
  7. package/dist/auth/session.js.map +1 -0
  8. package/dist/fiel/decode.d.ts +10 -0
  9. package/dist/fiel/decode.js +17 -0
  10. package/dist/fiel/decode.js.map +1 -0
  11. package/dist/fiel/fiel.d.ts +35 -0
  12. package/dist/fiel/fiel.js +39 -0
  13. package/dist/fiel/fiel.js.map +1 -0
  14. package/dist/fiel/store.d.ts +33 -0
  15. package/dist/fiel/store.js +61 -0
  16. package/dist/fiel/store.js.map +1 -0
  17. package/dist/fin/read.d.ts +19 -0
  18. package/dist/fin/read.js +54 -0
  19. package/dist/fin/read.js.map +1 -0
  20. package/dist/glossary.d.ts +17 -0
  21. package/dist/glossary.js +160 -0
  22. package/dist/glossary.js.map +1 -0
  23. package/dist/handlers.d.ts +38 -0
  24. package/dist/handlers.js +302 -0
  25. package/dist/handlers.js.map +1 -0
  26. package/dist/index.d.ts +2 -0
  27. package/dist/index.js +121 -0
  28. package/dist/index.js.map +1 -0
  29. package/dist/keychain/keychain.d.ts +14 -0
  30. package/dist/keychain/keychain.js +150 -0
  31. package/dist/keychain/keychain.js.map +1 -0
  32. package/dist/onboard/cli.d.ts +1 -0
  33. package/dist/onboard/cli.js +13 -0
  34. package/dist/onboard/cli.js.map +1 -0
  35. package/dist/onboard/server.d.ts +8 -0
  36. package/dist/onboard/server.js +395 -0
  37. package/dist/onboard/server.js.map +1 -0
  38. package/dist/public/lookup.d.ts +35 -0
  39. package/dist/public/lookup.js +45 -0
  40. package/dist/public/lookup.js.map +1 -0
  41. package/dist/public/verify.d.ts +37 -0
  42. package/dist/public/verify.js +61 -0
  43. package/dist/public/verify.js.map +1 -0
  44. package/dist/sat/artifacts.d.ts +33 -0
  45. package/dist/sat/artifacts.js +69 -0
  46. package/dist/sat/artifacts.js.map +1 -0
  47. package/dist/sat/descarga.d.ts +44 -0
  48. package/dist/sat/descarga.js +108 -0
  49. package/dist/sat/descarga.js.map +1 -0
  50. package/dist/sat/fielProvider.d.ts +28 -0
  51. package/dist/sat/fielProvider.js +22 -0
  52. package/dist/sat/fielProvider.js.map +1 -0
  53. package/dist/sat/jobs.d.ts +47 -0
  54. package/dist/sat/jobs.js +40 -0
  55. package/dist/sat/jobs.js.map +1 -0
  56. package/dist/sat/keychainFielProvider.d.ts +17 -0
  57. package/dist/sat/keychainFielProvider.js +36 -0
  58. package/dist/sat/keychainFielProvider.js.map +1 -0
  59. package/dist/sat/parse.d.ts +33 -0
  60. package/dist/sat/parse.js +55 -0
  61. package/dist/sat/parse.js.map +1 -0
  62. package/dist/sat/upload.d.ts +42 -0
  63. package/dist/sat/upload.js +67 -0
  64. package/dist/sat/upload.js.map +1 -0
  65. package/dist/telemetry/client.d.ts +32 -0
  66. package/dist/telemetry/client.js +53 -0
  67. package/dist/telemetry/client.js.map +1 -0
  68. package/dist/telemetry/installId.d.ts +1 -0
  69. package/dist/telemetry/installId.js +36 -0
  70. package/dist/telemetry/installId.js.map +1 -0
  71. package/dist/tools.d.ts +24 -0
  72. package/dist/tools.js +189 -0
  73. package/dist/tools.js.map +1 -0
  74. package/package.json +64 -4
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Backend-backed lookups for the SAT public lists (69-B + art. 69).
3
+ *
4
+ * The lists live in the Fintecia backend (Firestore, refreshed monthly); the
5
+ * MCP is a thin client. These lookups REQUIRE a logged-in session (ID token)
6
+ * per the "auth, not e-firma" rule — there is NO local fixture in production
7
+ * (a fixture would answer with stale/sample data and never hit the backend).
8
+ */
9
+ export function normalizeRfc(rfc) {
10
+ return rfc.trim().toUpperCase();
11
+ }
12
+ export class PublicLookupClient {
13
+ config;
14
+ constructor(config) {
15
+ this.config = config;
16
+ }
17
+ fetch(input, init) {
18
+ const fn = this.config.fetchFn ?? fetch;
19
+ return fn(input, init);
20
+ }
21
+ async get(path, rfc) {
22
+ const idToken = await this.config.getAuthToken();
23
+ if (!idToken) {
24
+ throw new Error("Iniciá sesión primero (fintecia_login) antes de consultar listados del SAT.");
25
+ }
26
+ const res = await this.fetch(`${this.config.baseUrl}${path}?rfc=${encodeURIComponent(rfc)}`, {
27
+ method: "GET",
28
+ headers: { authorization: `Bearer ${idToken}` },
29
+ });
30
+ if (res.status === 429) {
31
+ throw new Error("Rate limit excedido, reintentá en unos segundos.");
32
+ }
33
+ if (!res.ok) {
34
+ throw new Error(`lookup ${path} failed: ${res.status}`);
35
+ }
36
+ return (await res.json());
37
+ }
38
+ async checkEfos(rfc) {
39
+ return this.get("/api/v1/public/efos", normalizeRfc(rfc));
40
+ }
41
+ async checkDebts(rfc) {
42
+ return this.get("/api/v1/public/debts", normalizeRfc(rfc));
43
+ }
44
+ }
45
+ //# sourceMappingURL=lookup.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lookup.js","sourceRoot":"","sources":["../../src/public/lookup.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,MAAM,UAAU,YAAY,CAAC,GAAW;IACtC,OAAO,GAAG,CAAC,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC;AAClC,CAAC;AAgBD,MAAM,OAAO,kBAAkB;IACA;IAA7B,YAA6B,MAAgC;QAAhC,WAAM,GAAN,MAAM,CAA0B;IAAG,CAAC;IAEzD,KAAK,CAAC,KAAa,EAAE,IAAkB;QAC7C,MAAM,EAAE,GAAG,IAAI,CAAC,MAAM,CAAC,OAAO,IAAI,KAAK,CAAC;QACxC,OAAO,EAAE,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;IACzB,CAAC;IAEO,KAAK,CAAC,GAAG,CACf,IAAY,EACZ,GAAW;QAEX,MAAM,OAAO,GAAG,MAAM,IAAI,CAAC,MAAM,CAAC,YAAY,EAAE,CAAC;QACjD,IAAI,CAAC,OAAO,EAAE,CAAC;YACb,MAAM,IAAI,KAAK,CACb,6EAA6E,CAC9E,CAAC;QACJ,CAAC;QACD,MAAM,GAAG,GAAG,MAAM,IAAI,CAAC,KAAK,CAC1B,GAAG,IAAI,CAAC,MAAM,CAAC,OAAO,GAAG,IAAI,QAAQ,kBAAkB,CAAC,GAAG,CAAC,EAAE,EAC9D;YACE,MAAM,EAAE,KAAK;YACb,OAAO,EAAE,EAAE,aAAa,EAAE,UAAU,OAAO,EAAE,EAAE;SAChD,CACF,CAAC;QACF,IAAI,GAAG,CAAC,MAAM,KAAK,GAAG,EAAE,CAAC;YACvB,MAAM,IAAI,KAAK,CAAC,kDAAkD,CAAC,CAAC;QACtE,CAAC;QACD,IAAI,CAAC,GAAG,CAAC,EAAE,EAAE,CAAC;YACZ,MAAM,IAAI,KAAK,CAAC,UAAU,IAAI,YAAY,GAAG,CAAC,MAAM,EAAE,CAAC,CAAC;QAC1D,CAAC;QACD,OAAO,CAAC,MAAM,GAAG,CAAC,IAAI,EAAE,CAAmD,CAAC;IAC9E,CAAC;IAED,KAAK,CAAC,SAAS,CAAC,GAAW;QACzB,OAAO,IAAI,CAAC,GAAG,CAAC,qBAAqB,EAAE,YAAY,CAAC,GAAG,CAAC,CAAC,CAAC;IAC5D,CAAC;IAED,KAAK,CAAC,UAAU,CAAC,GAAW;QAC1B,OAAO,IAAI,CAAC,GAAG,CAAC,sBAAsB,EAAE,YAAY,CAAC,GAAG,CAAC,CAAC,CAAC;IAC7D,CAAC;CACF"}
@@ -0,0 +1,37 @@
1
+ /**
2
+ * SAT ConsultaCFDIService — verifies a CFDI's status (vigente/cancelado/no
3
+ * encontrado) plus whether the emitter is on the 69-B/EFOS list
4
+ * (ValidacionEFOS). Public SOAP service, no auth, no FIEL.
5
+ *
6
+ * The QR on a CFDI encodes the 4 fields (emisor RFC, receptor RFC, total,
7
+ * UUID) as `?re=..&rr=..&tt=..&id=..` — the "expresión impresa".
8
+ */
9
+ export interface ConsultaInput {
10
+ uuid?: string;
11
+ emisorRfc?: string;
12
+ receptorRfc?: string;
13
+ total?: number;
14
+ xmlBase64?: string;
15
+ }
16
+ export interface ConsultaResult {
17
+ estado: string;
18
+ codigoEstatus: string;
19
+ esCancelable?: string;
20
+ estatusCancelacion?: string;
21
+ validacionEfos?: string;
22
+ }
23
+ /** Build the QR "expresión impresa" from the 4 fields. */
24
+ export declare function buildExpresionImpresa(i: {
25
+ emisorRfc: string;
26
+ receptorRfc: string;
27
+ total: number;
28
+ uuid: string;
29
+ }): string;
30
+ export declare function buildConsultaEnvelope(expresionImpresa: string): string;
31
+ /** Parse the SOAP response into a ConsultaResult (pure, testable). */
32
+ export declare function parseConsultaResponse(xml: string): ConsultaResult;
33
+ export declare class VerificationClient {
34
+ private readonly fetchFn;
35
+ constructor(fetchFn?: typeof fetch);
36
+ consulta(expresionImpresa: string): Promise<ConsultaResult>;
37
+ }
@@ -0,0 +1,61 @@
1
+ /**
2
+ * SAT ConsultaCFDIService — verifies a CFDI's status (vigente/cancelado/no
3
+ * encontrado) plus whether the emitter is on the 69-B/EFOS list
4
+ * (ValidacionEFOS). Public SOAP service, no auth, no FIEL.
5
+ *
6
+ * The QR on a CFDI encodes the 4 fields (emisor RFC, receptor RFC, total,
7
+ * UUID) as `?re=..&rr=..&tt=..&id=..` — the "expresión impresa".
8
+ */
9
+ const SERVICE_URL = "https://consultaqr.facturaelectronica.sat.gob.mx/ConsultaCFDIService.svc";
10
+ const SOAP_ACTION = "http://tempuri.org/IConsultaCFDIService/Consulta";
11
+ /** Build the QR "expresión impresa" from the 4 fields. */
12
+ export function buildExpresionImpresa(i) {
13
+ const tt = i.total.toFixed(6).replace(/0+$/, "").replace(/\.$/, "");
14
+ return `?re=${encodeURIComponent(i.emisorRfc)}&rr=${encodeURIComponent(i.receptorRfc)}&tt=${tt}&id=${encodeURIComponent(i.uuid)}`;
15
+ }
16
+ function escapeXml(s) {
17
+ return s
18
+ .replace(/&/g, "&amp;")
19
+ .replace(/</g, "&lt;")
20
+ .replace(/>/g, "&gt;")
21
+ .replace(/"/g, "&quot;")
22
+ .replace(/'/g, "&apos;");
23
+ }
24
+ export function buildConsultaEnvelope(expresionImpresa) {
25
+ return `<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><Consulta xmlns="http://tempuri.org/"><expresionImpresa>${escapeXml(expresionImpresa)}</expresionImpresa></Consulta></soap:Body></soap:Envelope>`;
26
+ }
27
+ function tag(xml, name) {
28
+ const m = xml.match(new RegExp(`<${name}[^>]*>([^<]*)</${name}>`, "i"));
29
+ return m ? m[1].trim() : undefined;
30
+ }
31
+ /** Parse the SOAP response into a ConsultaResult (pure, testable). */
32
+ export function parseConsultaResponse(xml) {
33
+ const codigoEstatus = tag(xml, "CodigoEstatus") ?? "";
34
+ const estado = tag(xml, "Estado") ?? "Error";
35
+ return {
36
+ estado,
37
+ codigoEstatus,
38
+ esCancelable: tag(xml, "EsCancelable"),
39
+ estatusCancelacion: tag(xml, "EstatusCancelacion"),
40
+ validacionEfos: tag(xml, "ValidacionEFOS"),
41
+ };
42
+ }
43
+ export class VerificationClient {
44
+ fetchFn;
45
+ constructor(fetchFn = fetch) {
46
+ this.fetchFn = fetchFn;
47
+ }
48
+ async consulta(expresionImpresa) {
49
+ const res = await this.fetchFn(SERVICE_URL, {
50
+ method: "POST",
51
+ headers: {
52
+ "content-type": "text/xml; charset=utf-8",
53
+ SOAPAction: SOAP_ACTION,
54
+ },
55
+ body: buildConsultaEnvelope(expresionImpresa),
56
+ });
57
+ const xml = await res.text();
58
+ return parseConsultaResponse(xml);
59
+ }
60
+ }
61
+ //# sourceMappingURL=verify.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"verify.js","sourceRoot":"","sources":["../../src/public/verify.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,M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GAAG,CAAC,GAAG,EAAE,eAAe,CAAC,IAAI,EAAE,CAAC;IACtD,MAAM,MAAM,GAAG,GAAG,CAAC,GAAG,EAAE,QAAQ,CAAC,IAAI,OAAO,CAAC;IAC7C,OAAO;QACL,MAAM;QACN,aAAa;QACb,YAAY,EAAE,GAAG,CAAC,GAAG,EAAE,cAAc,CAAC;QACtC,kBAAkB,EAAE,GAAG,CAAC,GAAG,EAAE,oBAAoB,CAAC;QAClD,cAAc,EAAE,GAAG,CAAC,GAAG,EAAE,gBAAgB,CAAC;KAC3C,CAAC;AACJ,CAAC;AAED,MAAM,OAAO,kBAAkB;IACA;IAA7B,YAA6B,UAAwB,KAAK;QAA7B,YAAO,GAAP,OAAO,CAAsB;IAAG,CAAC;IAE9D,KAAK,CAAC,QAAQ,CAAC,gBAAwB;QACrC,MAAM,GAAG,GAAG,MAAM,IAAI,CAAC,OAAO,CAAC,WAAW,EAAE;YAC1C,MAAM,EAAE,MAAM;YACd,OAAO,EAAE;gBACP,cAAc,EAAE,yBAAyB;gBACzC,UAAU,EAAE,WAAW;aACxB;YACD,IAAI,EAAE,qBAAqB,CAAC,gBAAgB,CAAC;SAC9C,CAAC,CAAC;QACH,MAAM,GAAG,GAAG,MAAM,GAAG,CAAC,IAAI,EAAE,CAAC;QAC7B,OAAO,qBAAqB,CAAC,GAAG,CAAC,CAAC;IACpC,CAAC;CACF"}
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Disk-backed persistence for downloaded SAT packages (CFDI zips).
3
+ *
4
+ * Why (L22 bug): `runDownloadJob` kept the zips ONLY in memory; a failed
5
+ * upload lost the real SAT download — and the SAT limits re-downloads. Each
6
+ * package is persisted to disk BEFORE upload, so a retry can re-upload without
7
+ * a new DescargaMasiva request.
8
+ *
9
+ * Security: owner-only (0700 dirs / 0600 files). The data is the user's own
10
+ * CFDI zips on their own machine (the e-firma already lives locally), but the
11
+ * files still must not be world-readable.
12
+ */
13
+ export interface DownloadArtifactStore {
14
+ /** Persist one downloaded package (base64 zip) and return its path. */
15
+ save(requestKey: string, tipo: string, index: number, zipBase64: string): Promise<string>;
16
+ /** True if persisted packages exist for this request + tipo. */
17
+ has(requestKey: string, tipo: string): Promise<boolean>;
18
+ /** Load persisted packages (base64) for this request + tipo, in order. */
19
+ load(requestKey: string, tipo: string): Promise<string[]>;
20
+ /** Delete every package under a request key (after a successful upload). */
21
+ remove(requestKey: string): Promise<void>;
22
+ }
23
+ /** Deterministic on-disk key for a download request (rfc + period). */
24
+ export declare function buildRequestKey(rfc: string, desde: string, hasta: string): string;
25
+ export declare class FileDownloadArtifactStore implements DownloadArtifactStore {
26
+ private readonly baseDir;
27
+ constructor(baseDir?: string);
28
+ private dirFor;
29
+ save(requestKey: string, tipo: string, index: number, zipBase64: string): Promise<string>;
30
+ has(requestKey: string, tipo: string): Promise<boolean>;
31
+ load(requestKey: string, tipo: string): Promise<string[]>;
32
+ remove(requestKey: string): Promise<void>;
33
+ }
@@ -0,0 +1,69 @@
1
+ import { promises as fs } from "node:fs";
2
+ import path from "node:path";
3
+ import os from "node:os";
4
+ // RFC charset (A-Z, digits, Ñ, &) + `_` + `-` (dates). No `.` or `/`, so a
5
+ // key can never traverse the base dir.
6
+ const SEGMENT_RE = /^[A-Za-z0-9Ñ&_\-]+$/;
7
+ function safe(segment) {
8
+ if (!SEGMENT_RE.test(segment)) {
9
+ throw new Error(`invalid artifact segment: ${segment}`);
10
+ }
11
+ return segment;
12
+ }
13
+ /** Deterministic on-disk key for a download request (rfc + period). */
14
+ export function buildRequestKey(rfc, desde, hasta) {
15
+ return `${rfc}_${desde}_${hasta}`;
16
+ }
17
+ export class FileDownloadArtifactStore {
18
+ baseDir;
19
+ constructor(baseDir = defaultBaseDir()) {
20
+ this.baseDir = baseDir;
21
+ }
22
+ dirFor(requestKey, tipo) {
23
+ return path.join(this.baseDir, safe(requestKey), safe(tipo));
24
+ }
25
+ async save(requestKey, tipo, index, zipBase64) {
26
+ const dir = this.dirFor(requestKey, tipo);
27
+ await fs.mkdir(dir, { recursive: true, mode: 0o700 });
28
+ const file = path.join(dir, `${String(index).padStart(3, "0")}.zip`);
29
+ await fs.writeFile(file, Buffer.from(zipBase64, "base64"), { mode: 0o600 });
30
+ return file;
31
+ }
32
+ async has(requestKey, tipo) {
33
+ const dir = this.dirFor(requestKey, tipo);
34
+ try {
35
+ const entries = await fs.readdir(dir);
36
+ return entries.some((e) => e.endsWith(".zip"));
37
+ }
38
+ catch {
39
+ return false;
40
+ }
41
+ }
42
+ async load(requestKey, tipo) {
43
+ const dir = this.dirFor(requestKey, tipo);
44
+ let entries;
45
+ try {
46
+ entries = await fs.readdir(dir);
47
+ }
48
+ catch {
49
+ return [];
50
+ }
51
+ const zips = entries.filter((e) => e.endsWith(".zip")).sort();
52
+ const result = [];
53
+ for (const entry of zips) {
54
+ const buf = await fs.readFile(path.join(dir, entry));
55
+ result.push(buf.toString("base64"));
56
+ }
57
+ return result;
58
+ }
59
+ async remove(requestKey) {
60
+ await fs.rm(path.join(this.baseDir, safe(requestKey)), {
61
+ recursive: true,
62
+ force: true,
63
+ });
64
+ }
65
+ }
66
+ function defaultBaseDir() {
67
+ return path.join(os.homedir(), ".fintecia", "mcp", "downloads");
68
+ }
69
+ //# sourceMappingURL=artifacts.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"artifacts.js","sourceRoot":"","sources":["../../src/sat/artifacts.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,IAAI,EAAE,EAAE,MAAM,SAAS,CAAC;AACzC,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,MAAM,SAAS,CAAC;AA0BzB,2EAA2E;AAC3E,uCAAuC;AACvC,MAAM,UAAU,GAAG,qBAAqB,CAAC;AAEzC,SAAS,IAAI,CAAC,OAAe;IAC3B,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC;QAC9B,MAAM,IAAI,KAAK,CAAC,6BAA6B,OAAO,EAAE,CAAC,C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,IAAI;SACZ,CAAC,CAAC;IACL,CAAC;CACF;AAED,SAAS,cAAc;IACrB,OAAO,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,OAAO,EAAE,EAAE,WAAW,EAAE,KAAK,EAAE,WAAW,CAAC,CAAC;AAClE,CAAC"}
@@ -0,0 +1,44 @@
1
+ import { Fiel, QueryParameters, Service } from "@nodecfdi/sat-ws-descarga-masiva";
2
+ import type { FielMaterial } from "./fielProvider.js";
3
+ import { type DescargaTipo, type DownloadPhase, type Period } from "./parse.js";
4
+ /**
5
+ * DescargaMasiva client (T2) — runs the 4-step flow against the SAT using the
6
+ * LOCAL e-firma (the key never leaves the machine).
7
+ *
8
+ * Autentica (token, short-lived — handled by the library during query)
9
+ * → Solicitud (SolicitaDescarga, emitidos/recibidos, per period)
10
+ * → Verificación (poll for package ids)
11
+ * → Descarga (zip of CFDI XMLs)
12
+ *
13
+ * nodecfdi (`@nodecfdi/sat-ws-descarga-masiva`) is ESM-only: this whole module
14
+ * is a nodecfdi seam, tested via `tsx` smoke (never jest). Pure parsing/arg
15
+ * validation lives in `parse.ts` and IS jest-tested.
16
+ */
17
+ export declare const DEFAULT_TIMEOUT_MS = 60000;
18
+ export declare const DEFAULT_POLL_INTERVAL_MS = 5000;
19
+ export declare const DEFAULT_MAX_POLL_ATTEMPTS = 120;
20
+ export interface DescargaClientOptions {
21
+ /** Per HTTP call timeout (ms) passed to nodecfdi's HttpsWebClient. */
22
+ timeoutMs?: number;
23
+ /** Delay between VerificaSolicitudDescarga polls. */
24
+ pollIntervalMs?: number;
25
+ /** Max verify attempts before giving up. */
26
+ maxPollAttempts?: number;
27
+ /** Progress callback (Autentica → Solicitud → Verificación → Descarga). */
28
+ onPhase?: (phase: DownloadPhase) => void;
29
+ }
30
+ export declare class DescargaClient {
31
+ private readonly options;
32
+ constructor(options?: DescargaClientOptions);
33
+ /**
34
+ * Run the full flow and return the downloaded package ZIPs (base64) — NOT
35
+ * extracted: the client uploads the ZIPs as-is and the backend reuses its
36
+ * own `ingestZipBuffer` (same as the web app's `processCfdiZip`). A period
37
+ * with no invoices yields an empty array, not an error.
38
+ */
39
+ descargar(material: FielMaterial, periodo: Period, tipo: DescargaTipo): Promise<string[]>;
40
+ }
41
+ /** Build a configured nodecfdi Service for a validated FIEL. */
42
+ export declare function createService(fiel: Fiel, timeoutMs: number): Service;
43
+ /** Build the SolicitaDescarga query parameters for a period + tipo. */
44
+ export declare function buildQueryParameters(periodo: Period, tipo: DescargaTipo): QueryParameters;
@@ -0,0 +1,108 @@
1
+ import { DateTimePeriod, DocumentStatus, DownloadType, FielRequestBuilder, HttpsWebClient, QueryParameters, RequestType, Service, } from "@nodecfdi/sat-ws-descarga-masiva";
2
+ import { inspectFiel } from "../fiel/fiel.js";
3
+ /**
4
+ * DescargaMasiva client (T2) — runs the 4-step flow against the SAT using the
5
+ * LOCAL e-firma (the key never leaves the machine).
6
+ *
7
+ * Autentica (token, short-lived — handled by the library during query)
8
+ * → Solicitud (SolicitaDescarga, emitidos/recibidos, per period)
9
+ * → Verificación (poll for package ids)
10
+ * → Descarga (zip of CFDI XMLs)
11
+ *
12
+ * nodecfdi (`@nodecfdi/sat-ws-descarga-masiva`) is ESM-only: this whole module
13
+ * is a nodecfdi seam, tested via `tsx` smoke (never jest). Pure parsing/arg
14
+ * validation lives in `parse.ts` and IS jest-tested.
15
+ */
16
+ export const DEFAULT_TIMEOUT_MS = 60_000;
17
+ export const DEFAULT_POLL_INTERVAL_MS = 5_000;
18
+ export const DEFAULT_MAX_POLL_ATTEMPTS = 120; // ~10 minutes at 5s
19
+ export class DescargaClient {
20
+ options;
21
+ constructor(options = {}) {
22
+ this.options = options;
23
+ }
24
+ /**
25
+ * Run the full flow and return the downloaded package ZIPs (base64) — NOT
26
+ * extracted: the client uploads the ZIPs as-is and the backend reuses its
27
+ * own `ingestZipBuffer` (same as the web app's `processCfdiZip`). A period
28
+ * with no invoices yields an empty array, not an error.
29
+ */
30
+ async descargar(material, periodo, tipo) {
31
+ const { fiel } = inspectFiel(material.cer, material.key, material.password);
32
+ const service = createService(fiel, this.options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
33
+ // Autentica + Solicitud (the library authenticates + signs inside query()).
34
+ this.options.onPhase?.("autentica");
35
+ const params = buildQueryParameters(periodo, tipo);
36
+ const queryResult = await service.query(params);
37
+ if (!queryResult.getStatus().isAccepted()) {
38
+ throw new Error(`SAT rechazó la solicitud: ${queryResult.getStatus().getMessage()}`);
39
+ }
40
+ const requestId = queryResult.getRequestId();
41
+ // Verificación — poll until the SAT marks the request Finished.
42
+ this.options.onPhase?.("verificacion");
43
+ const packageIds = await pollPackages(service, requestId, {
44
+ intervalMs: this.options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS,
45
+ maxAttempts: this.options.maxPollAttempts ?? DEFAULT_MAX_POLL_ATTEMPTS,
46
+ });
47
+ // Descarga — one zip per package id.
48
+ this.options.onPhase?.("descarga");
49
+ const zips = [];
50
+ for (const packageId of packageIds) {
51
+ const result = await service.download(packageId);
52
+ if (!result.getStatus().isAccepted()) {
53
+ throw new Error(`SAT rechazó la descarga del paquete ${packageId}: ${result.getStatus().getMessage()}`);
54
+ }
55
+ zips.push(result.getPackageContent());
56
+ }
57
+ return zips;
58
+ }
59
+ }
60
+ /** Build a configured nodecfdi Service for a validated FIEL. */
61
+ export function createService(fiel, timeoutMs) {
62
+ const requestBuilder = new FielRequestBuilder(fiel);
63
+ const webClient = new HttpsWebClient(undefined, undefined, timeoutMs);
64
+ return new Service(requestBuilder, webClient);
65
+ }
66
+ /** Build the SolicitaDescarga query parameters for a period + tipo. */
67
+ export function buildQueryParameters(periodo, tipo) {
68
+ const downloadType = new DownloadType(tipo === "emitidos" ? "issued" : "received");
69
+ const period = DateTimePeriod.createFromValues(`${periodo.desde} 00:00:00`, `${periodo.hasta} 23:59:59`);
70
+ const requestType = new RequestType("xml");
71
+ const parameters = QueryParameters.create(period, downloadType, requestType);
72
+ // SAT rule: received+XML queries must use DocumentStatus "active" (the
73
+ // default "Todos" is rejected for received XML downloads). Mirrors the
74
+ // Fintecia backend (`requestSubmitter.ts`).
75
+ if (tipo === "recibidos") {
76
+ parameters.withDocumentStatus(new DocumentStatus("active"));
77
+ }
78
+ return parameters;
79
+ }
80
+ async function pollPackages(service, requestId, opts) {
81
+ for (let attempt = 0; attempt < opts.maxAttempts; attempt++) {
82
+ const result = await service.verify(requestId);
83
+ if (!result.getStatus().isAccepted()) {
84
+ throw new Error(`SAT verificó con error: ${result.getStatus().getMessage()}`);
85
+ }
86
+ const statusRequest = result.getStatusRequest();
87
+ if (statusRequest.isTypeOf("Finished")) {
88
+ return result.getPackageIds();
89
+ }
90
+ // EmptyResult: the period has no invoices for this tipo — a NORMAL empty
91
+ // result, not an error (mirrors the backend's poller).
92
+ if (statusRequest.isTypeOf("Rejected") && result.getCodeRequest().getEntryId() === "EmptyResult") {
93
+ return [];
94
+ }
95
+ if (statusRequest.isTypeOf("Failure") ||
96
+ statusRequest.isTypeOf("Rejected") ||
97
+ statusRequest.isTypeOf("Expired")) {
98
+ throw new Error(`SAT rechazó la solicitud ${requestId}: ${statusRequest.getEntryId()}`);
99
+ }
100
+ // Accepted / InProgress → wait before the next verify.
101
+ await sleep(opts.intervalMs);
102
+ }
103
+ throw new Error(`SAT no terminó la solicitud ${requestId} tras ${opts.maxAttempts} intentos`);
104
+ }
105
+ function sleep(ms) {
106
+ return new Promise((resolve) => setTimeout(resolve, ms));
107
+ }
108
+ //# sourceMappingURL=descarga.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"descarga.js","sourceRoot":"","sources":["../../src/sat/descarga.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,cAAc,EACd,cAAc,EACd,YAAY,EAEZ,kBAAkB,EAClB,cAAc,EACd,eAAe,EACf,WAAW,EACX,OAAO,GACR,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAQ9C;;;;;;;;;;;;GAYG;AAEH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AC,UAAU,CAAC;YAClC,aAAa,CAAC,QAAQ,CAAC,SAAS,CAAC,EACjC,CAAC;YACD,MAAM,IAAI,KAAK,CAAC,4BAA4B,SAAS,KAAK,aAAa,CAAC,UAAU,EAAE,EAAE,CAAC,CAAC;QAC1F,CAAC;QACD,uDAAuD;QACvD,MAAM,KAAK,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;IAC/B,CAAC;IACD,MAAM,IAAI,KAAK,CACb,+BAA+B,SAAS,SAAS,IAAI,CAAC,WAAW,WAAW,CAC7E,CAAC;AACJ,CAAC;AAED,SAAS,KAAK,CAAC,EAAU;IACvB,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,CAAC;AAC3D,CAAC"}
@@ -0,0 +1,28 @@
1
+ /**
2
+ * FIEL material provider (T2).
3
+ *
4
+ * The FIEL password is held ONLY in the OS keychain (never persisted in the
5
+ * file store, never logged, never uploaded). `load(rfc)` returns the `.cer` +
6
+ * `.key` (password-encrypted PEM) plus the keychain-held password for this
7
+ * session. The key/password must never be logged nor leave the machine.
8
+ *
9
+ * T1b wires the OS keychain / onboarding behind this same port; T2 ships only
10
+ * the interface + a minimal in-memory implementation so the download flow is
11
+ * fully typed and testable.
12
+ */
13
+ export interface FielMaterial {
14
+ /** .cer content (public). */
15
+ cer: string;
16
+ /** .key content (private, password-encrypted PEM). */
17
+ key: string;
18
+ /** Password to decrypt the .key (re-entered per session, never persisted). */
19
+ password: string;
20
+ }
21
+ export interface FielProvider {
22
+ load(rfc: string): Promise<FielMaterial | null>;
23
+ }
24
+ export declare class InMemoryFielProvider implements FielProvider {
25
+ private readonly entries;
26
+ set(rfc: string, material: FielMaterial): void;
27
+ load(rfc: string): Promise<FielMaterial | null>;
28
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * FIEL material provider (T2).
3
+ *
4
+ * The FIEL password is held ONLY in the OS keychain (never persisted in the
5
+ * file store, never logged, never uploaded). `load(rfc)` returns the `.cer` +
6
+ * `.key` (password-encrypted PEM) plus the keychain-held password for this
7
+ * session. The key/password must never be logged nor leave the machine.
8
+ *
9
+ * T1b wires the OS keychain / onboarding behind this same port; T2 ships only
10
+ * the interface + a minimal in-memory implementation so the download flow is
11
+ * fully typed and testable.
12
+ */
13
+ export class InMemoryFielProvider {
14
+ entries = new Map();
15
+ set(rfc, material) {
16
+ this.entries.set(rfc.toUpperCase(), material);
17
+ }
18
+ async load(rfc) {
19
+ return this.entries.get(rfc.toUpperCase()) ?? null;
20
+ }
21
+ }
22
+ //# sourceMappingURL=fielProvider.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fielProvider.js","sourceRoot":"","sources":["../../src/sat/fielProvider.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAeH,MAAM,OAAO,oBAAoB;IACd,OAAO,GAAG,IAAI,GAAG,EAAwB,CAAC;IAE3D,GAAG,CAAC,GAAW,EAAE,QAAsB;QACrC,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,WAAW,EAAE,EAAE,QAAQ,CAAC,CAAC;IAChD,CAAC;IAED,KAAK,CAAC,IAAI,CAAC,GAAW;QACpB,OAAO,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,WAAW,EAAE,CAAC,IAAI,IAAI,CAAC;IACrD,CAAC;CACF"}
@@ -0,0 +1,47 @@
1
+ import type { DownloadPhase } from "./parse.js";
2
+ /**
3
+ * In-memory download job registry (T2).
4
+ *
5
+ * `cfdi_download` is async by contract: it starts a job and returns a job id;
6
+ * `cfdi_download_status` polls it. T2 keeps jobs in memory (a restart loses
7
+ * them); persistence is a later task. No nodecfdi here — jest-safe.
8
+ */
9
+ export type DownloadJobStatus = "running" | "completed" | "failed";
10
+ export interface DownloadJobResult {
11
+ accepted: number;
12
+ rejected: number;
13
+ cfdiCount: number;
14
+ }
15
+ export interface DownloadJob {
16
+ jobId: string;
17
+ status: DownloadJobStatus;
18
+ phase: DownloadPhase;
19
+ tipo: string;
20
+ desde: string;
21
+ hasta: string;
22
+ rfc: string;
23
+ startedAt: string;
24
+ finishedAt?: string;
25
+ result?: DownloadJobResult;
26
+ error?: string;
27
+ }
28
+ export interface NewJobInput {
29
+ tipo: string;
30
+ desde: string;
31
+ hasta: string;
32
+ rfc: string;
33
+ }
34
+ export interface JobStore {
35
+ create(input: NewJobInput): DownloadJob;
36
+ get(jobId: string): DownloadJob | undefined;
37
+ update(jobId: string, patch: Partial<DownloadJob>): DownloadJob | undefined;
38
+ lastCompleted(): DownloadJob | undefined;
39
+ }
40
+ export declare class InMemoryJobStore implements JobStore {
41
+ private readonly jobs;
42
+ private readonly order;
43
+ create(input: NewJobInput): DownloadJob;
44
+ get(jobId: string): DownloadJob | undefined;
45
+ update(jobId: string, patch: Partial<DownloadJob>): DownloadJob | undefined;
46
+ lastCompleted(): DownloadJob | undefined;
47
+ }
@@ -0,0 +1,40 @@
1
+ import { randomUUID } from "node:crypto";
2
+ export class InMemoryJobStore {
3
+ jobs = new Map();
4
+ order = [];
5
+ create(input) {
6
+ const job = {
7
+ jobId: randomUUID(),
8
+ status: "running",
9
+ phase: "autentica",
10
+ tipo: input.tipo,
11
+ desde: input.desde,
12
+ hasta: input.hasta,
13
+ rfc: input.rfc,
14
+ startedAt: new Date().toISOString(),
15
+ };
16
+ this.jobs.set(job.jobId, job);
17
+ this.order.push(job.jobId);
18
+ return job;
19
+ }
20
+ get(jobId) {
21
+ return this.jobs.get(jobId);
22
+ }
23
+ update(jobId, patch) {
24
+ const job = this.jobs.get(jobId);
25
+ if (!job)
26
+ return undefined;
27
+ const updated = { ...job, ...patch };
28
+ this.jobs.set(jobId, updated);
29
+ return updated;
30
+ }
31
+ lastCompleted() {
32
+ for (let i = this.order.length - 1; i >= 0; i--) {
33
+ const job = this.jobs.get(this.order[i]);
34
+ if (job?.status === "completed")
35
+ return job;
36
+ }
37
+ return undefined;
38
+ }
39
+ }
40
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jB,CAAC;IAED,aAAa;QACX,KAAK,IAAI,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC;YAChD,MAAM,GAAG,GAAG,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;YACzC,IAAI,GAAG,EAAE,MAAM,KAAK,WAAW;gBAAE,OAAO,GAAG,CAAC;QAC9C,CAAC;QACD,OAAO,SAAS,CAAC;IACnB,CAAC;CACF"}
@@ -0,0 +1,17 @@
1
+ import type { FielProvider, FielMaterial } from "./fielProvider.js";
2
+ import type { FielStore } from "../fiel/store.js";
3
+ import { type Keychain } from "../keychain/keychain.js";
4
+ /**
5
+ * Keychain-backed FielProvider: loads the .cer + .key from the FielStore and
6
+ * the password from the OS keychain. Returns null when the FIEL or the
7
+ * password is missing (the download then surfaces a clear "re-run onboarding"
8
+ * error rather than guessing).
9
+ */
10
+ export declare class KeychainFielProvider implements FielProvider {
11
+ private readonly fielStore;
12
+ private readonly keychain;
13
+ constructor(fielStore: FielStore, keychain: Keychain);
14
+ load(rfc: string): Promise<FielMaterial | null>;
15
+ }
16
+ /** Persist the FIEL password into the keychain (called during onboarding). */
17
+ export declare function saveFielPassword(keychain: Keychain, rfc: string, password: string): Promise<void>;
@@ -0,0 +1,36 @@
1
+ import { fielKeychainKey } from "../keychain/keychain.js";
2
+ /**
3
+ * Keychain-backed FielProvider: loads the .cer + .key from the FielStore and
4
+ * the password from the OS keychain. Returns null when the FIEL or the
5
+ * password is missing (the download then surfaces a clear "re-run onboarding"
6
+ * error rather than guessing).
7
+ */
8
+ export class KeychainFielProvider {
9
+ fielStore;
10
+ keychain;
11
+ constructor(fielStore, keychain) {
12
+ this.fielStore = fielStore;
13
+ this.keychain = keychain;
14
+ }
15
+ async load(rfc) {
16
+ const rfcUpper = rfc.toUpperCase();
17
+ const creds = await this.fielStore.load(rfcUpper);
18
+ if (!creds)
19
+ return null;
20
+ const password = await this.keychain.get(fielKeychainKey(rfcUpper));
21
+ if (password === null) {
22
+ // The FIEL is registered but its password is missing from the keyring:
23
+ // a recoverable state, distinct from "no FIEL at all". Surface an
24
+ // actionable hint instead of the misleading "not registered" error.
25
+ throw new Error(`La e-firma del RFC ${rfcUpper} está registrada, pero su contraseña no ` +
26
+ `está en el keyring. Volvé a correr fintecia_login para re-ingresarla ` +
27
+ `(vinculación T1b).`);
28
+ }
29
+ return { cer: creds.certPem, key: creds.keyPem, password };
30
+ }
31
+ }
32
+ /** Persist the FIEL password into the keychain (called during onboarding). */
33
+ export async function saveFielPassword(keychain, rfc, password) {
34
+ await keychain.set(fielKeychainKey(rfc), password);
35
+ }
36
+ //# sourceMappingURL=keychainFielProvider.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"keychainFielProvider.js","sourceRoot":"","sources":["../../src/sat/keychainFielProvider.ts"],"names":[],"mappings":"AAEA,OAAO,EAAiB,eAAe,EAAE,MAAM,yBAAyB,CAAC;AAEzE;;;;;GAKG;AACH,MAAM,OAAO,oBAAoB;IAEZ;IACA;IAFnB,YACmB,SAAoB,EACpB,QAAkB;QADlB,cAAS,GAAT,SAAS,CAAW;QACpB,aAAQ,GAAR,QAAQ,CAAU;IAClC,CAAC;IAEJ,KAAK,CAAC,IAAI,CAAC,GAAW;QACpB,MAAM,QAAQ,GAAG,GAAG,CAAC,WAAW,EAAE,CAAC;QACnC,MAAM,KAAK,GAAG,MAAM,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;QAClD,IAAI,CAAC,KAAK;YAAE,OAAO,IAAI,CAAC;QAExB,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,eAAe,CAAC,QAAQ,CAAC,CAAC,CAAC;QACpE,IAAI,QAAQ,KAAK,IAAI,EAAE,CAAC;YACtB,uEAAuE;YACvE,kEAAkE;YAClE,oEAAoE;YACpE,MAAM,IAAI,KAAK,CACb,sBAAsB,QAAQ,0CAA0C;gBACtE,uEAAuE;gBACvE,oBAAoB,CACvB,CAAC;QACJ,CAAC;QAED,OAAO,EAAE,GAAG,EAAE,KAAK,CAAC,OAAO,EAAE,GAAG,EAAE,KAAK,CAAC,MAAM,EAAE,QAAQ,EAAE,CAAC;IAC7D,CAAC;CACF;AAED,8EAA8E;AAC9E,MAAM,CAAC,KAAK,UAAU,gBAAgB,CACpC,QAAkB,EAClB,GAAW,EACX,QAAgB;IAEhB,MAAM,QAAQ,CAAC,GAAG,CAAC,eAAe,CAAC,GAAG,CAAC,EAAE,QAAQ,CAAC,CAAC;AACrD,CAAC"}