games_app/backend/src/app.ts

120 lines
4.2 KiB
TypeScript

/**
* Express application setup.
* Configures security middleware, API routes, health checks, and global error handling.
*/
import express from 'express';
import cors from 'cors';
import helmet from 'helmet';
import { config } from './config';
import routes from './routes';
import { errorHandler } from './middleware/errorHandler';
import * as settingsRepository from './repositories/settingsRepository';
import { getWithdrawalNetworkFeeRaw } from './utils/withdrawalFee';
import { usesConsoleEmailTransport } from './services/emailService';
function resolveCorsOrigin(): cors.CorsOptions['origin'] {
const configured = config.app.corsOrigins;
if (configured.length > 0) return configured;
if (config.env !== 'production') return true;
if (config.app.publicUrl) return [config.app.publicUrl];
console.error(
'[cors] CORS_ORIGINS is not set in production — denying cross-origin requests (fail-closed)'
);
return (_origin, callback) => callback(null, false);
}
const app = express();
// Behind nginx / Docker reverse proxy (required for rate-limit + req.ip).
if (process.env.TRUST_PROXY === 'true' || process.env.TRUST_PROXY === '1') {
app.set('trust proxy', 1);
} else if (process.env.NODE_ENV === 'production') {
app.set('trust proxy', 1);
}
app.use(helmet());
app.use(cors({ origin: resolveCorsOrigin(), credentials: true }));
app.use(express.json());
app.use(config.apiPrefix, routes);
/**
* Infers TRON network label from the configured node URL for health reporting.
* @param url TRON node RPC URL
* @returns 'shasta', 'mainnet', or 'unknown'
*/
function labelTronNetwork(url: string): 'shasta' | 'mainnet' | 'unknown' {
const u = (url || '').toLowerCase();
if (u.includes('shasta')) return 'shasta';
if (u.includes('trongrid.io')) return 'mainnet';
return 'unknown';
}
/**
* Shortens a blockchain address for safe display in health/debug output.
* @param addr Full address or null/undefined
* @returns Masked address (first 6 + last 4 chars) or null when empty
*/
function maskAddress(addr: string | null | undefined): string | null {
if (!addr) return null;
const a = addr.trim();
if (a.length <= 12) return a;
return `${a.slice(0, 6)}…${a.slice(-4)}`;
}
app.get('/health', async (_req, res) => {
const settings = await settingsRepository.getSettings();
/** Fee in 6-decimal micro-USDT; clients scale to wallet decimals (e.g. BEP20 18). */
const feeRaw = getWithdrawalNetworkFeeRaw(settings, 6);
res.json({
status: 'ok',
timestamp: new Date().toISOString(),
env: config.env,
emailTransport: config.email.transport,
emailConsoleMode: usesConsoleEmailTransport(),
/** @deprecated Prefer `assets` — primary prediction ledger remains TRC20. */
asset: 'USDT_TRC20',
network: labelTronNetwork(config.blockchain.tron.nodeUrl),
assets: ['USDT_TRC20', 'USDT_BEP20'],
networks: {
USDT_TRC20: {
depositEnabled: settings.network_usdt_trc20_deposit_enabled,
withdrawEnabled: settings.network_usdt_trc20_withdraw_enabled,
label: labelTronNetwork(config.blockchain.tron.nodeUrl),
},
USDT_BEP20: {
depositEnabled: settings.network_usdt_bep20_deposit_enabled,
withdrawEnabled: settings.network_usdt_bep20_withdraw_enabled,
label: 'bsc',
},
},
withdrawalsEnabled: settings.allow_withdrawals,
requireWithdrawal2fa: settings.require_withdrawal_2fa,
withdrawalNetworkFeeRaw: feeRaw.toString(),
/** Min remaining after peer transfer (6-decimal micro-USDT; 0 = disabled). */
transferMinRemainingRaw: String(
Math.max(0, Math.floor(settings.transfer_min_remaining_usdt_micro || 0))
),
rpc: {
tronNodeUrl: config.blockchain.tron.nodeUrl,
bscRpcUrl: config.blockchain.bsc.rpcUrl,
},
contracts: {
usdtTrc20: maskAddress(config.blockchain.tron.usdtTrc20Contract),
usdtBep20: maskAddress(config.blockchain.bsc.usdtBep20Contract),
},
});
});
app.use((_req, res) => {
res.status(404).json({ error: 'Not found' });
});
app.use((err: Error, req: express.Request, res: express.Response, next: express.NextFunction) => {
errorHandler(err, req, res, next);
});
/** Configured Express application instance (not yet listening). */
export default app;