diff --git a/.gitignore b/.gitignore index 5393474..ad0f855 100644 --- a/.gitignore +++ b/.gitignore @@ -18,7 +18,10 @@ pids/ # Environment variables .env +.env.lab .env.local +tools/lab/.pids/ +tools/lab/.logs/ .env.development.local .env.test.local .env.production.local @@ -56,5 +59,6 @@ temp/ # CRM specific (cópia local) crm/vendor/ crm/storage/ +storage/ crm/cache/ crm/logs/ diff --git a/crm/Core/AuthMiddleware.php b/crm/Core/AuthMiddleware.php index d95faf4..46ecd2a 100644 --- a/crm/Core/AuthMiddleware.php +++ b/crm/Core/AuthMiddleware.php @@ -23,9 +23,6 @@ class AuthMiddleware */ public static function apiOrAuth(): void { - if (Auth::check()) { - return; - } $authHeader = $_SERVER['HTTP_AUTHORIZATION'] ?? ''; $token = null; if (stripos($authHeader, 'Bearer ') === 0) { @@ -33,10 +30,14 @@ class AuthMiddleware } $expected = $_ENV['REDIRECTS_API_KEY'] ?? ''; if ($expected && $token && hash_equals($expected, $token)) { - // Define flag indicando autenticação via API key (acesso total) $_SERVER['API_KEY_AUTH'] = true; return; } + + if (Auth::check()) { + return; + } + http_response_code(401); header('Content-Type: application/json'); echo json_encode(['success' => false, 'message' => 'Unauthorized']); diff --git a/crm/Modules/Redirects/Controllers/RedirectsApiController.php b/crm/Modules/Redirects/Controllers/RedirectsApiController.php index 21a607a..f9bdf9f 100644 --- a/crm/Modules/Redirects/Controllers/RedirectsApiController.php +++ b/crm/Modules/Redirects/Controllers/RedirectsApiController.php @@ -106,10 +106,10 @@ class RedirectsApiController extends BaseController } // Check if authenticated via session OR Bearer token - $isAuthenticated = \App\Core\Auth::check(); $hasValidToken = $expectedKey && $token && hash_equals($expectedKey, $token); + $isAuthenticated = $hasValidToken || \App\Core\Auth::check(); - if (!$isAuthenticated && !$hasValidToken) { + if (!$isAuthenticated) { $this->errorResponse('Unauthorized', 401); return; } diff --git a/nodejs-redirector/helpers/helpers.mjs b/nodejs-redirector/helpers/helpers.mjs index fe09145..53f44c1 100644 --- a/nodejs-redirector/helpers/helpers.mjs +++ b/nodejs-redirector/helpers/helpers.mjs @@ -1,35 +1,35 @@ import axios from 'axios'; -// ============================================================================ -// CONFIGURAÇÃO DA API -// ============================================================================ - -// Aceder diretamente ao IP do servidor para evitar CloudFlare -const CRM_API_URL = process.env.CRM_API_URL || 'http://94.23.75.89/api/redirects'; -const API_KEY = process.env.CRM_API_KEY || ''; - // ============================================================================ // FETCH REDIRECTS // ============================================================================ +function getCrmApiConfig() { + return { + url: process.env.CRM_API_URL || 'http://94.23.75.89/api/redirects', + key: process.env.CRM_API_KEY || '', + }; +} + /** * Busca redirects da API do CRM * @returns {Object} Objeto com redirects indexados por slug */ export async function fetchRedirects() { try { - console.log(`🔄 Fetching redirects from: ${CRM_API_URL}`); + const { url: crmApiUrl, key: apiKey } = getCrmApiConfig(); + console.log(`🔄 Fetching redirects from: ${crmApiUrl}`); const headers = { 'User-Agent': 'MoneyFlix-Redirector/1.0', 'Accept': 'application/json', 'Host': 'redirect.moneyflix.com' }; - if (API_KEY) { - headers['Authorization'] = `Bearer ${API_KEY}`; + if (apiKey) { + headers['Authorization'] = `Bearer ${apiKey}`; } - const response = await axios.get(CRM_API_URL, { + const response = await axios.get(crmApiUrl, { headers, timeout: 10000 }); diff --git a/nodejs-redirector/index.mjs b/nodejs-redirector/index.mjs index 305b72e..af7fab2 100644 --- a/nodejs-redirector/index.mjs +++ b/nodejs-redirector/index.mjs @@ -48,6 +48,7 @@ app.use((req, res, next) => { let redirectsCache = {}; let lastCacheHash = ''; +let lastCacheUpdate = Date.now(); const CACHE_REFRESH_INTERVAL = 60000; // 60 segundos (1 minuto) const INITIAL_RETRY_ATTEMPTS = 3; const INITIAL_RETRY_DELAY = 5000; // 5 segundos @@ -96,6 +97,7 @@ async function refreshRedirectsCache(isInitial = false) { const oldCount = Object.keys(redirectsCache).length; redirectsCache = newRedirects; lastCacheHash = newHash; + lastCacheUpdate = Date.now(); const newCount = Object.keys(redirectsCache).length; if (isInitial) { diff --git a/tools/lab/bootstrap.sh b/tools/lab/bootstrap.sh new file mode 100755 index 0000000..a9b89a0 --- /dev/null +++ b/tools/lab/bootstrap.sh @@ -0,0 +1,79 @@ +#!/usr/bin/env bash +# Bootstrap MoneyFlix lab stack on 10.10.50.17 (BIT-24693) +set -euo pipefail + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +LAB_DIR="$ROOT/tools/lab" +ENV_FILE="${MONEYFLIX_LAB_ENV:-$ROOT/.env.lab}" + +if [[ ! -f "$ENV_FILE" ]]; then + cp "$LAB_DIR/lab.env.example" "$ENV_FILE" + LAB_API_KEY="lab-$(openssl rand -hex 16)" + LAB_DB_PASS="lab-$(openssl rand -hex 12)" + sed -i "s/change-me-lab-api-key/$LAB_API_KEY/g" "$ENV_FILE" + sed -i "s/change-me-lab-only/$LAB_DB_PASS/g" "$ENV_FILE" + echo "Created $ENV_FILE with generated lab credentials" +fi + +# shellcheck disable=SC1090 +source "$ENV_FILE" + +MARIADB_CONTAINER="${MARIADB_CONTAINER:-}" +if [[ -z "$MARIADB_CONTAINER" ]]; then + MARIADB_CONTAINER="$(docker ps --format '{{.Names}}' | grep -E 'mariadb|mysql' | grep -E '3306|:3306' | head -1 || true)" + if [[ -z "$MARIADB_CONTAINER" ]]; then + MARIADB_CONTAINER="$(docker ps --format '{{.Names}}\t{{.Ports}}' | awk -F'\t' '$2 ~ /0\.0\.0\.0:3306/ {print $1; exit}')" + fi +fi + +if [[ -z "$MARIADB_CONTAINER" ]]; then + echo "ERROR: No MariaDB/MySQL container on port 3306 found" >&2 + exit 1 +fi + +echo "Using MariaDB container: $MARIADB_CONTAINER" + +docker exec -i "$MARIADB_CONTAINER" mariadb -uroot -p"${MARIADB_ROOT_PASSWORD}" < "$ROOT/.env" < "$ROOT/nodejs-redirector/.env" <&2 + exit 1 +fi + +# shellcheck disable=SC1090 +source "$ENV_FILE" + +PASS=0 +FAIL=0 +RESULTS=() + +check() { + local name=$1 + local cmd=$2 + local expect=$3 + local out + out="$(eval "$cmd" 2>/dev/null || true)" + if echo "$out" | grep -qE "$expect"; then + PASS=$((PASS + 1)) + RESULTS+=("PASS $name") + echo "PASS $name" + else + FAIL=$((FAIL + 1)) + RESULTS+=("FAIL $name") + echo "FAIL $name" + echo " expected pattern: $expect" + echo " got: $(echo "$out" | head -c 200)" + fi +} + +echo "=== MoneyFlix lab smoke (BIT-24693) ===" +echo "Host: $(hostname -I | awk '{print $1}')" +echo "CRM port: $CRM_PORT | Redirector port: $REDIRECTOR_PORT" +echo + +# Ensure stack is up +if ! curl -sf "http://127.0.0.1:${CRM_PORT}/system/status" >/dev/null 2>&1; then + echo "Stack not running — starting..." + bash "$ROOT/tools/lab/start.sh" + sleep 2 +fi + +check "CRM /system/status" \ + "curl -sf http://127.0.0.1:${CRM_PORT}/system/status" \ + '"status"[[:space:]]*:[[:space:]]*"OK"' + +check "CRM /api/redirects (Bearer)" \ + "curl -sf -H 'Authorization: Bearer ${REDIRECTS_API_KEY}' http://127.0.0.1:${CRM_PORT}/api/redirects" \ + '"success"[[:space:]]*:[[:space:]]*true' + +check "Redirector /health" \ + "curl -sf http://127.0.0.1:${REDIRECTOR_PORT}/health" \ + '"status"[[:space:]]*:[[:space:]]*"healthy"' + +check "Redirector /status" \ + "curl -sf http://127.0.0.1:${REDIRECTOR_PORT}/status" \ + '"status"[[:space:]]*:[[:space:]]*"running"' + +check "Redirector /test-db" \ + "curl -sf http://127.0.0.1:${REDIRECTOR_PORT}/test-db" \ + '"status"[[:space:]]*:[[:space:]]*"ok"' + +# Hit redirect slug — should 302 to example.com +REDIR_CODE="$(curl -s -o /dev/null -w '%{http_code}' -L --max-redirs 0 "http://127.0.0.1:${REDIRECTOR_PORT}/lab-smoke-test" 2>/dev/null || true)" +if [[ "$REDIR_CODE" == "302" || "$REDIR_CODE" == "301" ]]; then + PASS=$((PASS + 1)) + RESULTS+=("PASS redirect /lab-smoke-test -> 302") + echo "PASS redirect /lab-smoke-test -> HTTP $REDIR_CODE" +else + FAIL=$((FAIL + 1)) + RESULTS+=("FAIL redirect /lab-smoke-test") + echo "FAIL redirect /lab-smoke-test (HTTP $REDIR_CODE)" +fi + +# Flush analytics queue and verify MySQL write +curl -sf "http://127.0.0.1:${REDIRECTOR_PORT}/process-queue" >/dev/null 2>&1 || true +sleep 2 + +MARIADB_CONTAINER="${MARIADB_CONTAINER:-}" +if [[ -z "$MARIADB_CONTAINER" ]]; then + MARIADB_CONTAINER="$(docker ps --format '{{.Names}}\t{{.Ports}}' | awk -F'\t' '$2 ~ /0\.0\.0\.0:3306/ {print $1; exit}')" +fi + +HIT_COUNT="$(docker exec "$MARIADB_CONTAINER" mariadb -u"${DB_USER}" -p"${DB_PASS}" -N -e \ + "SELECT COUNT(*) FROM redirect_stats rs JOIN redirects r ON r.id=rs.redirect_id WHERE r.cuid='lab-smoke-test';" \ + moneyflix_lab 2>/dev/null || echo 0)" + +if [[ "${HIT_COUNT:-0}" -ge 1 ]]; then + PASS=$((PASS + 1)) + RESULTS+=("PASS MySQL analytics write (hits=$HIT_COUNT)") + echo "PASS MySQL analytics write (hits=$HIT_COUNT)" +else + FAIL=$((FAIL + 1)) + RESULTS+=("FAIL MySQL analytics write") + echo "FAIL MySQL analytics write (hits=$HIT_COUNT)" +fi + +echo +echo "=== Summary: $PASS passed, $FAIL failed ===" +printf '%s\n' "${RESULTS[@]}" + +if [[ "$FAIL" -gt 0 ]]; then + exit 1 +fi + +echo "All smoke checks passed." diff --git a/tools/lab/start.sh b/tools/lab/start.sh new file mode 100755 index 0000000..b2c9157 --- /dev/null +++ b/tools/lab/start.sh @@ -0,0 +1,64 @@ +#!/usr/bin/env bash +# Start MoneyFlix lab services (CRM PHP + Node redirector) +set -euo pipefail + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +ENV_FILE="${MONEYFLIX_LAB_ENV:-$ROOT/.env.lab}" +PID_DIR="$ROOT/tools/lab/.pids" +LOG_DIR="$ROOT/tools/lab/.logs" + +mkdir -p "$PID_DIR" "$LOG_DIR" + +if [[ ! -f "$ENV_FILE" ]]; then + echo "Run bootstrap first: bash tools/lab/bootstrap.sh" >&2 + exit 1 +fi + +# shellcheck disable=SC1090 +source "$ENV_FILE" + +stop_if_running() { + local name=$1 + local pidfile="$PID_DIR/$name.pid" + if [[ -f "$pidfile" ]]; then + local pid + pid="$(cat "$pidfile")" + if kill -0 "$pid" 2>/dev/null; then + echo "Stopping existing $name (pid $pid)" + kill "$pid" 2>/dev/null || true + sleep 1 + fi + rm -f "$pidfile" + fi +} + +stop_if_running crm +stop_if_running redirector + +echo "Starting CRM on :${CRM_PORT}..." +php -S "127.0.0.1:${CRM_PORT}" -t "$ROOT/crm" "$ROOT/crm/index.php" \ + > "$LOG_DIR/crm.log" 2>&1 & +echo $! > "$PID_DIR/crm.pid" + +echo "Starting redirector on :${REDIRECTOR_PORT}..." +(cd "$ROOT/nodejs-redirector" && node index.mjs) > "$LOG_DIR/redirector.log" 2>&1 & +echo $! > "$PID_DIR/redirector.pid" + +sleep 3 + +if ! kill -0 "$(cat "$PID_DIR/crm.pid")" 2>/dev/null; then + echo "CRM failed to start — see $LOG_DIR/crm.log" >&2 + tail -30 "$LOG_DIR/crm.log" >&2 || true + exit 1 +fi + +if ! kill -0 "$(cat "$PID_DIR/redirector.pid")" 2>/dev/null; then + echo "Redirector failed to start — see $LOG_DIR/redirector.log" >&2 + tail -30 "$LOG_DIR/redirector.log" >&2 || true + exit 1 +fi + +echo "Lab stack running:" +echo " CRM: http://127.0.0.1:${CRM_PORT}/system/status" +echo " Redirector: http://127.0.0.1:${REDIRECTOR_PORT}/health" +echo " Logs: $LOG_DIR/" diff --git a/tools/lab/stop.sh b/tools/lab/stop.sh new file mode 100755 index 0000000..dee0f7c --- /dev/null +++ b/tools/lab/stop.sh @@ -0,0 +1,18 @@ +#!/usr/bin/env bash +# Stop MoneyFlix lab services +set -euo pipefail + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +PID_DIR="$ROOT/tools/lab/.pids" + +for name in crm redirector; do + pidfile="$PID_DIR/$name.pid" + if [[ -f "$pidfile" ]]; then + pid="$(cat "$pidfile")" + if kill -0 "$pid" 2>/dev/null; then + kill "$pid" 2>/dev/null || true + echo "Stopped $name (pid $pid)" + fi + rm -f "$pidfile" + fi +done