diff --git a/.gitignore b/.gitignore index 5b0b043..480539c 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,4 @@ config/config.php +config/token.php +DatosPdf.txt .DS_Store diff --git a/README.md b/README.md index b6a659e..69695af 100644 --- a/README.md +++ b/README.md @@ -72,9 +72,11 @@ Edita `config/config.php`: - **`db`**: host, nombre de base, usuario y contraseña. - **`app.public_url`**: URL pública del sitio (para enlaces y QR). -- **API DC3 (opcional):** - `export CERTIMINE_DC3_TOKEN='tu_token'` - o rellena `penasquito_dc3.static_token` (no subas secretos al repositorio). +- **API DC3 — token (orden):** + 1) `CERTIMINE_DC3_TOKEN` + 2) `penasquito_dc3.static_token` en `config.php` + 3) **`config/token.php`** (copia de `config/token.example.php`; **no se sube a git**). + Documentación del proceso sin secretos: **`docs/DatosPdf.example.txt`**. Tu copia local **`DatosPdf.txt`** puede quedar fuera de git (véase `.gitignore`). - **`mobiliseme.mock`:** `true` para demo sin API legacy JWT; `false` solo si usas otro backend configurado en `mobiliseme`. ### 3. Servidor de desarrollo diff --git a/config/config.example.php b/config/config.example.php index a68328e..1ba182b 100644 --- a/config/config.example.php +++ b/config/config.example.php @@ -2,7 +2,7 @@ /** * Copiar a config.php y ajustar. config.php está en .gitignore. * - * Token DC3: preferir variable de entorno CERTIMINE_DC3_TOKEN (no commitear el valor real). + * Token DC3: ver orden en PenasquitoDc3Api::resolvedToken() (env → config → config/token.php). */ return [ 'app' => [ @@ -12,6 +12,7 @@ return [ 'timezone' => 'America/Mexico_City', 'qr_secret' => 'change-me-qr-hmac', 'qr_enforce' => false, + 'debug' => false, ], 'db' => [ 'host' => '127.0.0.1', diff --git a/config/token.example.php b/config/token.example.php new file mode 100644 index 0000000..87bcd03 --- /dev/null +++ b/config/token.example.php @@ -0,0 +1,13 @@ + '', +]; diff --git a/DatosPdf.txt b/docs/DatosPdf.example.txt similarity index 99% rename from DatosPdf.txt rename to docs/DatosPdf.example.txt index a68fbb2..fe1891a 100644 --- a/DatosPdf.txt +++ b/docs/DatosPdf.example.txt @@ -13,7 +13,7 @@ APIs. 1.1 Autenticación Todas las peticiones requieren un header de autorización con un token estático que se entrega aparte por canal privado: -TOKEN 43eff45fff1422d21d371e3d72d76ae56f435a2c +TOKEN Authorization: Token Las peticiones sin este header o con un token inválido son rechazadas con HTTP 401. 1.2 Endpoint 1 — Crear solicitud de búsqueda diff --git a/docs/mobiliseme-api.md b/docs/mobiliseme-api.md index 31f23e8..bc25606 100644 --- a/docs/mobiliseme-api.md +++ b/docs/mobiliseme-api.md @@ -1,6 +1,6 @@ # API DC3 Peñasquito (Wotbi) — CertiMine -Fuente detallada del flujo de scraping en Mobilise-Me: ver [DatosPdf.txt](../DatosPdf.txt) en el repositorio (texto extraído manualmente del PDF). +Fuente detallada del flujo: copia de trabajo sin secretos en [DatosPdf.example.txt](DatosPdf.example.txt). El archivo local **DatosPdf.txt** (si lo tienes) está en `.gitignore` y no debe contener el token en repositorios compartidos; use **`config/token.php`** o **`CERTIMINE_DC3_TOKEN`**. ## Autenticación @@ -12,11 +12,17 @@ Authorization: Token Sin cabecera válida → **HTTP 401**. -En CertiMine configure `CERTIMINE_DC3_TOKEN` (recomendado) o `penasquito_dc3.static_token` en `config/config.php`. **No subir el token real al control de versiones.** +En CertiMine el token se resuelve en este **orden**: + +1. Variable de entorno **`CERTIMINE_DC3_TOKEN`** (recomendado en producción). +2. **`penasquito_dc3.static_token`** en `config/config.php`. +3. Archivo local **`config/token.php`** (copiar de `config/token.example.php`; está en **`.gitignore`**). + +No leer el token desde documentación versionada. El ejemplo público del texto del PDF está en **`docs/DatosPdf.example.txt`** (línea del token redactada). ## Base URL -`https://penasquito.wotbi.com` (según DatosPdf.txt). +`https://penasquito.wotbi.com` (según la documentación en `docs/DatosPdf.example.txt`). ## Endpoint 1 — Crear solicitud de búsqueda diff --git a/lang/en.php b/lang/en.php index c500c0e..df4c407 100644 --- a/lang/en.php +++ b/lang/en.php @@ -50,7 +50,16 @@ return [ 'issued' => 'Issued', 'sync_title' => 'Synchronization', 'webhook_ok' => 'Event received', - 'dc3_lookup_error' => 'Could not load DC3 competencies. Check passport or API token.', + 'lookup_need_dc3' => 'No local record for that code. To query by passport (e.g. E000055821), configure the DC3 API token (CERTIMINE_DC3_TOKEN or config.php).', + 'lookup_need_dc3_title' => 'DC3 API not configured', + 'lookup_need_dc3_body' => 'Without a token, only local DB lookup works (demo numbers like 10001 or C-5001). Set the token via CERTIMINE_DC3_TOKEN, or penasquito_dc3.static_token in config.php, or copy config/token.example.php to config/token.php and set dc3_token (token.php is gitignored).', + 'lookup_using_example_config' => 'Currently loading config.example.php (config/config.php is missing): example token is empty. You may use config/token.php (see token.example.php).', + 'lookup_dc3_ready' => 'DC3 API enabled: passport lookups will call the service and store results locally.', + 'lookup_token_env' => 'Token from CERTIMINE_DC3_TOKEN.', + 'lookup_token_config' => 'Token from config.php.', + 'lookup_debug_hint' => 'Debug mode: API errors may include details on screen. Set app.debug=true or CERTIMINE_DEBUG=1.', + 'lookup_passport_hint' => 'Passports like E000055821 are normalized (case). Local DB is tried first; if no match and the API is configured, Wotbi is queried.', + 'dc3_lookup_error' => 'Could not load data from the DC3 API. Check passport, token, and network. Enable debug mode for technical details.', 'login_passport_hint' => 'With DC3 API (CERTIMINE_DC3_TOKEN), use your passport (e.g. E000055821). Password is unused. Without token: demo user with «contract» or employee.', 'login_demo_hint' => 'Without DC3 API: username containing «contract» simulates contractor; otherwise demo employee.', ]; diff --git a/lang/es.php b/lang/es.php index 239d0db..b8063d7 100644 --- a/lang/es.php +++ b/lang/es.php @@ -50,7 +50,16 @@ return [ 'issued' => 'Emitido', 'sync_title' => 'Sincronización', 'webhook_ok' => 'Evento recibido', - 'dc3_lookup_error' => 'No se pudieron obtener competencias del servicio DC3. Verifique el passport o el token del API.', + 'lookup_need_dc3' => 'No hay registro local con ese código. Para consultar por passport (p. ej. E000055821) hace falta configurar el token del API DC3 (CERTIMINE_DC3_TOKEN o config.php).', + 'lookup_need_dc3_title' => 'API DC3 no configurada', + 'lookup_need_dc3_body' => 'Sin token de acceso, solo se puede buscar en la base de datos local (números demo como 10001 o C-5001). Configure el token en este orden: variable CERTIMINE_DC3_TOKEN, o penasquito_dc3.static_token en config.php, o copie config/token.example.php a config/token.php y rellene dc3_token (token.php no se sube a git).', + 'lookup_using_example_config' => 'Ahora mismo está cargando config.example.php (no existe config/config.php): el token del ejemplo está vacío. Puede usar config/token.php (véase token.example.php).', + 'lookup_dc3_ready' => 'API DC3 activo: las búsquedas por passport consultarán el servicio y guardarán el resultado aquí.', + 'lookup_token_env' => 'Token vía variable de entorno CERTIMINE_DC3_TOKEN.', + 'lookup_token_config' => 'Token definido en config.php.', + 'lookup_debug_hint' => 'Modo debug: los errores del API pueden mostrarse en pantalla. active app.debug=true o CERTIMINE_DEBUG=1.', + 'lookup_passport_hint' => 'Passport tipo E000055821: puede escribirse en minúsculas; se normaliza. Primero se busca en BD local; si no hay coincidencia y el API está configurado, se consulta Wotbi.', + 'dc3_lookup_error' => 'No se pudieron obtener datos del API DC3. Revise el passport, el token y la red. Active el modo debug para ver el detalle técnico.', 'login_passport_hint' => 'Con API DC3 configurado (CERTIMINE_DC3_TOKEN), use su passport (ej. E000055821). La contraseña no se usa. Sin token: modo demo con usuario «contract» o empleado.', 'login_demo_hint' => 'Sin API DC3: si el usuario contiene «contract», se simula contratista; si no, empleado demo.', ]; diff --git a/public/index.php b/public/index.php index a8d6e27..5bbf204 100644 --- a/public/index.php +++ b/public/index.php @@ -6,6 +6,7 @@ use CertiMine\Auth; use CertiMine\Config; use CertiMine\I18n; use CertiMine\MobilisemeClient; +use CertiMine\PenasquitoDc3Api; use CertiMine\PersonRepository; use CertiMine\Security; use CertiMine\Util; @@ -38,6 +39,11 @@ try { case 'lookup': $error = null; $result = null; + $lookupDc3Ok = PenasquitoDc3Api::isConfigured(); + $envTok = getenv('CERTIMINE_DC3_TOKEN'); + $lookupDc3Env = is_string($envTok) && $envTok !== ''; + $lookupUsingExample = !Config::loadedFromLocalFile(); + $lookupDc3Base = (string) (Config::get('penasquito_dc3', 'base_url') ?? ''); if ($_SERVER['REQUEST_METHOD'] === 'POST') { if (!Security::verifyCsrf($_POST['_csrf'] ?? null)) { $error = I18n::t('csrf_invalid'); @@ -67,15 +73,15 @@ try { ); exit; } - if (\CertiMine\PenasquitoDc3Api::isConfigured()) { + if (PenasquitoDc3Api::isConfigured()) { try { - $apiRes = \CertiMine\PenasquitoDc3Api::fetchResultForPassport($code); - $isContractor = \CertiMine\PenasquitoDc3Api::guessContractorFromCompanyPublic( + $apiRes = PenasquitoDc3Api::fetchResultForPassport($code); + $isContractor = PenasquitoDc3Api::guessContractorFromCompanyPublic( (string) ($apiRes['company'] ?? '') ); $ptype = $type === 'contractor' || $isContractor ? 'contractor' : 'employee'; $pid = (string) ($apiRes['passport'] ?? $code); - \CertiMine\PenasquitoDc3Api::persistResult($pid, $apiRes, $ptype); + PenasquitoDc3Api::persistResult($pid, $apiRes, $ptype); PersonRepository::logAudit('lookup_dc3_api', $ptype, $code); $ecode = (string) ($apiRes['passport'] ?? $code); $sig = Security::qrSignature($ptype, $ecode); @@ -88,12 +94,12 @@ try { exit; } catch (Throwable $ex) { $error = I18n::t('dc3_lookup_error'); - if (getenv('CERTIMINE_DEBUG') === '1') { - $error .= ' ' . $ex->getMessage(); + if (Config::debugMode()) { + $error .= ' — ' . $ex->getMessage(); } } } else { - $error = I18n::t('no_results'); + $error = I18n::t('lookup_need_dc3'); } } } diff --git a/src/Config.php b/src/Config.php index a040d0c..b612b75 100644 --- a/src/Config.php +++ b/src/Config.php @@ -9,16 +9,24 @@ final class Config /** @var array */ private static array $data = []; + private static bool $loadedFromLocal = false; + public static function load(string $basePath): void { $local = $basePath . '/config/config.php'; $example = $basePath . '/config/config.example.php'; $file = is_file($local) ? $local : $example; + self::$loadedFromLocal = is_file($local); /** @var array $cfg */ $cfg = require $file; self::$data = $cfg; } + public static function loadedFromLocalFile(): bool + { + return self::$loadedFromLocal; + } + /** @return mixed */ public static function get(string $key, ?string $sub = null) { @@ -33,4 +41,13 @@ final class Config { return self::$data; } + + public static function debugMode(): bool + { + if (getenv('CERTIMINE_DEBUG') === '1') { + return true; + } + $d = self::get('app', 'debug'); + return $d === true || $d === 1 || $d === '1'; + } } diff --git a/src/PenasquitoDc3Api.php b/src/PenasquitoDc3Api.php index 67846dd..0ee8071 100644 --- a/src/PenasquitoDc3Api.php +++ b/src/PenasquitoDc3Api.php @@ -14,14 +14,38 @@ final class PenasquitoDc3Api { $env = getenv('CERTIMINE_DC3_TOKEN'); if (is_string($env) && $env !== '') { - return $env; + return trim($env); } $cfg = Config::get('penasquito_dc3'); - if (!is_array($cfg)) { + if (is_array($cfg)) { + $t = (string) ($cfg['static_token'] ?? ''); + if ($t !== '') { + return trim($t); + } + } + return self::tokenFromSecretsFile(); + } + + /** + * Archivo local ignorado por git: config/token.php (ver config/token.example.php). + */ + private static function tokenFromSecretsFile(): string + { + $app = Config::get('app'); + if (!is_array($app) || empty($app['base_path'])) { return ''; } - $t = (string) ($cfg['static_token'] ?? ''); - return $t; + $path = rtrim((string) $app['base_path'], '/') . '/config/token.php'; + if (!is_readable($path)) { + return ''; + } + /** @var mixed $data */ + $data = require $path; + if (!is_array($data)) { + return ''; + } + $t = (string) ($data['dc3_token'] ?? $data['CERTIMINE_DC3_TOKEN'] ?? ''); + return trim($t); } public static function isConfigured(): bool @@ -39,33 +63,58 @@ final class PenasquitoDc3Api if (!self::isConfigured()) { throw new \RuntimeException('DC3 API not configured (token vacío).'); } - $passport = trim($passport); + $passport = self::normalizePassport($passport); if ($passport === '') { throw new \RuntimeException('Passport vacío.'); } $search = self::search($passport); - $status = (string) ($search['status'] ?? ''); + return self::resolveSearchToResult($search); + } + + public static function normalizePassport(string $passport): string + { + $passport = trim($passport); + if ($passport === '') { + return ''; + } + if (preg_match('/^([a-zA-Z]+)(\d+)$/', $passport, $m)) { + return strtoupper($m[1]) . $m[2]; + } + return strtoupper($passport); + } + + /** + * @param array $search Respuesta del POST /search/ + * @return array{passport:string,name:string,company:string,competencies:list>,error:?string} + */ + private static function resolveSearchToResult(array $search): array + { + $status = strtolower((string) ($search['status'] ?? '')); if ($status === 'completed') { $res = $search['result'] ?? null; if (!is_array($res)) { - throw new \RuntimeException('Respuesta completed sin result.'); + throw new \RuntimeException('Respuesta completed sin bloque result.'); } self::assertResultOk($res); /** @var array{passport:string,name:string,company:string,competencies:list>,error:?string} $res */ return $res; } - if ($status === 'pending') { - $ticket = (string) ($search['ticket_id'] ?? ''); + if (in_array($status, ['pending', 'processing'], true)) { + $ticket = self::ticketIdFromResponse($search); if ($ticket === '') { - throw new \RuntimeException('pending sin ticket_id.'); + throw new \RuntimeException( + 'Estado "' . $status . '" sin ticket_id. Claves: ' . implode(', ', array_keys($search)) + ); } $cfg = Config::get('penasquito_dc3'); $pollS = is_array($cfg) ? (int) ($cfg['poll_interval_seconds'] ?? 2) : 2; - $max = is_array($cfg) ? (int) ($cfg['poll_max_attempts'] ?? 20) : 20; + $max = is_array($cfg) ? (int) ($cfg['poll_max_attempts'] ?? 40) : 40; for ($i = 0; $i < $max; $i++) { - usleep((int) max(1, $pollS) * 1_000_000); + if ($i > 0) { + usleep((int) max(1, $pollS) * 1_000_000); + } $r = self::ticketResult($ticket); - $st = (string) ($r['status'] ?? ''); + $st = strtolower((string) ($r['status'] ?? '')); if ($st === 'completed') { $res = $r['result'] ?? null; if (!is_array($res)) { @@ -82,7 +131,20 @@ final class PenasquitoDc3Api } throw new \RuntimeException('Tiempo de espera agotado consultando el ticket DC3.'); } - throw new \RuntimeException('Estado de búsqueda inesperado: ' . $status); + $hint = substr((string) json_encode($search, JSON_UNESCAPED_UNICODE), 0, 400); + throw new \RuntimeException('Estado de búsqueda no reconocido: "' . $status . '". ' . $hint); + } + + /** @param array $r */ + private static function ticketIdFromResponse(array $r): string + { + foreach (['ticket_id', 'ticketId', 'ticket'] as $k) { + if (!isset($r[$k]) || $r[$k] === '' || $r[$k] === null) { + continue; + } + return is_scalar($r[$k]) ? (string) $r[$k] : ''; + } + return ''; } /** @@ -150,7 +212,25 @@ final class PenasquitoDc3Api $url = $base . $path; $resp = self::request('POST', $url, ['passport' => $passport]); $j = $resp['json']; - return is_array($j) ? $j : []; + if (!is_array($j)) { + $raw = substr(preg_replace('/\s+/', ' ', (string) $resp['raw']), 0, 240); + throw new \RuntimeException( + 'DC3 search no devolvió JSON válido (HTTP ' . $resp['status'] . '). Inicio: ' . $raw + ); + } + return self::unwrapEnvelope($j); + } + + /** @param array $j */ + private static function unwrapEnvelope(array $j): array + { + if (isset($j['data']) && is_array($j['data'])) { + $d = $j['data']; + if (isset($d['status']) || isset($d['ticket_id']) || isset($d['ticketId'])) { + return $d; + } + } + return $j; } /** @return array */ @@ -162,7 +242,11 @@ final class PenasquitoDc3Api $path = str_replace('{ticket_id}', rawurlencode($ticketId), $tpl); $resp = self::request('GET', $base . $path, null); $j = $resp['json']; - return is_array($j) ? $j : []; + if (!is_array($j)) { + $raw = substr(preg_replace('/\s+/', ' ', (string) $resp['raw']), 0, 240); + throw new \RuntimeException('DC3 ticket result no JSON (HTTP ' . $resp['status'] . '): ' . $raw); + } + return self::unwrapEnvelope($j); } /** diff --git a/views/lookup.php b/views/lookup.php index 924e668..6e9cab2 100644 --- a/views/lookup.php +++ b/views/lookup.php @@ -1,19 +1,48 @@

+ +
+ warning +
+ + +
+ +
+ +
+ cloud_done + + + + — — + +
+ + + +
+ + -
+
@@ -27,7 +56,8 @@ require __DIR__ . '/partials/header.php';
- + +