seguridad: token DC3 vía env, config o config/token.php (gitignored)

- Elimina lectura del token desde DatosPdf; nuevo token.example.php y token.php ignorado.
- DatosPdf.txt deja de versionarse; docs/DatosPdf.example.txt con TOKEN redactado.
- Ajusta README, docs API, i18n y banderolas de consulta/diagnóstico previos.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
remaster 2026-05-13 18:49:11 -06:00
parent b78a4955c7
commit 84e94dcb55
12 changed files with 214 additions and 35 deletions

2
.gitignore vendored
View file

@ -1,2 +1,4 @@
config/config.php
config/token.php
DatosPdf.txt
.DS_Store

View file

@ -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

View file

@ -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',

13
config/token.example.php Normal file
View file

@ -0,0 +1,13 @@
<?php
/**
* Secreto local del API DC3 — NO versionar.
*
* Instalación:
* cp config/token.example.php config/token.php
* Edite dc3_token con el valor real (o deje vacío y use CERTIMINE_DC3_TOKEN).
*/
declare(strict_types=1);
return [
'dc3_token' => '',
];

View file

@ -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 <defina en config/token.php o CERTIMINE_DC3_TOKEN>
Authorization: Token <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

View file

@ -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 <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

View file

@ -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.',
];

View file

@ -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.',
];

View file

@ -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');
}
}
}

View file

@ -9,16 +9,24 @@ final class Config
/** @var array<string,mixed> */
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<string,mixed> $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';
}
}

View file

@ -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<string,mixed> $search Respuesta del POST /search/
* @return array{passport:string,name:string,company:string,competencies:list<array<string,mixed>>,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<array<string,mixed>>,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++) {
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<string,mixed> $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<string,mixed> $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<string,mixed> */
@ -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);
}
/**

View file

@ -1,19 +1,48 @@
<?php
declare(strict_types=1);
use CertiMine\Config;
use CertiMine\I18n;
use CertiMine\Security;
use CertiMine\Util;
/** @var string|null $error */
/** @var bool $lookupDc3Ok */
/** @var bool $lookupDc3Env */
/** @var bool $lookupUsingExample */
/** @var string $lookupDc3Base */
require __DIR__ . '/partials/header.php';
?>
<h1 class="h3 mb-3"><?= Util::h(I18n::t('lookup_title')) ?></h1>
<p class="text-muted"><?= Util::h(I18n::t('lookup_intro')) ?></p>
<?php if (!$lookupDc3Ok): ?>
<div class="alert alert-warning border-0 shadow-sm" role="status">
<span class="material-symbols-outlined align-middle">warning</span>
<strong><?= Util::h(I18n::t('lookup_need_dc3_title')) ?></strong><br>
<?= Util::h(I18n::t('lookup_need_dc3_body')) ?>
<?php if ($lookupUsingExample): ?>
<br><span class="small text-muted"><?= Util::h(I18n::t('lookup_using_example_config')) ?></span>
<?php endif; ?>
</div>
<?php else: ?>
<div class="alert alert-success border-0 shadow-sm py-2" role="status">
<span class="material-symbols-outlined align-middle">cloud_done</span>
<?= Util::h(I18n::t('lookup_dc3_ready')) ?>
<span class="small text-muted d-block mt-1">
<?= Util::h($lookupDc3Base) ?>
<?php if ($lookupDc3Env): ?> — <?= Util::h(I18n::t('lookup_token_env')) ?><?php else: ?> — <?= Util::h(I18n::t('lookup_token_config')) ?><?php endif; ?>
</span>
</div>
<?php endif; ?>
<?php if (Config::debugMode()): ?>
<div class="alert alert-secondary small"><?= Util::h(I18n::t('lookup_debug_hint')) ?></div>
<?php endif; ?>
<?php if ($error): ?>
<div class="alert alert-warning"><?= Util::h($error) ?></div>
<div class="alert alert-danger"><?= Util::h($error) ?></div>
<?php endif; ?>
<form method="post" class="card p-4 mb-3" style="max-width:520px">
@ -27,7 +56,8 @@ require __DIR__ . '/partials/header.php';
</div>
<div class="mb-3">
<label class="form-label"><?= Util::h(I18n::t('lookup_code')) ?></label>
<input class="form-control" name="code" required placeholder="10001 / C-5001">
<input class="form-control" name="code" required placeholder="E000055821 / 10001 / C-5001" autocomplete="off">
<div class="form-text"><?= Util::h(I18n::t('lookup_passport_hint')) ?></div>
</div>
<button class="btn btn-success" type="submit"><?= Util::h(I18n::t('lookup_submit')) ?></button>
</form>