UNPKG

ci-validation

Version:

🇺🇾 Complete TypeScript/JavaScript library for validating Uruguayan CI (Cédula de Identidad) with official algorithm and government service integration

295 lines 10.5 kB
import https from "https"; import { CiQueryResponse, ICiService } from "../interfaces/ICiService"; interface NewCiResponse { cedula: string; nombres: string; apellidos: string; fechaNacimiento: string; hasSession?: boolean; hasRefreshed?: boolean; tipoDocumento?: string; paisEmisor?: string; primerNombre?: string; segundoNombre?: string; primerApellido?: string; segundoApellido?: string; } export interface UrsecResponse { captchaSolveAttempts: number; response: string; isInRecord: boolean; error?: string; } interface CookieInfo { name: string; value: string; domain?: string; path?: string; } export declare class NewCiService implements ICiService { private readonly baseUrl; private readonly path; private readonly host; private readonly targetUrl; private readonly tramiteUrl; private static readonly outputDir; private cookies; sessionId: string; private email; private static sessionStorage; httpsAgent: https.Agent; timestamp: number; fields: { ci: { attId: string; frmId: string; }; email: { attId: string; frmId: string; }; }; introHeaders: { accept: string; "accept-encoding": string; "accept-language": string; connection: string; host: string; "sec-ch-ua": string; "sec-ch-ua-mobile": string; "sec-ch-ua-platform": string; "sec-fetch-dest": string; "sec-fetch-mode": string; "sec-fetch-site": string; "sec-fetch-user": string; "upgrade-insecure-requests": string; "user-agent": string; }; constructor(); /** * Initialize session storage based on environment */ static initializeSessionStorage(): Promise<void>; /** * Ensures the output directory exists */ private static ensureOutputDirectory; /** * Save session using the new storage system */ private saveSession; /** * Load session using the new storage system */ private loadSession; /** * Delete session using the new storage system */ private deleteSession; jsonToQueryString(jsonData: any): string; /** * Extrae y procesa los campos del formulario XML * @param xml - Contenido XML del formulario de datos personales * @returns Objeto con la información personal extraída */ getFields(xml: string): { cedula: string; nombres: string; apellidos: string; fechaNacimiento: string; tipoDocumento: string; paisEmisor: string; primerNombre: string; segundoNombre: string; primerApellido: string; segundoApellido: string; }; fireFinalEvent(tokenId: string, tabId: string, cookie?: string): Promise<{ hasSession: boolean; hasRefreshed: boolean; cedula: string; nombres: string; apellidos: string; fechaNacimiento: string; tipoDocumento: string; paisEmisor: string; primerNombre: string; segundoNombre: string; primerApellido: string; segundoApellido: string; }>; fireEvents3(tokenId: string, tabId: string): Promise<void>; fireEvents2(tokenId: string, tabId: string): Promise<void>; fireEvents(tokenId: string, tabId: string): Promise<void>; fireEventSingle(tokenId: string, tabId: string, frmId: string, attId: string, cookie?: string): Promise<string>; /** * Extrae proInstId y proEleInstId de una respuesta XML * @param xmlResponse - La respuesta XML que contiene la URL con los parámetros * @returns Objeto con proInstId y proEleInstId extraídos */ private extractProcessInstanceIds; /** * Convierte parámetros de URL a objeto JSON * @param urlParams - Cadena de parámetros URL (ej: "&tabId=123&tokenId=456" o "tabId=123&tokenId=456") * @returns Objeto JSON con los parámetros parseados */ private parseUrlParamsToJson; /** * Extrae específicamente tabId y tokenId de parámetros URL o URL completa * @param urlParams - Cadena de parámetros URL o URL completa * @returns Objeto con tabId y tokenId */ private extractTabAndTokenIds; /** * Extrae el valor de TAB_ID_REQUEST del HTML response o desde la función initPage * @param htmlContent - El contenido HTML donde buscar * @returns El valor de TAB_ID_REQUEST o null si no se encuentra */ private extractTabIdRequest; startCreationProcess(pathAction: string): Promise<void>; getDefaultHeaders(): { "Content-Type": string; Accept: string; Origin: string; Referer: string; "User-Agent": string; Cookie: string; }; redirect(redirectHtml: string): Promise<{ tabId: string; tokenId: string; }>; submitEntry(tokenId: string, tabId: string, attId: string, frmId: string, value: string): Promise<boolean>; fillEmail(tokenId: string, tabId: string): Promise<void>; queryCy(document: string, tokenId: string, tabId: string): Promise<boolean>; getCookieString(cookies: CookieInfo[]): string; generateTask(tabId: string, tokenId: string, formData: string): Promise<{ proInstId: string; proEleInstId: string; }>; /** * Extrae los valores del formulario desde el HTML usando Cheerio * @param htmlContent - El contenido HTML que contiene el formulario * @returns Objeto con los valores del formulario, URL de acción y datos codificados */ private extractFormData; /** * Extrae la URL del workArea desde el código JavaScript embebido en HTML * @param htmlContent - El contenido HTML que contiene el script con workArea * @returns La URL extraída o null si no se encuentra */ extractWorkAreaSrc(htmlContent: string): string | null; refreshCookies(proInstId: string, proEleInstId: string, tabId: string, tokenId: string): Promise<{ cookies: string; tabId: string; tokenId: string; }>; /** * Performs a GET request to the MEF portal and saves the response * This method uses the MEF "Consulta/Reclamación o Denuncia en Materia de Relaciones de Consumo" form * to access citizen information through the official government portal. * @param document - The document number to check * @param options - Optional parameters for the check * @param options.ignoreCache - If true, bypasses cache and performs a fresh check * @returns Promise<any> - The response data */ check(document: string, options?: { ignoreCache?: boolean; forceRefresh?: boolean; }, att?: number): Promise<NewCiResponse>; isServiceAvailable(): Promise<boolean>; queryCiInfo(ci: string): Promise<CiQueryResponse>; /** * Valida la configuración del servicio y maneja errores de inicialización */ private validateServiceConfiguration; /** * Maneja errores de forma centralizada y consistente */ private handleError; checkWithCookies(document: string, cookie: string, tokenId: string, tabId: string): Promise<{ hasSession: boolean; hasRefreshed: boolean; cedula: string; nombres: string; apellidos: string; fechaNacimiento: string; tipoDocumento: string; paisEmisor: string; primerNombre: string; segundoNombre: string; primerApellido: string; segundoApellido: string; }>; private extractCookiesStr; /** * Extracts cookies from the response headers * @param response - The axios response object * @returns Array of cookie information */ private extractCookies; /** * Extracts a specific attribute from cookie parts * @param cookieParts - Array of cookie parts * @param attribute - The attribute to extract * @returns The attribute value or undefined */ private extractCookieAttribute; fetchExtractedUrl(url: string, httpsAgent: https.Agent, cookieString: string): Promise<any>; private asyncCheckAction; /** * Checks if there are signable forms before proceeding to next step * @param refererUrl - The referer URL from the extracted iframe URL * @param tabId - The tab ID from previous requests * @param tokenId - The token ID from previous requests * @param cookies - Session cookies * @param httpsAgent - HTTPS agent for requests * @returns Promise<any> - The signable forms check response */ private checkSignableForms; /** * Solves CAPTCHA using OCR with serverless-compatible configuration * @param captchaUrl - The URL of the CAPTCHA image * @param cookies - Session cookies * @param httpsAgent - HTTPS agent for requests * @returns Promise<string> - The solved CAPTCHA text */ private solveCaptcha; /** * Cleans and normalizes CAPTCHA text recognition results * @param rawText - Raw text from OCR recognition * @returns Cleaned text suitable for CAPTCHA submission */ private cleanCaptchaText; /** * Generates a smarter CAPTCHA fallback with multiple strategies * @returns A better CAPTCHA guess based on common CAPTCHA patterns */ private generateSmartCaptchaFallback; /** * Generates a random string with specified length and character set * @param length - Length of the string to generate * @param chars - Character set to use * @returns Random string */ private generateRandomString; /** * Generates the CAPTCHA URL and name from the form data * @param tabId - The tab ID from previous requests * @returns Object containing CAPTCHA URL and name */ private generateCaptchaInfo; /** * Performs the final "go to next step" request after phone validation * @param refererUrl - The referer URL from the extracted iframe URL * @param tabId - The tab ID from previous requests * @param tokenId - The token ID from previous requests * @param cookies - Session cookies * @param httpsAgent - HTTPS agent for requests * @param phoneNumber - The phone number to validate * @returns Promise<any> - The next step response */ private performNextStepRequest; } export {}; //# sourceMappingURL=NewCiServiceDeprecated2.d.ts.map