"use strict"; /** * Application configuration loaded from environment variables. * Centralizes defaults for server, database, JWT, encryption, blockchain, and safety settings. */ var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.config = void 0; const dotenv_1 = __importDefault(require("dotenv")); const path_1 = __importDefault(require("path")); const MAIL_ENV_KEYS = [ 'EMAIL_TRANSPORT', 'SMTP_HOST', 'SMTP_PORT', 'SMTP_SECURE', 'SMTP_USER', 'SMTP_PASS', 'EMAIL_FROM', 'EMAIL_REPLY_TO', 'APP_PUBLIC_URL', 'VERIFY_EMAIL_PATH', 'RESET_PASSWORD_PATH', 'PASSWORD_RESET_EXPIRY_HOURS', 'EMAIL_VERIFICATION_EXPIRY_HOURS', 'EMAIL_VERIFICATION_SEND_MAX', 'PASSWORD_RESET_SEND_MAX', ]; function isSmtpEnvConfigured() { return !!(process.env.SMTP_HOST && process.env.SMTP_USER && process.env.SMTP_PASS && process.env.EMAIL_FROM); } function resolveEmailTransport() { const preferred = (process.env.EMAIL_TRANSPORT || '').toLowerCase(); if (preferred === 'console') return 'console'; if (preferred === 'smtp') return isSmtpEnvConfigured() ? 'smtp' : 'console'; return isSmtpEnvConfigured() ? 'smtp' : 'console'; } function loadEnvFiles() { const cwd = process.cwd(); const envFile = process.env.ENV_FILE || '.env'; dotenv_1.default.config({ path: path_1.default.resolve(cwd, envFile) }); // Repo-root .env often holds SMTP settings while backend/.env keeps local dev overrides. const rootResult = dotenv_1.default.config({ path: path_1.default.resolve(cwd, '..', '.env') }); if (rootResult.parsed) { for (const key of MAIL_ENV_KEYS) { const value = rootResult.parsed[key]; // Docker Compose / ENV_FILE values take precedence over repo-root .env if (value !== undefined && value !== '' && process.env[key] === undefined) { process.env[key] = value; } } } } loadEnvFiles(); function readEnvInt(key, fallback, min, max) { const raw = process.env[key]; if (!raw) return fallback; const n = parseInt(raw, 10); if (!Number.isFinite(n)) return fallback; return Math.min(max, Math.max(min, n)); } /** Resolved runtime configuration derived from process.env with safe defaults. */ exports.config = { env: process.env.NODE_ENV || 'development', port: parseInt(process.env.PORT || '4000', 10), apiPrefix: process.env.API_PREFIX || '/api/v1', database: { url: process.env.DATABASE_URL || '', }, jwt: { secret: process.env.JWT_SECRET || 'change-me-in-production', accessExpiry: process.env.JWT_ACCESS_EXPIRY || '15m', refreshExpiry: process.env.JWT_REFRESH_EXPIRY || '7d', }, encryption: { key: process.env.ENCRYPTION_KEY || '', }, blockchain: { tron: { nodeUrl: process.env.TRON_NODE_URL || 'https://api.trongrid.io', apiKey: process.env.TRON_API_KEY || '', confirmations: parseInt(process.env.TRON_CONFIRMATIONS || '20', 10), /** Optional override for USDT TRC20 contract (e.g. testnet token). When set, used instead of DB wallet_types.contract_address. */ usdtTrc20Contract: process.env.USDT_TRC20_CONTRACT || null, }, polygon: { rpcUrl: process.env.POLYGON_RPC_URL || 'https://polygon-rpc.com', usdcContract: process.env.USDC_POLYGON_CONTRACT || '0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359', confirmations: parseInt(process.env.POLYGON_CONFIRMATIONS || '64', 10), /** Max blocks per eth_getLogs call; Amoy public RPC rejects ~500-block ranges */ getLogsBlockRange: parseInt(process.env.POLYGON_GETLOGS_BLOCK_RANGE || '100', 10), }, bsc: { rpcUrl: process.env.BSC_RPC_URL || 'https://bsc-dataseed.binance.org', /** * Extra RPCs tried for eth_getLogs when the primary returns -32005 / limit exceeded. * Public Binance dataseeds often ban getLogs; rpc-bsc.48.club is the reliable free fallback. * (1rpc.io often returns 403 from datacenter / VPS IPs — do not list it by default.) */ rpcFallbacks: (process.env.BSC_RPC_FALLBACKS || 'https://rpc-bsc.48.club') .split(',') .map((s) => s.trim()) .filter(Boolean), /** Optional override; otherwise DB wallet_types.contract_address for USDT_BEP20 */ usdtBep20Contract: process.env.USDT_BEP20_CONTRACT || null, confirmations: parseInt(process.env.BSC_CONFIRMATIONS || '15', 10), getLogsBlockRange: parseInt(process.env.BSC_GETLOGS_BLOCK_RANGE || '2000', 10), /** * First-scan / balance catch-up lookback (~3s/block → 200k ≈ 7 days). * Missed deposits older than this need manual creditByTx. */ depositInitialLookbackBlocks: parseInt(process.env.BSC_DEPOSIT_INITIAL_LOOKBACK_BLOCKS || '200000', 10), /** Re-scan overlap each poll to survive empty eth_getLogs / late indexing. */ depositOverlapLookbackBlocks: parseInt(process.env.BSC_DEPOSIT_OVERLAP_LOOKBACK_BLOCKS || '5000', 10), /** * When HD still holds USDT (missed credit), rescan this many recent blocks via getLogs. * Must be wide enough for deposits missed while public RPCs were rate-limiting * (≈3s/block → 200000 ≈ 7 days). Used as floor with depositInitialLookbackBlocks. */ unpaidLookbackBlocks: parseInt(process.env.BSC_UNPAID_LOOKBACK_BLOCKS || '200000', 10), /** Optional Etherscan V2 / BscScan key for unpaid deposit fallback. */ explorerApiKey: process.env.BSCSCAN_API_KEY || process.env.ETHERSCAN_API_KEY || '', /** * Optional Etherscan-compatible tokentx API. Default empty: Blockscout BSC host is often 404; * deposit recovery relies on RPC fallbacks (+ BSCSCAN_API_KEY when set). */ explorerApiUrl: process.env.BSC_EXPLORER_API_URL || '', /** Native BNB top-up for sweeps (wei); default 0.001 BNB */ gasTopUpWei: process.env.SWEEP_BSC_GAS_TOPUP_WEI || '1000000000000000', }, }, rateLimit: { windowMs: parseInt(process.env.RATE_LIMIT_WINDOW_MS || '900000', 10), max: parseInt(process.env.RATE_LIMIT_MAX || (process.env.NODE_ENV === 'development' ? '2000' : '100'), 10), loginMax: parseInt(process.env.LOGIN_RATE_LIMIT_MAX || '5', 10), }, withdrawal: { dailyLimitUsd: parseInt(process.env.DAILY_WITHDRAWAL_LIMIT_USD || '10000', 10), largeThresholdUsd: parseInt(process.env.LARGE_WITHDRAWAL_THRESHOLD_USD || '1000', 10), /** Kill-switch: prevents broadcasting real chain txs unless explicitly enabled */ allowWithdrawals: process.env.ALLOW_WITHDRAWALS === 'true', /** Default network fee in USDT micro-units (6 decimals); admin can override in Settings. */ networkFeeUsdtMicro: parseInt(process.env.WITHDRAWAL_NETWORK_FEE_USDT_MICRO || '2000000', 10), }, security: { integrityCheckIntervalMs: parseInt(process.env.SECURITY_INTEGRITY_CHECK_INTERVAL_MS || '300000', 10), /** When set, overrides DB setting `require_admin_2fa` (use `false` for local Docker dev). */ requireAdmin2faEnv: process.env.REQUIRE_ADMIN_2FA?.trim().toLowerCase() || null, /** Skips JWT token_version check (enabled automatically in NODE_ENV=test). */ skipAccessTokenVersionCheck: process.env.NODE_ENV === 'test', }, treasury: { /** Moves on-chain deposits from user addresses to cold storage */ sweepEnabled: process.env.SWEEP_ENABLED === 'true', /** * When true, pending sweeps execute on-chain without Approvals (after safety checks). * Default false — keep human approval for cold destination / amount review. */ sweepAutoExecute: process.env.SWEEP_AUTO_EXECUTE === 'true', /** * Optional raw-unit cap for auto-execute. Above this amount, sweep stays pending * for Submit sweeps → Approvals. Empty = no cap when SWEEP_AUTO_EXECUTE=true. */ sweepAutoMaxAmountRaw: (process.env.SWEEP_AUTO_MAX_AMOUNT_RAW || '').trim(), /** * Optional comma-separated cold addresses allowed as sweep destinations (EVM lowercased). * When set, active cold must match; blocks sweeps if DB cold was changed to an unknown address. */ sweepColdAllowlist: (process.env.SWEEP_COLD_ALLOWLIST || '') .split(',') .map((s) => s.trim()) .filter(Boolean), sweepPollIntervalMs: parseInt(process.env.SWEEP_POLL_INTERVAL_MS || '120000', 10), /** Minimum token amount (raw units) to sweep */ sweepMinAmountRaw: process.env.SWEEP_MIN_AMOUNT_RAW || '1000000', /** TRX sent from hot wallet to fund TRC20 sweeps (sun) */ tronGasTopUpSun: process.env.SWEEP_TRON_GAS_TOPUP_SUN || '15000000', /** * Min USDT (chain raw units) to leave on hot after Hot→Cold USDT transfer. * Default 0 = no USDT floor (native withdrawal gas reserve still enforced). */ hotUsdtMinReserveRaw: (process.env.HOT_USDT_MIN_RESERVE_RAW || '0').trim() || '0', /** MATIC sent from hot wallet to fund USDC sweeps (wei) */ polygonGasTopUpWei: process.env.SWEEP_POLYGON_GAS_TOPUP_WEI || '100000000000000000', }, app: { /** Public web app URL used in verification links (e.g. http://localhost:5173) */ publicUrl: process.env.APP_PUBLIC_URL || 'http://localhost:5173', verifyEmailPath: process.env.VERIFY_EMAIL_PATH || '/verify-email', resetPasswordPath: process.env.RESET_PASSWORD_PATH || '/reset-password', /** Comma-separated allowed CORS origins in production */ corsOrigins: (process.env.CORS_ORIGINS || '') .split(',') .map((s) => s.trim()) .filter(Boolean), }, countries: { /** Optional REST Countries v5 API key. When unset, sync uses the ISO 3166 public catalog. */ restCountriesApiKey: process.env.REST_COUNTRIES_API_KEY || '', }, deposit: { /** Platform asset for deposits and predictions (USDT TRC20). */ walletTypeCode: process.env.PREDICTION_WALLET_TYPE || 'USDT_TRC20', }, candlePredict: { engineTickMs: readEnvInt('CANDLE_PREDICT_ENGINE_TICK_MS', 3000, 1000, 60000), backfillMaxPerTick: readEnvInt('CANDLE_PREDICT_BACKFILL_MAX_PER_TICK', 2, 1, 50), backfillIntervalMs: readEnvInt('CANDLE_PREDICT_BACKFILL_INTERVAL_MS', 60000, 10000, 600000), backfillSeedMax: readEnvInt('CANDLE_PREDICT_BACKFILL_SEED_MAX', 15, 5, 120), }, email: { /** smtp = send via SMTP; console = log link to stdout (dev) */ transport: resolveEmailTransport(), host: process.env.SMTP_HOST || '', port: parseInt(process.env.SMTP_PORT || '587', 10), secure: process.env.SMTP_SECURE === 'true', user: (process.env.SMTP_USER || '').trim(), pass: (process.env.SMTP_PASS || '').replace(/\s+/g, ''), /** Visible From (can be an alias, e.g. info@ while SMTP_USER is admin@). */ from: process.env.EMAIL_FROM || '', /** Optional Reply-To (defaults to the address inside EMAIL_FROM). */ replyTo: (process.env.EMAIL_REPLY_TO || '').trim(), verificationExpiryHours: parseInt(process.env.EMAIL_VERIFICATION_EXPIRY_HOURS || '24', 10), verificationSendMax: parseInt(process.env.EMAIL_VERIFICATION_SEND_MAX || '5', 10), passwordResetExpiryHours: parseInt(process.env.PASSWORD_RESET_EXPIRY_HOURS || '1', 10), passwordResetSendMax: parseInt(process.env.PASSWORD_RESET_SEND_MAX || '5', 10), }, slack: { /** Legacy fallback when channel-specific webhooks are not set */ webhookUrl: process.env.SLACK_WEBHOOK_URL || '', /** #security — withdrawals, auth, platform security alerts */ securityWebhookUrl: process.env.SLACK_SECURITY_WEBHOOK_URL || '', /** #referral-fraud — cap blocks, clawbacks, Sybil review */ referralWebhookUrl: process.env.SLACK_REFERRAL_WEBHOOK_URL || '', }, redis: { url: process.env.REDIS_URL || '', /** Auto-enabled when REDIS_URL is set unless REDIS_ENABLED=false */ enabled: process.env.REDIS_ENABLED === 'true' || (!!process.env.REDIS_URL && process.env.REDIS_ENABLED !== 'false'), /** Phase B: read round state from Redis before PostgreSQL */ roundCacheEnabled: process.env.REDIS_ROUND_CACHE === 'true', /** Phase B+: enqueue single bets to Redis Stream (requires worker-bets) */ betAsyncEnabled: process.env.BET_ASYNC === 'true', }, ws: { enabled: process.env.WS_ENABLED === 'true', port: parseInt(process.env.WS_PORT || '4001', 10), path: process.env.WS_PATH || '/ws/v1/games/candle-predict', supportPath: process.env.WS_SUPPORT_PATH || '/ws/v1/support', securityPath: process.env.WS_SECURITY_PATH || '/ws/v1/security', }, /** When false, API process skips starting game engines (use app-engine instead) */ engineEnabled: process.env.ENGINE_ENABLED !== 'false', setup: { /** * One-time secret for creating the first administrator on a fresh deployment. * Set INITIAL_SETUP_TOKEN in production (min. 32 random characters). */ token: process.env.INITIAL_SETUP_TOKEN || (process.env.NODE_ENV === 'development' ? 'dev-setup-change-me' : ''), }, turnstile: { siteKey: process.env.TURNSTILE_SITE_KEY || '', secretKey: process.env.TURNSTILE_SECRET_KEY || '', }, sentry: { dsn: process.env.SENTRY_DSN || '', tracesSampleRate: Math.min(1, Math.max(0, parseFloat(process.env.SENTRY_TRACES_SAMPLE_RATE || '0.1'))), }, clamav: { enabled: process.env.CLAMAV_ENABLED === 'true', host: process.env.CLAMAV_HOST || '127.0.0.1', port: parseInt(process.env.CLAMAV_PORT || '3310', 10), timeoutMs: readEnvInt('CLAMAV_TIMEOUT_MS', 30000, 5000, 120000), }, mobileReleases: { /** Expected Android signing certificate SHA-256 (hex, no colons). Empty = skip cert check (dev only). */ expectedCertSha256: (process.env.ANDROID_APK_EXPECTED_CERT_SHA256 || '').trim().toLowerCase().replace(/:/g, ''), expectedPackage: (process.env.ANDROID_APK_EXPECTED_PACKAGE || 'com.prediqo.mobile').trim(), maxUploadBytes: readEnvInt('APK_MAX_UPLOAD_BYTES', 120 * 1024 * 1024, 1000000, 300 * 1024 * 1024), /** HMAC secret for short-lived download tokens (falls back to JWT secret). */ downloadTokenSecret: process.env.APK_DOWNLOAD_TOKEN_SECRET || process.env.JWT_SECRET || 'change-me-in-production', downloadTokenTtlSeconds: readEnvInt('APK_DOWNLOAD_TOKEN_TTL_SECONDS', 3600, 60, 86400), }, /** Live TLS probes for admin SSL expiry page (defaults from APP_PUBLIC_URL + www). */ sslStatus: { warnDays: readEnvInt('SSL_STATUS_WARN_DAYS', 30, 1, 90), criticalDays: readEnvInt('SSL_STATUS_CRITICAL_DAYS', 7, 1, 30), timeoutMs: readEnvInt('SSL_STATUS_TIMEOUT_MS', 8000, 1000, 60000), }, /** Admin VPS monitor — Prometheus HTTP only (allowlisted PromQL). */ vpsMonitor: { prometheusUrl: (process.env.PROMETHEUS_URL || 'http://prometheus:9090').trim(), timeoutMs: readEnvInt('VPS_MONITOR_TIMEOUT_MS', 8000, 1000, 30000), thresholds: { cpuWarn: readEnvInt('VPS_MONITOR_CPU_WARN', 70, 1, 100), cpuCritical: readEnvInt('VPS_MONITOR_CPU_CRITICAL', 90, 1, 100), memWarn: readEnvInt('VPS_MONITOR_MEM_WARN', 75, 1, 100), memCritical: readEnvInt('VPS_MONITOR_MEM_CRITICAL', 90, 1, 100), diskWarn: readEnvInt('VPS_MONITOR_DISK_WARN', 75, 1, 100), diskCritical: readEnvInt('VPS_MONITOR_DISK_CRITICAL', 90, 1, 100), loadWarn: readEnvInt('VPS_MONITOR_LOAD_WARN', 4, 1, 256), loadCritical: readEnvInt('VPS_MONITOR_LOAD_CRITICAL', 8, 1, 256), }, }, }; //# sourceMappingURL=index.js.map